fact
stringlengths
10
4.79k
type
stringclasses
9 values
library
stringclasses
44 values
imports
listlengths
0
13
filename
stringclasses
718 values
symbolic_name
stringlengths
1
76
docstring
stringlengths
10
64.6k
@[always_inline, inline] protected tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s match x s with | Result.error e s => handle e (Backtrackable.restore s d) | ok => ok
def
Init.Prelude
[]
Init/Prelude.lean
tryCatch
Handles exceptions thrown in the combined error and state monad. The `Backtrackable δ σ` instance is used to save a snapshot of part of the state prior to running `x`. If an exception is caught, the state is updated with the saved snapshot, rolling back part of the state. If no instance of `Backtrackable` is provided, a fallback instance in which `δ` is `Unit` is used, and no information is rolled back.
@[always_inline, inline] protected orElse {δ} [Backtrackable δ σ] (x₁ : EStateM ε σ α) (x₂ : Unit → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error _ s => x₂ () (Backtrackable.restore s d) | ok => ok
def
Init.Prelude
[]
Init/Prelude.lean
orElse
Failure handling that does not depend on specific exception values. The `Backtrackable δ σ` instance is used to save a snapshot of part of the state prior to running `x₁`. If an exception is caught, the state is updated with the saved snapshot, rolling back part of the state. If no instance of `Backtrackable` is provided, a fallback instance in which `δ` is `Unit` is used, and no information is rolled back.
@[always_inline, inline] adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s => match x s with | Result.error e s => Result.error (f e) s | Result.ok a s => Result.ok a s
def
Init.Prelude
[]
Init/Prelude.lean
adaptExcept
Transforms exceptions with a function, doing nothing on successful results.
@[always_inline, inline] protected bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok a s => f a s | Result.error e s => Result.error e s
def
Init.Prelude
[]
Init/Prelude.lean
bind
Sequences two `EStateM ε σ` actions, passing the returned value from the first into the second.
@[always_inline, inline] protected map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s => match x s with | Result.ok a s => Result.ok (f a) s | Result.error e s => Result.error e s
def
Init.Prelude
[]
Init/Prelude.lean
map
Transforms the value returned from an `EStateM ε σ` action using a function.
@[always_inline, inline] protected seqRight (x : EStateM ε σ α) (y : Unit → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok _ s => y () s | Result.error e s => Result.error e s @[always_inline]
def
Init.Prelude
[]
Init/Prelude.lean
seqRight
Sequences two `EStateM ε σ` actions, running `x` before `y`. The first action's return value is ignored.
instMonad : Monad (EStateM ε σ) where bind := EStateM.bind pure := EStateM.pure map := EStateM.map seqRight := EStateM.seqRight
instance
Init.Prelude
[]
Init/Prelude.lean
instMonad
null
@[always_inline, inline] run (x : EStateM ε σ α) (s : σ) : Result ε σ α := x s
def
Init.Prelude
[]
Init/Prelude.lean
run
Executes an `EStateM` action with the initial state `s`. The returned value includes the final state and indicates whether an exception was thrown or a value was returned.
@[always_inline, inline] run' (x : EStateM ε σ α) (s : σ) : Option α := match run x s with | Result.ok v _ => some v | Result.error .. => none
def
Init.Prelude
[]
Init/Prelude.lean
run'
Executes an `EStateM` with the initial state `s` for the returned value `α`, discarding the final state. Returns `none` if an unhandled exception was thrown.
@[inline] dummySave : σ → PUnit := fun _ => ⟨⟩
def
Init.Prelude
[]
Init/Prelude.lean
dummySave
The `save` implementation for `Backtrackable PUnit σ`.
@[inline] dummyRestore : σ → PUnit → σ := fun s _ => s
def
Init.Prelude
[]
Init/Prelude.lean
dummyRestore
The `restore` implementation for `Backtrackable PUnit σ`.
nonBacktrackable : Backtrackable PUnit σ where save := dummySave restore := dummyRestore
instance
Init.Prelude
[]
Init/Prelude.lean
nonBacktrackable
A fallback `Backtrackable` instance that saves no information from a state. This allows every type to be used as a state in `EStateM`, with no rollback. Because this is the first declared instance of `Backtrackable _ σ`, it will be picked only if there are no other `Backtrackable _ σ` instances registered.
Hashable (α : Sort u) where /-- Hashes a value into a `UInt64`. -/ hash : α → UInt64 export Hashable (hash)
class
Init.Prelude
[]
Init/Prelude.lean
Hashable
Types that can be hashed into a `UInt64`.
@[extern "lean_uint64_mix_hash"] mixHash (u₁ u₂ : UInt64) : UInt64
opaque
Init.Prelude
[]
Init/Prelude.lean
mixHash
An opaque hash mixing operation, used to implement hashing for products.
@[extern "lean_string_hash"] protected String.hash (s : @& String) : UInt64
opaque
Init.Prelude
[]
Init/Prelude.lean
String.hash
Computes a hash for strings.
Name where /-- The "anonymous" name. -/ | anonymous : Name /-- A string name. The name `Lean.Meta.run` is represented at ```lean .str (.str (.str .anonymous "Lean") "Meta") "run" ``` -/ | str (pre : Name) (str : String) /-- A numerical name. This kind of name is used, for example, to create hierarchical names for free variables and metavariables. The identifier `_uniq.231` is represented as ```lean .num (.str .anonymous "_uniq") 231 ``` -/ | num (pre : Name) (i : Nat) with /-- A hash function for names, which is stored inside the name itself as a computed field. -/ @[computed_field] hash : Name → UInt64 | .anonymous => .ofNatLT 1723 (of_decide_eq_true rfl) | .str p s => mixHash p.hash s.hash | .num p v => mixHash p.hash (dite (LT.lt v UInt64.size) (fun h => UInt64.ofNatLT v h) (fun _ => UInt64.ofNatLT 17 (of_decide_eq_true rfl)))
inductive
Init.Prelude
[]
Init/Prelude.lean
Name
Hierarchical names consist of a sequence of components, each of which is either a string or numeric, that are written separated by dots (`.`). Hierarchical names are used to name declarations and for creating unique identifiers for free variables and metavariables. You can create hierarchical names using a backtick: ``` `Lean.Meta.whnf ``` It is short for `.str (.str (.str .anonymous "Lean") "Meta") "whnf"`. You can use double backticks to request Lean to statically check whether the name corresponds to a Lean declaration in scope. ``` ``Lean.Meta.whnf ``` If the name is not in scope, Lean will report an error. There are two ways to convert a `String` to a `Name`: 1. `Name.mkSimple` creates a name with a single string component. 2. `String.toName` first splits the string into its dot-separated components, and then creates a hierarchical name.
@[export lean_name_mk_string] mkStr (p : Name) (s : String) : Name := Name.str p s
abbrev
Init.Prelude
[]
Init/Prelude.lean
mkStr
`.str p s` is now the preferred form.
@[export lean_name_mk_numeral] mkNum (p : Name) (v : Nat) : Name := Name.num p v
abbrev
Init.Prelude
[]
Init/Prelude.lean
mkNum
`.num p v` is now the preferred form.
mkSimple (s : String) : Name := .str .anonymous s
abbrev
Init.Prelude
[]
Init/Prelude.lean
mkSimple
Converts a `String` to a `Name` without performing any parsing. `mkSimple s` is short for `.str .anonymous s`. This means that `mkSimple "a.b"` is the name `«a.b»`, not `a.b`.
@[expose, reducible] mkStr1 (s₁ : String) : Name := .str .anonymous s₁
def
Init.Prelude
[]
Init/Prelude.lean
mkStr1
Make name `s₁`
@[expose, reducible] mkStr2 (s₁ s₂ : String) : Name := .str (.str .anonymous s₁) s₂
def
Init.Prelude
[]
Init/Prelude.lean
mkStr2
Make name `s₁.s₂`
@[expose, reducible] mkStr3 (s₁ s₂ s₃ : String) : Name := .str (.str (.str .anonymous s₁) s₂) s₃
def
Init.Prelude
[]
Init/Prelude.lean
mkStr3
Make name `s₁.s₂.s₃`
@[expose, reducible] mkStr4 (s₁ s₂ s₃ s₄ : String) : Name := .str (.str (.str (.str .anonymous s₁) s₂) s₃) s₄
def
Init.Prelude
[]
Init/Prelude.lean
mkStr4
Make name `s₁.s₂.s₃.s₄`
@[expose, reducible] mkStr5 (s₁ s₂ s₃ s₄ s₅ : String) : Name := .str (.str (.str (.str (.str .anonymous s₁) s₂) s₃) s₄) s₅
def
Init.Prelude
[]
Init/Prelude.lean
mkStr5
Make name `s₁.s₂.s₃.s₄.s₅`
@[expose, reducible] mkStr6 (s₁ s₂ s₃ s₄ s₅ s₆ : String) : Name := .str (.str (.str (.str (.str (.str .anonymous s₁) s₂) s₃) s₄) s₅) s₆
def
Init.Prelude
[]
Init/Prelude.lean
mkStr6
Make name `s₁.s₂.s₃.s₄.s₅.s₆`
@[expose, reducible] mkStr7 (s₁ s₂ s₃ s₄ s₅ s₆ s₇ : String) : Name := .str (.str (.str (.str (.str (.str (.str .anonymous s₁) s₂) s₃) s₄) s₅) s₆) s₇
def
Init.Prelude
[]
Init/Prelude.lean
mkStr7
Make name `s₁.s₂.s₃.s₄.s₅.s₆.s₇`
@[expose, reducible] mkStr8 (s₁ s₂ s₃ s₄ s₅ s₆ s₇ s₈ : String) : Name := .str (.str (.str (.str (.str (.str (.str (.str .anonymous s₁) s₂) s₃) s₄) s₅) s₆) s₇) s₈
def
Init.Prelude
[]
Init/Prelude.lean
mkStr8
Make name `s₁.s₂.s₃.s₄.s₅.s₆.s₇.s₈`
@[extern "lean_name_eq"] protected beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁, str p₂ s₂ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁, num p₂ n₂ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false
def
Init.Prelude
[]
Init/Prelude.lean
beq
(Boolean) equality comparator for names.
@[expose] appendCore : Name → Name → Name | n, .anonymous => n | n, .str p s => .str (appendCore n p) s | n, .num p d => .num (appendCore n p) d
def
Init.Prelude
[]
Init/Prelude.lean
appendCore
This function does not have special support for macro scopes. See `Name.append`.
defaultMaxRecDepth := 512
def
Init.Prelude
[]
Init/Prelude.lean
defaultMaxRecDepth
The default maximum recursion depth. This is adjustable using the `maxRecDepth` option.
maxRecDepthErrorMessage : String := "maximum recursion depth has been reached\n\ use `set_option maxRecDepth <num>` to increase limit\n\ use `set_option diagnostics true` to get diagnostic information" /-! # Syntax -/
def
Init.Prelude
[]
Init/Prelude.lean
maxRecDepthErrorMessage
The message to display on stack overflow.
SourceInfo where /-- A token produced by the parser from original input that includes both leading and trailing whitespace as well as position information. The `leading` whitespace is inferred after parsing by `Syntax.updateLeading`. This is because the “preceding token” is not well-defined during parsing, especially in the presence of backtracking. -/ | original (leading : Substring.Raw) (pos : String.Pos.Raw) (trailing : Substring.Raw) (endPos : String.Pos.Raw) /-- Synthetic syntax is syntax that was produced by a metaprogram or by Lean itself (e.g. by a quotation). Synthetic syntax is annotated with a source span from the original syntax, which relates it to the source file. The delaborator uses this constructor to store an encoded indicator of which core language expression gave rise to the syntax. The `canonical` flag on synthetic syntax is enabled for syntax that is not literally part of the original input syntax but should be treated “as if” the user really wrote it for the purpose of hovers and error messages. This is usually used on identifiers in order to connect the binding site to the user's original syntax even if the name of the identifier changes during expansion, as well as on tokens that should receive targeted messages. Generally speaking, a macro expansion should only use a given piece of input syntax in a single canonical token. An exception to this rule is when the same identifier is used to declare two binders, as in the macro expansion for dependent if: ``` `(if $h : $cond then $t else $e) ~> `(dite $cond (fun $h => $t) (fun $h => $t)) ``` In these cases, if the user hovers over `h` they will see information about both binding sites. -/ | synthetic (pos : String.Pos.Raw) (endPos : String.Pos.Raw) (canonical := false) /-- A synthesized token without position information. -/ | protected none
inductive
Init.Prelude
[]
Init/Prelude.lean
SourceInfo
Source information that relates syntax to the context that it came from. The primary purpose of `SourceInfo` is to relate the output of the parser and the macro expander to the original source file. When produced by the parser, `Syntax.node` does not carry source info; the parser associates it only with atoms and identifiers. If a `Syntax.node` is introduced by a quotation, then it has synthetic source info that both associates it with an original reference position and indicates that the original atoms in it may not originate from the Lean file under elaboration. Source info is also used to relate Lean's output to the internal data that it represents; this is the basis for many interactive features. When used this way, it can occur on `Syntax.node` as well.
getPos? (info : SourceInfo) (canonicalOnly := false) : Option String.Pos.Raw := match info, canonicalOnly with | original (pos := pos) .., _ | synthetic (pos := pos) (canonical := true) .., _ | synthetic (pos := pos) .., false => some pos | _, _ => none
def
Init.Prelude
[]
Init/Prelude.lean
getPos
Gets the position information from a `SourceInfo`, if available. If `canonicalOnly` is true, then `.synthetic` syntax with `canonical := false` will also return `none`.
getTailPos? (info : SourceInfo) (canonicalOnly := false) : Option String.Pos.Raw := match info, canonicalOnly with | original (endPos := endPos) .., _ | synthetic (endPos := endPos) (canonical := true) .., _ | synthetic (endPos := endPos) .., false => some endPos | _, _ => none
def
Init.Prelude
[]
Init/Prelude.lean
getTailPos
Gets the end position information from a `SourceInfo`, if available. If `canonicalOnly` is true, then `.synthetic` syntax with `canonical := false` will also return `none`.
getTrailing? (info : SourceInfo) : Option Substring.Raw := match info with | original (trailing := trailing) .. => some trailing | _ => none
def
Init.Prelude
[]
Init/Prelude.lean
getTrailing
Gets the substring representing the trailing whitespace of a `SourceInfo`, if available.
getTrailingTailPos? (info : SourceInfo) (canonicalOnly := false) : Option String.Pos.Raw := match info.getTrailing? with | some trailing => some trailing.stopPos | none => info.getTailPos? canonicalOnly
def
Init.Prelude
[]
Init/Prelude.lean
getTrailingTailPos
Gets the end position information of the trailing whitespace of a `SourceInfo`, if available. If `canonicalOnly` is true, then `.synthetic` syntax with `canonical := false` will also return `none`.
SyntaxNodeKind := Name /-! # Syntax AST -/
abbrev
Init.Prelude
[]
Init/Prelude.lean
SyntaxNodeKind
Specifies the interpretation of a `Syntax.node` value. An abbreviation for `Name`. Node kinds may be any name, and do not need to refer to declarations in the environment. Conventionally, however, a node's kind corresponds to the `Parser` or `ParserDesc` declaration that produces it. There are also a number of built-in node kinds that are used by the parsing infrastructure, such as `nullKind` and `choiceKind`; these do not correspond to parser declarations.
Syntax.Preresolved where /-- A potential namespace reference -/ | namespace (ns : Name) /-- A potential global constant or section variable reference, with additional field accesses -/ | decl (n : Name) (fields : List String)
inductive
Init.Prelude
[]
Init/Prelude.lean
Syntax.Preresolved
A possible binding of an identifier in the context in which it was quoted. Identifiers in quotations may refer to either global declarations or to namespaces that are in scope at the site of the quotation. These are saved in the `Syntax.ident` constructor and are part of the implementation of hygienic macros.
Syntax where /-- A portion of the syntax tree that is missing because of a parse error. The indexing operator on `Syntax` also returns `Syntax.missing` when the index is out of bounds. -/ | missing : Syntax /-- A node in the syntax tree that may have further syntax as child nodes. The node's `kind` determines its interpretation. For nodes produced by the parser, the `info` field is typically `Lean.SourceInfo.none`, and source information is stored in the corresponding fields of identifiers and atoms. This field is used in two ways: 1. The delaborator uses it to associate nodes with metadata that are used to implement interactive features. 2. Nodes created by quotations use the field to mark the syntax as synthetic (storing the result of `Lean.SourceInfo.fromRef`) even when its leading or trailing tokens are not. -/ -- Remark: the `node` constructor did not have an `info` field in previous versions. This caused a -- bug in the interactive widgets, where the popup for `a + b` was the same as for `a`. The -- delaborator used to associate subexpressions with pretty-printed syntax by setting the (string) -- position of the first atom/identifier to the (expression) position of the subexpression. For -- example, both `a` and `a + b` have the same first identifier, and so their infos got mixed up. | node (info : SourceInfo) (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax /-- A non-identifier atomic component of syntax. All of the following are atoms: * keywords, such as `def`, `fun`, and `inductive` * literals, such as numeric or string literals * punctuation and delimiters, such as `(`, `)`, and `=>`. Identifiers are represented by the `Lean.Syntax.ident` constructor. Atoms also correspond to quoted strings inside `syntax` declarations. -/ | atom (info : SourceInfo) (val : String) : Syntax /-- An identifier. In addition to source information, identifiers have the following fields: * `rawVal` is the literal substring from the input file * `val` is the parsed Lean name, potentially including macro scopes. * `preresolved` is the list of possible declarations this could refer to, populated by [quotations](lean-manual://section/quasiquotation). -/ | ident (info : SourceInfo) (rawVal : Substring.Raw) (val : Name) (preresolved : List Syntax.Preresolved) : Syntax
inductive
Init.Prelude
[]
Init/Prelude.lean
Syntax
Lean syntax trees. Syntax trees are used pervasively throughout Lean: they are produced by the parser, transformed by the macro expander, and elaborated. They are also produced by the delaborator and presented to users.
Syntax.node1 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray1 a₁)
def
Init.Prelude
[]
Init/Prelude.lean
Syntax.node1
Create syntax node with 1 child
Syntax.node2 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray2 a₁ a₂)
def
Init.Prelude
[]
Init/Prelude.lean
Syntax.node2
Create syntax node with 2 children
Syntax.node3 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ a₃ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray3 a₁ a₂ a₃)
def
Init.Prelude
[]
Init/Prelude.lean
Syntax.node3
Create syntax node with 3 children
Syntax.node4 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ a₃ a₄ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray4 a₁ a₂ a₃ a₄)
def
Init.Prelude
[]
Init/Prelude.lean
Syntax.node4
Create syntax node with 4 children
Syntax.node5 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ a₃ a₄ a₅ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray5 a₁ a₂ a₃ a₄ a₅)
def
Init.Prelude
[]
Init/Prelude.lean
Syntax.node5
Create syntax node with 5 children
Syntax.node6 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ a₃ a₄ a₅ a₆ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray6 a₁ a₂ a₃ a₄ a₅ a₆)
def
Init.Prelude
[]
Init/Prelude.lean
Syntax.node6
Create syntax node with 6 children
Syntax.node7 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ a₃ a₄ a₅ a₆ a₇ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray7 a₁ a₂ a₃ a₄ a₅ a₆ a₇)
def
Init.Prelude
[]
Init/Prelude.lean
Syntax.node7
Create syntax node with 7 children
Syntax.node8 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ a₃ a₄ a₅ a₆ a₇ a₈ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray8 a₁ a₂ a₃ a₄ a₅ a₆ a₇ a₈)
def
Init.Prelude
[]
Init/Prelude.lean
Syntax.node8
Create syntax node with 8 children
@[expose] SyntaxNodeKinds := List SyntaxNodeKind
def
Init.Prelude
[]
Init/Prelude.lean
SyntaxNodeKinds
`SyntaxNodeKinds` is a set of `SyntaxNodeKind`, implemented as a list. Singleton `SyntaxNodeKinds` are extremely common. They are written as name literals, rather than as lists; list syntax is required only for empty or non-singleton sets of kinds.
TSyntax (ks : SyntaxNodeKinds) where /-- The underlying `Syntax` value. -/ raw : Syntax
structure
Init.Prelude
[]
Init/Prelude.lean
TSyntax
Typed syntax, which tracks the potential kinds of the `Syntax` it contains. While syntax quotations produce or expect `TSyntax` values of the correct kinds, this is not otherwise enforced; it can easily be circumvented by direct use of the constructor.
choiceKind : SyntaxNodeKind := `choice
abbrev
Init.Prelude
[]
Init/Prelude.lean
choiceKind
The `` `choice `` kind is used to represent ambiguous parse results. The parser prioritizes longer matches over shorter ones, but there is not always a unique longest match. All the parse results are saved, and the determination of which to use is deferred until typing information is available.
nullKind : SyntaxNodeKind := `null
abbrev
Init.Prelude
[]
Init/Prelude.lean
nullKind
`` `null `` is the “fallback” kind, used when no other kind applies. Null nodes result from repetition operators, and empty null nodes represent the failure of an optional parse. The null kind is used for raw list parsers like `many`.
groupKind : SyntaxNodeKind := `group
abbrev
Init.Prelude
[]
Init/Prelude.lean
groupKind
The `` `group `` kind is used for nodes that result from `Lean.Parser.group`. This avoids confusion with the null kind when used inside `optional`.
identKind : SyntaxNodeKind := `ident
abbrev
Init.Prelude
[]
Init/Prelude.lean
identKind
The pseudo-kind assigned to identifiers: `` `ident ``. The name `` `ident `` is not actually used as a kind for `Syntax.node` values. It is used by convention as the kind of `Syntax.ident` values.
strLitKind : SyntaxNodeKind := `str
abbrev
Init.Prelude
[]
Init/Prelude.lean
strLitKind
`` `str `` is the node kind of string literals like `"foo"`.
charLitKind : SyntaxNodeKind := `char
abbrev
Init.Prelude
[]
Init/Prelude.lean
charLitKind
`` `char `` is the node kind of character literals like `'A'`.
numLitKind : SyntaxNodeKind := `num
abbrev
Init.Prelude
[]
Init/Prelude.lean
numLitKind
`` `num `` is the node kind of number literals like `42` and `0xa1`
hexnumKind : SyntaxNodeKind := `hexnum
abbrev
Init.Prelude
[]
Init/Prelude.lean
hexnumKind
`` `hexnum `` is the node kind of hexadecimal numbers like `ea10` without the `0x` prefix. Recall that `hexnum` is not a token and must be prefixed. For hexadecimal number literals, you should use `num` instead. Example: `syntax anchor := "#" noWs hexnum`.
scientificLitKind : SyntaxNodeKind := `scientific
abbrev
Init.Prelude
[]
Init/Prelude.lean
scientificLitKind
`` `scientific `` is the node kind of floating point literals like `1.23e-3`.
nameLitKind : SyntaxNodeKind := `name
abbrev
Init.Prelude
[]
Init/Prelude.lean
nameLitKind
`` `name `` is the node kind of name literals like `` `foo ``.
fieldIdxKind : SyntaxNodeKind := `fieldIdx
abbrev
Init.Prelude
[]
Init/Prelude.lean
fieldIdxKind
`` `fieldIdx `` is the node kind of projection indices like the `2` in `x.2`.
hygieneInfoKind : SyntaxNodeKind := `hygieneInfo
abbrev
Init.Prelude
[]
Init/Prelude.lean
hygieneInfoKind
`` `hygieneInfo `` is the node kind of the `Lean.Parser.hygieneInfo` parser, which produces an “invisible token” that captures the hygiene information at the current point without parsing anything. They can be used to generate identifiers (with `Lean.HygieneInfo.mkIdent`) as if they were introduced in a macro's input, rather than by its implementation.
interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind
abbrev
Init.Prelude
[]
Init/Prelude.lean
interpolatedStrLitKind
`` `interpolatedStrLitKind `` is the node kind of interpolated string literal fragments like `"value = {` and `}"` in `s!"value = {x}"`.
interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind
abbrev
Init.Prelude
[]
Init/Prelude.lean
interpolatedStrKind
`` `interpolatedStrKind `` is the node kind of an interpolated string literal like `"value = {x}"` in `s!"value = {x}"`.
@[inline, expose] mkNode (k : SyntaxNodeKind) (args : Array Syntax) : TSyntax (.cons k .nil) := ⟨Syntax.node SourceInfo.none k args⟩
def
Init.Prelude
[]
Init/Prelude.lean
mkNode
Creates an info-less node of the given kind and children.
getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node _ k _ => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident .. => identKind
def
Init.Prelude
[]
Init/Prelude.lean
getKind
Creates an info-less `nullKind` node with the given children, if any. -/ -- NOTE: used by the quotation elaborator output @[inline, expose] def mkNullNode (args : Array Syntax := Array.empty) : Syntax := mkNode nullKind args |>.raw namespace Syntax /-- Gets the kind of a `Syntax.node` value, or the pseudo-kind of any other `Syntax` value. “Pseudo-kinds” are kinds that are assigned by convention to non-`Syntax.node` values: `identKind` for `Syntax.ident`, `` `missing `` for `Syntax.missing`, and the atom's string literal for atoms.
setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node info _ args => Syntax.node info k args | _ => stx
def
Init.Prelude
[]
Init/Prelude.lean
setKind
Changes the kind at the root of a `Syntax.node` to `k`. Returns all other `Syntax` values unchanged.
isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k
def
Init.Prelude
[]
Init/Prelude.lean
isOfKind
Checks whether syntax has the given kind or pseudo-kind. “Pseudo-kinds” are kinds that are assigned by convention to non-`Syntax.node` values: `identKind` for `Syntax.ident`, `` `missing `` for `Syntax.missing`, and the atom's string literal for atoms.
getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ _ args => args.getD i Syntax.missing | _ => Syntax.missing
def
Init.Prelude
[]
Init/Prelude.lean
getArg
Gets the `i`'th argument of the syntax node. This can also be written `stx[i]`. Returns `missing` if `i` is out of range.
getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ _ args => args | _ => Array.empty
def
Init.Prelude
[]
Init/Prelude.lean
getArgs
Gets the list of arguments of the syntax node, or `#[]` if it's not a `node`.
getNumArgs (stx : Syntax) : Nat := match stx with | Syntax.node _ _ args => args.size | _ => 0
def
Init.Prelude
[]
Init/Prelude.lean
getNumArgs
Gets the number of arguments of the syntax node, or `0` if it's not a `node`.
getOptional? (stx : Syntax) : Option Syntax := match stx with | Syntax.node _ k args => match and (beq k nullKind) (beq args.size 1) with | true => some (args.get!Internal 0) | false => none | _ => none
def
Init.Prelude
[]
Init/Prelude.lean
getOptional
Assuming `stx` was parsed by `optional`, returns the enclosed syntax if it parsed something and `none` otherwise.
isMissing : Syntax → Bool | Syntax.missing => true | _ => false
def
Init.Prelude
[]
Init/Prelude.lean
isMissing
Is this syntax `.missing`?
isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool := and (stx.isOfKind k) (beq stx.getNumArgs n)
def
Init.Prelude
[]
Init/Prelude.lean
isNodeOf
Is this syntax a `node` with kind `k`?
isIdent : Syntax → Bool | ident .. => true | _ => false
def
Init.Prelude
[]
Init/Prelude.lean
isIdent
`stx.isIdent` is `true` iff `stx` is an identifier.
getId : Syntax → Name | ident _ _ val _ => val | _ => Name.anonymous
def
Init.Prelude
[]
Init/Prelude.lean
getId
If this is an `ident`, return the parsed value, else `.anonymous`.
getInfo? : Syntax → Option SourceInfo | atom info .. => some info | ident info .. => some info | node info .. => some info | missing => none
def
Init.Prelude
[]
Init/Prelude.lean
getInfo
Retrieve the immediate info from the Syntax node.
partial getHeadInfo? : Syntax → Option SourceInfo | atom info _ => some info | ident info .. => some info | node SourceInfo.none _ args => let rec loop (i : Nat) : Option SourceInfo := match decide (LT.lt i args.size) with | true => match getHeadInfo? (args.get!Internal i) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | node info _ _ => some info | _ => none
def
Init.Prelude
[]
Init/Prelude.lean
getHeadInfo
Retrieve the left-most node or leaf's info in the Syntax tree.
partial getHeadInfo (stx : Syntax) : SourceInfo := match stx.getHeadInfo? with | some info => info | none => SourceInfo.none
def
Init.Prelude
[]
Init/Prelude.lean
getHeadInfo
Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token.
getPos? (stx : Syntax) (canonicalOnly := false) : Option String.Pos.Raw := stx.getHeadInfo.getPos? canonicalOnly
def
Init.Prelude
[]
Init/Prelude.lean
getPos
Get the starting position of the syntax, if possible. If `canonicalOnly` is true, non-canonical `synthetic` nodes are treated as not carrying position information.
partial getTailPos? (stx : Syntax) (canonicalOnly := false) : Option String.Pos.Raw := match stx, canonicalOnly with | atom (SourceInfo.original (endPos := pos) ..) .., _ | atom (SourceInfo.synthetic (endPos := pos) (canonical := true) ..) _, _ | atom (SourceInfo.synthetic (endPos := pos) ..) _, false | ident (SourceInfo.original (endPos := pos) ..) .., _ | ident (SourceInfo.synthetic (endPos := pos) (canonical := true) ..) .., _ | ident (SourceInfo.synthetic (endPos := pos) ..) .., false | node (SourceInfo.original (endPos := pos) ..) .., _ | node (SourceInfo.synthetic (endPos := pos) (canonical := true) ..) .., _ | node (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node _ _ args, _ => let rec loop (i : Nat) : Option String.Pos.Raw := match decide (LT.lt i args.size) with | true => match getTailPos? (args.get!Internal ((args.size.sub i).sub 1)) canonicalOnly with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _, _ => none
def
Init.Prelude
[]
Init/Prelude.lean
getTailPos
Get the ending position of the syntax, if possible. If `canonicalOnly` is true, non-canonical `synthetic` nodes are treated as not carrying position information.
SepArray (sep : String) where /-- The array of elements and separators, ordered like `#[el1, sep1, el2, sep2, el3]`. -/ elemsAndSeps : Array Syntax
structure
Init.Prelude
[]
Init/Prelude.lean
SepArray
An array of syntax elements interspersed with the given separators. Separator arrays result from repetition operators such as `,*`. [Coercions](lean-manual://section/coercions) to and from `Array Syntax` insert or remove separators as required. The typed equivalent is `Lean.Syntax.TSepArray`.
TSepArray (ks : SyntaxNodeKinds) (sep : String) where /-- The array of elements and separators, ordered like `#[el1, sep1, el2, sep2, el3]`. -/ elemsAndSeps : Array Syntax
structure
Init.Prelude
[]
Init/Prelude.lean
TSepArray
An array of syntax elements that alternate with the given separator. Each syntax element has a kind drawn from `ks`. Separator arrays result from repetition operators such as `,*`. [Coercions](lean-manual://section/coercions) to and from `Array (TSyntax ks)` insert or remove separators as required. The untyped equivalent is `Lean.Syntax.SepArray`.
TSyntaxArray (ks : SyntaxNodeKinds) := Array (TSyntax ks)
abbrev
Init.Prelude
[]
Init/Prelude.lean
TSyntaxArray
An array of syntaxes of kind `ks`.
unsafe TSyntaxArray.rawImpl : TSyntaxArray ks → Array Syntax := unsafeCast
def
Init.Prelude
[]
Init/Prelude.lean
TSyntaxArray.rawImpl
Implementation of `TSyntaxArray.raw`.
@[implemented_by TSyntaxArray.rawImpl] TSyntaxArray.raw (as : TSyntaxArray ks) : Array Syntax := Array.empty
opaque
Init.Prelude
[]
Init/Prelude.lean
TSyntaxArray.raw
Converts a `TSyntaxArray` to an `Array Syntax`, without reallocation.
unsafe TSyntaxArray.mkImpl : Array Syntax → TSyntaxArray ks := unsafeCast
def
Init.Prelude
[]
Init/Prelude.lean
TSyntaxArray.mkImpl
Implementation of `TSyntaxArray.mk`.
@[implemented_by TSyntaxArray.mkImpl] TSyntaxArray.mk (as : Array Syntax) : TSyntaxArray ks := Array.empty
opaque
Init.Prelude
[]
Init/Prelude.lean
TSyntaxArray.mk
Converts an `Array Syntax` to a `TSyntaxArray`, without reallocation.
SourceInfo.fromRef (ref : Syntax) (canonical := false) : SourceInfo := let noncanonical ref := match ref.getPos?, ref.getTailPos? with | some pos, some tailPos => .synthetic pos tailPos | _, _ => .none match canonical with | true => match ref.getPos? true, ref.getTailPos? true with | some pos, some tailPos => .synthetic pos tailPos true | _, _ => noncanonical ref | false => noncanonical ref
def
Init.Prelude
[]
Init/Prelude.lean
SourceInfo.fromRef
Constructs a synthetic `SourceInfo` using a `ref : Syntax` for the span.
mkAtom (val : String) : Syntax := Syntax.atom SourceInfo.none val
def
Init.Prelude
[]
Init/Prelude.lean
mkAtom
Constructs a synthetic `atom` with no source info.
mkAtomFrom (src : Syntax) (val : String) (canonical := false) : Syntax := Syntax.atom (SourceInfo.fromRef src canonical) val /-! # Parser descriptions -/
def
Init.Prelude
[]
Init/Prelude.lean
mkAtomFrom
Constructs a synthetic `atom` with source info coming from `src`.
ParserDescr where /-- A (named) nullary parser, like `ppSpace` -/ | const (name : Name) /-- A (named) unary parser, like `group(p)` -/ | unary (name : Name) (p : ParserDescr) /-- A (named) binary parser, like `orelse` or `andthen` (written as `p1 <|> p2` and `p1 p2` respectively in `syntax`) -/ | binary (name : Name) (p₁ p₂ : ParserDescr) /-- Parses using `p`, then pops the stack to create a new node with kind `kind`. The precedence `prec` is used to determine whether the parser should apply given the current precedence level. -/ | node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) /-- Like `node` but for trailing parsers (which start with a nonterminal). Assumes the lhs is already on the stack, and parses using `p`, then pops the stack including the lhs to create a new node with kind `kind`. The precedence `prec` and `lhsPrec` are used to determine whether the parser should apply. -/ | trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr) /-- Parses the literal symbol. The symbol is automatically included in the set of reserved tokens ("keywords"). Keywords cannot be used as identifiers, unless the identifier is otherwise escaped. For example, `"fun"` reserves `fun` as a keyword; to refer an identifier named `fun` one can write `«fun»`. Adding a `&` prefix prevents it from being reserved, for example `&"true"`. Whitespace before or after the atom is used as a pretty printing hint. For example, `" + "` parses `+` and pretty prints it with whitespace on both sides. The whitespace has no effect on parsing behavior. -/ | symbol (val : String) /-- Parses a literal symbol. The `&` prefix prevents it from being included in the set of reserved tokens ("keywords"). This means that the symbol can still be recognized as an identifier by other parsers. Some syntax categories, such as `tactic`, automatically apply `&` to the first symbol. Whitespace before or after the atom is used as a pretty printing hint. For example, `" + "` parses `+` and pretty prints it with whitespace on both sides. The whitespace has no effect on parsing behavior. (Not exposed by parser description syntax: If the `includeIdent` argument is true, lets `ident` be reinterpreted as `atom` if it matches.) -/ | nonReservedSymbol (val : String) (includeIdent : Bool) /-- Parses using the category parser `catName` with right binding power (i.e. precedence) `rbp`. -/ | cat (catName : Name) (rbp : Nat) /-- Parses using another parser `declName`, which can be either a `Parser` or `ParserDescr`. -/ ...
inductive
Init.Prelude
[]
Init/Prelude.lean
ParserDescr
A `ParserDescr` is a grammar for parsers. This is used by the `syntax` command to produce parsers without having to `import Lean`.
TrailingParserDescr := ParserDescr /-! Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/
abbrev
Init.Prelude
[]
Init/Prelude.lean
TrailingParserDescr
Although `TrailingParserDescr` is an abbreviation for `ParserDescr`, Lean will look at the declared type in order to determine whether to add the parser to the leading or trailing parser table. The determination is done automatically by the `syntax` command.
MacroScope := Nat
abbrev
Init.Prelude
[]
Init/Prelude.lean
MacroScope
A macro scope identifier is just a `Nat` that gets bumped every time we enter a new macro scope. Within a macro scope, all occurrences of identifier `x` parse to the same thing, but `x` parsed from different macro scopes will produce different identifiers.
reservedMacroScope := 0
def
Init.Prelude
[]
Init/Prelude.lean
reservedMacroScope
Macro scope used internally. It is not available for our frontend.
firstFrontendMacroScope := hAdd reservedMacroScope 1
def
Init.Prelude
[]
Init/Prelude.lean
firstFrontendMacroScope
First macro scope available for our frontend
MonadRef (m : Type → Type) where /-- Get the current value of the `ref` -/ getRef : m Syntax /-- Run `x : m α` with a modified value for the `ref` -/ withRef {α} : Syntax → m α → m α export MonadRef (getRef)
class
Init.Prelude
[]
Init/Prelude.lean
MonadRef
A `MonadRef` is a monad that has a `ref : Syntax` in the read-only state. This is used to keep track of the location where we are working; if an exception is thrown, the `ref` gives the location where the error will be reported, assuming no more specific location is provided.
replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos? with | some _ => ref | _ => oldRef
def
Init.Prelude
[]
Init/Prelude.lean
replaceRef
Replaces `oldRef` with `ref`, unless `ref` has no position info. This biases us to having a valid span to report an error on.
@[always_inline, inline] withRef [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α := bind getRef fun oldRef => let ref := replaceRef ref oldRef MonadRef.withRef ref x
def
Init.Prelude
[]
Init/Prelude.lean
withRef
Run `x : m α` with a modified value for the `ref`. This is not exactly the same as `MonadRef.withRef`, because it uses `replaceRef` to avoid putting syntax with bad spans in the state.
@[always_inline, inline] withRef? [Monad m] [MonadRef m] {α} (ref? : Option Syntax) (x : m α) : m α := match ref? with | some ref => withRef ref x | _ => x
def
Init.Prelude
[]
Init/Prelude.lean
withRef
If `ref? = some ref`, run `x : m α` with a modified value for the `ref` by calling `withRef`. Otherwise, run `x` directly.
MonadQuotation (m : Type → Type) extends MonadRef m where /-- Get the fresh scope of the current macro invocation -/ getCurrMacroScope : m MacroScope /-- Get the context name used in Note `Macro Scope Representation`. -/ getContext : m Name /-- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ withFreshMacroScope {α : Type} : m α → m α export MonadQuotation (getCurrMacroScope withFreshMacroScope) -- TODO: delete after rebootstrap @[inherit_doc MonadQuotation.getContext]
class
Init.Prelude
[]
Init/Prelude.lean
MonadQuotation
A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). We also apply the position of the result of `getRef` to each introduced symbol, which results in better error positions than not applying any position.