## Syntax diagram table of contents These railroad diagrams describe the main syntax of Lean 4 **v4.35.0**, the toolchain used by this project. This document comes with a companion file, [[🧩 Lean4 syntax categories]], which catalogues the keywords and symbols. Here is are the main sections: - [[🧩 Lean4 syntax diagrams#1. Lexical structure|1. Lexical structure]] - [[🧩 Lean4 syntax diagrams#2. File structure|2. File structure]] - [[🧩 Lean4 syntax diagrams#3. Commands|3. Commands]] - [[🧩 Lean4 syntax diagrams#4. Terms|4. Terms]] - [[🧩 Lean4 syntax diagrams#5. do notation|5. do notation]] - [[🧩 Lean4 syntax diagrams#6. Tactics|6. Tactics]] ## How to read the diagrams Follow any line from left to right, from the start marker to the end marker. Every path through a diagram is a valid form of that syntax. ![Railroad diagram legend|1782](legend.svg) - A **rounded green box** is literal text. It must appear exactly as shown. - A **square blue box** is a named rule, which usually has its own diagram. - A line that **branches around** a box makes that box optional. - Parallel lines are **alternatives**. Choose one. - A line that **loops back** allows repetition. If a box sits on the loop, that box is the separator between repetitions. - *Italic text* is a note about a condition, such as "no space". Each diagram is followed by the same rule as text. The text form uses: - `?` for optional, - `*` for zero or more, - `+` for one or more, - `|` for alternatives, and - `sepBy1(x, s)` or `sepBy(x, s)` for lists separated by `s`. These diagrams describe single tokens. Whitespace is not allowed inside a token, except inside strings and comments. Names in angle brackets, such as `<hex digits>`, are informal descriptions and have no diagram of their own. `sepBy(x, s)` allows an empty list. ## What the diagrams leave out The diagrams favor readability over completeness: - **Extensibility.** Lean's grammar is open. `command`, `term`, `tactic`, `doElem`, and other categories can be extended by any library, so the overview diagrams show the common forms only. - **Antiquotations.** Inside macros, almost any syntax position also accepts `$x` and related forms. - **Parser control.** Backtracking (`atomic`), error recovery, and pretty-printing hints are omitted. - **Most indentation rules.** Lean checks columns in many places, for example to decide where a tactic block ends. The diagrams note only the rules that matter when writing code. - **Precedence.** Numeric precedences are omitted. The [[🧩 Lean4 syntax categories#10.3 Operators and precedence|operator table]] lists them. - **Rarely used forms.** Some internal or very new clauses are omitted, and the description mentions this where it matters. ## 1. Lexical structure ### 1.1 Identifier ![Railroad diagram: Identifier|1218](ident.svg) ```ebnf ident ::= idPart ( (* no space *) "." (* no space *) idPart )* ``` An identifier is one or more parts joined by dots, with no spaces around the dots. `Nat.succ_le_of_lt` is a single identifier token, which is why a highlighter must read the whole dotted name before it decides whether a word is a keyword. Example: ```lean def Nat.myDouble (n : Nat) : Nat := n + n #check Nat.myDouble ``` Source: `Lean/Parser/Basic.lean (identFnAux)` ### 1.2 Identifier part ![Railroad diagram: Identifier part|820](idPart.svg) ```ebnf idPart ::= idFirst idRest* | "«" (* any text except » *) "»" ``` A part is either an ordinary name or any text wrapped in French quotes. The quoted form lets a name contain spaces or reuse a reserved word, as in `«hello world»` or `Foo.«end»`. Example: ```lean def «hello world» := 1 #check «hello world» ``` Source: `Init/Meta/Defs.lean` ### 1.3 First character of an identifier part ![Railroad diagram: First character of an identifier part|715](idFirst.svg) ```ebnf idFirst ::= <ASCII letter> | "_" | <letter-like Unicode> ``` Letter-like Unicode covers Greek and Coptic (except `λ`, `Π`, and `Σ`), Latin-1 and Latin Extended-A letters, the Letterlike Symbols block (which includes `ℕ` and `ℝ`), and mathematical script, double-struck, and Fraktur letters. Because `λ`, `Π`, and `Σ` are excluded, they can be used as syntax. Example: ```lean def α := 1 def _x := α #check _x ``` Source: `Init/Meta/Defs.lean (isLetterLike, isIdFirst)` ### 1.4 Later characters of an identifier part ![Railroad diagram: Later characters of an identifier part|842](idRest.svg) ```ebnf idRest ::= <ASCII letter or digit> | "_" | "'" | "!" | "?" | <letter-like Unicode> | <subscript letter or digit> ``` Later characters also allow the apostrophe, `!`, `?`, and subscripts. This means `h'`, `h₁`, `exact?`, and `simp!` are each one word, and an apostrophe inside a name never starts a character literal. Example: ```lean def h₁' := 1 def x! := h₁' #check x! ``` Source: `Init/Meta/Defs.lean (isIdRest)` ### 1.5 Natural-number literal ![Railroad diagram: Natural-number literal|812](numLit.svg) ```ebnf numLit ::= digits | "0b" | "0B" <binary digits> | "0o" | "0O" <octal digits> | "0x" | "0X" <hex digits> ``` Numbers can be decimal, binary, octal, or hexadecimal. Underscores can separate digits for readability. Lean has no negative literal: `-1` is the prefix operator applied to `1`. Example: ```lean #eval 1_000 #eval 0b1010 #eval 0o17 #eval 0xFF_FF ``` Source: `Lean/Parser/Basic.lean (numberFnAux)` ### 1.6 Scientific literal ![Railroad diagram: Scientific literal|1112](scientificLit.svg) ```ebnf scientificLit ::= digits "." digits exponent? | "." exponent? | exponent ``` A scientific literal has a fractional part, an exponent, or both. The exponent is `e` or `E`, an optional sign, and digits. Two consecutive dots end the number, so `1..5` is `1`, `..`, `5`. Example: ```lean #eval (1.5 : Float) #eval (1. : Float) #eval (1e3 : Float) #eval (1.5E-3 : Float) ``` Source: `Lean/Parser/Basic.lean (decimalNumberFn)` ### 1.7 String literal ![Railroad diagram: String literal|1250](strLit.svg) ```ebnf strLit ::= """ ( <any character except " or \> | escape )* """ ``` A string can span several lines. A prefix such as `s!`, `f!`, or `m!` turns the string into an interpolated string, where `{...}` holds a term. Example: ```lean #eval "first\tsecond" #eval s!"1 + 1 = {1 + 1}" ``` Source: `Lean/Parser/Basic.lean (strLitFnAux)` ### 1.8 Escape sequence ![Railroad diagram: Escape sequence|1080](escape.svg) ```ebnf escape ::= "\" "\" | """ | "'" | "r" | "n" | "t" | "x" hex hex | "u" hex hex hex hex | (* newline and indentation (strings only) *) ``` Escapes are the same in strings and character literals, except for the string gap: a backslash at the end of a line skips the newline and the indentation that follows it. Example: ```lean #eval "A\x41\u0041" #eval "one \ line" ``` Source: `Lean/Parser/Basic.lean (quotedCharCoreFn)` ### 1.9 Raw string literal ![Railroad diagram: Raw string literal|1512](rawStrLit.svg) ```ebnf rawStrLit ::= "r" "#"* """ (* any text *) """ "#"* (* same number of # *) ``` Raw strings have no escapes. Adding `#` characters lets the text contain a double quote. A highlighter must remember the number of `#` characters to find the end. Example: ```lean #eval r"a\n" #eval r#"a"b"# ``` Source: `Lean/Parser/Basic.lean (rawStrLitFnAux)` ### 1.10 Character literal ![Railroad diagram: Character literal|1100](charLit.svg) ```ebnf charLit ::= "'" <any character except ' or \> | escape "'" ``` A character literal holds exactly one character or escape. It can start only where a new token starts, so the apostrophe in `h'` is part of the identifier. Example: ```lean #eval 'a' #eval '\n' ``` Source: `Lean/Parser/Basic.lean (charLitFnAux)` ### 1.11 Name literal ![Railroad diagram: Name literal|748](nameLit.svg) ```ebnf nameLit ::= "`" | "``" (* no space *) ident ``` A single backtick quotes a name without checking it. A double backtick checks that the name exists and resolves it. Both are used in metaprogramming. Example: ```lean #check `foo.bar #check ``Nat.succ ``` Source: `Lean/Parser/Basic.lean (nameLitAux), Term.lean (doubleQuotedName)` ### 1.12 Comment ![Railroad diagram: Comment|1215](comment.svg) ```ebnf comment ::= "--" (* to end of line *) | "/-" (* text; /- -/ pairs nest *) "-/" | "/--" (* doc comment for the next declaration *) "-/" | "/-!" (* module documentation *) "-/" ``` Block comments nest, so a highlighter needs a depth counter. Ordinary comments are whitespace to the parser, but `/--` and `/-!` are real tokens and may appear only where the grammar allows them. Example: ```lean -- line comment /- outer /- inner -/ still a comment -/ /-! Module documentation -/ /-- Doc comment for `x`. -/ def x := 1 ``` Source: `Lean/Parser/Basic.lean (whitespace, finishCommentBlock)` ## 2. File structure ### 2.1 Source file ![Railroad diagram: Source file|720](module.svg) ```ebnf module ::= header command* ``` A file is a header followed by commands. There is no separator between commands: each command ends where the next one can begin. Example: ```lean import Lean def one := 1 #eval one ``` Source: `Lean/Parser/Module/Syntax.lean (module)` ### 2.2 File header ![Railroad diagram: File header|1135](header.svg) ```ebnf header ::= "module"? "prelude"? import* ``` The header must come first. `module` turns on the module system. `prelude` stops Lean from importing `Init` automatically, and is used only by the core library. Example: ```lean module public import Lean public def one := 1 ``` Source: `Lean/Parser/Module/Syntax.lean (header)` ### 2.3 Import ![Railroad diagram: Import|1362](import.svg) ```ebnf import ::= "public"? "meta"? "import" "all"? ident ``` An import names one module. The `public`, `meta`, and `all` options are available only in a file that starts with `module`, and `public` cannot be combined with `all`. Example: ```lean import Lean open Lean #check Name ``` Source: `Lean/Parser/Module/Syntax.lean (import), Module.lean (parseHeader)` ## 3. Commands A command is the top-level unit of a file. Lean parses one command at a time, so a macro defined by one command can be used by the next. ### 3.1 Command overview ![Railroad diagram: Command overview|888](command.svg) ```ebnf command ::= declaration | <scoping command> | <open or export> | <option or attribute command> | <information command> | <notation or syntax command> | <command in command> ``` This overview groups the main command families. The `command` category is open: libraries add commands, and Mathlib adds well over a hundred. Example: ```lean def two := 2 section #eval two end set_option pp.all true in #check two ``` Source: `Lean/Parser/Command.lean` ### 3.2 Command in command ![Railroad diagram: Command in command|720](commandIn.svg) ```ebnf commandIn ::= command "in" command ``` `A in B` limits the effect of command `A` to command `B`, as if the two were wrapped in a section of their own. It is most often used with `open`, `set_option`, `variable`, `include`, and `omit`. Example: ```lean open Nat in #check succ set_option pp.explicit true in #check 1 + 1 variable (n : Nat) in theorem t : n = n := rfl ``` Source: `Lean/Parser/Command.lean (in)` ### 3.3 Declaration ![Railroad diagram: Declaration|1058](declaration.svg) ```ebnf declaration ::= declModifiers abbrev | def | theorem | opaque | instance | axiom | example | inductive | coinductive | <class inductive> | <structure or class> ``` Every declaration has optional modifiers and then exactly one declaration form. `lemma` is not part of core Lean. Mathlib adds it as a command with the same shape as `theorem`. Example: ```lean @[simp] private theorem one_add_one : 1 + 1 = 2 := rfl protected def Nat.three : Nat := 3 noncomputable section end ``` Source: `Lean/Parser/Command.lean (declaration)` ### 3.4 Declaration modifiers ![Railroad diagram: Declaration modifiers|1912](declModifiers.svg) ```ebnf declModifiers ::= docComment? attributes? ( "private" | "public" )? "protected"? ( "meta" | "noncomputable" )? "unsafe"? ( "partial" | "nonrec" )? ``` Modifiers have a fixed order. For example, `private` must come before `noncomputable`, and `partial` comes last. Example: ```lean /-- Documented. -/ @[inline] private unsafe def f : Nat := 1 partial def g (n : Nat) : Nat := g n ``` Source: `Lean/Parser/Command.lean (declModifiers)` ### 3.5 Attribute list ![Railroad diagram: Attribute list|990](attributes.svg) ```ebnf attributes ::= "@[" sepBy1(( "scoped" | "local" )? attr, ",") "]" ``` An attribute list goes before a declaration. `local` limits an attribute to the current section, and `scoped` activates it only when its namespace is open. The `attr` category is open, so libraries can add attributes. Example: ```lean @[simp, reducible] def f := 1 section local instance : Inhabited Nat := ⟨0⟩ end ``` Source: `Lean/Parser/Term.lean (attributes, attrInstance), Attr.lean` ### 3.6 Declaration name ![Railroad diagram: Declaration name|1098](declId.svg) ```ebnf declId ::= ident ( (* no space *) ".{" sepBy1(ident, ",") "}" )? ``` A declaration name can introduce universe parameters directly after the name, with no space before `.{`. Example: ```lean def idAt.{u} (α : Sort u) (a : α) : α := a ``` Source: `Lean/Parser/Command.lean (declId)` ### 3.7 Declaration signature ![Railroad diagram: Declaration signature|1055](declSig.svg) ```ebnf declSig ::= ( binderIdent | bracketedBinder )* ":" term ``` A signature is a list of parameters, a colon, and a type. `theorem`, `axiom`, `opaque`, and `instance` require it. A form that accepts `optDeclSig` can leave out the type and let Lean infer it. Example: ```lean theorem le_self (n : Nat) : n ≤ n := Nat.le_refl n ``` Source: `Lean/Parser/Command.lean (declSig, optDeclSig)` ### 3.8 Optional declaration signature ![Railroad diagram: Optional declaration signature|1155](optDeclSig.svg) ```ebnf optDeclSig ::= ( binderIdent | bracketedBinder )* ( ":" term )? ``` This is the same as a signature, except that the type can be omitted. Example: ```lean def double (n : Nat) := n + n ``` Source: `Lean/Parser/Command.lean (optDeclSig)` ### 3.9 Declaration value ![Railroad diagram: Declaration value|1370](declVal.svg) ```ebnf declVal ::= ":=" term terminationSuffix whereDecls? | matchAlts terminationSuffix whereDecls? | "where" structInstFields whereDecls? ``` A value takes one of three forms: `:=` with a term, pattern-matching equations, or `where` with structure fields. Proofs usually use the first form with a `by` term. Example: ```lean def a : Nat := 1 def isZero : Nat → Bool | 0 => true | _ => false instance : Inhabited Nat where default := 0 ``` Source: `Lean/Parser/Command.lean (declVal)` ### 3.10 Termination hints ![Railroad diagram: Termination hints|1600](terminationSuffix.svg) ```ebnf terminationSuffix ::= ( <termination_by clause> | "partial_fixpoint" | "coinductive_fixpoint" | "inductive_fixpoint" )? ( "decreasing_by" tacticSeq )? ``` After a recursive definition, `termination_by` gives the measure that decreases, and `decreasing_by` proves that it decreases. The fixpoint keywords choose a different way of justifying the recursion. Example: ```lean def down (n : Nat) : Nat := if h : n = 0 then 0 else down (n - 1) termination_by n decreasing_by omega ``` Source: `Lean/Parser/Term.lean (Termination.suffix)` ### 3.11 Where clause ![Railroad diagram: Where clause|770](whereDecls.svg) ```ebnf whereDecls ::= "where" sepBy(letRecDecl, ";" | (* new line *)) ``` A `where` clause adds helper definitions after the main body. Each helper is available in the body above it. Example: ```lean def sumTo (n : Nat) : Nat := go n 0 where go : Nat → Nat → Nat | 0, acc => acc | k + 1, acc => go k (acc + k + 1) ``` Source: `Lean/Parser/Term.lean (whereDecls)` ### 3.12 def ![Railroad diagram: def|1728](def.svg) ```ebnf def ::= "def" declId optDeclSig declVal ( "deriving" sepBy1(<class name>, ",") )? ``` `def` introduces a definition. A definition can also derive instances directly with a trailing `deriving` clause. In v4.35.0 a `def` can also carry `given`, `requires`, and `ensures` contract clauses, which are not shown here. Example: ```lean def add (a b : Nat) : Nat := a + b ``` Source: `Lean/Parser/Command.lean (definition)` ### 3.13 theorem ![Railroad diagram: theorem|1042](theorem.svg) ```ebnf theorem ::= "theorem" declId declSig declVal ``` A theorem must state its type. Its value is a proof, and Lean treats the proof body as irrelevant to later computation. Example: ```lean theorem and_swap (p q : Prop) (h : p ∧ q) : q ∧ p := ⟨h.2, h.1⟩ ``` Source: `Lean/Parser/Command.lean (theorem)` ### 3.14 abbrev ![Railroad diagram: abbrev|1085](abbrev.svg) ```ebnf abbrev ::= "abbrev" declId optDeclSig declVal ``` `abbrev` is a definition marked `@[reducible]`, so Lean unfolds it freely. This makes it a good fit for short type names. Example: ```lean abbrev MyNat := Nat ``` Source: `Lean/Parser/Command.lean (abbrev)` ### 3.15 opaque ![Railroad diagram: opaque|1182](opaque.svg) ```ebnf opaque ::= "opaque" declId declSig ( ":=" term )? ``` An `opaque` constant has a type, and its value is hidden from the logic. Without a value, Lean uses an `Inhabited` or `Nonempty` instance of the type. Example: ```lean opaque secret : Nat ``` Source: `Lean/Parser/Command.lean (opaque)` ### 3.16 instance ![Railroad diagram: instance|1955](instance.svg) ```ebnf instance ::= ( "scoped" | "local" )? "instance" namedPrio? declId? declSig declVal ``` An instance registers a value for type-class search. The name is optional, and Lean generates one when it is left out. Example: ```lean instance (priority := low) myInst : Inhabited Nat := ⟨0⟩ ``` Source: `Lean/Parser/Command.lean (instance)` ### 3.17 axiom ![Railroad diagram: axiom|762](axiom.svg) ```ebnf axiom ::= "axiom" declId declSig ``` An axiom asserts a type without any value. Use `#print axioms` to see which axioms a theorem depends on. Example: ```lean axiom myAx : 1 = 1 #print axioms myAx ``` Source: `Lean/Parser/Command.lean (axiom)` ### 3.18 example ![Railroad diagram: example|892](example.svg) ```ebnf example ::= "example" optDeclSig declVal ``` An example is checked like a declaration, but it has no name and adds nothing to the environment. Example: ```lean example : 2 + 2 = 4 := rfl ``` Source: `Lean/Parser/Command.lean (example)` ### 3.19 inductive ![Railroad diagram: inductive|1935](inductive.svg) ```ebnf inductive ::= "inductive" | "coinductive" | "class" "inductive" declId optDeclSig ( ":=" | "where" )? ctor* ( "with" computedField+ )? ( "deriving" sepBy1(<class name>, ",") )? ``` An inductive type lists its constructors, each starting with `|`. The `where` keyword after the signature is optional. `coinductive` has the same shape, and also accepts `monotonicity_by` (not shown). Example: ```lean inductive Tree (α : Type) where | leaf : Tree α | node (left : Tree α) (value : α) (right : Tree α) : Tree α deriving Repr ``` Source: `Lean/Parser/Command.lean (inductive, classInductive)` ### 3.20 Constructor ![Railroad diagram: Constructor|1700](ctor.svg) ```ebnf ctor ::= docComment? "|" declModifiers <ident (no dots)> optDeclSig ``` A constructor is written after `|`. Its parameters appear before its optional type, as with a definition. Example: ```lean inductive Color where /-- The first color. -/ | red | rgb (r g b : Nat) ``` Source: `Lean/Parser/Command.lean (ctor)` ### 3.21 structure and class ![Railroad diagram: structure and class|2150](structure.svg) ```ebnf structure ::= "structure" | "class" declId optDeclSig ( "extends" sepBy1(structParent, ",") ( ":" term )? )? ( ":=" | "where" ( <ctor name> bracketedBinder* "::" )? structField* )? ( "deriving" sepBy1(<class name>, ",") )? ``` A structure is a single-constructor type with named fields. `class` has the same shape and also makes the type available to instance search. Example: ```lean structure Point where mk :: x : Nat y : Nat := 0 deriving Repr class Pointed (α : Type) where pt : α ``` Source: `Lean/Parser/Command.lean (structure)` ### 3.22 Structure field ![Railroad diagram: Structure field|1440](structField.svg) ```ebnf structField ::= "(" ident+ optDeclSig <field default>? ")" | "{" ident+ declSig "}" | "[" ident+ declSig "]" | ident optDeclSig <field default>? ``` A field can be plain or written in explicit, implicit, or instance brackets. Each form can start with modifiers, not shown. A field default is `:= term` or `:= by tactics`. Example: ```lean structure S where a : Nat := 1 (b c : Nat) {d : Nat} [inst : Inhabited Nat] e : a = a := by rfl ``` Source: `Lean/Parser/Command.lean (structFields)` ### 3.23 section ![Railroad diagram: section|2248](section.svg) ```ebnf section ::= ( "@[" "expose" "]" )? "public"? "noncomputable"? "meta"? "section" ident? ``` A section limits the effect of `variable`, `open`, `universe`, local attributes, and options. It ends with a matching `end`. The name is optional. Example: ```lean section Algebra variable (n : Nat) def inc := n + 1 end Algebra ``` Source: `Lean/Parser/Command.lean (section, sectionHeader)` ### 3.24 namespace ![Railroad diagram: namespace|592](namespace.svg) ```ebnf namespace ::= "namespace" ident ``` A namespace is a section that also prefixes every declaration name inside it. Example: ```lean namespace Foo def bar := 1 end Foo #check Foo.bar ``` Source: `Lean/Parser/Command.lean (namespace)` ### 3.25 end ![Railroad diagram: end|562](end.svg) ```ebnf end ::= "end" ident? ``` `end` closes the most recent section or namespace. If the scope was named, the same name must be given. Example: ```lean namespace A.B end A.B ``` Source: `Lean/Parser/Command.lean (end)` ### 3.26 variable ![Railroad diagram: variable|835](variable.svg) ```ebnf variable ::= "variable" bracketedBinder+ ``` `variable` declares parameters that are added automatically to later declarations in the scope when they use them. Theorem bodies do not trigger this inclusion, which is why `include` exists. Example: ```lean section variable {α : Type} [Inhabited α] def someA : α := default end ``` Source: `Lean/Parser/Command.lean (variable)` ### 3.27 universe ![Railroad diagram: universe|620](universe.svg) ```ebnf universe ::= "universe" ident+ ``` `universe` declares universe-level names for the current scope. Example: ```lean universe u v def constFn {α : Sort u} {β : Sort v} (a : α) (_ : β) : α := a ``` Source: `Lean/Parser/Command.lean (universe)` ### 3.28 include and omit ![Railroad diagram: include and omit|842](include.svg) ```ebnf include ::= "include" ident+ | "omit" ( ident | instBinder )+ ``` `include` forces section variables into later theorems, even when only the proof uses them. `omit` removes them again. Example: ```lean section variable (n : Nat) (h : n = 0) include h theorem t : n = 0 := h end ``` Source: `Lean/Parser/Command.lean (include, omit)` ### 3.29 open ![Railroad diagram: open|550](open.svg) ```ebnf open ::= "open" openDecl ``` `open` makes the names in a namespace available in short form until the end of the current scope. Example: ```lean open Nat #check succ ``` Source: `Lean/Parser/Command.lean (open)` ### 3.30 Open declaration ![Railroad diagram: Open declaration|1332](openDecl.svg) ```ebnf openDecl ::= ident+ | ident "hiding" ident+ | ident "renaming" sepBy1(ident "→" | "->" ident, ",") | ident "(" ident+ ")" | "scoped" ident+ ``` There are five forms: open everything, hide some names, rename some names, open only the listed names, or activate only scoped notation and attributes. Example: ```lean section open Nat hiding succ end section open Nat renaming zero → z end section open Nat (pred) end section open scoped Nat end ``` Source: `Lean/Parser/Command.lean (openDecl)` ### 3.31 export ![Railroad diagram: export|982](export.svg) ```ebnf export ::= "export" ident "(" ident+ ")" ``` `export` creates aliases in the current namespace for the listed names, so that anyone who opens this namespace sees them too. Example: ```lean namespace B export Nat (succ) end B #check B.succ ``` Source: `Lean/Parser/Command.lean (export)` ### 3.32 mutual ![Railroad diagram: mutual|770](mutual.svg) ```ebnf mutual ::= "mutual" command+ "end" ``` `mutual` groups declarations that refer to each other. Example: ```lean mutual def isEven : Nat → Bool | 0 => true | n + 1 => isOdd n def isOdd : Nat → Bool | 0 => false | n + 1 => isEven n end ``` Source: `Lean/Parser/Command.lean (mutual)` ### 3.33 attribute ![Railroad diagram: attribute|1348](attribute.svg) ```ebnf attribute ::= "attribute" "[" sepBy1("-" ident | attrInstance, ",") "]" ident+ ``` `attribute` adds or removes attributes on declarations that already exist. A leading `-` removes an attribute. Example: ```lean theorem t (n : Nat) : n + 0 = n := rfl attribute [simp] t attribute [-simp] t ``` Source: `Lean/Parser/Command.lean (attribute)` ### 3.34 set_option ![Railroad diagram: set_option|928](set_option.svg) ```ebnf set_option ::= "set_option" ident "true" | "false" | strLit | numLit ``` `set_option` changes a named option for the current scope. The same keyword also exists as a term and a tactic, where it must be followed by `in`. Example: ```lean set_option pp.all false set_option maxRecDepth 1000 ``` Source: `Lean/Parser/Command.lean (set_option)` ### 3.35 Standalone deriving ![Railroad diagram: Standalone deriving|1820](deriving.svg) ```ebnf deriving ::= "deriving" "noncomputable"? "instance" sepBy1(<class name>, ",") "for" sepBy1(term, ",") ``` This form derives instances separately from the type declaration. Example: ```lean inductive Dir where | up | down deriving instance BEq, Repr for Dir ``` Source: `Lean/Parser/Command.lean (deriving)` ### 3.36 Information commands ![Railroad diagram: Information commands|1228](info.svg) ```ebnf info ::= "#check" | "#check_failure" | "#eval" | "#eval!" | "#reduce" | "#synth" term | "#print" ( "axioms" | "sig" | "equations" | "eqns" )? ident | strLit | "#guard" term | "#where" | "#version" | "#exit" ``` Commands that start with `#` report information in the editor and change nothing. `#exit` ends parsing of the file. `#guard_msgs` and similar test commands also belong to this family. Example: ```lean #check Nat.succ #eval 1 + 1 #reduce 2 + 2 #synth Inhabited Nat #print axioms Classical.em #guard 1 + 1 == 2 ``` Source: `Lean/Parser/Command.lean, Init/Tactics.lean` ### 3.37 Infix, prefix, and postfix notation ![Railroad diagram: Infix, prefix, and postfix notation|2020](mixfix.svg) ```ebnf mixfix ::= <declModifiers (doc, attrs)> ( "scoped" | "local" )? "prefix" | "infix" | "infixl" | "infixr" | "postfix" ":" precedence namedName? namedPrio? notationItem "=>" term ``` These commands add an operator. The `:precedence` part is required. `infixl` and `infixr` set associativity, and `infix` is non-associative. Example: ```lean infixl:65 " +++ " => Nat.add #eval 1 +++ 2 ``` Source: `Lean/Parser/Syntax.lean (mixfix)` ### 3.38 notation ![Railroad diagram: notation|2042](notation.svg) ```ebnf notation ::= <declModifiers (doc, attrs)> ( "scoped" | "local" )? "notation" ( ":" precedence )? namedName? namedPrio? notationItem* "=>" term ``` `notation` defines a mixfix pattern of atoms and variables, and each variable can have a precedence. Example: ```lean notation:65 a " plus " b:66 => Nat.add a b #eval 1 plus 2 ``` Source: `Lean/Parser/Syntax.lean (notation)` ### 3.39 syntax ![Railroad diagram: syntax|2000](syntax.svg) ```ebnf syntax ::= <declModifiers (doc, attrs)> ( "scoped" | "local" )? "syntax" ( ":" precedence )? namedName? namedPrio? stx+ ":" <category name> ``` `syntax` adds a parser rule to a category. Each new string atom becomes a reserved token, with one exception: the first atom of a rule stays usable as an identifier when the category has `both` or `symbol` behavior, as `tactic` does. Example: ```lean syntax "myterm" : term macro_rules | `(myterm) => `(1) #eval myterm ``` Source: `Lean/Parser/Syntax.lean (syntax)` ### 3.40 declare_syntax_cat ![Railroad diagram: declare_syntax_cat|2198](declare_syntax_cat.svg) ```ebnf declare_syntax_cat ::= docComment? "declare_syntax_cat" ident ( "(" "behavior" ":=" "both" | "symbol" ")" )? ``` This command creates a new parser category, for example for an embedded language. Example: ```lean declare_syntax_cat color syntax "red" : color ``` Source: `Lean/Parser/Syntax.lean (syntaxCat)` ### 3.41 macro ![Railroad diagram: macro|2055](macro.svg) ```ebnf macro ::= <declModifiers (doc, attrs)> ( "scoped" | "local" )? "macro" ( ":" precedence )? namedName? namedPrio? macroArg+ ":" <category name> "=>" term ``` `macro` is a shorthand that declares syntax and its expansion together. Example: ```lean macro "two" : term => `(2) #eval two ``` Source: `Lean/Parser/Syntax.lean (macro)` ### 3.42 macro_rules ![Railroad diagram: macro_rules|2200](macro_rules.svg) ```ebnf macro_rules ::= <declModifiers (doc, attrs)> ( "scoped" | "local" )? "macro_rules" <kind clause>? matchAlts ``` `macro_rules` adds expansion rules for existing syntax. Later rules are tried first, which is how `trivial` is extended. Example: ```lean syntax "three" : term macro_rules | `(three) => `(3) #eval three ``` Source: `Lean/Parser/Syntax.lean (macro_rules)` ### 3.43 elab ![Railroad diagram: elab|1958](elab.svg) ```ebnf elab ::= <declModifiers (doc, attrs)> ( "scoped" | "local" )? "elab" ( ":" precedence )? macroArg+ ":" <category name> ( "<=" ident )? "=>" term ``` `elab` works like `macro`, but its right-hand side runs elaborator code in a monad instead of producing syntax. Example: ```lean open Lean Elab Tactic in elab "my_trace" : tactic => do logInfo m!"goal: {← getMainTarget}" ``` Source: `Lean/Parser/Syntax.lean (elab)` ### 3.44 elab_rules ![Railroad diagram: elab_rules|2000](elab_rules.svg) ```ebnf elab_rules ::= <declModifiers (doc, attrs)> ( "scoped" | "local" )? "elab_rules" <kind clause>? ( ":" ident )? ( "<=" ident )? matchAlts ``` `elab_rules` adds elaboration rules for existing syntax, in the same way that `macro_rules` adds expansions. Example: ```lean open Lean Elab Tactic in syntax "hello_goal" : tactic open Lean Elab Tactic in elab_rules : tactic | `(tactic| hello_goal) => logInfo "hello" ``` Source: `Lean/Parser/Syntax.lean (elab_rules)` ## 4. Terms Terms are expressions, types, and proofs. Lean has one syntax for all three. The `term` category uses a Pratt parser, so operators are handled by precedence instead of by grammar rules. ### 4.1 Term overview ![Railroad diagram: Term overview|758](term.svg) ```ebnf term ::= <identifier or literal> | application | <binder form> | <let or have> | match | if | <show or suffices> | by | do | calc | <bracketed term> | <universe term> | <operator application> | hole ``` This overview groups the main forms. The `term` category is open, and libraries add many forms through `notation`, `syntax`, and `macro`. Example: ```lean example : Nat := let x := 1; if x = 1 then x + 1 else (fun y => y) 0 ``` Source: `Lean/Parser/Term.lean` ### 4.2 Function application ![Railroad diagram: Function application|1148](app.svg) ```ebnf app ::= term ( "(" ident ":=" term ")" | ".." | <term at max precedence> )+ ``` Application is written by juxtaposition, with whitespace before each argument. Each argument must be indented past the column where the command or tactic block started. A named argument is `(x := e)`, and `..` fills the remaining explicit arguments with holes. Example: ```lean #check Nat.add 1 2 #check Nat.le_trans (m := 1) example (h : 1 = 2 ∧ 3 = 4) : 1 = 2 := match h with | And.intro a .. => a ``` Source: `Lean/Parser/Term.lean (app, argument)` ### 4.3 Projection and generalized field notation ![Railroad diagram: Projection and generalized field notation|1232](proj.svg) ```ebnf proj ::= term (* no space *) "." (* no space *) <field index> | <field name> ``` `p.1` takes a numbered field, and `xs.length` calls a function in the namespace of the type of `xs`. When the term is a plain name, the dotted name is read as one identifier and resolved later. Example: ```lean example (h : 1 = 1 ∧ 2 = 2) : 2 = 2 := h.2 #eval [1, 2].length ``` Source: `Lean/Parser/Term.lean (proj)` ### 4.4 Dotted constructor shorthand ![Railroad diagram: Dotted constructor shorthand|605](dotIdent.svg) ```ebnf dotIdent ::= "." (* no space *) name ``` `.name` looks up a name in the namespace of the expected type, so `.zero` can stand for `Nat.zero`. Example: ```lean def z : Nat := .zero ``` Source: `Lean/Parser/Term.lean (dotIdent)` ### 4.5 Binder name ![Railroad diagram: Binder name|412](binderIdent.svg) ```ebnf binderIdent ::= ident | "_" ``` A binder name is an identifier or `_`, which leaves the bound value unnamed. Example: ```lean def k (_ : Nat) := 0 ``` Source: `Lean/Parser/Term/Basic.lean (binderIdent)` ### 4.6 Bracketed binder ![Railroad diagram: Bracketed binder|735](bracketedBinder.svg) ```ebnf bracketedBinder ::= explicitBinder | strictImplicitBinder | implicitBinder | instBinder ``` The bracket style sets how the argument is supplied: by the caller, by unification, or by type-class search. Example: ```lean def f {α : Type} [Inhabited α] (n : Nat) : α := default ``` Source: `Lean/Parser/Term/Basic.lean (bracketedBinder)` ### 4.7 Explicit binder ![Railroad diagram: Explicit binder|1818](explicitBinder.svg) ```ebnf explicitBinder ::= "(" binderIdent+ ( ":" term )? ( ":=" term | ":=" "by" tacticSeq )? ")" ``` The caller supplies an explicit argument. A default value or a default tactic makes it optional at the call site. Example: ```lean def inc (n : Nat) (by_ : Nat := 1) : Nat := n + by_ #eval inc 1 ``` Source: `Lean/Parser/Term/Basic.lean (explicitBinder)` ### 4.8 Implicit binder ![Railroad diagram: Implicit binder|1082](implicitBinder.svg) ```ebnf implicitBinder ::= "{" binderIdent+ ( ":" term )? "}" ``` Lean fills an implicit argument by unification. Use `@f` to supply every argument explicitly. Example: ```lean def myId {α : Type} (a : α) := a #check @myId ``` Source: `Lean/Parser/Term/Basic.lean (implicitBinder)` ### 4.9 Strict-implicit binder ![Railroad diagram: Strict-implicit binder|1325](strictImplicitBinder.svg) ```ebnf strictImplicitBinder ::= "⦃" | "{{" binderIdent+ ( ":" term )? "⦄" | "}}" ``` A strict-implicit argument is filled only when a later explicit argument is also supplied. Example: ```lean def s ⦃α : Type⦄ (a : α) := a ``` Source: `Lean/Parser/Term/Basic.lean (strictImplicitBinder)` ### 4.10 Instance binder ![Railroad diagram: Instance binder|905](instBinder.svg) ```ebnf instBinder ::= "[" ( ident ":" )? term "]" ``` Lean finds an instance argument by type-class search. The name is optional. Example: ```lean def d [inst : Inhabited Nat] := inst.default ``` Source: `Lean/Parser/Term/Basic.lean (instBinder)` ### 4.11 Universal quantifier ![Railroad diagram: Universal quantifier|1648](forall.svg) ```ebnf forall ::= "∀" | "forall" ( binderIdent | bracketedBinder )+ ( ":" term )? "," term ``` `∀` binds names over a body, and the body extends as far as possible. Binder predicates such as `∀ x > 0, p x` and `∀ x ∈ s, p x` are also accepted through the `binderPred` category. Example: ```lean example : ∀ n : Nat, n = n := fun _ => rfl example : ∀ x > 0, x ≠ 0 := by omega ``` Source: `Lean/Parser/Term.lean (forall), Init/BinderPredicates.lean` ### 4.12 Existential quantifier ![Railroad diagram: Existential quantifier|1725](exists.svg) ```ebnf exists ::= "∃" | "exists" ( "(" binderIdent+ ":" term ")" )+ | binderIdent+ ( ":" term )? "," term ``` `∃` accepts either bracketed groups of binders or a plain list of names with one optional type. Example: ```lean example : ∃ x : Nat, x = 1 := ⟨1, rfl⟩ example : exists x : Nat, x = 1 := ⟨1, rfl⟩ example : ∃ (a b : Nat), a = b := ⟨0, 0, rfl⟩ ``` Source: `Init/NotationExtra.lean (explicitBinders)` ### 4.13 Function type ![Railroad diagram: Function type|1028](arrow.svg) ```ebnf arrow ::= term "→" | "->" term | bracketedBinder "→" | "->" term ``` `→` is right-associative at precedence 25. The second form names the argument, which gives a dependent function type. Example: ```lean def f : Nat → Nat := id def g : (n : Nat) → n = n := fun _ => rfl ``` Source: `Lean/Parser/Term.lean (arrow, depArrow)` ### 4.14 Function abstraction ![Railroad diagram: Function abstraction|1575](fun.svg) ```ebnf fun ::= "fun" | "λ" funBinder+ ( ":" term )? "=>" | "↦" term | matchAlts ``` `fun` makes a function. Its binders can be patterns. It can also be followed directly by `|` alternatives. Example: ```lean def f := fun (x : Nat) => x + 1 def g := fun ((a, b) : Nat × Nat) ↦ a + b def h : Nat → Bool := fun | 0 => true | _ => false ``` Source: `Lean/Parser/Term.lean (fun, basicFun)` ### 4.15 let and have ![Railroad diagram: let and have|1405](let.svg) ```ebnf let ::= "let" | "have" | "letI" | "haveI" letConfig letDecl ";" | (* new line *) term ``` `let` binds a value that can be unfolded. `have` hides the value and keeps only its type, which suits proofs. The body follows after a semicolon or on a new line. Example: ```lean example : Nat := let x := 1 have h : x = x := rfl x + 1 ``` Source: `Lean/Parser/Term.lean (let, have)` ### 4.16 Let declaration ![Railroad diagram: Let declaration|2098](letDecl.svg) ```ebnf letDecl ::= binderIdent | (* omitted: name is this *) ( binderIdent | bracketedBinder )* ( ":" term )? ":=" term | term ( ":" term )? ":=" term | binderIdent ( binderIdent | bracketedBinder )* ( ":" term )? matchAlts ``` A let declaration binds a name, destructures a pattern, or defines a function by equations. A `have` with no name binds the result to `this`. Example: ```lean example (p : Nat × Nat) : Nat := let f (x : Nat) := x + 1 let (a, _) := p f a example : 1 = 1 := by have : 1 = 1 := rfl exact this ``` Source: `Lean/Parser/Term.lean (letDecl, letIdDecl, letPatDecl, letEqnsDecl)` ### 4.17 let rec ![Railroad diagram: let rec|1248](letrec.svg) ```ebnf letrec ::= "let" "rec" sepBy1(letRecDecl, ",") ";" | (* new line *) term ``` `let rec` defines a local recursive function. `rec` is a contextual keyword here, so it can still be used as a normal name elsewhere. Example: ```lean def f (n : Nat) : Nat := let rec go : Nat → Nat | 0 => 0 | k + 1 => go k go n ``` Source: `Lean/Parser/Term.lean (letrec)` ### 4.18 match ![Railroad diagram: match|1472](match.svg) ```ebnf match ::= "match" <generalizing clause>? <motive clause>? sepBy1(( binderIdent ":" )? term, ",") "with" matchAlts ``` `match` inspects one or more terms at once. Writing `h : e` records the equation between the term and the pattern in each branch. Example: ```lean def f (n : Nat) : Bool := match h : n with | 0 => true | _ + 1 => false ``` Source: `Lean/Parser/Term.lean (match)` ### 4.19 Match alternatives ![Railroad diagram: Match alternatives|1085](matchAlts.svg) ```ebnf matchAlts ::= ( "|" sepBy1(sepBy1(term, ","), "|") "=>" <right-hand side> )+ ``` Each alternative starts with `|`. Several pattern groups can share a right-hand side. The right-hand side must start at or beyond the column of the `|`. Example: ```lean def f : Nat → Nat → Nat | 0, _ | _, 0 => 0 | a + 1, b + 1 => a + b ``` Source: `Lean/Parser/Term.lean (matchAlt, matchAlts)` ### 4.20 if ![Railroad diagram: if|1652](if.svg) ```ebnf if ::= "if" term | binderIdent ":" term | "let" term ":=" term "then" term "else" term ``` `if` chooses a branch on a decidable proposition. `if h : c` names the proof in each branch, and `if let` matches a pattern. In a term, `else` is required. Example: ```lean def f (n : Nat) := if n = 0 then 1 else 2 def g (xs : List Nat) : Nat := if h : xs ≠ [] then xs.head h else 0 def k (o : Option Nat) := if let some x := o then x else 0 ``` Source: `Init/Notation.lean (termIfThenElse, termDepIfThenElse, termIfLet)` ### 4.21 show ![Railroad diagram: show|970](show.svg) ```ebnf show ::= "show" term "from" term | "by" tacticSeq ``` As a term, `show t by ...` states the type of the proof that follows. The tactic `show` takes only the term. Example: ```lean example : 1 = 1 := show 1 = 1 by rfl ``` Source: `Lean/Parser/Term.lean (show)` ### 4.22 suffices ![Railroad diagram: suffices|2060](suffices.svg) ```ebnf suffices ::= "suffices" ( binderIdent ":" )? term "from" term | "by" tacticSeq ";" | (* new line *) term ``` `suffices h : t from e` states that `t` is enough to finish the proof. The term after it then proves `t`. Example: ```lean example (p : Prop) (hp : p) : p ∧ p := suffices h : p from ⟨h, h⟩ hp ``` Source: `Lean/Parser/Term.lean (suffices)` ### 4.23 by ![Railroad diagram: by|528](by.svg) ```ebnf by ::= "by" tacticSeq ``` `by` switches from term mode to tactic mode. The tactics must be indented past the saved position, and the block ends when the indentation returns. Example: ```lean theorem t : 1 + 1 = 2 := by rfl ``` Source: `Lean/Parser/Term.lean (byTactic)` ### 4.24 calc ![Railroad diagram: calc|1925](calc.svg) ```ebnf calc ::= "calc" term ( ":=" term )? ( (* new line, same column *) term ":=" term )* ``` `calc` chains relations. In the first step the proof can be left out, and `_` stands for the previous right-hand side in later steps. `calc` works as both a term and a tactic. Example: ```lean example (a b c : Nat) (h₁ : a = b) (h₂ : b = c) : a = c := calc a = b := h₁ _ = c := h₂ ``` Source: `Init/NotationExtra.lean (calcSteps)` ### 4.25 Anonymous constructor ![Railroad diagram: Anonymous constructor|655](anonCtor.svg) ```ebnf anonCtor ::= "⟨" sepBy(term, ",") "⟩" ``` `⟨a, b⟩` builds a value of the expected structure type. Extra arguments nest to the right. Example: ```lean example : 1 = 1 ∧ 2 = 2 := ⟨rfl, rfl⟩ ``` Source: `Lean/Parser/Term.lean (anonymousCtor)` ### 4.26 Parentheses, tuples, and type ascription ![Railroad diagram: Parentheses, tuples, and type ascription|1082](paren.svg) ```ebnf paren ::= "(" ( term | term "," sepBy1(term, ",") | term ":" term? )? ")" ``` Parentheses group a term. A comma makes a tuple, `(e : T)` states a type, and `()` is the unit value. Example: ```lean #eval (1 + 2) * 3 #eval (1, 2, 3) #eval (1 : Int) #eval () ``` Source: `Lean/Parser/Term.lean (paren, tuple, typeAscription)` ### 4.27 Structure instance ![Railroad diagram: Structure instance|1990](structInst.svg) ```ebnf structInst ::= "{" ( sepBy1(term, ",") "with" )? sepBy(structInstField, "," | (* new line *)) ".."? ( ":" term )? "}" ``` A structure instance fills named fields. `{ s with x := 1 }` copies `s` and changes one field. `..` leaves the remaining fields as holes. Example: ```lean structure P where x : Nat y : Nat def p : P := { x := 1, y := 2 } def q : P := { p with x := 3 } ``` Source: `Lean/Parser/Term.lean (structInst)` ### 4.28 Universe terms ![Railroad diagram: Universe terms|685](universeTerm.svg) ```ebnf universeTerm ::= "Prop" | "Type" level? | "Sort" level? ``` `Prop`, `Type`, and `Sort` name universes. A level, when present, must be separated by a space. Example: ```lean universe u #check Prop #check Type u #check Sort (u + 1) ``` Source: `Lean/Parser/Term.lean (type, sort, prop)` ### 4.29 Universe level ![Railroad diagram: Universe level|735](level.svg) ```ebnf level ::= numLit | ident | "_" | "(" level ")" | "max" level+ | "imax" level+ | level "+" numLit ``` Levels have their own small grammar. `max` and `imax` are contextual: they are special only inside a level. Example: ```lean universe u v #check Type (max u v) #check Sort (imax u v + 1) ``` Source: `Lean/Parser/Level.lean` ### 4.30 Holes and placeholders ![Railroad diagram: Holes and placeholders|620](hole.svg) ```ebnf hole ::= "_" | "?" ident | "_" | "sorry" ``` `_` asks Lean to infer a term. `?x` and `?_` create a goal to fill later, and they are used with `refine`. `sorry` closes any goal, and Lean reports a warning. Example: ```lean example : 1 = 1 := by refine Eq.trans ?_ rfl rfl example : 2 = 2 := sorry ``` Source: `Lean/Parser/Term/Basic.lean (hole, syntheticHole), Term.lean (sorry)` ### 4.31 Explicit application marker and other prefixes ![Railroad diagram: Explicit application marker and other prefixes|885](explicit.svg) ```ebnf explicit ::= "@" <term at max precedence> | ".(" term ")" | "<-" doElem | "←" doElem ``` `@f` turns off implicit arguments. `.(e)` marks an inaccessible pattern. `← e` runs a nested monadic action inside a `do` block. Example: ```lean #check @id Nat 1 def f : IO Nat := do return (← pure 1) + 1 ``` Source: `Lean/Parser/Term.lean (explicit, inaccessible), Do.lean (nestedAction)` ### 4.32 Operator application ![Railroad diagram: Operator application|950](operators.svg) ```ebnf operators ::= <prefix operator> term | term <infix operator> term | term <postfix operator> ``` Operators are not fixed grammar rules. They are ordinary entries in the `term` category, added with `notation`, and precedence decides how they group. See the operator table in `Lean4-syntax-categories.md`. Example: ```lean #eval 1 + 2 * 3 #check ¬ True ∧ False ``` Source: `Init/Notation.lean, Init/Core.lean` ## 5. do notation A `do` block sequences monadic actions. It has its own syntax category, `doElem`. ### 5.1 do block ![Railroad diagram: do block|1032](doSeq.svg) ```ebnf doSeq ::= "do" ( doElem ";"? )+ | "{" ( doElem ";"? )+ "}" ``` Elements are written one per line at the same column, or inside braces. Example: ```lean def main : IO Unit := do IO.println "a" IO.println "b" ``` Source: `Lean/Parser/Do.lean (do, doSeq)` ### 5.2 do element overview ![Railroad diagram: do element overview|520](doElem.svg) ```ebnf doElem ::= doLet | doReassign | doHave | doIf | doUnless | doFor | doWhile | doRepeat | doMatch | doTry | doReturn | "break" | "continue" | doNested | term ``` Elements include bindings, control flow, and plain terms, where a plain term is run as an action. Example: ```lean def f : IO Nat := do let mut s := 0 for i in [1, 2, 3] do if i == 2 then continue s := s + i return s ``` Source: `Lean/Parser/Do.lean` ### 5.3 let in do ![Railroad diagram: let in do|1832](doLet.svg) ```ebnf doLet ::= "let" "mut"? letConfig letDecl | ident | term ( ":" term )? "←" | "<-" doElem ( "|" doSeq )? ``` `let x := e` binds a pure value, and `let x ← e` runs an action. `mut` allows reassignment. An alternative after `|` handles a failed pattern match. Example: ```lean def f (o : Option Nat) : IO Nat := do let mut a := 1 let b ← pure 2 let some c := o | return 0 a := a + b + c return a ``` Source: `Lean/Parser/Do.lean (doLet, doLetArrow, doLetElse)` ### 5.4 if in do ![Railroad diagram: if in do|1755](doIf.svg) ```ebnf doIf ::= "if" doIfCond "then" doSeq ( "else" "if" doIfCond "then" doSeq )* ( "else" doSeq )? ``` Inside `do`, `if` can omit its `else`. The condition can also be `let pat ← e`, which runs an action and tests its result. Example: ```lean def f (n : Nat) : IO Unit := do if n = 0 then IO.println "zero" else if n = 1 then IO.println "one" ``` Source: `Lean/Parser/Do.lean (doIf)` ### 5.5 unless ![Railroad diagram: unless|828](doUnless.svg) ```ebnf doUnless ::= "unless" term "do" doSeq ``` `unless c do s` runs `s` when `c` is false. Example: ```lean def f (n : Nat) : IO Unit := do unless n = 2 do IO.println "not two" ``` Source: `Lean/Parser/Do.lean (doUnless)` ### 5.6 for ![Railroad diagram: for|1620](doFor.svg) ```ebnf doFor ::= "for" sepBy1(( ident ":" )? term "in" term, ",") <invariant clause>? <decreasing clause>? "do" doSeq ``` `for` iterates over a collection. Several comma-separated clauses advance together and stop with the shortest. `h : x in xs` names the membership proof. Example: ```lean def f : IO Unit := do for x in [1, 2], y in [3, 4] do IO.println (x + y) ``` Source: `Lean/Parser/Do.lean (doFor)` ### 5.7 while, repeat, and until ![Railroad diagram: while, repeat, and until|1090](doLoop.svg) ```ebnf doLoop ::= "while" doIfCond "do" doSeq | "repeat" doSeq ( "until" term )? ``` `while` tests before each iteration. `repeat` loops until `break`, or until the trailing `until` condition is true. Example: ```lean def f : IO Unit := do let mut n := 3 while n > 0 do n := n - 1 repeat n := n + 1 until n = 2 ``` Source: `Lean/Parser/Do.lean (doWhile, doRepeat, doRepeatUntil)` ### 5.8 match in do ![Railroad diagram: match in do|1532](doMatch.svg) ```ebnf doMatch ::= "match" sepBy1(matchDiscr, ",") "with" ( "|" sepBy1(term, ",") "=>" doSeq )+ ``` This is the same as term-level `match`, except that each right-hand side is a `do` sequence. Example: ```lean def f (n : Nat) : IO Unit := do match n with | 0 => IO.println "zero" | _ => pure () ``` Source: `Lean/Parser/Do.lean (doMatch)` ### 5.9 try, catch, and finally ![Railroad diagram: try, catch, and finally|1682](doTry.svg) ```ebnf doTry ::= "try" doSeq ( "catch" binderIdent ( ":" term )? "=>" doSeq | <match alternatives> )* ( "finally" doSeq )? ``` `try` runs a sequence, `catch` handles errors, and `finally` always runs. Example: ```lean def f : IO Unit := do try throw (IO.userError "x") catch e => IO.println e finally IO.println "done" ``` Source: `Lean/Parser/Do.lean (doTry, doCatch, doFinally)` ### 5.10 return ![Railroad diagram: return|830](doReturn.svg) ```ebnf doReturn ::= "return" ( (* same line *) term )? ``` `return` exits the whole `do` block with a value, and the value must begin on the same line. Example: ```lean def f : IO Nat := do return 1 ``` Source: `Lean/Parser/Do.lean (doReturn)` ## 6. Tactics Tactic mode is entered with `by`. The `tactic` category is open, and most tactic names are not reserved words. ### 6.1 Tactic sequence ![Railroad diagram: Tactic sequence|890](tacticSeq.svg) ```ebnf tacticSeq ::= sepBy1(tactic, ";" | (* new line, same column *)) | "{" sepBy(tactic, ";" | (* new line *)) "}" ``` Tactics run in order, each on its own line at the same column or separated by `;`. A trailing `;` is allowed. A sequence can also be wrapped in braces. Example: ```lean example : 1 = 1 ∧ 2 = 2 := by constructor; rfl rfl ``` Source: `Lean/Parser/Term/Basic.lean (tacticSeq)` ### 6.2 Tactic overview ![Railroad diagram: Tactic overview|822](tactic.svg) ```ebnf tactic ::= <structuring tactic> | <goal-closing tactic> | <introduction tactic> | <rewriting tactic> | <case-analysis tactic> | <forward-reasoning tactic> | <automation tactic> | tactic "<;>" tactic ``` This overview groups tactics by purpose. `t <;> s` runs `s` on every goal that `t` produces. `Lean4-syntax-categories.md` has the full list by purpose. Example: ```lean example (p q : Prop) (hp : p) (hq : q) : p ∧ q := by constructor <;> assumption ``` Source: `Init/Tactics.lean` ### 6.3 Structuring tactics ![Railroad diagram: Structuring tactics|1470](structuring.svg) ```ebnf structuring ::= "·" | "." tacticSeq | "(" tacticSeq ")" | "case" sepBy1(tag binderIdent*, "|") "=>" tacticSeq | "next" binderIdent* "=>" tacticSeq | "all_goals" | "any_goals" | "focus" | "try" | "repeat" tacticSeq | "first" ( "|" tacticSeq )+ ``` These tactics organize a proof. `·` focuses on the main goal and fails if the block leaves it open. `case` selects a goal by tag. `first` tries alternatives in order. Example: ```lean example : 1 = 1 ∧ 2 = 2 := by constructor · rfl · first | omega | rfl ``` Source: `Init/Tactics.lean (case, next, allGoals, first, try, repeat)` ### 6.4 intro and intros ![Railroad diagram: intro and intros|1122](intro.svg) ```ebnf intro ::= "intro" <term at max precedence>* | "intro" matchAlts | "intros" ( ident | "_" )* ``` `intro` moves a hypothesis from the goal into the context. An argument can be a pattern, so `intro ⟨a, b⟩` splits a conjunction. Example: ```lean example : ∀ n : Nat, n = 0 → n = 0 := by intro n h exact h ``` Source: `Init/Tactics.lean (intro, intros), Lean/Parser/Tactic.lean (introMatch)` ### 6.5 exact, apply, and refine ![Railroad diagram: exact, apply, and refine|692](exact.svg) ```ebnf exact ::= "exact" | "apply" | "refine" | "refine'" | "specialize" term ``` `exact` closes the goal with a term. `apply` matches the conclusion and leaves the premises as new goals. `refine` is like `exact` but allows `?_` holes. `specialize` instantiates a hypothesis. Example: ```lean example (p q : Prop) (f : p → q) (hp : p) : q := by apply f exact hp ``` Source: `Init/Tactics.lean (apply, exact, refine, specialize)` ### 6.6 rw and rewrite ![Railroad diagram: rw and rewrite|1955](rw.svg) ```ebnf rw ::= "rw" | "rewrite" optConfig "[" sepBy(( "←" | "<-" )? term, ",") "]" location? ``` `rw` rewrites using equations from left to right, and `←` reverses a rule. `rw` also tries `rfl` afterwards, while `rewrite` does not. Example: ```lean example (a b : Nat) (h : a = b) : b = a := by rw [← h] ``` Source: `Init/Tactics.lean (rwRule, rwRuleSeq, rewriteSeq, rwSeq)` ### 6.7 Location ![Railroad diagram: Location|918](location.svg) ```ebnf location ::= "at" "*" | ( hypothesis | "⊢" | "|" (* no space *) "-" )+ ``` `at` chooses where a tactic acts: on all hypotheses and the goal (`*`), on named hypotheses, or on the goal (`⊢` or `|-`). Example: ```lean example (a : Nat) (h : a + 0 = 1) : a = 1 := by simp at h ⊢ exact h ``` Source: `Init/Tactics.lean (location)` ### 6.8 simp ![Railroad diagram: simp|1342](simp.svg) ```ebnf simp ::= "simp" optConfig discharger? "only"? ( "[" sepBy(simpArg, ",") "]" )? location? ``` `simp` rewrites with lemmas tagged `@[simp]`. `only` restricts it to the listed lemmas. `only` is contextual, so it is not a reserved word. Example: ```lean example (l : List Nat) : (l ++ []).length = l.length := by simp only [List.append_nil] ``` Source: `Init/Tactics.lean (simp)` ### 6.9 simp argument ![Railroad diagram: simp argument|1028](simpArg.svg) ```ebnf simpArg ::= "*" | "-" <term at max precedence> | ( "↓" | "↑" )? ( "←" | "<-" )? term ``` `*` adds every hypothesis, `-foo` removes a lemma, `←` uses a lemma backwards, and `↓` or `↑` sets when it fires. Example: ```lean example (a b : Nat) (h : a = b) : a + 0 = b := by simp [*] ``` Source: `Init/Tactics.lean (simpLemma, simpErase, simpStar)` ### 6.10 Tactic configuration ![Railroad diagram: Tactic configuration|1075](optConfig.svg) ```ebnf optConfig ::= ( "+" (* no space *) ident | "-" (* no space *) ident | "(" ident ":=" term ")" )* ``` Many tactics accept configuration items. `+opt` turns an option on, `-opt` turns it off, and `(opt := v)` sets a value. Example: ```lean example : 1 = 1 := by simp +decide example : 2 = 2 := by simp (config := {}) -zeta ``` Source: `Lean/Parser/Term.lean (optConfig, configItem)` ### 6.11 induction and cases ![Railroad diagram: induction and cases|1738](induction.svg) ```ebnf induction ::= "induction" | "cases" sepBy1(elimTarget, ",") ( "using" term )? ( "generalizing" <term at max precedence>+ )? inductionAlts? ``` `induction` adds an induction hypothesis and `cases` does not. `generalizing` is available only with `induction`, and it makes the induction hypothesis stronger. `n : e` names an equation for the target. Example: ```lean example (n : Nat) : 0 + n = n := by induction n with | zero => rfl | succ k ih => omega ``` Source: `Init/Tactics.lean (induction, cases, elimTarget)` ### 6.12 Induction alternatives ![Railroad diagram: Induction alternatives|1455](inductionAlts.svg) ```ebnf inductionAlts ::= "with" tactic? ( inductionAltLHS+ ( "=>" "_" | "?" ident | tacticSeq )? )* ``` Each `inductionAltLHS` is `|`, a constructor name or `_`, and names for the new variables. Several `|` heads can share one body, and `| _ =>` matches the remaining cases. Example: ```lean example (n : Nat) : n = n := by cases n with | zero | succ _ => rfl ``` Source: `Init/Tactics.lean (inductionAltLHS, inductionAlt, inductionAlts)` ### 6.13 rcases, obtain, and rintro ![Railroad diagram: rcases, obtain, and rintro|1705](rcases.svg) ```ebnf rcases ::= "rcases" sepBy(elimTarget, ",") ( "with" rcasesPatLo )? | "obtain" rcasesPatMed? ( ":" term )? ( ":=" sepBy1(term, ",") )? | "rintro" rintroPat+ ( ":" term )? ``` These tactics destructure hypotheses with patterns. `obtain` has the form of a pattern, a type, and a proof, and `rintro` is `intro` combined with patterns. Example: ```lean example (p q : Prop) (h : p ∧ q) : q := by obtain ⟨_, hq⟩ := h exact hq example (p q : Prop) : p ∧ q → q := by rintro ⟨_, hq⟩ exact hq ``` Source: `Init/RCases.lean` ### 6.14 rcases pattern ![Railroad diagram: rcases pattern|905](rcasesPat.svg) ```ebnf rcasesPat ::= ident | "_" | "-" | "@" (* no space *) rcasesPat | "⟨" sepBy(rcasesPatLo, ",") "⟩" | "(" rcasesPatLo ")" | rcasesPat "|" rcasesPat ``` `⟨a, b⟩` splits a product, `a | b` splits a sum, `_` keeps a value without naming it, `-` clears it, and `rfl` substitutes an equation. In a `rcasesPatLo`, a pattern can be followed by `: type`. Example: ```lean example (p q : Prop) (h : p ∨ q) : q ∨ p := by rcases h with hp | hq · exact Or.inr hp · exact Or.inl hq ``` Source: `Init/RCases.lean (rcasesPat, rcasesPatMed, rcasesPatLo)` ### 6.15 have, show, and calc as tactics ![Railroad diagram: have, show, and calc as tactics|1070](haveTactic.svg) ```ebnf haveTactic ::= "have" | "let" | "replace" letConfig letDecl | "show" term | "calc" <calc steps> ``` `have` adds a fact, `show` restates the goal, and `calc` proves the goal by a chain of relations. They are reserved words because they also exist as terms. Example: ```lean example (a : Nat) (h : a = 1) : a + 0 = 1 := by have h2 : a + 0 = a := rfl show a + 0 = 1 omega ``` Source: `Init/Tactics.lean, Init/NotationExtra.lean` ### 6.16 match as a tactic ![Railroad diagram: match as a tactic|1740](matchTactic.svg) ```ebnf matchTactic ::= "match" sepBy1(matchDiscr, ",") "with" ( "|" sepBy1(term, ",") "=>" "_" | "?" ident | tacticSeq )+ ``` In tactic mode, each right-hand side of `match` is a tactic sequence or a hole. Example: ```lean example (n : Nat) : n = n := by match n with | 0 => rfl | _ + 1 => rfl ``` Source: `Lean/Parser/Tactic.lean (match)`