fact
stringlengths
12
2.2k
type
stringclasses
4 values
library
stringclasses
3 values
imports
listlengths
1
10
filename
stringclasses
26 values
symbolic_name
stringlengths
2
29
docstring
stringclasses
9 values
simple_ex (n m : ℕ) (h1 : ∀ {a b : Nat}, a + b = b + a) (h2 : ∀ {a b : Nat}, a = b + b): n + m = m + n := by simp [h1, h2]
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
simple_ex
null
Prod (α : Type u) (β : Type v) | mk : α → β → Prod α β
inductive
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
Prod
null
Sum (α : Type u) (β : Type v) where | inl : α → Sum α β | inr : β → Sum α β
inductive
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
Sum
null
sum (hi: Sum Nat Nat) : True := by rcases hi with a | b sorry; sorry
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
sum
null
prod (hi: Prod Nat Nat) : True := by rcases hi with ⟨a, b⟩ sorry open Lean Elab in
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
prod
null
infoTree (hi: InfoTree) : True := by rcases hi sorry; sorry; sorry
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
infoTree
null
th11 : ∀ (N : ℕ), ∃ M, N + N = M := by { intro n exact ⟨ n + n, rfl ⟩ }
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
th11
null
infinitude_of_primes : ∀ N, ∃ p, p ≥ N ∧ Nat.Prime p := by intro N let M := Nat.factorial N + 1 let p := Nat.minFac M have pp : Nat.Prime p := by apply Nat.minFac_prime have fac_pos: 0 < Nat.factorial N := by exact Nat.factorial_pos N omega have ppos: p ≥ N := by apply by_contradiction intro pln have h₁ : p ∣ Nat.factorial N := by sorry have h₂ : p ∣ Nat.factorial N + 1 := Nat.minFac_dvd M have h : p ∣ 1 := (Nat.dvd_add_right h₁).mp $ h₂ exact Nat.Prime.not_dvd_one pp h exact ⟨ p, ppos, pp ⟩
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
infinitude_of_primes
null
irrational_sqrt_2 : ¬ ∃ (q : ℚ), q * q = 2 := by apply not_exists.mpr intro ⟨n, d, _, coprime⟩ h have h₁ : n * n = 2 * d * d:= by rw [← Rat.normalize_self 2, Rat.mul_def, Rat.normalize_eq_iff] at h simp at h sorry -- linarith rw [← Int.natAbs_mul_self'] at h₁ have ⟨n', h₂⟩ : ∃ n', n.natAbs = 2 * n' := by have hm : Even (2 * d * d) := by rw [Nat.even_mul, Nat.even_mul] left; left trivial sorry have ⟨d', h₃⟩ : ∃ d', d = 2 * d' := by sorry rw [h₂, h₃] at h₁ have r : (∀ k, ¬ 2 * k = 1) := by sorry rw [Nat.coprime_iff_gcd_eq_one, h₂, h₃] at coprime rw [Nat.gcd_mul_left] at coprime apply r _ coprime
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
irrational_sqrt_2
null
mini_example : true = true := by have ⟨a, b⟩: ∃ c, c = 2 := by sorry have ⟨c, d⟩: ∃ e, e = 2 := ⟨2, rfl⟩ exact rfl
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
mini_example
null
test123 (p : Prop) (hp : p) : p ∧ p := by apply And.intro exact hp exact hp
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
test123
null
test (p q : Prop) (hp : p) (hq : q) : p ∧ q ∧ p := by apply And.intro exact hp apply And.intro exact hq exact hp
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
test
null
commutativityOfIntersections (s t : Set Nat) : s ∩ t = t ∩ s := by ext x apply Iff.intro intro h1 rw [Set.mem_inter_iff, and_comm] at h1 exact h1 intro h2 rw [Set.mem_inter_iff, and_comm] at h2 exact h2
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
commutativityOfIntersections
null
simple : ∀ (N : ℕ), ∃ M, N + N = M := by intro n use n + n
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
simple
null
theorem_7 (p q r : Prop) : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := by apply Iff.intro intro xxx rcases xxx with ⟨hp, hqr⟩ rcases hqr with hq | hr left -- apply And.intro -- exact hp -- exact hq -- apply And.intro hp hq exact And.intro hp hq right exact And.intro hp hr intro wow apply And.intro rcases wow with hm | heh exact hm.left exact heh.left rcases wow with a | b left exact a.right right exact b.right
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
theorem_7
null
small_irrational : ¬ ∃ (q : ℚ), q * q = 2 := by apply not_exists.mpr intro ⟨n, d, _, coprime⟩ h have ⟨n', h₂⟩ : ∃ n', n.natAbs = 2 * n' := by sorry have ⟨d', h₃⟩ : ∃ d', d = 2 * d' := by sorry have h₁ : n * n = 2 * d * d:= by sorry rw [← Int.natAbs_mul_self'] at h₁ rw [h₂, h₃] at h₁ have r : (∀ k, ¬ 2 * k = 1) := by sorry rw [Nat.coprime_iff_gcd_eq_one, h₂, h₃] at coprime rw [Nat.gcd_mul_left] at coprime apply r _ coprime
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
small_irrational
null
mem_split {a : α} {as : List α} (h : a ∈ as) : ∃ s t, as = s ++ a :: t := by induction as with | nil => cases h | cons b bs ih => cases h with | head bs => exact ⟨[], ⟨bs, rfl⟩⟩ | tail someVar h => match ih h with | ⟨s, ⟨t, h₂⟩⟩ => exact ⟨b :: s, ⟨t, h₂ ▸ rfl⟩⟩
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
mem_split
null
mem {a : α} {as : List α} (h : a ∈ as) : ∃ s t, as = s ++ a :: t := by induction as with | nil => cases h | cons m mm => sorry
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
mem
null
dojo4_uncombined (p q r : Prop) (hp : p) : (p ∨ q ∨ r) ∧ (q ∨ p ∨ r) ∧ (q ∨ r ∨ p) := by repeat (first | apply And.intro | apply Or.inl; assumption | apply Or.inr | assumption) -- 1. `apply Or.inl; assumption` is tried, but fails on `assumption` -- 2. `apply Or.inr; assumption` is tried, and succeeds
theorem
root
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.GCongr", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
Examples.lean
dojo4_uncombined
null
VERSION := 4
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Elab.Tactic", "import Services.BetterParser", "import Services.CheckIfUserIsStillTyping", "import Services.GoalsAt", "import Services.PrettifyRwTactic", "import Services.ShouldRenderSingleSequent" ]
lean/Paperproof.lean
VERSION
null
Mode where | single_tactic | tree deriving FromJson, ToJson
inductive
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Elab.Tactic", "import Services.BetterParser", "import Services.CheckIfUserIsStillTyping", "import Services.GoalsAt", "import Services.PrettifyRwTactic", "import Services.ShouldRenderSingleSequent" ]
lean/Paperproof.lean
Mode
null
InputParams where pos : Lsp.Position mode: Mode deriving FromJson, ToJson
structure
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Elab.Tactic", "import Services.BetterParser", "import Services.CheckIfUserIsStillTyping", "import Services.GoalsAt", "import Services.PrettifyRwTactic", "import Services.ShouldRenderSingleSequent" ]
lean/Paperproof.lean
InputParams
null
OutputParams where steps : List Paperproof.Services.ProofStep version: Nat deriving Inhabited, FromJson, ToJson @[server_rpc_method]
structure
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Elab.Tactic", "import Services.BetterParser", "import Services.CheckIfUserIsStillTyping", "import Services.GoalsAt", "import Services.PrettifyRwTactic", "import Services.ShouldRenderSingleSequent" ]
lean/Paperproof.lean
OutputParams
null
getSnapshotData (params : InputParams) : RequestM (RequestTask OutputParams) := do withWaitFindSnapAtPos params.pos fun snap => do Paperproof.Services.checkIfUserIsStillTyping snap params.pos match params.mode with | .single_tactic => let text : FileMap := (← readDoc).meta.text let hoverPos : String.Pos.Raw := text.lspPosToUtf8Pos params.pos let some goalsAtResult := (Paperproof.Services.goalsAt? snap.infoTree text hoverPos).head? | throwThe RequestError ⟨.invalidParams, "zeroProofSteps"⟩ let tacticInfo := goalsAtResult.tacticInfo if ← Paperproof.Services.shouldRenderSingleSequent tacticInfo text hoverPos then let some mvarId := tacticInfo.goalsAfter.head? | throwThe RequestError ⟨.invalidParams, "noGoalsAfter"⟩ let goal ← Paperproof.Services.printGoalInfo goalsAtResult.ctxInfo mvarId let fakeStep : Paperproof.Services.ProofStep := { tacticString := "fake" goalBefore := goal goalsAfter := [goal] tacticDependsOn := [] spawnedGoals := [] position := { start := ⟨0, 0⟩, stop := ⟨0, 0⟩ } theorems := [] } return { steps := [fakeStep], version := VERSION } else let forcedTacticString : String ← Paperproof.Services.prettifyRwTactic tacticInfo text hoverPos let info : Info := Elab.Info.ofTacticInfo tacticInfo let parsedTree ← Paperproof.Services.parseTacticInfo snap.infoTree goalsAtResult.ctxInfo info [] ∅ (isSingleTacticMode := true) (forcedTacticString := forcedTacticString) return { steps := parsedTree.steps, version := VERSION } | .tree => let some parsedTree ← Paperproof.Services.BetterParser snap.infoTree | throwThe RequestError ⟨.invalidParams, "noParsedTree"⟩ -- This happens when we hover over something other than a theorem if parsedTree.steps.length == 0 then throwThe RequestError ⟨.invalidParams, "zeroProofSteps"⟩ return { steps := parsedTree.steps, version := VERSION }
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Elab.Tactic", "import Services.BetterParser", "import Services.CheckIfUserIsStillTyping", "import Services.GoalsAt", "import Services.PrettifyRwTactic", "import Services.ShouldRenderSingleSequent" ]
lean/Paperproof.lean
getSnapshotData
null
dummyPosition : ProofStepPosition := { start := { line := 0, character := 0 }, stop := { line := 0, character := 0 } } -- Add ToJson instance for Result (original doesn't have one)
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
dummyPosition
null
static_printGoalInfo (printCtx : ContextInfo) (id : MVarId) : MetaM GoalInfo := do let some decl := printCtx.mctx.findDecl? id | throwError "Goal not found in mctx" let lctx := decl.lctx |>.sanitizeNames.run' {options := {}} let ppContext := printCtx.toPPContext lctx let hyps ← lctx.foldrM (init := []) (fun hypDecl acc => do if hypDecl.isAuxDecl || hypDecl.isImplementationDetail then return acc let type ← ppExprWithInfos ppContext hypDecl.type let value ← hypDecl.value?.mapM (fun expr => ppExprWithInfos ppContext expr) let isProof : String ← printCtx.runMetaM decl.lctx (mayBeProof hypDecl.toExpr) return ({ username := hypDecl.userName.toString, type := type.fmt.pretty, value := value.map (fun x => x.fmt.pretty), id := hypDecl.fvarId.name.toString, isProof := isProof } : Hypothesis) :: acc) return { username := decl.userName.toString type := (← ppExprWithInfos ppContext decl.type).fmt.pretty hyps := hyps id := id } -- Static version of getUnassignedGoals for MetaM
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
static_printGoalInfo
null
static_getUnassignedGoals (goals : List MVarId) (mctx : MetavarContext) : MetaM (List MVarId) := do goals.filterMapM fun id => do if let none := mctx.findDecl? id then return none if mctx.eAssignment.contains id || mctx.dAssignment.contains id then return none return some id -- Static version of getGoalsChange for MetaM
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
static_getUnassignedGoals
null
static_getGoalsChange (ctx : ContextInfo) (tInfo : TacticInfo) : MetaM (List (List String × GoalInfo × List GoalInfo)) := do let goalMVars := tInfo.goalsBefore ++ tInfo.goalsAfter let printCtx := {ctx with mctx := tInfo.mctxAfter} let mut goalsBefore ← static_getUnassignedGoals goalMVars tInfo.mctxBefore let mut goalsAfter ← static_getUnassignedGoals goalMVars tInfo.mctxAfter let commonGoals := goalsBefore.filter fun g => goalsAfter.contains g goalsBefore := goalsBefore.filter (!commonGoals.contains ·) goalsAfter := goalsAfter.filter (!commonGoals.contains ·) let mut result : List (List String × GoalInfo × List GoalInfo) := [] for goalBefore in goalsBefore do if let some goalDecl := tInfo.mctxBefore.findDecl? goalBefore then let assignedMVars ← ctx.runMetaM goalDecl.lctx (findMVarsAssigned goalBefore tInfo.mctxAfter) let tacticDependsOn ← ctx.runMetaM goalDecl.lctx (findHypsUsedByTactic goalBefore goalDecl tInfo.mctxAfter) result := ( tacticDependsOn, ← static_printGoalInfo printCtx goalBefore, ← goalsAfter.filter assignedMVars.contains |>.mapM (static_printGoalInfo printCtx) ) :: result return result -- We can eliminate this entirely and just call findTheoremsLikeHover directly! -- This is exactly what the original GetTheorems does, just with MetaM instead of RequestM -- Reuse existing prettifySteps, just provide original ProofStep with dummy position -- No need for separate static version! -- Static version of parseTacticInfo using original ProofStep structure
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
static_getGoalsChange
null
static_parseTacticInfo (infoTree: InfoTree) (ctx : ContextInfo) (info : Info) (steps : List ProofStep) (allGoals : Std.HashSet GoalInfo) : MetaM Result := do let .some ctx := info.updateContext? ctx | panic! "unexpected context node" let .ofTacticInfo tInfo := info | return { steps, allGoals } let .some tacticSubstring := getTacticSubstring tInfo | return { steps, allGoals } let tacticString := prettifyTacticString tacticSubstring.toString let steps := prettifySteps tInfo.stx steps -- Use original function! let proofTreeEdges ← static_getGoalsChange ctx tInfo let currentGoals := proofTreeEdges.map (fun ⟨ _, g₁, gs ⟩ => g₁ :: gs) |>.flatten let allGoals := allGoals.insertMany $ currentGoals -- Use original stepGoalsAfter and noInEdgeGoals functions! let orphanedGoals := currentGoals.foldl Std.HashSet.erase (noInEdgeGoals allGoals steps) |>.toArray.insertionSort (nameNumLt ·.id.name ·.id.name) |>.toList -- Call findTheoremsLikeHover directly instead of going through wrapper let theorems ← match ctx.mctx.findDecl? tInfo.goalsBefore.head!, getTacticSubstring tInfo with | some goalDecl, some tacticSubstring => ctx.runMetaM goalDecl.lctx do findTheoremsLikeHover infoTree tacticSubstring.startPos tacticSubstring.stopPos ctx goalDecl | _, _ => pure [] let newSteps := proofTreeEdges.filterMap fun ⟨ tacticDependsOn, goalBefore, goalsAfter ⟩ => if steps.map (·.goalBefore) |>.elem goalBefore then none else some { tacticString, goalBefore, goalsAfter, tacticDependsOn, spawnedGoals := orphanedGoals, position := dummyPosition, -- Just use dummy position! theorems := theorems } return { steps := newSteps ++ steps, allGoals }
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
static_parseTacticInfo
null
static_postNode (infoTree: InfoTree) (ctx : ContextInfo) (info : Info) (results : List (Option Result)) : MetaM Result := do let results : List Result := results.filterMap id let steps : List ProofStep := (results.map (λ result => result.steps)).flatten let allGoals : Std.HashSet GoalInfo := Std.HashSet.ofList ((results.map (λ result => result.allGoals.toList)).flatten) static_parseTacticInfo infoTree ctx info steps allGoals
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
static_postNode
null
static_BetterParser (infoTree : InfoTree) := infoTree.visitM (postNode := λ ctx info _ results => static_postNode infoTree ctx info results )
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
static_BetterParser
null
Config where file_path : System.FilePath := "." const_name : Lean.Name := `Unknown output_path : System.FilePath := "."
structure
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
Config
null
parseArgs (args : Array String) : IO Config := do if args.size < 3 then throw <| IO.userError "usage:lean exe terminal FILE_PATH CONST_NAME OUTPUT_FILE_PATH" let mut cfg : Config := {} cfg := { cfg with file_path := ⟨args[0]!⟩ } cfg := { cfg with const_name := args[1]!.toName } cfg := { cfg with output_path := ⟨args[2]!⟩ } IO.println (s!"File:{cfg.file_path}") IO.println (s!"Constant:{cfg.const_name}") IO.println (s!"Output:{cfg.output_path}") return cfg
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
parseArgs
null
processCommands : Frontend.FrontendM (List (Lean.Environment × InfoState)) := do let done ← Lean.Elab.Frontend.processCommand let st := ← get let infoState := st.commandState.infoState let env' := st.commandState.env -- clear the infostate set {st with commandState := {st.commandState with infoState := {}}} if done then return [(env', infoState)] else return (env', infoState) :: (←processCommands) ------------------------------------------------------------------ --Codes for printing and saving to Json, use printresult (r:Result) : IO Unit
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
processCommands
null
writeGoalInfo (goal : Paperproof.Services.GoalInfo) : IO Unit := do IO.println s!"Goal: {goal.type}" if goal.hyps.isEmpty then IO.println "\nNo hypotheses" else IO.println "\nHypotheses:" for hyp in goal.hyps do IO.println s!"{hyp.username}:{hyp.type}" IO.println "---"
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
writeGoalInfo
null
writeProofStep (step : ProofStep) (stepNumber : Nat) : IO Unit := do IO.println s!"\n=== Step {stepNumber} ===" IO.println s!"Tactic: {step.tacticString}" IO.println s!"\nGoals Before:{step.goalBefore.type}" if step.goalsAfter.isEmpty then IO.println "\nGoals After: No goals (proof completed)" else IO.println s!"\nGoals After: {step.goalsAfter.length} goal(s)" for (goal, i) in step.goalsAfter.zipIdx do IO.println s!"Goal {i + 1}:" writeGoalInfo goal if !step.spawnedGoals.isEmpty then IO.println s!"Spawned goals: {step.spawnedGoals.length}" for (goal, i) in step.spawnedGoals.zipIdx do IO.println s!"Spawned goal {i + 1}:" writeGoalInfo goal
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
writeProofStep
null
saveResultToFile (r : Result) (filePath : System.FilePath) : IO Unit := do let json := toJson r let jsonStr := Json.pretty json IO.FS.writeFile filePath jsonStr
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
saveResultToFile
null
printresult (r : Result)(filePath : System.FilePath) : IO Unit := do IO.println "Proof Tree:" IO.println "===========" if r.steps.isEmpty then IO.println "No proof steps" return let mut stepNumber := 1 for step in r.steps do writeProofStep step stepNumber stepNumber := stepNumber + 1 IO.println "\n=== Summary ===" IO.println s!"Total steps: {r.steps.length}" IO.println s!"Total goals in proof state: {r.allGoals.size}" if !r.allGoals.isEmpty then IO.println "\nAll unique goals encountered:" for goal in r.allGoals.toList do IO.println s!"- {goal.username} : {goal.type}" saveResultToFile r filePath
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
printresult
null
main (args : List String) : IO Unit := do IO.println ("running..") let config ← parseArgs args.toArray Lean.searchPathRef.set compile_time_search_path% let mut input ← IO.FS.readFile config.file_path Lean.enableInitializersExecution let inputCtx := Lean.Parser.mkInputContext input config.file_path.toString let (header, parserState, messages) ← Lean.Parser.parseHeader inputCtx let (env, messages) ← Lean.Elab.processHeader header {} messages inputCtx if messages.hasErrors then for msg in messages.toList do if msg.severity == .error then println! "ERROR: {← msg.toString}" throw <| IO.userError "Errors during import; aborting" let env := env.setMainModule (← Lean.moduleNameOfFileName config.file_path none) if env.contains config.const_name then throw <| IO.userError s!"constant of name {config.const_name} is already in environment" let commandState := { Lean.Elab.Command.mkState env messages {} with infoState.enabled := true } let (steps, _frontendState) ← (processCommands.run { inputCtx := inputCtx }).run { commandState := commandState, parserState := parserState, cmdPos := parserState.pos } ----- for ⟨env, s⟩ in steps do if env.contains config.const_name then for tree in s.trees do let ctx : Lean.Core.Context := { fileName := "", fileMap := default, options := {} } let state : Lean.Core.State := { env := env, messages := Lean.MessageLog.empty } let ioComputation := ((static_BetterParser tree).run {} {}).toIO ctx state let ((result, _), _) ← ioComputation match result with | some r => printresult r config.output_path | none => IO.println "Error" break
def
lean
[ "import Lean", "import Services.BetterParser", "import Services.GetTheorems" ]
lean/terminal.lean
main
null
Hypothesis where username : String type : String value : Option String -- unique identifier for the hypothesis, fvarId id : String isProof : String deriving Inhabited, ToJson, FromJson
structure
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
Hypothesis
null
GoalInfo where username : String type : String hyps : List Hypothesis -- unique identifier for the goal, mvarId id : MVarId deriving Inhabited, ToJson, FromJson
structure
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
GoalInfo
null
ProofStepPosition where start: Lsp.Position stop: Lsp.Position deriving Inhabited, ToJson, FromJson
structure
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
ProofStepPosition
null
ProofStep where tacticString : String goalBefore : GoalInfo goalsAfter : List GoalInfo tacticDependsOn : List String spawnedGoals : List GoalInfo position : ProofStepPosition theorems : List TheoremSignature deriving Inhabited, ToJson, FromJson
structure
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
ProofStep
null
stepGoalsAfter (step : ProofStep) : List GoalInfo := step.goalsAfter ++ step.spawnedGoals
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
stepGoalsAfter
null
noInEdgeGoals (allGoals : Std.HashSet GoalInfo) (steps : List ProofStep) : Std.HashSet GoalInfo := -- Some of the orphaned goals might be matched by tactics in sibling subtrees, e.g. for tacticSeq. (steps.flatMap stepGoalsAfter).foldl Std.HashSet.erase allGoals /- Instead of doing parsing of what user wrote (it wouldn't work for linarith etc), let's do the following. We have assigned something to our goal in mctxAfter. All the fvars used in these assignments are what was actually used instead of what was in syntax. -/
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
noInEdgeGoals
null
findHypsUsedByTactic (goalId: MVarId) (goalDecl : MetavarDecl) (mctxAfter : MetavarContext) : MetaM (List String) := do let some expr := mctxAfter.eAssignment.find? goalId | return [] -- Need to instantiate it to get all fvars let fullExpr ← instantiateExprMVars expr let fvarIds := (collectFVars {} fullExpr).fvarIds let fvars := fvarIds.filterMap goalDecl.lctx.find? return fvars.map (fun x => x.fvarId.name.toString) |>.toList -- This is used to match goalsBefore with goalsAfter to see what was assigned to what
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
findHypsUsedByTactic
null
findMVarsAssigned (goalId : MVarId) (mctxAfter : MetavarContext) : MetaM (List MVarId) := do let some expr := mctxAfter.eAssignment.find? goalId | return [] let (_, s) ← (Meta.collectMVars expr).run {} return s.result.toList
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
findMVarsAssigned
null
mayBeProof (expr : Expr) : MetaM String := do let type : Expr ← Lean.Meta.inferType expr if ← Meta.isProof expr then return "proof" if type.isSort then return "universe" else return "data"
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
mayBeProof
null
printGoalInfo (printCtx : ContextInfo) (id : MVarId) : RequestM GoalInfo := do let some decl := printCtx.mctx.findDecl? id | throwThe RequestError ⟨.invalidParams, "goalNotFoundInMctx"⟩ -- to get tombstones in name ✝ for unreachable hypothesis let lctx := decl.lctx |>.sanitizeNames.run' {options := {}} let ppContext := printCtx.toPPContext lctx let hyps ← lctx.foldrM (init := []) (fun hypDecl acc => do if hypDecl.isAuxDecl || hypDecl.isImplementationDetail then return acc let type ← liftM (ppExprWithInfos ppContext hypDecl.type) let value ← liftM (hypDecl.value?.mapM (ppExprWithInfos ppContext)) let isProof : String ← printCtx.runMetaM decl.lctx (mayBeProof hypDecl.toExpr) return ({ username := hypDecl.userName.toString, type := type.fmt.pretty, value := value.map (·.fmt.pretty), id := hypDecl.fvarId.name.toString, isProof := isProof } : Hypothesis) :: acc) return { username := decl.userName.toString type := (← ppExprWithInfos ppContext decl.type).fmt.pretty hyps := hyps id := id } -- Returns unassigned goals from the provided list of goals
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
printGoalInfo
null
getUnassignedGoals (goals : List MVarId) (mctx : MetavarContext) : RequestM (List MVarId) := do goals.filterMapM fun id => do if let none := mctx.findDecl? id then return none if mctx.eAssignment.contains id || mctx.dAssignment.contains id then return none return some id
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
getUnassignedGoals
null
Result where steps : List ProofStep allGoals : Std.HashSet GoalInfo
structure
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
Result
null
getGoalsChange (ctx : ContextInfo) (tInfo : TacticInfo) : RequestM (List (List String × GoalInfo × List GoalInfo)) := do -- We want to filter out `focus` like tactics which don't do any assignments -- therefore we check all goals on whether they were assigned during the tactic let goalMVars := tInfo.goalsBefore ++ tInfo.goalsAfter -- For printing purposes we always need to use the latest mctx assignments. For example in -- have h := by calc -- 3 ≤ 4 := by trivial -- 4 ≤ 5 := by trivial -- at mctxBefore type of `h` is `?m.260`, but by the time calc is elaborated at mctxAfter -- it's known to be `3 ≤ 5` let printCtx := {ctx with mctx := tInfo.mctxAfter} let mut goalsBefore ← getUnassignedGoals goalMVars tInfo.mctxBefore let mut goalsAfter ← getUnassignedGoals goalMVars tInfo.mctxAfter let commonGoals := goalsBefore.filter fun g => goalsAfter.contains g goalsBefore := goalsBefore.filter (!commonGoals.contains ·) goalsAfter := goalsAfter.filter (!commonGoals.contains ·) -- We need to match them into (goalBefore, goalsAfter) pairs according to assignment. let mut result : List (List String × GoalInfo × List GoalInfo) := [] for goalBefore in goalsBefore do if let some goalDecl := tInfo.mctxBefore.findDecl? goalBefore then let assignedMVars ← ctx.runMetaM goalDecl.lctx (findMVarsAssigned goalBefore tInfo.mctxAfter) let tacticDependsOn ← ctx.runMetaM goalDecl.lctx (findHypsUsedByTactic goalBefore goalDecl tInfo.mctxAfter) result := ( tacticDependsOn, ← printGoalInfo printCtx goalBefore, ← goalsAfter.filter assignedMVars.contains |>.mapM (printGoalInfo printCtx) ) :: result return result
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
getGoalsChange
null
prettifySteps (stx : Syntax) (steps : List ProofStep) : List ProofStep := Id.run do match stx with | `(tactic| rw [$_,*] $(_)?) | `(tactic| rewrite [$_,*] $(_)?) => let prettify (tStr : String) := let res := tStr.trim.dropRightWhile (· == ',') -- rw puts final rfl on the "]" token if res == "]" then "rfl" else res return steps.map fun a => { a with tacticString := s!"rw [{prettify a.tacticString}]" } | _ => return steps -- Comparator for names, e.g. so that _uniq.34 and _uniq.102 go in the right order. -- That's not completely right because it doesn't compare prefixes but -- it's much shorter to write than correct version and serves the purpose.
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
prettifySteps
null
nameNumLt (n1 n2 : Name) : Bool := match n1, n2 with | .num _ n₁, .num _ n₂ => n₁ < n₂ | .num _ _, _ => true | _, _ => false /-- By default, `.getSubstring()` captures empty lines and comments after the tactic - this function removes them. -/
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
nameNumLt
null
prettifyTacticString (tacticString: String) : String := (tacticString.splitOn "\n").head!.trim
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
prettifyTacticString
/-- By default, `.getSubstring()` captures empty lines and comments after the tactic - this function removes them. -/
getProofStepPosition (tacticSubstring: Substring.Raw) : RequestM ProofStepPosition := do let doc ← Lean.Server.RequestM.readDoc let text : FileMap := doc.meta.text return { start := Lean.FileMap.utf8PosToLspPos text tacticSubstring.startPos, stop := Lean.FileMap.utf8PosToLspPos text tacticSubstring.stopPos }
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
getProofStepPosition
/-- By default, `.getSubstring()` captures empty lines and comments after the tactic - this function removes them. -/
parseTacticInfo (infoTree: InfoTree) (ctx : ContextInfo) (info : Info) (steps : List ProofStep) (allGoals : Std.HashSet GoalInfo) (isSingleTacticMode : Bool) (forcedTacticString : String := "") : RequestM Result := do let .some ctx := info.updateContext? ctx | panic! "unexpected context node" let .ofTacticInfo tInfo := info | return { steps, allGoals } let .some tacticSubstring := getTacticSubstring tInfo | return { steps, allGoals } let mut tacticString := if forcedTacticString.length > 0 then forcedTacticString else prettifyTacticString (Substring.Raw.toString tacticSubstring) let steps := prettifySteps tInfo.stx steps let position ← getProofStepPosition tacticSubstring let proofTreeEdges ← getGoalsChange ctx tInfo let currentGoals := proofTreeEdges.map (fun ⟨ _, g₁, gs ⟩ => g₁ :: gs) |>.flatten let allGoals := allGoals.insertMany $ currentGoals -- It's like tacticDependsOn but unnamed mvars instead of hyps. -- Important to sort for have := calc for example, e.g. calc 3 < 4 ... 4 < 5 ... let orphanedGoals := currentGoals.foldl Std.HashSet.erase (noInEdgeGoals allGoals steps) |>.toArray.insertionSort (nameNumLt ·.id.name ·.id.name) |>.toList let theorems ← if isSingleTacticMode then GetTheorems infoTree tInfo ctx else pure [] let newSteps := proofTreeEdges.filterMap fun ⟨ tacticDependsOn, goalBefore, goalsAfter ⟩ => -- Leave only steps which are not handled in the subtree. if steps.map (·.goalBefore) |>.elem goalBefore then none else some { tacticString, goalBefore, goalsAfter, tacticDependsOn, spawnedGoals := orphanedGoals position := position theorems := theorems } return { steps := newSteps ++ steps, allGoals }
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
parseTacticInfo
null
postNode (infoTree: InfoTree) (ctx : ContextInfo) (info : Info) (results : List (Option Result)) : RequestM Result := do -- Remove `Option.none` values from the `results` list (we have them because of the `.visitM` implementation) let results : List Result := results.filterMap id -- 1. Flatten `ProofStep`s let steps : List ProofStep := (results.map (λ result => result.steps)).flatten -- 2. Flatten `GoalInfo`s let allGoals : Std.HashSet GoalInfo := Std.HashSet.ofList ((results.map (λ result => result.allGoals.toList)).flatten) parseTacticInfo infoTree ctx info steps allGoals (isSingleTacticMode := false)
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
postNode
null
BetterParser (infoTree : InfoTree) := infoTree.visitM (postNode := λ ctx info _ results => postNode infoTree ctx info results )
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Meta.CollectMVars", "import Services.GetTheorems", "import Services.GetTacticSubstring" ]
lean/Services/BetterParser.lean
BetterParser
null
checkIfUserIsStillTyping (snap : Snapshots.Snapshot) (hoverPos : Lsp.Position) : RequestM Unit := do -- old: snap.beginPos if let some beginPosition := snap.stx.getPos? then let doc ← readDoc let text := doc.meta.text let snapBegins := text.utf8PosToLspPos beginPosition -- We won't get error messages for this, -- but if we have the following arrangement, then there is some syntax error: -- -- snapBegins: (101, 0) -- hoverPos: (93, 4) -- -- hover snapBegins -- ─────┼──────────────────┼─────── -- 93 101 let isSyntaxError := hoverPos.line < snapBegins.line if isSyntaxError then throwThe RequestError ⟨.invalidParams, "stillTyping"⟩ for (msg : Message) in MessageLog.toList snap.msgLog do let messageHappened := text.leanPosToLspPos msg.pos if messageHappened.line >= snapBegins.line then -- Happens in these cases: -- .data equals "unknown tactic" -- .data equals "expected '(' or term" -- .data equals "unknown identifier 'm'" -- .data equals "tactic 'apply' failed, failed to unify..." let isError := match msg.severity with | MessageSeverity.error => true | _ => false -- Everything's fine, we'll get a nice InfoTree let isSorried := (← msg.data.toString).startsWith "unsolved goals" if isError && !isSorried then throwThe RequestError ⟨.invalidParams, "stillTyping"⟩
def
lean
[ "import Lean" ]
lean/Services/CheckIfUserIsStillTyping.lean
checkIfUserIsStillTyping
null
getTacticSubstring (tInfo : TacticInfo) : Option Substring.Raw := match tInfo.stx.getSubstring? with | .some substring => substring | .none => none
def
lean
[ "import Lean" ]
lean/Services/GetTacticSubstring.lean
getTacticSubstring
/-- InfoTree has a lot of non-user-written intermediate `TacticInfo`s, this function returns `none` for those. @EXAMPLES `tInfo.stx` //=> `(Tactic.tacticSeq1Indented [(Tactic.exact "exact" (Term.proj ab "." (fieldIdx "2")))])` `tInfo.stx.getSubstring?` //=> `(some (exact ab.2 ))` `tInfo.stx` //=> `(Tactic.rotateRight "rotate_right" []) -- (that's not actually present in our proof)` `tInfo.stx.getSubstring?` //=> `None` -/
ArgumentInfo where name : String type : String deriving Inhabited, FromJson, ToJson
structure
lean
[ "import Lean", "import Services.GetTacticSubstring" ]
lean/Services/GetTheorems.lean
ArgumentInfo
null
DeclarationInfo where name : Name declarationType : String -- "theorem", "lemma", "definition", "axiom", etc. body : Option String -- definition body if applicable deriving Inhabited, FromJson, ToJson
structure
lean
[ "import Lean", "import Services.GetTacticSubstring" ]
lean/Services/GetTheorems.lean
DeclarationInfo
null
TheoremSignature where name : String instanceArgs : List ArgumentInfo := [] -- [] implicitArgs : List ArgumentInfo := [] -- {} explicitArgs : List ArgumentInfo := [] -- () type : String := "" -- return type declarationType : String := "" -- declaration type body : Option String := none -- definition body if applicable deriving Inhabited, FromJson, ToJson
structure
lean
[ "import Lean", "import Services.GetTacticSubstring" ]
lean/Services/GetTheorems.lean
TheoremSignature
null
getIds : Syntax → NameSet | .node _ _ args => (args.map getIds).foldl (·.append ·) {} | .ident _ _ nm _ => NameSet.empty.insert nm | _ => {}
def
lean
[ "import Lean", "import Services.GetTacticSubstring" ]
lean/Services/GetTheorems.lean
getIds
null
getAllArgsWithTypes (expr : Expr) : MetaM (List ArgumentInfo × List ArgumentInfo × List ArgumentInfo × String) := do Meta.forallTelescope expr fun args body => do let mut lctx := LocalContext.empty for arg in args do let decl ← arg.fvarId!.getDecl lctx := lctx.addDecl decl let ppCtx : PPContext := { env := ← getEnv, mctx := ← getMCtx, lctx, opts := (← getOptions).setBool `pp.fullNames true } let mut instanceArgs := [] let mut implicitArgs := [] let mut explicitArgs := [] for arg in args do let decl ← arg.fvarId!.getDecl let typeStr ← ppExprWithInfos ppCtx decl.type let argInfo := { name := decl.userName.toString, type := typeStr.fmt.pretty : ArgumentInfo } match decl.binderInfo with | BinderInfo.instImplicit => instanceArgs := instanceArgs ++ [argInfo] | BinderInfo.implicit => implicitArgs := implicitArgs ++ [argInfo] | BinderInfo.strictImplicit => implicitArgs := implicitArgs ++ [argInfo] | BinderInfo.default => explicitArgs := explicitArgs ++ [argInfo] let bodyStr ← ppExprWithInfos ppCtx body return (instanceArgs, implicitArgs, explicitArgs, bodyStr.fmt.pretty) /-- Check if a substring position is within a given range -/
def
lean
[ "import Lean", "import Services.GetTacticSubstring" ]
lean/Services/GetTheorems.lean
getAllArgsWithTypes
null
isInRange (substr : Substring.Raw) (startPos stopPos : String.Pos.Raw) : Bool := substr.startPos >= startPos && substr.stopPos <= stopPos /-- Get declaration type string from ConstantInfo -/
def
lean
[ "import Lean", "import Services.GetTacticSubstring" ]
lean/Services/GetTheorems.lean
isInRange
/-- Check if a substring position is within a given range -/
getDeclarationType (ci : ConstantInfo) : String := match ci with | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" | .opaqueInfo _ => "opaque" | .quotInfo _ => "quotient" | .inductInfo _ => "inductive" | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" /-- Process a declaration and extract all relevant info (type, args, body) -/
def
lean
[ "import Lean", "import Services.GetTacticSubstring" ]
lean/Services/GetTheorems.lean
getDeclarationType
/-- Get declaration type string from ConstantInfo -/
processDeclaration (name : Name) (ctx : ContextInfo) (goalDecl : MetavarDecl) : MetaM (Option TheoremSignature) := do let constInfo ← getConstInfo name let declType := getDeclarationType constInfo -- Only process theorems, axioms, and definitions unless (declType == "theorem" || declType == "axiom" || declType == "def") do return none let ppCtx := { (ctx.toPPContext (goalDecl.lctx |>.sanitizeNames.run' {options := {}})) with opts := (ctx.toPPContext goalDecl.lctx).opts.setBool `pp.fullNames true } -- Get the name with full qualification let nameStr ← ppExprWithInfos ppCtx (mkConst constInfo.name) -- Extract arguments and return type let (instanceArgs, implicitArgs, explicitArgs, typeStr) ← getAllArgsWithTypes constInfo.type -- Only include definition body for "def" declarations let declBody ← if declType == "def" then match constInfo.value? with | some expr => do let bodyStr ← ppExprWithInfos ppCtx expr pure (some bodyStr.fmt.pretty) | none => pure none else pure none return some { name := nameStr.fmt.pretty, instanceArgs, implicitArgs, explicitArgs, type := typeStr, declarationType := declType, body := declBody } -- TODO I think now we can remove everything and just leave .const here /-- Extract theorem name from expression, handling constants, applications, and local variables -/
def
lean
[ "import Lean", "import Services.GetTacticSubstring" ]
lean/Services/GetTheorems.lean
processDeclaration
/-- Process a declaration and extract all relevant info (type, args, body) -/
extractTheoremName (expr : Expr) (lctx : LocalContext) : Option Name := do guard (!expr.isSyntheticSorry) -- It's important to use cleanExpr here, otherwise we'll be getting "fvar expected" exceptions sometimes let cleanExpr := expr.consumeMData match cleanExpr with | .const name _ => some name | .app .. => expr.getAppFn.consumeMData.constName? | .fvar .. => do let ldecl ← lctx.findFVar? cleanExpr let val ← ldecl.value? val.getAppFn.consumeMData.constName? | _ => none /-- Extract theorem names exactly like Lean's hover does - using built-in hover functionality -/
def
lean
[ "import Lean", "import Services.GetTacticSubstring" ]
lean/Services/GetTheorems.lean
extractTheoremName
/-- Extract theorem name from expression, handling constants, applications, and local variables -/
findTheoremsLikeHover (tree : Elab.InfoTree) (tacticStartPos tacticStopPos : String.Pos.Raw) (ctx : ContextInfo) (goalDecl : MetavarDecl) : MetaM (List TheoremSignature) := do let mut theoremNames : NameSet := {} -- Sample positions throughout the tactic range (every few characters) -- This ensures we catch all identifiers that would show on hover let mut currentPos := tacticStartPos let step : Nat := 3 -- Check every 3 characters while currentPos < tacticStopPos do -- Use Lean's actual hover function to find what would show at this position if let some infoWithCtx ← tree.hoverableInfoAtM? currentPos then -- Extract theorem name from the hover info match infoWithCtx.info with | .ofTermInfo termInfo => if let some name := extractTheoremName termInfo.expr termInfo.lctx then theoremNames := theoremNames.insert name | _ => pure () currentPos := ⟨currentPos.byteIdx + step⟩ -- Process each theorem name and filter for relevant declarations let theoremSignatures ← theoremNames.toList.filterMapM fun name => do let resolvedName ← resolveGlobalConstNoOverloadCore name processDeclaration resolvedName ctx goalDecl pure theoremSignatures
def
lean
[ "import Lean", "import Services.GetTacticSubstring" ]
lean/Services/GetTheorems.lean
findTheoremsLikeHover
/-- Extract theorem names exactly like Lean's hover does - using built-in hover functionality -/
GetTheorems (infoTree : InfoTree) (tacticInfo : TacticInfo) (ctx : ContextInfo) : RequestM (List TheoremSignature) := do let some goalDecl := ctx.mctx.findDecl? tacticInfo.goalsBefore.head! | throwThe RequestError ⟨.invalidParams, "noGoalDecl"⟩ let some tacticSubstring := getTacticSubstring tacticInfo | throwThe RequestError ⟨.invalidParams, "noTacticSubstring"⟩ ctx.runMetaM goalDecl.lctx do findTheoremsLikeHover infoTree tacticSubstring.startPos tacticSubstring.stopPos ctx goalDecl
def
lean
[ "import Lean", "import Services.GetTacticSubstring" ]
lean/Services/GetTheorems.lean
GetTheorems
null
goalsAt ? (t : InfoTree) (text : FileMap) (hoverPos : String.Pos.Raw) : List GoalsAtResult := let gs := t.collectNodesBottomUp fun ctx i cs gs => Id.run do if let Info.ofTacticInfo ti := i then if let (some pos, some tailPos) := (i.pos?, i.tailPos?) then let trailSize := i.stx.getTrailingSize -- dbg_trace trailSize -- show info at EOF even if strictly outside token + trail let atEOF := tailPos.byteIdx + trailSize == text.source.rawEndPos.byteIdx -- include at least one trailing character (see also `priority` below) if pos ≤ hoverPos ∧ (hoverPos.byteIdx < tailPos.byteIdx + max 1 trailSize || atEOF) then let isClosingBracketInRewriteSequence := ti.stx.getAtomVal == "]" if (gs.isEmpty || (hoverPos ≥ tailPos && gs.all (·.indented))) && !isClosingBracketInRewriteSequence then return [{ ctxInfo := ctx tacticInfo := ti useAfter := hoverPos > pos && !cs.any (hasNestedTactic pos tailPos) -- consider every position unindented after an empty `by` to support "hanging" `by` uses -- indented := indented := (text.toPosition pos).column > (text.toPosition hoverPos).column && !isEmptyBy ti.stx -- use goals just before cursor as fall-back only -- thus for `(by foo)`, placing the cursor after `foo` shows its state as long -- as there is no state on `)` priority := if hoverPos.byteIdx == tailPos.byteIdx + trailSize then 0 else 1 }] return gs let maxPrio? := gs.map (·.priority) |>.max? gs.filter (some ·.priority == maxPrio?) where hasNestedTactic (pos tailPos) : InfoTree → Bool | InfoTree.node i@(Info.ofTacticInfo _) cs => Id.run do if let `(by $_) := i.stx then return false -- ignore term-nested proofs such as in `simp [show p by ...]` if let (some pos', some tailPos') := (i.pos?, i.tailPos?) then -- ignore preceding nested infos -- ignore nested infos of the same tactic, e.g. from expansion if tailPos' > hoverPos && (pos', tailPos') != (pos, tailPos) then return true cs.any (hasNestedTactic pos tailPos) | InfoTree.node (Info.ofMacroExpansionInfo _) cs => cs.any (hasNestedTactic pos tailPos) | _ => false isEmptyBy (stx : Syntax) : Bool := -- there are multiple `by` kinds with the same structure stx.getNumArgs == 2 && stx[0].isToken "by" && stx[1].getNumArgs == 1 && stx[1][0].isMissing
def
lean
[ "import Lean" ]
lean/Services/GoalsAt.lean
goalsAt
null
State | start | tacticStringWillOccurSoon | tacticStringStarted /-- EXAMPLE `rw_mod_cast [Set.mem_inter_iff, and_com|m]` //=> `"rw_mod_cast"` `nth_rw 2 [Na|t.add_comm]` //=> `"nth_rw"` -/
inductive
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Elab.Tactic", "import Services.GetTacticSubstring" ]
lean/Services/PrettifyRwTactic.lean
State
null
getClosestRw (text: Lean.FileMap) (hoverPos: String.Pos.Raw) : Id String := do let mut currentPosition : String.Pos.Raw := hoverPos let text : String := Lean.FileMap.source text let mut state : State := State.start let mut rwList : List Char := [] while currentPosition != 0 do currentPosition := currentPosition.prev text let currentChar := currentPosition.get text match state with | State.start => if currentChar.toString == "[" then state := State.tacticStringWillOccurSoon | State.tacticStringWillOccurSoon => if !currentChar.isWhitespace && !currentChar.isDigit then state := State.tacticStringStarted rwList := currentChar :: rwList | State.tacticStringStarted => if !currentChar.isWhitespace then rwList := currentChar :: rwList else break return String.ofList rwList /-- EXAMPLE `prettifyRwRule "Set.mem_inter_iff, "` //=> `"Set.mem_inter_iff"` -/
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Elab.Tactic", "import Services.GetTacticSubstring" ]
lean/Services/PrettifyRwTactic.lean
getClosestRw
/-- EXAMPLE `rw_mod_cast [Set.mem_inter_iff, and_com|m]` //=> `"rw_mod_cast"` `nth_rw 2 [Na|t.add_comm]` //=> `"nth_rw"` -/
prettifyRwRule (tacticString : String) := (tacticString.splitOn ",").head!.trim
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Elab.Tactic", "import Services.GetTacticSubstring" ]
lean/Services/PrettifyRwTactic.lean
prettifyRwRule
/-- EXAMPLE `prettifyRwRule "Set.mem_inter_iff, "` //=> `"Set.mem_inter_iff"` -/
isTacticRwRule (tacticInfo: TacticInfo) : Bool := let string : String := tacticInfo.stx.formatStx.pretty string.startsWith "[(Tactic.rwRule"
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Elab.Tactic", "import Services.GetTacticSubstring" ]
lean/Services/PrettifyRwTactic.lean
isTacticRwRule
/-- EXAMPLE `prettifyRwRule "Set.mem_inter_iff, "` //=> `"Set.mem_inter_iff"` -/
prettifyRwTactic (tacticInfo : TacticInfo) (text : FileMap) (hoverPos : String.Pos.Raw) : RequestM String := do if (isTacticRwRule tacticInfo) then let .some tacticSubstring := getTacticSubstring tacticInfo | return "" let closestRwTacticName := getClosestRw text hoverPos let rwRule := ((Substring.Raw.toString tacticSubstring).splitOn ",").head!.trim pure s!"{closestRwTacticName} [{rwRule}]" else pure ""
def
lean
[ "import Lean", "import Lean.Meta.Basic", "import Lean.Elab.Tactic", "import Services.GetTacticSubstring" ]
lean/Services/PrettifyRwTactic.lean
prettifyRwTactic
/-- EXAMPLE `prettifyRwRule "Set.mem_inter_iff, "` //=> `"Set.mem_inter_iff"` -/
shouldRenderSingleSequent (tacticInfo : TacticInfo) (text : FileMap) (hoverPos : String.Pos.Raw) : RequestM Bool := do let .some tacticSubstring := tacticInfo.stx.getSubstring? | throwThe RequestError ⟨.invalidParams, "couldntFindTacticSubstring"⟩ let file : String := Lean.FileMap.source text let charBefore := hoverPos.prev file |>.get file let charAfter := hoverPos.get file let atEOF := hoverPos.atEnd file let isNotOnTactic := charBefore.isWhitespace && (charAfter.isWhitespace || atEOF) let isBy := tacticSubstring.toString.trim == "by" return isNotOnTactic || isBy
def
lean
[ "import Lean" ]
lean/Services/ShouldRenderSingleSequent.lean
shouldRenderSingleSequent
null
apply (a b : ℝ) : a = b := by apply le_antisymm
theorem
_examples
[ "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
_examples/demos/CommonTactics.lean
apply
null
have_ (a b : ℝ) (h1 : a ≤ b) (h2 : b ≤ a) : True := by have hi := le_antisymm h1 h2
theorem
_examples
[ "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
_examples/demos/CommonTactics.lean
have_
null
intro : ∀ (N : ℕ), ∃ M, N + N = M := by intro n
theorem
_examples
[ "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
_examples/demos/CommonTactics.lean
intro
null
rw (a b : ℕ) (h1: a = b) : (10 * a = 666) := by rw [h1]
theorem
_examples
[ "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
_examples/demos/CommonTactics.lean
rw
null
by_contra_ (m : ℕ) : 2 ≤ m := by by_contra h
theorem
_examples
[ "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
_examples/demos/CommonTactics.lean
by_contra_
null
use : ∃ x : Nat, x = 5 := by use 42
theorem
_examples
[ "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
_examples/demos/CommonTactics.lean
use
null
induction (n : ℕ) : Nat.mul 0 n = 0 := by induction n
theorem
_examples
[ "import Mathlib.Algebra.GCDMonoid.Multiset", "import Mathlib.Data.Real.Basic", "import Lean", "import Paperproof" ]
_examples/demos/CommonTactics.lean
induction
null
tacticProof (a b : Prop) : a ∧ b → b ∧ a := by intro ab rcases ab with ⟨hA, hB⟩ apply And.intro exact hB exact hA
theorem
_examples
[ "import Mathlib.Tactic.Cases", "import Mathlib.Tactic.Explode", "import Paperproof" ]
_examples/demos/Explode.lean
tacticProof
null
prooftermProof (a b : Prop) : a ∧ b → b ∧ a := λ ab => And.casesOn (motive := λ t => ab = t → b ∧ a) ab (λ hA hB _ => And.intro hB hA) (Eq.refl ab)
theorem
_examples
[ "import Mathlib.Tactic.Cases", "import Mathlib.Tactic.Explode", "import Paperproof" ]
_examples/demos/Explode.lean
prooftermProof
null
sweepingTacticProof : ∀ (a b : Prop), a ∧ b → b ∧ a := by myPersonalTactic -- #explode results in exactly the same output, because it's based on `Expr`s. -- Contrast this with Paperproof outputs, which are based on `InfoTree`s. #explode tacticProof #explode prooftermProof #explode sweepingTacticProof
theorem
_examples
[ "import Mathlib.Tactic.Cases", "import Mathlib.Tactic.Explode", "import Paperproof" ]
_examples/demos/Explode.lean
sweepingTacticProof
null
commutativityOfIntersections (s t : Set Nat) : s ∩ t = t ∩ s := by ext x apply Iff.intro intro h1 rw [Set.mem_inter_iff, and_comm] at h1 exact h1 intro h2 rw [Set.mem_inter_iff, and_comm] at h2 exact h2
theorem
_examples
[ "import Mathlib.Data.Set.Basic", "import Paperproof" ]
_examples/demos/ForVideos.lean
commutativityOfIntersections
null
gradual (p q : Prop) : p ∧ q ↔ q ∧ p := by tactic_1 tactic_2 sorry variable (p q : Prop) -- [this is the initial goal]
theorem
_examples
[ "import Lean.Elab.Tactic", "import Paperproof" ]
_examples/demos/GoalsFormATree.lean
gradual
null
andIntroductionTop {A B : Prop} (h1 : A) (h2 : B) : OurGoal := by have h := And.intro h1 h2 all_goals sorry
theorem
_examples
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Lean", "import Paperproof" ]
_examples/demos/NaturalDeduction.lean
andIntroductionTop
null
andIntroductionBottom {A B : Prop} (h1 : A) (h2 : B) : A ∧ B := by apply And.intro all_goals sorry
theorem
_examples
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Lean", "import Paperproof" ]
_examples/demos/NaturalDeduction.lean
andIntroductionBottom
null
andEliminationTop {A B : Prop} (h : A ∧ B) : OurGoal := by -- have h1 := h.left apply And.left at h sorry
theorem
_examples
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Lean", "import Paperproof" ]
_examples/demos/NaturalDeduction.lean
andEliminationTop
null
andEliminationBottom {A B : Prop} : A := by apply And.left (a := A) (b := B) sorry -- DISJUNCTION
theorem
_examples
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Lean", "import Paperproof" ]
_examples/demos/NaturalDeduction.lean
andEliminationBottom
null
orIntroductionTop {A B : Prop} (h : A) : OurGoal := by have ab : A ∨ B := Or.inl h sorry
theorem
_examples
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Lean", "import Paperproof" ]
_examples/demos/NaturalDeduction.lean
orIntroductionTop
null
orIntroductionBottom {A B : Prop} : A ∨ B := by apply Or.inl sorry
theorem
_examples
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Lean", "import Paperproof" ]
_examples/demos/NaturalDeduction.lean
orIntroductionBottom
null
orEliminationTop {A B : Prop} (h : A ∨ B) : OurGoal := by cases' h with a b all_goals sorry
theorem
_examples
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Lean", "import Paperproof" ]
_examples/demos/NaturalDeduction.lean
orEliminationTop
null
orEliminationBottom {A B : Prop} : OurGoal := by apply Or.elim (a := A) (b := B) all_goals sorry -- IMPLICATION
theorem
_examples
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Lean", "import Paperproof" ]
_examples/demos/NaturalDeduction.lean
orEliminationBottom
null
arrowIntroductionTop {A B : Prop} (b : B) : OurGoal := by let h := λ a : A => b sorry
theorem
_examples
[ "import Mathlib.Data.Nat.Prime.Basic", "import Mathlib.Data.List.Chain", "import Mathlib.Tactic.Linarith", "import Mathlib.Data.Set.Basic", "import Mathlib.Data.Finset.Fold", "import Mathlib.Algebra.GCDMonoid.Multiset", "import Lean", "import Paperproof" ]
_examples/demos/NaturalDeduction.lean
arrowIntroductionTop
null