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.

security: statically load marimo notebooks for run and edit (#4400)

Dylan Madisettidbb925621267
diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
index 406f5e70c2..d16e5ad0a9 100644
--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
@@ -179,12 +179,10 @@ export const MarimoErrorOutput = ({
className="mb-2"
>
<p className="pb-2">
- While the most cells can be in any order and contain any
- references (as long as they run in a DAG), the setup cell must be
- run first. This is because the setup cell is saved in python in
- such a way that it is immediately run when the notebook on import.
- As such, it cannot contain any references to variables defined by
- other cells.
+ The setup cell contains logic that must be run before any other
+ cell runs, including top-level imports used by top-level
+ functions. For this reason, it can't refer to other cells'
+ variables.
</p>
<p className="py-2">
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index eedb56fed0..74c7ecf6e7 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -59,7 +59,6 @@ from marimo._runtime.requests import (
FunctionCallRequest,
SetUIElementValueRequest,
)
-from marimo._utils.with_skip import SkipContext
if TYPE_CHECKING:
from collections.abc import Sequence
@@ -98,7 +97,7 @@ class _Namespace(Mapping[str, object]):
return tree(self._dict)._mime_()
-class _SetupContext(SkipContext):
+class _SetupContext:
"""
A context manager that controls imports from being executed in top level code.
See design discussion in MEP-0008 (github:marimo-team/meps/pull/8).
@@ -108,14 +107,13 @@ class _SetupContext(SkipContext):
super().__init__()
self._cell = cell
self._glbls: dict[str, Any] = {}
- self._frame = None
+ self._frame: Optional[FrameType] = None
self._previous: dict[str, Any] = {}
- def trace(self, with_frame: FrameType) -> None:
+ def __enter__(self) -> None:
+ with_frame = sys._getframe(1)
+
if refs := self._cell.refs - set(builtins.__dict__.keys()):
- if runtime_context_installed():
- self.skip()
- return
# Otherwise fail in say a script context.
raise SetupRootError(
f"The setup cell cannot reference any additional variables: {refs}"
@@ -132,12 +130,8 @@ class _SetupContext(SkipContext):
self,
exception: Optional[type[BaseException]],
instance: Optional[BaseException],
- _tracebacktype: Optional[TracebackType],
+ _traceback: Optional[TracebackType],
) -> Literal[False]:
- # Must be a Literal[False], for linters.
- # Whether to suppress a given exception.
- self.teardown()
-
# Manually hold on to defs for injection into script mode.
if self._frame is not None:
for var in self._cell.defs:
@@ -152,21 +146,12 @@ class _SetupContext(SkipContext):
if self._cell._app is not None:
app = self._cell._app._app
self._frame.f_locals["app"] = self._previous.get("app", app)
- # lose ref
self._previous = {}
if exception is not None:
- LOGGER.warning(
- "The setup cell was unable to execute, your notebook may not "
- "work as expected."
- )
- LOGGER.debug("Exception: %s", exception)
-
# Always should fail, since static loading still allows bad apps to
# load.
- # TODO(dmadisetti): Allow error to propagate on static app loads.
- return False # type: ignore
-
+ raise exception
return False
@@ -245,11 +230,13 @@ class App:
self._setup: Optional[_SetupContext] = None
# Filename is derived from the callsite of the app
- self._filename: str | None = None
- try:
- self._filename = inspect.getfile(inspect.stack()[1].frame)
- except Exception:
- ...
+ # unless explicitly set (e.g. for static loading case)
+ self._filename: str | None = kwargs.get("_filename", None)
+ if self._filename is None:
+ try:
+ self._filename = inspect.getfile(inspect.stack()[1].frame)
+ except Exception:
+ ...
def __del__(self) -> None:
try:
diff --git a/marimo/_ast/app_config.py b/marimo/_ast/app_config.py
index 2db2f3d871..4c4ba8a3a7 100644
--- a/marimo/_ast/app_config.py
+++ b/marimo/_ast/app_config.py
@@ -37,16 +37,17 @@ class _AppConfig:
# The type of SQL output to display
sql_output: SqlOutputType = "auto"
- # Experimental top-level cell support
- _toplevel_fn: bool = False
-
@staticmethod
def from_untrusted_dict(updates: dict[str, Any]) -> "_AppConfig":
+ # Certain flags are useful to pass to App for construction, but
+ # shouldn't make it into the config. (e.g. the _filename flag is
+ # internal)
+ other_allowed = {"_filename"}
config = _AppConfig()
for key in updates:
if hasattr(config, key):
config.__setattr__(key, updates[key])
- else:
+ elif key not in other_allowed:
LOGGER.warning(
f"Unrecognized key '{key}' in app config. Ignoring."
)
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index bfc5758848..5a5ac76ae7 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -600,7 +600,7 @@ class Cell:
"""
assert self._app is not None
- # Inject setup cell definitions so that We do not rerun the setup cell.
+ # Inject setup cell definitions so that we do not rerun the setup cell.
# With an exception for tests that should act as if it's in runtime.
if "PYTEST_CURRENT_TEST" not in os.environ:
if self._app._app._setup is not None:
diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.py
index a3648ecd9e..33132a9b3a 100644
--- a/marimo/_ast/cell_manager.py
+++ b/marimo/_ast/cell_manager.py
@@ -21,11 +21,16 @@ from marimo._ast.cell import Cell, CellConfig
from marimo._ast.compiler import (
cell_factory,
context_cell_factory,
+ ir_cell_factory,
toplevel_cell_factory,
)
from marimo._ast.models import CellData
from marimo._ast.names import DEFAULT_CELL_NAME, SETUP_CELL_NAME
from marimo._ast.pytest import process_for_pytest
+from marimo._schemas.serialization import (
+ CellDef,
+ SetupCell,
+)
from marimo._types.ids import CellId_t
if TYPE_CHECKING:
@@ -86,7 +91,6 @@ class CellManager:
self.seen_ids.add(CellId_t(_id))
return CellId_t(_id)
- # TODO: maybe remove this, it is leaky
def cell_decorator(
self,
obj: Obj[P, R] | None,
@@ -98,6 +102,9 @@ class CellManager:
top_level: bool = False,
) -> Cell | Obj[P, R] | Callable[[Obj[P, R]], Cell | Obj[P, R]]:
"""Create a cell decorator for marimo notebook cells."""
+ # NB. marimo also statically loads notebooks via the marimo/_ast/load
+ # path. This code is only called when run as a script or imported as a
+ # module.
cell_config = CellConfig(
column=column, disabled=disabled, hide_code=hide_code
)
@@ -161,6 +168,8 @@ class CellManager:
def _register_cell(
self, cell: Cell, app: InternalApp | None = None
) -> None:
+ if app is None:
+ raise ValueError("app must not be None")
if app is not None:
cell._register_app(app)
cell_impl = cell._cell
@@ -200,6 +209,20 @@ class CellManager:
cell=cell,
)
+ def register_ir_cell(
+ self, cell_def: CellDef, app: InternalApp | None = None
+ ) -> None:
+ if isinstance(cell_def, SetupCell):
+ cell_id = CellId_t(SETUP_CELL_NAME)
+ else:
+ cell_id = self.create_cell_id()
+ cell = ir_cell_factory(cell_def, cell_id=cell_id)
+ cell_config = CellConfig(
+ **cell_def.options,
+ )
+ cell._cell.configure(cell_config)
+ self._register_cell(cell, app=app)
+
def register_unparsable_cell(
self,
code: str,
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index a1991b3c2f..1c0b465858 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import ast
import builtins
-import importlib.util
import json
import os
import re
@@ -12,7 +11,6 @@ import textwrap
from typing import Any, Literal, Optional, cast
from marimo import __version__
-from marimo._ast.app import App
from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig, CellImpl
from marimo._ast.compiler import compile_cell
@@ -152,7 +150,7 @@ def build_setup_section(setup_cell: Optional[CellImpl]) -> str:
has_only_comments = all(
not line.strip() or line.strip().startswith("#")
- for line in block.splitlines()
+ for line in setup_cell.code.splitlines()
)
# Fails otherwise
if has_only_comments:
@@ -398,73 +396,6 @@ def generate_filecontents(
return "\n".join(filecontents)
-class MarimoFileError(Exception):
- pass
-
-
-def get_app(filename: Optional[str]) -> Optional[App]:
- """Load and return app from a marimo-generated module.
-
- Args:
- filename: Path to a marimo notebook file (.py or .md)
-
- Returns:
- The marimo App instance if the file exists and contains valid code,
- None if the file is empty or contains only comments.
-
- Raises:
- MarimoFileError: If the file exists but doesn't define a valid marimo app
- RuntimeError: If there are issues loading the module
- SyntaxError: If the file contains a syntax error
- FileNotFoundError: If the file doesn't exist
- """
- if filename is None:
- return None
-
- with open(filename, encoding="utf-8") as f:
- contents = f.read().strip()
-
- if not contents:
- return None
-
- if filename.endswith(".md"):
- from marimo._cli.convert.markdown import convert_from_md_to_app
-
- return convert_from_md_to_app(contents)
-
- # Below assumes it's a Python file
-
- # This means it could have only the package dependencies
- # but no actual code yet.
- has_only_comments = all(
- not line.strip() or line.strip().startswith("#")
- for line in contents.splitlines()
- )
- if has_only_comments:
- return None
-
- # TODO(dmadisetti): Consider replacing with a completely static load for
- # edit.
- spec = importlib.util.spec_from_file_location("marimo_app", filename)
- if spec is None:
- raise RuntimeError("Failed to load module spec")
- marimo_app = importlib.util.module_from_spec(spec)
- if spec.loader is None:
- raise RuntimeError("Failed to load module spec's loader")
- try:
- sys.modules["marimo_app"] = marimo_app
- spec.loader.exec_module(marimo_app) # This may throw a SyntaxError
- finally:
- sys.modules.pop("marimo_app", None)
- if not hasattr(marimo_app, "app"):
- raise MarimoFileError(f"{filename} missing attribute `app`.")
- if not isinstance(marimo_app.app, App):
- raise MarimoFileError("`app` attribute must be of type `marimo.App`.")
-
- app = marimo_app.app
- return app
-
-
def recover(filename: str) -> str:
"""Generate a module for code recovered from a disconnected frontend"""
with open(filename, encoding="utf-8") as f:
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.py
index 9b8d473152..6675f4e8be 100644
--- a/marimo/_ast/compiler.py
+++ b/marimo/_ast/compiler.py
@@ -10,10 +10,11 @@ import re
import sys
import textwrap
import token as token_types
-from tokenize import TokenInfo, tokenize
+from tokenize import tokenize
from typing import TYPE_CHECKING, Any, Callable, Optional
from marimo import _loggers
+from marimo._ast import parse
from marimo._ast.cell import (
Cell,
CellImpl,
@@ -24,6 +25,7 @@ from marimo._ast.names import SETUP_CELL_NAME
from marimo._ast.transformers import ContainedExtractWithBlock
from marimo._ast.variables import is_local
from marimo._ast.visitor import ImportData, Name, ScopedVisitor
+from marimo._schemas.serialization import CellDef, ClassCell
from marimo._types.ids import CellId_t
from marimo._utils.tmpdir import get_tmpdir
@@ -36,7 +38,6 @@ LOGGER = _loggers.marimo_logger()
Cls: TypeAlias = type
if TYPE_CHECKING:
- from collections.abc import Iterator
from types import FrameType
@@ -335,7 +336,7 @@ def context_cell_factory(
end_node = with_block.body[-1]
col_offset = start_node.col_offset
# A trailing "pass" is added in cases where there are only comments.
- end_line = end_node.end_lineno + 1
+ end_line = end_node.end_lineno
if start_node == end_node and lines[end_line - 1].strip() == "pass":
end_line -= 1
cell_code = textwrap.dedent("\n".join(lines[entry_line:end_line])).rstrip()
@@ -413,6 +414,22 @@ def toplevel_cell_factory(
)
+def ir_cell_factory(cell_def: CellDef, cell_id: CellId_t) -> Cell:
+ test_name = isinstance(cell_def, ClassCell) and cell_def.name.startswith(
+ "Test"
+ )
+ test_name |= not isinstance(
+ cell_def, ClassCell
+ ) and cell_def.name.startswith("test_")
+ return Cell(
+ _name=cell_def.name,
+ _cell=compile_cell(
+ cell_def.code,
+ cell_id=cell_id,
+ ),
+ )
+
+
def cell_factory(
f: Callable[..., Any],
cell_id: CellId_t,
@@ -428,114 +445,19 @@ def cell_factory(
code, lnum = inspect.getsourcelines(f)
function_code = textwrap.dedent("".join(code))
- # tokenize to find the start of the function body, including
- # comments --- we have to use tokenize because the ast treats the first
- # line of code as the starting line of the function body, whereas we
- # want the first indented line after the signature
- tokens: Iterator[TokenInfo] = tokenize(
- io.BytesIO(function_code.encode("utf-8")).readline
- )
-
- def_node: Optional[TokenInfo] = None
- for token in tokens:
- if token.type == token_types.NAME and token.string == "def":
- def_node = token
- break
- assert def_node is not None
-
- paren_counter: Optional[int] = None
- for token in tokens:
- if token.type == token_types.OP and token.string == "(":
- paren_counter = 1 if paren_counter is None else paren_counter + 1
- elif token.type == token_types.OP and token.string == ")":
- assert paren_counter is not None
- paren_counter -= 1
-
- if paren_counter == 0:
- break
- assert paren_counter == 0
-
- for token in tokens:
- if token.type == token_types.OP and token.string == ":":
- break
-
- after_colon = next(tokens)
- start_line: int
- start_col: int
- if after_colon.type == token_types.NEWLINE:
- fn_body_token = next(tokens)
- start_line = fn_body_token.start[0] - 1
- start_col = 0
- elif after_colon.type == token_types.COMMENT:
- newline_token = next(tokens)
- assert newline_token.type == token_types.NEWLINE
- fn_body_token = next(tokens)
- start_line = fn_body_token.start[0] - 1
- start_col = 0
- else:
- # function body starts on same line as definition, such as in
- # the following examples:
- #
- # def foo(): pass
- #
- # def foo(): x = 0; return x
- #
- # def foo(): x = """
- #
- # """; return x
- fn_body_token = after_colon
- start_line = fn_body_token.start[0] - 1
- start_col = fn_body_token.start[1]
-
- col_offset = fn_body_token.end[1] - start_col
-
- # it would be difficult to tell if the last return token were in fact the
- # last statement of the function body, so we use the ast, which lets us
- # easily find the last statement of the function body;
- tree = ast.parse(function_code)
- return_node: Optional[ast.Return]
- first_stmt = tree.body[0]
- # Handle case where first statement does not have a body
- if not hasattr(first_stmt, "body"):
- return_node = None
- else:
- return_node = (
- first_stmt.body[-1] # type: ignore
- if isinstance(first_stmt.body[-1], ast.Return) # type: ignore
- else None
- )
-
- end_line, return_offset = (
- (return_node.lineno - 1, return_node.col_offset)
- if return_node is not None
- else (None, None)
- )
-
- cell_code: str
- lines = function_code.split("\n")
- if start_line == end_line:
- # remove leading indentation
- cell_code = textwrap.dedent(lines[start_line][start_col:return_offset])
- else:
- first_line = lines[start_line][start_col:]
- cell_code = textwrap.dedent(
- "\n".join([first_line] + lines[start_line + 1 : end_line])
- ).strip()
- if end_line is not None and not lines[end_line].strip().startswith(
- "return"
- ):
- # handle return written on same line as last statement in cell
- cell_code += "\n" + lines[end_line][:return_offset]
+ extractor = parse.Extractor(contents=function_code)
+ func_ast = ast.parse(function_code).body[0]
+ cell_def = extractor.to_cell(func_ast, attribute="cell")
# anonymous file is required for deterministic testing.
source_position = None
if not anonymous_file:
source_position = get_source_position(
- f, lnum + start_line - 1, col_offset
+ f, lnum + cell_def.lineno - 1, cell_def.col_offset
)
cell = compile_cell(
- cell_code,
+ cell_def.code,
cell_id=cell_id,
source_position=source_position,
test_rewrite=test_rewrite,
diff --git a/marimo/_ast/load.py b/marimo/_ast/load.py
new file mode 100644
index 0000000000..3593a16f51
--- /dev/null
+++ b/marimo/_ast/load.py
@@ -0,0 +1,119 @@
+# Copyright 2025 Marimo. All rights reserved.
+from __future__ import annotations
+
+import importlib.util
+import sys
+from typing import Optional
+
+from marimo import _loggers
+from marimo._ast.app import App, InternalApp
+from marimo._ast.parse import MarimoFileError, parse_notebook
+from marimo._schemas.serialization import UnparsableCell
+
+LOGGER = _loggers.marimo_logger()
+
+# Notebooks have 4 entry points:
+# 1. edit mode
+# 2. run mode
+# 3. as a script
+# 4. loaded as a module
+#
+# When being run as a script or module, the expectation is to run _as_ python.
+# However for "managed" marimo (i.e. run/ edit), the expectation is to not fail
+# on startup and defer errors to the runtime.
+
+
+def _maybe_contents(filename: Optional[str]) -> Optional[str]:
+ if filename is None:
+ return None
+
+ with open(filename, encoding="utf-8") as f:
+ contents = f.read().strip()
+
+ return contents
+
+
+# Used in tests and current fallback
+def _dynamic_load(filename: str) -> Optional[App]:
+ """Create and execute a module with the provided filename."""
+ contents = _maybe_contents(filename)
+ if not contents:
+ return None
+
+ spec = importlib.util.spec_from_file_location("marimo_app", filename)
+ if spec is None:
+ raise RuntimeError("Failed to load module spec")
+ marimo_app = importlib.util.module_from_spec(spec)
+ if spec.loader is None:
+ raise RuntimeError("Failed to load module spec's loader")
+ try:
+ sys.modules["marimo_app"] = marimo_app
+ spec.loader.exec_module(marimo_app) # This may throw a SyntaxError
+ finally:
+ sys.modules.pop("marimo_app", None)
+ if not hasattr(marimo_app, "app"):
+ return None
+ if not isinstance(marimo_app.app, App):
+ raise MarimoFileError("`app` attribute must be of type `marimo.App`.")
+
+ app = marimo_app.app
+ return app
+
+
+def _static_load(filename: str) -> Optional[App]:
+ notebook = parse_notebook(filename)
+ if notebook is None or not notebook.valid:
+ return None
+ app = App(**notebook.app.options, _filename=filename)
+ for cell in notebook.cells:
+ if isinstance(cell, UnparsableCell):
+ app._unparsable_cell(cell.code, **cell.options)
+ continue
+ app._cell_manager.register_ir_cell(cell, InternalApp(app))
+ return app
+
+
+def load_app(filename: Optional[str]) -> Optional[App]:
+ """Load and return app from a marimo-generated module.
+
+ Args:
+ filename: Path to a marimo notebook file (.py or .md)
+
+ Returns:
+ The marimo App instance if the file exists and contains valid code,
+ None if the file is empty or contains only comments.
+
+ Raises:
+ MarimoFileError: If the file exists but doesn't define a valid marimo app
+ RuntimeError: If there are issues loading the module
+ SyntaxError: If the file contains a syntax error
+ FileNotFoundError: If the file doesn't exist
+ """
+
+ if filename is None:
+ return None
+
+ if filename.endswith(".md"):
+ contents = _maybe_contents(filename)
+ if not contents:
+ return None
+ from marimo._cli.convert.markdown import convert_from_md_to_app
+
+ return convert_from_md_to_app(contents) if contents else None
+
+ if not filename.endswith(".py"):
+ raise MarimoFileError("File must end with .py or .md")
+
+ try:
+ return _static_load(filename)
+ except MarimoFileError:
+ # Security advantages of static load are lost here, but reasonable
+ # fallback for now.
+ _app = _dynamic_load(filename)
+ LOGGER.warning(
+ "Static loading of notebook failed; "
+ "falling back to dynamic loading. "
+ "If you can, please report this issue to the marimo team — "
+ "https://github.com/marimo-team/marimo/issues/new?template=bug_report.yaml"
+ )
+ return _app
diff --git a/marimo/_ast/parse.py b/marimo/_ast/parse.py
new file mode 100644
index 0000000000..b6e70b0bd2
--- /dev/null
+++ b/marimo/_ast/parse.py
@@ -0,0 +1,866 @@
+# Copyright 2025 Marimo. All rights reserved.
+from __future__ import annotations
+
+import ast
+import io
+import token as token_types
+from textwrap import dedent
+from tokenize import TokenInfo, tokenize
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Generic,
+ Optional,
+ TypeVar,
+ Union,
+ cast,
+)
+
+from marimo._ast.names import DEFAULT_CELL_NAME, SETUP_CELL_NAME
+from marimo._schemas.serialization import (
+ AppInstantiation,
+ CellDef,
+ ClassCell,
+ FunctionCell,
+ Header,
+ NotebookSerialization,
+ SetupCell,
+ UnparsableCell,
+ Violation,
+)
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+
+ from typing_extensions import TypeAlias
+
+
+FnNode: TypeAlias = Union[ast.FunctionDef, ast.AsyncFunctionDef]
+CellNode: TypeAlias = Union[FnNode, ast.ClassDef]
+Node: TypeAlias = Union[ast.stmt, ast.expr]
+
+
+V = TypeVar("V")
+U = TypeVar("U")
+
+
+class MarimoFileError(Exception):
+ pass
+
+
+class Extractor:
+ """Helper to extract AST nodes to schema/serialization ir."""
+
+ def __init__(
+ self, filename: Optional[str] = None, contents: Optional[str] = None
+ ):
+ self.contents = None
+ if filename is not None:
+ assert contents is None, (
+ "Cannot provide both filename and contents"
+ )
+ with open(filename, encoding="utf-8") as f:
+ self.contents = f.read().strip()
+ elif contents is not None:
+ self.contents = contents
+
+ self.lines = self.contents.splitlines() if self.contents else []
+
+ def extract_from_offsets(
+ self,
+ lineno: int,
+ col_offset: int,
+ end_lineno: int,
+ end_col_offset: Optional[int],
+ ) -> str:
+ if lineno == end_lineno:
+ return self.lines[lineno][col_offset:end_col_offset]
+ if lineno + 1 == end_lineno:
+ return "\n".join(
+ [
+ self.lines[lineno][col_offset:],
+ self.lines[end_lineno][:end_col_offset],
+ ]
+ )
+ return "\n".join(
+ [
+ self.lines[lineno][col_offset:],
+ "\n".join(self.lines[lineno + 1 : end_lineno]),
+ self.lines[end_lineno][:end_col_offset],
+ ]
+ )
+
+ def extract_from_code(self, node: Node) -> str:
+ # NB. Ast line reference and col index is on a 1-indexed basis.
+ lineno = node.lineno
+ col_offset = node.col_offset
+
+ if hasattr(node, "decorator_list"):
+ # From the ast, having a decorator list means we are either a
+ # function or a class.
+ assert isinstance(
+ node, (ast.AsyncFunctionDef, ast.FunctionDef, ast.ClassDef)
+ )
+
+ # Scrub past the decorator + 1, lineno 1 index -1
+ if (
+ len(node.decorator_list)
+ and (decorator := get_valid_decorator(node)) # type: ignore
+ ):
+ lineno = _none_to_0(decorator.end_lineno)
+ col_offset = decorator.col_offset - 1
+ else:
+ lineno -= 1
+
+ code = self.extract_from_offsets(
+ lineno,
+ col_offset,
+ _none_to_0(node.end_lineno) - 1,
+ _none_to_0(node.end_col_offset),
+ )
+ return dedent(code)
+
+ def to_cell_def(self, node: FnNode, kwargs: dict[str, Any]) -> CellDef:
+ # A general note on the apparent brittleness of this code:
+ # - Ast line reference and col index is on a 1-indexed basis
+ # - Multiline statements need to be accounted for
+ # - Painstaking testing can be found in test/_ast/test_{load, parse}
+
+ function_code = self.extract_from_code(node)
+ lineno_offset, col_offset = extract_offsets_post_colon(
+ function_code,
+ block_start="def",
+ )
+ start_lineno = node.lineno + lineno_offset
+
+ end_lineno = _none_to_0(node.end_lineno)
+ end_col_offset = node.end_col_offset
+ assert len(node.body) > 0
+ if node.lineno - node.body[0].lineno == 0:
+ # Quirk where the ellipse token seems to have a line index at
+ # the end of the dots ...<
+ if isinstance(getattr(node.body[0], "value", None), ast.Ellipsis):
+ col_offset += node.body[0].col_offset - 3
+ else:
+ col_offset += node.body[0].col_offset - 1
+ else:
+ col_offset = 0
+
+ has_return = isinstance(node.body[-1], ast.Return)
+ single_line = node.lineno - node.body[-1].lineno == 0
+ if has_return:
+ # we need to adjust for the trailing return statement
+ # which is not included in the function body
+ if len(node.body) > 1:
+ end_lineno = max(
+ _none_to_0(node.body[-2].end_lineno),
+ node.body[-1].lineno - 1,
+ )
+ end_col_offset = len(self.lines[end_lineno - 1]) + 1
+ if node.body[-1].end_lineno == end_lineno:
+ end_lineno = node.body[-1].lineno
+ end_col_offset = node.body[-1].col_offset
+
+ # We're in the case where we have something like
+ # @app.cell
+ # def foo():
+ # # Just comments
+ # return
+ else:
+ # If we are on the same line as the return statement,
+ # just return a blank cell.
+ if start_lineno == node.body[0].lineno:
+ return CellDef(
+ code="",
+ options=kwargs,
+ lineno=start_lineno,
+ col_offset=node.col_offset + col_offset,
+ end_lineno=start_lineno,
+ end_col_offset=len(self.lines[-1]),
+ name=getattr(node, "name", DEFAULT_CELL_NAME),
+ )
+ else:
+ end_lineno = node.body[-1].lineno - 1
+ end_col_offset = None
+
+ # NB. node.[end_]lineno only captures the starting line of the
+ # captured node, same with col_offset.
+ # If the node spans multiple lines, then we need to adjust these
+ # positions such that _all_ relevant text is captured.
+ cell_code = self.extract_from_offsets(
+ lineno=start_lineno - 1,
+ col_offset=col_offset,
+ end_lineno=end_lineno - 1,
+ end_col_offset=end_col_offset,
+ )
+
+ # NB: Feels pretty hacky, would love if someone had a suggestion for this
+ # But the only other better way (I can see) is to drop down to the
+ # toeknizer lever and handle it there + handle particular edge
+ # cases.
+ #
+ # If the last value is not a return statement, we need to grab
+ # trailing comments.
+ if not has_return and not single_line:
+ # Determine leading spaces
+ leading_spaces = len(cell_code) - len(cell_code.lstrip())
+ indent = cell_code[:leading_spaces]
+
+ # Attempt to keep adding lines, and ensure it dedents to the correct
+ # level
+ new_end = end_lineno - 1
+ for new_end in range(end_lineno, len(self.lines)):
+ if not self.lines[new_end].strip() or self.lines[
+ new_end
+ ].startswith(indent):
+ end_col_offset = len(self.lines[new_end])
+ continue
+ new_end -= 1
+ break
+ if new_end > end_lineno:
+ cell_code += "\n".join(
+ self.lines[end_lineno : new_end + 1]
+ ).rstrip()
+ end_lineno = new_end - 1
+
+ if end_col_offset is None:
+ end_col_offset = 0
+
+ # Line positioning here is still consequential for correct stack tracing
+ # produced in _ast.compiler.
+ return CellDef(
+ code=dedent(cell_code),
+ options=kwargs,
+ lineno=start_lineno - 1,
+ col_offset=node.col_offset + col_offset,
+ end_lineno=_none_to_0(node.end_lineno) + end_lineno,
+ end_col_offset=_none_to_0(node.end_col_offset) + end_col_offset,
+ name=getattr(node, "name", DEFAULT_CELL_NAME),
+ )
+
+ def to_setup_cell(self, node: Node) -> SetupCell:
+ kwargs, _violations = _maybe_kwargs(node.items[0].context_expr) # type: ignore
+ code = self.extract_from_code(node)
+ code = dedent(code)
+ if code.endswith("\npass"):
+ code = code[: -len("\npass")]
+ return SetupCell(
+ code=code,
+ options=kwargs,
+ lineno=node.lineno,
+ col_offset=node.col_offset,
+ end_lineno=max(node.lineno, _none_to_0(node.end_lineno)),
+ end_col_offset=_none_to_0(node.end_col_offset),
+ name=SETUP_CELL_NAME,
+ )
+
+ def to_cell(self, node: Node, attribute: Optional[str] = None) -> CellDef:
+ """Convert an AST node to a CellDef."""
+ if isinstance(
+ node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)
+ ):
+ decorator = get_valid_decorator(node)
+ kwargs, _violations = _maybe_kwargs(decorator)
+ if attribute is None and decorator is not None:
+ if isinstance(decorator, ast.Call):
+ if not hasattr(decorator.func, "attr"):
+ raise MarimoFileError(
+ "Invalid decorator, expected form `@app.fn`"
+ )
+ attribute = decorator.func.attr
+ else:
+ attribute = decorator.attr
+
+ # switch on app.cell vs app.function
+ if attribute == "cell":
+ assert isinstance(
+ node, (ast.FunctionDef, ast.AsyncFunctionDef)
+ ), "@app.cell cannot be used on classes."
+ return self.to_cell_def(node, kwargs)
+ cell_types: dict[Optional[str], type[CellDef]] = {
+ "function": FunctionCell,
+ "class_definition": ClassCell,
+ }
+ cell_type = cell_types.get(attribute, None)
+ if cell_type is not None:
+ return cell_type(
+ code=self.extract_from_code(node),
+ _ast=node,
+ options=kwargs,
+ )
+
+ raise MarimoFileError(f"Unsupported cell type. {attribute}")
+ elif is_unparsable_cell(node):
+ # These are all captured by is_unparsable_cell
+ # but mypy is struggling.
+ kwargs, _violations = _eval_kwargs(node.value.keywords) # type: ignore
+ return UnparsableCell(
+ code=node.value.args[0].value, # type: ignore
+ options=kwargs,
+ _ast=node,
+ )
+
+ raise MarimoFileError(
+ "Unexpected node type for cell extraction. "
+ "Please report this issue to the Marimo team with "
+ "your code if possible: "
+ "github.com/marimo-team/marimo/issues"
+ )
+
+
+class ParseResult(Generic[V]):
+ """Helper class to bundle "violations" and results"""
+
+ __slots__ = ("_value", "_violations")
+
+ def __init__(
+ self,
+ value: V | None = None,
+ violations: list[Violation] | None = None,
+ ) -> None:
+ self._value = value
+ self._violations = []
+ if violations is not None:
+ self._violations = violations
+
+ @property
+ def violations(self) -> list[Violation]:
+ return self._violations
+
+ def __bool__(self) -> bool:
+ return self._value is not None
+
+ def unwrap(self) -> V:
+ return cast(V, self._value)
+
+
+class Parser:
+ """
+ Parser scrubs through tokens given a file to extract relevant parts of
+ the notebook.
+ """
+
+ def __init__(self, *args: Any, **kwargs: Any):
+ self.extractor = Extractor(*args, **kwargs)
+
+ def node_stack(self) -> PeekStack[Node]:
+ return PeekStack(iter(ast.parse(self.extractor.contents or "").body))
+
+ def parse_header(self, body: PeekStack[Node]) -> ParseResult[Header]:
+ # header? = (docstring | comments)*
+ while node := next(body):
+ # Just string, comments are stripped
+ if not is_string(node):
+ break
+
+ if not node:
+ end_lineno = len(self.extractor.lines) - 1
+ end_col_offset = len(self.extractor.lines[-1])
+ return ParseResult(
+ Header(
+ lineno=0,
+ col_offset=0,
+ end_lineno=end_lineno,
+ end_col_offset=end_col_offset,
+ value=self.extractor.extract_from_offsets(
+ 0, 0, end_lineno, end_col_offset
+ ),
+ )
+ )
+
+ return ParseResult(
+ Header(
+ lineno=0,
+ col_offset=0,
+ end_lineno=node.lineno - 1,
+ end_col_offset=node.col_offset,
+ value=self.extractor.extract_from_offsets(
+ 0, 0, node.lineno - 1, node.col_offset
+ ),
+ )
+ )
+
+ def parse_import(self, body: PeekStack[Node]) -> ParseResult[Node]:
+ # app = import marimo + __generated_with + App(kwargs*)
+ violations: list[Violation] = []
+
+ # Attempt to find import statement
+ node = body.last
+ while node:
+ if is_marimo_import(node):
+ return ParseResult(node, violations=violations)
+ violations.append(
+ Violation(
+ "Unexpected statement (expected marimo import)",
+ lineno=node.lineno,
+ )
+ )
+ node = next(body)
+ return ParseResult(violations=violations)
+
+ def parse_version(self, body: PeekStack[Node]) -> ParseResult[str]:
+ # __generated_with not being correctly set should not break marimo.
+ violations: list[Violation] = []
+ node = body.peek()
+ version = _maybe_version(node) if node else None
+ if not version:
+ lineno = node.lineno if node else 0
+ violations.append(
+ Violation(
+ "Expected `__generated_with` assignment for marimo version number.",
+ lineno=lineno,
+ )
+ )
+ else:
+ # dequeue since version was consumed
+ next(body)
+ return ParseResult(version, violations=violations)
+
+ def parse_app(
+ self, body: PeekStack[Node]
+ ) -> ParseResult[AppInstantiation]:
+ # app = import marimo + __generated_with + App(kwargs*)
+ violations: list[Violation] = []
+ node = body.last
+ while node:
+ if is_app_def(node):
+ # type caught by is_app_def
+ _kwargs, _violations = _eval_kwargs(node.value.keywords) # type: ignore
+ violations.extend(_violations)
+ return ParseResult(
+ AppInstantiation(
+ options=_kwargs,
+ )
+ )
+ violations.append(
+ Violation(
+ "Unexpected statement, expected App initialization.",
+ node.lineno,
+ )
+ )
+ node = next(body)
+
+ return ParseResult(violations=violations)
+
+ def parse_setup(self, body: PeekStack[Node]) -> ParseResult[SetupCell]:
+ # setup? = Async?With(kwargs*, stmt*)
+ violations: list[Violation] = []
+ node = body.last
+ maybe_setup = node
+ while node:
+ if is_cell(maybe_setup := body.peek()):
+ break
+ node = next(body)
+ if not node:
+ return ParseResult(violations=violations)
+ violations.append(
+ Violation(
+ "Unexpected statement, expected cell definitions.",
+ node.lineno,
+ )
+ )
+
+ if maybe_setup and is_setup_cell(maybe_setup):
+ next(body)
+ return ParseResult(
+ self.extractor.to_setup_cell(maybe_setup),
+ violations=violations,
+ )
+ return ParseResult(violations=violations)
+
+ def parse_body(self, body: PeekStack[Node]) -> ParseResult[list[CellDef]]:
+ # Continue with remainder of body
+ cells = []
+ violations: list[Violation] = []
+
+ while node := next(body):
+ if is_body_cell(node):
+ cells.append(self.extractor.to_cell(node))
+ elif is_run_guard(node):
+ break
+ else:
+ violations.append(
+ Violation(
+ "Unexpected statement, expected body cell definition.",
+ node.lineno,
+ )
+ )
+ return ParseResult(
+ cells,
+ violations=violations,
+ )
+
+
+class PeekStack(Generic[U]):
+ """Builtins don't have a peek, which is useful here."""
+
+ def __init__(self, iterable: Iterator[U]):
+ self._iterable = iterable
+ self._next: Optional[U] = None
+ self.last: Optional[U] = None
+
+ def __next__(self) -> Optional[U]:
+ if self._next:
+ self.last = self._next
+ self._next = None
+ else:
+ try:
+ self.last = next(self._iterable)
+ except StopIteration:
+ self.last = None
+ return self.last
+
+ def peek(self) -> Optional[U]:
+ if self._next:
+ return self._next
+ try:
+ self._next = next(self._iterable)
+ except StopIteration:
+ self._next = None
+ return self._next
+
+
+def _maybe_kwargs(
+ node: Optional[ast.expr],
+) -> tuple[dict[str, Any], list[Violation]]:
+ if isinstance(node, ast.Call):
+ return _eval_kwargs(node.keywords)
+ elif node is None or isinstance(node, ast.Attribute):
+ return {}, []
+ raise MarimoFileError(f"Provided node ({node}) is not an attribute.")
+
+
+def _maybe_version(node: Node) -> Optional[str]:
+ # Expected ast:
+ #
+ # Assign(
+ # targets=[
+ # Name(id='__generated_with', ctx=Store())],
+ # value=Constant(value=...)
+ # )
+ if (
+ isinstance(node, ast.Assign)
+ and len(node.targets) == 1
+ and isinstance(node.targets[0], ast.Name)
+ and node.targets[0].id == "__generated_with"
+ and isinstance(node.value, ast.Constant)
+ ):
+ return str(node.value.value)
+ return None
+
+
+def _eval_kwargs(
+ keywords: list[ast.keyword],
+) -> tuple[dict[str, Any], list[Violation]]:
+ """Convert a list of keyword arguments to a dictionary."""
+ kwargs = {}
+ violations = []
+ for kw in keywords:
+ # Only accept Constants
+ if kw.arg and isinstance(kw.value, ast.Constant):
+ kwargs[kw.arg] = kw.value.value
+ else:
+ violations.append(
+ Violation(
+ "Unexpected value for keyword argument",
+ lineno=kw.lineno,
+ col_offset=kw.col_offset,
+ )
+ )
+ return kwargs, violations
+
+
+def _none_to_0(n: Optional[int]) -> int:
+ return n if n is not None else 0
+
+
+def extract_offsets_post_colon(
+ function_code: str, block_start: str = "def"
+) -> tuple[int, int]:
+ # tokenize to find the start of the function body, including
+ # comments --- we have to use tokenize because the ast treats the first
+ # line of code as the starting line of the function body, whereas we
+ # want the first indented line after the signature
+ tokens = PeekStack(
+ tokenize(io.BytesIO(function_code.encode("utf-8")).readline)
+ )
+
+ def_node: Optional[TokenInfo] = None
+ while token := next(tokens):
+ if token.type == token_types.NAME and token.string == block_start:
+ def_node = token
+ break
+ assert def_node is not None
+
+ paren_counter: Optional[int] = None
+ token = tokens.peek()
+ while token := next(tokens):
+ if token.type == token_types.OP and token.string == "(":
+ paren_counter = 1 if paren_counter is None else paren_counter + 1
+ elif token.type == token_types.OP and token.string == ")":
+ assert paren_counter is not None
+ paren_counter -= 1
+
+ # NB. Paren counter is initially _None_
+ # So this doesn't activate until we see the first paren.
+ if paren_counter == 0:
+ break
+ elif paren_counter is None:
+ # In the setup block case, parens are not bound to be present.
+ next_token = tokens.peek()
+ if (
+ next_token
+ and next_token.type == token_types.OP
+ and next_token.string == ":"
+ ):
+ paren_counter = 0
+ break
+
+ assert paren_counter == 0
+
+ while token := next(tokens):
+ if token.type == token_types.OP and token.string == ":":
+ break
+
+ after_colon = next(tokens)
+ assert after_colon
+ start_line: int
+ start_col: int
+ if after_colon.type == token_types.NEWLINE:
+ fn_body_token = next(tokens)
+ assert fn_body_token
+ start_line = fn_body_token.start[0] - 1
+ start_col = 0
+ elif after_colon.type == token_types.COMMENT:
+ newline_token = next(tokens)
+ assert newline_token
+ assert newline_token.type == token_types.NEWLINE
+ fn_body_token = next(tokens)
+ assert fn_body_token
+ start_line = fn_body_token.start[0] - 1
+ start_col = 0
+ else:
+ # function body starts on same line as definition, such as in
+ # the following examples:
+ #
+ # def foo(): pass
+ #
+ # def foo(): x = 0; return x
+ #
+ # def foo(): x = """
+ #
+ # """; return x
+ fn_body_token = after_colon
+ start_line = fn_body_token.start[0] - 1
+ start_col = fn_body_token.start[1]
+
+ col_offset = fn_body_token.end[1] - start_col
+ return start_line, col_offset
+
+
+def get_valid_decorator(
+ node: CellNode,
+) -> Optional[Union[ast.Attribute, ast.Call]]:
+ valid_decorators = (
+ "cell",
+ "function",
+ "class_definition",
+ )
+ for decorator in node.decorator_list:
+ if (
+ isinstance(decorator, ast.Call)
+ and decorator.func.attr in valid_decorators # type: ignore
+ ) or (
+ isinstance(decorator, ast.Attribute)
+ and decorator.attr in valid_decorators
+ ):
+ return decorator
+ return None
+
+
+def is_marimo_import(node: Node) -> bool:
+ return isinstance(node, ast.Import) and node.names[0].name == "marimo"
+
+
+def is_string(node: Node) -> bool:
+ return (
+ isinstance(node, ast.Expr)
+ and isinstance(node.value, ast.Constant)
+ and isinstance(node.value.value, str)
+ )
+
+
+def is_app_def(node: Node) -> bool:
+ # Expected Ast:
+ #
+ # Assign(
+ # targets=[
+ # Name(id='app', ctx=Store())],
+ # value=Call(
+ # func=Attribute(
+ # value=Name(id='marimo', ctx=Load()),
+ # attr='App',
+ # ctx=Load()),
+ # args=[],
+ # keywords=[
+ # keyword(
+ # arg=...,
+ # value=Constant(value=...)),
+ # ]
+ # )
+ # )
+
+ # A bit obnoxious as a huge conditional, but also better for line coverage.
+ return (
+ isinstance(node, ast.Assign)
+ and len(node.targets) == 1
+ and isinstance(node.targets[0], ast.Name)
+ and node.targets[0].id == "app"
+ and isinstance(node.value, ast.Call)
+ and isinstance(node.value.func, ast.Attribute)
+ and isinstance(node.value.func.value, ast.Name)
+ and node.value.func.value.id == "marimo"
+ and node.value.func.attr == "App"
+ )
+
+
+def is_cell_decorator(decorator: ast.expr) -> bool:
+ if isinstance(decorator, ast.Attribute):
+ return (
+ isinstance(decorator.value, ast.Name)
+ and decorator.value.id == "app"
+ and decorator.attr in ("cell", "function", "class_definition")
+ )
+ elif isinstance(decorator, ast.Call):
+ return is_cell_decorator(decorator.func)
+ return False
+
+
+def is_unparsable_cell(node: Node) -> bool:
+ return (
+ isinstance(node, ast.Expr)
+ and isinstance(node.value, ast.Call)
+ and isinstance(node.value.func, ast.Attribute)
+ and isinstance(node.value.func.value, ast.Name)
+ and node.value.func.value.id == "app"
+ and node.value.func.attr == "_unparsable_cell"
+ and len(node.value.args) == 1
+ )
+
+
+def is_body_cell(node: Node) -> bool:
+ # should have decorator @app.cell, @app.function, @app.class_definition
+ return (
+ isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef, ast.ClassDef))
+ and (decorator := get_valid_decorator(node))
+ and is_cell_decorator(decorator)
+ ) or is_unparsable_cell(node)
+
+
+def _is_setup_call(node: Node) -> bool:
+ if isinstance(node, ast.Attribute):
+ return (
+ isinstance(node.value, ast.Name)
+ and node.value.id == "app"
+ and node.attr == "setup"
+ )
+ elif isinstance(node, ast.Call):
+ return _is_setup_call(node.func)
+ return False
+
+
+def is_setup_cell(node: Node) -> bool:
+ return (
+ isinstance(node, (ast.AsyncWith, ast.With))
+ and len(node.items) == 1
+ and _is_setup_call(node.items[0].context_expr)
+ )
+
+
+def is_cell(node: Optional[Node]) -> bool:
+ return bool(node and (is_setup_cell(node) or is_body_cell(node)))
+
+
+def is_run_guard(node: Optional[Node]) -> bool:
+ return bool(
+ node
+ and (node == ast.parse('if __name__ == "__main__": app.run()').body[0])
+ )
+
+
+def parse_notebook(filename: str) -> Optional[NotebookSerialization]:
+ parser = Parser(filename)
+ if not parser.extractor.contents:
+ return None
+
+ violations: list[Violation] = []
+ cells: list[CellDef] = []
+
+ body: PeekStack[Node] = parser.node_stack()
+
+ header_result = parser.parse_header(body)
+ violations.extend(header_result.violations)
+ header = header_result.unwrap()
+
+ if not (import_result := parser.parse_import(body)):
+ violations.append(
+ Violation(
+ "Only able to extract header.",
+ lineno=1,
+ )
+ )
+ return NotebookSerialization(
+ header=Header(
+ lineno=0,
+ col_offset=0,
+ end_lineno=len(parser.extractor.lines),
+ end_col_offset=len(parser.extractor.lines[-1]),
+ value=parser.extractor.contents,
+ ),
+ version=None,
+ app=AppInstantiation(),
+ cells=[],
+ violations=violations,
+ valid=False,
+ )
+ violations.extend(import_result.violations)
+
+ version = None
+ if version_result := parser.parse_version(body):
+ version = version_result.unwrap()
+ violations.extend(version_result.violations)
+
+ if not (app_result := parser.parse_app(body)):
+ raise MarimoFileError("`marimo.App` definition expected.")
+ app = app_result.unwrap()
+ violations.extend(app_result.violations)
+
+ setup_result = parser.parse_setup(body)
+ violations.extend(setup_result.violations)
+ if setup_cell := setup_result.unwrap():
+ cells.append(setup_cell)
+
+ if is_run_guard(body.last):
+ return NotebookSerialization(
+ header=header,
+ version=version,
+ app=app,
+ violations=violations,
+ cells=cells,
+ )
+
+ body_result = parser.parse_body(body)
+ cells.extend(body_result.unwrap())
+ violations.extend(body_result.violations)
+
+ # Expected a run guard, but that's OK.
+ if not is_run_guard(body.last):
+ violations.append(Violation("Expected run guard statement"))
+
+ return NotebookSerialization(
+ header=header,
+ version=version,
+ app=app,
+ cells=cells,
+ violations=violations,
+ )
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 0453aaf45e..625b428a42 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -13,7 +13,7 @@ import click
import marimo._cli.cli_validators as validators
from marimo import __version__, _loggers
-from marimo._ast import codegen
+from marimo._ast import codegen, load
from marimo._cli.config.commands import config
from marimo._cli.convert.commands import convert
from marimo._cli.development.commands import development
@@ -56,7 +56,7 @@ def helpful_usage_error(self: Any, file: Any = None) -> None:
def check_app_correctness(filename: str) -> None:
try:
- codegen.get_app(filename)
+ load.load_app(filename)
except SyntaxError:
import traceback
diff --git a/marimo/_schemas/serialization.py b/marimo/_schemas/serialization.py
new file mode 100644
index 0000000000..d60dc26135
--- /dev/null
+++ b/marimo/_schemas/serialization.py
@@ -0,0 +1,129 @@
+# Copyright 2025 Marimo. All rights reserved.
+from __future__ import annotations
+
+import ast
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any, Optional, Union
+
+from marimo._ast.names import DEFAULT_CELL_NAME
+
+if TYPE_CHECKING:
+ from typing_extensions import TypeAlias
+
+NodeRef: TypeAlias = Union[ast.stmt, ast.expr]
+
+
+@dataclass
+class Node:
+ """
+ Loosely mirror the python ast statement nodes:
+ github:python/cpython/Include/internal/pycore_ast.h#L196
+ """
+
+ lineno: int = 0
+ col_offset: int = 0
+ end_lineno: int = 0
+ end_col_offset: int = 0
+
+
+@dataclass
+class Header(Node):
+ value: str = ""
+
+
+@dataclass
+class AppInstantiation(Node):
+ # NB. differs from InternalApp and App, because this is what's directly read
+ # from the notebook.
+ options: dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class CellDef(Node):
+ code: str = ""
+ name: str = DEFAULT_CELL_NAME
+ options: dict[str, Any] = field(default_factory=dict)
+
+ _ast: Optional[NodeRef] = None
+
+ def __post_init__(self) -> None:
+ if self._ast:
+ self.lineno = self._ast.lineno if self.lineno == 0 else self.lineno
+ self.col_offset = (
+ self._ast.col_offset
+ if self.col_offset == 0
+ else self.col_offset
+ )
+ self.end_lineno = (
+ self._ast.end_lineno
+ if self.end_lineno == 0 and self._ast.end_lineno
+ else self.end_lineno
+ )
+ self.end_col_offset = (
+ self._ast.end_col_offset
+ if self.end_col_offset == 0 and self._ast.end_col_offset
+ else self.end_col_offset
+ )
+ self.name = getattr(self._ast, "name", DEFAULT_CELL_NAME)
+
+
+class SetupCell(CellDef): ...
+
+
+class FunctionCell(CellDef): ...
+
+
+class ClassCell(CellDef): ...
+
+
+class UnparsableCell(CellDef): ...
+
+
+@dataclass
+class Violation:
+ """
+ "Violation" is borrowed from ruff's internal representation.
+ A bit harsh sounding, but reasonable.
+
+ Essentially a stub for now:
+ - Potentially move to marimo/_lint
+ - Consider subclassing to hardcoded descriptions
+ - Consider violation ID (e.g mo-0001)
+ """
+
+ description: str
+ lineno: int = 0
+ col_offset: int = 0
+
+
+@dataclass(frozen=True)
+class NotebookSerializationV1:
+ """
+ The expectation of a notebook structure is as follows:
+ notebook = header? + app + setup? + cells* + run_guard
+ header = (docstring | comments)*
+ app = import marimo + __generated_with + App(kwargs*)
+ cells = cell | function | class_definition | unparsable
+ setup = Async?With(kwargs*, stmt*)
+ cell = Async?Function(kwargs*, stmt*, @cell)
+ function = Async?Function(kwargs*, stmt*, @function + decorators*)
+ class_definition = ClassDef(kwargs*, stmt*, @class_definition + decorators*)
+ unparsable = app._unparsable_cell(code, kwargs*)
+ run_guard = if __name__ == "__main__": app.run()
+
+ This is meant to be a representation of the notebook as extracted directly
+ from a script
+ """
+
+ app: AppInstantiation
+ header: Optional[Header] = None
+ version: Optional[str] = None
+ cells: list[CellDef] = field(default_factory=list)
+ violations: list[Violation] = field(default_factory=list)
+ valid: bool = True
+
+
+NotebookSerialization: TypeAlias = NotebookSerializationV1
+
+
+VERSION = "1"
diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.py
index bc704a0de0..c1136c8f1f 100644
--- a/marimo/_server/file_manager.py
+++ b/marimo/_server/file_manager.py
@@ -8,7 +8,7 @@ from pathlib import Path
from typing import Any, Optional, Union
from marimo import _loggers
-from marimo._ast import codegen
+from marimo._ast import codegen, load
from marimo._ast.app import App, InternalApp
from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig
@@ -161,7 +161,7 @@ class AppFileManager:
def _load_app(self, path: Optional[str]) -> InternalApp:
"""Read the app from the file."""
- app = codegen.get_app(path)
+ app = load.load_app(path)
if app is None:
kwargs = (
{"width": self._default_width}
diff --git a/marimo/_snippets/snippets.py b/marimo/_snippets/snippets.py
index 4ba8be615e..15eac28056 100644
--- a/marimo/_snippets/snippets.py
+++ b/marimo/_snippets/snippets.py
@@ -7,7 +7,7 @@ from pathlib import Path
from typing import Any, Optional
from marimo import _loggers
-from marimo._ast.codegen import get_app
+from marimo._ast.load import load_app
from marimo._config.manager import get_default_config_manager
from marimo._utils.paths import marimo_package_path
@@ -36,7 +36,7 @@ async def read_snippets() -> Snippets:
snippets: list[Snippet] = []
for file in read_snippet_filenames_from_config():
- app = get_app(file)
+ app = load_app(file)
assert app is not None
sections: list[SnippetSection] = []
title = ""
diff --git a/openapi/api.yaml b/openapi/api.yaml
index d4154da8f5..8f6d36a618 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -1103,8 +1103,6 @@ components:
properties:
app_config:
properties:
- _toplevel_fn:
- type: boolean
app_title:
nullable: true
type: string
@@ -1144,7 +1142,6 @@ components:
- width
- auto_download
- sql_output
- - _toplevel_fn
type: object
capabilities:
properties:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index c9fbb7b4db..185838327f 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2780,7 +2780,6 @@ export interface components {
| null;
KernelReady: {
app_config: {
- _toplevel_fn: boolean;
app_title?: string | null;
auto_download: ("html" | "markdown")[];
css_file?: string | null;
diff --git a/tests/_ast/codegen_data/test_get_app_kwargs.py b/tests/_ast/codegen_data/test_get_app_kwargs.py
new file mode 100644
index 0000000000..babd68a3fb
--- /dev/null
+++ b/tests/_ast/codegen_data/test_get_app_kwargs.py
@@ -0,0 +1,8 @@
+import marimo
+
+app = marimo.App(
+ app_title="title",
+ auto_download="html",
+ layout_file="layouts/layout.json",
+ invalid_arg=1
+)
diff --git a/tests/_ast/codegen_data/test_get_codes_empty.py b/tests/_ast/codegen_data/test_get_codes_empty.py
index e38dad51d4..7dc89403cf 100644
--- a/tests/_ast/codegen_data/test_get_codes_empty.py
+++ b/tests/_ast/codegen_data/test_get_codes_empty.py
@@ -12,6 +12,17 @@ def one(): return
def two():
return
+# fmt: off
+def three(
+ ): return
+
+def four(
+ ):
+ return
+
+# fmt: on
if __name__ == "__main__":
app.run()
diff --git a/tests/_ast/codegen_data/test_get_codes_messy_toplevel.py b/tests/_ast/codegen_data/test_get_codes_messy_toplevel.py
new file mode 100644
index 0000000000..c7b6f8581a
--- /dev/null
+++ b/tests/_ast/codegen_data/test_get_codes_messy_toplevel.py
@@ -0,0 +1,34 @@
+import marimo
+
+__generated_with = '0.1.0'
+app = marimo.App()
+
+
+# We want a wrapper as a proof of concept. Note, that this will not serialize
+# in this form.
+def wrapper(func):
+ def wrapper(*args, **kwargs):
+ return func(*args, **kwargs)
+ return wrapper
+
+
+def fn(a,
+ b, # hello,
+ c, # again
+ d,) -> int:
+ # comment
+ # another comment
+
+ # yet another comment
+ return 0 + a + b + c + d
+
+
+@wrapper
+def wrapped():
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_ast/codegen_data/test_get_setup.py b/tests/_ast/codegen_data/test_get_setup.py
new file mode 100644
index 0000000000..56f1fe8f4b
--- /dev/null
+++ b/tests/_ast/codegen_data/test_get_setup.py
@@ -0,0 +1,18 @@
+import marimo
+
+__generated_with = '0.0.0'
+app = marimo.App()
+
+
+with app.setup:
+ variable = 1
+
+
+def fn(x: int):
+ return x + variable
+
+
+if __name__ == "__main__":
+ app.run()
+
diff --git a/tests/_ast/codegen_data/test_get_setup_blank.py b/tests/_ast/codegen_data/test_get_setup_blank.py
new file mode 100644
index 0000000000..5e177090fc
--- /dev/null
+++ b/tests/_ast/codegen_data/test_get_setup_blank.py
@@ -0,0 +1,21 @@
+import marimo
+
+__generated_with = '0.0.0'
+app = marimo.App()
+
+
+with app.setup:
+ # Only comments
+ # and a pass
+ pass
+
+
+def fn(x: int):
+ return x + variable
+
+
+if __name__ == "__main__":
+ app.run()
+
+
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index cd3bc0b863..8016273f9a 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -13,7 +13,7 @@ import codegen_data.test_main as mod
import pytest
from marimo import __version__
-from marimo._ast import codegen, compiler
+from marimo._ast import codegen, compiler, load
from marimo._ast.app import App, InternalApp
from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig
@@ -71,7 +71,7 @@ def get_idempotent_marimo_source(name: str) -> str:
from marimo._utils.formatter import Formatter
path = get_filepath(name)
- app = codegen.get_app(path)
+ app = load.load_app(path)
header_comments = codegen.get_header_comments(path)
generated_contents = codegen.generate_filecontents(
list(app._cell_manager.codes()),
@@ -325,158 +325,6 @@ class TestGeneration:
assert "import marimo" in source
-class TestGetCodes:
- @staticmethod
- def test_get_codes() -> None:
- app = codegen.get_app(get_filepath("test_generate_filecontents"))
- assert app is not None
- cell_manager = app._cell_manager
- assert list(cell_manager.names()) == [
- "one",
- "two",
- "three",
- "four",
- "five",
- ]
- assert list(cell_manager.codes()) == [
- "import numpy as np",
- "x = 0\nxx = 1",
- "y = x + 1",
- "# comment\nz = np.array(x + y)",
- "# just a comment",
- ]
-
- @staticmethod
- def test_get_codes_async() -> None:
- app = codegen.get_app(get_filepath("test_generate_filecontents_async"))
- assert app is not None
- cell_manager = app._cell_manager
- assert list(cell_manager.names()) == [
- "one",
- "two",
- "three",
- ]
- assert list(cell_manager.codes()) == [
- "import numpy as np\nimport asyncio",
- "x = 0\nxx = 1\nawait asyncio.sleep(1)",
- "async def _():\n await asyncio.sleep(x)",
- ]
-
- @staticmethod
- def test_get_codes_with_incorrect_args_rets() -> None:
- app = codegen.get_app(
- get_filepath("test_get_codes_with_incorrect_args_rets")
- )
- assert app is not None
- cell_manager = app._cell_manager
- assert list(cell_manager.names()) == [
- "one",
- "two",
- "three",
- "four",
- "five",
- ]
- assert list(cell_manager.codes()) == [
- "import numpy as np",
- "x = 0\nxx = 1",
- "y = x + 1",
- "# comment\nz = np.array(x + y)",
- "# just a comment\n...",
- ]
-
- @staticmethod
- def test_get_codes_with_name_error() -> None:
- # name mo is not defined --- make sure this file is still parseable
- app = codegen.get_app(get_filepath("test_get_codes_with_name_error"))
- assert app is not None
- cell_manager = app._cell_manager
- assert list(cell_manager.names()) == ["one"]
- assert list(cell_manager.codes()) == [
- "mo",
- ]
-
- @staticmethod
- def test_get_codes_multiline_fndef() -> None:
- app = codegen.get_app(get_filepath("test_get_codes_multiline_fndef"))
- assert app is not None
- cell_manager = app._cell_manager
- assert list(cell_manager.names()) == ["one"]
- assert list(cell_manager.codes()) == [
- "# comment\nx = 0 + a + b + c + d",
- ]
-
- @staticmethod
- def test_get_codes_messy() -> None:
- app = codegen.get_app(get_filepath("test_get_codes_messy"))
- assert app is not None
- cell_manager = app._cell_manager
- assert list(cell_manager.names()) == ["__"]
- assert list(cell_manager.codes()) == [
- "# comment\n# another comment\n\n# yet another comment\n"
- + "x = 0 + a + b + c + d",
- ]
-
- @staticmethod
- def test_get_codes_single_line_fn() -> None:
- app = codegen.get_app(get_filepath("test_get_codes_single_line_fn"))
- assert app is not None
- cell_manager = app._cell_manager
- assert list(cell_manager.names()) == ["one"]
- assert list(cell_manager.codes()) == ["c = a + b; print(c); "]
-
- @staticmethod
- def test_get_codes_multiline_string() -> None:
- app = codegen.get_app(get_filepath("test_get_codes_multiline_string"))
- assert app is not None
- cell_manager = app._cell_manager
- assert list(cell_manager.names()) == ["one"]
- assert list(cell_manager.codes()) == ['c = """\n a, b"""; ']
-
- @staticmethod
- def test_get_codes_comment_after_sig() -> None:
- app = codegen.get_app(get_filepath("test_get_codes_comment_after_sig"))
- assert app is not None
- cell_manager = app._cell_manager
- assert list(cell_manager.names()) == ["one"]
- assert list(cell_manager.codes()) == ['print("hi")']
-
- @staticmethod
- def test_get_codes_empty() -> None:
- app = codegen.get_app(get_filepath("test_get_codes_empty"))
- assert app is not None
- cell_manager = app._cell_manager
- assert list(cell_manager.names()) == ["one", "two"]
- assert [c.strip() for c in cell_manager.codes()] == ["", ""]
-
- @staticmethod
- def test_get_codes_syntax_error() -> None:
- app = codegen.get_app(
- get_filepath("test_generate_filecontents_with_syntax_error")
- )
- assert app is not None
- cell_manager = app._cell_manager
- assert list(cell_manager.names()) == ["one", "two", "_", "_"]
- assert list(cell_manager.codes()) == [
- "import numpy as np",
- "_ error",
- "'all good'",
- '_ another_error\n_ and """another"""\n\n \\t',
- ]
-
- @staticmethod
- def test_get_codes_app_with_only_comments() -> None:
- app = codegen.get_app(get_filepath("test_app_with_only_comments"))
- assert app is None
-
- @staticmethod
- def test_get_codes_app_with_no_cells() -> None:
- app = codegen.get_app(get_filepath("test_app_with_no_cells"))
- assert app is not None
- app._cell_manager.ensure_one_cell()
- assert list(app._cell_manager.names()) == ["_"]
- assert list(app._cell_manager.codes()) == [""]
-
-
@pytest.fixture
def marimo_app() -> App:
return mod.app
diff --git a/tests/_ast/test_load.py b/tests/_ast/test_load.py
new file mode 100644
index 0000000000..5075b77490
--- /dev/null
+++ b/tests/_ast/test_load.py
@@ -0,0 +1,253 @@
+# Copyright 2025 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+import textwrap
+
+import pytest
+
+from marimo._ast import load
+
+DIR_PATH = os.path.dirname(os.path.realpath(__file__))
+
+
+def get_filepath(name: str) -> str:
+ return os.path.join(DIR_PATH, f"codegen_data/{name}.py")
+
+
+def static_load():
+ return load._static_load
+
+
+def dynamic_load():
+ return load._dynamic_load
+
+
[email protected](params=["static_load", "dynamic_load"])
+def load_app(request):
+ return request.getfixturevalue(request.param)
+
+
+class TestGetCodes:
+ @staticmethod
+ def test_get_codes(load_app) -> None:
+ app = load_app(get_filepath("test_generate_filecontents"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == [
+ "one",
+ "two",
+ "three",
+ "four",
+ "five",
+ ]
+ assert list(cell_manager.codes()) == [
+ "import numpy as np",
+ "x = 0\nxx = 1",
+ "y = x + 1",
+ "# comment\nz = np.array(x + y)",
+ "# just a comment",
+ ]
+
+ @staticmethod
+ def test_get_codes_async(load_app) -> None:
+ app = load_app(get_filepath("test_generate_filecontents_async"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == [
+ "one",
+ "two",
+ "three",
+ ]
+ assert list(cell_manager.codes()) == [
+ "import numpy as np\nimport asyncio",
+ "x = 0\nxx = 1\nawait asyncio.sleep(1)",
+ "async def _():\n await asyncio.sleep(x)",
+ ]
+
+ @staticmethod
+ def test_get_codes_with_incorrect_args_rets(load_app) -> None:
+ app = load_app(get_filepath("test_get_codes_with_incorrect_args_rets"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == [
+ "one",
+ "two",
+ "three",
+ "four",
+ "five",
+ ]
+ assert list(cell_manager.codes()) == [
+ "import numpy as np",
+ "x = 0\nxx = 1",
+ "y = x + 1",
+ "# comment\nz = np.array(x + y)",
+ "# just a comment\n...",
+ ]
+
+ @staticmethod
+ def test_get_codes_with_name_error(load_app) -> None:
+ # name mo is not defined --- make sure this file is still parseable
+ app = load_app(get_filepath("test_get_codes_with_name_error"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one"]
+ assert list(cell_manager.codes()) == [
+ "mo",
+ ]
+
+ @staticmethod
+ def test_get_codes_multiline_fndef(load_app) -> None:
+ app = load_app(get_filepath("test_get_codes_multiline_fndef"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one"]
+ assert list(cell_manager.codes()) == [
+ "# comment\nx = 0 + a + b + c + d",
+ ]
+
+ @staticmethod
+ def test_get_codes_messy(load_app) -> None:
+ app = load_app(get_filepath("test_get_codes_messy"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["__"]
+ assert list(cell_manager.codes()) == [
+ "# comment\n# another comment\n\n# yet another comment\n"
+ + "x = 0 + a + b + c + d",
+ ]
+
+ @staticmethod
+ def test_get_setup(load_app) -> None:
+ app = load_app(get_filepath("test_get_setup"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["setup", "fn"]
+ assert list(cell_manager.codes()) == [
+ "variable = 1",
+ textwrap.dedent(
+ """\
+ def fn(x: int):
+ return x + variable"""
+ ),
+ ]
+
+ @staticmethod
+ def test_get_setup_blank(load_app) -> None:
+ app = load_app(get_filepath("test_get_setup_blank"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["setup", "fn"]
+ assert list(cell_manager.codes()) == [
+ "# Only comments\n# and a pass",
+ textwrap.dedent(
+ """\
+ def fn(x: int):
+ return x + variable"""
+ ),
+ ]
+
+ @staticmethod
+ def test_get_codes_messy_toplevel(load_app) -> None:
+ app = load_app(get_filepath("test_get_codes_messy_toplevel"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["fn", "wrapped"]
+ assert list(cell_manager.codes()) == [
+ "def fn(a,\n b, # hello,\n c, # again\n d,) -> int:\n"
+ + " # comment\n # another comment\n\n # yet another comment\n"
+ + " return 0 + a + b + c + d",
+ "",
+ ]
+
+ @staticmethod
+ def test_get_codes_single_line_fn(load_app) -> None:
+ app = load_app(get_filepath("test_get_codes_single_line_fn"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one"]
+ assert list(cell_manager.codes()) == ["c = a + b; print(c); "]
+
+ @staticmethod
+ def test_get_codes_multiline_string(load_app) -> None:
+ app = load_app(get_filepath("test_get_codes_multiline_string"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one"]
+ assert list(cell_manager.codes()) == ['c = """\n a, b"""; ']
+
+ @staticmethod
+ def test_get_codes_comment_after_sig(load_app) -> None:
+ app = load_app(get_filepath("test_get_codes_comment_after_sig"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one"]
+ assert list(cell_manager.codes()) == ['print("hi")']
+
+ @staticmethod
+ def test_get_codes_empty(load_app) -> None:
+ app = load_app(get_filepath("test_get_codes_empty"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one", "two", "three", "four"]
+ assert [c.strip() for c in cell_manager.codes()] == ["", "", "", ""]
+
+ @staticmethod
+ def test_get_codes_syntax_error(load_app) -> None:
+ app = load_app(
+ get_filepath("test_generate_filecontents_with_syntax_error")
+ )
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == ["one", "two", "_", "_"]
+ assert list(cell_manager.codes()) == [
+ "import numpy as np",
+ "_ error",
+ "'all good'",
+ '_ another_error\n_ and """another"""\n\n \\t',
+ ]
+
+ @staticmethod
+ def test_get_codes_app_with_only_comments(load_app) -> None:
+ app = load_app(get_filepath("test_app_with_only_comments"))
+ assert app is None
+
+ @staticmethod
+ def test_get_codes_app_with_no_cells(load_app) -> None:
+ app = load_app(get_filepath("test_app_with_no_cells"))
+ assert app is not None
+ app._cell_manager.ensure_one_cell()
+ assert list(app._cell_manager.names()) == ["_"]
+ assert list(app._cell_manager.codes()) == [""]
+
+ @staticmethod
+ def test_get_codes_toplevel(load_app) -> None:
+ app = load_app(get_filepath("test_generate_filecontents_toplevel"))
+ assert app is not None
+ cell_manager = app._cell_manager
+ assert list(cell_manager.names()) == [
+ "setup",
+ "_",
+ "addition",
+ "shadow_case",
+ "_",
+ "_",
+ "fun_that_uses_mo",
+ "fun_that_uses_another_but_out_of_order",
+ "fun_that_uses_another",
+ "cell_with_ref_and_def",
+ "_",
+ "ExampleClass",
+ "SubClass",
+ ]
+
+ @staticmethod
+ def test_get_app_kwargs(load_app) -> None:
+ app = load_app(get_filepath("test_get_app_kwargs"))
+ assert app is not None
+ assert app._filename.endswith("test_get_app_kwargs.py")
+ assert app._config.layout_file == "layouts/layout.json"
+ assert app._config.app_title == "title"
+ assert app._config.auto_download == "html"
diff --git a/tests/_ast/test_parse.py b/tests/_ast/test_parse.py
new file mode 100644
index 0000000000..2d5bff1fb9
--- /dev/null
+++ b/tests/_ast/test_parse.py
@@ -0,0 +1,101 @@
+# Copyright 2025 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+
+from marimo._ast.parse import Parser, parse_notebook
+
+DIR_PATH = os.path.dirname(os.path.realpath(__file__))
+
+
+def get_filepath(name: str) -> str:
+ return os.path.join(DIR_PATH, f"codegen_data/{name}.py")
+
+
+# NB. Some barebones testing at the areas that seemed to be most sensitive.
+# Note that loader should cover these cases and more by proxy.
+class TestParser:
+ @staticmethod
+ def test_parse_codes() -> None:
+ parser = Parser(get_filepath("test_generate_filecontents"))
+ body = parser.node_stack()
+ body_result = parser.parse_body(body)
+ assert body_result
+ cells = body_result.unwrap()
+ assert len(cells) == 5
+ assert [cell.name for cell in cells] == [
+ "one",
+ "two",
+ "three",
+ "four",
+ "five",
+ ]
+
+ @staticmethod
+ def test_parse_setup_blank() -> None:
+ parser = Parser(get_filepath("test_get_setup_blank"))
+ body = parser.node_stack()
+ _ = parser.parse_header(body)
+ setup_result = parser.parse_setup(body)
+ assert setup_result, setup_result.violations
+ setup_cell = setup_result.unwrap()
+ assert setup_cell.name == "setup"
+ assert setup_cell.code == "# Only comments\n# and a pass"
+
+ @staticmethod
+ def test_parse_codes_toplevel() -> None:
+ notebook = parse_notebook(
+ get_filepath("test_generate_filecontents_toplevel")
+ )
+ assert notebook
+ assert notebook.header.value.startswith(
+ "# This comment should be preserved"
+ )
+ # Likely over extended scope in this case.
+ assert "import marimo" not in notebook.header.value
+
+ assert [cell.name for cell in notebook.cells] == [
+ "setup",
+ "_",
+ "addition",
+ "shadow_case",
+ "_",
+ "_",
+ "fun_that_uses_mo",
+ "fun_that_uses_another_but_out_of_order",
+ "fun_that_uses_another",
+ "cell_with_ref_and_def",
+ "_",
+ "ExampleClass",
+ "SubClass",
+ ]
+
+ @staticmethod
+ def test_parse_app_with_only_comments() -> None:
+ parser = Parser(get_filepath("test_app_with_only_comments"))
+ body = parser.node_stack()
+ header_result = parser.parse_header(body)
+ assert header_result
+
+ import_result = parser.parse_import(body)
+ assert not import_result
+
+ @staticmethod
+ def test_just_app() -> None:
+ notebook = parse_notebook(get_filepath("test_get_app_kwargs"))
+ # No generated with, or run guard
+ assert len(notebook.violations) == 2
+ assert "generated_with" in notebook.violations[0].description
+ assert "run guard" in notebook.violations[1].description
+
+ @staticmethod
+ def test_parse_messy_toplevel() -> None:
+ notebook = parse_notebook(
+ get_filepath("test_get_codes_messy_toplevel")
+ )
+ assert notebook
+ # unexpected statements and a missing run guard
+ assert len(notebook.violations) == 3
+ assert "statement" in notebook.violations[0].description
+ assert "statement" in notebook.violations[1].description
+ assert "run guard" in notebook.violations[2].description
diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.py
index e9d6af1487..391a60d069 100644
--- a/tests/_cli/test_cli.py
+++ b/tests/_cli/test_cli.py
@@ -104,7 +104,7 @@ def _try_fetch(
url = f"{url}?access_token={token}"
return urllib.request.urlopen(url).read()
except Exception:
- time.sleep(0.5)
+ time.sleep(0.6)
print("Failed to fetch contents")
return None
@@ -128,8 +128,8 @@ def _check_contents(
contents: Optional[bytes],
) -> None:
try:
- assert contents is not None
- assert phrase in contents
+ assert contents is not None, contents
+ assert phrase in contents, contents
finally:
p.kill()
diff --git a/tests/_runtime/test_trace.py b/tests/_runtime/test_trace.py
index 131ea9f6e0..bfe796bf49 100644
--- a/tests/_runtime/test_trace.py
+++ b/tests/_runtime/test_trace.py
@@ -55,7 +55,7 @@ class TestScriptTrace:
# y = y / x
# ^
# exact line numbers differ by python version
- if sys.version_info >= (3, 11):
+ if sys.version_info == (3, 11):
assert (
result.split("y / x")[1].split("\n")[1].startswith(" ^")
)
@@ -131,12 +131,9 @@ class TestScriptTrace:
assert p.returncode == 1
result = p.stderr.decode()
- assert "The setup cell was unable to execute" in result
- assert "ZeroDivisionError: division by zero" in result
- # TODO(dmadisetti): re-enable assertion, behavior should go back to
- # expected with #4400
- # assert ('script_exception_setup_cell.py", line 10') in result
- # assert "y / x" in result
+ assert "ZeroDivisionError" in result
+ assert ('script_exception_setup_cell.py", line 10') in result
+ assert "y / x" in result
class TestAppTrace:
diff --git a/tests/_server/export/snapshots/notebook_with_outputs.ipynb.txt b/tests/_server/export/snapshots/notebook_with_outputs.ipynb.txt
index 605be4dd52..7e4d6268f1 100644
--- a/tests/_server/export/snapshots/notebook_with_outputs.ipynb.txt
+++ b/tests/_server/export/snapshots/notebook_with_outputs.ipynb.txt
@@ -87,7 +87,7 @@
},
"outputs": [],
"source": [
- "import marimo as mo"
+ "import marimo as mo\n"
]
},
{