Files
coursebank/src/export/typst.rs
T
alexmandClaude c8d6f4a5dd
Pipeline / check (pull_request) Successful in 12m21s
Pipeline / docs (pull_request) Skipped
Pipeline / nightly (pull_request) Skipped
Pipeline / release (pull_request) Skipped
Name Scienting as the copyright holder and contributor
Replace 'Scientific Computing Studio' in the source headers, the Cargo.toml
authors, and the LICENSE contributor line. pixi.toml still has the old
authors line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014zNf4shD4zaCKLucZWPYL9
2026-10-20 00:21:19 -04:00

476 lines
15 KiB
Rust

// SPDX-License-Identifier: Prosperity-3.0.0
// Copyright Scienting
// Source: https://git.scient.ing/education/coursebank
//! Rendering a printed exam with Typst.
//!
//! Typst rather than LaTeX because the toolchain is one binary with no package
//! manager, the error messages point at a line, and the compile is fast enough to
//! iterate on. `pixi run -e docs typst compile` turns the output of this module
//! into a PDF.
//!
//! ## What changed, and why
//!
//! This module used to build a document with `format!`. That made the position of
//! the points label a Rust change, put a `#grid` call in a match arm, and meant
//! the only way to move something on the page was to fork the crate. It also made
//! a generated exam a dead end: you could edit the output, but the next export
//! overwrote the edit.
//!
//! So the tool no longer writes documents. It loads a Typst file that you own,
//! finds the markers in it, and injects data:
//!
//! ```typst
//! // coursebank:begin questions
//! #render-question((number: 1, stem: [Sample.], options: ()))
//! // coursebank:end questions
//! ```
//!
//! `render-question` is defined in your template. What the payload contains is
//! governed by [`config::RenderConfig`]; where it lands and how it looks is
//! governed by the template. The default templates are compiled into the binary,
//! and `coursebank template dump` writes them into `templates/` so that
//! customizing means editing a file. See [`template`] for the marker syntax, the
//! slot list, and the lookup order.
//!
//! ## What is still enforced here
//!
//! Two invariants survived the rewrite, because both are the kind of mistake a
//! room full of students discovers simultaneously.
//!
//! **A form's key is derived from the same permutation as its paper.** Option order
//! comes from [`select::option_order`](crate::select::option_order) against the
//! form's recorded seed, never from anything stored, so every export of form B
//! agrees with every other. The paper, the key, and the answer sheet are all built
//! from one [`payload::Payload`].
//!
//! **The paper's payload does not contain the answer.** Not `correct: false`, not a
//! flag to check — the field is absent. See [`config::Reveal`]. A template cannot
//! leak what it was never given, and that stays true through every future edit of
//! the template by someone who has not read this comment.
pub mod config;
pub mod diagnostic;
pub mod payload;
pub mod template;
pub mod value;
use std::path::{Path, PathBuf};
pub use config::{
CONFIG_FILE, CONFIG_TEMPLATE, ConfigFile, ContentMode, Fields, LetterStyle, Overrides,
RenderConfig, Reveal, StimulusMode, Variant,
};
pub use payload::Payload;
pub use template::{Origin, Slot, Template};
pub use value::Value;
use crate::Layout;
use crate::assessment::{AssessmentFile, Form};
use crate::catalog::Catalog;
use crate::error::{Error, Result};
use crate::markup;
/// What to render.
#[derive(Debug, Clone)]
pub struct Options {
/// Which form.
pub form: Form,
/// Which document.
pub variant: Variant,
/// A template path that overrides the usual lookup. Takes precedence over
/// `template` in the render config.
pub template: Option<PathBuf>,
/// What to put in the payload, and how.
pub config: RenderConfig,
}
impl Default for Options {
fn default() -> Options {
Options {
form: Form {
id: "A".to_string(),
seed: 0,
shuffle_items: false,
shuffle_options: false,
},
variant: Variant::Exam,
template: None,
config: RenderConfig::for_variant(Variant::Exam),
}
}
}
impl Options {
/// Options for one variant, with that variant's default configuration.
///
/// # Arguments
///
/// * `variant` - which document.
/// * `form` - the form to render.
///
/// # Returns
///
/// The options.
pub fn new(variant: Variant, form: Form) -> Options {
Options {
form,
variant,
template: None,
config: RenderConfig::for_variant(variant),
}
}
/// The template path to use, preferring the explicit one.
fn template_path(&self) -> Option<&Path> {
self.template.as_deref().or(self.config.template.as_deref())
}
}
/// A finished document, with everything a caller needs to explain it.
#[derive(Debug, Clone)]
pub struct Rendered {
/// Which document this is.
pub variant: Variant,
/// Where the template came from.
pub origin: Origin,
/// Which slots the template declared and this render filled.
pub slots: Vec<Slot>,
/// The Typst source.
pub text: String,
/// The payload, kept so a caller can also write it as JSON without rebuilding.
pub payload: Payload,
/// Advisory problems: markup that will probably confuse the Typst compiler, and
/// a template that declared no markers at all.
pub warnings: Vec<String>,
}
/// Renders one document.
///
/// # Arguments
///
/// * `catalog` - the loaded course.
/// * `record` - the assessment record.
/// * `opts` - what to render.
///
/// # Returns
///
/// The finished document.
///
/// # Errors
///
/// Returns [`Error::Unresolved`] when a placement references a missing item,
/// [`Error::Io`] when an explicitly requested template cannot be read, and
/// [`Error::Invalid`] when the template's markers are malformed or every placement
/// is marked dropped.
pub fn render(catalog: &Catalog, record: &AssessmentFile, opts: &Options) -> Result<Rendered> {
let template = template::load(
&catalog.layout,
opts.variant,
Some(record.assessment.id.as_str()),
opts.template_path(),
)?;
let payload = payload::build(catalog, record, &opts.form, &opts.config)?;
if payload.questions.is_empty() {
return Err(Error::Invalid(vec![
"this assessment has no printable items; every placement is marked dropped".to_string(),
]));
}
// Only build what the template asked for. A paper template that never mentions
// `data` should not pay for a second copy of every stem.
let mut bodies = Vec::new();
if template.wants(Slot::Meta) {
bodies.push((Slot::Meta, payload::meta_body(&payload, &opts.config)));
}
if template.wants(Slot::Questions) {
bodies.push((
Slot::Questions,
payload::questions_body(&payload, &opts.config),
));
}
if template.wants(Slot::Data) {
bodies.push((Slot::Data, payload::data_body(&payload, &opts.config)));
}
let mut warnings = payload::check(&payload, &opts.config);
for (slot, body) in &bodies {
if markup::needs_chem_import(&template.source, body) {
warnings.push(format!(
"the `{}` slot carries a chemical formula, but the template {} does not import \
whalogen, so Typst will stop at `unknown variable: ce`; add `{}`",
slot.as_str(),
template.origin,
markup::CHEM_IMPORT
));
}
}
if template.is_inert() {
warnings.push(format!(
"the template {} declares no coursebank markers, so no questions were injected; add \
`// coursebank:questions` where they belong",
template.origin
));
}
Ok(Rendered {
variant: opts.variant,
origin: template.origin.clone(),
slots: template.slots(),
text: template.render(&bodies),
payload,
warnings,
})
}
/// Builds the payload without rendering a template.
///
/// For writing the questions out as JSON, which is what a hand-written Typst exam
/// that already calls `json("questions.json")` wants.
///
/// # Arguments
///
/// * `catalog` - the loaded course.
/// * `record` - the assessment record.
/// * `opts` - what to render; only the form and config are consulted.
///
/// # Returns
///
/// The payload.
///
/// # Errors
///
/// Returns [`Error::Unresolved`] when a placement references a missing item.
pub fn build_payload(
catalog: &Catalog,
record: &AssessmentFile,
opts: &Options,
) -> Result<Payload> {
payload::build(catalog, record, &opts.form, &opts.config)
}
/// The path a course's Typst configuration lives at.
///
/// # Arguments
///
/// * `layout` - the course layout.
pub fn config_path(layout: &Layout) -> PathBuf {
template::dir(layout).join(CONFIG_FILE)
}
/// Loads a course's Typst configuration.
///
/// # Arguments
///
/// * `layout` - the course layout.
///
/// # Returns
///
/// The parsed config file, or an empty one when `templates/typst.yaml` is absent.
/// Absence is not an error: a course that has never customized anything should
/// export without being told to write a config file first.
///
/// # Errors
///
/// Returns [`Error::Yaml`] when the file exists but does not parse.
pub fn load_config(layout: &Layout) -> Result<ConfigFile> {
let path = config_path(layout);
if path.is_file() {
crate::yaml::read(&path)
} else {
Ok(ConfigFile::default())
}
}
/// Renders the question paper.
///
/// Kept so existing callers keep working. New code should use [`render`], which
/// also reports which template was used and what it warned about.
///
/// # Arguments
///
/// * `catalog` - the loaded course.
/// * `record` - the assessment record.
/// * `opts` - rendering options; the variant is forced to [`Variant::Exam`].
///
/// # Returns
///
/// A complete Typst document.
///
/// # Errors
///
/// As [`render`].
pub fn exam(catalog: &Catalog, record: &AssessmentFile, opts: &Options) -> Result<String> {
render_variant(catalog, record, opts, Variant::Exam)
}
/// Renders the answer key.
///
/// # Arguments
///
/// * `catalog` - the loaded course.
/// * `record` - the assessment record.
/// * `opts` - rendering options; the variant is forced to [`Variant::Key`].
///
/// # Returns
///
/// A complete Typst document.
///
/// # Errors
///
/// As [`render`].
pub fn answer_key(catalog: &Catalog, record: &AssessmentFile, opts: &Options) -> Result<String> {
render_variant(catalog, record, opts, Variant::Key)
}
/// Renders a bubble sheet matching the form.
///
/// # Arguments
///
/// * `catalog` - the loaded course.
/// * `record` - the assessment record.
/// * `opts` - rendering options; the variant is forced to [`Variant::AnswerSheet`].
///
/// # Returns
///
/// A complete Typst document.
///
/// # Errors
///
/// As [`render`].
pub fn bubble_sheet(catalog: &Catalog, record: &AssessmentFile, opts: &Options) -> Result<String> {
render_variant(catalog, record, opts, Variant::AnswerSheet)
}
/// Renders one variant, substituting that variant's default config when the caller
/// passed the config for a different one.
fn render_variant(
catalog: &Catalog,
record: &AssessmentFile,
opts: &Options,
variant: Variant,
) -> Result<String> {
let mut opts = opts.clone();
if opts.variant != variant {
// The caller asked for a different document than the config describes, so
// the config's `reveal` almost certainly belongs to the other one. Taking
// the variant's own default is the safe reading, and the direction that
// matters is the paper: never inherit a key's `reveal`.
opts.config = RenderConfig::for_variant(variant);
opts.variant = variant;
}
Ok(render(catalog, record, &opts)?.text)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::assessment::Placement;
use crate::select;
#[test]
fn options_default_to_the_paper_and_withhold_the_key() {
let opts = Options::default();
assert_eq!(opts.variant, Variant::Exam);
assert!(!opts.config.reveal.shows_key());
}
#[test]
fn an_explicit_template_beats_the_config() {
let mut opts = Options::default();
opts.config.template = Some(PathBuf::from("from-config.typ"));
assert_eq!(opts.template_path(), Some(Path::new("from-config.typ")));
opts.template = Some(PathBuf::from("from-cli.typ"));
assert_eq!(opts.template_path(), Some(Path::new("from-cli.typ")));
}
#[test]
fn the_key_reports_letters_as_printed() {
// Shuffling must relabel the key: if the correct option moves to the third
// printed position, the key says C.
let form = Form {
id: "B".into(),
seed: 99,
shuffle_items: false,
shuffle_options: true,
};
let order = select::option_order(&form, "bank::q-1", 4);
let correct_source = 0usize;
let printed_position = order.iter().position(|i| *i == correct_source).unwrap();
let letter = LetterStyle::Upper.label(printed_position);
assert!(["A", "B", "C", "D"].contains(&letter.as_str()));
// And it is reproducible.
let again = select::option_order(&form, "bank::q-1", 4);
assert_eq!(order, again);
}
#[test]
fn dropped_items_are_not_printed() {
let record = AssessmentFile {
schema_version: "1.0".into(),
assessment: crate::assessment::Assessment {
id: "e1".into(),
title: "Exam 1".into(),
term: None,
kind: crate::assessment::Kind::Exam,
date: None,
platform: crate::assessment::Platform::Paper,
minutes_allowed: None,
attempts: None,
shuffle: None,
scoring_policy: None,
instructions: None,
notes: None,
},
blueprint: None,
forms: Vec::new(),
items: vec![
Placement {
number: 1,
item: "b::q-1".into(),
version: None,
stem_digest: None,
distractors: Vec::new(),
variant: None,
fingerprint: None,
points: None,
bonus: false,
key: vec!["A".into()],
level: None,
learning_targets: Vec::new(),
credit_overrides: Default::default(),
dropped: true,
dropped_as: None,
dropped_before_printing: false,
},
Placement {
number: 2,
item: "b::q-2".into(),
version: None,
stem_digest: None,
distractors: Vec::new(),
variant: None,
fingerprint: None,
points: None,
bonus: false,
key: vec!["B".into()],
level: None,
learning_targets: Vec::new(),
credit_overrides: Default::default(),
dropped: false,
dropped_as: None,
dropped_before_printing: false,
},
],
};
let printable: Vec<u32> = select::layout(&record, &Options::default().form)
.into_iter()
.filter(|p| p.was_printed())
.map(|p| p.number)
.collect();
assert_eq!(printable, vec![1, 2]);
}
}