# Lean 4 syntax categories
This document catalogues the keywords, symbols, and other syntactic elements of Lean 4 **v4.35.0**, the toolchain used by this project. Its word lists were extracted from the running toolchain with the script in Appendix C, so they reflect what Lean actually recognizes. The companion file `Lean4-syntax-diagrams.md` shows how these pieces fit together.
With `import Lean`, Lean v4.35.0 has 504 tokens. Adding `import Mathlib` raises that to 1155. These numbers change with imports because libraries add new tokens.
## 1. How Lean classifies text
Lean does not have a fixed list of keywords. It has a **token table** that grows as files are imported and as `syntax` and `notation` commands run. Text falls into four groups, and the difference matters both when you write proofs and when you build a highlighter.
| Group | Examples | Can it be used as a name? | How to recognize it |
|---|---|---|---|
| Reserved token | `theorem`, `by`, `at`, `fun`, `โ` | No, unless written as `ยซatยป` | It is in the token table. |
| Contextual keyword | `only`, `rec`, `max`, `motive` | Yes | It is special only at one spot in the grammar. |
| Tactic name | `intro`, `simp`, `rw`, `omega` | Yes | It is the first word of a rule in the `tactic` category. |
| Ordinary identifier | `Nat.succ`, `hโ`, `ih` | It is a name | Everything else. |
At each position, Lean reads the longest possible identifier and the longest matching token. It keeps the longer of the two, and a token wins a tie. So `fun` is the keyword, `fun_foo` is one identifier, and `h.left` is one identifier even if `left` is a tactic.
Two consequences are worth remembering:
- **Tactic names are not reserved.** `intro` and `simp` are absent from the token table, and you can write `(simp : Nat)`. A highlighter needs a separate tactic list, and it needs to look at context so that a hypothesis named `left` is not colored as a tactic.
- **Imports can reserve new words.** Mathlib adds tokens such as `lemma`, `to`, `over`, and `says`, so those words stop being valid names in files that import Mathlib.
## 2. Whitespace and layout
Lean ignores most whitespace, but a few rules are strict.
| Rule | Detail |
|---|---|
| No tabs | A tab character outside a string or comment is a parse error. |
| No space inside a dotted name | `Nat.succ` is one identifier, and `Nat . succ` is not. |
| No space before `.{` | `foo.{u}` gives explicit universes. |
| Space before an argument | `f x` applies `f`, and `f(x)` does not parse as an application. |
| Space before a universe level | `Type u`, not `Type(u)`. |
| Column of arguments | Arguments must be indented past the saved position, usually the start of the command. |
| Tactic block column | Every tactic in a block starts in the same column. A smaller indent ends the block. |
| `by` block | The tactics must be indented past the column of the enclosing saved position. |
| `\|` alternatives | The right-hand side must start at or beyond the column of the `\|`. |
| `return` value | The value must begin on the same line as `return`. |
| `calc` steps | Later steps start in the same column as each other. |
Inside `Lean/Parser`, these rules appear as `checkColGt`, `checkColGe`, `checkColEq`, `checkLineEq`, `checkWsBefore`, and `checkNoWsBefore`.
Semicolons can replace a line break in tactic blocks and `do` blocks, and between `let`, `have`, and their bodies.
## 3. Comments
| Syntax | Meaning | Notes |
|---|---|---|
| `-- text` | Line comment | Runs to the end of the line. |
| `/- text -/` | Block comment | Pairs nest. |
| `/-- text -/` | Doc comment | A real token. It attaches to the next declaration. |
| `/-! text -/` | Module doc | A real token. It documents a section of the file. |
## 4. Identifiers
| Element | Rule |
|---|---|
| First character | ASCII letter, `_`, or letter-like Unicode. |
| Letter-like Unicode | Greek and Coptic except `ฮป`, `ฮ `, `ฮฃ`; Greek Extended; Latin-1 and Latin Extended-A letters; Letterlike Symbols (U+2100 to U+214F); script, double-struck, and Fraktur letters (U+1D49C to U+1D59F). |
| Later characters | The above, plus digits, `'`, `!`, `?`, and subscripts. |
| Dotted name | Parts joined by `.` with no spaces. |
| Escaped part | `ยซany textยป`. |
| Hierarchical meaning | `Nat.succ` means `succ` in namespace `Nat`. |
| Name style | Mathlib uses `snake_case` for theorems, `lowerCamelCase` for defs, and `UpperCamelCase` for types. This is a convention, and the parser does not care. |
## 5. Literals
| Kind | Examples | Notes |
|---|---|---|
| Natural number | `0`, `1_000` | Elaborated through `OfNat`. |
| Binary, octal, hex | `0b101`, `0o17`, `0xFF` | Prefix letters can be uppercase. |
| Scientific | `1.5`, `1.`, `2e10`, `1.5E-3` | Elaborated through `OfScientific`. |
| String | `"a\n"` | Can span lines. Escapes: `\\`, `\"`, `\'`, `\r`, `\n`, `\t`, `\xHH`, `\uHHHH`, and the line-end gap. |
| Raw string | `r"a\b"`, `r#"a"b"#` | No escapes. The number of `#` must match. |
| Interpolated string | `s!"{x}"`, `f!"{x}"`, `m!"{x}"` | `{...}` holds a term. |
| Character | `'a'`, `'\n'` | Exactly one character or escape. |
| Name | `` `foo ``, ` ``Nat.succ ` | A double backtick checks that the name exists. |
| Booleans | `true`, `false` | Ordinary constructors, not tokens. |
| Propositions | `True`, `False` | Ordinary constants, not tokens. |
| Array | `#[1, 2]` | The `#[` is a token. |
| List | `[1, 2]` | Macro notation. |
## 6. Reserved keywords by purpose
### 6.1 Declarations
| Keyword | Purpose |
|---|---|
| `def` | Defines a value or function. |
| `theorem` | States and proves a proposition. |
| `abbrev` | A definition that unfolds freely. |
| `example` | An anonymous declaration, checked and then discarded. |
| `axiom` | Assumes a statement with no proof. |
| `opaque` | A constant whose value is hidden. |
| `instance` | Registers a type-class instance. |
| `inductive` | Declares an inductive type. |
| `coinductive` | Declares a coinductive predicate. |
| `structure` | Declares a record type. |
| `class` | Declares a type class. |
### 6.2 Modifiers
| Keyword | Purpose |
|---|---|
| `private` | Visible only in this file. |
| `public` | Exported from a `module`. |
| `protected` | The short name is not available after `open`. |
| `noncomputable` | Has no executable code. |
| `partial` | May not terminate, and is opaque to the logic. |
| `unsafe` | Can use unsafe features, and is excluded from the logic. |
| `nonrec` | The name in the body refers to an earlier declaration, not this one. |
| `meta` | Available at compile time in the module system. |
| `local` | Attribute or notation lasts until the end of the section. |
| `scoped` | Attribute or notation is active when the namespace is open. |
The header words `module`, `prelude`, and `all` are recognized only at the top of a file. They are not in the token table.
### 6.3 Scopes and names
| โฃโโฃโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃโโฃKeyword | Purpose |
| --------------------- | --------------------------------------------------------------------------------- |
| `import` | Imports a module. |
| `namespace` | Opens a namespace block. |
| `section` | Opens a section. |
| `end` | Closes a section, namespace, or `mutual` block. |
| `open` | Makes a namespace's names available. |
| `hiding` | `open X hiding a`: excludes names. |
| `renaming` | `open X renaming a โ b`: gives names new short forms. |
| `export` | Re-exports names from another namespace. |
| `universe` | Declares universe variables. |
| `variable` | Declares section parameters. |
| `include` | Forces variables into later theorems. |
| `omit` | Removes variables from later theorems. |
| `mutual` | Groups mutually recursive declarations. |
| `in` | `A in B` limits command `A` to `B`. Also used by `for x in xs` and `open X in t`. |
| `with_weak_namespace` | Runs a command in a namespace without opening it. |
### 6.4 Parts of declarations
|โฃโโฃโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃโโฃKeyword|Purpose|
| ------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| `where` | Introduces constructors, fields, or local helper definitions. |
| `extends` | Lists parent structures. |
| `deriving` | Requests generated instances. |
| `with` | Used in `match`, `{ s with ... }`, computed fields, and tactic alternatives. |
| `termination_by` | Gives the decreasing measure. |
| `termination_by?` | Asks Lean to suggest a measure. |
| `decreasing_by` | Proves that the measure decreases. |
| `partial_fixpoint` | Justifies recursion as a partial fixpoint. |
| `inductive_fixpoint` | Justifies recursion as a least fixpoint. |
| `coinductive_fixpoint` | Justifies recursion as a greatest fixpoint. |
| `monotonicity_by` | Proves monotonicity for a coinductive declaration. |
### 6.5 Terms
| โฃโโฃโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃโโฃKeyword | Purpose |
|---|---|
| `fun`, `ฮป` | Function abstraction. |
| `forall`, `โ` | Universal quantifier. |
| `exists`, `โ` | Existential quantifier. The word `exists` is also a tactic. |
| `let` | Local definition whose value stays visible. |
| `have` | Local fact whose value is hidden. |
| `letI`, `haveI` | `let` and `have` that are inlined in the elaborated term. |
| `show` | States the expected type. |
| `suffices` | Reduces the goal to a stated fact. |
| `from` | Gives the proof in `show` and `suffices`. |
| `by` | Starts tactic mode. |
| `by?` | Runs tactics and suggests the resulting term. |
| `calc` | Chains relations. |
| `match` | Pattern matching. |
| `matches` | `e matches p` tests a pattern and returns a `Bool`. |
| `nomatch` | Closes a goal with no possible cases. |
| `nofun` | A function with no possible input cases. |
| `if`, `then`, `else` | Conditional on a decidable proposition. |
| `bif` | Conditional on a `Bool`. |
| `Prop`, `Type`, `Sort` | Universes. |
| `sorry` | Placeholder for a missing proof. |
| `inferInstanceAs` | Finds an instance at a stated type. |
| `nat_lit` | A raw natural-number literal. |
| `no_index` | Excludes a subterm from discrimination-tree indexing. |
| `show_term` | Runs tactics and displays the resulting term. |
| `StateRefT` | Special syntax for a state-monad transformer type. |
### 6.6 do notation
| Keyword | Purpose |
|---|---|
| `do` | Starts a `do` block. |
| `mut` | Makes a `let` binding reassignable. |
| `for` | Loop over a collection. `in` separates the variable from the collection. |
| `while`, `until`, `repeat` | Other loops. |
| `break`, `continue` | Leave a loop or go to the next iteration. |
| `unless` | Runs a block when a condition is false. |
| `return` | Exits the block with a value. |
| `try`, `catch`, `finally` | Error handling. |
| `assert!`, `debug_assert!` | Runtime checks. |
| `dbg_trace` | Debug output. |
| `panic!`, `unreachable!` | Runtime failure. |
### 6.7 Words used inside tactics
These are reserved even though they appear mostly in tactic blocks.
| Keyword | Purpose |
|---|---|
| `at` | Chooses where a tactic acts. |
| `using` | Supplies a term or eliminator, as in `simpa using h`. |
| `generalizing` | Generalizes variables in `induction`. |
| `with` | Introduces alternatives or patterns. |
| `show`, `have`, `let`, `calc`, `match`, `if`, `open`, `set_option`, `try`, `repeat` | These are also tokens because they exist as terms, commands, or `do` elements. |
### 6.8 Options and attributes
| Keyword | Purpose |
|---|---|
| `set_option` | Sets an option. |
| `attribute` | Adds or removes attributes on existing declarations. |
| `seal`, `unseal` | Change the reducibility of a definition within a scope. |
### 6.9 Notation and metaprogramming
| Keyword | Purpose |
|---|---|
| `infix`, `infixl`, `infixr` | Infix operators, with no, left, or right associativity. |
| `prefix`, `postfix` | Operators before or after their operand. |
| `notation` | Mixfix notation. |
| `syntax` | Adds a parser rule. |
| `declare_syntax_cat` | Creates a parser category. |
| `macro`, `macro_rules` | Defines syntax expansions. |
| `elab`, `elab_rules` | Defines elaborators. |
| `binder_predicate` | Adds a form such as `โ x > 0`. |
| `leading_parser`, `trailing_parser` | Used to write parsers in Lean's own source. |
| `initialize`, `builtin_initialize` | Runs code at module initialization. |
| `run_cmd`, `run_elab`, `run_meta` | Runs a metaprogram in place. |
| `throwError`, `throwErrorAt` | Report an error from a metaprogram. |
| `sepBy(`, `sepBy1(`, `unicode(` | Combinators inside a `syntax` rule. |
| `s!`, `f!`, `m!` | Interpolated strings: a `String`, a `Format`, and a `MessageData`. |
| `trace[` | Writes to a named trace class. |
| `simproc`, `dsimproc`, `simproc_decl`, `dsimproc_decl` | Define simplification procedures. |
| `unif_hint` | Adds a unification hint. |
| `recall` | Restates an existing declaration, and Lean checks that it matches. |
| `add_decl_doc` | Attaches a doc comment to an existing declaration. |
| `include_str` | Inserts the contents of a file as a string. |
| `register_option`, `register_simp_attr`, `register_label_attr` | Register options and attributes. |
| `declare_simp_like_tactic` | Defines a tactic with the same shape as `simp`. |
| `grind_pattern` | Sets the trigger pattern for a `grind` lemma. |
### 6.10 Other reserved words
These tokens exist in v4.35.0 and are mostly internal to Lean, or are rarely written by hand. Those ending in `%` are elaboration primitives.
`#guard_panic`, `#v[`, `EStackโจ`, `Macro.trace[`, `assert_not_exists`, `assert_not_imported`, `binop%`, `binop_lazy%`, `binrel%`, `binrel_no_prop%`, `builtin_cbv_simproc`, `builtin_cbv_simproc_decl`, `builtin_cbv_simproc_pattern%`, `builtin_dsimproc`, `builtin_dsimproc_decl`, `builtin_grind_propagator`, `builtin_simproc`, `builtin_simproc_decl`, `builtin_simproc_pattern%`, `by_elab`, `cbv_eval`, `cbv_simproc`, `cbv_simproc_decl`, `cbv_simproc_pattern%`, `clear%`, `date(`, `datespec(`, `datetime(`, `decl_name%`, `declare_bitwise_int_theorems`, `declare_bitwise_uint_theorems`, `declare_command_config_elab`, `declare_command_config_elab_legacy`, `declare_config_elab`, `declare_config_elab_legacy`, `declare_core_config_elab`, `declare_eval_bin`, `declare_eval_bin_bitwise`, `declare_eval_bin_bool_pred`, `declare_int_theorems`, `declare_sint_simprocs`, `declare_term_config_elab`, `declare_uint_simprocs`, `declare_uint_theorems`, `def_eval_config_item`, `default_or_ofNonempty%`, `deprecated_module`, `deprecated_syntax`, `docs_to_verso`, `elabToSyntax%`, `elab_stx_quot`, `ensure_expected_type%`, `ensure_type_of%`, `estackโจ`, `eval_prec`, `eval_prio`, `exact?%`, `for_in%`, `for_in'%`, `gen_injective_theorems%`, `grind_annotated`, `grind_propagator`, `idbg`, `init_grind_norm`, `init_quot`, `json%`, `leftact%`, `let_delayed`, `let_expr`, `let_fun`, `let_mvar%`, `let_tmp`, `let_ฮป`, `logNamedError`, `logNamedErrorAt`, `logNamedWarning`, `logNamedWarningAt`, `match_expr`, `max_prec`, `mod_cast`, `no_error_if_unused%`, `no_implicit_lambda%`, `norm_cast_add_elim`, `offset(`, `println!`, `private_decl%`, `recall?`, `recommended_spelling`, `register_builtin_option`, `register_error_explanation`, `register_grind_attr`, `register_linter_set`, `register_parser_alias`, `register_sym_dsimp`, `register_sym_simp`, `register_sym_simp_attr`, `register_tactic_tag`, `register_try?_tactic`, `reportDbgIssue!`, `reportEMatchIssue!`, `reportIssue!`, `reprove`, `reset_grind_attrs%`, `rightact%`, `satisfies_binder_pred%`, `set_library_suggestions`, `show_panel_widgets`, `show_term_elab`, `simproc_pattern%`, `struct_inst_default%`, `tactic_alt`, `tactic_extension`, `tactic_name`, `tactic_tag`, `test_extern`, `throwNamedError`, `throwNamedErrorAt`, `time(`, `timezone(`, `trace_goal[`, `type_of%`, `unlock_limits`, `unop%`, `using!`, `value_of%`, `wait_for_expected_type%`, `wait_if_contains_mvar%`, `wait_if_type_contains_mvar%`, `wait_if_type_mvar%`, `with_annotate_term`, `with_decl_name%`, `without_expected_type`, `zoned(`
## 7. Commands that start with #
These commands report information and do not add declarations.
| Command | Purpose |
|---|---|
| `#check` | Shows the type of a term. |
| `#check_failure` | Like `#check`, but expects elaboration to fail. |
| `#eval`, `#eval!` | Evaluates a term. `#eval!` runs even if it depends on `sorry`. |
| `#reduce` | Reduces a term to normal form. |
| `#print` | Shows a declaration, or a string. |
| `#print axioms` | Lists the axioms that a declaration depends on. |
| `#synth` | Runs type-class search. |
| `#guard` | Fails if a `Bool` term is false. |
| `#guard_msgs` | Tests the messages produced by the next command. |
| `#guard_expr` | Tests that two expressions match. |
| `#where` | Shows the current scope. |
| `#version` | Shows the Lean version. |
| `#exit` | Stops processing the file. |
| `#time` | Measures how long a command takes. |
| `#check_tactic`, `#check_tactic_failure` | Test what a tactic does. |
| `#check_simp` | Tests what `simp` does. |
| `#import_path` | Shows why a module is imported. |
| `#with_exporting` | Runs a command with the public view of a module. |
| `#widget` | Displays a widget. |
| `#info_trees` | Shows the elaboration info trees. |
| `#discr_tree_key`, `#discr_tree_simp_key` | Show discrimination-tree keys. |
| `#grind_lint` | Lints `grind` annotations. |
| `#show_deprecated_modules`, `#check_assertions`, `#dump_async_env_state` | Maintenance tools. |
Mathlib adds many more, including `#find`, `#loogle`, `#leansearch`, `#simp`, `#norm_num`, `#help`, `#lint`, and `#min_imports`.
## 8. Contextual keywords
These words are special only at one place in the grammar. They can still be used as names elsewhere. They are declared with `nonReservedSymbol` in parser code and `&"..."` in `syntax` rules.
| Word | Where it is special |
|---|---|
| `only` | `simp only`, `dsimp only`, and similar. |
| `rec` | `let rec`. |
| `max`, `imax` | Universe levels. |
| `motive` | `match (motive := ...)`. |
| `generalizing` | The `(generalizing := ...)` option of `match`. This word is also a reserved token. |
| `priority`, `name`, `kind`, `behavior` | The `(priority := ...)`, `(name := ...)`, `(kind := ...)`, and `(behavior := ...)` options. |
| `both`, `symbol` | Values for `behavior`. |
| `axioms`, `sig`, `equations`, `eqns`, `tactic`, `tags` | After `#print`. |
| `true`, `false` | Option values and similar. |
| `nondep`, `usedOnly`, `zeta`, `postponeValue`, `generalize`, `eq` | Options for `let` and `have`. |
| `structural` | `termination_by structural`. |
| `monotonicity` | After a fixpoint keyword. |
| `invariant`, `decreasing` | Loop clauses in `do`. |
| `given`, `requires`, `ensures` | Contract clauses on `def`. |
| `erased`, `assert` | `do` elements. |
| `dependent` | `match (dependent := ...)` in `do`. |
| `since` | Deprecation clauses. |
| `expose` | `@[expose]`. |
| `extern`, `inline`, `default_instance`, `specialize`, `recursor` | Attribute forms. |
| `allowTrailingSep`, `preserveForPP`, `withAnonymousAntiquot` | Inside parser descriptions. |
## 9. Tactics by purpose
A tactic transforms the goals. The lists below cover the tactics you are most likely to use. Appendix B lists every tactic known to `import Lean` and `import Mathlib` in v4.35.0. **(M)** marks a Mathlib tactic.
| โฃโโฃโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃโโฃPurpose | Tactics |
| ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Move hypotheses | `intro`, `intros`, `revert`, `rintro`, `clear`, `rename_i`, `rename`, `exfalso` |
| Close with a term | `exact`, `apply`, `refine`, `refine'`, `assumption`, `exact?`, `apply?`, `exacts` (M), `eapply` (M) |
| Close simple goals | `rfl`, `trivial`, `contradiction`, `decide`, `native_decide`, `nofun`, `nomatch`, `absurd` (M) |
| Rewrite | `rw`, `rewrite`, `rwa`, `erw`, `simp_rw` (M), `nth_rw` (M), `subst`, `subst_vars` |
| Simplify | `simp`, `simp_all`, `simp?`, `simpa`, `dsimp`, `unfold`, `norm_cast`, `push_cast`, `simp_arith`, `ring_nf` (M), `field_simp` (M), `norm_num` (M), `push_neg` (M) |
| Decision procedures | `omega`, `grind`, `lia`, `bv_decide`, `bv_omega`, `ring` (M), `linarith` (M), `nlinarith` (M), `positivity` (M), `tauto` (M), `polyrith` (M), `abel` (M), `group` (M), `norm_num` (M), `aesop` (M), `fun_prop` (M), `continuity` (M), `measurability` (M), `gcongr` (M) |
| Case analysis | `cases`, `induction`, `rcases`, `obtain`, `by_cases`, `split`, `fun_induction`, `fun_cases`, `injection`, `by_contra` (M), `interval_cases` (M), `fin_cases` (M), `split_ifs` (M), `contrapose` (M), `wlog` (M) |
| Construct | `constructor`, `exists`, `left`, `right`, `and_intros`, `use` (M), `existsi` (M), `refine` |
| Forward reasoning | `have`, `let`, `show`, `suffices`, `replace`, `specialize`, `generalize`, `calc`, `set` (M), `choose` (M), `lift` (M) |
| Equality and extensionality | `ext`, `funext`, `congr`, `ac_rfl`, `symm`, `trans` (M), `convert` (M), `congrm` (M), `nontriviality` (M) |
| Structure a proof | `case`, `next`, `ยท`, `<;>`, `all_goals`, `any_goals`, `focus`, `first`, `try`, `repeat`, `iterate`, `skip`, `done`, `rotate_left`, `rotate_right`, `on_goal` (M), `pick_goal` (M), `swap` (M) |
| Inspect or debug | `trace`, `trace_state`, `show_term`, `sorry`, `admit`, `stop`, `fail`, `fail_if_success`, `guard_hyp`, `guard_target`, `extract_goal` (M), `says` (M) |
| Change transparency | `with_reducible`, `with_reducible_and_instances`, `with_unfolding_all`, `classical` |
| Enter another mode | `conv`, `run_tac` |
| Program verification | `mvcgen`, `mspec`, `mintro`, `mcases`, `mexact`, `mrevert`, `mrefine`, `mleft`, `mright`, `mconstructor` |
## 10. Symbols
### 10.1 Delimiters
| Symbol | Meaning |
|---|---|
| `( )` | Grouping, tuples, type ascription, and explicit binders. |
| `{ }` | Implicit binders, structure instances, and bracketed tactic or `do` blocks. |
| `[ ]` | Instance binders, lists, rewrite rules, and attribute lists. |
| `โจ โฉ` | Anonymous constructor. |
| `โฆ โฆ`, `{{ }}` | Strict-implicit binders. |
| `โน โบ` | `โนpโบ` finds a proof of `p` by assumption. |
| `ยซ ยป` | Escaped identifier. |
| `@[ ]` | Attribute list. |
| `#[ ]` | Array literal. |
| `.{ }` | Explicit universes. |
| `.( )` | Inaccessible pattern. |
| `` `( ) `` | Syntax quotation. `` `(tactic\| ...) `` quotes in a named category. |
### 10.2 Structural punctuation
|Symbol|Meaning|
| ------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- |
| `:` | Has type. Also precedes a precedence, as in `infixl:65`. |
| `:=` | Is defined as. |
| `::` | List cons, and the constructor name separator in `structure`. |
| `,` | Separates items and precedes a quantifier body. |
| `;` | Separates tactics, `do` elements, and `let` bodies. |
| `.` | Separates name parts, projects a field, and starts `.ctor`. Also an ASCII form of `ยท`. |
| `..` | Remaining arguments or fields. |
| `\|` | Starts a `match` alternative or constructor, and separates `rcases` patterns. |
| `=>` | Separates a pattern or binder from its result. |
| `โฆ` | Same as `=>` in `fun`. |
| `ยท` | Focuses a goal, and also creates an anonymous function argument, as in `(ยท + 1)`. |
| `_` | A hole to infer, or an unused binder. |
| `?x`, `?_` | A named or anonymous metavariable. |
| `โข` | The goal, as in `at h โข`. |
| `<;>` | Applies a tactic to all goals from the previous one. |
| `โฏ` | An omitted term in printed output. |
| `โ` | End-of-proof mark in tactic mode. |
### 10.3 Operators and precedence
Higher numbers bind more tightly. `max` is 1024. `<|` and similar operators use `min`, which is 10. These entries come from `Init/Notation.lean` and `Init/Core.lean`.
| โฃโโฃโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃโโฃPrecedence|Operators|Associativity|Meaning|
|---|---|---|---|
| max | `ยฌ`, `!` | prefix | Logical and Boolean not. Their operand has precedence 40. |
| max | `โปยน` | postfix | Inverse. |
| 100 | `<
gt;` | right | `Functor.map`. |
| 100 | `~~~` | prefix | Bitwise complement. |
| 90 | `โ` | right | Function composition. |
| 80 | `^` | right | Power. |
| 75 | `<<<`, `>>>` | left | Shifts. |
| 75 | `-` | prefix | Negation. |
| 75 | `โธ` | special | Rewrites with an equation. |
| 73 | `โข` | right | Scalar multiplication. |
| 70 | `*`, `/`, `%`, `โฉ`, `\` | left (`\` non-assoc) | Multiplication, division, modulo, intersection, set difference. |
| 67 | `::` | right | List cons. |
| 65 | `+`, `-`, `++`, `โช` | left | Addition, subtraction, append, union. |
| 60 | `&&&` | left | Bitwise and. |
| 60 | `>>`, `<*>`, `<*`, `*>` | mixed | Sequencing. |
| 58 | `^^^` | left | Bitwise xor. |
| 55 | `\|\|\|`, `>>=` | left | Bitwise or, monadic bind. |
| 50 | `=`, `โ `, `<`, `โค`, `>`, `โฅ`, `==`, `!=`, `โ`, `โ`, `โฃ`, `โ`, `โ`, `โ`, `โ`, `โ`, `โ` | none | Comparisons. |
| 35 | `โง`, `&&` | right, left | And. |
| 35 | `ร`, `ร'` | right | Product types. |
| 30 | `โจ`, `\|\|` | right, left | Or. |
| 30 | `โ`, `โ'` | right | Sum types. |
| 25 | `โ` | right | Function type or implication. |
| 20 | `โ` | none | If and only if. |
| 20 | `<\|>` | right | Alternative. |
| min | `<\|`, `
| right | Low-precedence application. |
| min1 or min | `\|>`, `\|>.` | left | Pipeline. |
### 10.4 ASCII alternatives and typing Unicode
Lean accepts these ASCII spellings. All of the listed forms were compiled against v4.35.0. In VS Code and in the Lean web editor, type the backslash abbreviation and a space.
| Symbol | ASCII form | Editor input |
|---|---|---|
| `โ` | `->` | `\to` |
| `โ` | `<-` | `\l` |
| `โ` | `<->` | `\iff` |
| `โง` | `/\` | `\and` |
| `โจ` | `\/` | `\or` |
| `ยฌ` | none | `\not` |
| `โ` | `forall` | `\forall` |
| `โ` | `exists` | `\ex` |
| `ฮป` | `fun` | `\fun` |
| `โฆ` | `=>` | `\mapsto` |
| `โค` | `<=` | `\le` |
| `โฅ` | `>=` | `\ge` |
| `โ ` | none | `\ne` |
| `ยท` | `.` | `\.` |
| `โจ โฉ` | none | `\<` and `\>` |
| `โ` | none | `\comp` |
| `ร` | none | `\x` |
| `โ`, `โ` | none | `\in`, `\notin` |
| `โช`, `โฉ` | none | `\cup`, `\cap` |
| `โ ` | none | `\empty` |
| `โข` | `\|-` in locations | `\\|-` |
| `โธ` | none | `\t` |
| `โฃ` | none | `\dvd` |
| `โปยน` | none | `\-1` |
| `โ`, `โค`, `โ`, `โ`, `โ` | `Nat`, `Int` (others have no short form) | `\N`, `\Z`, `\Q`, `\R`, `\C` |
| `ฮฑ`, `ฮฒ`, `ฮณ` | none | `\a`, `\b`, `\g` |
| `โน โบ` | none | `\f<` and `\f>` |
| `ยซ ยป` | none | `\f<<` and `\f>>` |
`โ`, `โค`, `โ`, `โ`, and `โ` are Mathlib notation. Core Lean has only `Nat`, `Int`, and so on.
### 10.5 Prefix markers
| Marker | Meaning |
|---|---|
| `@f` | Makes all arguments of `f` explicit. |
| `@&` | Marks a borrowed parameter. |
| `x@p` | Names the value matched by pattern `p`. No spaces. |
| `โ e` | Runs a nested action inside `do`. |
| `โe` | Coercion. |
| `โe`, `โe` in `simp` | Simplification timing. |
| `โf`, `โฅs` | Function and type coercions. |
| `$x` | Antiquotation inside a syntax quotation. |
| `+opt`, `-opt` | Tactic configuration. No space. |
| `-foo` | Removes a lemma in `simp [...]`, or an attribute in `attribute [...]`. |
| `` `x ``, ` ``x ` | Name literals. |
## 11. Common attributes
Attributes go in `@[...]` or in an `attribute [...]` command.
| Attribute | Purpose |
|---|---|
| `simp` | Lets `simp` use this lemma. |
| `ext` | Registers an extensionality lemma. |
| `norm_cast` | Registers a cast lemma. |
| `grind` | Registers a lemma for `grind`. |
| `refl`, `symm` | Register lemmas for those tactics. |
| `trans` | Registers a transitivity lemma (Mathlib). |
| `reducible`, `irreducible` | Set how freely a definition unfolds. |
| `inline`, `noinline`, `always_inline`, `specialize` | Compiler hints. |
| `implemented_by`, `extern`, `csimp` | Replace compiled code. |
| `export` | Sets the name used in compiled code. |
| `macro` | Marks a function as a macro. |
| `instance`, `class`, `default_instance` | Type-class controls. |
| `coe` | Marks a function for `โ` display. |
| `match_pattern` | Allows a definition in patterns. |
| `deprecated` | Marks a declaration as deprecated. |
| `inherit_doc` | Copies a doc comment. |
| `to_additive`, `simps`, `reassoc`, `aesop`, `fun_prop`, `mono`, `norm_num`, `positivity`, `measurability` | Mathlib attributes. |
## 12. Parser categories
Grammar rules are organized into categories. Libraries can add rules to any of them, and `declare_syntax_cat` creates new ones.
| Category | What it parses |
|---|---|
| `command` | Top-level commands. |
| `term` | Terms, types, and proofs. |
| `tactic` | Tactics. |
| `conv` | Tactics for `conv` mode. |
| `doElem` | Elements of a `do` block. |
| `attr` | Attributes. |
| `level` | Universe levels. |
| `binderPred` | Predicates in binders, such as `> 0` in `โ x > 0`. |
| `structInstFieldDecl` | Field values in a structure instance. |
| `rcasesPat`, `rintroPat` | Patterns for `rcases` and `rintro`. |
| `stx`, `prec`, `prio` | Syntax descriptions, precedences, and priorities, used by `syntax` and `notation`. |
| `mintroPat`, `mcasesPat`, `mrefinePat`, `mrevertPat` | Patterns for program-verification tactics. |
With `import Lean` in v4.35.0, there are also categories for `grind` configuration (`grind`, `grind_mod`, `grind_filter`, `grind_ref`), symbolic simplification (`sym_simproc`, `sym_dsimproc`, `sym_simp_field`, `sym_dsimp_field`, `sym_discharger`), Verso doc comments (`block`, `inline`, `list_item`, `link_target`, `desc_item`, `doc_arg`, `arg_val`), `json`, `rawStx`, and `vcgenDischarge`.
A category's **behavior** controls how an identifier at the start of a rule is treated. With `both` or `symbol` behavior, as in `tactic` and `conv`, the first word of a rule is matched without being reserved. This is why tactic names are not tokens.
## 13. Mathlib additions
A file that imports Mathlib gains the following kinds of syntax.
| Kind | Examples |
|---|---|
| Declarations | `lemma`, `alias`, `irreducible_def`, `proof_wanted`, `notation3`, `library_note` |
| Universe helpers | `Type*`, `Sort*` |
| Scope helpers | `suppress_compilation`, `unset_option`, `variable?` |
| Number sets | `โ`, `โค`, `โ`, `โ`, `โ`, `โ+`, `โโ` |
| Big operators | `โ`, `โ`, `โซ`, `โจ`, `โจ `, `โ`, `โ` |
| Order and lattice | `โ`, `โ`, `โค`, `โฅ` |
| Quantifier variants | `โ!`, `โแถ `, `โแถ `, `โแต`, `โแต` |
| Morphisms and equivalences | `โ+`, `โ*`, `โ+*`, `โโ[`, `โ`, `โ+`, `โ*`, `โโ[`, `โ `, `โถ` |
| Norms and rounding | `โ`, `โ`, `โ`, `โ`, `โ` |
| Superscripts and subscripts | `แถ`, `แต`, `โปยน'`, `โ`, `โ` |
| Set theory | `''`, `โปยน'`, `รหข` |
## 14. How these categories map to highlight colors
The plugin plan in `Lean4-syntax-plugin-plans.md` uses this mapping. Style names are the CodeMirror and Prism names that Obsidian's themes already color.
| Lean category | CodeMirror style | Prism token |
|---|---|---|
| Comments and doc comments | `comment` | `comment` |
| Reserved keywords (section 6), `#` commands, modifiers | `keyword` | `keyword` |
| Tactic names in tactic position (section 9) | `builtin` | `builtin` |
| Name after `def`, `theorem`, and similar | `def` | `function` |
| `Prop`, `Type`, `Sort`, and number sets | `type` | `class-name` |
| `true`, `false`, `True`, `False`, name literals | `atom` | `boolean` |
| Numbers | `number` | `number` |
| Strings and characters | `string` | `string` |
| Operators (section 10.3) | `operator` | `operator` |
| Attribute lists, syntax quotations | `meta` | `annotation` |
| Metavariables and antiquotations | `variable-2` | `variable` |
| `sorry`, `admit`, `stop` | `error` | `important` |
| Delimiters | `bracket` | `punctuation` |
## Appendix A. Complete token table
### A.1 Word tokens with `import Lean`
`#`, `#[`, `#check`, `#check_assertions`, `#check_failure`, `#check_simp`, `#check_tactic`, `#check_tactic_failure`, `#discr_tree_key`, `#discr_tree_simp_key`, `#dump_async_env_state`, `#eval`, `#eval!`, `#exit`, `#grind_lint`, `#guard`, `#guard_expr`, `#guard_msgs`, `#guard_panic`, `#import_path`, `#info_trees`, `#print`, `#reduce`, `#show_deprecated_modules`, `#synth`, `#time`, `#v[`, `#version`, `#where`, `#widget`, `#with_exporting`,
`
`EStackโจ`, `Macro.trace[`, `Prop`, `Sort`, `StateRefT`, `Type`, `_`,
`abbrev`, `add_decl_doc`, `assert!`, `assert_not_exists`, `assert_not_imported`, `at`, `attribute`, `axiom`,
`bif`, `binder_predicate`, `binop%`, `binop_lazy%`, `binrel%`, `binrel_no_prop%`, `break`, `builtin_cbv_simproc`, `builtin_cbv_simproc_decl`, `builtin_cbv_simproc_pattern%`, `builtin_dsimproc`, `builtin_dsimproc_decl`, `builtin_grind_propagator`, `builtin_initialize`, `builtin_simproc`, `builtin_simproc_decl`, `builtin_simproc_pattern%`, `by`, `by?`, `by_elab`,
`calc`, `catch`, `cbv_eval`, `cbv_simproc`, `cbv_simproc_decl`, `cbv_simproc_pattern%`, `class`, `clear%`, `coinductive`, `coinductive_fixpoint`, `continue`,
`date(`, `datespec(`, `datetime(`, `dbg_trace`, `debug_assert!`, `decl_name%`, `declare_bitwise_int_theorems`, `declare_bitwise_uint_theorems`, `declare_command_config_elab`, `declare_command_config_elab_legacy`, `declare_config_elab`, `declare_config_elab_legacy`, `declare_core_config_elab`, `declare_eval_bin`, `declare_eval_bin_bitwise`, `declare_eval_bin_bool_pred`, `declare_int_theorems`, `declare_simp_like_tactic`, `declare_sint_simprocs`, `declare_syntax_cat`, `declare_term_config_elab`, `declare_uint_simprocs`, `declare_uint_theorems`, `decreasing_by`, `def`, `def_eval_config_item`, `default_or_ofNonempty%`, `deprecated_module`, `deprecated_syntax`, `deriving`, `do`, `docs_to_verso`, `dsimproc`, `dsimproc_decl`,
`elab`, `elabToSyntax%`, `elab_rules`, `elab_stx_quot`, `else`, `end`, `ensure_expected_type%`, `ensure_type_of%`, `estackโจ`, `eval_prec`, `eval_prio`, `exact?%`, `example`, `exists`, `export`, `extends`,
`f!`, `finally`, `for`, `for_in%`, `for_in'%`, `forall`, `from`, `fun`,
`gen_injective_theorems%`, `generalizing`, `grind_annotated`, `grind_pattern`, `grind_propagator`,
`have`, `haveI`, `hiding`,
`idbg`, `if`, `import`, `in`, `include`, `include_str`, `inductive`, `inductive_fixpoint`, `inferInstanceAs`, `infix`, `infixl`, `infixr`, `init_grind_norm`, `init_quot`, `initialize`, `instance`,
`json%`,
`leading_parser`, `leftact%`, `let`, `letI`, `let_delayed`, `let_expr`, `let_fun`, `let_mvar%`, `let_tmp`, `let_ฮป`, `local`, `logNamedError`, `logNamedErrorAt`, `logNamedWarning`, `logNamedWarningAt`,
`m!`, `macro`, `macro_rules`, `match`, `match_expr`, `matches`, `max_prec`, `meta`, `mod_cast`, `monotonicity_by`, `mut`, `mutual`,
`namespace`, `nat_lit`, `no_error_if_unused%`, `no_implicit_lambda%`, `no_index`, `nofun`, `nomatch`, `noncomputable`, `nonrec`, `norm_cast_add_elim`, `notation`,
`offset(`, `omit`, `opaque`, `open`,
`panic!`, `partial`, `partial_fixpoint`, `postfix`, `prefix`, `println!`, `private`, `private_decl%`, `protected`, `public`,
`recall`, `recall?`, `recommended_spelling`, `register_builtin_option`, `register_error_explanation`, `register_grind_attr`, `register_label_attr`, `register_linter_set`, `register_option`, `register_parser_alias`, `register_simp_attr`, `register_sym_dsimp`, `register_sym_simp`, `register_sym_simp_attr`, `register_tactic_tag`, `register_try?_tactic`, `renaming`, `repeat`, `reportDbgIssue!`, `reportEMatchIssue!`, `reportIssue!`, `reprove`, `reset_grind_attrs%`, `return`, `rightact%`, `run_cmd`, `run_elab`, `run_meta`,
`s!`, `satisfies_binder_pred%`, `scoped`, `seal`, `section`, `sepBy(`, `sepBy1(`, `set_library_suggestions`, `set_option`, `show`, `show_panel_widgets`, `show_term`, `show_term_elab`, `simproc`, `simproc_decl`, `simproc_pattern%`, `sorry`, `struct_inst_default%`, `structure`, `suffices`, `syntax`,
`tactic_alt`, `tactic_extension`, `tactic_name`, `tactic_tag`, `termination_by`, `termination_by?`, `test_extern`, `then`, `theorem`, `throwError`, `throwErrorAt`, `throwNamedError`, `throwNamedErrorAt`, `time(`, `timezone(`, `trace[`, `trace_goal[`, `trailing_parser`, `try`, `type_of%`,
`unicode(`, `unif_hint`, `universe`, `unless`, `unlock_limits`, `unop%`, `unreachable!`, `unsafe`, `unseal`, `until`, `using`, `using!`,
`value_of%`, `variable`,
`wait_for_expected_type%`, `wait_if_contains_mvar%`, `wait_if_type_contains_mvar%`, `wait_if_type_mvar%`, `where`, `while`, `with`, `with_annotate_term`, `with_decl_name%`, `with_weak_namespace`, `without_expected_type`,
`zoned(`
### A.2 Symbol tokens with `import Lean`
`!`, `!=`, `!~>`, `
, `%`, `%[`, `&`, `&&`, `&&&`, `(`, `)`, `*`, `*...`, `*...*`, `*...<`, `*...=`, `*>`, `+`, `++`, `,`, `,*`, `,*,?`, `,+`, `,+,?`, `-`, `->`, `.`, `.(`, `..`, `...`, `...*`, `...<`, `...=`, `.{`, `/`, `/-!`, `/--`, `//`, `/\`, `:`, `::`, `:=`, `:=~`, `:=โ`, `:=โ`, `:~`, `:โ`, `:โ`, `;`, `;*`, `<`, `<gt;`, `<&&>`, `<&>`, `<*`, `<*>`, `<+:`, `<-`, `<->`, `<...`, `<...*`, `<...<`, `<...=`, `<:+`, `<:+:`, `<;>`, `<<<`, `<=`, `<=<`, `<|`, `<|>`, `<||>`, `=`, `=/=`, `=<<`, `==`, `=>`, `=?=`, `=~`, `=โ`, `=โ`, `>`, `>=`, `>=>`, `>>`, `>>=`, `>>>`, `?`, `@`, `@&`, `@[`, `[`, `\`, `\/`, `]`, `]'`, `^`, `^^`, `^^^`, `` ` ``, `` `( ``, \`` `(arg_val| \``, `` `(binderPred| ``, `` `(block| ``, `` `(conv| ``, `` `(desc_item| ``, `` `(doc_arg| ``, `` `(grind_filter| ``, `` `(grind_mod| ``, `` `(grind_ref| ``, `` `(grind| ``, `` `(inline| ``, `` `(json| ``, `` `(link_target| ``, `` `(list_item| ``, `` `(mcasesPat| ``, `` `(mintroPat| ``, `` `(mrefinePat| ``, `` `(mrevertPat| ``, `` `(rawStx| ``, `` `(rcasesPat| ``, `` `(rintroPat| ``, `` `(sym_discharger| ``, `` `(sym_dsimp_field| ``, `` `(sym_dsimproc| ``, `` `(sym_simp_field| ``, `` `(sym_simproc| ``, `` `(tactic| ``, `` `(vcgenDischarge| ``,
`{`, `|`, `|*`, `|>`, `|>.`, `||`, `|||`, `}`, `~`, `~>`, `~~~`, `ยฌ`, `ยท`, `ร`, `ร'`, `ฮฃ`, `ฮฃ'`, `ฮป`, `โข`, `โน`, `โบ`, `โปยน`, `โ`, `โ`, `โ`, `โโ`, `โ`, `โ`, `โฅ`, `โฆ`, `โ`, `โ`, `โ`, `โ`, `โ`, `โ `, `โ`, `โ`, `โ`, `โ`, `โฃ`, `โง`, `โงโ`, `โจ`, `โฉ`, `โช`, `โ`, `โ`, `โ`, `โ `, `โค`, `โฅ`, `โ`, `โ`, `โ`, `โ`, `โ`, `โ'`, `โข`, `โฏ`, `โ`, `โ`, `โก`, `โธ`, `โจ`, `โฉ`, `โฆ`, `โฆ`
### A.3 Additional word tokens with `import Mathlib`
`#adaptation_note`, `#aesop_rules`, `#aesop_stats`, `#allow_unused_tactic`, `#check'`, `#clear_deprecations`, `#click_suggestions`, `#conv`, `#count_heartbeats`, `#count_heartbeats!`, `#defeq_abuse`, `#deprecate`, `#dlmf_tags`, `#explode`, `#find`, `#find_home`, `#find_syntax`, `#help`, `#html`, `#import_bumps`, `#import_diff`, `#instances`, `#kerodon_tags`, `#leansearch`, `#lint`, `#list_linters`, `#lmfdb_tags`, `#long_instances`, `#long_names`, `#loogle`, `#min_imports`, `#minimize_imports`, `#norm_imports`, `#norm_num`, `#parse`, `#pibase_tags`, `#print_fun_prop_theorems`, `#pull`, `#push`, `#push_discr_tree`, `#redundant_imports`, `#reset_min_imports`, `#rw??`, `#sample`, `#search`, `#show_kind`, `#show_unused`, `#simp`, `#stacks_tags`, `#statesearch`, `#string_diagram`, `#test`, `#trans_imports`, `#unfold?`, `#whats_new`, `#whnf`, `#whnfR`, `#wikidata_tags`,
`C(`, `Category*`, `GL`, `Gal(`, `PiType`, `Proj|`, `Sort*`, `T(`, `Type*`,
`add_aesop_rules`, `aesop_trace![`, `aesop_trace[`, `alias`, `assert_no_sorry`, `assumeInstancesCommuteDummy`,
`beta%`,
`cHole%`, `c[`, `clean%`, `compile_def%`, `compile_inductive%`, `congr(`,
`declare_aesop_rule_sets`, `def_wanted`, `delta%`, `deprecate`, `derive_fintype%`, `distTriang`, `dsimp%`,
`elementwise_of%`, `erase_aesop_rules`, `eval%`, `expand_binders%`, `expand_foldl%`, `expand_foldr%`, `extend_docs`,
`fast_instance%`, `fbinop%`, `finset%`, `from_lrat`, `funโ`,
`guard_min_heartbeats`,
`haveI'`,
`inferInstanceAs%`, `initialize_simps_projections`, `initialize_simps_projections?`, `insert_to_additive_translation`, `insert_to_dual_translation`, `instance_wanted`, `irreducible_def`,
`kerodon`,
`lemma`, `letI'`, `let_impl_detail`, `library_note`, `line[`, `lrat_proof`,
`map_of%`, `mk_iff_of_inductive_prop`, `mk_rpc_widget%`,
`name_poly_vars`, `name_power_vars`, `nosimp`, `notation3`,
`ofNat(`, `ordCompl[`, `ordProj[`, `over`,
`prod_assoc%`, `prod_assoc_internal%`, `proof_wanted`, `proxy_equiv%`,
`reassoc_of%`, `reduceProj%`, `register_hint`,
`s(`, `says`, `stacks`, `sudo`, `suppress_compilation`,
`theorem_wanted`, `to`, `to_additive_name_hint`, `to_app_of%`, `to_dual_for`, `to_dual_insert_cast`, `to_dual_insert_cast_fun`, `to_dual_name_hint`,
`unset_option`, `unsuppress_compilation`,
`variable?`, `variables`,
`whatsnew`, `without_cdot(`, `without_cdot_impl(`,
`zeta%`
### A.4 Additional symbol tokens with `import Mathlib`
`!![`, `![`, `