Every Python team eventually pays the lint tax. Flake8 plus isort plus a formatter means three tools, three config formats, and a CI job that crawls through a large monorepo one interpreter process at a time. On a million-line repository, waiting for the lint gate becomes a planning decision in itself. The pain is not the rules — it is that the checking loop is slow, fragmented, and fragile around every edge case Python’s grammar allows.

Ruff, from astral-sh, attacks that pain at the root. It is a single static binary written in Rust that reimplements the rule sets of a dozen ecosystem tools — over 900 built-in rules by its README’s count — at 10 to 100 times the speed. The repo is a Cargo workspace whose crates/ directory holds 57 member crates, each with a sharply drawn boundary: a parser, an AST, a semantic model, a rule registry, an autofix engine, and a workspace resolver that decides which pyproject.toml governs which file.

What follows is a tour of that tree as it exists on main today, with every symbol and line number verified against the actual checkout. Two diagrams generated from the code anchor the tour: one for the shape of the whole system, one for the internals of the lint and fix flow.

Ruff overview architecture: linter driver, AST checker, rule registry, autofix engine, parser, and workspace config

The whole system at a glance: the fix loop drives a lint pass, which feeds an AST checker that dispatches to generated rule enums, and qualifying diagnostics flow back into the autofix engine.

Reading the overview from left to right:

  • lint_fix, L519 is the top of the driver: a loop that parses, lints, applies fixes, and repeats until the source stabilizes — with an explicit escape hatch to bail after 100 iterations.
  • check_path, L121 is one lint pass: it orchestrates token rules, filesystem rules, logical-line rules, the AST checker, import sorting, physical-line rules, and the noqa audit in a fixed order.
  • parse_unchecked_source, L294 parses Python into a ModModule even when the file contains syntax errors, which is what lets the linter keep working on broken code.
  • Lexer, L38 is a 2,639-line hand-written tokenizer whose next_token drives the parser’s token source.
  • Checker, L196 is the giant visitor struct in a 3,689-line file; it owns the semantic model, locator, settings, and diagnostic context in one place.
  • code_to_rule, L238 is the rule registry: a proc macro expands roughly 991 (linter, code) => rule match arms into the generated Rule enum.
  • fix_file, L30 filters diagnostics down to those whose fixes pass the applicability threshold, then apply_fixes, L54 rewrites the source.
  • resolve_root_settings, L451 turns a pyproject.toml plus its ancestors into effective per-path settings before any of the above runs.
Ruff detail architecture: driver loop, parser and lexer, generated AST, checker visits and deferred work, source-level checks, rule registry, and autofix engine

The detail view: seven diagnostic sources feeding off one parsed token stream, the deferred-visit ordering inside the checker, and the sorted, isolation-checked fix application.

Why a Linter Needed to Be Rust

Ruff’s speed story starts in crates/ruff_python_parser. The crate exposes a small entry surface — parse_module at line 112, parse_expression at line 135, and the general parse at line 281 — but the workhorse for linting is parse_unchecked_source at line 294, which returns a Parsed<ModModule> even from invalid source. That error tolerance is a deliberate architectural choice: the AST it produces is lossless enough for the linter to keep finding violations in a file with a typo three functions below the error. A stricter parse-then-abort design would silently disable most rules on any file in a broken state, which is exactly when developers are running the linter manually.

Under the parser sits Lexer at line 38 of a 2,639-line lexer.rs — a hand-written tokenizer, not a grammar-generator output, with next_token at line 144 feeding the token source. Beyond grammar, the parser crate also carries SemanticSyntaxChecker at line 19 of semantic_errors.rs, which validates what the grammar alone cannot: global and nonlocal misuse, match-statement binding mistakes, and similar semantic syntax errors that surface in the checker via a RefCell<Vec<SemanticSyntaxError>> collected in the checker module.

The AST itself is generated code. crates/ruff_python_ast/src/generated.rs runs 9,999 lines and defines the Stmt enum at line 125, Expr at line 1298, AnyNodeRef at line 5831, and the ModModule root at line 9280. nodes.rs adds hand-written helper logic on top — 3,735 lines of conveniences like Comprehension at line 2996 and Parameters at line 3325. The generated AST keeps node shapes close to what you know from the CPython ast module, which is what makes rule ports from the Python ecosystem tractable — the same design instinct that later powered mypy style semantic layers built on parsed trees.

The Driver Loop: Seven Sources of Diagnostics

check_path at line 121 of linter.rs is the lint pass, and its structure explains most of ruff’s runtime behavior. Each source of diagnostics is gated by whether any enabled rule actually needs it: token rules run behind context.has_rules_for(LintSource::Tokens) at line 155, filesystem rules at line 169, logical-line rules at line 182, the AST checker at line 192, import sorting at line 212, physical-line rules at line 240, and the noqa audit at line 319. Select only a rule subset that touches tokens and the AST pass still runs; select nothing logical-line-shaped and that phase is skipped entirely. Crucially, AST rules only run when parsed.has_valid_syntax() holds at line 188 — a broken file still gets token and line checks, but not tree-dependent ones.

The AST checker itself is worth dwelling on because it is the largest file in the linting crate: checkers/ast/mod.rs at 3,689 lines. The tail of check_ast (defined at line 3534) reads like a choreography score. First checker.visit_module and checker.visit_body walk the tree at lines 3592 to 3593, with visit_stmt at line 1055 and visit_expr at line 1788 dispatching to analyze::statement and analyze::expression for every enabled rule. Then visit_deferred at line 3598 drains queues of deferred snapshots — function bodies and lambdas are collected in checkers/ast/deferred.rs with its functions vector at line 12 and lambdas at line 13 — in a carefully commented order so that visiting a deferred function cannot enqueue work of a kind already drained. After that come the post-pass analyses in fixed sequence: analyze::deferred_lambdas at line 3602, deferred for-loops, deferred comprehensions, definitions, analyze::bindings at line 3606, unresolved references at line 3607, and finally analyze::deferred_scopes at line 3613 after the scope stack resets to module level.

Settings for all of this come from crates/ruff_workspace. The resolver walks a target path’s ancestor directories looking for the closest pyproject.toml, but only when the resolver is_hierarchical at line 505 — and project_files_in_path at line 487 marks each ancestor as seen so repeated lookups terminate early. resolve_root_settings at line 451 handles the top-level entry, and the ConfigurationOrigin enum at line 461 distinguishes user-specified configs, user-level defaults, and ancestor-discovered ones. Per-file-ignores apply at the very start: LintContext::new at line 3636 of the checker module strips ignored rules before the first diagnostic is reported.

From noqa Codes to a Generated Rule Enum

The registry design is the most instructive build fact in the repo. File crates/ruff_linter/src/codes.rs is 1,331 lines, and almost all of it is one match table inside code_to_rule at line 238, annotated with #[ruff_macros::map_codes] at line 237. Each arm maps a linter prefix plus a code suffix to a rule implementation — for instance (Pycodestyle, "E501") => rules::pycodestyle::rules::LineTooLong at line 288. Counting the arms that delegate to rules:: yields roughly 991 mappings, and the attribute macro turns that single table into the Rule enum, NoqaCode handling (the struct sits at line 20), category assignments, and status metadata like stable and preview flags.

Selection precedence is spelled out in the docs above the Category enum: ALL < category < linter group < linter prefix < rule, with the five default categories enumerated at line 201 — Correctness, Suspicious, Complexity, Performance, Style. Underneath, registry.rs defines the Linter enum at line 36 where every member carries a #[prefix] attribute, from AIR for Airflow to YTT for flake8-2020. Going the other direction — from a code like F401 back to its rule — is Rule::from_code at line 16, which parses the linter prefix and scans that linter’s rules for a matching noqa suffix. The rule implementations themselves live in 59 directories under crates/ruff_linter/src/rules/, about 3,154 files in total, grouped by upstream tool. If you have ever wondered how ruff can claim drop-in parity with flake8 plugins, the answer is structural: the code-to-rule table is the parity contract, and each arm points at a native Rust port with its own test fixtures.

From Diagnostics to Rewrites: the Autofix Loop

The fix engine is a 388-line file, crates/ruff_linter/src/fix/mod.rs, and it is more conservative than its reputation suggests. fix_file at line 30 first filters diagnostics to those whose fix applicability clears the requested threshold — unsafe_fixes.required_applicability() — and bails out entirely if no fix qualifies. apply_fixes at line 54 then applies edits through three gates: fixes are ordered by cmp_fix at line 131 with a special-cased ordering so RedefinedWhileUnused resolves before UnusedImport, fixes carrying an IsolationLevel::Group id skip if a fix in that group already ran at lines 83 to 87, and any fix whose start position falls before the last applied edit’s end is discarded as overlapping at line 90. The output is assembled as one string plus a source map, not by mutating ranges in place — which keeps each rewrite pass a pure function over the previous source.

Around that engine, lint_fix at line 519 runs the convergence loop that ruff --fix actually exposes. Each iteration re-parses the transformed source with parse_unchecked_source, rebuilds the Locator, Stylist, and Indexer, re-extracts # noqa and # isort: skip directives at line 560, and calls check_path again. The loop is guarded on both ends: the code records whether the initial source had valid syntax at iteration zero, and if a later fix pass introduces a syntax error that did not exist before, it discards the result and returns the original code — the check sits at lines 588 to 599. The bail-after-100-iterations comment at line 534 is the honest admission that fixability is a graph property, not a guaranteed fixpoint. This parse-transform-verify loop discipline later shaped uv, built by the same team.

Honest Limits

The tour above is accurate to main at this writing, but ruff moves fast: line numbers drift with every merged pull request, and the checker module is under active restructuring — the LintContext and DiagnosticGuard types at lines 3626 to 3690 show API migrations in progress. Second, the diagrams compress a 57-crate workspace into seven groups; crates like ruff_db (diagnostics and its own module resolver), the formatter crate, and ruff_source_file do real work that no single graph can carry. Third, this post intentionally skips the type-inference story: ruff’s rule set mostly avoids needing one, but rules that do need type information lean on narrow heuristics rather than a full type checker, and pretending otherwise would mislead anyone porting rules that mypy-grade inference would handle. Finally, every count here — 991 rule mappings, 59 rule directories, 3,154 rule files — was measured on the day of writing, and the registry table grows weekly; treat the numbers as a snapshot, not a spec.

Watch PyShine on YouTube

Contents