formal-conjectures / lean_project /scripts /extract_names.lean
nielsr's picture
nielsr HF Staff
Add Formal Conjectures (snapshot 86a2f58): statements + files parquet, Lean project (part 7)
8ca48d7 verified
Raw History Blame Contribute Delete
15 kB
/-
Copyright 2025 The Formal Conjectures Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
module
public import Lean
public meta import FormalConjecturesUtil.Metadata
public import FormalConjecturesUtil.Attributes.Basic
/-!
# Extract Names
This script extracts metadata (theorem names, statements, categories, subjects,
formal proof links, and whether the source poses the statement as a question) from
formalized mathematical conjectures in the repository.
### Usage
The script reads the compiled `.olean` files, so build the problems first.
```bash
lake build
lake exe extract_names [directory-or-file] [--exclude=key1,key2] [--no-docstrings]
```
-/
@[expose] public meta section
open Lean ProblemAttributes
def getModuleNameFromFile (file : System.FilePath) : IO Name := do
let components := file.withExtension "" |>.components
-- Assuming the file is under FormalConjectures/
let mut moduleComponents := []
let mut found := false
for c in components do
if c == "FormalConjectures" || found then
found := true
moduleComponents := moduleComponents ++ [c]
if moduleComponents.isEmpty then
throw <| IO.userError s!"Could not determine module name for {file}. Is it under FormalConjectures/?"
return moduleComponents.foldl (fun n s => Name.mkStr n s) Name.anonymous
-- Helper to format Category as string
def categoryToString : Category → String
| .textbook => "textbook"
| .research .open => "research open"
| .research .solved => "research solved"
| .test => "test"
| .API => "API"
-- Helper to format FormalProofKind as string
def formalProofKindToString : FormalProofKind → String
| .formalConjecturesProof => "formal_conjectures"
| .lean4 => "lean4"
| .otherSystem => "other_system"
/-- Run a git command and return its stdout, trimmed. Returns `none` on failure. -/
def gitOutput (args : Array String) : IO (Option String) := do
try
let out ← IO.Process.output { cmd := "git", args := args }
if out.exitCode == 0 then
let s := out.stdout.trimAscii.toString
return if s.isEmpty then none else some s
else return none
catch _ => return none
/-- Get the ISO 8601 timestamp of when a file was first added to the repo. -/
def getFileFirstAdded (file : System.FilePath) : IO (Option String) :=
gitOutput #["log", "--diff-filter=A", "--follow", "--format=%aI", "--", file.toString]
<&> (·.bind (·.splitOn "\n" |>.getLast?))
/-- Get the ISO 8601 timestamp of the most recent commit that modified a file. -/
def getFileLastModified (file : System.FilePath) : IO (Option String) :=
gitOutput #["log", "-1", "--format=%aI", "--", file.toString]
/-- Valid keys for the `--exclude` flag. -/
def validExcludeKeys : List String :=
["docstring", "statement", "subjects", "formalProofs",
"hasSorryFreeProof", "moduleDocstrings", "question",
"fileFirstAdded", "fileLastModified"]
-- `FormalProofInfo` and its ordering live in `FormalConjecturesUtil.Metadata`,
-- the shared home for facts more than one tool consumes.
open FormalConjectures.Metadata
structure TheoremInfo where
«theorem» : String
module : String
category : String
subjects : List String
statement : String
docstring : Option String
formalProofs : List FormalProofInfo
hasSorryFreeProof : Bool
subsets : List String
/-- The kind of question (`"yes_no"` or `"value"`) if the declaration carries the
`question` attribute. -/
question : Option String
fileFirstAdded : Option String
fileLastModified : Option String
/-- Serialize `TheoremInfo` to JSON, omitting fields whose keys are in `exclude`. -/
def TheoremInfo.toFilteredJson (info : TheoremInfo) (exclude : Std.HashSet String := {}) : Json :=
let fields : List (String × Json) :=
[("theorem", toJson info.theorem),
("module", toJson info.module),
("category", toJson info.category)]
++ (if exclude.contains "subjects" then [] else [("subjects", toJson info.subjects)])
++ (if exclude.contains "statement" then [] else [("statement", toJson info.statement)])
++ (if exclude.contains "docstring" then [] else [("docstring", toJson info.docstring)])
++ (if exclude.contains "formalProofs" || info.formalProofs.isEmpty then [] else
[("formalProofs", Json.arr (info.formalProofs.map FormalProofInfo.toJson).toArray)])
++ (if exclude.contains "hasSorryFreeProof" then [] else
[("hasSorryFreeProof", toJson info.hasSorryFreeProof)])
++ (if info.subsets.isEmpty then [] else [("subsets", toJson info.subsets)])
++ (match info.question with
| some kind => if exclude.contains "question" then [] else [("question", toJson kind)]
| none => [])
++ (if exclude.contains "fileFirstAdded" then [] else
[("fileFirstAdded", toJson info.fileFirstAdded)])
++ (if exclude.contains "fileLastModified" then [] else
[("fileLastModified", toJson info.fileLastModified)])
Json.mkObj fields
instance : ToJson TheoremInfo where
toJson info := info.toFilteredJson
unsafe def runWithImports {α : Type} (moduleNames : Array Name) (actionToRun : CoreM α) : IO α := do
initSearchPath (← getBuildDir)
let imports := moduleNames.map fun n => { module := n }
let currentCtx := { fileName := "", fileMap := default }
Lean.enableInitializersExecution
let env ← Lean.importModules imports {} (trustLevel := 1024) (loadExts := true)
let (result, _newState) ← Core.CoreM.toIO actionToRun currentCtx { env := env }
return result
partial def getAllLeanFiles (dir : System.FilePath) : IO (Array System.FilePath) := do
let mut files := #[]
if ← dir.isDir then
for entry in ← dir.readDir do
if ← entry.path.isDir then
files := files ++ (← getAllLeanFiles entry.path)
else if entry.path.extension == some "lean" then
files := files.push entry.path
return files
unsafe def main (args : List String) : IO Unit := do
-- Parse flags vs file arguments
let (flags, fileArgs) := args.partition (·.startsWith "--")
let mut excludeSet : Std.HashSet String := {}
for flag in flags do
if flag == "--no-docstrings" then
excludeSet := excludeSet.insert "docstring" |>.insert "moduleDocstrings"
else if flag.startsWith "--exclude=" then
let excludeStr := flag.drop 10 |>.toString
let fields := excludeStr.splitOn ","
for f in fields do
if f ∉ validExcludeKeys then
throw <| IO.userError s!"Unknown exclude key: '{f}'. Valid keys: {validExcludeKeys}"
excludeSet := excludeSet.insert f
else
throw <| IO.userError s!"Unknown flag: '{flag}'. Supported: --exclude=key1,key2 --no-docstrings"
let leanFiles ← match fileArgs with
| [] =>
let f1 ← getAllLeanFiles "FormalConjectures"
pure (f1)
| [arg] =>
let p := System.FilePath.mk arg
if ← p.isDir then
getAllLeanFiles p
else
pure #[p]
| _ =>
let usageMsg :=
"Usage: extract_names [directory-or-file] [--exclude=key1,key2] [--no-docstrings]\n\n" ++
"Note: Build first."
throw <| IO.userError usageMsg
-- Pre-compute git timestamps for each file and build module name array (only when not excluded)
let needFirstAdded := !excludeSet.contains "fileFirstAdded"
let needLastModified := !excludeSet.contains "fileLastModified"
let needGitInfo := needFirstAdded || needLastModified
let mut moduleNames := #[]
let mut fileTimestamps : Std.HashMap Name (Option String × Option String) := {}
for file in leanFiles do
try
let modName ← getModuleNameFromFile file
moduleNames := moduleNames.push modName
if needGitInfo then
let firstAdded ← if needFirstAdded then getFileFirstAdded file else pure none
let lastModified ← if needLastModified then getFileLastModified file else pure none
fileTimestamps := fileTimestamps.insert modName (firstAdded, lastModified)
catch _ => pure ()
runWithImports moduleNames do
let env ← getEnv
let tags ← getTags
let subjectTags ← getSubjectTags
let formalProofTags ← getFormalProofTags
-- Create maps for quick lookup
let mut categoryMap : Std.HashMap Name (List String) := {}
let mut categoryFullMap : Std.HashMap Name CategoryTag := {}
for tag in tags do
categoryMap := categoryMap.insert tag.declName (categoryToString tag.category :: categoryMap.getD tag.declName [])
categoryFullMap := categoryFullMap.insert tag.declName tag
-- Create formal proof map. A declaration may carry several `formal_proof` annotations,
-- so collect them all rather than keeping whichever arrives last.
let mut formalProofMap : Std.HashMap Name (List FormalProofTag) := {}
for tag in formalProofTags do
formalProofMap :=
formalProofMap.insert tag.declName (tag :: formalProofMap.getD tag.declName [])
let mut subjectMap : Std.HashMap Name (List String) := {}
for tag in subjectTags do
let subjects := tag.subjects.map (fun (s : AMS) => s!"{s.toNat?.get!}")
subjectMap := subjectMap.insert tag.declName (subjects ++ subjectMap.getD tag.declName [])
let mut theoremToSubsets : Std.HashMap Name (List String) := {}
for (declName, _) in env.constants do
if let .str (.str grandparent subsetName) "problems" := declName then
if grandparent.toString == "Subsets" then
let info ← getConstInfo declName
if let some val := info.value? then
try
let problemsList ← Lean.Meta.MetaM.run' <|
unsafe Lean.Meta.evalExpr (List Name) (mkApp (mkConst ``List [.zero]) (mkConst ``Name)) val
for p in problemsList do
theoremToSubsets := theoremToSubsets.insert p (subsetName :: theoremToSubsets.getD p [])
catch e =>
let msg ← e.toMessageData.toString
IO.eprintln s!"WARNING: Failed to evaluate problems list for {declName}: {msg}"
let mut allResults : List TheoremInfo := []
for modName in moduleNames do
let some modIdx := env.header.moduleNames.findIdx? (· == modName)
| continue
let modData := env.header.moduleData[modIdx]!
for info in modData.constants do
let name := info.name
match info with
| ConstantInfo.thmInfo .. =>
if !isPrivateName name then
let cats := categoryMap.getD name []
let subjs := subjectMap.getD name []
if !cats.isEmpty || !subjs.isEmpty then
if cats.length ≠ 1 then
throwError m!"Theorem {name} must have exactly one category, found {cats.length}."
let statement := toString (← Meta.MetaM.run' (Meta.ppExpr info.type))
let docstring ← findDocString? env name
if docstring.isNone then
IO.eprintln s!"WARNING: Theorem {name} (category: {cats.head!}) is missing a docstring"
-- Extract formal proof info from the separate formal_proof attributes. Each
-- carries its own `conditions`, since one proof can be conditional while
-- another of the same statement is not.
let formalProofs :=
((formalProofMap.getD name []).map fun tag =>
{ kind := formalProofKindToString tag.proofKind,
link := tag.proofLink,
conditions := tag.conditions.map Name.toString : FormalProofInfo })
|>.toArray.qsort (fun a b => a.sortKey < b.sortKey) |>.toList
-- Check whether the proof term is sorry-free
let hasSorryFreeProof :=
info.value? (allowOpaque := true) |>.any (!·.hasSorry)
-- Warn about suspicious category / sorry combinations
if let some catTag := categoryFullMap.get? name then
match catTag.category, hasSorryFreeProof with
| .research .open, true =>
IO.eprintln s!"WARNING: Theorem {name} is categorised as `research open` but has a sorry-free proof"
| .test, false =>
IO.eprintln s!"WARNING: Theorem {name} is categorised as `test` but has no sorry-free proof"
| .API, false =>
IO.eprintln s!"WARNING: Theorem {name} is categorised as `API` but has no sorry-free proof"
| _, _ => pure ()
let subsets := (theoremToSubsets.getD name []).toArray.qsort (· < ·) |>.toList
let (fileFirstAdded, fileLastModified) :=
fileTimestamps.getD modName (none, none)
allResults := {
«theorem» := name.toString,
module := modName.toString,
category := cats.head!,
subjects := subjs,
statement := statement,
docstring := docstring,
formalProofs := formalProofs,
hasSorryFreeProof := hasSorryFreeProof,
subsets := subsets
question := (← getQuestionKind? name).map toString
fileFirstAdded := fileFirstAdded
fileLastModified := fileLastModified
} :: allResults
| _ => pure ()
-- Collect module docstrings via Lean's getModuleDoc? API
let mut moduleDocstrings : List (String × String) := []
if !excludeSet.contains "moduleDocstrings" then
for modName in moduleNames do
if let some docs := getModuleDoc? env modName then
if docs.size != 1 then
IO.eprintln s!"WARNING: Module {modName} has {docs.size} module docstrings"
if docs.size > 0 then
let combined := "\n\n".intercalate (docs.toList.map (·.doc))
moduleDocstrings := (modName.toString, combined) :: moduleDocstrings
-- Build structured output: { problems: [...], moduleDocstrings: {...} }
let problemsJson := toJson (allResults.reverse.map (·.toFilteredJson excludeSet))
-- Consumers should not have to guess whether they are reading the old
-- `formalProofKind` shape or the `formalProofs` list; say so.
let mut outputFields : List (String × Json) :=
[("schemaVersion", Lean.toJson (2 : Nat)), ("problems", problemsJson)]
if !excludeSet.contains "moduleDocstrings" then
let moduleDocJson := Json.mkObj (moduleDocstrings.reverse.map fun (k, v) => (k, toJson v))
outputFields := outputFields ++ [("moduleDocstrings", moduleDocJson)]
let output := Json.mkObj outputFields
IO.println output.pretty