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/transform.py ADDED
@@ -0,0 +1,769 @@
1
+ """Student notebook from the source notebook.
2
+
3
+ The transform edits the source as text, line by line, so everything it does not touch keeps
4
+ its exact layout and comments.
5
+ """
6
+
7
+ import ast
8
+ import io
9
+ import re
10
+ import tokenize
11
+ from collections.abc import Mapping, Sequence
12
+ from collections.abc import Set as AbstractSet
13
+ from enum import StrEnum
14
+ from pathlib import PurePosixPath
15
+
16
+ from mogs import __version__
17
+ from mogs.config import (
18
+ PACKAGE,
19
+ TESTS_FOLDER,
20
+ AssignmentConfig,
21
+ normalize_newlines,
22
+ set_dependency,
23
+ split_lines,
24
+ )
25
+ from mogs.source import (
26
+ BEGIN,
27
+ END,
28
+ SOLUTION,
29
+ Cell,
30
+ CellKind,
31
+ Marker,
32
+ Notebook,
33
+ SourceError,
34
+ answer_placeholders,
35
+ cell_names,
36
+ line_marker,
37
+ parse_notebook,
38
+ question_id,
39
+ )
40
+
41
+ EXPORT_BUTTON = "export_button"
42
+ MARKDOWN_PLACEHOLDER = "*Write your answer here.*"
43
+ DEFAULT_ALIAS = "mogs"
44
+ MARIMO_ALIAS = "mo"
45
+ # Solution lines that may appear in the student copy by chance: no letters, or a bare keyword.
46
+ TRIVIAL_LINE_RE = re.compile(r"[^A-Za-z]*|(?:pass|return|break|continue|else|try|finally):?")
47
+
48
+
49
+ class MarimoImport(StrEnum):
50
+ """Where the student copy gets `mo`, the name marimo is imported as."""
51
+
52
+ SETUP = "setup"
53
+ CELL = "cell"
54
+ MISSING = "missing"
55
+
56
+
57
+ # Replacement lines by 1-based source line number, each with the source line it comes from.
58
+ # A line not in the map is kept as it is.
59
+ type Edits = dict[int, list[tuple[int, str]]]
60
+
61
+
62
+ def pinned_requirement(cfg: AssignmentConfig) -> str:
63
+ """Requirement on this exact package version, with the `pdf` extra if a question is manual."""
64
+
65
+ extra = "[pdf]" if any(question.manual for question in cfg.questions.values()) else ""
66
+ return f"mogs{extra}=={__version__}"
67
+
68
+
69
+ def student_notebook(
70
+ src: str,
71
+ nb: Notebook,
72
+ cfg: AssignmentConfig,
73
+ tool_requirement: str,
74
+ *,
75
+ solutions: bool = False,
76
+ ) -> str:
77
+ r"""Turn a source notebook into the notebook students get.
78
+
79
+ - A `# BEGIN SOLUTION` ... `# END SOLUTION` region becomes its `# PROMPT: <code>` lines,
80
+ at the indent of `# BEGIN SOLUTION`, or `...` without them. In a Markdown cell the
81
+ markers are `<!-- BEGIN SOLUTION -->`, `<!-- END SOLUTION -->` and
82
+ `<!-- PROMPT: <text> -->`, and the placeholder is `*Write your answer here.*`.
83
+ - `x = rhs # SOLUTION` becomes `x = ...`, and the same goes for `x: T = rhs`,
84
+ `return rhs`, `yield rhs` and `yield from rhs`. Another statement ending in
85
+ `# SOLUTION` is dropped.
86
+ - `# HIDDEN` cells, public test cells, the `assignment(...)` cell and instructor cells
87
+ are dropped with the blank lines after them. The public tests go to their own files
88
+ instead (`public_test_files`).
89
+ - `grade("q1", points=<p>)` becomes `grade("q1", points=<p>, title=<title>,
90
+ test_file="tests/q1.py", uses=[<names>], hidden=<n>)`, where `uses` lists the student
91
+ names the public tests read, so marimo runs the cell again when one of them changes.
92
+ For a written question it becomes `grade("q2", points=<p>, title=<title>,
93
+ manual=True)`. The points and title come from `cfg`.
94
+ - A written question's Markdown cells are named for the export: its answers
95
+ `answer_<qid>`, `answer_<qid>_2`, ..., and its prompts `prompt_<qid>`, `prompt_<qid>_2`,
96
+ ... (`Notebook.written_cells`). The cells keep their order, so the PDF pairs each
97
+ answer with the prompts just before it.
98
+ - Export cells go after the last cell: a "Submit" note, the export button and the export
99
+ panel (`export_cells`).
100
+ - The header depends on `tool_requirement`.
101
+
102
+ With `solutions=True` it makes the solved copy instead: the same notebook, except that a
103
+ solution region keeps its code without the marker and `# PROMPT:` lines, and
104
+ `# SOLUTION` comments are removed with the code kept.
105
+
106
+ Args:
107
+ src: Source notebook text.
108
+ nb: The notebook parsed from `src`. It should pass `validate`.
109
+ cfg: Assignment config of the notebook.
110
+ tool_requirement: Requirement on this package for the header, such as
111
+ `pinned_requirement(cfg)`.
112
+ solutions: Keep the solutions.
113
+
114
+ Returns:
115
+ The student notebook, with `\n` line ends.
116
+
117
+ Raises:
118
+ ValueError: If `nb` was not parsed from `src`.
119
+ SourceError: If a `# SOLUTION` comment does not end a statement it can edit, a grade
120
+ call names an unknown question, solution markers do not pair up, the source
121
+ defines `export_button` itself, or the result is not valid Python.
122
+ ConfigError: If a header edit fails.
123
+ """
124
+
125
+ if normalize_newlines(src) != nb.src:
126
+ raise ValueError("`nb` was not parsed from `src`.")
127
+
128
+ if EXPORT_BUTTON in nb.student_names():
129
+ raise SourceError(
130
+ f"The source notebook defines `{EXPORT_BUTTON}`. The build adds the export cells "
131
+ "itself; remove yours."
132
+ )
133
+
134
+ text = _edited(nb, cfg, tool_requirement, solutions=solutions)
135
+ manual = [question.id for question in cfg.questions.values() if question.manual]
136
+ # The copy, not the source: the edits may have removed an import or a name. Placeholders
137
+ # come from the student copy, so the solved copy's answers do not count as untouched.
138
+ copy = parse_notebook(text)
139
+ student = parse_notebook(_edited(nb, cfg, tool_requirement)) if solutions else copy
140
+ placeholders = answer_placeholders(student, manual)
141
+ cells = export_cells(cfg, package_alias(copy), placeholders, marimo=marimo_import(copy))
142
+
143
+ return _append_cells(text, cells)
144
+
145
+
146
+ def solution_leaks(nb: Notebook, student: str) -> list[str]:
147
+ """Solution lines of `nb` that the student copy `student` still has.
148
+
149
+ A check after the transform, in case it misses a solution. The solution lines are those
150
+ inside solution regions, other than the markers and prompt lines, and the code before a
151
+ `# SOLUTION` comment. A line counts as leaked when `student` has it, after stripping
152
+ indents, and no line outside the solutions has the same text. Lines without letters and
153
+ bare keywords such as `pass` are skipped.
154
+
155
+ Returns:
156
+ One message per leaked line, naming its line in the source.
157
+ """
158
+
159
+ lines = split_lines(nb.src)
160
+ markdown = nb.markdown_lines()
161
+ solution: dict[int, str] = {}
162
+ prompts: set[str] = set()
163
+ start: int | None = None
164
+
165
+ for number, line in enumerate(lines, start=1):
166
+ marker, text = line_marker(line, number in markdown)
167
+
168
+ match marker, start:
169
+ case Marker.BEGIN, None:
170
+ start = number
171
+ case Marker.END, int():
172
+ start = None
173
+ case Marker.PROMPT, _:
174
+ prompts.add(text.strip())
175
+ case None, int():
176
+ solution[number] = line.strip()
177
+
178
+ for token in tokenize.generate_tokens(io.StringIO(nb.src).readline):
179
+ if token.type == tokenize.COMMENT and token.string.strip() == SOLUTION:
180
+ number = token.start[0]
181
+ solution[number] = lines[number - 1][: token.start[1]].strip()
182
+
183
+ public = prompts | {line.strip() for n, line in enumerate(lines, 1) if n not in solution}
184
+ student_lines = {line.strip() for line in split_lines(student)}
185
+
186
+ return [
187
+ f"line {number}: `{code}`"
188
+ for number, code in sorted(solution.items())
189
+ if code in student_lines and code not in public and not TRIVIAL_LINE_RE.fullmatch(code)
190
+ ]
191
+
192
+
193
+ def test_file(qid: str) -> PurePosixPath:
194
+ """Path of a question's public test file, relative to the student notebook."""
195
+
196
+ return PurePosixPath(TESTS_FOLDER, f"{qid}.py")
197
+
198
+
199
+ def public_test_files(nb: Notebook) -> dict[PurePosixPath, str]:
200
+ """The public test file of each auto-graded question, by `test_file` path.
201
+
202
+ A file holds the bodies of the question's public test cells, in file order. A question
203
+ without public tests gets a file with only its first comment line.
204
+
205
+ Args:
206
+ nb: The source notebook. It should pass `validate`.
207
+ """
208
+
209
+ tested = nb.tests_by_question()
210
+ qids = dict.fromkeys(
211
+ cell.grade_qid
212
+ for cell in nb.cells
213
+ if cell.grade_qid in tested and not cell.hidden and not cell.instructor
214
+ )
215
+ files = {}
216
+
217
+ for qid in qids:
218
+ bodies = [nb.cell_body_source(cell) for cell in _public_test_cells(nb, qid)]
219
+ head = f'# Public tests for {qid}, run by grade("{qid}") in the notebook.\n'
220
+ files[test_file(qid)] = "\n\n".join([head, *bodies])
221
+
222
+ return files
223
+
224
+
225
+ def _public_test_cells(nb: Notebook, qid: str) -> list[Cell]:
226
+ return [
227
+ cell
228
+ for cell in nb.cells
229
+ if cell.tests and not cell.hidden and question_id(cell.tests[0]) == qid
230
+ ]
231
+
232
+
233
+ def package_alias(nb: Notebook) -> str | None:
234
+ """The name the setup cell imports this package as, if it does.
235
+
236
+ Raises:
237
+ SourceError: If it does not, and `mogs`, the name the export cells would import it
238
+ as, is already taken.
239
+ """
240
+
241
+ for node in ast.parse(nb.setup_source()).body:
242
+ match node:
243
+ case ast.Import(names=names):
244
+ for alias in names:
245
+ if alias.name == PACKAGE:
246
+ return alias.asname or PACKAGE
247
+
248
+ if DEFAULT_ALIAS in nb.student_names() | cell_names(nb.setup_source())[0]:
249
+ raise SourceError(
250
+ f"The export cells need `{PACKAGE}`, and `{DEFAULT_ALIAS}` is taken. Add "
251
+ f"`import {PACKAGE} as <name>` to the setup cell."
252
+ )
253
+
254
+ return None
255
+
256
+
257
+ def marimo_import(nb: Notebook) -> MarimoImport:
258
+ """Which cell has `import marimo as mo`: the setup cell, a student cell, or none.
259
+
260
+ Raises:
261
+ SourceError: If none does, and `mo`, the name the export cells would import marimo as,
262
+ is already taken.
263
+ """
264
+
265
+ cells = [cell for cell in nb.cells if not cell.hidden and cell.kind is not CellKind.SETUP]
266
+ sources = [
267
+ (MarimoImport.SETUP, nb.setup_source()),
268
+ *((MarimoImport.CELL, nb.cell_body_source(cell)) for cell in cells),
269
+ ]
270
+ bound: set[str] = set()
271
+
272
+ for where, source in sources:
273
+ for node in ast.parse(source).body:
274
+ match node:
275
+ case ast.Import(names=names) if any(
276
+ alias.name == "marimo" and alias.asname == MARIMO_ALIAS for alias in names
277
+ ):
278
+ return where
279
+
280
+ bound |= cell_names(source)[0]
281
+
282
+ if MARIMO_ALIAS in bound:
283
+ raise SourceError(
284
+ f"The Submit note needs `import marimo as {MARIMO_ALIAS}`, and `{MARIMO_ALIAS}` is "
285
+ "taken. Add `import marimo as mo` to the setup cell."
286
+ )
287
+
288
+ return MarimoImport.MISSING
289
+
290
+
291
+ def export_cells(
292
+ cfg: AssignmentConfig,
293
+ alias: str | None,
294
+ placeholders: Mapping[str, str] | None = None,
295
+ *,
296
+ marimo: MarimoImport = MarimoImport.SETUP,
297
+ ) -> str:
298
+ """Cells that let the student export a submission: a note, the button and the panel.
299
+
300
+ The note is a cell with nothing but `mo.md(...)`. marimo renders such a cell when the
301
+ notebook opens, before anything runs, so the student sees how to show the button.
302
+
303
+ Args:
304
+ cfg: Assignment config.
305
+ alias: The setup cell's name for this package; `None` adds a cell that imports it as
306
+ `mogs`.
307
+ placeholders: The student copy's text per answer cell name, so the export can warn
308
+ about an answer left as it was.
309
+ marimo: Which cell has `import marimo as mo`; `MISSING` adds a cell that does.
310
+ """
311
+
312
+ manual = [question.id for question in cfg.questions.values() if question.manual]
313
+ titles = {qid: question.title for qid, question in cfg.questions.items()}
314
+ name = alias or DEFAULT_ALIAS
315
+ call = (
316
+ f"{name}.export({EXPORT_BUTTON}, name={python_literal(cfg.name)}, "
317
+ f"manual={python_literal(manual)}, titles={python_literal(titles)}, "
318
+ f"placeholders={python_literal(dict(placeholders or {}))})"
319
+ )
320
+ imports = [
321
+ *([("marimo", MARIMO_ALIAS)] if marimo is MarimoImport.MISSING else []),
322
+ *([] if alias is not None else [(PACKAGE, DEFAULT_ALIAS)]),
323
+ ]
324
+ names = [as_name for _, as_name in imports]
325
+ importer = (
326
+ "@app.cell(hide_code=True)\ndef _():\n"
327
+ + "".join(
328
+ f" import {module}\n" if module == as_name else f" import {module} as {as_name}\n"
329
+ for module, as_name in imports
330
+ )
331
+ + f"\n return {_returned(names)}\n\n\n"
332
+ if imports
333
+ else ""
334
+ )
335
+ # A cell takes the names other cells define as parameters; setup names are global.
336
+ note_args = "" if marimo is MarimoImport.SETUP else MARIMO_ALIAS
337
+ button_args = "" if alias is not None else DEFAULT_ALIAS
338
+ export_args = ", ".join(sorted({EXPORT_BUTTON, name} if alias is None else {EXPORT_BUTTON}))
339
+ contents = "your notebook and your written answers" if manual else "your notebook"
340
+
341
+ return (
342
+ importer
343
+ + f'''@app.cell(hide_code=True)
344
+ def _({note_args}):
345
+ {MARIMO_ALIAS}.md(r"""
346
+ ## Submit
347
+
348
+ Save the notebook, then click **Export submission** below. It runs the public tests on
349
+ the saved file and makes a zip of {contents}. Upload that zip to Gradescope.
350
+
351
+ No button below? Run the notebook first: **Run all stale cells**, or Ctrl+Shift+R
352
+ (Cmd+Shift+R on a Mac).
353
+ """)
354
+ return
355
+
356
+
357
+ @app.cell(hide_code=True)
358
+ def _({button_args}):
359
+ {EXPORT_BUTTON} = {name}.export_button()
360
+ {EXPORT_BUTTON}
361
+ return ({EXPORT_BUTTON},)
362
+
363
+
364
+ @app.cell(hide_code=True)
365
+ def _({export_args}):
366
+ {call}
367
+ return
368
+ '''
369
+ )
370
+
371
+
372
+ def _returned(names: Sequence[str]) -> str:
373
+ """A cell's return value for `names`, as marimo writes it: `(a,)` or `(a, b)`."""
374
+
375
+ return f"({names[0]},)" if len(names) == 1 else f"({', '.join(names)})"
376
+
377
+
378
+ type Literal = str | Sequence[str] | Mapping[str, str]
379
+
380
+
381
+ def python_literal(value: Literal) -> str:
382
+ """Python source for a string, or a list or dict of strings, quoted the way ruff formats it.
383
+
384
+ Strings get double quotes, unless they hold `"` and no `'`. Characters that are not
385
+ printable are escaped as `repr` escapes them, so any string reads back the same.
386
+ """
387
+
388
+ match value:
389
+ case str():
390
+ return _string_literal(value)
391
+ case Mapping():
392
+ items = (f"{_string_literal(k)}: {_string_literal(v)}" for k, v in value.items())
393
+ return "{" + ", ".join(items) + "}"
394
+ case _:
395
+ return "[" + ", ".join(_string_literal(item) for item in value) + "]"
396
+
397
+
398
+ def _string_literal(text: str) -> str:
399
+ if '"' in text and "'" not in text:
400
+ return repr(text)
401
+
402
+ escaped = []
403
+
404
+ for char in text:
405
+ match char:
406
+ case "\\":
407
+ escaped.append("\\\\")
408
+ case '"':
409
+ escaped.append('\\"')
410
+ case _ if char.isprintable():
411
+ escaped.append(char)
412
+ case _:
413
+ escaped.append(repr(char)[1:-1])
414
+
415
+ return '"' + "".join(escaped) + '"'
416
+
417
+
418
+ def _edited(
419
+ nb: Notebook, cfg: AssignmentConfig, tool_requirement: str, *, solutions: bool = False
420
+ ) -> str:
421
+ """`student_notebook` without the export cells."""
422
+
423
+ lines = split_lines(nb.src)
424
+ edits: Edits = {}
425
+
426
+ for cell in nb.cells:
427
+ if cell.hidden or cell.tests or cell.assignment or cell.instructor:
428
+ _drop_cell(edits, lines, cell)
429
+
430
+ regions = _solution_regions(edits, lines, solutions, nb.markdown_lines())
431
+ _inline_solutions(edits, lines, nb.src, solutions, regions)
432
+
433
+ for cell in nb.cells:
434
+ if cell.grade_qid is not None and not cell.hidden and not cell.instructor:
435
+ _rewrite_grade(edits, lines, nb, cell, cfg)
436
+
437
+ for question in cfg.questions.values():
438
+ if question.manual:
439
+ _name_written_cells(edits, lines, nb, question.id)
440
+
441
+ copied = [
442
+ pair
443
+ for number, line in enumerate(lines, start=1)
444
+ for pair in edits.get(number, [(number, line)])
445
+ ]
446
+ text = "\n".join(new for _, new in copied)
447
+ # Parsed before the header edit, which can change the line count. The header is
448
+ # comments only, so it does not change whether the code parses.
449
+ _check_python(text, [number for number, _ in copied], lines)
450
+ text = set_dependency(text, tool_requirement)
451
+
452
+ if not solutions and (leaks := solution_leaks(nb, text)):
453
+ raise SourceError(
454
+ "Solution code would reach the student notebook. Check the solution markers "
455
+ "around these lines:\n" + "\n".join(leaks)
456
+ )
457
+
458
+ return text
459
+
460
+
461
+ def _append_cells(text: str, cells: str) -> str:
462
+ """Insert `cells` after the last cell of `text`, or at its end when it has none."""
463
+
464
+ lines = split_lines(text)
465
+ nb = parse_notebook(text)
466
+ end = nb.cells[-1].end if nb.cells else len(lines)
467
+ head = "\n".join(lines[:end]).rstrip("\n")
468
+ tail = "\n".join(lines[end:]).lstrip("\n")
469
+
470
+ return f"{head}\n\n\n{cells}" + (f"\n\n{tail}" if tail else "")
471
+
472
+
473
+ def _check_python(text: str, origin: list[int], lines: list[str]) -> None:
474
+ """Raise if the student copy `text` does not parse, naming the source line.
475
+
476
+ Args:
477
+ text: The student copy.
478
+ origin: For each line of `text`, the number of the source line it came from.
479
+ lines: The source lines.
480
+
481
+ Raises:
482
+ SourceError: If `text` is not valid Python.
483
+ """
484
+
485
+ def source(copy_line: int) -> int:
486
+ return origin[min(max(copy_line, 1), len(origin)) - 1]
487
+
488
+ try:
489
+ ast.parse(text)
490
+ except SyntaxError as e:
491
+ # Text that fails to parse has at least one line, so `origin` is not empty.
492
+ number = source(e.lineno or len(origin))
493
+ # The message can name other lines of the copy, as in "after function
494
+ # definition on line 20".
495
+ msg = re.sub(r"\bline (\d+)", lambda m: f"line {source(int(m[1]))}", e.msg)
496
+ code = lines[number - 1].strip()
497
+
498
+ raise SourceError(
499
+ f"The student notebook is not valid Python at source line {number} (`{code}`): "
500
+ f"{msg}. Check the `{SOLUTION}` and `{BEGIN}` edits around that line."
501
+ ) from e
502
+
503
+
504
+ def _drop_cell(edits: Edits, lines: list[str], cell: Cell) -> None:
505
+ """Drop a cell and the blank lines after it."""
506
+
507
+ end = cell.end
508
+ while end < len(lines) and not lines[end].strip():
509
+ end += 1
510
+
511
+ for number in range(cell.start, end + 1):
512
+ edits[number] = []
513
+
514
+
515
+ def _solution_regions(
516
+ edits: Edits, lines: list[str], keep: bool, markdown: AbstractSet[int]
517
+ ) -> set[int]:
518
+ """Replace each solution region with its prompt lines, or a placeholder.
519
+
520
+ Lines in `markdown` belong to Markdown cells, whose markers are HTML comments. There the
521
+ placeholder is `MARKDOWN_PLACEHOLDER`; elsewhere it is `...`. With `keep`, drop only
522
+ the marker and prompt lines.
523
+
524
+ Returns:
525
+ The numbers of the lines inside the regions, markers excluded.
526
+ """
527
+
528
+ start: int | None = None
529
+ indent = ""
530
+ prompt: list[str] = []
531
+ prompts: list[int] = []
532
+ inside: set[int] = set()
533
+
534
+ for number, line in enumerate(lines, start=1):
535
+ marker, text = line_marker(line, number in markdown)
536
+
537
+ match marker, start:
538
+ case Marker.BEGIN, None:
539
+ start, indent, prompt = number, line[: len(line) - len(line.lstrip())], []
540
+ prompts = []
541
+ case Marker.END, int() if keep:
542
+ inside.update(range(start + 1, number))
543
+ if start not in edits:
544
+ for marker in (start, *prompts, number):
545
+ _replace(edits, marker, marker, [])
546
+ start = None
547
+ case Marker.END, int():
548
+ inside.update(range(start + 1, number))
549
+ if start not in edits:
550
+ default = MARKDOWN_PLACEHOLDER if start in markdown else "..."
551
+ stub = [indent + code if code else "" for code in prompt or [default]]
552
+ _replace(edits, start, number, stub, prompts or None)
553
+ start = None
554
+ case Marker.BEGIN | Marker.END, _:
555
+ raise SourceError(f"line {number}: `{line.strip()}` does not pair up.")
556
+ case Marker.PROMPT, int():
557
+ prompt.append(text)
558
+ prompts.append(number)
559
+
560
+ if start is not None:
561
+ raise SourceError(f"line {start}: `{BEGIN}` without a matching `{END}`.")
562
+
563
+ return inside
564
+
565
+
566
+ def _inline_solutions(
567
+ edits: Edits, lines: list[str], src: str, keep: bool, regions: set[int]
568
+ ) -> None:
569
+ """Blank out the value of a statement marked `# SOLUTION`, or drop the statement.
570
+
571
+ `x = rhs`, `x: T = rhs`, `return rhs`, `yield rhs` and `yield from rhs` keep everything
572
+ but the value, which becomes `...`. Any other simple statement is dropped.
573
+
574
+ With `keep`, only the comments go. A comment inside a solution region (`regions`) is not
575
+ checked, since the student copy drops the whole region; with `keep` it is removed, and so
576
+ is its line when nothing else is on it. Both copies accept the same sources.
577
+ """
578
+
579
+ tree = ast.parse(src)
580
+ comments = [
581
+ token
582
+ for token in tokenize.generate_tokens(io.StringIO(src).readline)
583
+ if token.type == tokenize.COMMENT and token.string.strip() == SOLUTION
584
+ ]
585
+
586
+ for comment in comments:
587
+ number = comment.start[0]
588
+ if number in edits:
589
+ continue
590
+
591
+ if number in regions:
592
+ code = lines[number - 1][: comment.start[1]].rstrip()
593
+ _replace(edits, number, number, [code] if code else [])
594
+ continue
595
+
596
+ ending = [
597
+ node
598
+ for node in ast.walk(tree)
599
+ if isinstance(node, ast.stmt) and node.end_lineno == number
600
+ ]
601
+ if not ending:
602
+ raise SourceError(f"line {number}: `{SOLUTION}` must end a statement.")
603
+ stmt = max(ending, key=lambda node: (node.lineno, node.col_offset))
604
+
605
+ # The whole statement is rewritten from its targets, since brackets around the
606
+ # value are not part of the value's AST node.
607
+ line = lines[stmt.lineno - 1]
608
+ before = line[: _char_col(line, stmt.col_offset)]
609
+ last = lines[number - 1]
610
+ uncommented = [last[: comment.start[1]].rstrip()]
611
+
612
+ match stmt:
613
+ case ast.Assign() if keep:
614
+ _replace(edits, number, number, uncommented)
615
+ case ast.Assign(targets=targets):
616
+ names = " = ".join(_segment(src, target) for target in targets)
617
+ _replace(edits, stmt.lineno, number, [f"{before}{names} = ..."])
618
+ case ast.AnnAssign(value=ast.expr()) if keep:
619
+ _replace(edits, number, number, uncommented)
620
+ case ast.AnnAssign(target=target, annotation=annotation, value=ast.expr()):
621
+ names = f"{_segment(src, target)}: {_segment(src, annotation)}"
622
+ _replace(edits, stmt.lineno, number, [f"{before}{names} = ..."])
623
+ case (
624
+ ast.Return(value=ast.expr())
625
+ | ast.Expr(value=ast.Yield(value=ast.expr()) | ast.YieldFrom())
626
+ ) if keep:
627
+ _replace(edits, number, number, uncommented)
628
+ case ast.Return(value=ast.expr()):
629
+ _replace(edits, stmt.lineno, number, [f"{before}return ..."])
630
+ case ast.Expr(value=ast.Yield(value=ast.expr())):
631
+ _replace(edits, stmt.lineno, number, [f"{before}yield ..."])
632
+ case ast.Expr(value=ast.YieldFrom()):
633
+ _replace(edits, stmt.lineno, number, [f"{before}yield from ..."])
634
+ case (
635
+ ast.FunctionDef()
636
+ | ast.AsyncFunctionDef()
637
+ | ast.ClassDef()
638
+ | ast.If()
639
+ | ast.For()
640
+ | ast.AsyncFor()
641
+ | ast.While()
642
+ | ast.With()
643
+ | ast.AsyncWith()
644
+ | ast.Try()
645
+ | ast.TryStar()
646
+ | ast.Match()
647
+ ):
648
+ raise SourceError(
649
+ f"line {number}: `{SOLUTION}` must end a simple statement, not the end of "
650
+ "a block."
651
+ )
652
+ case _:
653
+ if before.strip():
654
+ raise SourceError(
655
+ f"line {number}: `{SOLUTION}` statement must start its own line."
656
+ )
657
+ _replace(
658
+ edits, number if keep else stmt.lineno, number, uncommented if keep else []
659
+ )
660
+
661
+
662
+ def _rewrite_grade(
663
+ edits: Edits, lines: list[str], nb: Notebook, cell: Cell, cfg: AssignmentConfig
664
+ ) -> None:
665
+ """Pass points and title, and the test file, its names and hidden-test count, or `manual`."""
666
+
667
+ call = nb.grade_call(cell)
668
+ qid = cell.grade_qid
669
+ question = cfg.questions.get(qid) if qid is not None else None
670
+ if qid is None or question is None:
671
+ raise SourceError(f"line {call.lineno}: grade() names an unknown question {qid!r}.")
672
+
673
+ _, hidden = nb.tests_by_question().get(qid, ([], []))
674
+ students = nb.student_names()
675
+ uses = sorted(
676
+ {
677
+ name
678
+ for test_cell in _public_test_cells(nb, qid)
679
+ for name in cell_names(nb.cell_body_source(test_cell))[1] & students
680
+ }
681
+ )
682
+ points = question.points
683
+ shown = str(int(points)) if points.is_integer() else repr(points)
684
+ func = ast.get_source_segment(nb.src, call.func)
685
+ head = f"{func}({python_literal(qid)}, points={shown}, title={python_literal(question.title)}"
686
+ new_call = (
687
+ f"{head}, manual=True)"
688
+ if question.manual
689
+ else f"{head}, test_file={python_literal(str(test_file(qid)))}, "
690
+ f"uses=[{', '.join(uses)}], hidden={len(hidden)})"
691
+ )
692
+
693
+ first = lines[call.lineno - 1]
694
+ last = lines[_end_line(call) - 1]
695
+ start = _char_col(first, call.col_offset)
696
+ end = _char_col(last, _end_col(call))
697
+ _replace(edits, call.lineno, _end_line(call), [first[:start] + new_call + last[end:]])
698
+
699
+
700
+ def _name_written_cells(edits: Edits, lines: list[str], nb: Notebook, qid: str) -> None:
701
+ """Name a written question's prompt and answer cells, so the export can find them."""
702
+
703
+ prompts, answers = nb.written_cells(qid)
704
+
705
+ for prefix, cells in (("prompt", prompts), ("answer", answers)):
706
+ for index, cell in enumerate(cells, start=1):
707
+ name = f"{prefix}_{qid}" if index == 1 else f"{prefix}_{qid}_{index}"
708
+ old = f"def {cell.name}("
709
+ number = next((n for n in range(cell.start, cell.end + 1) if old in lines[n - 1]), None)
710
+
711
+ if number is None:
712
+ raise SourceError(f"line {cell.start}: cannot name the cell `{name}`.")
713
+
714
+ _replace(edits, number, number, [lines[number - 1].replace(old, f"def {name}(", 1)])
715
+
716
+
717
+ def _segment(src: str, node: ast.expr) -> str:
718
+ """Source text of an expression."""
719
+
720
+ match ast.get_source_segment(src, node):
721
+ case str() as text:
722
+ return text
723
+ case None:
724
+ raise SourceError(f"line {node.lineno}: no source for expression.")
725
+
726
+
727
+ def _replace(
728
+ edits: Edits, first: int, last: int, new: list[str], origins: list[int] | None = None
729
+ ) -> None:
730
+ """Replace lines `first` to `last` (inclusive) with `new`.
731
+
732
+ `origins` gives the source line of each string in `new`. Without it, each line of `new`
733
+ (a string can hold several) maps to the next source line from `first`, stopping at `last`.
734
+ """
735
+
736
+ taken = [number for number in range(first, last + 1) if number in edits]
737
+ if taken:
738
+ raise SourceError(f"line {taken[0]}: two student-copy edits touch this line.")
739
+
740
+ if origins is None:
741
+ parts = "\n".join(new).split("\n") if new else []
742
+ edits[first] = [(min(first + index, last), part) for index, part in enumerate(parts)]
743
+ else:
744
+ edits[first] = list(zip(origins, new, strict=True))
745
+
746
+ for number in range(first + 1, last + 1):
747
+ edits[number] = []
748
+
749
+
750
+ def _char_col(line: str, byte_col: int) -> int:
751
+ """Character offset in `line` of an AST column, which counts UTF-8 bytes."""
752
+
753
+ return len(line.encode()[:byte_col].decode())
754
+
755
+
756
+ def _end_line(node: ast.expr) -> int:
757
+ match node.end_lineno:
758
+ case int() as end:
759
+ return end
760
+ case None:
761
+ raise SourceError(f"line {node.lineno}: expression has no end line.")
762
+
763
+
764
+ def _end_col(node: ast.expr) -> int:
765
+ match node.end_col_offset:
766
+ case int() as end:
767
+ return end
768
+ case None:
769
+ raise SourceError(f"line {node.lineno}: expression has no end column.")