Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/tests/eval_math.rs

23.8 KiB, 2 runs

created by r1870400018:63600, 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//! U7: equations laid out by `flow::math` against the `typst` 0.15 oracle. Each fixture under
2//! `tests/fixtures/eval/math/` holds maths alone; it is evaluated, realised and laid out here, and
3//! compiled by `typst` on a page that fits the equation exactly, at New Computer Modern Math's regular
4//! weight (the face this crate embeds; Typst's default is its book weight, whose glyphs sit at the same
5//! positions). Every glyph's ink box and every rule's box in Typst's SVG must be matched by one in
6//! Austenite's layout, and the box sizes must agree.
7//!
8//! A fixture's first line may be `// needs: <field>` naming a schema field of another unit (for
9//! instance `text.fill`); the fixture is reported pending until that field exists. A missing `typst`
10//! fails the suite unless `EVAL_ORACLE_SKIP=1` is set.
11
12use oxedyne_fe2o3_austenite::eval::content::{
13 Content,
14 ElemKind,
15};
16use oxedyne_fe2o3_austenite::eval::eval_source as eval_module;
17use oxedyne_fe2o3_austenite::eval::intro::Builder;
18use oxedyne_fe2o3_austenite::eval::realise::{
19 realise,
20 RealiseMode,
21};
22use oxedyne_fe2o3_austenite::eval::styles::StyleChain;
23use oxedyne_fe2o3_austenite::eval::{
24 Engine,
25 World,
26};
27use oxedyne_fe2o3_austenite::flow::math::layout_equation;
28use oxedyne_fe2o3_austenite::flow::Region;
29use oxedyne_fe2o3_austenite::ir::{
30 DrawOp,
31 LeafKind,
32 Node,
33 Sp,
34};
35use oxedyne_fe2o3_austenite::ledger::Position;
36
37use oxedyne_fe2o3_core::prelude::*;
38use oxedyne_fe2o3_graphics::transform::Transform;
39
40use std::path::PathBuf;
41use std::process::Command;
42use std::sync::Arc;
43
44const TOL: f64 = 0.02; // points
45
46type BoxF = [f64; 4]; // x0, y0, x1, y1, points, y down
47
48fn fixture_dir() -> PathBuf {
49 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/eval/math")
50}
51
52fn work_dir() -> Outcome<PathBuf> {
53 let d = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("eval_math");
54 res!(std::fs::create_dir_all(&d).map_err(|e| err!(e, "work dir"; IO)));
55 Ok(d)
56}
57
58fn typst_available() -> bool {
59 Command::new("typst").arg("--version").output().map(|o| o.status.success()).unwrap_or(false)
60}
61
62const PRELUDE: &str = "#set page(width: auto, height: auto, margin: 0pt)\n";
63
64// A construct another unit has still to implement stops a layout with an `Unimplemented` error: the
65// fixture waits for it, and `EVAL_ORACLE_STRICT=math` turns the wait into a failure.
66fn waiting_on(e: &Error<ErrTag>) -> Option<String> {
67 if e.tags().contains(&ErrTag::Unimplemented) {
68 Some(e.msgs().last().cloned().unwrap_or_default())
69 } else {
70 None
71 }
72}
73
74fn strict() -> bool {
75 std::env::var("EVAL_ORACLE_STRICT").map(|v| v.split(',').any(|a| a.trim() == "math")).unwrap_or(false)
76}
77
78// Austenite
79
80fn austenite(name: &str, src: &str) -> Outcome<(Vec<BoxF>, (f64, f64))> { austenite_nth(name, src, 0) }
81
82// The `nth` equation of the document, laid out after a second pass, so a number counts the equations
83// before it as the previous pass saw them.
84fn austenite_nth(name: &str, src: &str, nth: usize) -> Outcome<(Vec<BoxF>, (f64, f64))> {
85 let dir = res!(work_dir());
86 let mut e = Engine::new(World::new(dir.clone()));
87 let id = res!(e.world.add_source(dir.join(fmt!("{}.typ", name)), src.to_string()));
88 let module = match eval_module(&mut e, id) {
89 Ok(m) => m,
90 Err(err) => return Err(err!("eval {}: {} {:?}", name, err, e.diags; Invalid)),
91 };
92 // An inline equation alone realises as a paragraph's content; until paragraphs have their schema,
93 // such a fixture is realised in inline mode instead. A leading directive (`#show`, `#set`) or comment
94 // does not decide it.
95 let first = src.lines().map(|l| l.trim_start()).find(|l| !l.is_empty() && !l.starts_with('#') && !l.starts_with("//"));
96 let mode = if first.map(|l| l.starts_with("$ ")).unwrap_or(false) { RealiseMode::Flow } else { RealiseMode::Inline };
97 let mut pairs = match realise(&mut e, &module.content, &StyleChain::root(), mode) {
98 Ok(p) => p,
99 Err(err) => return Err(err!("realise {}: {} {:?}", name, err, e.diags; Invalid)),
100 };
101 // A number reads the equation counter at its own location, which only the previous pass's introspector
102 // holds, so a numbered equation needs the second pass the fixpoint would make.
103 if nth > 0 || src.contains("numbering") {
104 // The second pass sees the first's equations, as the fixpoint's second pass does.
105 let elems: Vec<Content> = pairs.iter().filter(|p| p.content.is(ElemKind::Equation)).map(|p| p.content.clone()).collect();
106 let mut builder = Builder::new();
107 for (i, c) in elems.iter().enumerate() {
108 builder.record(c, Position::new(1, Sp::ZERO, Sp(i as i32)), None);
109 }
110 e.intro = Arc::new(builder.finish());
111 e.locator.reset();
112 pairs = match realise(&mut e, &module.content, &StyleChain::root(), mode) {
113 Ok(p) => p,
114 Err(err) => return Err(err!("second pass {}: {} {:?}", name, err, e.diags; Invalid)),
115 };
116 }
117 let (eq, styles) = match find_equation(&pairs, nth) {
118 Some(x) => x,
119 None => return Err(err!("{}: no equation {} realised", name, nth + 1; Missing)),
120 };
121 let region = Region::new(Sp(i32::MAX), Sp(i32::MAX));
122 let node = match layout_equation(&mut e, &eq, &styles, region) {
123 Ok(n) => n,
124 Err(err) => return Err(err!(err, "layout {}: {:?}", name, e.diags; Invalid)),
125 };
126 let (w, h, d) = match &node {
127 Node::HBox(b) | Node::VBox(b) => (b.dims.width.to_pt(), b.dims.height.to_pt(), b.dims.depth.to_pt()),
128 _ => (0.0, 0.0, 0.0),
129 };
130 let mut boxes = Vec::new();
131 res!(walk(&node, 0.0, 0.0, &mut boxes));
132 Ok((boxes, (w, h + d)))
133}
134
135fn find_equation(pairs: &[oxedyne_fe2o3_austenite::eval::realise::Pair], nth: usize) -> Option<(Content, StyleChain)> {
136 pairs.iter().filter(|p| p.content.is(ElemKind::Equation)).nth(nth).map(|p| (p.content.clone(), p.styles.clone()))
137}
138
139// Walks a node with its top-left at (x, y), collecting ink boxes.
140fn walk(node: &Node, x: f64, y: f64, out: &mut Vec<BoxF>) -> Outcome<()> {
141 match node {
142 Node::HBox(b) => {
143 let base = y + b.dims.height.to_pt();
144 let mut cx = x;
145 for c in &b.list {
146 match c {
147 Node::Glue(g) => cx += g.natural.to_pt(),
148 Node::Leaf(l) => {
149 let top = base - l.dims.height.to_pt() + l.shift.to_pt();
150 res!(leaf(l, cx, top, out));
151 cx += l.dims.width.to_pt();
152 }
153 Node::HBox(i) | Node::VBox(i) => {
154 res!(walk(c, cx, base - i.dims.height.to_pt(), out));
155 cx += i.dims.width.to_pt();
156 }
157 Node::Frame(f) => {
158 res!(walk(c, cx, base - f.dims.height.to_pt(), out));
159 cx += f.dims.width.to_pt();
160 }
161 _ => (),
162 }
163 }
164 }
165 Node::VBox(b) => {
166 let mut cy = y;
167 for c in &b.list {
168 match c {
169 Node::Glue(g) => cy += g.natural.to_pt(),
170 Node::Leaf(l) => {
171 res!(leaf(l, x, cy + l.shift.to_pt(), out));
172 cy += l.dims.vextent().to_pt();
173 }
174 Node::HBox(i) | Node::VBox(i) => {
175 res!(walk(c, x, cy, out));
176 cy += i.dims.vextent().to_pt();
177 }
178 Node::Frame(f) => {
179 res!(walk(c, x, cy, out));
180 cy += f.dims.vextent().to_pt();
181 }
182 _ => (),
183 }
184 }
185 }
186 Node::Leaf(l) => res!(leaf(l, x, y + l.shift.to_pt(), out)),
187 // A number is laid as a block, which the block flow hands back as a frame of positioned children.
188 Node::Frame(f) => for (ox, oy, c) in &f.items {
189 res!(walk(c, x + ox.to_pt(), y + oy.to_pt(), out));
190 },
191 _ => (),
192 }
193 Ok(())
194}
195
196fn leaf(l: &oxedyne_fe2o3_austenite::ir::Leaf, x: f64, top: f64, out: &mut Vec<BoxF>) -> Outcome<()> {
197 match &l.kind {
198 LeafKind::Text(shaped) => {
199 let base = top + l.dims.height.to_pt();
200 for g in &shaped.run().glyphs {
201 let path = res!(shaped.outline(g));
202 if let Some(b) = path.bounds(&Transform::IDENTITY) {
203 let ox = x + g.x as f64;
204 let oy = base - g.y as f64;
205 out.push([ox + b.x0 as f64, oy - b.y1 as f64, ox + b.x1 as f64, oy - b.y0 as f64]);
206 }
207 }
208 }
209 LeafKind::Graphic(gr) => for op in &gr.ops {
210 if let DrawOp::Fill { path, .. } = op {
211 if let Some(b) = path.bounds(&Transform::IDENTITY) {
212 out.push([x + b.x0 as f64, top + b.y0 as f64, x + b.x1 as f64, top + b.y1 as f64]);
213 }
214 }
215 },
216 LeafKind::Rule => {
217 out.push([x, top, x + l.dims.width.to_pt(), top + l.dims.vextent().to_pt()]);
218 }
219 _ => (),
220 }
221 Ok(())
222}
223
224// The oracle's SVG
225
226fn attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
227 let key = fmt!(" {}=\"", name);
228 let i = tag.find(&key)? + key.len();
229 let j = tag[i..].find('"')? + i;
230 Some(&tag[i..j])
231}
232
233fn nums(s: &str) -> Vec<f64> {
234 s.split(|c: char| c == ' ' || c == ',' || c == '(' || c == ')')
235 .filter_map(|t| t.parse::<f64>().ok())
236 .collect()
237}
238
239// An SVG transform attribute as an affine map (a, b, c, d, e, f).
240fn transform(s: Option<&str>) -> [f64; 6] {
241 let mut m = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
242 let s = match s {
243 Some(s) => s,
244 None => return m,
245 };
246 for part in s.split(')').filter(|p| !p.trim().is_empty()) {
247 let n = nums(part);
248 let t = if part.contains("matrix") && n.len() == 6 {
249 [n[0], n[1], n[2], n[3], n[4], n[5]]
250 } else if part.contains("translate") {
251 [1.0, 0.0, 0.0, 1.0, n.first().copied().unwrap_or(0.0), n.get(1).copied().unwrap_or(0.0)]
252 } else if part.contains("scale") {
253 let sx = n.first().copied().unwrap_or(1.0);
254 [sx, 0.0, 0.0, n.get(1).copied().unwrap_or(sx), 0.0, 0.0]
255 } else {
256 continue;
257 };
258 m = compose(m, t);
259 }
260 m
261}
262
263// `outer` applied after `inner`.
264fn compose(outer: [f64; 6], inner: [f64; 6]) -> [f64; 6] {
265 let [a, b, c, d, e, f] = outer;
266 let [a2, b2, c2, d2, e2, f2] = inner;
267 [a * a2 + c * b2, b * a2 + d * b2, a * c2 + c * d2, b * c2 + d * d2, a * e2 + c * f2 + e, b * e2 + d * f2 + f]
268}
269
270fn apply(m: &[f64; 6], x: f64, y: f64) -> (f64, f64) {
271 (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5])
272}
273
274fn bbox_of(points: &[(f64, f64)], m: &[f64; 6]) -> Option<BoxF> {
275 let mut out: Option<BoxF> = None;
276 for &(x, y) in points {
277 let (px, py) = apply(m, x, y);
278 out = Some(match out {
279 None => [px, py, px, py],
280 Some(b) => [b[0].min(px), b[1].min(py), b[2].max(px), b[3].max(py)],
281 });
282 }
283 out
284}
285
286// The points of an SVG path, control points included, as the font outline's control box has them.
287fn path_points(d: &str) -> Vec<(f64, f64)> {
288 let mut pts = Vec::new();
289 let mut cur = (0.0f64, 0.0f64);
290 let mut start = cur;
291 let mut cmd = 'M';
292 let mut pending: Option<(f64, f64)> = None; // a move counts only once something is drawn from it
293 let mut toks: Vec<String> = Vec::new();
294 let mut num = String::new();
295 for ch in d.chars() {
296 if ch.is_ascii_alphabetic() && ch != 'e' {
297 if !num.is_empty() {
298 toks.push(std::mem::take(&mut num));
299 }
300 toks.push(ch.to_string());
301 } else if ch == ' ' || ch == ',' {
302 if !num.is_empty() {
303 toks.push(std::mem::take(&mut num));
304 }
305 } else if ch == '-' && !num.is_empty() && !num.ends_with('e') {
306 toks.push(std::mem::take(&mut num));
307 num.push(ch);
308 } else {
309 num.push(ch);
310 }
311 }
312 if !num.is_empty() {
313 toks.push(num);
314 }
315 let mut i = 0;
316 let mut args: Vec<f64> = Vec::new();
317 while i <= toks.len() {
318 let t = toks.get(i);
319 let is_cmd = t.map(|t| t.chars().all(|c| c.is_ascii_alphabetic())).unwrap_or(true);
320 if is_cmd {
321 // Flush the previous command's arguments.
322 let rel = cmd.is_ascii_lowercase();
323 let n = match cmd.to_ascii_uppercase() { 'M' | 'L' | 'T' => 2, 'H' | 'V' => 1, 'C' => 6, 'S' | 'Q' => 4, _ => 0 };
324 let mut k = 0;
325 while n > 0 && k + n <= args.len() {
326 let a = &args[k..k + n];
327 let (ox, oy) = if rel { cur } else { (0.0, 0.0) };
328 let up = cmd.to_ascii_uppercase();
329 if up != 'M' || k > 0 {
330 if let Some(p) = pending.take() {
331 pts.push(p);
332 }
333 }
334 match up {
335 'M' if k == 0 => {
336 cur = (ox + a[0], oy + a[1]);
337 start = cur;
338 pending = Some(cur);
339 }
340 'M' | 'L' | 'T' => {
341 cur = (ox + a[0], oy + a[1]);
342 pts.push(cur);
343 }
344 'H' => { cur = (if rel { cur.0 + a[0] } else { a[0] }, cur.1); pts.push(cur); }
345 'V' => { cur = (cur.0, if rel { cur.1 + a[0] } else { a[0] }); pts.push(cur); }
346 'C' => {
347 pts.push((ox + a[0], oy + a[1]));
348 pts.push((ox + a[2], oy + a[3]));
349 cur = (ox + a[4], oy + a[5]);
350 pts.push(cur);
351 }
352 'S' | 'Q' => {
353 pts.push((ox + a[0], oy + a[1]));
354 cur = (ox + a[2], oy + a[3]);
355 pts.push(cur);
356 }
357 _ => (),
358 }
359 k += n;
360 }
361 args.clear();
362 match t {
363 Some(t) => {
364 cmd = t.chars().next().unwrap_or('M');
365 if cmd == 'Z' || cmd == 'z' {
366 cur = start;
367 }
368 }
369 None => break,
370 }
371 } else if let Some(v) = t.and_then(|t| t.parse::<f64>().ok()) {
372 args.push(v);
373 }
374 i += 1;
375 }
376 pts
377}
378
379fn oracle(name: &str, src: &str) -> Outcome<(Vec<BoxF>, (f64, f64))> {
380 let dir = res!(work_dir());
381 let typ = dir.join(fmt!("{}.typ", name));
382 let svg = dir.join(fmt!("{}.svg", name));
383 res!(std::fs::write(&typ, fmt!("{}{}", PRELUDE, src)).map_err(|e| err!(e, "write fixture"; IO)));
384 let out = res!(Command::new("typst").arg("compile").arg(&typ).arg(&svg).output()
385 .map_err(|e| err!(e, "run typst"; IO)));
386 if !out.status.success() {
387 return Err(err!("typst failed on {}: {}", name, String::from_utf8_lossy(&out.stderr); Input, Invalid));
388 }
389 let text = res!(std::fs::read_to_string(&svg).map_err(|e| err!(e, "read svg"; IO)));
390 Ok(read_svg(&text))
391}
392
393fn read_svg(text: &str) -> (Vec<BoxF>, (f64, f64)) {
394 // Symbols first: each glyph's outline points by id.
395 let mut symbols: Vec<(String, Vec<(f64, f64)>)> = Vec::new();
396 let mut rest = text;
397 while let Some(i) = rest.find("<symbol ") {
398 let tag_end = rest[i..].find('>').map(|j| i + j).unwrap_or(rest.len());
399 let tag = &rest[i..tag_end];
400 let id = attr(tag, "id").unwrap_or("").to_string();
401 let close = rest[i..].find("</symbol>").map(|j| i + j).unwrap_or(rest.len());
402 let body = &rest[tag_end..close];
403 let mut pts = Vec::new();
404 let mut b = body;
405 while let Some(p) = b.find("<path ") {
406 let pe = b[p..].find('>').map(|j| p + j).unwrap_or(b.len());
407 if let Some(d) = attr(&b[p..pe], "d") {
408 pts.extend(path_points(d));
409 }
410 b = &b[pe..];
411 }
412 symbols.push((id, pts));
413 rest = &rest[close..];
414 }
415 let size = match text.find("<svg ") {
416 Some(i) => {
417 let tag = &text[i..text[i..].find('>').map(|j| i + j).unwrap_or(text.len())];
418 let v = nums(attr(tag, "viewBox").unwrap_or(""));
419 (v.get(2).copied().unwrap_or(0.0), v.get(3).copied().unwrap_or(0.0))
420 }
421 None => (0.0, 0.0),
422 };
423 // Then the body, outside `<defs>`, with a stack of group transforms.
424 let body = match text.find("<defs") {
425 Some(i) => &text[..i],
426 None => text,
427 };
428 let mut boxes = Vec::new();
429 let mut stack: Vec<[f64; 6]> = vec![[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]];
430 let mut first_path = true;
431 let mut s = body;
432 while let Some(i) = s.find('<') {
433 let end = s[i..].find('>').map(|j| i + j).unwrap_or(s.len());
434 let tag = &s[i..=end.min(s.len() - 1)];
435 let top = *stack.last().unwrap_or(&[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
436 if tag.starts_with("<g") {
437 let m = compose(top, transform(attr(tag, "transform")));
438 if tag.ends_with("/>") {
439 // An empty group.
440 } else {
441 stack.push(m);
442 }
443 } else if tag.starts_with("</g") {
444 if stack.len() > 1 {
445 stack.pop();
446 }
447 } else if tag.starts_with("<use") {
448 let id = attr(tag, "xlink:href").or_else(|| attr(tag, "href")).unwrap_or("").trim_start_matches('#');
449 let ux = attr(tag, "x").and_then(|v| v.parse::<f64>().ok()).unwrap_or(0.0);
450 let uy = attr(tag, "y").and_then(|v| v.parse::<f64>().ok()).unwrap_or(0.0);
451 let m = compose(compose(top, transform(attr(tag, "transform"))), [1.0, 0.0, 0.0, 1.0, ux, uy]);
452 if let Some((_, pts)) = symbols.iter().find(|(sid, _)| sid == id) {
453 if let Some(b) = bbox_of(pts, &m) {
454 boxes.push(b);
455 }
456 }
457 } else if tag.starts_with("<path") {
458 if first_path {
459 first_path = false; // the page background
460 } else {
461 let m = compose(top, transform(attr(tag, "transform")));
462 let pts = path_points(attr(tag, "d").unwrap_or(""));
463 match attr(tag, "stroke-width").and_then(|v| v.parse::<f64>().ok()) {
464 Some(t) if attr(tag, "fill") == Some("none") => {
465 let cap = attr(tag, "stroke-linecap").unwrap_or("butt");
466 for w in pts.windows(2) {
467 if let Some(b) = stroke_box(w[0], w[1], t, cap, &m) {
468 boxes.push(b);
469 }
470 }
471 }
472 _ => if let Some(b) = bbox_of(&pts, &m) {
473 boxes.push(b);
474 },
475 }
476 }
477 }
478 s = &s[end.min(s.len() - 1) + 1..];
479 }
480 (boxes, size)
481}
482
483fn stroke_box(p0: (f64, f64), p1: (f64, f64), t: f64, cap: &str, m: &[f64; 6]) -> Option<BoxF> {
484 let (dx, dy) = (p1.0 - p0.0, p1.1 - p0.1);
485 let len = dx.hypot(dy);
486 if len == 0.0 {
487 return None;
488 }
489 let (ux, uy) = (dx / len, dy / len);
490 let (nx, ny) = (-uy * t / 2.0, ux * t / 2.0);
491 let ext = if cap == "butt" { 0.0 } else { t / 2.0 };
492 let a = (p0.0 - ux * ext, p0.1 - uy * ext);
493 let b = (p1.0 + ux * ext, p1.1 + uy * ext);
494 bbox_of(&[(a.0 + nx, a.1 + ny), (a.0 - nx, a.1 - ny), (b.0 + nx, b.1 + ny), (b.0 - nx, b.1 - ny)], m)
495}
496
497// Matching
498
499fn close(a: &BoxF, b: &BoxF) -> bool {
500 (0..4).all(|i| (a[i] - b[i]).abs() <= TOL)
501}
502
503fn compare(name: &str, ours: &(Vec<BoxF>, (f64, f64)), theirs: &(Vec<BoxF>, (f64, f64))) -> Vec<String> {
504 let mut errs = Vec::new();
505 if (ours.1.0 - theirs.1.0).abs() > TOL || (ours.1.1 - theirs.1.1).abs() > TOL {
506 errs.push(fmt!("{}: size {:.4} x {:.4}, oracle {:.4} x {:.4}", name, ours.1.0, ours.1.1, theirs.1.0, theirs.1.1));
507 }
508 let mut left: Vec<BoxF> = ours.0.clone();
509 let mut missing = Vec::new();
510 for t in &theirs.0 {
511 match left.iter().position(|o| close(o, t)) {
512 Some(i) => { left.remove(i); }
513 None => missing.push(*t),
514 }
515 }
516 let f = |b: &BoxF| fmt!("[{:.3} {:.3} {:.3} {:.3}]", b[0], b[1], b[2], b[3]);
517 for m in &missing {
518 errs.push(fmt!("{}: oracle ink {} unmatched", name, f(m)));
519 }
520 for l in &left {
521 errs.push(fmt!("{}: austenite ink {} extra", name, f(l)));
522 }
523 errs
524}
525
526// A fixture's dependency, `// needs: elem.field`, absent from the schemas yet.
527fn pending(src: &str) -> Option<String> {
528 let first = src.lines().next()?;
529 let need = first.strip_prefix("// needs:")?.trim();
530 let (kind, field) = need.split_once('.')?;
531 let k = ElemKind::ALL.iter().find(|k| k.path() == kind)?;
532 if k.field_id(field).is_some() { None } else { Some(need.to_string()) }
533}
534
535#[test]
536fn maths_fixtures_match_the_typst_oracle() -> Outcome<()> {
537 if !typst_available() {
538 if std::env::var("EVAL_ORACLE_SKIP").as_deref() == Ok("1") {
539 return Ok(());
540 }
541 return Err(err!("typst is not on PATH; set EVAL_ORACLE_SKIP=1 to skip the oracle deliberately"; Missing));
542 }
543 let only = std::env::var("MATH_FIXTURE").ok();
544 let mut names: Vec<String> = Vec::new();
545 for entry in res!(std::fs::read_dir(fixture_dir()).map_err(|e| err!(e, "fixture dir"; IO))) {
546 let p = res!(entry.map_err(|e| err!(e, "fixture entry"; IO))).path();
547 if p.extension().and_then(|x| x.to_str()) == Some("typ") {
548 if let Some(stem) = p.file_stem().and_then(|x| x.to_str()) {
549 if only.as_deref().map(|o| o == stem).unwrap_or(true) {
550 names.push(stem.to_string());
551 }
552 }
553 }
554 }
555 names.sort();
556 let mut errs = Vec::new();
557 let mut passed = 0;
558 let mut waiting = Vec::new();
559 for name in &names {
560 let src = res!(std::fs::read_to_string(fixture_dir().join(fmt!("{}.typ", name))).map_err(|e| err!(e, "read"; IO)));
561 if let Some(need) = pending(&src) {
562 waiting.push(fmt!("{} ({})", name, need));
563 continue;
564 }
565 let theirs = match oracle(name, &src) {
566 Ok(t) => t,
567 Err(e) => {
568 errs.push(fmt!("{}: {}", name, e));
569 continue;
570 }
571 };
572 if theirs.0.is_empty() {
573 errs.push(fmt!("{}: the oracle drew nothing", name));
574 continue;
575 }
576 match austenite(name, &src) {
577 Ok(ours) => {
578 let e = compare(name, &ours, &theirs);
579 if e.is_empty() {
580 passed += 1;
581 }
582 errs.extend(e);
583 }
584 Err(e) => match waiting_on(&e) {
585 Some(why) => waiting.push(fmt!("{} ({})", name, why)),
586 None => errs.push(fmt!("{}: {}", name, e)),
587 },
588 }
589 }
590 println!("maths fixtures: {} of {} match the oracle, {} pending: {:?}", passed, names.len() - waiting.len(),
591 waiting.len(), waiting);
592 if strict() && !waiting.is_empty() {
593 return Err(err!("{} maths fixtures are still waiting on another unit", waiting.len(); Missing));
594 }
595 if !errs.is_empty() {
596 for e in &errs {
597 println!("{}", e);
598 }
599 return Err(err!("{} maths layout differences from the oracle", errs.len(); Mismatch));
600 }
601 Ok(())
602}
603
604/// The number of a numbered block equation is its counter's value, read through the model's lookup
605/// seam: the third equation of a document reads (3), as it does in Typst with a counter update ahead of
606/// one equation. A first equation reads (1), so the two are told apart.
607#[test]
608fn a_numbered_equation_counts_the_equations_before_it() -> Outcome<()> {
609 if !typst_available() {
610 if std::env::var("EVAL_ORACLE_SKIP").as_deref() == Ok("1") {
611 return Ok(());
612 }
613 return Err(err!("typst is not on PATH; set EVAL_ORACLE_SKIP=1 to skip the oracle deliberately"; Missing));
614 }
615 let set = "#set math.equation(numbering: \"(1)\")\n";
616 let third = match austenite_nth("count_third", &fmt!("{}$ a $\n$ b $\n$ c + d = 1 $", set), 2) {
617 Ok(t) => t,
618 Err(e) => match waiting_on(&e) {
619 Some(why) if !strict() => {
620 println!("count_third waits on another unit: {}", why);
621 return Ok(());
622 }
623 _ => return Err(e),
624 },
625 };
626 let counted = res!(oracle("count_third_typst", &fmt!("{}#counter(math.equation).update(2)\n$ c + d = 1 $", set)));
627 let first = res!(oracle("count_first_typst", &fmt!("{}$ c + d = 1 $", set)));
628 let errs = compare("count_third", &third, &counted);
629 for e in &errs {
630 println!("{}", e);
631 }
632 assert!(errs.is_empty(), "{} differences from the oracle's third equation", errs.len());
633 assert!(!compare("count_third", &third, &first).is_empty(), "(3) must not be laid out as (1)");
634 Ok(())
635}
636
637/// The comparator must fail on a real difference: a glyph moved by a tenth of a point, a box missing.
638#[test]
639fn the_comparator_catches_a_moved_glyph() {
640 let a = (vec![[0.0, 0.0, 1.0, 1.0], [2.0, 0.0, 3.0, 1.0]], (3.0, 1.0));
641 let moved = (vec![[0.0, 0.0, 1.0, 1.0], [2.1, 0.0, 3.1, 1.0]], (3.0, 1.0));
642 let fewer = (vec![[0.0, 0.0, 1.0, 1.0]], (3.0, 1.0));
643 assert!(compare("same", &a, &a).is_empty());
644 assert!(!compare("moved", &moved, &a).is_empty());
645 assert!(!compare("fewer", &fewer, &a).is_empty());
646}
647
648#[test]
649fn svg_paths_read_relative_and_absolute_commands() {
650 let pts = path_points("M 1 2l 3 0h 1v -2c 0 1 1 1 1 0Z");
651 assert_eq!(pts.first(), Some(&(1.0, 2.0)));
652 assert!(pts.contains(&(4.0, 2.0)));
653 assert!(pts.contains(&(5.0, 2.0)));
654 assert!(pts.contains(&(5.0, 0.0)));
655 assert!(pts.contains(&(6.0, 0.0)));
656}
657
658#[test]
659fn debug_dump() {
660 let src = std::env::var("MATH_DUMP").unwrap_or_default();
661 if src.is_empty() { return; }
662 let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR"));
663 let mut e = Engine::new(World::new(dir.clone()));
664 let id = e.world.add_source(dir.join("dump.typ"), src).unwrap_or_else(|x| panic!("{}", x));
665 let m = eval_module(&mut e, id).unwrap_or_else(|x| panic!("{} {:?}", x, e.diags));
666 let pairs = realise(&mut e, &m.content, &StyleChain::root(), RealiseMode::Flow).unwrap_or_else(|x| panic!("{}", x));
667 let (eq, st) = find_equation(&pairs, 0).unwrap_or_else(|| panic!("no eq"));
668 let node = layout_equation(&mut e, &eq, &st, Region::new(Sp(i32::MAX), Sp(i32::MAX))).unwrap_or_else(|x| panic!("{}", x));
669 fn show(n: &Node, d: usize) {
670 match n {
671 Node::HBox(b) | Node::VBox(b) => { println!("{:w$}box {:?}", "", b.dims, w = d); for c in &b.list { show(c, d + 2); } }
672 Node::Leaf(l) => match &l.kind {
673 LeafKind::Text(t) => println!("{:w$}text {:?} shift {:?}", "", t.source(), l.shift, w = d),
674 LeafKind::Graphic(g) => println!("{:w$}graphic {} ops", "", g.ops.len(), w = d),
675 _ => println!("{:w$}leaf", "", w = d),
676 },
677 Node::Glue(g) => println!("{:w$}glue {:?}", "", g.natural.to_pt(), w = d),
678 Node::Frame(f) => {
679 println!("{:w$}frame {:?}", "", f.dims, w = d);
680 for (x, y, c) in &f.items {
681 println!("{:w$}at ({:.2}, {:.2})", "", x.to_pt(), y.to_pt(), w = d + 2);
682 show(c, d + 4);
683 }
684 }
685 Node::Transform(t) => { println!("{:w$}transform {:?}", "", t.dims, w = d); for c in &t.list { show(c, d + 2); } }
686 Node::Clip(c) => { println!("{:w$}clip {:?}", "", c.dims, w = d); for k in &c.list { show(k, d + 2); } }
687 Node::Tag(_) | Node::Anchor(_) | Node::Mark(_) => println!("{:w$}tag", "", w = d),
688 _ => println!("{:w$}other", "", w = d),
689 }
690 }
691 show(&node, 0);
692}