Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

docs: script to generate lint docs (#6379)

Dylan Madisetti8d078a17bbc8
diff --git a/docs/guides/index.md b/docs/guides/index.md
index 2b62548809..341bd09426 100644
--- a/docs/guides/index.md
+++ b/docs/guides/index.md
@@ -15,6 +15,7 @@ These guides cover marimo's core concepts.
| [Migrating from Jupyter](coming_from/jupyter.md) | Tips for transitioning from Jupyter |
| [Expensive notebooks](expensive_notebooks.md) | Tips for working with expensive notebooks |
| [Understanding errors](understanding_errors/index.md) | Understanding marimo's constraints on notebook code |
+| [Lint rules](lint_rules/index.md) | Comprehensive linting system and rule reference |
| [Working with data](working_with_data/index.md) | Using SQL cells, no-code dataframe, and reactive plots |
| [Package management](package_management/index.md) | Inlining dependencies in notebook files and other package management guides |
| [Generate with AI](generate_with_ai/index.md) | Generate notebooks with AI |
diff --git a/docs/guides/lint_rules/index.md b/docs/guides/lint_rules/index.md
new file mode 100644
index 0000000000..01f5b380c2
--- /dev/null
+++ b/docs/guides/lint_rules/index.md
@@ -0,0 +1,57 @@
+# Lint Rules
+
+marimo includes a comprehensive linting system that helps you write better, more reliable notebooks. The linter checks for various issues that could prevent your notebook from running correctly or cause confusion.
+
+## How to Use
+
+You can run the linter using the CLI:
+
+```bash
+# Check all notebooks in current directory
+marimo check .
+
+# Check specific files
+marimo check notebook1.py notebook2.py
+
+# Auto-fix fixable issues
+marimo check --fix .
+```
+
+## Rule Categories
+
+marimo's lint rules are organized into three main categories based on their severity:
+
+### 🚨 Breaking Rules
+
+These errors prevent notebook execution.
+
+| Code | Name | Description | Fixable |
+|------|------|-------------|----------|
+| [MB001](rules/unparsable_cells.md) | unparsable-cells | Cell contains unparsable code | ❌ |
+| [MB002](rules/multiple_definitions.md) | multiple-definitions | Multiple cells define the same variable | ❌ |
+| [MB003](rules/cycle_dependencies.md) | cycle-dependencies | Cells have circular dependencies | ❌ |
+| [MB004](rules/setup_cell_dependencies.md) | setup-cell-dependencies | Setup cell cannot have dependencies | ❌ |
+
+### ✨ Formatting Rules
+
+These are style and formatting issues.
+
+| Code | Name | Description | Fixable |
+|------|------|-------------|----------|
+| [MF001](rules/general_formatting.md) | general-formatting | General formatting issues with the notebook format. | 🛠️ |
+| [MF002](rules/parse_stdout.md) | parse-stdout | Parse captured stdout during notebook loading | ❌ |
+| [MF003](rules/parse_stderr.md) | parse-stderr | Parse captured stderr during notebook loading | ❌ |
+
+## Legend
+
+- 🛠️ = Automatically fixable with `marimo check --fix`
+- ❌ = Not automatically fixable
+
+## Configuration
+
+Most lint rules are enabled by default. You can configure the linter behavior through marimo's configuration system.
+
+## Related Documentation
+
+- [Understanding Errors](../understanding_errors/index.md) - Detailed explanations of common marimo errors
+- [CLI Reference](../../cli.md) - Complete CLI documentation including `marimo check`
diff --git a/docs/guides/lint_rules/rules/cycle_dependencies.md b/docs/guides/lint_rules/rules/cycle_dependencies.md
new file mode 100644
index 0000000000..62710700ae
--- /dev/null
+++ b/docs/guides/lint_rules/rules/cycle_dependencies.md
@@ -0,0 +1,47 @@
+# MB003: cycle-dependencies
+
+🚨 **Breaking** ❌ Not Fixable
+
+MB003: Cells have circular dependencies.
+
+## What it does
+
+Analyzes the dependency graph to detect circular references between cells,
+where cells depend on each other in a way that creates an impossible
+execution order.
+
+## Why is this bad?
+
+Circular dependencies prevent marimo from:
+- Determining a valid execution order
+- Running notebooks reproducibly
+- Executing notebooks as scripts
+- Providing reliable reactive updates
+
+This is a breaking error because it makes the notebook non-executable.
+
+## Examples
+
+**Problematic:**
+```python
+# Cell 1
+a = b + 1 # Reads b
+
+# Cell 2
+b = a + 1 # Reads a -> Cycle!
+```
+
+**Solution:**
+```python
+# Cell 1
+a = 1
+
+# Cell 2
+b = a + 1 # Unidirectional dependency
+```
+
+## References
+
+- [Cycles Guide](https://docs.marimo.io/guides/understanding_errors/cycles/)
+- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+
diff --git a/docs/guides/lint_rules/rules/general_formatting.md b/docs/guides/lint_rules/rules/general_formatting.md
new file mode 100644
index 0000000000..87ef55ce5a
--- /dev/null
+++ b/docs/guides/lint_rules/rules/general_formatting.md
@@ -0,0 +1,59 @@
+# MF001: general-formatting
+
+✨ **Formatting** 🛠️ Fixable
+
+MF001: General formatting issues with the notebook format.
+
+## What it does
+
+Examines the notebook serialization for structural violations such as:
+- Missing or incorrect marimo import statements
+- Improperly formatted cell definitions
+- Missing app initialization code
+- Incorrect file generation metadata
+
+## Why is this bad?
+
+Format violations can prevent marimo from properly loading or executing
+notebooks. While these don't affect the Python code logic, formatting errors
+mark a deviation in the expected script structure, which can lead to
+unexpected behavior when run as a script, or when loading the notebook.
+
+## Examples
+
+**Problematic:**
+```python
+# Missing marimo import
+def __():
+ return
+
+
+if __name__ == "__main__":
+ app.run()
+```
+
+**Solution:**
+```python
+import marimo
+
+__generated_with = "0.1.0"
+app = marimo.App()
+
+
+def __():
+ return
+
+
+if __name__ == "__main__":
+ app.run()
+```
+
+**Note:** Most format issues are automatically fixable with `marimo check --fix`.
+
+## References
+
+- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+- [File Format Documentation](https://docs.marimo.io/guides/coming_from/jupyter/#marimo-file-format)
+
diff --git a/docs/guides/lint_rules/rules/multiple_definitions.md b/docs/guides/lint_rules/rules/multiple_definitions.md
new file mode 100644
index 0000000000..2a6c3b4ec5
--- /dev/null
+++ b/docs/guides/lint_rules/rules/multiple_definitions.md
@@ -0,0 +1,46 @@
+# MB002: multiple-definitions
+
+🚨 **Breaking** ❌ Not Fixable
+
+MB002: Multiple cells define the same variable.
+
+## What it does
+
+Analyzes the dependency graph to detect variables that are defined in more
+than one cell, which violates marimo's fundamental constraint for reactive execution.
+
+## Why is this bad?
+
+Multiple definitions prevent marimo from:
+- Determining the correct execution order
+- Creating a reliable dependency graph
+- Running notebooks as scripts
+- Providing consistent reactive updates
+
+This is a breaking error because it makes the notebook non-executable.
+
+## Examples
+
+**Problematic:**
+```python
+# Cell 1
+x = 1
+
+# Cell 2
+x = 2 # Error: x defined in multiple cells
+```
+
+**Solution:**
+```python
+# Cell 1
+x = 1
+
+# Cell 2
+y = 2 # Use different variable name
+```
+
+## References
+
+- [Multiple Definitions Guide](https://docs.marimo.io/guides/understanding_errors/multiple_definitions/)
+- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+
diff --git a/docs/guides/lint_rules/rules/parse_stderr.md b/docs/guides/lint_rules/rules/parse_stderr.md
new file mode 100644
index 0000000000..7b7db08526
--- /dev/null
+++ b/docs/guides/lint_rules/rules/parse_stderr.md
@@ -0,0 +1,42 @@
+# MF003: parse-stderr
+
+✨ **Formatting** ❌ Not Fixable
+
+MF003: Parse captured stderr during notebook loading.
+
+## What it does
+
+Captures stderr output during notebook loading and creates diagnostics
+from any error messages or warnings. This helps identify potential
+issues that don't prevent parsing but may affect runtime behavior.
+
+## Why is this bad?
+
+Stderr output during parsing often indicates:
+- Syntax warnings (like invalid escape sequences)
+- Import warnings or errors
+- Deprecation notices from libraries
+- Configuration issues that might affect execution
+
+While these don't break the notebook, they can lead to unexpected
+behavior or indicate code that needs updating.
+
+## Examples
+
+**Captured stderr:**
+```
+notebook.py:68: SyntaxWarning: invalid escape sequence '\l'
+```
+
+**Result:** Creates a diagnostic pointing to line 68 about the invalid escape sequence.
+
+**Common issues:**
+- Raw strings needed: `r"\path\to\file"` instead of `"\path\to\file"`
+- Deprecated library usage
+- Missing import dependencies
+
+## References
+
+- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+- [Python Warning Categories](https://docs.python.org/3/library/warnings.html#warning-categories)
+
diff --git a/docs/guides/lint_rules/rules/parse_stdout.md b/docs/guides/lint_rules/rules/parse_stdout.md
new file mode 100644
index 0000000000..6a2c191a39
--- /dev/null
+++ b/docs/guides/lint_rules/rules/parse_stdout.md
@@ -0,0 +1,33 @@
+# MF002: parse-stdout
+
+✨ **Formatting** ❌ Not Fixable
+
+MF002: Parse captured stdout during notebook loading.
+
+## What it does
+
+Captures and parses stdout output during notebook loading, looking for
+structured warning messages that include file and line number references.
+Creates diagnostics from any warnings or messages found.
+
+## Why is this bad?
+
+While stdout output doesn't prevent execution, it often indicates:
+- Deprecation warnings from imported libraries
+- Configuration issues
+- Potential compatibility problems
+- Code that produces unexpected side effects during import
+
+## Examples
+
+**Captured stdout:**
+```
+notebook.py:15: DeprecationWarning: 'imp' module is deprecated
+```
+
+**Result:** Creates a diagnostic pointing to line 15 with the deprecation warning.
+
+## References
+
+- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+
diff --git a/docs/guides/lint_rules/rules/setup_cell_dependencies.md b/docs/guides/lint_rules/rules/setup_cell_dependencies.md
new file mode 100644
index 0000000000..c007d20633
--- /dev/null
+++ b/docs/guides/lint_rules/rules/setup_cell_dependencies.md
@@ -0,0 +1,45 @@
+# MB004: setup-cell-dependencies
+
+🚨 **Breaking** ❌ Not Fixable
+
+MB004: Setup cell cannot have dependencies.
+
+## What it does
+
+Validates that the setup cell (if present) does not depend on variables
+defined in other cells, ensuring proper execution order.
+
+## Why is this bad?
+
+Setup cell dependencies break marimo's execution model because:
+- The setup cell must run first to initialize the notebook
+- Dependencies on other cells would create impossible execution order
+- It violates the setup cell's purpose as initialization code
+
+This is a breaking error because it makes the notebook non-executable.
+
+## Examples
+
+**Problematic:**
+```python
+# Setup cell
+y = x + 1 # Error: setup depends on other cells
+
+# Cell 1
+x = 1
+```
+
+**Solution:**
+```python
+# Setup cell
+y = 1 # Setup defines its own variables
+
+# Cell 1
+x = y + 1 # Other cells can use setup variables
+```
+
+## References
+
+- [Setup References Guide](https://docs.marimo.io/guides/understanding_errors/setup/)
+- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+
diff --git a/docs/guides/lint_rules/rules/unparsable_cells.md b/docs/guides/lint_rules/rules/unparsable_cells.md
new file mode 100644
index 0000000000..a4fd0fb78d
--- /dev/null
+++ b/docs/guides/lint_rules/rules/unparsable_cells.md
@@ -0,0 +1,43 @@
+# MB001: unparsable-cells
+
+🚨 **Breaking** ❌ Not Fixable
+
+MB001: Cell contains unparsable code.
+
+## What it does
+
+Identifies cells that cannot be parsed into valid Python AST nodes, indicating
+fundamental syntax or encoding problems that prevent the notebook from being loaded.
+
+## Why is this bad?
+
+Unparsable cells prevent the notebook from running as a script and will throw
+errors when executed in notebook mode. While marimo can still open the notebook,
+these cells cannot be run until the parsing issues are resolved.
+
+## Examples
+
+**Problematic:**
+```python
+# Cell with encoding issues or corrupt data
+x = 1 \x00\x01\x02 # Binary data in source
+```
+
+**Problematic:**
+```python
+# Cell with fundamental syntax errors
+def func(
+ # Missing closing parenthesis and body
+```
+
+**Solution:**
+```python
+# Fix syntax errors and encoding issues
+def func():
+ return 42
+```
+
+## References
+
+- [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+
diff --git a/docs/guides/scripts.md b/docs/guides/scripts.md
index cba674e688..761565eeb1 100644
--- a/docs/guides/scripts.md
+++ b/docs/guides/scripts.md
@@ -11,6 +11,16 @@ Running a notebook as a script is useful when your notebook has side-effects,
like writing to disk. Print statements and other console outputs will show
up in your terminal.
+!!! tip "Check before running"
+
+ Before running a notebook as a script, you can use marimo's linter to check for issues that might prevent execution:
+
+ ```bash
+ marimo check my_marimo_notebook.py
+ ```
+
+ See the [Lint Rules](lint_rules/index.md) guide for more information about marimo's linting system.
+
!!! note "Saving notebook outputs"
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index c3e6971ce3..085097b3d0 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -127,6 +127,22 @@ If you find yourself needing to force execution order often, it might be a sign
## General debugging tips
+### Check for common issues with the linter
+
+Before diving into manual debugging, try running marimo's built-in linter to catch common issues:
+
+```bash
+marimo check my_notebook.py
+```
+
+The linter can identify problems like:
+- Multiple variable definitions across cells
+- Circular dependencies between cells
+- Unparsable code that prevents execution
+- Other code quality issues
+
+See the [Lint Rules](lint_rules/index.md) guide for a complete list of checks.
+
### Understanding dependencies
- Use the Variables Panel to inspect variable values and see where they're defined and used.
diff --git a/docs/guides/understanding_errors/index.md b/docs/guides/understanding_errors/index.md
index 6e34b9047a..f73c181511 100644
--- a/docs/guides/understanding_errors/index.md
+++ b/docs/guides/understanding_errors/index.md
@@ -24,6 +24,17 @@ how to work around them.
These errors might be surprising at first, but spend just a
bit of time with marimo and adhering to these constraints will become second nature — and you'll get used to writing error-free code by default.
+## Lint Rules
+
+marimo includes a comprehensive linting system that automatically detects these constraints and other code quality issues. The linter can help you identify and fix problems before they cause runtime errors.
+
+Run the linter using:
+```bash
+marimo check .
+```
+
+See the [Lint Rules](../lint_rules/index.md) guide for a complete list of rules and detailed explanations.
+
| Guide | Description |
|-------|-------------|
| [Multiple definitions](multiple_definitions.md) | How to deal with variables defined in multiple cells |
diff --git a/marimo/_lint/diagnostic.py b/marimo/_lint/diagnostic.py
index ee8b704bcf..4e37bdec91 100644
--- a/marimo/_lint/diagnostic.py
+++ b/marimo/_lint/diagnostic.py
@@ -26,9 +26,9 @@ class Diagnostic:
"""Represents a diagnostic found in a notebook."""
message: str
- cell_id: None | list[CellId_t]
line: int | list[int]
column: int | list[int]
+ cell_id: None | list[CellId_t] = None
code: Optional[str] = None
name: Optional[str] = None
severity: Optional[Severity] = None
diff --git a/marimo/_lint/rules/breaking/__init__.py b/marimo/_lint/rules/breaking/__init__.py
index d4020aef8b..a28dee103d 100644
--- a/marimo/_lint/rules/breaking/__init__.py
+++ b/marimo/_lint/rules/breaking/__init__.py
@@ -9,9 +9,9 @@ from marimo._lint.rules.breaking.unparsable import UnparsableRule
BREAKING_RULE_CODES: dict[str, type[LintRule]] = {
"MB001": UnparsableRule,
- "MR002": MultipleDefinitionsRule,
- "MR003": CycleDependenciesRule,
- "MR004": SetupCellDependenciesRule,
+ "MB002": MultipleDefinitionsRule,
+ "MB003": CycleDependenciesRule,
+ "MB004": SetupCellDependenciesRule,
}
__all__ = [
diff --git a/marimo/_lint/rules/breaking/graph.py b/marimo/_lint/rules/breaking/graph.py
index 14370c04fd..206adb00fa 100644
--- a/marimo/_lint/rules/breaking/graph.py
+++ b/marimo/_lint/rules/breaking/graph.py
@@ -137,7 +137,7 @@ class GraphRule(LintRule):
class MultipleDefinitionsRule(GraphRule):
- """MR001: Multiple cells define the same variable.
+ """MB002: Multiple cells define the same variable.
marimo requires that each variable be defined in only one cell. This constraint
ensures that notebooks are reproducible, executable as scripts, and shareable
@@ -146,24 +146,51 @@ class MultipleDefinitionsRule(GraphRule):
When a variable is defined in multiple cells, marimo cannot determine which
definition to use, leading to unpredictable behavior and hidden bugs.
- See Also:
- - https://docs.marimo.io/guides/understanding_errors/multiple_definitions/
- - https://docs.marimo.io/guides/understanding_errors/ (Understanding errors)
+ ## What it does
+
+ Analyzes the dependency graph to detect variables that are defined in more
+ than one cell, which violates marimo's fundamental constraint for reactive execution.
+
+ ## Why is this bad?
+
+ Multiple definitions prevent marimo from:
+ - Determining the correct execution order
+ - Creating a reliable dependency graph
+ - Running notebooks as scripts
+ - Providing consistent reactive updates
+
+ This is a breaking error because it makes the notebook non-executable.
+
+ ## Examples
+
+ **Problematic:**
+ ```python
+ # Cell 1
+ x = 1
+
+ # Cell 2
+ x = 2 # Error: x defined in multiple cells
+ ```
- Examples:
- Violation:
- Cell 1: x = 1
- Cell 2: x = 2 # Error: x defined in multiple cells
+ **Solution:**
+ ```python
+ # Cell 1
+ x = 1
- Solution:
- Cell 1: x = 1
- Cell 2: y = 2 # Use different variable name
+ # Cell 2
+ y = 2 # Use different variable name
+ ```
+
+ ## References
+
+ - [Multiple Definitions Guide](https://docs.marimo.io/guides/understanding_errors/multiple_definitions/)
+ - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
"""
- code = "MR001"
+ code = "MB002"
name = "multiple-definitions"
description = "Multiple cells define the same variable"
- severity = Severity.RUNTIME
+ severity = Severity.BREAKING
fixable = False
async def _validate_graph(
@@ -207,7 +234,7 @@ class MultipleDefinitionsRule(GraphRule):
class CycleDependenciesRule(GraphRule):
- """MR002: Cells have circular dependencies.
+ """MB003: Cells have circular dependencies.
marimo prevents circular dependencies between cells to ensure a well-defined
execution order. If cell A declares variable 'a' and reads variable 'b', then
@@ -216,24 +243,52 @@ class CycleDependenciesRule(GraphRule):
Cycles make notebooks non-reproducible and prevent marimo from determining
the correct execution order, leading to undefined behavior.
- See Also:
- - https://docs.marimo.io/guides/understanding_errors/cycles/
- - https://docs.marimo.io/guides/understanding_errors/ (Understanding errors)
+ ## What it does
+
+ Analyzes the dependency graph to detect circular references between cells,
+ where cells depend on each other in a way that creates an impossible
+ execution order.
+
+ ## Why is this bad?
+
+ Circular dependencies prevent marimo from:
+ - Determining a valid execution order
+ - Running notebooks reproducibly
+ - Executing notebooks as scripts
+ - Providing reliable reactive updates
+
+ This is a breaking error because it makes the notebook non-executable.
- Examples:
- Violation:
- Cell 1: a = b + 1 # Reads b
- Cell 2: b = a + 1 # Reads a -> Cycle!
+ ## Examples
- Solution:
- Cell 1: a = 1
- Cell 2: b = a + 1 # Unidirectional dependency
+ **Problematic:**
+ ```python
+ # Cell 1
+ a = b + 1 # Reads b
+
+ # Cell 2
+ b = a + 1 # Reads a -> Cycle!
+ ```
+
+ **Solution:**
+ ```python
+ # Cell 1
+ a = 1
+
+ # Cell 2
+ b = a + 1 # Unidirectional dependency
+ ```
+
+ ## References
+
+ - [Cycles Guide](https://docs.marimo.io/guides/understanding_errors/cycles/)
+ - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
"""
- code = "MR002"
+ code = "MB003"
name = "cycle-dependencies"
description = "Cells have circular dependencies"
- severity = Severity.RUNTIME
+ severity = Severity.BREAKING
fixable = False
async def _validate_graph(
@@ -277,7 +332,7 @@ class CycleDependenciesRule(GraphRule):
class SetupCellDependenciesRule(GraphRule):
- """MR003: Setup cell cannot have dependencies.
+ """MB004: Setup cell cannot have dependencies.
The setup cell in marimo is special - it runs first and can define variables
that are available to all other cells. However, the setup cell itself cannot
@@ -287,24 +342,50 @@ class SetupCellDependenciesRule(GraphRule):
The setup cell is designed for imports, configuration, and other initialization
code that should run before any other cells execute.
- See Also:
- - https://docs.marimo.io/guides/understanding_errors/setup/
- - https://docs.marimo.io/guides/understanding_errors/ (Understanding errors)
+ ## What it does
+
+ Validates that the setup cell (if present) does not depend on variables
+ defined in other cells, ensuring proper execution order.
+
+ ## Why is this bad?
+
+ Setup cell dependencies break marimo's execution model because:
+ - The setup cell must run first to initialize the notebook
+ - Dependencies on other cells would create impossible execution order
+ - It violates the setup cell's purpose as initialization code
+
+ This is a breaking error because it makes the notebook non-executable.
+
+ ## Examples
+
+ **Problematic:**
+ ```python
+ # Setup cell
+ y = x + 1 # Error: setup depends on other cells
+
+ # Cell 1
+ x = 1
+ ```
+
+ **Solution:**
+ ```python
+ # Setup cell
+ y = 1 # Setup defines its own variables
+
+ # Cell 1
+ x = y + 1 # Other cells can use setup variables
+ ```
- Examples:
- Violation:
- Setup cell: y = x + 1 # Error: setup depends on other cells
- Cell 1: x = 1
+ ## References
- Solution:
- Setup cell: y = 1 # Setup defines its own variables
- Cell 1: x = y + 1 # Other cells can use setup variables
+ - [Setup References Guide](https://docs.marimo.io/guides/understanding_errors/setup/)
+ - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
"""
- code = "MR003"
+ code = "MB004"
name = "setup-cell-dependencies"
description = "Setup cell cannot have dependencies"
- severity = Severity.RUNTIME
+ severity = Severity.BREAKING
fixable = False
async def _validate_graph(
diff --git a/marimo/_lint/rules/breaking/unparsable.py b/marimo/_lint/rules/breaking/unparsable.py
index f11c8f2926..8b88ae0877 100644
--- a/marimo/_lint/rules/breaking/unparsable.py
+++ b/marimo/_lint/rules/breaking/unparsable.py
@@ -1,4 +1,4 @@
-# Copyright 2024 Marimo. All rights reserved.
+# Copyright 2025 Marimo. All rights reserved.
from __future__ import annotations
from typing import TYPE_CHECKING
@@ -12,7 +12,49 @@ if TYPE_CHECKING:
class UnparsableRule(LintRule):
- """MB001: Cell contains unparsable code."""
+ """MB001: Cell contains unparsable code.
+
+ This rule detects cells that contain code that cannot be parsed as valid Python.
+ Unparsable cells typically occur when a notebook file is corrupted, contains invalid
+ syntax, or has encoding issues that prevent proper parsing.
+
+ ## What it does
+
+ Identifies cells that cannot be parsed into valid Python AST nodes, indicating
+ fundamental syntax or encoding problems that prevent the notebook from being loaded.
+
+ ## Why is this bad?
+
+ Unparsable cells prevent the notebook from running as a script and will throw
+ errors when executed in notebook mode. While marimo can still open the notebook,
+ these cells cannot be run until the parsing issues are resolved.
+
+ ## Examples
+
+ **Problematic:**
+ ```python
+ # Cell with encoding issues or corrupt data
+ x = 1 \\x00\\x01\\x02 # Binary data in source
+ ```
+
+ **Problematic:**
+ ```python
+ # Cell with fundamental syntax errors
+ def func(
+ # Missing closing parenthesis and body
+ ```
+
+ **Solution:**
+ ```python
+ # Fix syntax errors and encoding issues
+ def func():
+ return 42
+ ```
+
+ ## References
+
+ - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+ """
code = "MB001"
name = "unparsable-cells"
diff --git a/marimo/_lint/rules/formatting/general.py b/marimo/_lint/rules/formatting/general.py
index 86137b6614..94f1642f00 100644
--- a/marimo/_lint/rules/formatting/general.py
+++ b/marimo/_lint/rules/formatting/general.py
@@ -11,7 +11,65 @@ if TYPE_CHECKING:
class GeneralFormattingRule(LintRule):
- """MF001: General formatting issues."""
+ """MF001: General formatting issues with the notebook format.
+
+ This rule detects violations in the marimo notebook file format that affect
+ the structure and metadata of the notebook. These issues typically arise
+ when notebook files are manually edited or corrupted during parsing.
+
+ ## What it does
+
+ Examines the notebook serialization for structural violations such as:
+ - Missing or incorrect marimo import statements
+ - Improperly formatted cell definitions
+ - Missing app initialization code
+ - Incorrect file generation metadata
+
+ ## Why is this bad?
+
+ Format violations can prevent marimo from properly loading or executing
+ notebooks. While these don't affect the Python code logic, formatting errors
+ mark a deviation in the expected script structure, which can lead to
+ unexpected behavior when run as a script, or when loading the notebook.
+
+ ## Examples
+
+ **Problematic:**
+ ```python
+ # Missing marimo import
+ @app.cell
+ def __():
+ return
+
+
+ if __name__ == "__main__":
+ app.run()
+ ```
+
+ **Solution:**
+ ```python
+ import marimo
+
+ __generated_with = "0.1.0"
+ app = marimo.App()
+
+
+ @app.cell
+ def __():
+ return
+
+
+ if __name__ == "__main__":
+ app.run()
+ ```
+
+ **Note:** Most format issues are automatically fixable with `marimo check --fix`.
+
+ ## References
+
+ - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+ - [File Format Documentation](https://docs.marimo.io/guides/coming_from/jupyter/#marimo-file-format)
+ """
code = "MF001"
name = "general-formatting"
diff --git a/marimo/_lint/rules/formatting/parsing.py b/marimo/_lint/rules/formatting/parsing.py
index e7b2408a1f..6a1fb4e8b3 100644
--- a/marimo/_lint/rules/formatting/parsing.py
+++ b/marimo/_lint/rules/formatting/parsing.py
@@ -12,9 +12,39 @@ if TYPE_CHECKING:
class StdoutRule(LintRule):
- """MF002: Parse stdout captured during notebook loading.
+ """MF002: Parse captured stdout during notebook loading.
- When marimo parses a notebook file, any output to stdout.
+ This rule processes any output that was captured from stdout while marimo
+ was parsing and loading a notebook file. Stdout output during parsing
+ typically indicates warnings or informational messages from the Python
+ interpreter or imported modules.
+
+ ## What it does
+
+ Captures and parses stdout output during notebook loading, looking for
+ structured warning messages that include file and line number references.
+ Creates diagnostics from any warnings or messages found.
+
+ ## Why is this bad?
+
+ While stdout output doesn't prevent execution, it often indicates:
+ - Deprecation warnings from imported libraries
+ - Configuration issues
+ - Potential compatibility problems
+ - Code that produces unexpected side effects during import
+
+ ## Examples
+
+ **Captured stdout:**
+ ```
+ notebook.py:15: DeprecationWarning: 'imp' module is deprecated
+ ```
+
+ **Result:** Creates a diagnostic pointing to line 15 with the deprecation warning.
+
+ ## References
+
+ - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
"""
code = "MF002"
@@ -64,19 +94,48 @@ class StdoutRule(LintRule):
class StderrRule(LintRule):
- """MF003: Parse stderr captured during notebook loading.
+ """MF003: Parse captured stderr during notebook loading.
+
+ This rule processes any output that was captured from stderr while marimo
+ was parsing and loading a notebook file. Stderr output typically contains
+ warnings and error messages from the Python interpreter, such as syntax
+ warnings, deprecation notices, and import errors.
+
+ ## What it does
+
+ Captures stderr output during notebook loading and creates diagnostics
+ from any error messages or warnings. This helps identify potential
+ issues that don't prevent parsing but may affect runtime behavior.
+
+ ## Why is this bad?
+
+ Stderr output during parsing often indicates:
+ - Syntax warnings (like invalid escape sequences)
+ - Import warnings or errors
+ - Deprecation notices from libraries
+ - Configuration issues that might affect execution
+
+ While these don't break the notebook, they can lead to unexpected
+ behavior or indicate code that needs updating.
+
+ ## Examples
+
+ **Captured stderr:**
+ ```
+ notebook.py:68: SyntaxWarning: invalid escape sequence '\\l'
+ ```
+
+ **Result:** Creates a diagnostic pointing to line 68 about the invalid escape sequence.
- When marimo parses a notebook file, any output to stderr (such as syntax
- warnings) is captured and converted to formatting diagnostics. This rule
- processes that captured output and extracts useful information like line
- numbers.
+ **Common issues:**
+ - Raw strings needed: `r"\\path\\to\\file"` instead of `"\\path\\to\\file"`
+ - Deprecated library usage
+ - Missing import dependencies
- Examples:
- Stderr: "file.py:68: SyntaxWarning: invalid escape sequence '\\l'"
- -> Creates diagnostic pointing to line 68
+ ## References
- Stdout: General parsing information
- -> Creates diagnostic at line 1
+ - [Understanding Errors](https://docs.marimo.io/guides/understanding_errors/)
+ - [Python Warning Categories](https://docs.python.org/3/library/warnings.html#warning-categories)
"""
code = "MF003"
diff --git a/mkdocs.yml b/mkdocs.yml
index 60a1dae5ce..dca8955fbe 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -93,6 +93,16 @@ nav:
- Import star: guides/understanding_errors/import_star.md
- Cycles: guides/understanding_errors/cycles.md
- Setup References: guides/understanding_errors/setup.md
+ - Lint Rules:
+ - Lint Rules: guides/lint_rules/index.md
+ - Rules:
+ - Unparsable cells: guides/lint_rules/rules/unparsable_cells.md
+ - Multiple definitions: guides/lint_rules/rules/multiple_definitions.md
+ - Cycle dependencies: guides/lint_rules/rules/cycle_dependencies.md
+ - Setup cell dependencies: guides/lint_rules/rules/setup_cell_dependencies.md
+ - General formatting: guides/lint_rules/rules/general_formatting.md
+ - Parse stdout: guides/lint_rules/rules/parse_stdout.md
+ - Parse stderr: guides/lint_rules/rules/parse_stderr.md
- SQL, dataframes, and plots:
- SQL, dataframes, and plots: guides/working_with_data/index.md
- DataFrames: guides/working_with_data/dataframes.md
diff --git a/pyproject.toml b/pyproject.toml
index 4964b134e4..48cf216227 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -324,25 +324,26 @@ line-length = 79
target-version = "py39"
include = ["marimo/**/*.py", "tests/**/*.py", "dagger/**/*.py"]
exclude = [
+ "build",
+ "docs",
"examples",
- "scripts",
- "marimo/_tutorials",
- "marimo/_snippets/data",
+ "frontend",
"marimo/_smoke_tests",
- "marimo/_test_utils/codegen_data",
- "marimo/_test_utils/_tutorials",
+ "marimo/_snippets/data",
"marimo/_static/files/wasm-intro.py",
+ "marimo/_test_utils/_tutorials",
+ "marimo/_test_utils/codegen_data",
+ "marimo/_tutorials",
+ "scripts",
"tests/_ast/app_data",
- "tests/_ast/codegen_data",
"tests/_ast/cell_data",
+ "tests/_ast/codegen_data",
+ "tests/_ast/test_app.py",
"tests/_cli/cli_data",
"tests/_cli/ipynb_data",
- "tests/_runtime/runtime_data",
- "tests/_ast/test_app.py",
"tests/_convert/ipynb_data/*.ipynb",
- "frontend",
- "docs",
- "build",
+ "tests/_lint/test_files",
+ "tests/_runtime/runtime_data",
]
[tool.ruff.lint]
diff --git a/scripts/generate_lint_docs.py b/scripts/generate_lint_docs.py
new file mode 100644
index 0000000000..c5d49ca19d
--- /dev/null
+++ b/scripts/generate_lint_docs.py
@@ -0,0 +1,527 @@
+# /// script
+# requires-python = ">=3.13,<3.14"
+# dependencies = []
+#
+# [tool.uv]
+# exclude-newer = "2025-06-27T12:38:25.742953-04:00"
+# ///
+"""Generate documentation for marimo's lint rules.
+
+This script automatically generates comprehensive documentation for all lint rules
+in the marimo codebase, including:
+- Main rules index page with categorized listings
+- Individual rule pages with detailed explanations
+- Validation of rule metadata and structure
+
+Inspired by Ruff's documentation structure but adapted for marimo's style.
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+import textwrap
+from dataclasses import dataclass
+from enum import Enum
+from pathlib import Path
+from typing import Any
+
+
+class Severity(Enum):
+ """Severity levels for diagnostic errors."""
+ FORMATTING = "formatting"
+ # Retained for future use: RUNTIME severity is intended for runtime-related lint rules.
+ RUNTIME = "runtime"
+ BREAKING = "breaking"
+
+
+@dataclass
+class RuleInfo:
+ """Information about a lint rule extracted from source code."""
+ code: str
+ name: str
+ description: str
+ severity: Severity
+ fixable: bool
+ docstring: str
+ file_path: Path
+ class_name: str
+
+
+# Add marimo to the path so we can import it
+MARIMO_ROOT = Path(__file__).parent.parent
+
+
+def extract_rule_info_from_file(file_path: Path) -> list[RuleInfo]:
+ """Extract rule information from a Python file."""
+ content = file_path.read_text()
+ tree = ast.parse(content)
+
+ rules = []
+
+ for node in ast.walk(tree):
+ if (isinstance(node, ast.ClassDef) and
+ any(isinstance(base, ast.Name) and base.id in ["LintRule", "GraphRule"] for base in node.bases)):
+
+ # Extract class attributes
+ rule_data = {}
+
+ for item in node.body:
+ if isinstance(item, ast.Assign):
+ for target in item.targets:
+ if isinstance(target, ast.Name):
+ attr_name = target.id
+ if attr_name in ["code", "name", "description", "severity", "fixable"]:
+ if isinstance(item.value, ast.Constant):
+ rule_data[attr_name] = item.value.value
+ elif isinstance(item.value, ast.Attribute):
+ # Handle Severity.BREAKING etc
+ if (isinstance(item.value.value, ast.Name) and
+ item.value.value.id == "Severity"):
+ severity_name = item.value.attr
+ rule_data[attr_name] = Severity(severity_name.lower())
+
+ # Extract docstring
+ docstring = ""
+ if (node.body and isinstance(node.body[0], ast.Expr) and
+ isinstance(node.body[0].value, ast.Constant) and
+ isinstance(node.body[0].value.value, str)):
+ docstring = node.body[0].value.value
+
+ # Create rule info if we have required data
+ if all(key in rule_data for key in ["code", "name", "description", "severity", "fixable"]):
+ rules.append(RuleInfo(
+ code=rule_data["code"],
+ name=rule_data["name"],
+ description=rule_data["description"],
+ severity=rule_data["severity"],
+ fixable=rule_data["fixable"],
+ docstring=docstring,
+ file_path=file_path,
+ class_name=node.name
+ ))
+
+ return rules
+
+
+def discover_all_rules() -> dict[str, RuleInfo]:
+ """Discover all lint rules that are actually registered in the codebase."""
+ # First, get the registered rule codes from the init files
+ breaking_init = MARIMO_ROOT / "marimo" / "_lint" / "rules" / "breaking" / "__init__.py"
+ formatting_init = MARIMO_ROOT / "marimo" / "_lint" / "rules" / "formatting" / "__init__.py"
+
+ registered_codes = set()
+
+ # Parse the breaking rules init file
+ try:
+ content = breaking_init.read_text()
+ # Extract codes from BREAKING_RULE_CODES dictionary
+ for line in content.split('\n'):
+ if '"MB' in line and ':' in line:
+ # Extract the code between quotes
+ start = line.find('"MB')
+ if start != -1:
+ end = line.find('"', start + 1)
+ if end != -1:
+ code = line[start + 1:end]
+ registered_codes.add(code)
+ except Exception as e:
+ print(f"Warning: Could not parse breaking rules init: {e}")
+
+ # Parse the formatting rules init file
+ try:
+ content = formatting_init.read_text()
+ # Extract codes from FORMATTING_RULE_CODES dictionary
+ for line in content.split('\n'):
+ if '"MF' in line and ':' in line:
+ # Extract the code between quotes
+ start = line.find('"MF')
+ if start != -1:
+ end = line.find('"', start + 1)
+ if end != -1:
+ code = line[start + 1:end]
+ registered_codes.add(code)
+ except Exception as e:
+ print(f"Warning: Could not parse formatting rules init: {e}")
+
+ # Now discover rules from source files
+ rules_dir = MARIMO_ROOT / "marimo" / "_lint" / "rules"
+ rule_files = list(rules_dir.rglob("*.py"))
+
+ all_rules = {}
+
+ for file_path in rule_files:
+ if file_path.name in ["__init__.py", "base.py"]:
+ continue
+
+ try:
+ rules = extract_rule_info_from_file(file_path)
+ for rule in rules:
+ # Only include rules that are actually registered
+ if rule.code in registered_codes:
+ all_rules[rule.code] = rule
+ else:
+ print(f"Skipping unregistered rule: {rule.code} ({rule.class_name})")
+ except Exception as e:
+ print(f"Warning: Could not parse {file_path}: {e}")
+
+ return all_rules
+
+
+def get_severity_info(severity: Severity) -> tuple[str, str, str]:
+ """Get display information for a severity level."""
+ severity_map = {
+ Severity.BREAKING: ("🚨", "Breaking", "These errors prevent notebook execution"),
+ Severity.RUNTIME: ("⚠️", "Runtime", "These issues may cause runtime problems"),
+ Severity.FORMATTING: ("✨", "Formatting", "These are style and formatting issues"),
+ }
+ return severity_map.get(severity, ("❓", "Unknown", ""))
+
+
+def validate_rule_info(rule: RuleInfo) -> list[str]:
+ """Validate that a rule has all required information."""
+ issues = []
+
+ # Check required attributes are present and valid
+ if not rule.code:
+ issues.append("Missing rule code")
+ elif not re.match(r'^M[BRF]\d{3}$', rule.code):
+ issues.append(f"Invalid rule code format: {rule.code} (expected MB###, MR###, or MF###)")
+
+ if not rule.name:
+ issues.append("Missing rule name")
+
+ if not rule.description:
+ issues.append("Missing rule description")
+
+ if not isinstance(rule.severity, Severity):
+ issues.append(f"Invalid severity: {rule.severity}")
+
+ if not isinstance(rule.fixable, bool):
+ issues.append(f"Fixable must be a boolean, got {type(rule.fixable)}")
+
+ # Validate docstring exists and is properly formatted
+ if not rule.docstring:
+ issues.append("Missing docstring")
+ else:
+ lines = rule.docstring.split('\n')
+ first_line = lines[0].strip() if lines else ""
+ if first_line and ':' in first_line:
+ docstring_code = first_line.split(':')[0].strip()
+ if docstring_code != rule.code:
+ issues.append(f"Docstring code '{docstring_code}' doesn't match class code '{rule.code}'")
+
+ # Validate rule code matches severity prefix
+ code_prefix = rule.code[:2]
+ expected_prefixes = {
+ Severity.BREAKING: "MB",
+ Severity.RUNTIME: "MR",
+ Severity.FORMATTING: "MF"
+ }
+ expected_prefix = expected_prefixes.get(rule.severity)
+ if expected_prefix and code_prefix != expected_prefix:
+ issues.append(f"Rule code prefix '{code_prefix}' doesn't match severity '{rule.severity.value}' (expected '{expected_prefix}')")
+
+ return issues
+
+
+def get_rule_details(rule: RuleInfo) -> dict[str, Any]:
+ """Extract detailed information about a rule."""
+ if not rule.docstring:
+ raise ValueError(f"Rule {rule.code} ({rule.class_name}) must have a docstring")
+
+ # Remove the first line (rule code/description) and dedent the rest
+ lines = rule.docstring.split('\n')
+ full_description = lines[0] if lines else rule.description
+
+ # Join everything after the first line and dedent it
+ remaining_content = '\n'.join(lines[1:]) if len(lines) > 1 else ""
+ dedented_content = textwrap.dedent(remaining_content)
+ dedented_lines = dedented_content.split('\n')
+
+ # Parse structured sections from dedented content
+ sections = {}
+ current_section = None
+ current_content = []
+
+ for line in dedented_lines:
+ stripped = line.strip()
+
+ # Check for section headers
+ if stripped.startswith('## '):
+ # Save previous section
+ if current_section and current_content:
+ sections[current_section] = '\n'.join(current_content).strip()
+
+ # Start new section
+ current_section = stripped[3:].strip()
+ current_content = []
+ elif current_section:
+ # Add content to current section
+ current_content.append(line)
+
+ # Save last section
+ if current_section and current_content:
+ sections[current_section] = '\n'.join(current_content).strip()
+
+ return {
+ 'code': rule.code,
+ 'name': rule.name,
+ 'description': rule.description,
+ 'severity': rule.severity,
+ 'fixable': rule.fixable,
+ 'docstring': rule.docstring,
+ 'full_description': full_description,
+ 'sections': sections,
+ 'file_path': str(rule.file_path.relative_to(MARIMO_ROOT)),
+ 'class_name': rule.class_name,
+ }
+
+
+def generate_main_index_page(rules_by_severity: dict[Severity, list[dict[str, Any]]]) -> str:
+ """Generate the main lint rules index page."""
+ content = """# Lint Rules
+
+marimo includes a comprehensive linting system that helps you write better, more reliable notebooks. The linter checks for various issues that could prevent your notebook from running correctly or cause confusion.
+
+## How to Use
+
+You can run the linter using the CLI:
+
+```bash
+# Check all notebooks in current directory
+marimo check .
+
+# Check specific files
+marimo check notebook1.py notebook2.py
+
+# Auto-fix fixable issues
+marimo check --fix .
+```
+
+## Rule Categories
+
+marimo's lint rules are organized into three main categories based on their severity:
+
+"""
+
+ for severity in [Severity.BREAKING, Severity.RUNTIME, Severity.FORMATTING]:
+ if severity not in rules_by_severity:
+ continue
+
+ icon, name, description = get_severity_info(severity)
+ rules = rules_by_severity[severity]
+
+ content += f"### {icon} {name} Rules\n\n"
+ content += f"{description}.\n\n"
+
+ # Create table of rules
+ content += "| Code | Name | Description | Fixable |\n"
+ content += "|------|------|-------------|----------|\n"
+
+ for rule in sorted(rules, key=lambda r: r['code']):
+ fixable_icon = "🛠️" if rule['fixable'] else "❌"
+ filename = rule['name'].replace("-", "_") + ".md"
+ rule_link = f"[{rule['code']}](rules/{filename})"
+ content += f"| {rule_link} | {rule['name']} | {rule['description']} | {fixable_icon} |\n"
+
+ content += "\n"
+
+ content += """## Legend
+
+- 🛠️ = Automatically fixable with `marimo check --fix`
+- ❌ = Not automatically fixable
+
+## Configuration
+
+Most lint rules are enabled by default. You can configure the linter behavior through marimo's configuration system.
+
+## Related Documentation
+
+- [Understanding Errors](../understanding_errors/index.md) - Detailed explanations of common marimo errors
+- [CLI Reference](../../cli.md) - Complete CLI documentation including `marimo check`
+"""
+
+ return content
+
+
+def generate_rule_page(rule_details: dict[str, Any]) -> str:
+ """Generate documentation page for an individual rule."""
+ rule = rule_details
+ icon, severity_name, _ = get_severity_info(rule['severity'])
+
+ content = f"""# {rule['code']}: {rule['name']}
+
+{icon} **{severity_name}** {'🛠️ Fixable' if rule['fixable'] else '❌ Not Fixable'}
+
+"""
+
+ # Add the first line of the docstring as main description
+ if rule['full_description'] and rule['full_description'] != rule['description']:
+ # Split the first line from the rest
+ desc_lines = rule['full_description'].split('.')
+ if len(desc_lines) > 1:
+ main_desc = desc_lines[0] + '.'
+ rest_desc = '.'.join(desc_lines[1:]).strip()
+ if rest_desc:
+ content += f"{main_desc}\n\n{rest_desc}\n\n"
+ else:
+ content += f"{main_desc}\n\n"
+ else:
+ content += f"{rule['full_description']}\n\n"
+ else:
+ content += f"{rule['description']}\n\n"
+
+ # Add structured sections from docstring
+ sections = rule.get('sections', {})
+
+ # Add sections in preferred order
+ preferred_order = [
+ 'What it does',
+ 'Why is this bad?',
+ 'Examples',
+ 'How to fix',
+ 'References'
+ ]
+
+ for section_name in preferred_order:
+ if section_name in sections:
+ content += f"## {section_name}\n\n{sections[section_name]}\n\n"
+
+ # Add any remaining sections not in the preferred order
+ for section_name, section_content in sections.items():
+ if section_name not in preferred_order:
+ content += f"## {section_name}\n\n{section_content}\n\n"
+
+ # Add default sections if not present in docstring
+ if 'References' not in sections:
+ content += "## References\n\n"
+ content += "- [Understanding Errors](../understanding_errors/index.md)\n"
+ content += f"- [Rule implementation]({_get_github_link(rule)})\n"
+
+ return content
+
+
+def _get_github_link(rule_details: dict[str, Any]) -> str:
+ """Generate GitHub link for rule implementation."""
+ file_path = rule_details['file_path']
+ return f"https://github.com/marimo-team/marimo/blob/main/{file_path}"
+
+
+def validate_mkdocs_integration(all_rules: dict[str, RuleInfo]) -> list[str]:
+ """Validate that all generated rule pages are included in mkdocs.yml."""
+ issues = []
+
+ # Read mkdocs.yml
+ mkdocs_path = MARIMO_ROOT / "mkdocs.yml"
+ if not mkdocs_path.exists():
+ issues.append("mkdocs.yml not found")
+ return issues
+
+ mkdocs_content = mkdocs_path.read_text()
+
+ # Check if main lint rules index is in mkdocs
+ if "guides/lint_rules/index.md" not in mkdocs_content:
+ issues.append("Main lint rules page (guides/lint_rules/index.md) not found in mkdocs.yml")
+
+ # Check if each rule page is in mkdocs
+ for code, rule in all_rules.items():
+ filename = rule.name.replace("-", "_") + ".md"
+ rule_path = f"guides/lint_rules/rules/{filename}"
+
+ if rule_path not in mkdocs_content:
+ issues.append(f"Rule page {rule_path} not found in mkdocs.yml")
+
+ return issues
+
+
+def main() -> None:
+ """Generate all lint rule documentation."""
+ print("Generating marimo lint rules documentation...")
+
+ # Discover all rules
+ all_rules = discover_all_rules()
+ print(f"📋 Discovered {len(all_rules)} rules")
+
+ # Validate all rules first
+ validation_issues = {}
+ for code, rule in all_rules.items():
+ issues = validate_rule_info(rule)
+ if issues:
+ validation_issues[code] = issues
+
+ # Check for duplicate rule codes and names across all rules
+ codes_seen = set()
+ names_seen = set()
+ global_issues = []
+
+ for code, rule in all_rules.items():
+ if code in codes_seen:
+ global_issues.append(f"Duplicate rule code: {code}")
+ codes_seen.add(code)
+
+ if rule.name in names_seen:
+ global_issues.append(f"Duplicate rule name: {rule.name}")
+ names_seen.add(rule.name)
+
+ # Check mkdocs integration
+ mkdocs_issues = validate_mkdocs_integration(all_rules)
+
+ if validation_issues or global_issues or mkdocs_issues:
+ print("❌ Validation issues found:")
+ if global_issues:
+ print(" Global issues:")
+ for issue in global_issues:
+ print(f" - {issue}")
+ if mkdocs_issues:
+ print(" mkdocs.yml issues:")
+ for issue in mkdocs_issues:
+ print(f" - {issue}")
+ for code, issues in validation_issues.items():
+ print(f" {code}:")
+ for issue in issues:
+ print(f" - {issue}")
+ return
+
+ print(f"✅ Validated {len(all_rules)} rules and mkdocs.yml integration")
+
+ # Organize rules by severity
+ rules_by_severity: dict[Severity, list[dict[str, Any]]] = {}
+ for code, rule in all_rules.items():
+ rule_details = get_rule_details(rule)
+ severity = rule_details['severity']
+
+ if severity not in rules_by_severity:
+ rules_by_severity[severity] = []
+ rules_by_severity[severity].append(rule_details)
+
+ # Create output directories
+ docs_dir = MARIMO_ROOT / "docs" / "guides" / "lint_rules"
+ rules_dir = docs_dir / "rules"
+
+ docs_dir.mkdir(parents=True, exist_ok=True)
+ rules_dir.mkdir(parents=True, exist_ok=True)
+
+ # Generate main index page
+ print("📝 Generating main index page...")
+ main_content = generate_main_index_page(rules_by_severity)
+ (docs_dir / "index.md").write_text(main_content)
+
+ # Generate individual rule pages
+ print("📝 Generating individual rule pages...")
+ for code, rule in all_rules.items():
+ rule_details = get_rule_details(rule)
+ rule_content = generate_rule_page(rule_details)
+
+ # Use the human-readable name for the filename
+ filename = rule.name.replace("-", "_") + ".md"
+ rule_file = rules_dir / filename
+ rule_file.write_text(rule_content)
+ print(f" Generated {rule_file.name}")
+
+ print(f"✅ Generated documentation for {len(all_rules)} rules")
+ print(f"📁 Documentation written to: {docs_dir}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/_lint/snapshots/cycle_dependencies_errors.txt b/tests/_lint/snapshots/cycle_dependencies_errors.txt
index 72fc6ed70f..00cfbf7e51 100644
--- a/tests/_lint/snapshots/cycle_dependencies_errors.txt
+++ b/tests/_lint/snapshots/cycle_dependencies_errors.txt
@@ -1,4 +1,4 @@
-error[cycle-dependencies]: Cell is part of a circular dependency
+critical[cycle-dependencies]: Cell is part of a circular dependency
--> tests/_lint/test_files/cycle_dependencies.py:8:1
8 | def _(z):
9 | x = 1 + z # This should trigger MR002 - cycle dependency
diff --git a/tests/_lint/snapshots/multiple_definitions_errors.txt b/tests/_lint/snapshots/multiple_definitions_errors.txt
index c427be3149..63f1c2ddd0 100644
--- a/tests/_lint/snapshots/multiple_definitions_errors.txt
+++ b/tests/_lint/snapshots/multiple_definitions_errors.txt
@@ -1,4 +1,4 @@
-error[multiple-definitions]: Variable 'x' is defined in multiple cells
+critical[multiple-definitions]: Variable 'x' is defined in multiple cells
--> tests/_lint/test_files/multiple_definitions.py:9:1
9 | print(1)
10 | x = 1
diff --git a/tests/_lint/snapshots/setup_dependencies_errors.txt b/tests/_lint/snapshots/setup_dependencies_errors.txt
index 6f77fa416b..061d3141df 100644
--- a/tests/_lint/snapshots/setup_dependencies_errors.txt
+++ b/tests/_lint/snapshots/setup_dependencies_errors.txt
@@ -1,4 +1,4 @@
-error[setup-cell-dependencies]: Setup cell cannot have dependencies
+critical[setup-cell-dependencies]: Setup cell cannot have dependencies
--> tests/_lint/test_files/setup_dependencies.py:8:1
8 | with app.setup:
9 | y = x + 1 # This should trigger MR003 - setup cell dependencies
diff --git a/tests/_lint/test_async_context_system.py b/tests/_lint/test_async_context_system.py
index 1a6279a916..de84d807f6 100644
--- a/tests/_lint/test_async_context_system.py
+++ b/tests/_lint/test_async_context_system.py
@@ -305,7 +305,7 @@ def _():
diagnostics = await ctx.get_diagnostics()
assert len(diagnostics) > 0
- assert diagnostics[0].severity == Severity.RUNTIME
+ assert diagnostics[0].severity == Severity.BREAKING
assert "multiple cells" in diagnostics[0].message
async def test_unparsable_rule(self):
@@ -366,6 +366,14 @@ def _():
# Should include all the standard rules
rule_codes = {rule.code for rule in checker.rules}
- expected_codes = {"MF001", "MR001", "MR002", "MR003", "MB001"}
+ expected_codes = {
+ "MF001",
+ "MF002",
+ "MF003",
+ "MB001",
+ "MB002",
+ "MB003",
+ "MB004",
+ }
assert expected_codes.issubset(rule_codes)
diff --git a/tests/_lint/test_streaming_early_stopping.py b/tests/_lint/test_streaming_early_stopping.py
index 8b024494a8..73fe146a4e 100644
--- a/tests/_lint/test_streaming_early_stopping.py
+++ b/tests/_lint/test_streaming_early_stopping.py
@@ -359,8 +359,8 @@ def _():
from marimo._lint.rules.breaking import MultipleDefinitionsRule
from marimo._lint.rules.formatting import GeneralFormattingRule
- # Stop on first runtime error
- config = EarlyStoppingConfig(stop_on_runtime=True)
+ # Stop on first breaking error
+ config = EarlyStoppingConfig(stop_on_breaking=True)
checker = RuleEngine(
[MultipleDefinitionsRule(), GeneralFormattingRule()],
early_stopping=config,
@@ -371,12 +371,12 @@ def _():
self.notebook
):
diagnostics.append(diagnostic)
- # Should stop after first runtime error
- if diagnostic.severity == Severity.RUNTIME:
+ # Should stop after first breaking error
+ if diagnostic.severity == Severity.BREAKING:
break
- # Should have at least one runtime diagnostic (multiple definitions)
- runtime_diagnostics = [
- d for d in diagnostics if d.severity == Severity.RUNTIME
+ # Should have at least one breaking diagnostic (multiple definitions)
+ breaking_diagnostics = [
+ d for d in diagnostics if d.severity == Severity.BREAKING
]
- assert len(runtime_diagnostics) > 0
+ assert len(breaking_diagnostics) > 0