| /- | |
| Copyright (c) 2020 Microsoft Corporation. All rights reserved. | |
| Released under Apache 2.0 license as described in the file LICENSE. | |
| Authors: Leonardo de Moura, Sebastian Ullrich | |
| -/ | |
| module | |
| prelude | |
| public import Lean.ScopedEnvExtension | |
| import Lean.Compiler.InitAttr | |
| import Lean.Compiler.IR.CompilerM | |
| import Lean.ExtraModUses | |
| public section | |
| /-! | |
| A builder for attributes that are applied to declarations of a common type and | |
| group them by the given attribute argument (an arbitrary `Name`, currently). | |
| Also creates a second "builtin" attribute used for bootstrapping, which saves | |
| the applied declarations in an `IO.Ref` instead of an environment extension. | |
| Used to register elaborators, macros, tactics, and delaborators. | |
| -/ | |
| namespace Lean | |
| namespace KeyedDeclsAttribute | |
| -- could be a parameter as well, but right now it's all names | |
| abbrev Key := Name | |
| def evalIdentKey (stx : Syntax) : AttrM Key := do | |
| let stx ← Attribute.Builtin.getIdent stx | |
| let kind := stx.getId | |
| if (← getEnv).contains kind then | |
| recordExtraModUseFromDecl (isMeta := false) kind | |
| if (← Elab.getInfoState).enabled then | |
| Elab.addConstInfo stx kind none | |
| pure kind | |
| /-- | |
| `KeyedDeclsAttribute` definition. | |
| Important: `mkConst valueTypeName` and `γ` must be definitionally equal. -/ | |
| structure Def (γ : Type) where | |
| /-- Builtin attribute name, if any (e.g., `builtin_term_elab) -/ | |
| builtinName : Name := Name.anonymous | |
| /-- Attribute name (e.g., `term_elab) -/ | |
| name : Name | |
| /-- Attribute description -/ | |
| descr : String | |
| valueTypeName : Name | |
| /-- Convert `Syntax` into a `Key`, the default implementation expects an identifier. -/ | |
| evalKey (builtin : Bool) (stx : Syntax) : AttrM Key := evalIdentKey stx | |
| onAdded (builtin : Bool) (declName : Name) (key : Key) : AttrM Unit := pure () | |
| /-- | |
| Returns the value of the declaration `declName` if it is given by data in the environment, in | |
| which case the declaration is not evaluated and does not need to have type `valueTypeName`. | |
| -/ | |
| valueOfDecl? (env : Environment) (declName : Name) : Option γ := none | |
| deriving Inhabited | |
| structure OLeanEntry where | |
| key : Key | |
| /-- Name of a declaration stored in the environment which has type `mkConst Def.valueTypeName`. -/ | |
| declName : Name | |
| deriving Inhabited | |
| structure AttributeEntry (γ : Type) extends OLeanEntry where | |
| isBuiltin : Bool | |
| /-- Recall that we cannot store `γ` into .olean files because it is a closure. | |
| Given `OLeanEntry.declName`, we convert it into a `γ` by using the unsafe function `evalConstCheck`. -/ | |
| value : γ | |
| abbrev Table (γ : Type) := SMap Key (List (AttributeEntry γ)) | |
| structure ExtensionState (γ : Type) where | |
| newEntries : List OLeanEntry := [] | |
| table : Table γ := {} | |
| declNames : PHashSet Name := {} | |
| erased : PHashSet Name := {} | |
| deriving Inhabited | |
| abbrev Extension (γ : Type) := ScopedEnvExtension OLeanEntry (AttributeEntry γ) (ExtensionState γ) | |
| end KeyedDeclsAttribute | |
| structure KeyedDeclsAttribute (γ : Type) where | |
| defn : KeyedDeclsAttribute.Def γ | |
| -- imported/builtin instances | |
| tableRef : IO.Ref (KeyedDeclsAttribute.Table γ) | |
| -- instances from current module | |
| ext : KeyedDeclsAttribute.Extension γ | |
| deriving Nonempty | |
| namespace KeyedDeclsAttribute | |
| private def Table.insert (table : Table γ) (v : AttributeEntry γ) : Table γ := | |
| match table.find? v.key with | |
| | some vs => SMap.insert table v.key (v::vs) | |
| | none => SMap.insert table v.key [v] | |
| def ExtensionState.insert (s : ExtensionState γ) (v : AttributeEntry γ) : ExtensionState γ := { | |
| table := s.table.insert v | |
| newEntries := v.toOLeanEntry :: s.newEntries | |
| declNames := s.declNames.insert v.declName | |
| erased := s.erased.erase v.declName | |
| } | |
| def addBuiltin (attr : KeyedDeclsAttribute γ) (key : Key) (declName : Name) (value : γ) : IO Unit := | |
| attr.tableRef.modify fun m => m.insert { key, declName, value, isBuiltin := true } | |
| def mkStateOfTable (table : Table γ) : ExtensionState γ := { | |
| table | |
| declNames := table.fold (init := {}) fun s _ es => es.foldl (init := s) fun s e => s.insert e.declName | |
| } | |
| def ExtensionState.erase (s : ExtensionState γ) (attrName : Name) (declName : Name) : CoreM (ExtensionState γ) := do | |
| unless s.declNames.contains declName do | |
| throwError "Cannot erase attribute `{attrName}`: `{.ofConstName declName}` does not have this attribute" | |
| return { s with erased := s.erased.insert declName, declNames := s.declNames.erase declName } | |
| /-- safety: requires that `mkConst df.valueTypeName _` and `γ` are definitionally equal. -/ | |
| protected unsafe def init {γ} (df : Def γ) (attrDeclName : Name := by exact decl_name%) : IO (KeyedDeclsAttribute γ) := do | |
| let tableRef ← IO.mkRef ({} : Table γ) | |
| let ext : Extension γ ← registerScopedEnvExtension { | |
| name := attrDeclName | |
| mkInitial := return mkStateOfTable (← tableRef.get) | |
| ofOLeanEntry := fun _ entry => do | |
| let ctx ← read | |
| if let some f := df.valueOfDecl? ctx.env entry.declName then | |
| return { toOLeanEntry := entry, value := f, isBuiltin := false } | |
| match ctx.env.evalConstCheck γ ctx.opts df.valueTypeName entry.declName with | |
| | Except.ok f => return { toOLeanEntry := entry, value := f, isBuiltin := false } | |
| | Except.error ex => throw (IO.userError ex) | |
| addEntry := fun s e => s.insert e | |
| toOLeanEntry := (·.toOLeanEntry) | |
| } | |
| unless df.builtinName.isAnonymous do | |
| registerBuiltinAttribute { | |
| ref := attrDeclName | |
| name := df.builtinName | |
| descr := "(builtin) " ++ df.descr | |
| add := fun declName stx kind => do | |
| unless kind == AttributeKind.global do throwAttrMustBeGlobal df.builtinName kind | |
| let key ← df.evalKey true stx | |
| let decl ← getConstInfo declName | |
| let throwUnexpectedType := | |
| throwAttrDeclNotOfExpectedType df.builtinName declName decl.type (mkConst df.valueTypeName) | |
| match decl.type with | |
| | Expr.const c _ => | |
| if c != df.valueTypeName then throwUnexpectedType | |
| else | |
| /- builtin_initialize @addBuiltin $(mkConst valueTypeName) $(mkConst attrDeclName) $(key) $(declName) $(mkConst declName) -/ | |
| let val := mkAppN (mkConst ``addBuiltin) #[mkConst df.valueTypeName, mkConst attrDeclName, toExpr key, toExpr declName, mkConst declName] | |
| declareBuiltin declName val | |
| df.onAdded true declName key | |
| | _ => throwUnexpectedType | |
| applicationTime := AttributeApplicationTime.afterCompilation | |
| } | |
| registerBuiltinAttribute { | |
| ref := attrDeclName | |
| name := df.name | |
| descr := df.descr | |
| erase := fun declName => do | |
| let s := ext.getState (← getEnv) | |
| let s ← s.erase df.name declName | |
| modifyEnv fun env => ext.modifyState env fun _ => s | |
| add := fun declName stx attrKind => do | |
| ensureAttrDeclIsMeta attrDeclName declName attrKind | |
| let key ← df.evalKey false stx | |
| match IR.getSorryDep (← getEnv) declName with | |
| | none => | |
| let val ← match df.valueOfDecl? (← getEnv) declName with | |
| | some val => pure val | |
| | none => evalConstCheck γ df.valueTypeName declName | |
| ext.add { key := key, declName := declName, value := val, isBuiltin := true } attrKind | |
| df.onAdded false declName key | |
| | _ => | |
| -- If the declaration contains `sorry`, we skip `evalConstCheck` to avoid unnecessary bizarre error message | |
| pure () | |
| applicationTime := AttributeApplicationTime.afterCompilation | |
| } | |
| pure { defn := df, tableRef := tableRef, ext := ext } | |
| /-- | |
| Tags `declName` with `[attr key]`, where the value of `declName` is given by | |
| `attr.defn.valueOfDecl?`. | |
| -/ | |
| def addValueOfDecl (attr : KeyedDeclsAttribute γ) (declName : Name) (key : Key) | |
| (attrKind : AttributeKind) : AttrM Unit := do | |
| let some value := attr.defn.valueOfDecl? (← getEnv) declName | |
| | throwError "Cannot add attribute `[{attr.defn.name}]`: No value for `{.ofConstName declName}` found" | |
| attr.ext.add { key, declName, value, isBuiltin := true } attrKind | |
| attr.defn.onAdded false declName key | |
| /-- Retrieve entries tagged with `[attr key]` or `[builtinAttr key]`. -/ | |
| def getEntries {γ} (attr : KeyedDeclsAttribute γ) (env : Environment) (key : Name) : List (AttributeEntry γ) := | |
| let s := attr.ext.getState env | |
| let attrs := s.table.findD key [] | |
| if s.erased.isEmpty then | |
| attrs | |
| else | |
| attrs.filter fun attr => !s.erased.contains attr.declName | |
| /-- Retrieve values tagged with `[attr key]` or `[builtinAttr key]`. -/ | |
| def getValues {γ} (attr : KeyedDeclsAttribute γ) (env : Environment) (key : Name) : List γ := | |
| (getEntries attr env key).map AttributeEntry.value | |
| end KeyedDeclsAttribute | |
| end Lean | |
| namespace Lean.Elab | |
| /-- | |
| Syntax tree with numbered holes that can be stored in `.olean` files. It serves as a syntax | |
| quotation that is matched and instantiated without generating code: `matchSyntax?` follows the | |
| semantics of quotation patterns and `instantiate` those of quotation terms. | |
| -/ | |
| inductive SyntaxTemplate where | |
| /-- Hole standing for the variable with the given index. -/ | |
| | var (idx : Nat) | |
| | atom (val : String) | |
| /-- | |
| Identifier. If `hygienic` is set, `instantiate` adds the current macro scope to `val`. | |
| `preresolved` holds the resolutions of `val` at the declaration of the template. | |
| -/ | |
| | ident (rawVal : String) (val : Name) (preresolved : List Syntax.Preresolved) (hygienic : Bool) | |
| | node (kind : SyntaxNodeKind) (args : Array SyntaxTemplate) | |
| deriving Inhabited | |
| namespace SyntaxTemplate | |
| partial def matchCore (vars : Array Syntax) : SyntaxTemplate → Syntax → Option (Array Syntax) | |
| | .var idx, stx => some (vars.setIfInBounds idx stx) | |
| | .atom _, _ => some vars | |
| | .ident _ val .., stx => if stx.matchesIdent val then some vars else none | |
| | .node kind args, stx => | |
| if kind == `patternIgnore then | |
| some vars | |
| else if isLitKind kind then | |
| match args.toList with | |
| | [.atom val] => if stx.matchesLit kind val then some vars else none | |
| | _ => none | |
| else if (if kind == nullKind then stx.matchesNull args.size else stx.isOfKind kind) then | |
| args.size.foldM (init := vars) fun i _ vars => matchCore vars args[i] (stx.getArg i) | |
| else | |
| none | |
| /-- | |
| Matches `stx` against the template like a quotation pattern would and returns the syntax trees | |
| matched by the variables `0, ..., numVars - 1`. | |
| -/ | |
| def matchSyntax? (t : SyntaxTemplate) (stx : Syntax) (numVars : Nat) : Option (Array Syntax) := | |
| matchCore (.replicate numVars .missing) t stx | |
| /-- | |
| Returns the syntax tree described by the template like a quotation term would, where `info` is the | |
| source info of all new nodes and `mainModule` and `scp` make up the macro scope of hygienic | |
| identifiers. | |
| -/ | |
| partial def instantiate (info : SourceInfo) (mainModule : Name) (scp : MacroScope) | |
| (vars : Array Syntax) : SyntaxTemplate → Syntax | |
| | .var idx => vars[idx]! | |
| | .atom val => .atom info val | |
| | .ident rawVal val preresolved hygienic => | |
| .ident info rawVal.toRawSubstring' (if hygienic then addMacroScope mainModule val scp else val) preresolved | |
| | .node kind args => .node info kind (args.map (instantiate info mainModule scp vars)) | |
| end SyntaxTemplate | |
| /-- The data of a `notation` command whose macro and unexpander need no generated code. -/ | |
| structure NotationRule where | |
| /-- Number of variables of the notation. -/ | |
| numVars : Nat | |
| /-- The syntax of the notation. -/ | |
| pat : SyntaxTemplate | |
| /-- The expansion of the notation. -/ | |
| rhs : SyntaxTemplate | |
| /-- | |
| The arguments of the application of a constant that the expansion consists of, if it can be | |
| unexpanded into the notation. | |
| -/ | |
| unexpandArgs? : Option (Array SyntaxTemplate) | |
| deriving Inhabited | |
| /-- Maps the parser declaration of a `notation` command to its rule. -/ | |
| builtin_initialize notationRuleExt : MapDeclarationExtension NotationRule ← | |
| mkMapDeclarationExtension | |
| /-- The macro of a `notation` command. -/ | |
| def NotationRule.expand (rule : NotationRule) : Macro := fun stx => do | |
| let some vars := rule.pat.matchSyntax? stx rule.numVars | |
| | Macro.throwUnsupported | |
| let info ← MonadRef.mkInfoFromRefPos | |
| let scp ← getCurrMacroScope | |
| let mainModule ← MonadQuotation.getContext | |
| return rule.rhs.instantiate info mainModule scp vars | |
| /-- The app unexpander of a `notation` command with expansion `c args*`. -/ | |
| def NotationRule.unexpand (rule : NotationRule) (args : Array SyntaxTemplate) : | |
| PrettyPrinter.Unexpander := fun stx => do | |
| let mut f := stx | |
| let mut vars := .replicate rule.numVars .missing | |
| unless args.isEmpty do | |
| unless stx.isOfKind `Lean.Parser.Term.app && stx[1].matchesNull args.size do | |
| throw () | |
| f := stx[0] | |
| let some vars' := (SyntaxTemplate.node nullKind args).matchSyntax? stx[1] rule.numVars | |
| | throw () | |
| vars := vars' | |
| unless f.isIdent do | |
| throw () | |
| -- The reference is the function instead of the entire application | |
| return rule.pat.instantiate (.fromRef f) .anonymous 0 vars | |
| end Lean.Elab |