Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/tests/runs.rs

15.3 KiB, 1 run

created by r1870400018:62391, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! A caption, a footnote and a heading set a reference, a citation, a footnote and an index marker as a
2//! paragraph sets them, since every place a run is set answers for what the run asks for: nothing is
3//! dropped, and a citation is never set as its raw key when the bibliography holds it. Driven through the
4//! `compile` functions the wasm `DaimondTypst` calls, with the source map installed as it installs one.
5
6use oxedyne_fe2o3_austenite::compile::{
7 self,
8 DiagnosticKind,
9 Rendered,
10 Report,
11};
12use oxedyne_fe2o3_austenite::fonts;
13use oxedyne_fe2o3_austenite::ir::DrawOp;
14use oxedyne_fe2o3_austenite::ledger::AnchorKind;
15use oxedyne_fe2o3_austenite::page::PlacedKind;
16use oxedyne_fe2o3_austenite::vfs;
17
18use oxedyne_fe2o3_core::prelude::*;
19use oxedyne_fe2o3_graphics::colour::Rgba;
20use oxedyne_fe2o3_graphics::pixmap::Pixmap;
21
22use std::collections::HashMap;
23use std::path::{
24 Path,
25 PathBuf,
26};
27use std::sync::{
28 Arc,
29 Mutex,
30 MutexGuard,
31};
32
33// The source map is a process global, so the tests that install one take turns.
34static VFS_TURN: Mutex<()> = Mutex::new(());
35
36fn turn() -> MutexGuard<'static, ()> {
37 VFS_TURN.lock().unwrap_or_else(|p| p.into_inner())
38}
39
40const MAIN: &str = "/proj/main.typ";
41const BIB: &str = "@article{smith2020, author = {Smith, John}, title = {A Study}, journal = {J}, year = {2020}}\n";
42
43/// Installs `files`, compiles `MAIN` as the wasm surface does, and returns the render and its report,
44/// clearing the map either way.
45fn compile_of(files: &[(&str, &str)]) -> Outcome<(Rendered, Report)> {
46 let bytes: Vec<(&str, &[u8])> = files.iter().map(|(p, b)| (*p, b.as_bytes())).collect();
47 compile_bytes(&bytes)
48}
49
50/// As [`compile_of`], for files given as bytes.
51fn compile_bytes(files: &[(&str, &[u8])]) -> Outcome<(Rendered, Report)> {
52 let mut map: HashMap<PathBuf, Vec<u8>> = HashMap::new();
53 for (p, b) in files {
54 map.insert(PathBuf::from(p), b.to_vec());
55 }
56 res!(vfs::install(map));
57 let main = PathBuf::from(MAIN);
58 let fonts = Arc::new(res!(fonts::libertinus()));
59 let run = || -> Outcome<(Rendered, Report)> {
60 let assembled = res!(compile::assemble(&main, || Ok(fonts.clone())));
61 let empty = assembled.blocks.is_empty();
62 let rendered = res!(compile::author_and_run(assembled));
63 let report = Report::new(rendered.out.pages.len(), &rendered.refusals, empty);
64 Ok((rendered, report))
65 };
66 let out = run();
67 res!(vfs::clear());
68 out
69}
70
71/// Every word set on every page, in placing order, one space between words.
72fn words(rendered: &Rendered) -> String {
73 let mut out = Vec::new();
74 for page in &rendered.out.pages {
75 for placed in &page.frame.placed {
76 if let PlacedKind::Text(t) = &placed.kind {
77 out.push(t.source().to_string());
78 }
79 }
80 }
81 out.join(" ").split_whitespace().collect::<Vec<_>>().join(" ")
82}
83
84/// The body, a caption, a footnote and a heading each set a reference as the words its label resolves to
85/// and a citation as its author-year text; a footnote in a caption and one in a footnote are set at the
86/// page foot, numbered in order; an index marker in a caption is recorded; and nothing is reported.
87#[test]
88fn captions_footnotes_and_headings_set_what_a_paragraph_sets() -> Outcome<()> {
89 let _turn = turn();
90 let src = "= Intro <intro>\n\nBody sees @intro and #cite(<smith2020>).\n\n\
91 == Sub about @intro #cite(<smith2020>)#footnote[Headnote words.]\n\n\
92 #figure(table(columns: 1, [Cell]), caption: [Caption sees @intro and #cite(<smith2020>)#footnote[Capnote words.]#index[Captioned].])\n\n\
93 Para.#footnote[Footnote sees @intro and #cite(<smith2020>)#footnote[Nested words.].]\n";
94 let (rendered, report) = res!(compile_of(&[(MAIN, src), ("/proj/refs.bib", BIB)]));
95 let text = words(&rendered);
96 assert!(report.diagnostics.is_empty(), "nothing is reported: {:?}", report.diagnostics);
97 assert!(!text.contains("smith2020"), "no citation is set as its key: {}", text);
98 for want in ["Caption sees Chapter 1 and (Smith 2020)", "Footnote sees Chapter 1 and (Smith 2020)",
99 "about Chapter 1 (Smith 2020)", "Headnote words.", "Capnote words.", "Nested words."]
100 {
101 assert!(text.contains(want), "{:?} is set: {}", want, text);
102 }
103 let indexed = rendered.out.ledger.anchors()
104 .any(|a| a.id.kind == AnchorKind::IndexEntry && a.id.key.contains("Captioned"));
105 assert!(indexed, "the caption's index marker is recorded");
106 Ok(())
107}
108
109/// A citation in a caption or a heading whose key the bibliography lacks is set as its keys and reported
110/// where it is written, as one in a paragraph is; a reference in a footnote to a label nothing carries is
111/// reported too. Before, both were set as raw keys or dropped with nothing said.
112#[test]
113fn what_a_caption_footnote_or_heading_cannot_resolve_is_reported() -> Outcome<()> {
114 let _turn = turn();
115 let src = "= Intro\n\n== Sub #cite(<nobody>)\n\n\
116 #figure(table(columns: 1, [Cell]), caption: [Cites #cite(<nokey>).])\n\n\
117 Para.#footnote[See @nolabel.]\n";
118 let (_, report) = res!(compile_of(&[(MAIN, src), ("/proj/refs.bib", BIB)]));
119 let lines: Vec<(usize, &str)> = report.diagnostics.iter().map(|d| (d.line, d.message.as_str())).collect();
120 assert_eq!(lines.len(), 3, "{:?}", lines);
121 assert!(lines[0].0 == 3 && lines[0].1.starts_with("#cite(<nobody>) names a key the bibliography does not hold"), "{:?}", lines);
122 assert!(lines[1].0 == 5 && lines[1].1.starts_with("#cite(<nokey>) names a key"), "{:?}", lines);
123 assert!(lines[2].0 == 7 && lines[2].1.starts_with("@nolabel names no label"), "{:?}", lines);
124 Ok(())
125}
126
127/// A callout's body is set through the whole block walk: a heading, a figure with its image, a display
128/// equation, a plain image and its prose are all set, and an image the project lacks is reported where it
129/// stands, so strict refuses the document -- where the callout once set its prose alone and dropped the rest
130/// with nothing said.
131#[test]
132fn a_callout_body_sets_every_block_it_holds() -> Outcome<()> {
133 let _turn = turn();
134 let png = res!(res!(Pixmap::filled(8, 8, Rgba::opaque(200, 0, 0))).to_png());
135 let src = "= Top\n\n#styled-box[\n= Boxed Heading\n\n#figure(image(\"pic.png\", width: 2cm), caption: [Boxed figure.])\n\n\
136 $ x^2 + y^2 $\n\n#image(\"gone-in-box.png\")\n\nBoxed words.\n]\n\nAfter.\n";
137 let (rendered, report) = res!(compile_bytes(&[(MAIN, src.as_bytes()), ("/proj/pic.png", &png)]));
138 let text = words(&rendered);
139 for want in ["Boxed Heading", "Figure 1: Boxed figure.", "Boxed words.", "After."] {
140 assert!(text.contains(want), "{:?} is set: {}", want, text);
141 }
142 assert!(text.contains('\u{1d465}') || text.contains(" x "), "the equation is set: {}", text);
143 let drawn = rendered.out.pages.iter().flat_map(|p| p.frame.placed.iter()).any(|pl| match &pl.kind {
144 PlacedKind::Graphic(g) => g.ops.iter().any(|op| matches!(op, DrawOp::Image { .. })),
145 _ => false,
146 });
147 assert!(drawn, "the boxed figure's image is drawn");
148 let missing: Vec<_> = report.diagnostics.iter().filter(|d| d.message.contains("gone-in-box.png")).collect();
149 assert_eq!(missing.len(), 1, "{:?}", report.diagnostics);
150 assert_eq!(missing[0].kind, DiagnosticKind::MissingFile, "{}", missing[0]);
151 assert!(report.strict_failure(Path::new(MAIN)).is_some(), "strict refuses the missing image");
152 Ok(())
153}
154
155/// A floating `#place` inside a callout, which a callout laid out whole has no band to float, has its float
156/// refused where the reader builds the callout, and its body is set where it stands with the rest.
157#[test]
158fn a_float_inside_a_callout_is_refused() -> Outcome<()> {
159 let _turn = turn();
160 let src = "= Top\n\n#styled-box[\nBefore.\n\n#place(top, float: true)[Floated words.]\n\nAfter.\n]\n";
161 let (rendered, report) = res!(compile_of(&[(MAIN, src)]));
162 let text = words(&rendered);
163 assert!(text.contains("Before. Floated words. After."), "{}", text);
164 let names: Vec<&str> = report.diagnostics.iter().map(|d| d.message.as_str()).collect();
165 assert_eq!(names, ["#place float inside a container is refused, so its body is set where it stands"]);
166 Ok(())
167}
168
169const IN_PLACE: &str = "#figure placement inside a container is refused, so the figure is set where it stands";
170
171/// The position of each of `words` in `text`, in order, failing unless each follows the one before.
172fn in_order(text: &str, words: &[&str]) -> Outcome<()> {
173 let mut from = 0usize;
174 for w in words {
175 match text[from..].find(w) {
176 Some(at) => from += at + w.len(),
177 None => return Err(err!("{:?} does not follow {:?} in: {}", w, &text[..from], text; Test, Missing)),
178 }
179 }
180 Ok(())
181}
182
183/// A floating figure or table in a callout, and a floating figure in a floating `#place`, are set where they
184/// stand, each placement refused at its figure, where the compile once ended with no PDF. Strict refuses them.
185#[test]
186fn a_floating_figure_inside_a_container_is_set_where_it_stands() -> Outcome<()> {
187 let _turn = turn();
188 let png = res!(res!(Pixmap::filled(8, 8, Rgba::opaque(200, 0, 0))).to_png());
189 let src = "= Top\n\n#styled-box[\nBefore.\n\n\
190 #figure(image(\"pic.png\", width: 2cm), caption: [Boxed float.], placement: top)\n\n\
191 #figure(table(columns: 1, [Cell]), caption: [Boxed table.], placement: auto)\n\nAfter.\n]\n\n\
192 #place(top, float: true)[\nPlaced.\n\n#figure(table(columns: 1, [Inner]), caption: [Placed table.], placement: bottom)\n]\n\n\
193 Body.\n";
194 let (rendered, report) = res!(compile_bytes(&[(MAIN, src.as_bytes()), ("/proj/pic.png", &png)]));
195 let text = words(&rendered);
196 res!(in_order(&text, &["Before.", "Boxed float.", "Boxed table.", "After."]));
197 res!(in_order(&text, &["Placed.", "Inner", "Placed table."]));
198 let drawn = rendered.out.pages.iter().flat_map(|p| p.frame.placed.iter()).any(|pl| match &pl.kind {
199 PlacedKind::Graphic(g) => g.ops.iter().any(|op| matches!(op, DrawOp::Image { .. })),
200 _ => false,
201 });
202 assert!(drawn, "the boxed figure's image is drawn");
203 let names: Vec<&str> = report.diagnostics.iter().map(|d| d.message.as_str()).collect();
204 assert_eq!(names, [IN_PLACE, IN_PLACE, IN_PLACE]);
205 assert!(report.diagnostics.iter().all(|d| d.kind == DiagnosticKind::Unsupported), "{:?}", report.diagnostics);
206 assert!(report.strict_failure(Path::new(MAIN)).is_some(), "strict refuses a placement not honoured");
207 Ok(())
208}
209
210/// A floating callout in a callout is set where it stands, its float refused, and a column change in a
211/// `#columns` body inside a callout is refused, its body set in the callout's one column: neither ends the
212/// compile.
213#[test]
214fn a_floating_callout_or_a_column_change_inside_a_callout_is_set_in_place() -> Outcome<()> {
215 let _turn = turn();
216 let src = "#let aside-box(title: none, float: true, body) = {\n\
217 \tlet inner = box(width: 100%, inset: 1em, fill: luma(240), [#text(size: 0.85em)[#body]])\n\
218 \tif float { figure(placement: auto, inner) } else { inner }\n}\n\n\
219 = Top\n\n#styled-box[\nBefore.\n\n#aside-box[Aside words.]\n\n\
220 #columns(2)[\n#set columns(gutter: 8pt)\nColumned words.\n]\n\nAfter.\n]\n";
221 let (rendered, report) = res!(compile_of(&[(MAIN, src)]));
222 let text = words(&rendered);
223 res!(in_order(&text, &["Before.", "Aside words.", "Columned words.", "After."]));
224 let names: Vec<&str> = report.diagnostics.iter().map(|d| d.message.as_str()).collect();
225 assert_eq!(names, [
226 "skipped #let (fixed-point)",
227 "skipped #columns (unsupported)",
228 "callout float inside a container is refused, so the callout is set where it stands",
229 "column change inside a container is refused, so its body is set in the container's one column",
230 ]);
231 Ok(())
232}
233
234/// The first 1-based page whose runs, joined, hold `word`, or `None` when no page does. A word may be set
235/// as several runs, parted at a kerning pair or a ligature, so the runs are joined with nothing between.
236fn page_of(rendered: &Rendered, word: &str) -> Option<usize> {
237 rendered.out.pages.iter().position(|page| {
238 let joined: String = page.frame.placed.iter().filter_map(|placed| match &placed.kind {
239 PlacedKind::Text(t) => Some(t.source()),
240 _ => None,
241 }).collect();
242 joined.contains(word)
243 }).map(|i| i + 1)
244}
245
246const ASIDE: &str = "#let aside-box(title: none, float: true, body) = {\n\
247 \tlet inner = box(width: 100%, inset: 1em, fill: luma(240), [#text(size: 0.85em)[#body]])\n\
248 \tif float { figure(placement: auto, inner) } else { inner }\n}\n\n";
249
250/// A footnote in a float -- a floating figure's caption, a floating `#place`'s body, a floating callout's
251/// body -- is set at the foot of the page the float lands on, where it was answered "set" and laid nowhere;
252/// a float deferred to a later page takes its note there, in one column or two.
253#[test]
254fn a_float_sets_its_footnotes_on_the_page_it_lands_on() -> Outcome<()> {
255 let _turn = turn();
256 let filler: String = (1..=40).map(|n| fmt!("Filler paragraph {} of the page{}.\n\n", n,
257 if n == 40 { " Fortieth" } else { "" })).collect();
258 // A float too tall for any page that already carries a few paragraphs, so it waits for the next.
259 let rows: String = (1..=34).map(|n| fmt!("[Row {}], ", n)).collect();
260 let one = fmt!("{}= Top\n\n\
261 #figure(table(columns: 1, [Cell]), caption: [Alphafloat.#footnote[Alphanote.]], placement: top)\n\n\
262 #place(bottom, float: true)[Betaplace.#footnote[Betanote.]]\n\n\
263 #aside-box[Gammaaside.#footnote[Gammanote.]]\n\n\
264 {}#figure(table(columns: 1, {}), caption: [Deltadeferred.#footnote[Deltanote.]], placement: top)\n\n\
265 {}", ASIDE, filler, rows, filler);
266 let two = fmt!("#set page(columns: 2)\n\n= Top\n\n\
267 #figure(table(columns: 1, [Cell]), caption: [Epsilonparent.#footnote[Epsilonnote.]], placement: top, scope: \"parent\")\n\n\
268 #figure(table(columns: 1, [Cell]), caption: [Thetaparent.#footnote[Thetanote.]], placement: bottom, scope: \"parent\")\n\n\
269 #figure(table(columns: 1, [Cell]), caption: [Zetacolumn.#footnote[Zetanote.]], placement: bottom)\n\n\
270 {}#figure(table(columns: 1, {}), caption: [Etadeferred.#footnote[Etanote.]], placement: top)\n\n\
271 {}{}", filler, rows, filler, filler);
272 for (src, pairs, deferred) in [
273 (one.as_str(), vec![("Alphafloat", "Alphanote"), ("Betaplace", "Betanote"), ("Gammaaside", "Gammanote"),
274 ("Deltadeferred", "Deltanote")], "Deltadeferred"),
275 (two.as_str(), vec![("Epsilonparent", "Epsilonnote"), ("Thetaparent", "Thetanote"), ("Zetacolumn", "Zetanote"),
276 ("Etadeferred", "Etanote")],
277 "Etadeferred"),
278 ] {
279 let (rendered, report) = res!(compile_of(&[(MAIN, src)]));
280 for (float, note) in pairs {
281 let at = page_of(&rendered, float);
282 assert!(at.is_some(), "{:?} is set", float);
283 assert_eq!(page_of(&rendered, note), at, "{:?} is set on the page {:?} lands on", note, float);
284 }
285 assert!(page_of(&rendered, deferred) > page_of(&rendered, "Fortieth"), "{:?} is deferred past the filler: {:?} {:?}",
286 deferred, page_of(&rendered, deferred), page_of(&rendered, "Fortieth"));
287 assert!(report.diagnostics.iter().all(|d| d.message.starts_with("skipped #let")), "{:?}", report.diagnostics);
288 }
289 Ok(())
290}
291
292/// What a list item asks for is answered at that item's own line, and a nested item's at its own, as the
293/// reader places an unknown call in the same item -- where every item's once stood at the list's first line.
294#[test]
295fn a_list_item_answers_at_its_own_line() -> Outcome<()> {
296 let _turn = turn();
297 let src = "= Top\n\n- first item\n- second item\n- third #foo(1) item and @gone\n - nested @alsogone\n";
298 let (_, report) = res!(compile_of(&[(MAIN, src)]));
299 let got: Vec<(usize, &str)> = report.diagnostics.iter().map(|d| (d.line, d.message.as_str())).collect();
300 assert_eq!(got.len(), 3, "{:?}", got);
301 assert!(got.iter().any(|(l, m)| *l == 5 && m.contains("#foo")), "{:?}", got);
302 assert!(got.iter().any(|(l, m)| *l == 5 && m.starts_with("@gone")), "{:?}", got);
303 assert!(got.iter().any(|(l, m)| *l == 6 && m.starts_with("@alsogone")), "{:?}", got);
304 Ok(())
305}