diff --git a/Leanfran/Check.lean b/Leanfran/Check.lean index 5c7c4536..dfea0778 100644 --- a/Leanfran/Check.lean +++ b/Leanfran/Check.lean @@ -5,6 +5,7 @@ import Lean.Meta.Instances import Lean.Replay import Lean.Util.CollectAxioms import Leanfran.Check.Rejected +import Leanfran.Check.Syntax import Leanfran.Cli import Leanfran.Embed.Types import Leanfran.Module.Job @@ -85,12 +86,20 @@ structure Judge where /-- The modules with files that Lean rejects. -/ rejected : NameSet := {} checked : IO.Ref Kernel.Environment + tokens : IO.Ref (Option Tokens) + /-- The modules of obligations with what changes how Lean reads them. -/ + changes : IO.Ref (NameMap (Option String)) def Judge.new (policy : Policy) (sysroot : FilePath) (env : Environment) (rejected : NameSet := {}) : IO Judge := do let lib := s!"{sysroot / "lib" / "lean"}/" let toolchain ← env.header.moduleNames.filterM fun m => return (← findOLean m).toString.startsWith lib let base ← importModules ((if policy.replay then toolchain else #[]).map fun m => {module := m}) {} - return {policy, rejected, toolchain := toolchain.foldl NameSet.insert {}, checked := ← IO.mkRef base.toKernelEnv} + return { + policy, rejected + toolchain := toolchain.foldl NameSet.insert {} + checked := ← IO.mkRef base.toKernelEnv + tokens := ← IO.mkRef none + changes := ← IO.mkRef {}} private def moduleOf (env : Environment) (n : Name) : Option Name := (env.getModuleIdxFor? n).map fun idx => env.header.moduleNames[idx.toNat]! @@ -130,6 +139,30 @@ def rejection (judge : Judge) (env : Environment) (thm : Name) (uses : List Name let problem ← replayProblem judge env (thm :: uses) return problem.map (s!"the kernel rejected {thm} or a declaration it uses: {·}") +private def packageModule (module : Name) : IO Bool := do + let components := (← findOLean module).components + return (components.zip (components.drop 1)).any fun (a, b) => a.startsWith ".lake" && b == "packages" + +/-- What changes how Lean reads the translated definition of `stmt`. -/ +def changedSyntax (judge : Judge) (stmt : Name) : MetaM (Option String) := do + let env ← getEnv + let some module := moduleOf env stmt | return none + if let some found := (← judge.changes.get).find? module then return found + let ours := fun m => judge.toolchain.contains m || within judge.policy.library m + let mut blocks : NameSet := {} + for m in env.header.moduleNames do + unless ours m || within judge.policy.models m || (← packageModule m) do blocks := blocks.insert m + let reading : Reading := {ours, blocks := blocks.contains} + let tokens ← match ← judge.tokens.get with + | some tokens => pure tokens + | none => + let tokens ← reading.tokens env + judge.tokens.set (some tokens) + pure tokens + let found ← reading.change tokens module + judge.changes.modify (·.insert module found) + return found + def orphanInstance (judge : Judge) (stmt : Name) : MetaM (Option (Name × Name)) := do let env ← getEnv let ours := fun (n : Name) => (moduleOf env n).any fun m => @@ -174,6 +207,8 @@ def checkObligation (judge : Judge) (o : ObligationRef) : MetaM Judgement := do if let some (inst, module) ← orphanInstance judge stmt then let detail := s!"the translated definition uses the instance {inst} from {module} on standard types" return result {label, status := .unextracted, detail, file, line} + if let some detail ← changedSyntax judge stmt then + return result {label, status := .unextracted, detail, file, line} if hasError env judge.rejected thm then return result {label, status := .failed, detail := s!"Lean rejects the proof {thm}", file, line} let axioms ← collectAxioms thm diff --git a/Leanfran/Check/Syntax.lean b/Leanfran/Check/Syntax.lean new file mode 100644 index 00000000..3fd13246 --- /dev/null +++ b/Leanfran/Check/Syntax.lean @@ -0,0 +1,158 @@ +import Lean.Elab.Do.Basic +import Lean.Elab.Do.InferControlInfo +import Lean.Elab.Term +import Lean.Meta.Coe +import Lean.Meta.Instances + +open Lean Meta + +namespace Leanfran.Check + +/-- Where a module may change how Lean reads the code of the translated definitions. -/ +structure Reading where + /-- The modules of Lean and of the models of the language. -/ + ours : Name → Bool + /-- The other modules whose syntax is checked. -/ + blocks : Name → Bool + +private def Reading.declares (r : Reading) (env : Environment) (n : Name) : Bool := + match env.getModuleIdxFor? n with + | some index => r.ours env.header.moduleNames[index.toNat]! + | none => true + +private def entryOf : ScopedEnvExtension.Entry α → α + | .global a | .scoped _ a => a + +private def keyed (attr : KeyedDeclsAttribute γ) (env : Environment) (index : ModuleIdx) : Array Name := + (attr.ext.ext.getModuleEntries env index).map fun e => (entryOf e).key + +private def elaborated (env : Environment) (index : ModuleIdx) : Array Name := + keyed Elab.macroAttribute env index ++ keyed Elab.Term.termElabAttribute env index ++ + keyed Elab.Do.doElemElabAttribute env index ++ keyed Elab.Do.controlInfoElemAttribute env index ++ + keyed Elab.Command.commandElabAttribute env index + +private def proofCategories : List Name := [`tactic, `conv] + +private def inProofs (env : Environment) (kind : Name) : Bool := + let categories := (Parser.parserExtension.getState env).categories + proofCategories.any fun category => (categories.find? category).any (·.kinds.contains kind) + +/-- The first tokens of a parser, or `none` when it starts with something else. -/ +private partial def firstTokens (e : Expr) : Option (List String) := + let e := e.consumeMData + let arg := fun (n : Nat) => e.getAppArgs[n]?.getD default + match e.getAppFn.constName? with + | some ``ParserDescr.symbol | some ``ParserDescr.nonReservedSymbol => + match arg 0 with + | .lit (.strVal s) => some [s.trimAscii.toString] + | _ => none + | some ``ParserDescr.node => firstTokens (arg 2) + | some ``ParserDescr.trailingNode => firstTokens (arg 3) + | some ``ParserDescr.nodeWithAntiquot => firstTokens (arg 2) + | some ``ParserDescr.unary => if isName (arg 0) `atomic || isName (arg 0) `patternIgnore then firstTokens (arg 1) else none + | some ``ParserDescr.binary => + if isName (arg 0) `orelse then return (← firstTokens (arg 1)) ++ (← firstTokens (arg 2)) + else if isName (arg 0) `andthen then firstTokens (arg 1) + else none + | _ => none +where + isName (e : Expr) (n : Name) : Bool := e.name? == some n + +private def parsers (env : Environment) (index : ModuleIdx) : Array (Name × Name) := + (Parser.parserExtension.ext.getModuleEntries env index).filterMap fun e => match entryOf e with + | .parser category decl _ => some (category, decl) + | _ => none + +private def descr (env : Environment) (decl : Name) : Bool × Option (List String) := + match (env.find? decl).bind (·.value? (allowOpaque := true)) with + | some value => (!value.getAppFn.isConstOf ``ParserDescr.trailingNode, firstTokens value) + | none => (true, none) + +/-- The categories with the first tokens of their leading and of their trailing parsers. -/ +abbrev Tokens := Std.HashSet (Name × Bool × String) + +def Reading.tokens (r : Reading) (env : Environment) : IO Tokens := do + let mut tokens : Tokens := {} + for (category, c) in (← Parser.builtinParserCategoriesRef.get).toList do + for (token, _) in c.tables.leadingTable.toList do tokens := tokens.insert (category, true, token.getString!) + for (token, _) in c.tables.trailingTable.toList do tokens := tokens.insert (category, false, token.getString!) + for index in [0:env.header.moduleNames.size] do + unless r.ours env.header.moduleNames[index]! do continue + for (category, decl) in parsers env index do + let (leading, first) := descr env decl + for token in first.getD [] do tokens := tokens.insert (category, leading, token) + return tokens + +private def opening : List String := ["(", "[", "{", "⟨"] + +private def parsed (tokens : Tokens) (env : Environment) (index : ModuleIdx) : Option Name := + (parsers env index).findSome? fun (category, decl) => + let (leading, first) := descr env decl + let overlaps := fun (token : String) => + tokens.contains (category, leading, token) || opening.any fun b => token != b && token.startsWith b + if !proofCategories.contains category && first.all (·.any overlaps) then some decl else none + +private def coercionClasses : List Name := [``Coe, ``CoeTC, ``CoeOut, ``CoeOTC, ``CoeHead, ``CoeHTC, ``CoeTail, ``CoeHTCT, + ``CoeDep, ``CoeT, ``CoeFun, ``CoeSort] + +/-- An instance of a module that changes a coercion between types of `r.ours`. -/ +def Reading.coercion (r : Reading) (modules : Array Name) : MetaM (Option (Name × Name)) := do + let env ← getEnv + let state := instanceExtension.getState env + let mut found := #[] + for (name, _) in state.instanceNames.toList do + let some index := env.getModuleIdxFor? name | continue + let module := env.header.moduleNames[index.toNat]! + unless modules.contains module do continue + let some info := env.find? name | continue + let target := info.type.getForallBody + unless target.getAppFn.constName?.any coercionClasses.contains do continue + unless target.getUsedConstants.all (r.declares env) do continue + found := found.push (name, module) + if found.isEmpty then return none + for (name, module) in found do + let some info := env.find? name | continue + let changes ← withoutModifyingEnv do + for (other, _) in found do + modifyEnv (instanceExtension.modifyState · (·.eraseCore other)) + forallTelescope info.type fun _ target => do + let args := target.getAppArgs + let some source := args[0]? | return false + withLocalDeclD `x source fun x => do + if target.isAppOf ``CoeFun then return (← coerceToFunction? x).isSome + if target.isAppOf ``CoeSort then return (← coerceToSort? x).isSome + let some result := args.back? | return false + if let .some _ ← coerceSimple? x result then return true + return false + if changes then return some (name, module) + return none + +/-- The modules that `module` imports, and `module`. -/ +private def imported (env : Environment) (module : Name) : Array Name := Id.run do + let mut todo := [module] + let mut seen : NameSet := {} + let mut found := #[] + while let m :: rest := todo do + todo := rest + if seen.contains m then continue + seen := seen.insert m + let some index := env.getModuleIdx? m | continue + found := found.push m + todo := (env.header.moduleData[index.toNat]!.imports.map (·.module)).toList ++ todo + return found + +/-- What a module that `module` imports changes in the syntax of Lean and of the models of the language. -/ +def Reading.change (r : Reading) (tokens : Tokens) (module : Name) : MetaM (Option String) := do + let env ← getEnv + let modules := (imported env module).filter r.blocks + for m in modules do + let some index := env.getModuleIdx? m | continue + if let some kind := (elaborated env index).find? fun kind => r.declares env kind && !inProofs env kind then + return s!"{m} changes the meaning of the syntax {kind}" + if let some decl := parsed tokens env index then + return s!"the syntax {decl} of {m} overlaps the syntax of Lean" + if let some (inst, m) ← r.coercion modules then + return s!"the instance {inst} of {m} changes a coercion between standard types" + return none + +end Leanfran.Check diff --git a/docs/c-development.md b/docs/c-development.md index 1fd575e4..a279ff8e 100644 --- a/docs/c-development.md +++ b/docs/c-development.md @@ -15,7 +15,7 @@ The C backend builds on Lean's native C emitter and runtime. It selects Lean def - `langs/C/LeanC/Build.lean` uses Lake's module dependencies and native objects to assemble the library. `langs/C/LeanC/Link.lean` uses the active toolchain's `leanc --print-ldflags` output to generate pkg-config, Make, and CMake settings. Linux groups the static Lean libraries for the linker. macOS links them without GNU linker groups. - `langs/C/LeanC/ClangAst.lean` reads `compile_commands.json`, runs `clang -Xclang -ast-dump=json`, and parses the JSON AST for `LF_STRUCT`, `LF_MODEL`, and `leanfran --lang c translate`. A file uses the first entry for it in `compile_commands.json`. - `langs/C/LeanC/Embed/Scan.lean` reads the values of `[embed.c]`, which `Leanfran/Config.lean` reads from `leanfran.toml`, and extracts Lean blocks from C comments. `Embed/Models.lean` reads `LF_STRUCT` structs and their `LF_FIELD` constraints and writes them as Lean structures in the module `LeanfranModels`. `Embed/Workspace.lean` builds the project library, headers, and link settings from the blocks. `writeCheck` makes `leanfran.mk` and the CMake package run `support/leanfran-check.sh`, which reads `status --output json`, and without the compiler or clang compares the text of the blocks with the digest that `Embed/Fresh.lean` writes into it. The script and `Fresh.sources` read the same files and lines: the patterns of `leanfran.toml` are regular expressions in the script. `leanfran.mk` then includes itself again, so that `LEANFRAN_AUTO_SYNC=1` builds with the settings of the new `sync`. `Embed/Backend.lean` defines the C `Backend` that `Leanfran.Embed` (`Leanfran/Embed/`) runs for `sync`, `check`, and `status`: the core writes the workspace in `.leanfran/c/workspace`, maps diagnostics to the C sources, places the generated files with rollback, and keeps `leanfran.manifest.json` and `leanfran.lock`. The workspace also holds `LeanCLib.C`, so a block can import it. -- `langs/C/lean/LeanCLib/C.lean` defines the meaning of C arithmetic, conversions, array reads and loops, with undefined behavior as `C.Exc` failures. `langs/C/LeanC/Verify/Translate.lean` reads the clang JSON AST and translates C function definitions into Lean `do` blocks over `LeanCLib.C`. clang does not desugar the result in the type of a function, so `Env.expand` follows the typedefs of the file. `leanfran --lang c translate` (`LeanC/Verify/Command.lean`) writes the translation of one C file as the module `LeanCModel.` and reports each function outside the supported subset as `unextracted` with its position and reason. `LF_ARRAY(len)` marks a `const T *` parameter whose length is the parameter `len`, and the translation takes the Lean `Array` and derives `len` from its size. Generated headers mark public structures and their fields with `LF_LEAN("")` so the translation can read them by value. +- `langs/C/lean/LeanCLib/C.lean` defines the meaning of C arithmetic, conversions, array reads and loops, with undefined behavior as `C.Exc` failures. `langs/C/LeanC/Verify/Translate.lean` reads the clang JSON AST and translates C function definitions into Lean `do` blocks over `LeanCLib.C`. clang does not desugar the result in the type of a function, so `Env.expand` follows the typedefs of the file. `leanfran --lang c translate` (`LeanC/Verify/Command.lean`) writes the translation of one C file as the module `LeanCModel.` and reports each function outside the supported subset as `unextracted` with its position and reason. `langs/C/LeanC/Verify/Flags.lean` reads what the compile flags, clang's predefined macros, and the preprocessed source say about the functions of the file: the target, the flags, pragmas, and attributes that change `double` results, the flags that change layouts or aliasing, `static` array lengths, and decimal constants that clang and GCC type differently. `LF_ARRAY(len)` marks a `const T *` parameter whose length is the parameter `len`, and the translation takes the Lean `Array` and derives `len` from its size. Generated headers mark public structures and their fields with `LF_LEAN("")` so the translation can read them by value. - `langs/C/LeanC/Embed/Verify.lean` finds functions marked with `LF_MODEL("refines=", "requires=", "ensures=