mogs 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. mogs/__init__.py +17 -0
  2. mogs/_assertrewrite.py +44 -0
  3. mogs/_env.py +26 -0
  4. mogs/_run.py +111 -0
  5. mogs/_typst/preview/cmarker/0.1.10/LICENSE +7 -0
  6. mogs/_typst/preview/cmarker/0.1.10/lib.typ +462 -0
  7. mogs/_typst/preview/cmarker/0.1.10/plugin.wasm +0 -0
  8. mogs/_typst/preview/cmarker/0.1.10/typst.toml +11 -0
  9. mogs/_typst/preview/mitex/0.2.7/LICENSE +176 -0
  10. mogs/_typst/preview/mitex/0.2.7/lib.typ +1 -0
  11. mogs/_typst/preview/mitex/0.2.7/mitex.typ +45 -0
  12. mogs/_typst/preview/mitex/0.2.7/mitex.wasm +0 -0
  13. mogs/_typst/preview/mitex/0.2.7/specs/latex/standard.typ +1187 -0
  14. mogs/_typst/preview/mitex/0.2.7/specs/mod.typ +12 -0
  15. mogs/_typst/preview/mitex/0.2.7/specs/prelude.typ +230 -0
  16. mogs/_typst/preview/mitex/0.2.7/typst.toml +12 -0
  17. mogs/assignment.py +172 -0
  18. mogs/build.py +605 -0
  19. mogs/check.py +410 -0
  20. mogs/cli.py +272 -0
  21. mogs/config.py +619 -0
  22. mogs/environment.py +118 -0
  23. mogs/export.py +556 -0
  24. mogs/grader/__init__.py +1 -0
  25. mogs/grader/_process.py +383 -0
  26. mogs/grader/_user.py +7 -0
  27. mogs/grader/bundle.py +320 -0
  28. mogs/grader/child.py +317 -0
  29. mogs/grader/datafiles.py +54 -0
  30. mogs/grader/main.py +132 -0
  31. mogs/grader/protocol.py +175 -0
  32. mogs/grader/results.py +337 -0
  33. mogs/grader/sandbox.py +462 -0
  34. mogs/grader/templates/__init__.py +38 -0
  35. mogs/grader/templates/run_autograder +3 -0
  36. mogs/grader/templates/setup.sh +28 -0
  37. mogs/loader.py +260 -0
  38. mogs/pdf.py +676 -0
  39. mogs/regrade.py +223 -0
  40. mogs/requirements.py +232 -0
  41. mogs/runner.py +281 -0
  42. mogs/scaffold.py +155 -0
  43. mogs/selfcheck.py +173 -0
  44. mogs/source.py +1438 -0
  45. mogs/transform.py +769 -0
  46. mogs-0.7.0.dist-info/METADATA +17 -0
  47. mogs-0.7.0.dist-info/RECORD +49 -0
  48. mogs-0.7.0.dist-info/WHEEL +4 -0
  49. mogs-0.7.0.dist-info/entry_points.txt +3 -0
mogs/source.py ADDED
@@ -0,0 +1,1438 @@
1
+ """Static parse of a marimo source notebook into cells, and checks of its authoring rules.
2
+
3
+ The notebook is never imported or run. Cells, tests, hidden cells and grade calls come from
4
+ its AST and its text.
5
+ """
6
+
7
+ import ast
8
+ import io
9
+ import re
10
+ import symtable
11
+ import textwrap
12
+ import tokenize
13
+ from collections.abc import Iterable
14
+ from dataclasses import dataclass
15
+ from enum import StrEnum
16
+
17
+ from mogs.config import (
18
+ ASSIGNMENT,
19
+ Api,
20
+ AssignmentConfig,
21
+ ConfigError,
22
+ api_calls,
23
+ normalize_newlines,
24
+ normalized_name,
25
+ question_id,
26
+ read_header,
27
+ split_lines,
28
+ )
29
+
30
+ INSTRUCTOR = "instructor"
31
+
32
+
33
+ class Marker(StrEnum):
34
+ """Comments that mark hidden cells and solutions."""
35
+
36
+ HIDDEN = "# HIDDEN"
37
+ BEGIN = "# BEGIN SOLUTION"
38
+ END = "# END SOLUTION"
39
+ SOLUTION = "# SOLUTION"
40
+ PROMPT = "# PROMPT:"
41
+
42
+
43
+ HIDDEN = Marker.HIDDEN
44
+ BEGIN = Marker.BEGIN
45
+ END = Marker.END
46
+ SOLUTION = Marker.SOLUTION
47
+ PROMPT = Marker.PROMPT
48
+
49
+
50
+ class HtmlMarker(StrEnum):
51
+ """Solution markers in a Markdown cell, where a `#` line would be a heading."""
52
+
53
+ BEGIN = "<!-- BEGIN SOLUTION -->"
54
+ END = "<!-- END SOLUTION -->"
55
+ PROMPT = "<!-- PROMPT: <text> -->"
56
+
57
+
58
+ HTML_PROMPT_RE = re.compile(r"<!-- PROMPT:(?: (.*?))? -->")
59
+
60
+ # Comments that look like a marker but are not spelled exactly like one.
61
+ NEAR_HTML_RE = re.compile(r"<!--\s*(?:(?:begin|end)\s*)?(?:solu\w*|pro?m\w*)", re.IGNORECASE)
62
+ NEAR_PROMPT_RE = re.compile(r"#\s*prompt\b", re.IGNORECASE)
63
+ NEAR_HIDDEN_RE = re.compile(r"#\s*hidden\b", re.IGNORECASE)
64
+ # The first two words of a comment, for `near_solution_marker`.
65
+ LEADING_WORDS_RE = re.compile(r"(?:#|<!--)\s*([A-Za-z]+)(?:\s+([A-Za-z]+))?")
66
+ SOLUTION_WORD = "solution"
67
+ REGION_WORDS = ("begin", "end")
68
+
69
+
70
+ # What the build report and the assignment summary show for a written question without prompts.
71
+ NO_TEXT = "no question text"
72
+
73
+
74
+ class SourceError(Exception):
75
+ """The notebook source cannot be parsed into cells."""
76
+
77
+
78
+ class CellKind(StrEnum):
79
+ """How a cell is written in the notebook file."""
80
+
81
+ SETUP = "setup"
82
+ CELL = "cell"
83
+ FUNCTION = "function"
84
+ CLASS = "class"
85
+
86
+
87
+ @dataclass(frozen=True, slots=True)
88
+ class Cell:
89
+ """One marimo cell.
90
+
91
+ Attributes:
92
+ kind: Cell kind.
93
+ name: Function or class name; `_` for an unnamed cell; `setup` for the setup cell.
94
+ start: First line, 1-based, decorators included.
95
+ end: Last line, 1-based, inclusive.
96
+ tests: Names of the `test_*` functions the cell defines at its top level.
97
+ hidden: The cell holds a `# HIDDEN` line.
98
+ grade_qid: Question id of the cell's `grade(...)` call, if any.
99
+ assignment: The cell holds an `assignment(...)` call.
100
+ late_hidden: Line of a `# HIDDEN` that comes after the cell's first statement, if any.
101
+ """
102
+
103
+ kind: CellKind
104
+ name: str
105
+ start: int
106
+ end: int
107
+ tests: tuple[str, ...]
108
+ hidden: bool
109
+ grade_qid: str | None
110
+ assignment: bool = False
111
+ late_hidden: int | None = None
112
+
113
+ @property
114
+ def instructor(self) -> bool:
115
+ """Named `instructor` or `instructor_<suffix>`: for the instructor only.
116
+
117
+ The build leaves such cells out of the student and solved copies.
118
+ """
119
+
120
+ return self.name == INSTRUCTOR or self.name.startswith(f"{INSTRUCTOR}_")
121
+
122
+
123
+ @dataclass(frozen=True, slots=True)
124
+ class Notebook:
125
+ r"""A parsed source notebook.
126
+
127
+ Attributes:
128
+ cells: Cells in file order.
129
+ src: Notebook source, with line ends turned into `\n`.
130
+ """
131
+
132
+ cells: tuple[Cell, ...]
133
+ src: str
134
+
135
+ def tests_by_question(self) -> dict[str, tuple[list[str], list[str]]]:
136
+ """Public and hidden test names per question id, in file order."""
137
+
138
+ out: dict[str, tuple[list[str], list[str]]] = {}
139
+
140
+ for cell in self.cells:
141
+ for name in cell.tests:
142
+ public, hidden = out.setdefault(question_id(name), ([], []))
143
+ (hidden if cell.hidden else public).append(name)
144
+
145
+ return out
146
+
147
+ def student_names(self) -> set[str]:
148
+ """Names that cells without tests and without `# HIDDEN` define for the notebook.
149
+
150
+ Function and class cells define their own name; plain cells define the names they
151
+ return. The setup cell is not included.
152
+ """
153
+
154
+ names: set[str] = set()
155
+
156
+ for cell in self.cells:
157
+ if cell.tests or cell.hidden:
158
+ continue
159
+ match cell.kind:
160
+ case CellKind.FUNCTION | CellKind.CLASS:
161
+ names.add(cell.name)
162
+ case CellKind.CELL:
163
+ names |= _returned_names(_cell_node(self.src, cell))
164
+ case CellKind.SETUP:
165
+ pass
166
+
167
+ return names
168
+
169
+ def helper_cells(self) -> tuple[Cell, ...]:
170
+ """`# HIDDEN` cells without tests: data and helpers for hidden tests."""
171
+
172
+ return tuple(
173
+ cell
174
+ for cell in self.cells
175
+ if cell.hidden and not cell.tests and cell.kind is not CellKind.SETUP
176
+ )
177
+
178
+ def answer_cells(self, qid: str) -> tuple[Cell, ...]:
179
+ """Cells named `answer_<qid>` or `answer_<qid>_<suffix>`, as in the student copy."""
180
+
181
+ return self._named("answer", qid)
182
+
183
+ def prompt_cells(self, qid: str) -> tuple[Cell, ...]:
184
+ """Cells named `prompt_<qid>` or `prompt_<qid>_<suffix>`, as in the student copy."""
185
+
186
+ return self._named("prompt", qid)
187
+
188
+ def question_cells(self, qid: str) -> tuple[Cell, ...]:
189
+ """The cells of a question in the source: after the previous grade cell, up to its own.
190
+
191
+ The grade cell itself is not included. Empty when no grade cell names `qid`.
192
+ """
193
+
194
+ graded = [i for i, cell in enumerate(self.cells) if cell.grade_qid is not None]
195
+ end = next((i for i in graded if self.cells[i].grade_qid == qid), None)
196
+
197
+ if end is None:
198
+ return ()
199
+
200
+ start = max((i + 1 for i in graded if i < end), default=0)
201
+
202
+ return self.cells[start:end]
203
+
204
+ def written_cells(self, qid: str) -> tuple[tuple[Cell, ...], tuple[Cell, ...]]:
205
+ """Prompt and answer cells of a written question in the source, in file order.
206
+
207
+ The answers are the plain Markdown cells of the question (`question_cells`) that hold
208
+ a `<!-- BEGIN SOLUTION -->` line. Each answer's prompt is the run of `mo.md(...)` cells
209
+ just before it. Cells students don't see (hidden, instructor, test and assignment
210
+ cells) are skipped; any other cell, an answer included, ends the run. So text between
211
+ two answers belongs to the second. A prompt need not be a plain string; the PDF shows
212
+ such a cell as source.
213
+ """
214
+
215
+ lines = split_lines(self.src)
216
+ prompts: list[Cell] = []
217
+ answers: list[Cell] = []
218
+ run: list[Cell] = []
219
+
220
+ for cell in self.question_cells(qid):
221
+ if cell.hidden or cell.tests or cell.assignment or cell.instructor:
222
+ continue
223
+
224
+ if is_markdown(self, cell) and any(
225
+ line_marker(line, True)[0] is Marker.BEGIN
226
+ for line in lines[cell.start - 1 : cell.end]
227
+ ):
228
+ prompts += run
229
+ answers.append(cell)
230
+ run = []
231
+ elif is_md_call(self, cell):
232
+ run.append(cell)
233
+ else:
234
+ run = []
235
+
236
+ return tuple(prompts), tuple(answers)
237
+
238
+ def setup_source(self) -> str:
239
+ """Dedented body of the setup cell, or `""` when the notebook has none."""
240
+
241
+ setup = [cell for cell in self.cells if cell.kind is CellKind.SETUP]
242
+ return "".join(self.cell_body_source(cell) for cell in setup)
243
+
244
+ def cell_body_source(self, cell: Cell) -> str:
245
+ """Dedented source of a cell's body, ending in a newline.
246
+
247
+ For a plain cell this drops the `def` line and the final `return`. For the setup
248
+ cell it drops the `with` line. For a function or class cell it is the definition
249
+ without the `@app` decorators.
250
+
251
+ Raises:
252
+ SourceError: If the body starts on the same line as the `def` or `with`.
253
+ """
254
+
255
+ lines = split_lines(self.src)
256
+ node = _cell_node(self.src, cell)
257
+
258
+ match node:
259
+ case ast.FunctionDef() | ast.AsyncFunctionDef() | ast.ClassDef() if cell.kind in (
260
+ CellKind.FUNCTION,
261
+ CellKind.CLASS,
262
+ ):
263
+ first, last = _after_app_decorator(node), cell.end
264
+ case ast.FunctionDef() | ast.AsyncFunctionDef() | ast.With():
265
+ first = _header_end(lines, node, cell) + 1
266
+ body = node.body
267
+ match body[-1]:
268
+ case ast.Return() if cell.kind is CellKind.CELL:
269
+ last = body[-1].lineno - 1
270
+ case _:
271
+ last = cell.end
272
+ case _:
273
+ raise SourceError(f"line {cell.start}: unexpected {cell.kind} cell.")
274
+
275
+ chunk = lines[first - 1 : last]
276
+ while chunk and not chunk[-1].strip():
277
+ chunk.pop()
278
+
279
+ return textwrap.dedent("".join(line + "\n" for line in chunk))
280
+
281
+ def markdown_lines(self) -> frozenset[int]:
282
+ """Line numbers of the cells that are just `mo.md("...")`, decorators included."""
283
+
284
+ return frozenset(
285
+ number
286
+ for cell in self.cells
287
+ if is_markdown(self, cell)
288
+ for number in range(cell.start, cell.end + 1)
289
+ )
290
+
291
+ def grade_call(self, cell: Cell) -> ast.Call:
292
+ """The grade call of a cell, with line numbers of the whole notebook.
293
+
294
+ Raises:
295
+ SourceError: If the cell does not hold exactly one grade call.
296
+ """
297
+
298
+ calls = api_calls(ast.parse(self.src), _cell_node(self.src, cell), Api.GRADE)
299
+
300
+ match calls:
301
+ case [call]:
302
+ return call
303
+ case _:
304
+ raise SourceError(
305
+ f"line {cell.start}: expected one grade call, found {len(calls)}."
306
+ )
307
+
308
+ def grade_test_file(self, cell: Cell) -> str | None:
309
+ """The path a cell's grade call passes as a string literal `test_file`, if it does.
310
+
311
+ Raises:
312
+ SourceError: If the cell does not hold exactly one grade call.
313
+ """
314
+
315
+ for keyword in self.grade_call(cell).keywords:
316
+ match keyword:
317
+ case ast.keyword(arg="test_file", value=ast.Constant(value=str() as path)):
318
+ return path
319
+
320
+ return None
321
+
322
+ def _named(self, prefix: str, qid: str) -> tuple[Cell, ...]:
323
+ name = f"{prefix}_{qid}"
324
+ return tuple(
325
+ cell for cell in self.cells if cell.name == name or cell.name.startswith(f"{name}_")
326
+ )
327
+
328
+
329
+ def cell_names(source: str) -> tuple[set[str], set[str]]:
330
+ """Names `source`, run as a module, binds at top level, and global names it reads otherwise.
331
+
332
+ Uses Python's scope analysis, so names local to a function, class body or comprehension
333
+ are neither bound nor read.
334
+ """
335
+
336
+ top = symtable.symtable(source, "<cell>", "exec")
337
+ bound = set()
338
+ read = set()
339
+
340
+ for symbol in top.get_symbols():
341
+ if symbol.is_assigned() or symbol.is_imported() or symbol.is_namespace():
342
+ bound.add(symbol.get_name())
343
+ elif symbol.is_referenced():
344
+ read.add(symbol.get_name())
345
+
346
+ tables = list(top.get_children())
347
+
348
+ while tables:
349
+ table = tables.pop()
350
+ tables += table.get_children()
351
+ read |= {s.get_name() for s in table.get_symbols() if s.is_global() and s.is_referenced()}
352
+
353
+ return bound, read - bound
354
+
355
+
356
+ def module_tests(source: str) -> tuple[str, ...]:
357
+ """Names of the `test_*` functions that `source` defines at top level, in file order.
358
+
359
+ Raises:
360
+ SyntaxError: If `source` is not valid Python.
361
+ """
362
+
363
+ return tuple(
364
+ node.name
365
+ for node in ast.parse(source).body
366
+ if isinstance(node, ast.FunctionDef) and node.name.startswith("test_")
367
+ )
368
+
369
+
370
+ def prompt_previews(nb: Notebook, qid: str, width: int = 60) -> tuple[str, ...]:
371
+ """The first non-blank line of each prompt cell of a written question in the source.
372
+
373
+ A line longer than `width` is cut and ends in `…`. For a prompt that is not a plain
374
+ string, the line comes from its source. A blank prompt has no line, so a question with
375
+ only blank prompts gets `()`.
376
+ """
377
+
378
+ previews = []
379
+
380
+ for cell in nb.written_cells(qid)[0]:
381
+ text = answer_text(nb, cell)
382
+ source = nb.cell_body_source(cell) if text is None else text
383
+ line = next((line.strip() for line in source.splitlines() if line.strip()), "")
384
+
385
+ if line:
386
+ previews.append(line if len(line) <= width else line[: width - 1] + "…")
387
+
388
+ return tuple(previews)
389
+
390
+
391
+ def answer_text(nb: Notebook, cell: Cell) -> str | None:
392
+ """The Markdown of an answer cell that is just `mo.md("...")`; `None` for other code."""
393
+
394
+ try:
395
+ tree = ast.parse(nb.cell_body_source(cell))
396
+ except (SyntaxError, SourceError):
397
+ return None
398
+
399
+ match tree.body:
400
+ case []:
401
+ return ""
402
+ case [
403
+ ast.Expr(
404
+ value=ast.Call(
405
+ func=ast.Attribute(attr="md"), args=[ast.Constant(value=str() as text)]
406
+ )
407
+ )
408
+ ]:
409
+ return textwrap.dedent(text).strip()
410
+ case _:
411
+ return None
412
+
413
+
414
+ def is_md_call(nb: Notebook, cell: Cell) -> bool:
415
+ """A plain cell that is just a call to `mo.md`, with any argument."""
416
+
417
+ if cell.kind is not CellKind.CELL:
418
+ return False
419
+
420
+ try:
421
+ tree = ast.parse(nb.cell_body_source(cell))
422
+ except (SyntaxError, SourceError):
423
+ return False
424
+
425
+ match tree.body:
426
+ case [ast.Expr(value=ast.Call(func=ast.Attribute(attr="md")))]:
427
+ return True
428
+ case _:
429
+ return False
430
+
431
+
432
+ def is_markdown(nb: Notebook, cell: Cell) -> bool:
433
+ """A plain cell that is just `mo.md("...")`, the way marimo writes a Markdown cell."""
434
+
435
+ if cell.kind is not CellKind.CELL:
436
+ return False
437
+
438
+ try:
439
+ tree = ast.parse(nb.cell_body_source(cell))
440
+ except (SyntaxError, SourceError):
441
+ return False
442
+
443
+ return bool(tree.body) and answer_text(nb, cell) is not None
444
+
445
+
446
+ def answer_placeholders(nb: Notebook, qids: Iterable[str]) -> dict[str, str]:
447
+ """The text of each answer cell of `qids`, as `answer_text` gives it, by cell name.
448
+
449
+ Only answer cells holding non-blank `mo.md("...")` are included.
450
+ """
451
+
452
+ placeholders = {}
453
+
454
+ for qid in qids:
455
+ for cell in nb.answer_cells(qid):
456
+ match answer_text(nb, cell):
457
+ case str() as text if text.strip():
458
+ placeholders[cell.name] = text
459
+
460
+ return placeholders
461
+
462
+
463
+ def unanswered(text: str | None, placeholder: str | None) -> bool:
464
+ """Whether an answer is blank or still its starting text, ignoring whitespace.
465
+
466
+ Args:
467
+ text: The answer cell's text from `answer_text`; `None`, for code, counts as an answer.
468
+ placeholder: The text the answer cell starts with, if any.
469
+ """
470
+
471
+ if text is None:
472
+ return False
473
+
474
+ return not text.strip() or (placeholder is not None and _words(text) == _words(placeholder))
475
+
476
+
477
+ def _words(text: str) -> str:
478
+ """`text` with each run of whitespace made one space."""
479
+
480
+ return " ".join(text.split())
481
+
482
+
483
+ def cell_source(nb: Notebook, cell: Cell) -> str:
484
+ """The cell's lines as written, decorators included."""
485
+
486
+ return "\n".join(split_lines(nb.src)[cell.start - 1 : cell.end])
487
+
488
+
489
+ # Parsing
490
+
491
+
492
+ def parse_notebook(src: str) -> Notebook:
493
+ """Parse the cells of a marimo notebook.
494
+
495
+ Raises:
496
+ SourceError: If the source is not valid Python, or a grade call does not name its
497
+ question with a string literal, or a cell holds more than one, or an `@app.*`
498
+ decorator does not fit what it decorates.
499
+ """
500
+
501
+ src = normalize_newlines(src)
502
+
503
+ try:
504
+ tree = ast.parse(src)
505
+ except SyntaxError as e:
506
+ raise SourceError(f"The notebook is not valid Python (line {e.lineno}): {e.msg}") from e
507
+
508
+ lines = split_lines(src)
509
+ cells = []
510
+
511
+ for node in tree.body:
512
+ match node:
513
+ case ast.With(items=[ast.withitem(context_expr=expr)]) if _app_attr(expr) == "setup":
514
+ kind, name, start = CellKind.SETUP, "setup", node.lineno
515
+ case ast.FunctionDef() | ast.AsyncFunctionDef() | ast.ClassDef():
516
+ match _decorator_kind(node):
517
+ case None:
518
+ continue
519
+ case kind:
520
+ name = node.name
521
+ start = min(d.lineno for d in node.decorator_list)
522
+ case _:
523
+ continue
524
+
525
+ end = _trailing_comments_end(lines, _end(node))
526
+ text = lines[start - 1 : end]
527
+ tests = _tests(node, kind)
528
+ markers = [start + i for i, line in enumerate(text) if line.strip() == HIDDEN]
529
+ first_statement = node.body[0].lineno
530
+ late = next((line for line in markers if line > first_statement), None)
531
+ plain = kind is CellKind.CELL
532
+ grade = _call_qid(tree, node, Api.GRADE) if plain else None
533
+ assignment = bool(api_calls(tree, node, Api.ASSIGNMENT))
534
+
535
+ cells.append(Cell(kind, name, start, end, tests, bool(markers), grade, assignment, late))
536
+
537
+ return Notebook(tuple(cells), src)
538
+
539
+
540
+ def _app_attr(expr: ast.expr) -> str | None:
541
+ """`x` for `app.x` or `app.x(...)`."""
542
+
543
+ match expr:
544
+ case (
545
+ ast.Attribute(value=ast.Name(id="app"), attr=attr)
546
+ | ast.Call(func=ast.Attribute(value=ast.Name(id="app"), attr=attr))
547
+ ):
548
+ return attr
549
+ case _:
550
+ return None
551
+
552
+
553
+ def _decorator_kind(node: ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef) -> CellKind | None:
554
+ """Cell kind from the node's `@app.*` decorator, or None if it has none."""
555
+
556
+ for decorator in node.decorator_list:
557
+ match _app_attr(decorator), node:
558
+ case "cell", ast.FunctionDef() | ast.AsyncFunctionDef():
559
+ return CellKind.CELL
560
+ case "function", ast.FunctionDef():
561
+ return CellKind.FUNCTION
562
+ case "class_definition", ast.ClassDef():
563
+ return CellKind.CLASS
564
+ case str() as attr, _:
565
+ raise SourceError(f"line {decorator.lineno}: unexpected `@app.{attr}` here.")
566
+
567
+ return None
568
+
569
+
570
+ def _after_app_decorator(node: ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef) -> int:
571
+ """First line after the `@app.*` decorator: the next decorator, or the definition."""
572
+
573
+ rest = [d for d in node.decorator_list if _app_attr(d) is None]
574
+ return min([node.lineno] + [d.lineno for d in rest])
575
+
576
+
577
+ def _tests(node: ast.stmt, kind: CellKind) -> tuple[str, ...]:
578
+ match node, kind:
579
+ case ast.FunctionDef(name=name), CellKind.FUNCTION if name.startswith("test_"):
580
+ return (name,)
581
+ case ast.FunctionDef(body=body) | ast.AsyncFunctionDef(body=body), CellKind.CELL:
582
+ return tuple(
583
+ stmt.name
584
+ for stmt in body
585
+ if isinstance(stmt, ast.FunctionDef) and stmt.name.startswith("test_")
586
+ )
587
+ case _:
588
+ return ()
589
+
590
+
591
+ def _call_qid(tree: ast.Module, node: ast.stmt, api: Api) -> str | None:
592
+ """Question id of the single `api` call in a cell, or None if it has none."""
593
+
594
+ found: list[str] = []
595
+
596
+ for call in api_calls(tree, node, api):
597
+ match call.args:
598
+ case [ast.Constant(value=str() as qid), *_]:
599
+ found.append(qid)
600
+ case _:
601
+ raise SourceError(
602
+ f"line {call.lineno}: {api}() needs the question id as a string literal "
603
+ f'first argument, e.g. mogs.{api}("q1", points=10).'
604
+ )
605
+
606
+ match found:
607
+ case []:
608
+ return None
609
+ case [qid]:
610
+ return qid
611
+ case _:
612
+ raise SourceError(
613
+ f"line {node.lineno}: a cell may hold only one {api} call, found {len(found)}."
614
+ )
615
+
616
+
617
+ def _cell_node(src: str, cell: Cell) -> ast.stmt:
618
+ """AST of one cell, with line numbers of the whole notebook."""
619
+
620
+ lines = split_lines(src)
621
+ padding = "\n" * (cell.start - 1)
622
+ return ast.parse(padding + "\n".join(lines[cell.start - 1 : cell.end])).body[0]
623
+
624
+
625
+ def _end(node: ast.stmt) -> int:
626
+ match node.end_lineno:
627
+ case int() as end:
628
+ return end
629
+ case None:
630
+ raise SourceError(f"line {node.lineno}: statement has no end line.")
631
+
632
+
633
+ def _trailing_comments_end(lines: list[str], end: int) -> int:
634
+ """Move `end` past indented comment lines that follow it, such as `# END SOLUTION`."""
635
+
636
+ last = end
637
+
638
+ for number in range(end + 1, len(lines) + 1):
639
+ line = lines[number - 1]
640
+ if not line.strip():
641
+ continue
642
+ if line[0] not in " \t" or not line.strip().startswith("#"):
643
+ break
644
+ last = number
645
+
646
+ return last
647
+
648
+
649
+ def _header_end(lines: list[str], node: ast.stmt, cell: Cell) -> int:
650
+ """Last line of a `def ...:` or `with ...:` header, before its body and comments."""
651
+
652
+ match node:
653
+ case ast.FunctionDef(body=body) | ast.AsyncFunctionDef(body=body) | ast.With(body=body):
654
+ pass
655
+ case _:
656
+ raise SourceError(f"line {cell.start}: not a cell body.")
657
+
658
+ header = [
659
+ number
660
+ for number in range(node.lineno, body[0].lineno)
661
+ if lines[number - 1].strip() and not lines[number - 1].strip().startswith("#")
662
+ ]
663
+ if not header:
664
+ raise SourceError(f"line {node.lineno}: put the cell body on its own lines.")
665
+
666
+ return header[-1]
667
+
668
+
669
+ def _returned_names(node: ast.stmt) -> set[str]:
670
+ """Names in the final `return` of a plain cell."""
671
+
672
+ match node:
673
+ case (
674
+ ast.FunctionDef(body=[*_, ast.Return(value=value)])
675
+ | ast.AsyncFunctionDef(body=[*_, ast.Return(value=value)])
676
+ ):
677
+ pass
678
+ case _:
679
+ return set()
680
+
681
+ match value:
682
+ case ast.Tuple(elts=elts):
683
+ return {elt.id for elt in elts if isinstance(elt, ast.Name)}
684
+ case ast.Name(id=name):
685
+ return {name}
686
+ case _:
687
+ return set()
688
+
689
+
690
+ # Validation
691
+
692
+
693
+ def source_warnings(nb: Notebook) -> list[str]:
694
+ """Things in the notebook that build but may not do what the instructor meant."""
695
+
696
+ late = [
697
+ f"line {cell.late_hidden}: `{HIDDEN}` hides the whole cell at line {cell.start}, not "
698
+ "only the code after it. Move it to the cell's first line, or move the hidden tests "
699
+ "to a cell of their own."
700
+ for cell in nb.cells
701
+ if cell.late_hidden is not None
702
+ ]
703
+ uncollected = [
704
+ f"line {cell.start}: `pytest` on the notebook skips {', '.join(cell.tests)}, since "
705
+ "marimo collects only cells that hold nothing but tests. Gradescope still runs them. "
706
+ "Move the other code to a cell of its own."
707
+ for cell in nb.cells
708
+ if cell.kind is CellKind.CELL and cell.tests and not _only_tests(nb, cell)
709
+ ]
710
+
711
+ return late + uncollected
712
+
713
+
714
+ def _only_tests(nb: Notebook, cell: Cell) -> bool:
715
+ """Whether marimo's pytest plugin collects the cell: its body defines only `test*` names.
716
+
717
+ Mirrors `contains_only_tests` in marimo's compiler, without pytest fixtures, which the
718
+ grader doesn't support.
719
+ """
720
+
721
+ for node in ast.parse(nb.cell_body_source(cell)).body:
722
+ match node:
723
+ case ast.FunctionDef() | ast.AsyncFunctionDef() | ast.ClassDef() if (
724
+ node.name.lower().startswith("test")
725
+ ):
726
+ continue
727
+ case _:
728
+ return False
729
+
730
+ return True
731
+
732
+
733
+ def validate(nb: Notebook, cfg: AssignmentConfig) -> list[str]:
734
+ """Check the notebook against its config and the authoring rules.
735
+
736
+ Returns:
737
+ One message per problem. Empty when the notebook is valid.
738
+ """
739
+
740
+ # Misspelled markers first: they also cause the region errors below.
741
+ errors = _near_marker_errors(nb) + _near_html_marker_errors(nb)
742
+ errors += _test_name_errors(nb, cfg) + _question_errors(nb, cfg)
743
+ errors += _hidden_grade_errors(nb) + _public_cell_errors(nb) + _marker_errors(nb)
744
+ errors += _assignment_errors(nb) + _instructor_errors(nb) + _pytest_dependency_errors(nb)
745
+ errors += _public_marker_errors(nb)
746
+ errors += _hidden_name_errors(nb) + _cell_variable_errors(nb)
747
+
748
+ return errors
749
+
750
+
751
+ def _test_name_errors(nb: Notebook, cfg: AssignmentConfig) -> list[str]:
752
+ """Duplicate tests, cells mixing questions, and unknown questions in tests or grades."""
753
+
754
+ errors = []
755
+ seen: set[str] = set()
756
+
757
+ for cell in nb.cells:
758
+ # A test of an unknown question gets its own error below, usually a misnamed test.
759
+ known = {question_id(name) for name in cell.tests} & cfg.questions.keys()
760
+
761
+ if len(known) > 1:
762
+ errors.append(
763
+ f"line {cell.start}: tests of different questions share a cell "
764
+ f"({', '.join(cell.tests)}). Put each question's tests in their own cell."
765
+ )
766
+
767
+ for name in cell.tests:
768
+ if name in seen:
769
+ errors.append(f"`{name}` (line {cell.start}) is defined more than once.")
770
+ seen.add(name)
771
+
772
+ qid = question_id(name)
773
+ if qid not in cfg.questions:
774
+ errors.append(
775
+ f"`{name}` (line {cell.start}): no question `{qid}`. Tests are named "
776
+ f"`test_<qid>_<name>`, so rename it, or declare `{qid}` in a cell with "
777
+ f'`mogs.grade("{qid}", points=...)`.'
778
+ )
779
+
780
+ if cell.grade_qid is not None and cell.grade_qid not in cfg.questions:
781
+ errors.append(
782
+ f'grade("{cell.grade_qid}") (line {cell.start}): no question '
783
+ f"`{cell.grade_qid}` in the config."
784
+ )
785
+
786
+ return errors
787
+
788
+
789
+ def _question_errors(nb: Notebook, cfg: AssignmentConfig) -> list[str]:
790
+ """Each auto question has tests and a grade cell; each manual one has an answer cell."""
791
+
792
+ errors = []
793
+ tests = nb.tests_by_question()
794
+ graded = {cell.grade_qid for cell in nb.cells}
795
+
796
+ for qid, question in cfg.questions.items():
797
+ public, hidden = tests.get(qid, ([], []))
798
+
799
+ if question.manual:
800
+ if public or hidden:
801
+ errors.append(
802
+ f"Question `{qid}` is manual but has tests: {', '.join(public + hidden)}."
803
+ )
804
+ if not nb.written_cells(qid)[1]:
805
+ errors.append(
806
+ f"Question `{qid}` has no tests and no written answer. Add `test_{qid}_*` "
807
+ f'functions, or a Markdown cell before `mogs.grade("{qid}", ...)` with '
808
+ f"your answer between `{HtmlMarker.BEGIN}` and `{HtmlMarker.END}`."
809
+ )
810
+ continue
811
+
812
+ if not public and not hidden:
813
+ errors.append(f"Question `{qid}` has no tests. Add `test_{qid}_*` functions.")
814
+ elif public and qid not in graded:
815
+ errors.append(
816
+ f"Question `{qid}` has public tests but no grade cell. Add a cell with "
817
+ f'`mogs.grade("{qid}", points=...)`.'
818
+ )
819
+
820
+ return errors
821
+
822
+
823
+ def _hidden_grade_errors(nb: Notebook) -> list[str]:
824
+ """Grade calls sit outside `# HIDDEN` cells, which the student copy drops."""
825
+
826
+ return [
827
+ f"grade() for {cell.grade_qid} is in a hidden cell (line {cell.start}), so the student "
828
+ f"copy would lose it. Move it to a cell without `{HIDDEN}`."
829
+ for cell in nb.cells
830
+ if cell.hidden and cell.grade_qid is not None
831
+ ]
832
+
833
+
834
+ def _pytest_dependency_errors(nb: Notebook) -> list[str]:
835
+ """A notebook that imports `pytest` lists it in the header's `dependencies`.
836
+
837
+ The grader has pytest either way, but marimo adds a pinned `pytest` to the header of a
838
+ student notebook that imports it without one.
839
+ """
840
+
841
+ lines = [
842
+ node.lineno
843
+ for node in ast.walk(ast.parse(nb.src))
844
+ if isinstance(node, ast.Import)
845
+ and any(alias.name.split(".")[0] == "pytest" for alias in node.names)
846
+ or isinstance(node, ast.ImportFrom)
847
+ and (node.module or "").split(".")[0] == "pytest"
848
+ ]
849
+
850
+ if not lines:
851
+ return []
852
+
853
+ try:
854
+ dependencies = read_header(nb.src).get("dependencies", [])
855
+ except ConfigError as error:
856
+ return [
857
+ f"line {lines[0]}: the notebook imports `pytest`, but its header is unreadable: {error}"
858
+ ]
859
+
860
+ if any(normalized_name(dep) == "pytest" for dep in dependencies):
861
+ return []
862
+
863
+ return [
864
+ f"line {lines[0]}: the notebook imports `pytest`, but the header's `dependencies` "
865
+ "doesn't list it. Add `pytest` there, or marimo adds a pinned one to each student's "
866
+ "header."
867
+ ]
868
+
869
+
870
+ def _assignment_errors(nb: Notebook) -> list[str]:
871
+ """The `assignment(...)` call sits alone in a plain cell, which the build drops."""
872
+
873
+ errors = []
874
+
875
+ for cell in nb.cells:
876
+ if not cell.assignment:
877
+ continue
878
+
879
+ node = _cell_node(nb.src, cell)
880
+ calls = api_calls(ast.parse(nb.src), node, Api.ASSIGNMENT)
881
+ match node:
882
+ case ast.FunctionDef(body=[ast.Expr(value=ast.Call() as call), *rest]) if (
883
+ cell.kind is CellKind.CELL
884
+ and not cell.hidden
885
+ and calls == [call]
886
+ and all(isinstance(stmt, ast.Return) and stmt.value is None for stmt in rest)
887
+ and len(rest) <= 1
888
+ ):
889
+ continue
890
+
891
+ errors.append(
892
+ f"line {cell.start}: put `{ASSIGNMENT}` in a cell of its own, without other code "
893
+ f"or `{HIDDEN}`. The build removes that cell from the student notebook."
894
+ )
895
+
896
+ return errors
897
+
898
+
899
+ def _instructor_errors(nb: Notebook) -> list[str]:
900
+ """Instructor cells are plain cells that the rest of the notebook does not need.
901
+
902
+ The build drops them, so they define no names for other cells and hold no tests or grade
903
+ calls.
904
+ """
905
+
906
+ errors = []
907
+
908
+ for cell in nb.cells:
909
+ if not cell.instructor:
910
+ continue
911
+
912
+ where = f"Instructor cell `{cell.name}` (line {cell.start})"
913
+
914
+ if cell.kind is not CellKind.CELL:
915
+ errors.append(f"{where} must be a plain `@app.cell`; the build removes it.")
916
+ continue
917
+
918
+ returned = sorted(_returned_names(_cell_node(nb.src, cell)))
919
+ problems = [
920
+ *([f"returns {', '.join(returned)}"] if returned else []),
921
+ *([f"defines {', '.join(cell.tests)}"] if cell.tests else []),
922
+ *([f"calls grade() for {cell.grade_qid}"] if cell.grade_qid else []),
923
+ *([f"holds `{HIDDEN}`"] if cell.hidden else []),
924
+ ]
925
+
926
+ if problems:
927
+ errors.append(
928
+ f"{where} {'; '.join(problems)}. The build removes instructor cells from the "
929
+ "student notebook, so keep only notes for yourself in them."
930
+ )
931
+
932
+ return errors
933
+
934
+
935
+ def _public_cell_errors(nb: Notebook) -> list[str]:
936
+ """Public test cells hold only `test_*` functions, as marimo's pytest collection needs."""
937
+
938
+ errors = []
939
+
940
+ for cell in nb.cells:
941
+ if cell.kind is not CellKind.CELL or not cell.tests or cell.hidden:
942
+ continue
943
+
944
+ node = _cell_node(nb.src, cell)
945
+ match node:
946
+ case ast.FunctionDef(body=body) | ast.AsyncFunctionDef(body=body):
947
+ pass
948
+ case _:
949
+ continue
950
+
951
+ for index, stmt in enumerate(body):
952
+ where = (
953
+ f"Public test cell with {', '.join(cell.tests)} (line {cell.start}) has "
954
+ f"`{split_lines(ast.unparse(stmt))[0]}` at line {stmt.lineno}."
955
+ )
956
+ match stmt:
957
+ case ast.FunctionDef(name=name) if name.startswith("test_"):
958
+ continue
959
+ case ast.Return() if index == len(body) - 1:
960
+ continue
961
+ case ast.Import() | ast.ImportFrom():
962
+ errors.append(
963
+ f"{where} marimo's pytest collection skips test cells with imports. "
964
+ "Move the import to the setup cell (`with app.setup:`)."
965
+ )
966
+ case _:
967
+ errors.append(
968
+ f"{where} A public test cell may hold only `test_*` functions. Move "
969
+ f"other code to its own cell, or mark the cell `{HIDDEN}`."
970
+ )
971
+ break
972
+
973
+ return errors
974
+
975
+
976
+ def _hidden_name_errors(nb: Notebook) -> list[str]:
977
+ """Names the grader cannot provide to hidden cells, and hidden cells shadowing others.
978
+
979
+ When grading, every test cell runs on its own, so a name defined in a test cell is not
980
+ available to other cells. A hidden cell that redefines a student or setup name would
981
+ replace the student's value. Names starting with `_` are private to their cell in marimo,
982
+ so a hidden cell may reuse them.
983
+ """
984
+
985
+ errors = []
986
+ students = nb.student_names()
987
+ setup, _ = cell_names(nb.setup_source())
988
+ names = {cell: cell_names(nb.cell_body_source(cell)) for cell in nb.cells if _graded(cell)}
989
+ helpers = {name for cell in nb.helper_cells() for name in names[cell][0]}
990
+ shared = students | setup | helpers
991
+
992
+ for cell, (bound, _) in names.items():
993
+ if not cell.hidden:
994
+ continue
995
+ bound = {name for name in bound if not name.startswith("_")}
996
+ for name in sorted(bound & students):
997
+ errors.append(
998
+ f"line {cell.start}: hidden cell defines `{name}`, which is also defined by a "
999
+ "student cell."
1000
+ )
1001
+ for name in sorted(bound & setup):
1002
+ errors.append(
1003
+ f"line {cell.start}: hidden cell defines `{name}`, which is also defined by "
1004
+ "the setup cell."
1005
+ )
1006
+
1007
+ for cell, (_, free) in names.items():
1008
+ for name in sorted(free - shared):
1009
+ owners = [other for other, (bound, _) in names.items() if name in bound]
1010
+ if owners and cell not in owners:
1011
+ errors.append(
1012
+ f"line {cell.start}: uses `{name}`, which only the test cell at line "
1013
+ f"{owners[0].start} defines. Test cells run on their own when grading; "
1014
+ f"define `{name}` in a `{HIDDEN}` cell without tests."
1015
+ )
1016
+
1017
+ errors += _helper_cycle_errors({cell: names[cell] for cell in nb.helper_cells()})
1018
+
1019
+ return errors
1020
+
1021
+
1022
+ CELL_VARIABLE_FIX = (
1023
+ "The grader imports the functions the tests use without running the notebook, so it "
1024
+ "can't get that name. Write the answer as an `@app.function` that the test calls, and put "
1025
+ "data the tests need in the setup cell (`with app.setup:`) or load it in the test."
1026
+ )
1027
+
1028
+
1029
+ def _cell_variable_errors(nb: Notebook) -> list[str]:
1030
+ """Tests and hidden helpers that read a name defined by a student's plain cell.
1031
+
1032
+ The grader can get such a name only by running the whole notebook (see `loader`), where
1033
+ one failing cell anywhere makes it unavailable. Graded answers are functions instead.
1034
+ """
1035
+
1036
+ errors = []
1037
+ defined = _cell_variable_lines(nb)
1038
+ helpers = nb.helper_cells()
1039
+
1040
+ for cell in nb.cells:
1041
+ if cell.tests:
1042
+ for test, line, read in _test_reads(nb, cell):
1043
+ errors += [
1044
+ f"Question `{question_id(test)}`: `{test}` (line {line}) reads `{name}`, "
1045
+ f"which a plain `@app.cell` defines at line {defined[name]}. "
1046
+ + CELL_VARIABLE_FIX
1047
+ for name in sorted(read & defined.keys())
1048
+ ]
1049
+ elif cell in helpers:
1050
+ _, read = cell_names(nb.cell_body_source(cell))
1051
+ errors += [
1052
+ f"The `{HIDDEN}` cell at line {cell.start} reads `{name}`, which a plain "
1053
+ f"`@app.cell` defines at line {defined[name]}. " + CELL_VARIABLE_FIX
1054
+ for name in sorted(read & defined.keys())
1055
+ ]
1056
+
1057
+ return errors
1058
+
1059
+
1060
+ def _cell_variable_lines(nb: Notebook) -> dict[str, int]:
1061
+ """Each name a student's plain cell returns, with the line that first binds it."""
1062
+
1063
+ lines = {}
1064
+
1065
+ for cell in nb.cells:
1066
+ if cell.kind is not CellKind.CELL or cell.tests or cell.hidden:
1067
+ continue
1068
+
1069
+ node = _cell_node(nb.src, cell)
1070
+ for name in _returned_names(node):
1071
+ lines[name] = _binding_line(node, name) or cell.start
1072
+
1073
+ return lines
1074
+
1075
+
1076
+ def _binding_line(node: ast.stmt, name: str) -> int | None:
1077
+ """Line of the first statement in a plain cell's body that binds `name`."""
1078
+
1079
+ match node:
1080
+ case ast.FunctionDef(body=body) | ast.AsyncFunctionDef(body=body):
1081
+ pass
1082
+ case _:
1083
+ return None
1084
+
1085
+ for stmt in body:
1086
+ for sub in ast.walk(stmt):
1087
+ match sub:
1088
+ case ast.Name(id=found, ctx=ast.Store()) if found == name:
1089
+ return sub.lineno
1090
+ case (
1091
+ ast.FunctionDef(name=found)
1092
+ | ast.AsyncFunctionDef(name=found)
1093
+ | ast.ClassDef(name=found)
1094
+ ) if found == name:
1095
+ return sub.lineno
1096
+ case ast.alias(name=imported, asname=alias) if (
1097
+ alias or imported.split(".")[0]
1098
+ ) == name:
1099
+ return stmt.lineno
1100
+
1101
+ return None
1102
+
1103
+
1104
+ def _test_reads(nb: Notebook, cell: Cell) -> list[tuple[str, int, set[str]]]:
1105
+ """Each test of a cell, its line, and the global names it reads.
1106
+
1107
+ Names the cell reads outside its tests, such as in a helper function of a hidden test
1108
+ cell, count for every test of the cell.
1109
+ """
1110
+
1111
+ node = _cell_node(nb.src, cell)
1112
+ bound, read = cell_names(nb.cell_body_source(cell))
1113
+
1114
+ match node:
1115
+ case ast.FunctionDef(body=body) | ast.AsyncFunctionDef(body=body) if (
1116
+ cell.kind is CellKind.CELL
1117
+ ):
1118
+ functions = [stmt for stmt in body if isinstance(stmt, ast.FunctionDef)]
1119
+ case ast.FunctionDef():
1120
+ functions = [node]
1121
+ case _:
1122
+ functions = []
1123
+
1124
+ tests = {fn.name: fn for fn in functions if fn.name in cell.tests}
1125
+ own = {name: cell_names(ast.unparse(fn))[1] - bound for name, fn in tests.items()}
1126
+ rest = read - set().union(*own.values())
1127
+
1128
+ return [(name, fn.lineno, own[name] | rest) for name, fn in tests.items()]
1129
+
1130
+
1131
+ def _graded(cell: Cell) -> bool:
1132
+ """A test cell or a hidden helper cell."""
1133
+
1134
+ return bool(cell.tests) or (cell.hidden and cell.kind is not CellKind.SETUP)
1135
+
1136
+
1137
+ def _helper_cycle_errors(names: dict[Cell, tuple[set[str], set[str]]]) -> list[str]:
1138
+ """One error per cycle of hidden helper cells that need each other's names."""
1139
+
1140
+ needs = {
1141
+ cell: [other for other, (bound, _) in names.items() if other is not cell and free & bound]
1142
+ for cell, (_, free) in names.items()
1143
+ }
1144
+ done: set[Cell] = set()
1145
+ errors = []
1146
+
1147
+ def visit(cell: Cell, path: list[Cell]) -> None:
1148
+ if cell in path:
1149
+ cycle = path[path.index(cell) :]
1150
+ lines = ", ".join(str(c.start) for c in cycle)
1151
+ errors.append(f"hidden cells at lines {lines} need each other's names in a cycle.")
1152
+ return
1153
+
1154
+ if cell in done:
1155
+ return
1156
+
1157
+ for other in needs[cell]:
1158
+ visit(other, [*path, cell])
1159
+
1160
+ done.add(cell)
1161
+
1162
+ for cell in needs:
1163
+ visit(cell, [])
1164
+
1165
+ return errors
1166
+
1167
+
1168
+ def _public_marker_errors(nb: Notebook) -> list[str]:
1169
+ """Solution markers in public test cells, which go to students as written.
1170
+
1171
+ One error per cell, at its first marker.
1172
+ """
1173
+
1174
+ markers = (SOLUTION, BEGIN, END)
1175
+ public = [cell for cell in nb.cells if cell.tests and not cell.hidden]
1176
+ found: dict[Cell, tuple[int, str]] = {}
1177
+
1178
+ for token in tokenize.generate_tokens(io.StringIO(nb.src).readline):
1179
+ number = token.start[0]
1180
+ comment = token.string.rstrip()
1181
+
1182
+ if token.type != tokenize.COMMENT or comment not in markers:
1183
+ continue
1184
+
1185
+ for cell in public:
1186
+ if cell.start <= number <= cell.end:
1187
+ found.setdefault(cell, (number, comment))
1188
+
1189
+ return [
1190
+ f"line {number}: `{comment}` is in a public test cell. Students get the public tests "
1191
+ f"as written, so move the solution to a `{HIDDEN}` cell."
1192
+ for number, comment in found.values()
1193
+ ]
1194
+
1195
+
1196
+ def line_marker(line: str, markdown: bool) -> tuple[Marker | None, str]:
1197
+ """The solution marker `line` is, and a prompt line's text.
1198
+
1199
+ In a Markdown cell the markers are HTML comments (`HtmlMarker`); elsewhere they are
1200
+ Python comments. A line that is no marker gives `(None, "")`.
1201
+ """
1202
+
1203
+ stripped = line.strip()
1204
+
1205
+ if markdown:
1206
+ match stripped:
1207
+ case HtmlMarker.BEGIN:
1208
+ return Marker.BEGIN, ""
1209
+ case HtmlMarker.END:
1210
+ return Marker.END, ""
1211
+
1212
+ prompt = HTML_PROMPT_RE.fullmatch(stripped)
1213
+ return (Marker.PROMPT, prompt.group(1) or "") if prompt else (None, "")
1214
+
1215
+ match stripped:
1216
+ case Marker.BEGIN | Marker.END:
1217
+ return Marker(stripped), ""
1218
+ case _ if stripped.startswith(PROMPT):
1219
+ return Marker.PROMPT, stripped.removeprefix(PROMPT).removeprefix(" ")
1220
+ case _:
1221
+ return None, ""
1222
+
1223
+
1224
+ def _marker_errors(nb: Notebook) -> list[str]:
1225
+ """Solution markers pair up in the same cell, and Markdown cells use the HTML ones."""
1226
+
1227
+ errors = []
1228
+ opened: int | None = None
1229
+ markdown = nb.markdown_lines()
1230
+
1231
+ def cell_at(number: int) -> Cell | None:
1232
+ return next((cell for cell in nb.cells if cell.start <= number <= cell.end), None)
1233
+
1234
+ for number, line in enumerate(split_lines(nb.src), start=1):
1235
+ if number in markdown:
1236
+ errors += _markdown_line_errors(number, line.strip())
1237
+ elif line_marker(line, True)[0] is not None:
1238
+ errors.append(
1239
+ f"line {number}: `{line.strip()}` is read only in a Markdown cell written with "
1240
+ 'a plain string, `mo.md(r"""...""")`. Elsewhere the solution would reach '
1241
+ "students."
1242
+ )
1243
+
1244
+ match line_marker(line, number in markdown)[0], opened:
1245
+ case Marker.BEGIN, None:
1246
+ opened = number
1247
+ case Marker.BEGIN, int():
1248
+ errors.append(
1249
+ f"line {number}: `{BEGIN}` inside the region opened at line {opened}."
1250
+ )
1251
+ case Marker.END, None:
1252
+ errors.append(f"line {number}: `{END}` without a matching `{BEGIN}`.")
1253
+ case Marker.END, int() as start:
1254
+ if cell_at(start) != cell_at(number):
1255
+ errors.append(
1256
+ f"line {start}: `{BEGIN}` is closed in another cell, at line {number}."
1257
+ )
1258
+ opened = None
1259
+
1260
+ if opened is not None:
1261
+ errors.append(f"line {opened}: `{BEGIN}` without a matching `{END}`.")
1262
+
1263
+ return errors
1264
+
1265
+
1266
+ def _markdown_line_errors(number: int, stripped: str) -> list[str]:
1267
+ """A `#` marker in a Markdown cell, where it is a heading."""
1268
+
1269
+ html = {
1270
+ BEGIN: HtmlMarker.BEGIN,
1271
+ END: HtmlMarker.END,
1272
+ SOLUTION: f"{HtmlMarker.BEGIN} ... {HtmlMarker.END}",
1273
+ }
1274
+
1275
+ for marker, replacement in html.items():
1276
+ if stripped == marker or stripped.endswith(f" {marker}"):
1277
+ return [
1278
+ f"line {number}: `{marker}` in a Markdown cell is a heading. Write "
1279
+ f"`{replacement}` instead."
1280
+ ]
1281
+
1282
+ if stripped.startswith(PROMPT):
1283
+ return [
1284
+ f"line {number}: `{PROMPT}` in a Markdown cell is a heading. Write "
1285
+ f"`{HtmlMarker.PROMPT}` instead."
1286
+ ]
1287
+
1288
+ return []
1289
+
1290
+
1291
+ def _near_marker_errors(nb: Notebook) -> list[str]:
1292
+ """Comments that look like a marker but are misspelled, or a `# HIDDEN` after code.
1293
+
1294
+ A misspelled marker is an ordinary comment to the transform, so the solution or hidden
1295
+ test next to it would reach the student copy. Prompt lines count only inside solution
1296
+ regions, so a comment such as `# prompt template` elsewhere is fine.
1297
+ """
1298
+
1299
+ errors = []
1300
+ markers = (SOLUTION, BEGIN, END)
1301
+ lines = split_lines(nb.src)
1302
+ regions = _region_lines(lines, nb.markdown_lines())
1303
+
1304
+ for token in tokenize.generate_tokens(io.StringIO(nb.src).readline):
1305
+ if token.type != tokenize.COMMENT:
1306
+ continue
1307
+
1308
+ comment = token.string.rstrip()
1309
+ number = token.start[0]
1310
+
1311
+ if near_solution_marker(comment) and comment not in markers:
1312
+ errors.append(
1313
+ f"line {number}: `{comment}` looks like a solution marker. Write it exactly as "
1314
+ f"`{SOLUTION}`, `{BEGIN}` or `{END}`."
1315
+ )
1316
+ elif NEAR_HIDDEN_RE.match(comment) and comment != HIDDEN:
1317
+ errors.append(
1318
+ f"line {number}: `{comment}` looks like a hidden marker. Write it exactly as "
1319
+ f"`{HIDDEN}` on its own line, or reword the comment."
1320
+ )
1321
+ elif comment == HIDDEN and lines[number - 1].strip() != HIDDEN:
1322
+ errors.append(f"line {number}: `{HIDDEN}` must be on its own line to hide its cell.")
1323
+ elif number in regions and NEAR_PROMPT_RE.match(comment) and not comment.startswith(PROMPT):
1324
+ errors.append(
1325
+ f"line {number}: `{comment}` looks like a prompt line. Write it as "
1326
+ f"`{PROMPT} <code>`."
1327
+ )
1328
+
1329
+ return errors
1330
+
1331
+
1332
+ def _near_html_marker_errors(nb: Notebook) -> list[str]:
1333
+ """HTML comments in Markdown cells that look like a marker but are misspelled.
1334
+
1335
+ Only `<!--` lines count. A `#` line in Markdown is a heading, such as `# Solution
1336
+ approach`; `_markdown_line_errors` handles the exact `#` markers there.
1337
+ """
1338
+
1339
+ errors = []
1340
+ lines = split_lines(nb.src)
1341
+ exact = (HtmlMarker.BEGIN, HtmlMarker.END)
1342
+
1343
+ for number in sorted(nb.markdown_lines()):
1344
+ stripped = lines[number - 1].strip()
1345
+
1346
+ if not stripped.startswith("<!--"):
1347
+ continue
1348
+
1349
+ if stripped in exact or HTML_PROMPT_RE.fullmatch(stripped):
1350
+ continue
1351
+
1352
+ if NEAR_HTML_RE.match(stripped) or near_solution_marker(stripped):
1353
+ errors.append(
1354
+ f"line {number}: `{stripped}` looks like a solution marker. Write it exactly as "
1355
+ f"`{HtmlMarker.BEGIN}`, `{HtmlMarker.END}` or `{HtmlMarker.PROMPT}`."
1356
+ )
1357
+
1358
+ return errors
1359
+
1360
+
1361
+ def near_solution_marker(comment: str) -> bool:
1362
+ """Whether `comment` starts like a solution marker, misspelled or not.
1363
+
1364
+ `comment` is a `#` or `<!--` comment. Its first word, or its first two words after
1365
+ `BEGIN` or `END`, are compared with `SOLUTION`, `BEGIN SOLUTION` and `END SOLUTION`,
1366
+ ignoring case and spaces. One typo (a wrong, missing, extra or swapped letter) counts.
1367
+ Two count only in an all-caps word that keeps the first letter, as in `# SLOUTOIN`;
1368
+ lowercase words two typos away are ordinary English, such as `resolution`.
1369
+ The caller checks that the comment is not the exact marker.
1370
+ """
1371
+
1372
+ match = LEADING_WORDS_RE.match(comment)
1373
+ if match is None:
1374
+ return False
1375
+
1376
+ first, second = match.group(1), match.group(2)
1377
+
1378
+ if _near_word(first, SOLUTION_WORD):
1379
+ return True
1380
+
1381
+ if any(_near_word(first, region + SOLUTION_WORD) for region in REGION_WORDS):
1382
+ return True
1383
+
1384
+ region = any(_typos(first.lower(), word) <= 1 for word in REGION_WORDS)
1385
+ return region and second is not None and _near_word(second, SOLUTION_WORD)
1386
+
1387
+
1388
+ def _near_word(word: str, target: str) -> bool:
1389
+ """`word` is at most one typo from `target`, or two in all caps with the same first letter."""
1390
+
1391
+ lower = word.lower()
1392
+ typos = _typos(lower, target)
1393
+
1394
+ return typos <= 1 or (typos == 2 and word.isupper() and lower[0] == target[0])
1395
+
1396
+
1397
+ def _typos(a: str, b: str) -> int:
1398
+ """Edits between `a` and `b`: letters inserted, deleted, replaced or swapped with the next.
1399
+
1400
+ This is the optimal string alignment distance.
1401
+ """
1402
+
1403
+ previous: list[int] = []
1404
+ row = list(range(len(b) + 1))
1405
+
1406
+ for i, char in enumerate(a, start=1):
1407
+ before, previous, row = previous, row, [i] + [0] * len(b)
1408
+
1409
+ for j, other in enumerate(b, start=1):
1410
+ row[j] = min(previous[j] + 1, row[j - 1] + 1, previous[j - 1] + (char != other))
1411
+
1412
+ if i > 1 and j > 1 and char == b[j - 2] and a[i - 2] == other:
1413
+ row[j] = min(row[j], before[j - 2] + 1)
1414
+
1415
+ return row[-1]
1416
+
1417
+
1418
+ def _region_lines(lines: list[str], markdown: frozenset[int]) -> set[int]:
1419
+ """Line numbers inside solution regions, markers included.
1420
+
1421
+ A region left open runs to the end of the file.
1422
+ """
1423
+
1424
+ inside: set[int] = set()
1425
+ start: int | None = None
1426
+
1427
+ for number, line in enumerate(lines, start=1):
1428
+ match line_marker(line, number in markdown)[0], start:
1429
+ case Marker.BEGIN, None:
1430
+ start = number
1431
+ case Marker.END, int():
1432
+ inside |= set(range(start, number + 1))
1433
+ start = None
1434
+
1435
+ if start is not None:
1436
+ inside |= set(range(start, len(lines) + 1))
1437
+
1438
+ return inside