Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve reporting of unparsable code #3500

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ marimo/_lsp/

.vscode
.vercel
.idea

.marimo.toml
.mypy_cache/
Expand Down
21 changes: 18 additions & 3 deletions marimo/_ast/app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations

import ast
import inspect
from dataclasses import asdict, dataclass, field
from textwrap import dedent
from typing import (
TYPE_CHECKING,
Any,
Expand Down Expand Up @@ -155,6 +157,7 @@ def __init__(self, **kwargs: Any) -> None:
self._execution_context: ExecutionContext | None = None
self._runner = dataflow.Runner(self._graph)

self._unparsable_code: list[str] = []
self._unparsable = False
self._initialized = False
# injection hook set by contexts like tests such that script traces are
Expand Down Expand Up @@ -222,14 +225,26 @@ def _unparsable_cell(
name,
CellConfig.from_dict(config),
)
self._unparsable_code.append(code)
self._unparsable = True

def _maybe_initialize(self) -> None:
if self._unparsable:
errors = []
for code in self._unparsable_code:
try:
ast.parse(dedent(code))
except SyntaxError as e:
error_line = e.text
error_marker = " " * (e.offset - 1) + "^"
err = f"{error_line}{error_marker}\n{e.msg}"
errors.append(err)
syntax_errors = "\n-----\n".join(errors)

raise UnparsableError(
"This notebook has cells with syntax errors, "
"so it cannot be initialized."
)
f"The notebook '{self._filename}' has cells with syntax errors, "
+ f"so it cannot be initialized:\n {syntax_errors}"
) from None

if self._initialized:
return
Expand Down
3 changes: 2 additions & 1 deletion tests/_ast/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,9 @@ def one() -> tuple[int]:
app._unparsable_cell("_ _")
app._unparsable_cell("_ _", name="foo")

with pytest.raises(UnparsableError):
with pytest.raises(UnparsableError) as e:
app.run()
e.match("_ _")

@staticmethod
def test_init_not_rewritten_as_local() -> None:
Expand Down
Loading