| -- Copyright 2026 The Fuchsia Authors | |
| -- | |
| -- Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| -- <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| -- license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| -- This file may not be copied, modified, or distributed except according to | |
| -- those terms. | |
| import Lean.Elab.Import | |
| import Lean.Replay | |
| import Lean.Compiler.ImplementedByAttr | |
| import Lean.Compiler.ExternAttr | |
| import Lean.Compiler.CSimpAttr | |
| import Lean.Compiler.InitAttr | |
| import Lean.Compiler.ExportAttr | |
| import Lean.Compiler.LCNF.Main | |
| import Lean.Compiler.LCNF.Passes | |
| import Lean.Compiler.LCNF.Simp.ConstantFold | |
| import Lean.Meta.Match.MatcherInfo | |
| import Lean.Meta.Match.MatchEqs | |
| import Lean.Meta.Constructions.SparseCasesOn | |
| /-! | |
| # Compiled `.olean` Kernel-Environment Audit (`olean_audit.lean`) | |
| Inspects compiled target `.olean` artifacts at `trustLevel := 0` with | |
| `plugins := #[]` and `loadExts := false` (so serialized module initializers and | |
| extension callbacks never execute in the inspector process), and parses raw | |
| `.lean` module headers via `Lean.Parser.parseHeader` for `"headers"` mode. | |
| Mirrors Anneal's own `TrustedBoundary` policy (`isForbiddenPureNamespace` | |
| with `banLeanRoot := true`, `forbiddenPureIdentifiers`, `Internal.UV`, | |
| `isForbiddenSpecTransitiveConst` transitively from `Spec.*`, `isPanicSpecConst` | |
| on audited `Spec.*` declarations, `isAllowedRepoLeanHelper`, `optParam` and | |
| authenticated `(autoParam dom tac)` in `theory/`, `Lean.aliasExtension` audit, | |
| paired `*._unsafe_rec` admission, `reservedKernelRoots`, transitive | |
| `declarationEdges` checks, sysroot-first search path, and compiler-generated | |
| realized-theorem / matcher-splitter checks). | |
| -/ | |
| open Lean | |
| namespace OleanAudit | |
| private def forbiddenSysRoots : List Name := | |
| [`Lean, `Lake, `IO, `BaseIO, `EIO, `EST, `ST, `Task, `System, | |
| `LeanIR, `LeanExport, `LakeMain, `LeanChecker, `Leanc] | |
| private def forbiddenEffectRoots : List Name := | |
| [`IO, `BaseIO, `EIO, `EST, `ST, `Task] | |
| private def forbiddenPureIdentifiers : List Name := | |
| [`dbgTrace, `dbgTraceVal, `dbgTraceIfShared, | |
| `dbgStackTrace, `dbgStackTraceIf, `dbgSleep, | |
| `lean_dbg_trace, `lean_dbg_trace_if_shared, | |
| `lean_dbg_stack_trace, `lean_dbg_sleep, | |
| `withPtrAddr, `withPtrEq, `withPtrEqDecEq, | |
| `ptrAddrUnsafe, `withPtrAddrUnsafe, `withPtrEqUnsafe, | |
| `ptrEq, `ptrEqList, `isExclusiveUnsafe, | |
| `lean_ptr_addr, `lean_is_exclusive_obj, | |
| `loadDynlib, `loadPlugin, | |
| `lean_load_dynlib, `lean_load_plugin, | |
| `lean_dynlib_load, `lean_dynlib_get, `lean_dynlib_symbol_run_as_init, | |
| `includeStr] | |
| private def forbiddenSysUvPrefixes : List Name := | |
| [`Init.System, `Std.Internal.UV, `Internal.UV, `Std.Async, `Std.Http, | |
| `Std.Sync, | |
| `Lean.LoadDynlib, `Lean.loadDynlib, `Lean.loadPlugin, `Lean.Dynlib, `Dynlib, | |
| `Lean.Syntax, `Lean.TSyntax, `Lean.TSyntaxArray, `Lean.SourceInfo, | |
| `Lean.SyntaxNodeKind, `Lean.mkAtom, `Lean.mkIdent, `Lean.mkNode, | |
| `Lean.mkCIdent, `Lean.mkCIdentFrom, `Lean.mkNullNode, | |
| `Lean.Name, `Lean.NameMap, `Lean.NameSet, | |
| `Lean.Macro, `Lean.Elab, `Lean.Meta, `Lean.Core, `Lean.Parser, | |
| `Lean.Environment, `Lean.Compiler, `Lean.Internal, | |
| `Lean.ConstantInfo, `Lean.Expr, `Lean.Level, `Lean.Exception, `Lean.Eval, | |
| `Lean.MonadEnv, `Lean.EnvExtension, `Lean.SimplePersistentEnvExtension, | |
| `Lean.PersistentEnvExtension, `Lean.ScopedEnvExtension, | |
| `Lean.AttributeImpl, `Lean.registerBuiltinAttribute, | |
| `Lean.getGithash, `Lean.version] | |
| private def allowedSystemPlatformDecls : List Name := | |
| [`System.Platform.numBits, `System.Platform.getNumBits, | |
| `System.Platform.numBits_eq] | |
| private def forbiddenConsts : List Name := | |
| [`sorryAx, `Lean.ofReduceBool, `Lean.ofReduceNat, `Lean.trustCompiler, | |
| `Lean.reduceBool, `Lean.reduceNat] | |
| private def forbiddenPanicIdentifiers : List Name := | |
| [`panic, `panicCore, `panicWithPos, `panicWithPosWithDecl, | |
| `outOfBounds, `mkPanicMessage, `mkPanicMessageWithDecl, | |
| `String.Pos.sliceOrPanic, `String.Slice.Pos.sliceOrPanic] | |
| private def specPanicBaseIdentifiers : List Name := | |
| [`panic, `panicCore, `panicWithPos, `panicWithPosWithDecl, | |
| `outOfBounds, `String.Pos.sliceOrPanic, `String.Slice.Pos.sliceOrPanic] | |
| private def reservedRoots : List Name := | |
| [`Trusted, `Captured, `Expected, `Spec, `Specs, `Proof, `Anneal, | |
| `IncorrectnessCheck, `IncorrectnessExpected, `TrustedBoundary, | |
| `SpecPreflight, `Nat, `String, `Char, `Bool, `Int, `Int8, `Int16, `Int32, | |
| `Int64, `ISize, `UInt8, `UInt16, `UInt32, `UInt64, `USize, `BitVec, `Float, | |
| `Float32, `ByteArray, `Subarray, `Array, `List, `Option, `Sum, `Prod, `Fin, | |
| `Subtype, `Eq, `HEq, `Quot, `Classical, `Lean, `Init, `Std, `Lake, | |
| `LeanExport, `LeanIR, `LakeMain, `LeanChecker, `Leanc, | |
| `System, `IO, `Task, `Thunk, `Unit, `PUnit, `Empty, `PEmpty, `True, `False, | |
| `And, `Or, `Not, `Iff, `Exists, `Sigma, `PSigma, `Decidable, `Nonempty, | |
| `Ordering, `Rat, `Except, `EStateM, `StateM] | |
| private def sysrootRoots : List Name := | |
| [`Init, `Std, `Lean, `Lake] | |
| private def isSysrootModName (m : Name) : Bool := | |
| sysrootRoots.contains m.getRoot | |
| private def isTrustedModName (m : Name) : Bool := | |
| m == `Trusted || (`Trusted).isPrefixOf m | |
| private def isSpecModName (m : Name) : Bool := | |
| m == `Spec || (`Spec).isPrefixOf m | |
| private def isAnnealModName (m : Name) : Bool := | |
| m == `Anneal || (`Anneal).isPrefixOf m | |
| private def isBaseTrustedMod (m : Name) : Bool := | |
| isSysrootModName m || isTrustedModName m | |
| private def kernelAcceleratedNames : List Name := | |
| [`Nat.zero, `Nat.succ, `Nat.add, `Nat.sub, `Nat.mul, `Nat.pow, `Nat.gcd, | |
| `Nat.mod, `Nat.div, `Nat.beq, `Nat.ble, `Nat.land, `Nat.lor, `Nat.xor, | |
| `Nat.shiftLeft, `Nat.shiftRight, `String.ofList] | |
| private partial def stripLeadingRootPrefix (n : Name) : Name := | |
| if n == rootNamespace then .anonymous | |
| else if rootNamespace.isPrefixOf n then | |
| stripLeadingRootPrefix (n.replacePrefix rootNamespace .anonymous) | |
| else n | |
| private def stripOnePrivatePrefix (n : Name) : Name := | |
| let rec go : Name → Option Name | |
| | .anonymous => none | |
| | .num p idx => | |
| match go p with | |
| | some rest => some (.num rest idx) | |
| | none => | |
| if p.getRoot == privateHeader then some .anonymous else none | |
| | .str p seg => | |
| match go p with | |
| | some rest => some (.str rest seg) | |
| | none => none | |
| (go n).getD n | |
| private partial def stripRootAndPrivatePrefixes (n : Name) : Name := | |
| let s := stripLeadingRootPrefix n | |
| let p := stripOnePrivatePrefix (privateToUserName s) | |
| if p == s then s | |
| else stripRootAndPrivatePrefixes p | |
| private def hasMalformedRootOrPrivate (u : Name) : Bool := | |
| u.isAnonymous || isPrivateName u || u.getRoot == privateHeader || | |
| u.components.any (· == rootNamespace) | |
| private def hasCompoundName : Name → Bool | |
| | .str .anonymous _ | .num .anonymous _ | .anonymous => false | |
| | _ => true | |
| private def isForbiddenImport (m : Name) : Bool := | |
| let r := m.getRoot | |
| forbiddenSysRoots.contains r || | |
| m == `Std || m == `Std.Internal || | |
| [`Init.System, `Init.Meta, `Std.Internal.UV, `Internal.UV, | |
| `Std.Async, `Std.Http, `Std.Sync].any fun pre => m == pre || pre.isPrefixOf m | |
| private def isAllowedImportForRole (role : String) (impMod : Name) : Bool := | |
| if isForbiddenImport impMod then | |
| false | |
| else if isBaseTrustedMod impMod then | |
| true | |
| else if role == "spec" then | |
| isSpecModName impMod | |
| else if role == "theory" then | |
| isAnnealModName impMod | |
| else | |
| false | |
| private def hasBangComponent (id : Name) : Bool := | |
| id.components.any fun | |
| | .str .anonymous seg => seg.contains '!' | |
| | _ => false | |
| private def hasSliceOrPanicComponent (id : Name) : Bool := | |
| id.components.any fun | |
| | .str .anonymous seg => seg == "sliceOrPanic" | |
| | _ => false | |
| private def isForbiddenRepoPanicRef (n : Name) : Bool := | |
| let u := stripRootAndPrivatePrefixes n | |
| forbiddenPanicIdentifiers.contains u || | |
| hasBangComponent u || hasSliceOrPanicComponent u | |
| private def isPanicSpecConst (n : Name) : Bool := | |
| let u := stripRootAndPrivatePrefixes n | |
| specPanicBaseIdentifiers.contains u || | |
| hasBangComponent u || hasSliceOrPanicComponent u | |
| private def isAutoParamConst (n : Name) : Bool := | |
| stripRootAndPrivatePrefixes n == ``autoParam | |
| private def isLeanSyntaxConst (n : Name) : Bool := | |
| let u := stripRootAndPrivatePrefixes n | |
| u == `Lean.Syntax || (`Lean.Syntax).isPrefixOf u || | |
| u == `Lean.TSyntax || (`Lean.TSyntax).isPrefixOf u | |
| private def isForbiddenPureNamespace (n : Name) | |
| (banLeanRoot : Bool := false) : Bool := | |
| let u := stripLeadingRootPrefix n | |
| let r := u.getRoot | |
| forbiddenEffectRoots.contains r || [`Lake, `System].contains r || | |
| (banLeanRoot && r == `Lean) || | |
| forbiddenSysUvPrefixes.any fun pre => u == pre || pre.isPrefixOf u | |
| private def isAutoDigitsSuffix (s : String) : Bool := | |
| match s.dropPrefix? "_auto_" with | |
| | some rest => | |
| let parts := rest.copy.splitOn "_" | |
| !parts.isEmpty && parts.all fun seg => !seg.isEmpty && seg.all Char.isDigit | |
| | none => false | |
| private def isAutoParamAuxName : Name → Bool | |
| | .str _ "_autoParam" => true | |
| | .str _ seg => isAutoDigitsSuffix seg | |
| | _ => false | |
| private partial def collectExprProjStructs (e : Expr) : NameSet := | |
| let rec go : List Expr → Std.HashSet Expr → NameSet → NameSet | |
| | [], _, acc => acc | |
| | cur :: rest, seen, acc => | |
| if seen.contains cur then go rest seen acc | |
| else | |
| let seen := seen.insert cur | |
| match cur with | |
| | .proj s _ b => go (b :: rest) seen (acc.insert s) | |
| | .app a b | .forallE _ a b _ | .lam _ a b _ => | |
| go (a :: b :: rest) seen acc | |
| | .letE _ t v b _ => go (t :: v :: b :: rest) seen acc | |
| | .mdata _ b => go (b :: rest) seen acc | |
| | _ => go rest seen acc | |
| go [e] {} {} | |
| private def exprAllRefs (e : Expr) : NameSet := | |
| e.getUsedConstantsAsSet ++ collectExprProjStructs e | |
| private def collectExprConsts (exprs : List Expr) : NameSet := | |
| exprs.foldl (init := {}) fun acc e => acc ++ exprAllRefs e | |
| private def isAllowedLeanHelperName (role : String) (u : Name) : Bool := | |
| let sharedExact := | |
| [`Lean.injEq_helper, `Lean.Arrow, `Lean.arrow_congr, | |
| `Lean.arrow_congr_left, `Lean.arrow_congr_right, `Lean.arrow_true, | |
| `Lean.arrow_true_congr, `Lean.true_arrow, `Lean.true_arrow_congr, | |
| `Lean.true_arrow_congr_left, `Lean.true_arrow_congr_right, | |
| `Lean.false_arrow, `Lean.false_arrow_congr, | |
| `Lean.instGetElemRArrayNatTrue].contains u | |
| let sharedPfx := [`Lean.Grind, `Lean.Omega, `Lean.RArray, | |
| `Lean.Data.AC, `Lean.Sym].any fun pre => u == pre || pre.isPrefixOf u | |
| let theoryOnly := role == "theory" && | |
| (u == `Lean.instForInLoopUnitOfMonad || | |
| [`Lean.Loop, `Lean.Order].any fun pre => u == pre || pre.isPrefixOf u) | |
| u.getRoot == `Lean && (sharedExact || sharedPfx || theoryOnly) | |
| private def isAllowedLeanHelper (env : Environment) (role : String) | |
| (n : Name) : Bool := | |
| let u := stripRootAndPrivatePrefixes n | |
| if hasMalformedRootOrPrivate u || !isAllowedLeanHelperName role u || | |
| isAutoParamAuxName n then | |
| false | |
| else | |
| let fromInit := match env.getModuleIdxFor? n with | |
| | some idx => | |
| match env.header.moduleNames[idx.toNat]? with | |
| | some mod => mod.getRoot == `Init | |
| | none => false | |
| | none => false | |
| if !fromInit then false | |
| else | |
| match env.find? n with | |
| | some ci => | |
| !ci.isUnsafe && !(ci matches .opaqueInfo _) && | |
| !(collectExprConsts [ci.type]).any fun c => | |
| let cu := stripRootAndPrivatePrefixes c | |
| hasMalformedRootOrPrivate cu || | |
| forbiddenPureRoot (cu.getRoot) || | |
| (cu.getRoot == `Lean && !isAllowedLeanHelperName role cu) | |
| | none => false | |
| where | |
| forbiddenPureRoot (r : Name) : Bool := | |
| ([`Lake, `IO, `BaseIO, `EIO, `EST, `ST, `Task, `System].contains r) | |
| private def isAllowedTheoryThmProof (env : Environment) (n : Name) : Bool := | |
| n == ``List.get!Internal && | |
| match env.getModuleIdxFor? n with | |
| | some idx => env.header.moduleNames[idx.toNat]? == some `Init.GetElem | |
| | none => false | |
| private def isAllowedSysPlatform (u : Name) : Bool := | |
| allowedSystemPlatformDecls.any fun ok => u == ok || ok.isPrefixOf u | |
| private def isInitMod (env : Environment) (n : Name) : Bool := | |
| match env.getModuleIdxFor? n with | |
| | some idx => | |
| match env.header.moduleNames[idx.toNat]? with | |
| | some mod => mod.getRoot == `Init | |
| | none => false | |
| | none => false | |
| private def isSysrootMod (env : Environment) (n : Name) : Bool := | |
| match env.getModuleIdxFor? n with | |
| | some idx => | |
| match env.header.moduleNames[idx.toNat]? with | |
| | some mod => sysrootRoots.contains mod.getRoot | |
| | none => false | |
| | none => false | |
| private def mkStrArity? : Name → Option Nat | |
| | ``Lean.Name.mkStr1 => some 1 | ``Lean.Name.mkStr2 => some 2 | |
| | ``Lean.Name.mkStr3 => some 3 | ``Lean.Name.mkStr4 => some 4 | |
| | ``Lean.Name.mkStr5 => some 5 | ``Lean.Name.mkStr6 => some 6 | |
| | ``Lean.Name.mkStr7 => some 7 | ``Lean.Name.mkStr8 => some 8 | |
| | _ => none | |
| private def decodePureAutoNat? : Expr → Option Nat | |
| | .lit (.natVal n) => some n | |
| | .app (.app (.app (.const ``OfNat.ofNat [.zero]) (.const ``Nat [])) | |
| (.lit (.natVal n))) | |
| (.app (.const ``instOfNatNat []) (.lit (.natVal m))) => | |
| if n == m then some n else none | |
| | _ => none | |
| private partial def decodePureAutoName? (e : Expr) : Option Name := do | |
| match e with | |
| | .const ``Lean.Name.anonymous [] => return .anonymous | |
| | .app (.app (.const ``Lean.Name.str []) p) (.lit (.strVal s)) => | |
| return .str (← decodePureAutoName? p) s | |
| | .app (.app (.const ``Lean.Name.num []) p) nE => | |
| return .num (← decodePureAutoName? p) (← decodePureAutoNat? nE) | |
| | _ => | |
| let .const fn [] := e.getAppFn | none | |
| let arity ← mkStrArity? fn | |
| let args := e.getAppArgs | |
| guard (args.size == arity) | |
| let mut acc : Name := .anonymous | |
| for a in args do | |
| let .lit (.strVal s) := a | none | |
| acc := .str acc s | |
| return acc | |
| private partial def decodePureStringList? (e : Expr) : | |
| Option (List String) := do | |
| match e with | |
| | .app (.const ``List.nil [.zero]) (.const ``String []) => return [] | |
| | .app (.app (.app (.const ``List.cons [.zero]) (.const ``String [])) | |
| (.lit (.strVal s))) tl => | |
| return s :: (← decodePureStringList? tl) | |
| | _ => none | |
| private partial def decodePurePreresolved? (e : Expr) : | |
| Option (List Syntax.Preresolved) := do | |
| match e with | |
| | .app (.const ``List.nil [.zero]) | |
| (.const ``Lean.Syntax.Preresolved []) => return [] | |
| | .app (.app (.app (.const ``List.cons [.zero]) | |
| (.const ``Lean.Syntax.Preresolved [])) hd) tl => | |
| let item ← match hd with | |
| | .app (.const ``Lean.Syntax.Preresolved.namespace []) nsE => | |
| some (Syntax.Preresolved.namespace (← decodePureAutoName? nsE)) | |
| | .app (.app (.const ``Lean.Syntax.Preresolved.decl []) dE) lsE => | |
| some (Syntax.Preresolved.decl (← decodePureAutoName? dE) | |
| (← decodePureStringList? lsE)) | |
| | _ => none | |
| return item :: (← decodePurePreresolved? tl) | |
| | _ => none | |
| mutual | |
| private partial def decodePureSyntaxArray? (e : Expr) : | |
| Option (Array Syntax) := do | |
| match e with | |
| | .app (.const ``Array.empty [.zero]) (.const ``Lean.Syntax []) => | |
| return #[] | |
| | .app (.app (.app (.const ``Array.push [.zero]) (.const ``Lean.Syntax [])) | |
| arrE) elemE => | |
| return (← decodePureSyntaxArray? arrE).push (← decodePureAutoSyntax? elemE) | |
| | _ => none | |
| private partial def decodePureAutoSyntax? (e : Expr) : Option Syntax := do | |
| match e with | |
| | .app (.const ``Lean.mkAtom []) (.lit (.strVal val)) => | |
| return Lean.mkAtom val | |
| | .app (.app (.app (.app (.const ``Lean.Syntax.ident []) | |
| (.const ``Lean.SourceInfo.none [])) | |
| (.app (.const ``String.toRawSubstring []) (.lit (.strVal raw)))) | |
| valE) prereE => | |
| return .ident .none (String.toRawSubstring raw) | |
| (← decodePureAutoName? valE) (← decodePurePreresolved? prereE) | |
| | .app (.app (.app (.const ``Lean.Syntax.node []) | |
| (.const ``Lean.SourceInfo.none [])) kindE) argsE => | |
| return .node .none (← decodePureAutoName? kindE) | |
| (← decodePureSyntaxArray? argsE) | |
| | _ => none | |
| end | |
| private def allowedAutoSyntaxKinds : NameSet := .ofList [ | |
| `null, ``Parser.Term.anonymousCtor, ``Parser.Term.app, ``Parser.Term.arrow, | |
| ``Parser.Term.basicFun, ``Parser.Term.binderDefault, ``Parser.Term.cdot, | |
| ``Parser.Term.dotIdent, ``Parser.Term.explicit, ``Parser.Term.explicitBinder, | |
| ``Parser.Term.forall, ``Parser.Term.fromTerm, ``Parser.Term.fun, | |
| ``Parser.Term.have, `Lean.Parser.Term.haveDecl, `Lean.Parser.Term.haveId, | |
| `Lean.Parser.Term.haveIdDecl, `Lean.Parser.Term.haveIdLhs, | |
| ``Parser.Term.hole, ``Parser.Term.hygienicLParen, | |
| ``Parser.Term.implicitBinder, ``Parser.Term.instBinder, ``Parser.Term.let, | |
| ``Parser.Term.letConfig, ``Parser.Term.letDecl, ``Parser.Term.letId, | |
| ``Parser.Term.letIdDecl, ``Parser.Term.letPatDecl, ``Parser.Term.match, | |
| ``Parser.Term.matchAlt, ``Parser.Term.matchAlts, | |
| ``Parser.Term.matchAltsWhereDecls, ``Parser.Term.matchDiscr, | |
| ``Parser.Term.namedArgument, ``Parser.Term.nomatch, | |
| ``Parser.Term.optEllipsis, ``Parser.Term.paren, ``Parser.Term.proj, | |
| ``Parser.Term.prop, ``Parser.Term.show, ``Parser.Term.sort, | |
| ``Parser.Term.strictImplicitBinder, ``Parser.Term.structInst, | |
| ``Parser.Term.structInstField, ``Parser.Term.structInstFieldDef, | |
| ``Parser.Term.structInstFieldEqns, ``Parser.Term.structInstFields, | |
| ``Parser.Term.structInstLVal, ``Parser.Term.subst, | |
| ``Parser.Term.syntheticHole, ``Parser.Term.tuple, ``Parser.Term.type, | |
| ``Parser.Term.typeAscription, ``Parser.Term.typeSpec, | |
| ``Parser.Term.attrInstance, ``Parser.Term.attrKind, | |
| ``Parser.Term.attributes, ``Parser.Attr.simple, ``Parser.Attr.instance, | |
| `Lean.Parser.Attr.simp, ``Lean.binderIdent, ``Lean.explicitBinders, | |
| ``Lean.bracketedExplicitBinders, ``Lean.unbracketedExplicitBinders, | |
| `fieldIdx, `group, `hygieneInfo, `num, `str, `char, `scientific, `term!_, | |
| `termIfThenElse, `termDepIfThenElse, `«term[_]», `«term_&&_», `«term_||_», | |
| `«term_+_», `«term_-_», `«term_*_», `«term_::_», `«term_++_», `«term_<_», | |
| `«term_≤_», `«term_>_», `«term_≥_», `«term_==_», `«term_!=_», `«term_=_», | |
| `«term_≠_», `«term__[_]_?», `«term_×_», `«term_↔_», `«term_∈_», `«term_∧_», | |
| `«term_∨_», `«term¬_», `«term∃_,_», `«term‹_›», `Lean.cdot, `Lean.cdotTk, | |
| ``Parser.Term.byTactic, ``Parser.Term.binderTactic, | |
| `Lean.Parser.Tactic.apply, `Lean.Parser.Tactic.cases, | |
| `Lean.Parser.Tactic.change, `Lean.Parser.Tactic.constructor, | |
| `Lean.Parser.Tactic.decide, `Lean.Parser.Tactic.dsimp, | |
| `Lean.Parser.Tactic.elimTarget, `Lean.Parser.Tactic.exact, | |
| `Lean.Parser.Tactic.first, `Lean.Parser.Tactic.induction, | |
| `Lean.Parser.Tactic.inductionAlt, `Lean.Parser.Tactic.inductionAltLHS, | |
| `Lean.Parser.Tactic.inductionAlts, `Lean.Parser.Tactic.injection, | |
| `Lean.Parser.Tactic.intro, `Lean.Parser.Tactic.left, | |
| `Lean.Parser.Tactic.location, `Lean.Parser.Tactic.locationHyp, | |
| `Lean.Parser.Tactic.optConfig, `Lean.Parser.Tactic.paren, | |
| `Lean.Parser.Tactic.refine, `Lean.Parser.Tactic.revert, | |
| `Lean.Parser.Tactic.right, `Lean.Parser.Tactic.rwRule, | |
| `Lean.Parser.Tactic.rwRuleSeq, `Lean.Parser.Tactic.rwSeq, | |
| `Lean.Parser.Tactic.simp, `Lean.Parser.Tactic.simpLemma, | |
| `Lean.Parser.Tactic.subst, `Lean.Parser.Tactic.tacticHave__, | |
| `Lean.Parser.Tactic.tacticLet__, `Lean.Parser.Tactic.«tacticNomatch_,,», | |
| `Lean.Parser.Tactic.tacticRepeat_, `Lean.Parser.Tactic.tacticRfl, | |
| `Lean.Parser.Tactic.tacticSeq, `Lean.Parser.Tactic.tacticSeq1Indented, | |
| `Lean.Parser.Tactic.«tactic_<;>_», `Lean.Parser.Tactic.unfold, | |
| `tacticFunext___] | |
| private def shallowPrivateModule? (n : Name) : Option Name := | |
| let rec go : Name → Option Name | |
| | .anonymous => none | |
| | .num p 0 => | |
| match go p with | |
| | some m => some m | |
| | none => | |
| if p.getRoot == privateHeader && p != privateHeader then | |
| some (p.replacePrefix privateHeader .anonymous) | |
| else none | |
| | .num p _ => go p | |
| | .str p _ => go p | |
| go n | |
| private def isAllowedFoundationAuto (env : Environment) (n : Name) : Bool := | |
| isAutoParamAuxName n && | |
| match env.getModuleIdxFor? n with | |
| | some idx => | |
| match env.header.moduleNames[idx.toNat]? with | |
| | some mod => mod.getRoot == `Init && !isForbiddenImport mod | |
| | none => false | |
| | none => false | |
| private partial def autoSyntaxHasBadRefs : Syntax → Bool | |
| | .ident _ _ val preresolved => | |
| let valBad := | |
| let u := stripRootAndPrivatePrefixes val | |
| hasMalformedRootOrPrivate u || forbiddenPureIdentifiers.contains u || | |
| isForbiddenRepoPanicRef u || u == `autoParam || u == `optParam || | |
| isForbiddenPureNamespace u (banLeanRoot := true) | |
| let prereBad := preresolved.any fun pr => | |
| let targets := match pr with | .namespace ns => [ns] | .decl d _ => [d] | |
| targets.any fun cand => | |
| let c0 := stripLeadingRootPrefix cand | |
| let u := stripRootAndPrivatePrefixes c0 | |
| let privBad := | |
| if isPrivateName c0 then | |
| match shallowPrivateModule? c0, privatePrefix? c0 with | |
| | some mod, some (.num _ 0) => | |
| let inner := stripLeadingRootPrefix (privateToUserName c0) | |
| isPrivateName inner || inner.getRoot == privateHeader || | |
| isForbiddenImport mod || | |
| isForbiddenPureNamespace mod (banLeanRoot := true) | |
| | _, _ => true | |
| else c0.getRoot == privateHeader | |
| c0.isAnonymous || c0.hasMacroScopes || | |
| c0.components.any (· == rootNamespace) || privBad || | |
| hasMalformedRootOrPrivate u || | |
| forbiddenPureIdentifiers.contains u || | |
| isForbiddenRepoPanicRef u || u == `autoParam || u == `optParam || | |
| isForbiddenPureNamespace u (banLeanRoot := true) | |
| valBad || prereBad | |
| | .node _ kind args => | |
| !allowedAutoSyntaxKinds.contains kind || args.any autoSyntaxHasBadRefs | |
| | .atom _ _ => false | |
| | .missing => true | |
| private def collectValidatedAutos (env : Environment) (role : String) : | |
| NameSet := Id.run do | |
| if role != "theory" then return {} | |
| let mut out : NameSet := {} | |
| for m in env.header.moduleNames, data in env.header.moduleData do | |
| if sysrootRoots.contains m.getRoot then continue | |
| for ci in data.constants do | |
| if isAutoParamAuxName ci.name && (ci matches .defnInfo _) && | |
| !ci.isUnsafe && !ci.isPartial && ci.levelParams.isEmpty && | |
| ci.type == .const ``Lean.Syntax [] then | |
| if let some val := ci.value? true then | |
| if let some stx := decodePureAutoSyntax? val then | |
| if !autoSyntaxHasBadRefs stx then | |
| out := out.insert ci.name | |
| return out | |
| private partial def collectAutoIgnored (env : Environment) (role : String) | |
| (validatedAutos : NameSet) (e : Expr) : Bool × NameSet := | |
| if role != "theory" then (true, {}) | |
| else | |
| let rec go : List Expr → Std.HashSet Expr → NameSet → Bool × NameSet | |
| | [], _, ignored => (true, ignored) | |
| | cur :: rest, seen, ignored => | |
| if seen.contains cur then go rest seen ignored | |
| else | |
| let seen := seen.insert cur | |
| match cur with | |
| | .app (.app (.const ``autoParam [_]) dom) (.const tac []) => | |
| let okTac := validatedAutos.contains tac || | |
| isAllowedFoundationAuto env tac | |
| if !okTac then (false, ignored) | |
| else | |
| let ignored := (ignored.insert ``autoParam).insert tac | |
| go (dom :: rest) seen ignored | |
| | .const n _ => | |
| if isAutoParamConst n || validatedAutos.contains n || | |
| isAllowedFoundationAuto env n then | |
| (false, ignored) | |
| else go rest seen ignored | |
| | .app a b | .forallE _ a b _ | .lam _ a b _ => | |
| go (a :: b :: rest) seen ignored | |
| | .letE _ t v b _ => go (t :: v :: b :: rest) seen ignored | |
| | .mdata _ b | .proj _ _ b => go (b :: rest) seen ignored | |
| | _ => go rest seen ignored | |
| go [e] {} {} | |
| private def isForbiddenTransitiveSysConst (role : String) (n : Name) : Bool := | |
| let u := stripRootAndPrivatePrefixes n | |
| if hasMalformedRootOrPrivate u then true | |
| else | |
| let r := u.getRoot | |
| let specLoopBad := | |
| role == "spec" && | |
| (u == `Lean.Loop || (`Lean.Loop).isPrefixOf u || | |
| u == `repeatM || (`repeatM).isPrefixOf u) | |
| if forbiddenEffectRoots.contains r || specLoopBad then true | |
| else if [`Lean.Macro, `Lean.Elab, `Lean.Core, `Lean.Meta, | |
| `Lean.Environment, `Lean.Compiler, `Lean.Internal, | |
| `Lean.LoadDynlib, `Lean.loadDynlib, `Lean.loadPlugin, `Lean.Dynlib, | |
| `Lean.getGithash, `Lean.version, | |
| `Init.System, `Std.Internal.UV, `Internal.UV, `Std.Async, | |
| `Std.Http, `Std.Sync, `Dynlib].any | |
| (fun pre => u == pre || pre.isPrefixOf u) then true | |
| else if r == `System then !isAllowedSysPlatform u | |
| else forbiddenPureIdentifiers.contains u | |
| private def isForbiddenEnvRef (env : Environment) (role : String) | |
| (n : Name) (inThmProof : Bool := false) | |
| (directInModule : Bool := true) : Bool := | |
| if isAllowedLeanHelper env role n || | |
| (role == "theory" && inThmProof && isAllowedTheoryThmProof env n) then | |
| false | |
| else | |
| let u := stripRootAndPrivatePrefixes n | |
| if hasMalformedRootOrPrivate u || forbiddenPureIdentifiers.contains u then | |
| true | |
| else if role == "spec" then | |
| let sysBad := u.getRoot == `System && !isAllowedSysPlatform u | |
| let directBad := | |
| directInModule && | |
| (isLeanSyntaxConst u || isPanicSpecConst u || isAutoParamConst u || | |
| (isForbiddenPureNamespace u (banLeanRoot := false) && | |
| !isAllowedSysPlatform u)) | |
| directBad || isForbiddenTransitiveSysConst "spec" u || sysBad | |
| else | |
| let isSysModule := isSysrootMod env n | |
| let panicBad := | |
| (!isSysModule || directInModule) && isForbiddenRepoPanicRef u | |
| let sysBad := u.getRoot == `System && !isAllowedSysPlatform u | |
| let metaBad := | |
| if directInModule || !isSysModule then | |
| u == `autoParam || u == `Init.Meta || (`Init.Meta).isPrefixOf u || | |
| (isForbiddenPureNamespace u (banLeanRoot := true) && !sysBad) | |
| else | |
| isForbiddenTransitiveSysConst "theory" u | |
| panicBad || sysBad || metaBad | |
| private def declarationEdges (ci : ConstantInfo) : NameSet := | |
| let typeEdges := exprAllRefs ci.type | |
| let valEdges := (ci.value? true).map exprAllRefs |>.getD {} | |
| let base := typeEdges ++ valEdges ++ .ofList ci.all | |
| match ci with | |
| | .inductInfo v => base ++ .ofList v.ctors | |
| | .ctorInfo v => base.insert v.induct | |
| | .recInfo v => | |
| v.rules.foldl (init := base ++ .ofList v.all) fun acc rule => | |
| (acc.insert rule.ctor) ++ exprAllRefs rule.rhs | |
| | _ => base | |
| private def isPairedUnsafeRec (modConsts : Std.HashMap Name ConstantInfo) | |
| (ci : ConstantInfo) : Bool := | |
| if !ci.isPartial || ci.isUnsafe || !(ci matches .defnInfo _) then false | |
| else | |
| match Compiler.isUnsafeRecName? ci.name with | |
| | some parent => | |
| match modConsts.get? parent with | |
| | some (parentCi@(.defnInfo _)) => | |
| !parentCi.isUnsafe && !parentCi.isPartial && | |
| ci.type == parentCi.type && ci.levelParams == parentCi.levelParams | |
| | _ => false | |
| | none => false | |
| private def collectAllMatchers (env : Environment) : NameSet := Id.run do | |
| let mut matchers : NameSet := {} | |
| for modIdx in Array.range env.header.moduleData.size do | |
| for entry in | |
| Lean.Meta.Match.Extension.extension.getModuleEntries env modIdx do | |
| matchers := matchers.insert entry.name | |
| return matchers | |
| private partial def isImportedHelperRoot (env : Environment) (modIdx : Nat) | |
| (allMatchers : NameSet) (n userN : Name) : Bool := | |
| let importedCompound := | |
| hasCompoundName userN && | |
| match env.getModuleIdxFor? n, env.getModuleIdxFor? userN with | |
| | some j, _ => j != modIdx | |
| | _, some j => j != modIdx | |
| | none, none => false | |
| if importedCompound then true | |
| else | |
| match n, userN with | |
| | .str rawParent _, .str userParent "splitter" => | |
| (allMatchers.contains rawParent || allMatchers.contains userParent) && | |
| isImportedHelperRoot env modIdx allMatchers rawParent userParent | |
| | .str rawParent _, .str userParent _ => | |
| let isKnownSparse := | |
| (Lean.Meta.getSparseCasesOnInfoCore env n).isSome || | |
| (Lean.Meta.getSparseCasesOnInfoCore env userN).isSome | |
| let isKnownMatcher := allMatchers.contains n || allMatchers.contains userN | |
| if isKnownSparse || isKnownMatcher then | |
| isImportedHelperRoot env modIdx allMatchers rawParent userParent | |
| else false | |
| | _, _ => false | |
| private def isRealizedOrCompilerHelper (env : Environment) (modIdx : Nat) | |
| (allMatchers : NameSet) (ci : ConstantInfo) : Bool := | |
| let n := ci.name | |
| let userN := privateToUserName n | |
| let hasParent := isImportedHelperRoot env modIdx allMatchers | |
| match ci, n, userN with | |
| | .thmInfo _, .str rawParent _, .str userParent suffix => | |
| ((Lean.isReservedName env n || Lean.isReservedName env userN) && | |
| hasParent rawParent userParent) || | |
| ((allMatchers.contains rawParent || allMatchers.contains userParent) && | |
| (suffix == "splitter" || Lean.Meta.isEqnReservedNameSuffix suffix || | |
| Lean.Meta.Match.isCongrEqnReservedNameSuffix suffix) && | |
| hasParent rawParent userParent) | |
| | .defnInfo _, .str rawParent _, .str userParent suffix => | |
| isPrivateName n && | |
| if suffix == "splitter" then | |
| (allMatchers.contains rawParent || allMatchers.contains userParent) && | |
| hasParent rawParent userParent | |
| else if (Lean.Meta.getSparseCasesOnInfoCore env n).isSome || | |
| (Lean.Meta.getSparseCasesOnInfoCore env userN).isSome then | |
| hasParent rawParent userParent | |
| else false | |
| | _, _, _ => false | |
| private def isApprovedAxiom (env : Environment) (n : Name) : Bool := | |
| let orig := match env.getModuleIdxFor? n with | |
| | some idx => env.header.moduleNames[idx.toNat]? | |
| | none => none | |
| (n == ``propext && orig == some `Init.Core) || | |
| ((n == ``Classical.choice || n == ``Quot.sound) && | |
| orig == some `Init.Prelude) | |
| private def isInModSet (env : Environment) (modSet : NameSet) (n : Name) : | |
| Bool := | |
| match env.getModuleIdxFor? n with | |
| | some idx => | |
| match env.header.moduleNames[idx.toNat]? with | |
| | some mod => modSet.contains mod | |
| | none => false | |
| | none => false | |
| private def checkExprAndEdges (env : Environment) (role : String) | |
| (validatedAutos : NameSet) (n : Name) (ci : ConstantInfo) | |
| (directMod : Bool) : Array String := Id.run do | |
| let mut vs : Array String := #[] | |
| let mut ignored : NameSet := {} | |
| if role == "theory" && !validatedAutos.contains n then | |
| let (okT, igT) := collectAutoIgnored env role validatedAutos ci.type | |
| let (okV, igV) := match ci.value? true with | |
| | some val => collectAutoIgnored env role validatedAutos val | |
| | none => (true, {}) | |
| if !okT || !okV then | |
| vs := vs.push s!"malformed_auto_param:{n}" | |
| ignored := igT ++ igV | |
| let allEdges := declarationEdges ci | |
| let valRefs := (ci.value? true).map exprAllRefs |>.getD {} | |
| let typeRefs := exprAllRefs ci.type | |
| let isThm := ci matches .thmInfo _ | |
| for dep in allEdges do | |
| if ignored.contains dep then continue | |
| let inValOnly := isThm && valRefs.contains dep && !typeRefs.contains dep | |
| if isForbiddenEnvRef env role dep inValOnly directMod then | |
| vs := vs.push s!"transitive_forbidden_ref:{n}:{dep}" | |
| return vs | |
| private def checkTransitiveClosure (env : Environment) (role : String) | |
| (auditedSet : NameSet) (validatedAutos : NameSet) | |
| (seeds : Array Name) : Array String := Id.run do | |
| let mut vs : Array String := #[] | |
| let mut visited : NameSet := {} | |
| let mut queue : List Name := seeds.toList | |
| while !queue.isEmpty do | |
| let cur :: rest := queue | break | |
| queue := rest | |
| if visited.contains cur then continue | |
| visited := visited.insert cur | |
| let some ci := env.find? cur | continue | |
| let fromSys := isSysrootMod env cur | |
| if ci.isAxiom && !isApprovedAxiom env cur then | |
| vs := vs.push s!"transitive_custom_axiom:{cur}" | |
| if !fromSys then | |
| if ci.isUnsafe then | |
| vs := vs.push s!"transitive_unsafe_decl:{cur}" | |
| if ci.isPartial then | |
| vs := vs.push s!"transitive_partial_decl:{cur}" | |
| let inAudited := isInModSet env auditedSet cur | |
| let directMod := | |
| if role == "spec" then inAudited | |
| else !fromSys | |
| let skipSysInternals := fromSys && isInitMod env cur | |
| if !skipSysInternals && | |
| !(role == "theory" && validatedAutos.contains cur) then | |
| if isForbiddenEnvRef env role cur false directMod then | |
| vs := vs.push s!"transitive_forbidden_ref:{cur}" | |
| vs := vs ++ checkExprAndEdges env role validatedAutos cur ci directMod | |
| for dep in declarationEdges ci do | |
| let depU := stripRootAndPrivatePrefixes dep | |
| if forbiddenConsts.contains depU then | |
| vs := vs.push s!"transitive_forbidden_const:{cur}:{dep}" | |
| if !visited.contains dep then | |
| queue := dep :: queue | |
| return vs | |
| private def constKind : ConstantInfo → Nat | |
| | .axiomInfo _ => 0 | .defnInfo _ => 1 | .thmInfo _ => 2 | |
| | .opaqueInfo _ => 3 | .quotInfo _ => 4 | .inductInfo _ => 5 | |
| | .ctorInfo _ => 6 | .recInfo _ => 7 | |
| private def sameConstantShape (a b : ConstantInfo) : Bool := | |
| let kindAndFlags := | |
| a.name == b.name && constKind a == constKind b && | |
| a.isUnsafe == b.isUnsafe && a.isPartial == b.isPartial && | |
| a.levelParams == b.levelParams && a.type == b.type && | |
| a.value? true == b.value? true && a.all == b.all | |
| if !kindAndFlags then | |
| false | |
| else | |
| match a, b with | |
| | .defnInfo da, .defnInfo db => | |
| da.hints == db.hints | |
| | .inductInfo ia, .inductInfo ib => | |
| ia.numParams == ib.numParams && ia.numIndices == ib.numIndices && | |
| ia.ctors == ib.ctors && ia.numNested == ib.numNested && | |
| ia.isRec == ib.isRec && ia.isReflexive == ib.isReflexive | |
| | .ctorInfo ca, .ctorInfo cb => | |
| ca.induct == cb.induct && ca.cidx == cb.cidx && | |
| ca.numParams == cb.numParams && ca.numFields == cb.numFields | |
| | .recInfo ra, .recInfo rb => | |
| ra.all == rb.all && | |
| ra.numParams == rb.numParams && ra.numIndices == rb.numIndices && | |
| ra.numMotives == rb.numMotives && ra.numMinors == rb.numMinors && | |
| ra.k == rb.k && | |
| ra.rules.map (fun r => (r.ctor, r.nfields, r.rhs)) == | |
| rb.rules.map (fun r => (r.ctor, r.nfields, r.rhs)) | |
| | .quotInfo qa, .quotInfo qb => | |
| match qa.kind, qb.kind with | |
| | .type, .type | .ctor, .ctor | .lift, .lift | .ind, .ind => true | |
| | _, _ => false | |
| | _, _ => true | |
| private def isValidCompanionConstant (isMod : Bool) | |
| (privCi compCi : ConstantInfo) : Bool := | |
| !privCi.isUnsafe && ( | |
| (!compCi.isUnsafe && sameConstantShape privCi compCi) || | |
| (isMod && match privCi, compCi with | |
| | .thmInfo _, .axiomInfo ax | |
| | .defnInfo _, .axiomInfo ax | |
| | .opaqueInfo _, .axiomInfo ax => | |
| ax.isUnsafe == privCi.isPartial && | |
| compCi.name == privCi.name && | |
| compCi.levelParams == privCi.levelParams && | |
| compCi.type == privCi.type | |
| | _, _ => false)) | |
| private def partExtEntries {α β σ : Type} [Inhabited σ] | |
| (ext : PersistentEnvExtension α β σ) (data : ModuleData) : Array α := | |
| data.entries.foldl (init := #[]) fun acc (extName, entries) => | |
| if extName == ext.name then | |
| acc ++ unsafe (unsafeCast entries : Array α) | |
| else | |
| acc | |
| private def readModulePartsChecked (m : Name) : | |
| IO (Array (ModuleData × CompactedRegion) × | |
| Array (ModuleData × CompactedRegion) × Array String) := do | |
| let mFile ← findOLean m | |
| unless (← mFile.pathExists) do | |
| return (#[], #[], #[s!"missing_olean:{m}"]) | |
| let main ← unsafe CompactedRegion.read (α := ModuleData) mFile #[] | |
| let sFile := OLeanLevel.server.adjustFileName mFile | |
| let pFile := OLeanLevel.private.adjustFileName mFile | |
| let mut vs : Array String := #[] | |
| let olean ← if !main.1.isModule then | |
| if (← sFile.pathExists) || (← pFile.pathExists) then | |
| vs := vs.push s!"unexpected_companion_olean:{m}" | |
| pure #[main] | |
| else | |
| -- Defense in depth behind `importModules` (which fails on missing parts). | |
| if !(← sFile.pathExists) || !(← pFile.pathExists) then | |
| vs := vs.push s!"missing_companion_olean:{m}" | |
| pure #[main] | |
| else | |
| let server ← unsafe CompactedRegion.read (α := ModuleData) sFile #[main.2] | |
| let priv ← unsafe CompactedRegion.read (α := ModuleData) pFile | |
| #[main.2, server.2] | |
| pure #[main, server, priv] | |
| let irSigFile := mFile.withExtension "ir.sig" | |
| let irFile := mFile.withExtension "ir" | |
| let irSigExists ← irSigFile.pathExists | |
| let irExists ← irFile.pathExists | |
| let ir ← if irSigExists && irExists then | |
| let irSig ← unsafe CompactedRegion.read (α := ModuleData) irSigFile #[] | |
| let irData ← unsafe CompactedRegion.read (α := ModuleData) irFile | |
| #[irSig.2] | |
| pure #[irSig, irData] | |
| else | |
| if irExists && !irSigExists then | |
| vs := vs.push s!"missing_companion_ir_sig:{m}" | |
| else if irSigExists && !irExists then | |
| -- Defense in depth behind `importModules` (which throws before this). | |
| vs := vs.push s!"missing_companion_ir:{m}" | |
| pure #[] | |
| return (olean, ir, vs) | |
| private def checkModule (env : Environment) (allMatchers : NameSet) | |
| (auditedSet : NameSet) (validatedAutos : NameSet) | |
| (role : String) (m : Name) | |
| (oleanParts irParts : Array (ModuleData × CompactedRegion)) | |
| (partErrs : Array String) : Array String := Id.run do | |
| let mut vs : Array String := partErrs | |
| if (role == "spec" && !isSpecModName m) || | |
| (role == "theory" && !isAnnealModName m) then | |
| vs := vs.push s!"unexpected_role_module:{m}" | |
| let some idx := env.header.moduleNames.idxOf? m | |
| | return vs.push s!"missing_module:{m}" | |
| let some data := env.header.moduleData[idx]? | |
| | return vs.push s!"missing_module_data:{m}" | |
| unless data.constNames == data.constants.map ConstantInfo.name do | |
| vs := vs.push s!"corrupt_const_names:{m}" | |
| let hasNonMetaInit := data.imports.any fun i => i.module == `Init && !i.isMeta | |
| for imp in data.imports do | |
| let importAllOk := role == "theory" && data.isModule && | |
| imp.module == `Init.Data.Nat.Bitwise.Basic | |
| if !isAllowedImportForRole role imp.module || | |
| (imp.importAll && !importAllOk) || | |
| (imp.isMeta && !(imp.module == `Init && hasNonMetaInit)) then | |
| vs := vs.push s!"forbidden_import:{m}:{imp.module}" | |
| let mut modConsts : Std.HashMap Name ConstantInfo := {} | |
| for ci in data.constants do | |
| modConsts := modConsts.insert ci.name ci | |
| for (partData, _) in oleanParts do | |
| unless partData.isModule == data.isModule do | |
| vs := vs.push s!"mismatched_companion_isModule:{m}" | |
| unless partData.imports == data.imports do | |
| vs := vs.push s!"mismatched_companion_imports:{m}" | |
| unless partData.constNames == partData.constants.map ConstantInfo.name do | |
| vs := vs.push s!"corrupt_const_names:{m}" | |
| let mut partSeen : NameSet := {} | |
| for ci in partData.constants do | |
| if partSeen.contains ci.name then | |
| vs := vs.push s!"duplicate_companion_const:{m}:{ci.name}" | |
| partSeen := partSeen.insert ci.name | |
| match modConsts.get? ci.name with | |
| | some privCi => | |
| unless isValidCompanionConstant data.isModule privCi ci do | |
| vs := vs.push s!"companion_const_mismatch:{m}:{ci.name}" | |
| | none => | |
| vs := vs.push s!"companion_const_missing:{m}:{ci.name}" | |
| let allParts := oleanParts ++ irParts | |
| for (partData, _) in allParts do | |
| for (d, _) in partExtEntries Compiler.implementedByAttr.ext partData do | |
| vs := vs.push s!"codegen_implemented_by:{d}" | |
| for (d, _) in partExtEntries externAttr.ext partData do | |
| vs := vs.push s!"codegen_extern:{d}" | |
| for e in partExtEntries Compiler.CSimp.ext.ext partData do | |
| let d := match e with | .global g | .scoped _ g => g.fromDeclName | |
| vs := vs.push s!"codegen_csimp:{d}" | |
| for (d, _) in partExtEntries exportAttr.ext partData do | |
| vs := vs.push s!"codegen_export:{d}" | |
| for (d, _) in partExtEntries regularInitAttr.ext partData do | |
| vs := vs.push s!"codegen_init:{d}" | |
| for (d, _) in partExtEntries builtinInitAttr.ext partData do | |
| vs := vs.push s!"codegen_builtin_init:{d}" | |
| for d in partExtEntries Compiler.LCNF.passManagerExt partData do | |
| vs := vs.push s!"codegen_cpass:{d}" | |
| for entry in | |
| partExtEntries Compiler.LCNF.Simp.ConstantFold.folderExt partData do | |
| vs := vs.push s!"codegen_constant_fold:{entry.declName}" | |
| for entry in | |
| partExtEntries Compiler.LCNF.postponedCompileDeclsExt partData do | |
| if entry.declNames.isEmpty then | |
| vs := vs.push s!"codegen_postponed:{m}" | |
| else | |
| for dn in entry.declNames do | |
| vs := vs.push s!"codegen_postponed:{dn}" | |
| let mut pairedUnsafeRecs : NameSet := {} | |
| for ci in data.constants do | |
| if isPairedUnsafeRec modConsts ci then | |
| pairedUnsafeRecs := pairedUnsafeRecs.insert ci.name | |
| let mut seeds : Array Name := #[] | |
| for ci in data.constants do | |
| let n := ci.name | |
| if !pairedUnsafeRecs.contains n then | |
| seeds := seeds.push n | |
| let userN := stripRootAndPrivatePrefixes n | |
| if hasMalformedRootOrPrivate userN then | |
| vs := vs.push s!"malformed_const_name:{n}" | |
| if ci.isAxiom then vs := vs.push s!"custom_axiom:{n}" | |
| if ci.isUnsafe then vs := vs.push s!"unsafe_decl:{n}" | |
| if ci.isPartial && !pairedUnsafeRecs.contains n then | |
| vs := vs.push s!"partial_decl:{n}" | |
| if ci matches .quotInfo _ then vs := vs.push s!"quot_prim:{n}" | |
| if ci matches .opaqueInfo _ then vs := vs.push s!"opaque_decl:{n}" | |
| if ci.hasValue true && (ci.value? true).isNone then | |
| vs := vs.push s!"missing_body:{n}" | |
| if ci matches .thmInfo _ then | |
| if ci.type == mkConst ``False || | |
| ci.type == (.forallE `_ (.sort Level.zero) (.bvar 0) .default) then | |
| vs := vs.push s!"unsound_theorem:{n}" | |
| if kernelAcceleratedNames.contains userN then | |
| vs := vs.push s!"reserved_namespace:{n}" | |
| let root := userN.getRoot | |
| let roleAllowed := | |
| (role == "spec" && root == `Spec) || | |
| (role == "theory" && root == `Anneal) | |
| let compilerHelper := isRealizedOrCompilerHelper env idx allMatchers ci | |
| if !roleAllowed && reservedRoots.contains root && !compilerHelper then | |
| vs := vs.push s!"reserved_namespace:{n}" | |
| if role == "theory" && validatedAutos.contains n then | |
| continue | |
| let mut ignored : NameSet := {} | |
| if role == "theory" then | |
| let (okT, igT) := collectAutoIgnored env role validatedAutos ci.type | |
| let (okV, igV) := match ci.value? true with | |
| | some val => collectAutoIgnored env role validatedAutos val | |
| | none => (true, {}) | |
| if !okT || !okV then | |
| vs := vs.push s!"forbidden_env_ref:{n}:autoParam" | |
| ignored := igT ++ igV | |
| let allEdges := declarationEdges ci | |
| let valRefs := (ci.value? true).map exprAllRefs |>.getD {} | |
| let typeRefs := exprAllRefs ci.type | |
| let nonValRefs := allEdges.foldl (init := ({} : NameSet)) fun acc d => | |
| if valRefs.contains d && !(typeRefs.contains d) then | |
| acc | |
| else acc.insert d | |
| let isThm := ci matches .thmInfo _ | |
| for dep in nonValRefs do | |
| if ignored.contains dep then continue | |
| let depU := stripRootAndPrivatePrefixes dep | |
| if forbiddenConsts.contains depU || | |
| (!pairedUnsafeRecs.contains n && pairedUnsafeRecs.contains dep) then | |
| vs := vs.push s!"forbidden_const_ref:{n}:{dep}" | |
| if isForbiddenEnvRef env role dep false true then | |
| vs := vs.push s!"forbidden_env_ref:{n}:{dep}" | |
| for dep in valRefs do | |
| if nonValRefs.contains dep || ignored.contains dep then continue | |
| let depU := stripRootAndPrivatePrefixes dep | |
| if forbiddenConsts.contains depU || | |
| (!pairedUnsafeRecs.contains n && pairedUnsafeRecs.contains dep) then | |
| vs := vs.push s!"forbidden_const_ref:{n}:{dep}" | |
| if isForbiddenEnvRef env role dep isThm true then | |
| vs := vs.push s!"forbidden_env_ref:{n}:{dep}" | |
| for (partData, _) in allParts do | |
| for (aliasName, targetName) in | |
| partExtEntries Lean.aliasExtension partData do | |
| seeds := seeds.push targetName | |
| let aliasUser := stripRootAndPrivatePrefixes aliasName | |
| let aliasRoot := aliasUser.getRoot | |
| let roleAllowed := | |
| (role == "spec" && aliasRoot == `Spec) || | |
| (role == "theory" && aliasRoot == `Anneal) | |
| if aliasUser.hasMacroScopes || hasMalformedRootOrPrivate aliasUser || | |
| (!roleAllowed && reservedRoots.contains aliasRoot) || | |
| kernelAcceleratedNames.contains aliasUser || | |
| forbiddenPureIdentifiers.contains aliasUser || | |
| isForbiddenPureNamespace aliasUser (banLeanRoot := true) || | |
| isForbiddenRepoPanicRef aliasUser || | |
| aliasUser == `autoParam || aliasUser == `optParam then | |
| vs := vs.push s!"forbidden_alias:{aliasName}" | |
| let targetU := stripRootAndPrivatePrefixes targetName | |
| let allowedSpecOpaque := | |
| role == "spec" && isInitMod env targetName && | |
| allowedSystemPlatformDecls.contains targetName | |
| let badAliasTargetCi := match env.find? targetName with | |
| | some tci => | |
| tci.isUnsafe || tci.isPartial || | |
| ((tci matches .opaqueInfo _) && !allowedSpecOpaque) || | |
| (tci.isAxiom && !isApprovedAxiom env targetName) | |
| | none => false | |
| if forbiddenConsts.contains targetU || badAliasTargetCi || | |
| targetU == `autoParam || targetU == `optParam || | |
| isForbiddenEnvRef env role targetName false true then | |
| vs := vs.push s!"forbidden_alias_target:{aliasName}:{targetName}" | |
| vs := vs ++ checkTransitiveClosure env role auditedSet validatedAutos seeds | |
| return vs | |
| private def runHeaders (j : Json) : IO Json := do | |
| let sources ← IO.ofExcept <| | |
| j.getObjValAs? (Array (String × String)) "sources" | |
| let mut rows : Array Json := #[] | |
| for (modStr, pathStr) in sources do | |
| let text ← IO.FS.readFile pathStr | |
| let (hdr, _, log) ← Parser.parseHeader (Parser.mkInputContext text pathStr) | |
| if log.hasErrors then | |
| throw <| IO.userError s!"header parse error in {modStr}" | |
| let imps := (Elab.HeaderSyntax.imports hdr).map (·.module.toString) | |
| rows := rows.push <| Json.arr #[toJson modStr, toJson imps] | |
| return Json.mkObj [("headers", .arr rows)] | |
| private def sameRealizedThmHeader (a b : ConstantInfo) : Bool := | |
| match a, b with | |
| | .thmInfo ta, .thmInfo tb => | |
| a.name == b.name && a.type == b.type && | |
| a.levelParams == b.levelParams && ta.all == tb.all | |
| | _, _ => false | |
| private def checkAlternateProofs (replayed : Kernel.Environment) | |
| (alternates : Array ConstantInfo) : IO (Array String) := do | |
| let mut vs : Array String := #[] | |
| let checkedEnv := Environment.ofKernelEnv replayed | |
| let mut freshIdx := 0 | |
| for ci in alternates do | |
| let .thmInfo info := ci | |
| | vs := vs.push s!"alternate_non_theorem:{ci.name}" | |
| continue | |
| match Kernel.check checkedEnv {} info.type with | |
| | .error err => | |
| let msg ← (err.toMessageData {}).toString | |
| vs := vs.push s!"alternate_type_failed:{ci.name}:{msg}" | |
| | .ok sortTy => | |
| match Kernel.isDefEq checkedEnv {} sortTy (.sort Level.zero) with | |
| | .ok true => | |
| let mut fresh := Name.num `_redteam_checked_alternate freshIdx | |
| while (replayed.find? fresh).isSome do | |
| freshIdx := freshIdx + 1 | |
| fresh := Name.num `_redteam_checked_alternate freshIdx | |
| freshIdx := freshIdx + 1 | |
| match replayed.addDeclCore 0 0 | |
| (.thmDecl { info with name := fresh }) (cancelTk? := none) with | |
| | .ok _ => pure () | |
| | .error err => | |
| let msg ← (err.toMessageData {}).toString | |
| vs := vs.push s!"alternate_replay_failed:{ci.name}:{msg}" | |
| | .ok false => | |
| vs := vs.push s!"alternate_not_prop:{ci.name}" | |
| | .error err => | |
| let msg ← (err.toMessageData {}).toString | |
| vs := vs.push s!"alternate_prop_check_failed:{ci.name}:{msg}" | |
| return vs | |
| private def replayTargetModules (env : Environment) (mods : Array Name) : | |
| IO (Array String) := do | |
| let mut vs : Array String := #[] | |
| let baseMods := env.header.moduleNames.filter fun m => !mods.contains m | |
| let baseEnv ← | |
| if baseMods.isEmpty then | |
| mkEmptyEnvironment | |
| else | |
| importModules (baseMods.map ({ module := · })) {} | |
| (trustLevel := 0) (plugins := #[]) (loadExts := false) | |
| (level := .private) | |
| let baseKernel := baseEnv.toKernelEnv | |
| let mut replayMap : Std.HashMap Name ConstantInfo := {} | |
| let mut alternates : Array ConstantInfo := #[] | |
| for m in mods do | |
| let some idx := env.header.moduleNames.idxOf? m | continue | |
| let some data := env.header.moduleData[idx]? | continue | |
| for ci in data.constants do | |
| if !ci.isUnsafe && !ci.isPartial then | |
| if let some baseCi := baseKernel.find? ci.name then | |
| if sameRealizedThmHeader baseCi ci then | |
| alternates := alternates.push ci | |
| else | |
| vs := vs.push s!"shadowed_base_const:{ci.name}" | |
| else if let some prevCi := replayMap.get? ci.name then | |
| if sameRealizedThmHeader prevCi ci then | |
| match prevCi, ci with | |
| | .thmInfo a, .thmInfo b => | |
| if a.value != b.value then | |
| alternates := (alternates.push prevCi).push ci | |
| | _, _ => pure () | |
| else | |
| vs := vs.push s!"duplicate_const:{ci.name}" | |
| else | |
| replayMap := replayMap.insert ci.name ci | |
| if !vs.isEmpty then | |
| return vs | |
| if replayMap.isEmpty && alternates.isEmpty then | |
| return vs | |
| try | |
| let replayed ← Kernel.Environment.replay replayMap baseKernel | |
| for (n, _) in replayMap do | |
| unless (replayed.find? n).isSome do | |
| vs := vs.push s!"kernel_replay_omitted:{n}" | |
| if vs.isEmpty && !alternates.isEmpty then | |
| vs := vs ++ (← checkAlternateProofs replayed alternates) | |
| catch err => | |
| vs := vs.push s!"kernel_replay_failed:{err}" | |
| return vs | |
| private def checkShadowedSysroot (sp : Array String) : IO (Array String) := do | |
| let mut vs : Array String := #[] | |
| let exts := | |
| ["", ".olean", ".olean.private", ".olean.server", ".ir", ".ir.sig"] | |
| for spDir in sp do | |
| let base : System.FilePath := ⟨spDir⟩ | |
| for r in sysrootRoots do | |
| let rs := r.toString | |
| if ← exts.anyM (fun ext => (base / s!"{rs}{ext}").pathExists) then | |
| vs := vs.push s!"sp_shadows_sysroot:{rs}" | |
| return vs | |
| private def dedupTargetMods (mods : Array Name) (env : Environment) : | |
| Array Name := Id.run do | |
| let mut out : Array Name := #[] | |
| let mut seen : NameSet := {} | |
| for m in mods do | |
| if !seen.contains m then | |
| seen := seen.insert m | |
| out := out.push m | |
| for m in env.header.moduleNames do | |
| if !isBaseTrustedMod m && !seen.contains m then | |
| seen := seen.insert m | |
| out := out.push m | |
| return out | |
| private def runAudit (j : Json) : IO Json := do | |
| let sys ← IO.ofExcept <| j.getObjValAs? String "sysroot" | |
| let sp ← IO.ofExcept <| j.getObjValAs? (Array String) "searchPath" | |
| let mods := (← IO.ofExcept <| | |
| j.getObjValAs? (Array String) "modules").map String.toName | |
| let role ← IO.ofExcept <| j.getObjValAs? String "role" | |
| if mods.isEmpty then | |
| return Json.mkObj [ | |
| ("ok", toJson false), | |
| ("auditedModules", toJson (#[] : Array String)), | |
| ("violations", toJson #["empty_modules"])] | |
| let shadowVs ← checkShadowedSysroot sp | |
| if !shadowVs.isEmpty then | |
| return Json.mkObj [ | |
| ("ok", toJson false), | |
| ("auditedModules", toJson (mods.map Name.toString)), | |
| ("violations", toJson shadowVs)] | |
| searchPathRef.set ((← getBuiltinSearchPath sys) ++ | |
| (sp.map System.FilePath.mk).toList) | |
| let env ← importModules (mods.map ({ module := · })) {} | |
| (trustLevel := 0) (plugins := #[]) (loadExts := false) (level := .private) | |
| let targetMods := dedupTargetMods mods env | |
| let mut allMatchers := collectAllMatchers env | |
| let mut partsByMod : Std.HashMap Name ( | |
| Array (ModuleData × CompactedRegion) × | |
| Array (ModuleData × CompactedRegion) × Array String) := {} | |
| for m in targetMods do | |
| let (oleanParts, irParts, partErrs) ← readModulePartsChecked m | |
| partsByMod := partsByMod.insert m (oleanParts, irParts, partErrs) | |
| for (partData, _) in oleanParts ++ irParts do | |
| for entry in | |
| partExtEntries Lean.Meta.Match.Extension.extension partData do | |
| allMatchers := allMatchers.insert entry.name | |
| let auditedSet : NameSet := .ofList targetMods.toList | |
| let validatedAutos := collectValidatedAutos env role | |
| let mut vs : Array String := #[] | |
| for m in targetMods do | |
| let (oleanParts, irParts, partErrs) := partsByMod.getD m (#[], #[], #[]) | |
| vs := vs ++ checkModule env allMatchers auditedSet validatedAutos role m | |
| oleanParts irParts partErrs | |
| vs := vs ++ (← replayTargetModules env targetMods) | |
| let mut uniqVs : Array String := #[] | |
| let mut seenVs : Std.HashSet String := {} | |
| for v in vs do | |
| if !seenVs.contains v then | |
| seenVs := seenVs.insert v | |
| uniqVs := uniqVs.push v | |
| return Json.mkObj [ | |
| ("ok", toJson uniqVs.isEmpty), | |
| ("auditedModules", toJson (targetMods.map Name.toString)), | |
| ("violations", toJson uniqVs)] | |
| end OleanAudit | |
| def main (args : List String) : IO UInt32 := do | |
| let [reqPath] := args | |
| | IO.eprintln "expected request JSON path"; return 2 | |
| try | |
| let j ← IO.ofExcept <| Json.parse (← IO.FS.readFile reqPath) | |
| let mode := (j.getObjValAs? String "mode").toOption.getD "audit" | |
| let out ← match mode with | |
| | "headers" => OleanAudit.runHeaders j | |
| | "audit" => OleanAudit.runAudit j | |
| | _ => throw <| IO.userError s!"unknown mode {mode}" | |
| IO.println out.compress | |
| return 0 | |
| catch err => | |
| IO.eprintln err.toString | |
| return 2 |