Appendix B. Extending syntax without changing the logic
Lean’s notation is extensible. An application can introduce a small surface language that expands into ordinary Lean expressions. Introduce notation when readers already know the concept and the shorthand helps them read the code.
Begin with a function
def twiceValue (n : Nat) : Nat := n + n
syntax "twice[" term "]" : term
macro_rules
| `(twice[$value]) => `(twiceValue $value)
example : twice[7] = 14 := by rfl
The syntax declaration tells the parser how to recognise the new form. The macro matches the new form and builds replacement syntax. The backtick introduces a syntax quotation, and $value inserts the matched term into the replacement.
After expansion, the elaborator checks the resulting function call. Proofs about the expression use the existing definition and Lean’s logic.
Know the layers
The parser recognises the written structure, and macros transform syntax. The elaborator uses expected types, inference, and the environment to turn the resulting syntax into typed core expressions.
Tactics construct proof terms by working on goals. The kernel checks the final expressions.
For a notation that simply abbreviates an expression, a macro may be enough. A construct whose interpretation depends on the inferred type may need an elaborator. A proof procedure may need tactic code that inspects goals and constructs evidence.
Preserve ordinary APIs
Keep the underlying function available and documented. It is easier to search for a named declaration, inspect its type, and state a theorem about it than to debug a large expansion with no stable API. Use local or scoped notation when its interpretation belongs to one domain.
Macros use hygiene mechanisms to avoid accidentally capturing identifiers from their expansion context. Keep hygiene enabled when writing examples. When a macro needs to bind names or generate declarations, read the reference material on hygiene and elaboration before extending it.
The account project uses ordinary functions to express its operations. In libraries with custom notation, follow the expansion to find the underlying definitions.
Practice
Add an afterFee[amount] notation that expands into an ordinary fee function call. Prove a concrete example by reduction, then inspect the function’s type independently of the notation. Use the underlying function’s definition to justify the proof.