How it works

flowchart TD
  source[Lean source] --> parse[Parse]
  parse --> roles[Assign roles]
  roles --> rules[Derive layout rules]
  rules --> certify[Certify]
  certify --> choose[Choose a layout]
  choose --> output[Canonical source]
  certify -. cannot certify .-> refuse[Refused]

Terms

  • Item: a token or a comment.
  • Gap: the whitespace before the first item, between two items, or after the last.
  • Role: what whitespace a gap is allowed to hold, decided from the syntax tree.
  • Candidate layout: a complete choice of separator at every gap from the options its role allows.
  • Box: the set of all candidate layouts for a module (one independent choice per gap).
  • Guard: one of Lean’s whitespace checks.
  • Rule: a condition (an OR of one or more guard checks) that must hold before a given token.
  • Cover: a partition of the original box used to verify that dropping unsafe break options didn’t drop a better valid layout.
Role Separator
tight none
attached one space
flow one space, or a newline plus base indentation + 2 spaces
header one space, or a newline plus base indentation + 4 spaces
block a newline plus base indentation + 2 spaces
peer a newline plus base indentation

The remaining roles are fixed: a blank line between commands, a newline at imports and documentation comments, nothing at the start of the file, and a trailing newline at the end.

Guard Lean’s check Holds when
ws checkWsBefore there is whitespace since the previous token
noWs checkNoWsBefore there is no whitespace since the previous token
linebreak checkLinebreakBefore there is a newline since the previous token
colGt checkColGt the token starts strictly right of the saved column
colGe checkColGe the token starts at or right of the saved column
colEq checkColEq the token starts in the saved column
lineEq checkLineEq the token is on the saved line
colIs (extension pin) the token starts in an exact absolute column

Steps

  1. Parse. bridge/Frontend.lean runs Lean’s own parser on the input. Declarations are parsed without elaborating them; scope commands like open are elaborated, and in-file infix/prefix/postfix/notation, syntax, syntax … := …, and declare_syntax_cat declarations register their parser rules so the active grammar stays up to date. The frontend returns the syntax tree and the grammar in force at each part of the file. Rust reads the token spans and extracts ordinary comments from the gaps between them.
  2. Assign roles. Each gap gets a role (tight, attached, flow, block, …) from the syntax tree alone — original columns and whitespace are ignored. See src/layout.rs and src/source.rs.
  3. Derive layout rules. grammar/lean.grammar is generated from Lean’s parser definitions and records where every parser checks whitespace (the seven guards above, plus colIs for column-sensitive extensions). Matching the syntax tree against that grammar gives the rules the output must preserve: checks that passed during parsing must still pass, and checks that stopped an alternative parser must still fail. When Lean tries several parsers and keeps the one that consumes the most tokens, each losing parser is tracked across the tokens ahead so it keeps losing. Similar rules keep adjacent tokens and comments from merging. See src/obligations.rs and src/lexical.rs.
  4. Certify. The checker verifies all rules across every candidate layout at once, not just the one that will be picked. If a break option violates a rule, it is removed first. If any rule still can’t be proved to hold across all remaining candidates, the file is refused. See src/layout_core.rs.
  5. Choose a layout. Dynamic programming picks the best-ranked layout from the remaining line-break choices: least overflow past 100 Unicode scalar values per line, then fewest newlines, then a fixed tie-break. A checker verifies the plan before emitting any text.

Canolean does not re-parse its output. Instead, the rule checker proves that every remaining layout satisfies the derived rules. Whether Lean actually accepts every layout satisfying those rules is tested against the real parser rather than proved.

The rule checker, cover checker, plan checker, and emitter are verified in Lean using Charon and Aeneas. See Verification and proofs/README.md.

Why candidate layouts?

A single syntax tree has multiple candidate layouts because of 100-column line wrapping, while still having one unique canonical output. Fixed roles (tight, attached, block, peer) allow only one separator; wrappable roles (flow, header) allow two: stay on the same line or wrap to an indented continuation. Every combination of those binary choices is a candidate layout. Because roles come only from the syntax tree and never from the input’s whitespace, two differently formatted files with the same AST produce the exact same set of candidates. Canolean/CanonicalLeanSource.lean defines the canonical output as the unique minimum over all candidates that Lean accepts, ranked by overflow past 100 Unicode scalar values, then newlines, then a deterministic tie-break.

The dynamic-programming planner finds that exact minimum in linear time over independent per-gap choices, but it cannot enforce cross-gap Lean indentation rules directly. Most of the time, every candidate in the box is already safe, so the planner runs directly on the unmodified choices. When a wrappable gap allows a combination that breaks a parser rule, a repair pass shrinks the box by dropping unsafe break options before planning. To make sure repair never drops a valid layout that would have beaten the winner, layout_core::cover_verified checks a partition certificate over the original box: every dropped sub-box must either break a required parser rule in every layout (Refuted) or have a best possible score strictly worse than the emitted winner (Dominated). If that can’t be proved within the search budget, the file is refused so Canolean never emits a non-canonical layout.