## 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.

- 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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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

```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)`