Skip to content

About

A community style guide for writing programs, libraries and tools in Lean 4 (draft)

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

 

History

16 Commits

Folders and files

Repository files navigation

A Lean Style Guide for Software

Community draft, October 2026.

This guide describes how to write programs, libraries and tools in Lean 4, focusing on general-purpose software, not math.

It's a community project, not an official document of the Lean FRO or of Mathlib.

Main resources used here are Lean's own style guide and naming conventions for the standard library. Some rules were borrowed from other language ecosystems where they make sense for Lean, e.g Haskell, OCaml

Guiding principles

Rules

"Use", "Write" and "Don't" mean always, "Prefer" and "Avoid" mean usually, and "Consider" means it's often worth it. Once Lean's official formatter is released (FRO roadmap), its output takes precedence over the layout rules.

  • Use a structure for a value with several parts and an inductive for alternatives (data-structure-inductive).
  • Define structures with named fields instead of passing tuples around (data-own-types).
  • Wrap a primitive in a single-field structure when its values must not be mixed with others, such as IDs (data-wrappers).
  • Check a value once where it enters the program, and pass a type that carries the check (data-boundary).
  • Use abbrev for exact synonyms, structure for new domain types, and never def for type synonyms (data-abbrev).
  • Use extends only when one structure clearly "is a" kind of another (data-extends).
  • Avoid indexed families in APIs, except in code that resembles a typed language (data-indexed-families).
  • Derive instances instead of writing them, and derive Repr for every data type (data-deriving).
  • Build structures with named fields unless the order of the fields is obvious (data-constructors).
  • Update a structure with { s with field := value } instead of copying fields by hand (data-update).
  • Keep program logic in pure functions and IO in a thin outer layer (effects-pure-core).
  • Pass shared configuration through ReaderT, and define the application's monad with abbrev (effects-config).
  • Put acquire and release in a with… helper built with try … finally (effects-resources).
  • Use IO for sequential code, Task for parallel computation and Async for programs that mostly wait on I/O (effects-concurrency).
  • Don't #eval actions with side effects in library files (effects-eval).
  • Handle special cases first and return early, so the main path isn't nested (do-early-return).
  • Unwrap an Option with let some x := e | fallback when the failure case is short (do-let-else).
  • Use let mut and for when they're clearer than a fold or a state monad (do-mutation).
  • Use modify to update state, instead of get followed by set (effects-modify).
  • Use (← action) inline for a result you use once, and let x ← action otherwise (do-nested-actions).
  • End do blocks with return x, and use pure x outside them (do-return).
  • Return Option for one obvious failure and Except when the caller needs to know which failure happened (errors-option-except).
  • Give a library an inductive error type with a ToString instance (errors-types).
  • In IO code, throw errors instead of returning default values (errors-io).
  • Add context to an error at the level that knows it, such as the file being read (errors-context).
  • Don't replace a missing value with a default when its absence can mean that the program is misconfigured (errors-defaults).
  • Use panic! and ! functions only when essential: for bugs, where you can't pass a proof instead, and never to reject bad input (errors-panics).
  • Say in the docstring how a function fails when its type doesn't already say so (errors-document).
  • Log where the code makes a decision that its result can't express (logging-decisions).
  • Record the value that decided the branch, not just the outcome (logging-values).
  • Log what was asked for, since a span records only the route (logging-requests).
  • Don't log ordinary success when a span already records the request (logging-success).
  • Make public only what callers need (api-surface).
  • Use the module system in libraries, with a plain public section in program files (api-modules).
  • Mark helpers private, or put them in an Internal namespace (api-private).
  • Mark a declaration protected if its short name would clash after open (api-protected).
  • Deprecate a public declaration before you rename, remove or change it, and note every such change in the changelog (api-deprecation).
  • Avoid variable in program code (api-variable).
  • Use UpperCamelCase for types and namespaces, lowerCamelCase for functions, values and fields, and snake_case for theorems (naming-case).
  • Put the functions about a type in the namespace named after the type (naming-namespaces).
  • Name Bool functions as questions, as in isEmpty, and Prop predicates with Is, as in IsSorted (naming-predicates).
  • Mark failure in the name with ? for an Option, ! for a panic and D for a default (naming-failure).
  • Name conversions toX and ofX, never fromX (naming-conversions).
  • Add M to the name of a variant that runs in a monad, as in mapM and forM (naming-monadic).
  • Don't name a variant of a public function by adding ' (naming-primes).
  • Write acronyms of four or more letters as words, as in Json, and shorter ones in one case, as in IO (naming-acronyms).
  • Use short local names only by convention, such as xs for arrays, acc for accumulators and i for indices (naming-locals).
  • Leave instances anonymous (naming-instances).
  • Name packages in lowercase and modules in UpperCamelCase, with file paths that match (naming-files).
  • Define a type class only when several types will have instances and code is generic over them (classes-when).
  • Ask for the weakest class a function needs, so it works for more types (classes-weakest).
  • Make BEq agree with Hashable, and Ord with LT and LE (classes-consistent).
  • Add a coercion only when every source value has an obvious counterpart in the target type (classes-coercions).
  • For a recursive type, write the recursive function in the type's namespace and have the instance call it (classes-recursive).
  • Write instances with where, one method per line (classes-where).
  • Use Array for sequences you build, index or update, and List for small ones you take apart from the front (collections-array).
  • Keep a single reference to an array you're updating, so Lean can update it in place (collections-sharing).
  • Loop over elements rather than indices, and prefer xs[i]? or a proof to xs[i]! (collections-iterate).
  • Use Std.HashMap for lookups and Std.TreeMap when key order matters (collections-maps).
  • Prefer structural recursion, and give a measure with termination_by when the recursion isn't structural (recursion-structural).
  • Mark a function partial only when it might not terminate, or nobody knows whether it does (recursion-partial).
  • Use for, while and repeat instead of recursive helpers that only loop (recursion-loops).
  • Use loops or accumulators for recursion over large inputs (recursion-deep).
  • Prove claims as theorems by default, and fall back to property tests and examples only when a proof doesn't work out (proofs-first).
  • Keep the simple version of an optimized function as its specification, and prove that the two agree (proofs-spec).
  • Time-box a proof, and if it fails, write a property test with a comment that records the obstacle (proofs-timebox).
  • When a module with property tests changes, check whether each property can now be proved (proofs-recheck).
  • Keep short lemmas next to their definitions, and move longer proofs to their own module (proofs-location).
  • Prefer grind, omega and simp to long manual proofs, and squeeze simp calls that aren't the last step (proofs-automation).
  • Name a theorem after what it states, in snake_case, starting from the conclusion (proofs-names).
  • Don't commit sorry (proofs-sorry).
  • Test what types and proofs don't cover (tests-coverage).
  • Don't write tests that only restate literals from the source (tests-literals).
  • Put tests in a <Pkg>Test library run by lake test, or in a test/ subproject when a library's tests need extra dependencies (tests-library).
  • Check results with #guard_msgs and #guard (tests-guard-msgs).
  • Compare whole outputs with saved copies only where their exact form is the contract, and review every regenerated copy (tests-golden).
  • Use an executable test driver for tests that run IO (tests-runtime).
  • Test properties of your own code that aren't proved yet on random inputs, with Plausible.Testable.check rather than the plausible tactic (tests-property).
  • In test files that are modules, import the code under test with meta import (tests-meta-import).
  • Write a docstring when the name and type leave something unsaid, and not one that restates them (docs-when).
  • Begin a file with a module docstring, with a # title, when the file needs more explanation than its code gives (docs-module).
  • Start a function's docstring with a verb such as "Returns", and a type's with a noun phrase (docs-summary).
  • Show short examples in docstrings, and check them with tests (docs-examples).
  • Put a short docstring on one line, and the delimiters of a longer one on lines of their own (docs-layout).
  • Explain why in comments, and don't restate what the code does (comments-why).
  • Write down every invariant that your types don't enforce (comments-invariants).
  • Leave history and dead code to version control, and unfinished work to the issue tracker (comments-history).
  • Get standard notation by implementing classes such as Add and GetElem (macros-classes).
  • Use macros for syntax sugar, and elaborators when the translation needs types or decisions (macros-macro-or-elab).
  • Make notation scoped unless every user of your library needs it (macros-scoped).
  • Don't add macro_rules that cover only some uses of existing syntax (macros-overlap).
  • Make your notation appear in Lean's output the way users write it (macros-output).
  • Don't add @[inline] or @[specialize] without a measurement that shows they help (perf-measure).
  • Prefer @[csimp] with a proof to @[implemented_by], which Lean doesn't check (perf-implemented-by).
  • Keep unsafe code in small functions with a safe interface, and say in a comment why it's needed (perf-unsafe).
  • Keep @[extern] declarations in one small module behind a safe Lean API (perf-ffi).
  • Start from the layout lake new creates, with a small Main.lean (project-layout).
  • Commit lean-toolchain and lake-manifest.json, and require dependencies at release tags (project-dependencies).
  • Declare files that you embed with include_str as Lake inputs in the library's needs, or editing them rebuilds nothing (project-embedded-files).
  • Set autoImplicit = false in the Lake configuration (project-options).
  • Check for warnings in CI with lake build --wfail, and don't set warningAsError in a library (project-warnings).
  • Keep Lean's built-in linters on (project-linters).
  • Don't mix reformatting with other changes (project-formatting).
  • Order each file as licence comment, module, imports, module docstring, then code (layout-file).
  • Indent with two spaces, never with tabs (layout-indentation).
  • Keep lines under 100 characters (layout-line-length).
  • Put single spaces around :, :=, |, ::, =>, ← and infix operators (layout-spaces).
  • Start top-level commands at column 0, and don't indent inside namespace or section (layout-top-level).
  • Indent the continuation lines of a long declaration header by four spaces, and never start a line with the colon (layout-headers).
  • Split long expressions at argument boundaries, with infix operators at the end of the line (layout-splitting).
  • Put match arms at the column of the match, without padding to align the arrows (layout-match).
  • Start where, deriving, termination_by and decreasing_by at the column of the declaration they belong to (layout-where).
  • In a multi-line structure instance, put { at the end of the line before it and } on its own line (layout-structure-instances).
  • Put do on the same line as the :=, => or ← before it (layout-do).

Contributing

Open an issue or a pull request. Every Lean example has to compile:

python3 tools/check_examples.py

Licence

The text of this guide is licensed under CC BY 4.0. The code examples, tools/ and research/scripts/ are licensed under Apache-2.0. Material quoted in research/ stays under its original licence, listed for each source in research/index.md.

About

A community style guide for writing programs, libraries and tools in Lean 4 (draft)

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages