From fd4a95d261b1ee0e9bf11f1f9ec5a4a67a5f678a Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Thu, 12 Nov 2026 22:11:18 -0500 Subject: [PATCH] craft-math: tests for the OMML writer and the linear format (port of wordcraft#6080) The OMML writer (omml/write.rs) had no tests of its own, and the linear-format parser (math_linear.rs) none in its own module. - omml/write/tests.rs: every MNode variant and option, run properties, the three sources write_equation takes an equation from (kept OMML, nodes, linear text), the equation colour (#1467), display jc, resolve_numbers, m:mathPr and the matrix and depth caps (#4000) are written and read back with read_omath. What the reader gives back differently on purpose (merged runs, half-point sizes, matrix column alignments, an empty delimiter...) is stated as such. Element order, which a round trip can't see, is pinned by exact XML: each structure with its defaults and with every property on, a run, m:oMathPara and m:mathPr. The strings follow the ECMA-376 shared-math sequences. - math_linear/tests.rs: one case per construct of the module doc, the helpers (closer, is_combining, strip_parens), to_linear round trips and truncated input. Where Word builds the same text, the expected tree is Word's. Tests only; no behaviour change. Ported from storytold/wordcraft#6080 (issue wordcraft#6079), on top of the other ports in this series, which they pass with unchanged. The writer tests move from WordCraft's docx/src/write/math/tests.rs to omml/write/tests.rs, with craft-math's paths for what they used from WordCraft (read_omath, para_jc and read_math_pr from omml, each_run_mut from math_tree, map_args from math_linear), and OMML read back with omml::parse instead of WordCraft's xml::parse_strict over namespace-wrapped text. --- crates/math/src/math_linear.rs | 3 + crates/math/src/math_linear/tests.rs | 253 +++++++++++ crates/math/src/omml/write.rs | 3 + crates/math/src/omml/write/tests.rs | 601 +++++++++++++++++++++++++++ 4 files changed, 860 insertions(+) create mode 100644 crates/math/src/math_linear/tests.rs create mode 100644 crates/math/src/omml/write/tests.rs diff --git a/crates/math/src/math_linear.rs b/crates/math/src/math_linear.rs index 1dccd2c46..47634cbcf 100644 --- a/crates/math/src/math_linear.rs +++ b/crates/math/src/math_linear.rs @@ -845,3 +845,6 @@ pub fn map_args(n: MNode, f: &dyn Fn(Arg) -> Arg) -> MNode { MNode::Phant { show, zero_wid, zero_asc, zero_desc, e } => MNode::Phant { show, zero_wid, zero_asc, zero_desc, e: f(e) }, } } + +#[cfg(test)] +mod tests; diff --git a/crates/math/src/math_linear/tests.rs b/crates/math/src/math_linear/tests.rs new file mode 100644 index 000000000..236a6f74d --- /dev/null +++ b/crates/math/src/math_linear/tests.rs @@ -0,0 +1,253 @@ +//! The linear format (UnicodeMath) parser: one case per construct in the module doc. Where Word +//! builds the same text (observed with Word's build-up), the expected tree is the one Word builds; +//! where it differs, the case says so. + +use super::*; +use crate::math::{ColJc, to_linear}; + +fn r(t: &str) -> MNode { + MNode::Run(MRun::new(t)) +} + +fn a(t: &str) -> Arg { + vec![r(t)] +} + +fn up(t: &str) -> Arg { + vec![MNode::Run(MRun::plain(t))] +} + +fn sup(base: Arg, s: Arg) -> MNode { + MNode::Script { kind: ScriptKind::Sup, base, sub: Vec::new(), sup: s } +} + +fn sub(base: Arg, s: Arg) -> MNode { + MNode::Script { kind: ScriptKind::Sub, base, sub: s, sup: Vec::new() } +} + +fn frac(kind: FracKind, num: Arg, den: Arg) -> MNode { + MNode::Frac { kind, num, den } +} + +/// A delimiter as the parser makes it: one element has no separator. +fn delim(beg: Option, end: Option, elems: Vec) -> MNode { + let sep = (elems.len() > 1).then_some('|'); + MNode::Delim { beg, end, sep, grow: true, shp_match: false, elems } +} + +#[track_caller] +fn parses(s: &str, want: Arg) { + assert_eq!(parse(s), want, "{s}"); +} + +/// Linear text printed back from the tree parses to the same tree. +#[track_caller] +fn stable(s: &str) { + let n = parse(s); + let back = to_linear(&n); + assert_eq!(parse(&back), n, "{s} → {back}"); +} + +// --- Fractions. --------------------------------------------------------------------------------- + +#[test] +fn fraction_operators() { + parses("a/b+c", vec![frac(FracKind::Bar, a("a"), a("b")), r("+c")]); + parses("a⁄b", vec![frac(FracKind::Skewed, a("a"), a("b"))]); + parses("a∕b", vec![frac(FracKind::Linear, a("a"), a("b"))]); + parses("a¦b", vec![frac(FracKind::NoBar, a("a"), a("b"))]); + // A parenthesised operand loses its parentheses; `/` groups to the left (as in Word). + parses("(a+b)/(c+d)", vec![frac(FracKind::Bar, a("a+b"), a("c+d"))]); + parses("a/b/c", vec![frac(FracKind::Bar, vec![frac(FracKind::Bar, a("a"), a("b"))], a("c"))]); + // Placeholders are empty arguments; a missing denominator is empty. + parses("⬚/⬚", vec![frac(FracKind::Bar, vec![], vec![])]); + parses("a/", vec![frac(FracKind::Bar, a("a"), vec![])]); +} + +// --- Scripts. ----------------------------------------------------------------------------------- + +#[test] +fn scripts() { + parses("x^(-1)", vec![sup(a("x"), a("-1"))]); + parses("x_i^2", vec![MNode::Script { kind: ScriptKind::SubSup, base: a("x"), sub: a("i"), sup: a("2") }]); + // Either order makes one sub-superscript. + parses("a^b_c", vec![MNode::Script { kind: ScriptKind::SubSup, base: a("a"), sub: a("c"), sup: a("b") }]); + parses("x_(i_j)", vec![sub(a("x"), vec![sub(a("i"), a("j"))])]); +} + +/// `^`/`_` with nothing before them are pre-scripts (module doc). Word's build-up doesn't make an +/// `m:sPre` from this text. +#[test] +fn pre_scripts() { + parses("_1^n▒Y", vec![MNode::Script { kind: ScriptKind::Pre, base: a("Y"), sub: a("1"), sup: a("n") }]); +} + +// --- Radicals, n-ary operators, functions, limits. ---------------------------------------------- + +#[test] +fn radicals() { + parses("√x", vec![MNode::Rad { deg: vec![], deg_hide: true, e: a("x") }]); + parses("√(3&x)", vec![MNode::Rad { deg: a("3"), deg_hide: false, e: a("x") }]); + parses("√", vec![MNode::Rad { deg: vec![], deg_hide: true, e: vec![] }]); +} + +#[test] +fn nary_operators() { + let nary = |chr, sub, sup, e| MNode::Nary { chr, lim_loc: None, grow: false, sub_hide: false, sup_hide: false, sub, sup, e }; + parses("∑_(i=1)^n▒i^2", vec![nary('∑', a("i=1"), a("n"), vec![sup(a("i"), a("2"))])]); + parses("∫_0^1▒f(x)dx", vec![nary('∫', a("0"), a("1"), vec![r("f"), delim(Some('('), Some(')'), vec![a("x")]), r("dx")])]); +} + +#[test] +fn function_names() { + parses("sin x", vec![MNode::Func { name: up("sin"), e: a("x") }]); + parses("log_2 x", vec![MNode::Func { name: vec![sub(up("log"), a("2"))], e: a("x") }]); + parses("lim┬(n→∞) a_n", vec![MNode::Func { name: vec![MNode::Lim { upper: false, e: up("lim"), lim: a("n→∞") }], e: vec![sub(a("a"), a("n"))] }]); +} + +#[test] +fn limits_on_any_base() { + parses("x┬k", vec![MNode::Lim { upper: false, e: a("x"), lim: a("k") }]); + parses("x┴k", vec![MNode::Lim { upper: true, e: a("x"), lim: a("k") }]); + parses("a/b┬c", vec![frac(FracKind::Bar, a("a"), vec![MNode::Lim { upper: false, e: a("b"), lim: a("c") }])]); +} + +// --- Brackets. ---------------------------------------------------------------------------------- + +#[test] +fn brackets() { + parses("(a│b)", vec![delim(Some('('), Some(')'), vec![a("a"), a("b")])]); + parses("|x|+‖v‖", vec![delim(Some('|'), Some('|'), vec![a("x")]), r("+"), delim(Some('‖'), Some('‖'), vec![a("v")])]); + parses("f'(x)", vec![r("f'"), delim(Some('('), Some(')'), vec![a("x")])]); + // `├`…`┤` make one-sided or reversed brackets (module doc; Word's build-up leaves `├]a[┤` as + // text, but builds `{█(x@y)┤`). + parses("├]a[┤", vec![delim(Some(']'), Some('['), vec![a("a")])]); + parses("{█(x@y)┤", vec![delim(Some('{'), None, vec![vec![MNode::EqArr { rows: vec![a("x"), a("y")] }]])]); + // An unclosed bracket closes at the end; stray closers are text. + parses("(a", vec![delim(Some('('), None, vec![a("a")])]); + parses("a)", a("a)")); + parses("]x", a("]x")); + parses(")a(", vec![r(")a"), delim(Some('('), None, vec![vec![]])]); +} + +// --- Prefix structures and accents. ------------------------------------------------------------- + +#[test] +fn prefix_structures() { + parses("▭(a)", vec![MNode::BorderBox { hide: [false; 4], strike: [false; 4], e: a("a") }]); + parses("□(a)", vec![MNode::Boxed { e: a("a") }]); + parses("¯(ab)", vec![MNode::Bar { top: true, e: a("ab") }]); + parses("▁(ab)", vec![MNode::Bar { top: false, e: a("ab") }]); + parses("⏞(a+b)", vec![MNode::GroupChr { chr: '⏞', top: true, e: a("a+b") }]); + parses("⏟(a+b)", vec![MNode::GroupChr { chr: '⏟', top: false, e: a("a+b") }]); +} + +#[test] +fn combining_accents() { + parses("A\u{20D7}", vec![MNode::Acc { chr: '\u{20D7}', e: a("A") }]); + parses("x\u{302}", vec![MNode::Acc { chr: '\u{302}', e: a("x") }]); + assert!(is_combining('\u{302}') && is_combining('\u{20D7}')); + assert!(!is_combining('x') && !is_combining('^')); +} + +// --- Arrays and numbering. ---------------------------------------------------------------------- + +#[test] +fn arrays() { + parses("█(a=b@c=d)", vec![MNode::EqArr { rows: vec![a("a=b"), a("c=d")] }]); + parses("█(a@b", vec![MNode::EqArr { rows: vec![a("a"), a("b")] }]); + // Column alignments are left to the writer (it writes centred columns). + parses("■(a&b@c&d)", vec![MNode::Matrix { rows: vec![vec![a("a"), a("b")], vec![a("c"), a("d")]], col_jc: Vec::::new() }]); +} + +#[test] +fn a_top_level_hash_numbers_the_equation() { + let number = delim(Some('('), Some(')'), vec![a("1")]); + parses("E=mc^2#(1)", vec![MNode::EqArr { rows: vec![vec![r("E=m"), sup(a("c"), a("2")), r("#"), number]] }]); + assert!(matches!(&parse("a=b#")[..], [MNode::EqArr { rows }] if rows.len() == 1)); + assert!(!matches!(&parse("a=b")[..], [MNode::EqArr { .. }])); +} + +// --- Helpers. ----------------------------------------------------------------------------------- + +#[test] +fn closers_pair_with_openers() { + for (o, c) in [('(', ')'), ('[', ']'), ('{', '}'), ('⟨', '⟩'), ('〈', '〉'), ('⌈', '⌉'), ('⌊', '⌋'), ('⟦', '⟧'), ('〖', '〗')] + { + assert_eq!(closer(o), Some(c)); + assert!(is_closer(c)); + } + assert_eq!(closer('a'), None); + assert_eq!(closer('|'), None, "| closes itself, by matching"); +} + +#[test] +fn strip_parens_unwraps_one_plain_group() { + let inner = a("a+b"); + assert_eq!(strip_parens(vec![delim(Some('('), Some(')'), vec![inner.clone()])]), inner); + assert_eq!(strip_parens(vec![delim(None, None, vec![inner.clone()])]), inner, "invisible brackets"); + let square = vec![delim(Some('['), Some(']'), vec![inner.clone()])]; + assert_eq!(strip_parens(square.clone()), square, "only round or invisible brackets"); + let two = vec![delim(Some('('), Some(')'), vec![a("a"), a("b")])]; + assert_eq!(strip_parens(two.clone()), two, "only one element"); + let more = vec![delim(Some('('), Some(')'), vec![inner]), r("c")]; + assert_eq!(strip_parens(more.clone()), more, "only a lone group"); +} + +// --- Round trip through `to_linear`. ------------------------------------------------------------ + +#[test] +fn every_construct_prints_back_to_the_same_tree() { + for s in [ + "a/b+c", + "(a+b)/(c+d)", + "a/b/c", + "a⁄b", + "a∕b", + "a¦b", + "⬚/⬚", + "x_i^2", + "a^b_c", + "x^(-1)", + "x_(i_j)", + "_1^n▒Y", + "√x", + "√(3&x)", + "∑_(i=1)^n▒i^2", + "∫_0^1▒f(x)dx", + "sin x", + "log_2 x", + "lim┬(n→∞) a_n", + "x┬k", + "x┴k", + "a/b┬c", + "(a│b)", + "|x|+‖v‖", + "f'(x)", + "├]a[┤", + "{█(x@y)┤", + "(a", + ")a(", + "▭(a)", + "□(a)", + "¯(ab)", + "▁(ab)", + "⏞(a+b)", + "⏟(a+b)", + "A\u{20D7}", + "x\u{302}", + "█(a=b@c=d)", + "■(a&b@c&d)", + "E=mc^2#(1)", + ] { + stable(s); + } +} + +#[test] +fn truncated_input_parses() { + for s in ["√", "(a", "a/", "█(a@b", "x_", "■(", "├", "┤", "〖", "#", "▒", "/", "^", "_"] { + let n = parse(s); + assert_eq!(parse(&to_linear(&n)), n, "{s:?} → {:?}", to_linear(&n)); + } +} diff --git a/crates/math/src/omml/write.rs b/crates/math/src/omml/write.rs index 4d8f2dd0c..3f571fc96 100644 --- a/crates/math/src/omml/write.rs +++ b/crates/math/src/omml/write.rs @@ -491,3 +491,6 @@ fn run(w: &mut W, r: &MRun) { w.leaf("m:t", &[("xml:space", "preserve")], &r.text); w.close("m:r"); } + +#[cfg(test)] +mod tests; diff --git a/crates/math/src/omml/write/tests.rs b/crates/math/src/omml/write/tests.rs new file mode 100644 index 000000000..c828822ac --- /dev/null +++ b/crates/math/src/omml/write/tests.rs @@ -0,0 +1,601 @@ +//! The OMML writer: content and values are checked by writing a tree and reading it back with +//! [`crate::omml::read_omath`]; element order, which the reader can't see (it looks children +//! up by name), is checked against exact XML. The golden strings were checked against the +//! ECMA-376 shared-math schema (`CT_*` sequences); they come from this writer, not from Word. + +use super::*; +use crate::math::to_linear; + +const RED: Rgb = Rgb(0xFF, 0, 0); +const GREEN: Rgb = Rgb(0, 0x80, 0); +const BLUE: Rgb = Rgb(0, 0, 0xFF); + +fn r(t: &str) -> MNode { + MNode::Run(MRun::new(t)) +} + +fn a(t: &str) -> Arg { + vec![r(t)] +} + +fn delim(beg: Option, end: Option, elems: Vec) -> MNode { + MNode::Delim { beg, end, sep: Some('|'), grow: true, shp_match: false, elems } +} + +fn math(nodes: Arg) -> Math { + Math { nodes, ..Default::default() } +} + +/// `write_equation` into a fresh writer, without the XML declaration. +fn write(m: &Math, linear: &str, display: bool, color: Option) -> String { + let mut w = W::default(); + write_equation(&mut w, linear, display, m, color); + w.s +} + +fn xml(nodes: &Arg) -> String { + write(&math(nodes.clone()), "", false, None) +} + +/// Read written OMML back (inline or display), as the DOCX reader does. +fn read(xml: &str) -> Math { + let e = crate::omml::parse(xml).unwrap(); + match e.name.as_str() { + "m:oMathPara" => read_omath(e.find("m:oMath").unwrap(), crate::omml::para_jc(&e)), + _ => read_omath(&e, MathJc::CenterGroup), + } +} + +fn round_trip(nodes: &Arg) -> Arg { + read(&xml(nodes)).nodes +} + +#[track_caller] +fn assert_round_trip(label: &str, nodes: Arg) { + assert_eq!(round_trip(&nodes), nodes, "{label}: {}", xml(&nodes)); +} + +/// The equation's runs. +fn runs(nodes: &Arg) -> Vec { + let mut out = Vec::new(); + let mut n = nodes.clone(); + crate::math_tree::each_run_mut(&mut n, &mut |r| out.push(r.clone())); + out +} + +// --- Round trip: every structure and option comes back as written. ----------------------------- + +#[test] +fn every_structure_round_trips() { + use MNode::*; + for kind in [FracKind::Bar, FracKind::Skewed, FracKind::Linear, FracKind::NoBar] { + assert_round_trip("frac", vec![Frac { kind, num: a("a"), den: a("b") }]); + } + assert_round_trip("empty frac", vec![Frac { kind: FracKind::Bar, num: vec![], den: vec![] }]); + assert_round_trip("sup", vec![Script { kind: ScriptKind::Sup, base: a("x"), sub: vec![], sup: a("2") }]); + assert_round_trip("sub", vec![Script { kind: ScriptKind::Sub, base: a("x"), sub: a("i"), sup: vec![] }]); + assert_round_trip("subsup", vec![Script { kind: ScriptKind::SubSup, base: a("x"), sub: a("i"), sup: a("2") }]); + assert_round_trip("pre", vec![Script { kind: ScriptKind::Pre, base: a("x"), sub: a("i"), sup: a("2") }]); + assert_round_trip("sqrt", vec![Rad { deg: vec![], deg_hide: true, e: a("x") }]); + assert_round_trip("root", vec![Rad { deg: a("3"), deg_hide: false, e: a("x") }]); + assert_round_trip("empty degree shown", vec![Rad { deg: vec![], deg_hide: false, e: a("x") }]); + for (chr, lim_loc) in [('∫', None), ('∑', Some(LimLoc::UndOvr)), ('∏', Some(LimLoc::SubSup))] { + assert_round_trip("nary", vec![Nary { chr, lim_loc, grow: false, sub_hide: false, sup_hide: false, sub: a("i"), sup: a("n"), e: a("x") }]); + } + assert_round_trip( + "nary flags", + vec![Nary { chr: '∑', lim_loc: None, grow: true, sub_hide: true, sup_hide: true, sub: vec![], sup: vec![], e: a("x") }], + ); + assert_round_trip("parens", vec![delim(Some('('), Some(')'), vec![a("a")])]); + assert_round_trip("one-sided", vec![delim(Some('{'), None, vec![a("a")])]); + assert_round_trip("no opening", vec![delim(None, Some(']'), vec![a("a")])]); + assert_round_trip("empty element", vec![delim(Some('('), Some(')'), vec![vec![]])]); + assert_round_trip( + "brackets, separator, two elements", + vec![Delim { beg: Some('['), end: Some(']'), sep: Some(';'), grow: true, shp_match: false, elems: vec![a("a"), a("b")] }], + ); + assert_round_trip( + "no separator", + vec![Delim { beg: Some('('), end: Some(')'), sep: None, grow: true, shp_match: false, elems: vec![a("a"), a("b")] }], + ); + assert_round_trip( + "fixed size, matched shape", + vec![Delim { beg: Some('|'), end: Some('|'), sep: Some('|'), grow: false, shp_match: true, elems: vec![a("a")] }], + ); + assert_round_trip("func", vec![Func { name: vec![MNode::Run(MRun::plain("sin"))], e: a("x") }]); + assert_round_trip("lim low", vec![Lim { upper: false, e: vec![MNode::Run(MRun::plain("lim"))], lim: a("n→∞") }]); + assert_round_trip("lim upp", vec![Lim { upper: true, e: a("x"), lim: a("k") }]); + assert_round_trip("hat", vec![Acc { chr: '\u{302}', e: a("x") }]); + assert_round_trip("vector", vec![Acc { chr: '\u{20D7}', e: a("v") }]); + assert_round_trip("overbar", vec![Bar { top: true, e: a("x") }]); + assert_round_trip("underbar", vec![Bar { top: false, e: a("x") }]); + assert_round_trip("border box", vec![BorderBox { hide: [false; 4], strike: [false; 4], e: a("x") }]); + assert_round_trip("border box flags", vec![BorderBox { hide: [true, false, true, false], strike: [false, true, false, true], e: a("x") }]); + assert_round_trip("box", vec![Boxed { e: a("x") }]); + assert_round_trip("underbrace", vec![GroupChr { chr: '\u{23DF}', top: false, e: a("x") }]); + assert_round_trip("overbrace", vec![GroupChr { chr: '\u{23DE}', top: true, e: a("x") }]); + assert_round_trip("eqarr", vec![EqArr { rows: vec![a("a=b"), a("c=d")] }]); + assert_round_trip("numbered eqarr", vec![EqArr { rows: vec![a("a=b#(1)")] }]); + assert_round_trip("matrix", vec![Matrix { rows: vec![vec![a("a"), a("b")], vec![a("c"), a("d")]], col_jc: vec![ColJc::Left, ColJc::Right] }]); + assert_round_trip("phantom", vec![Phant { show: true, zero_wid: false, zero_asc: false, zero_desc: false, e: a("x") }]); + assert_round_trip("hidden phantom", vec![Phant { show: false, zero_wid: true, zero_asc: true, zero_desc: true, e: a("x") }]); +} + +#[test] +fn nested_structures_round_trip() { + let quadratic = parse_linear("x=(-b±√(b^2-4ac))/2a"); + assert_round_trip("quadratic", quadratic); + let sum = parse_linear("∑_(i=1)^n▒(i^2)/(n+1)"); + assert_round_trip("sum", sum); +} + +#[test] +fn run_properties_round_trip() { + let with = |f: &dyn Fn(&mut MRun)| { + let mut x = MRun::new("ab"); + f(&mut x); + vec![MNode::Run(x)] + }; + for s in [MSty::Plain, MSty::Bold, MSty::Italic, MSty::BoldItalic] { + assert_round_trip("sty", with(&|x| x.sty = Some(s))); + } + for s in [MScr::Script, MScr::Fraktur, MScr::DoubleStruck, MScr::SansSerif, MScr::Monospace] { + assert_round_trip("scr", with(&|x| x.scr = s)); + } + assert_round_trip("lit", with(&|x| x.lit = true)); + assert_round_trip( + "normal text in a font", + with(&|x| { + x.nor = true; + x.font = Some("Arial".into()); + }), + ); + assert_round_trip("size", with(&|x| x.size = Some(11.0))); + assert_round_trip("half-point size", with(&|x| x.size = Some(10.5))); + assert_round_trip("colour", with(&|x| x.color = Some(RED))); + assert_round_trip("break", with(&|x| x.brk = Some(0))); + assert_round_trip("aligned break", with(&|x| x.brk = Some(3))); + for t in ["af", " a b ", " ", "a\tb\nc", "𝑥𝟙", "\u{F061}"] { + assert_round_trip(t, a(t)); + } +} + +// --- Normalisation: what the reader gives back differently, on purpose. ------------------------ + +#[test] +fn reading_back_normalises_runs() { + // Equal neighbours merge (`merge_runs`); an empty run is no run. + assert_eq!(round_trip(&vec![r("a"), r("b")]), a("ab")); + assert_eq!(round_trip(&vec![r("a"), r(""), r("b")]), a("ab")); + assert_eq!(round_trip(&a("")), vec![]); + // Characters XML can't carry are dropped. + assert_eq!(round_trip(&a("a\u{1}b")), a("ab")); + // Sizes are half points, within 1–1638 pt. + let sized = |s: f32| vec![MNode::Run(MRun { size: Some(s), ..MRun::new("x") })]; + assert_eq!(round_trip(&sized(10.3)), sized(10.5)); + assert_eq!(round_trip(&sized(0.5)), sized(1.0)); + assert_eq!(round_trip(&sized(2000.0)), sized(1638.0)); + // A font belongs to normal text only; normal text without one is written in Cambria Math, + // as Word writes it (layout treats that as the text font). + let font = vec![MNode::Run(MRun { font: Some("Arial".into()), ..MRun::new("x") })]; + assert_eq!(round_trip(&font), a("x")); + let nor = vec![MNode::Run(MRun { nor: true, ..MRun::new("x") })]; + assert_eq!(round_trip(&nor), vec![MNode::Run(MRun { nor: true, font: Some("Cambria Math".into()), ..MRun::new("x") })]); +} + +#[test] +fn reading_back_normalises_structures() { + use MNode::*; + // A script keeps only the slots its kind has. + let stray = vec![Script { kind: ScriptKind::Sup, base: a("x"), sub: a("i"), sup: a("2") }]; + assert_eq!(round_trip(&stray), vec![Script { kind: ScriptKind::Sup, base: a("x"), sub: vec![], sup: a("2") }]); + // A delimiter has at least one element. + assert_eq!(round_trip(&vec![delim(Some('('), Some(')'), vec![])]), vec![delim(Some('('), Some(')'), vec![vec![]])]); + // A matrix gets one column alignment per column and rectangular rows (#3643). + let cells = vec![vec![a("a"), a("b")], vec![a("c")]]; + let padded = vec![vec![a("a"), a("b")], vec![a("c"), vec![]]]; + assert_eq!(round_trip(&vec![Matrix { rows: cells, col_jc: vec![] }]), vec![Matrix { rows: padded, col_jc: vec![ColJc::Center; 2] }]); + assert_eq!(round_trip(&vec![Matrix { rows: vec![], col_jc: vec![] }]), vec![Matrix { rows: vec![], col_jc: vec![ColJc::Center] }]); +} + +/// Every linear-format equation saves and reopens as the same tree, once matrices have their +/// column alignments filled in. +#[test] +fn linear_equations_survive_a_save() { + fn fill_col_jc(a: Arg) -> Arg { + a.into_iter() + .map(|n| match n { + MNode::Matrix { rows, col_jc } if col_jc.is_empty() => { + let cols = rows.iter().map(Vec::len).max().unwrap_or(0).max(1); + let rows = rows.into_iter().map(|row| row.into_iter().map(fill_col_jc).collect()).collect(); + MNode::Matrix { rows, col_jc: vec![ColJc::Center; cols] } + } + other => crate::math_linear::map_args(other, &fill_col_jc), + }) + .collect() + } + for s in [ + "x=(-b±√(b^2-4ac))/2a", + "〖a+b〗^2", + "├]a[┤", + "{█(x@y)┤", + "(a│b)", + "▭(a)+□(b)+¯(c)+▁(d)", + "⏞(a+b)+⏟(c+d)", + "⬚/⬚", + "a⁄b+a∕b+a¦b", + "_1^n▒Y", + "x┬k+x┴k", + "A⃗+x̂", + "log_2⁡x", + "lim┬(n→∞)⁡a_n", + ")a(", + "E=mc^2#(1)", + "■(a&b@c&d)", + "√(3&x)", + "∫_0^1▒f(x)dx", + "|x|+‖v‖", + ] { + let n = parse_linear(s); + assert_eq!(round_trip(&n), fill_col_jc(n.clone()), "{s} → {}", to_linear(&n)); + } +} + +// --- Where `write_equation` takes the equation from. -------------------------------------------- + +#[test] +fn kept_omml_is_written_back_unchanged() { + let kept = "KEPT"; + let m = Math { nodes: a("NODES"), omml: kept.into(), ..Default::default() }; + assert_eq!(write(&m, "linear", false, None), kept); +} + +#[test] +fn kept_xml_that_is_not_an_omath_is_rewritten_from_the_nodes() { + let m = Math { nodes: a("NODES"), omml: "X".into(), ..Default::default() }; + let out = write(&m, "linear", false, None); + assert_eq!(read(&out).nodes, a("NODES")); +} + +#[test] +fn without_nodes_the_linear_text_is_written() { + let out = write(&Math::default(), "a/b", false, None); + assert_eq!(read(&out).nodes, parse_linear("a/b")); + assert_eq!(write(&Math::default(), "", false, None), ""); +} + +#[test] +fn an_equation_colour_rewrites_the_kept_omml() { + let kept_red = r#"a"#; + let nodes = vec![r("a"), MNode::Run(MRun { color: Some(GREEN), ..MRun::new("g") })]; + let m = Math { nodes, omml: kept_red.into(), ..Default::default() }; + let colours = |c: Option| runs(&read(&write(&m, "", false, c)).nodes).into_iter().map(|r| (r.text, r.color)).collect::>(); + // The same colour keeps the source XML. + assert_eq!(write(&m, "", false, Some(RED)), kept_red); + // Another colour goes on every run without its own (#1467). + assert_eq!(colours(Some(BLUE)), vec![("a".to_string(), Some(BLUE)), ("g".to_string(), Some(GREEN))]); + // No colour takes the old one off. + assert_eq!(colours(None), vec![("a".to_string(), None), ("g".to_string(), Some(GREEN))]); +} + +#[test] +fn kept_omml_without_one_colour_is_kept_without_an_equation_colour() { + for kept in [ + "a", + r#"ab"#, + ] { + let m = Math { nodes: a("ab"), omml: kept.into(), ..Default::default() }; + assert_eq!(write(&m, "", false, None), kept); + } +} + +#[test] +fn display_justification_round_trips() { + for jc in [MathJc::CenterGroup, MathJc::Center, MathJc::Left, MathJc::Right] { + let out = write(&Math { nodes: a("x"), jc, ..Default::default() }, "", true, None); + assert_eq!(read(&out).jc, jc, "{out}"); + assert_eq!(out.contains("m:oMathParaPr"), jc != MathJc::CenterGroup, "{out}"); + } + assert!(!write(&math(a("x")), "", false, None).contains("oMathPara")); +} + +// --- Equation numbers. -------------------------------------------------------------------------- + +fn rows(rs: &[&str]) -> Math { + math(vec![MNode::EqArr { rows: rs.iter().map(|s| a(s)).collect() }]) +} + +#[test] +fn automatic_numbers_are_written_out() { + // A `#` with nothing after it gets the next number; a written number counts too, as in + // layout's `auto_numbers`. + let mut n = 0; + let out = resolve_numbers(&rows(&["a=b#", "c=d", "e=f#(9)", "g#"]), true, &mut n).unwrap(); + assert_eq!(n, 3); + assert_eq!(to_linear(&out.nodes), "█(a=b#(1)@c=d@e=f#(9)@g#(3))"); + assert!(out.omml.is_empty(), "the numbered copy is written from its nodes"); + // The counter carries on into the next equation. + let out = resolve_numbers(&rows(&["h#"]), true, &mut n).unwrap(); + assert_eq!((n, to_linear(&out.nodes)), (4, "h#(4)".to_string()), "a one-row array prints without █"); +} + +#[test] +fn equations_without_automatic_numbers_are_left_alone() { + let mut n = 5; + assert!(resolve_numbers(&rows(&["a=b#(7)"]), true, &mut n).is_none()); + assert_eq!(n, 6, "a written number still counts"); + let mut n = 0; + assert!(resolve_numbers(&rows(&["a#"]), false, &mut n).is_none(), "inline"); + assert!(resolve_numbers(&math(a("a=b#")), true, &mut n).is_none(), "not an equation array"); + let nested = math(vec![MNode::EqArr { rows: vec![vec![MNode::Frac { kind: FracKind::Bar, num: a("a#"), den: a("b") }]] }]); + assert!(resolve_numbers(&nested, true, &mut n).is_none(), "a # inside a structure isn't a number mark"); + assert_eq!(n, 0); +} + +// --- Settings: m:mathPr. ------------------------------------------------------------------------ + +fn math_pr_round_trip(m: &MathProps) -> MathProps { + let mut w = W::default(); + math_pr(&mut w, m); + let root = parse_kept(&w.s).unwrap(); + assert_eq!(root.name, "m:mathPr"); + crate::omml::read_math_pr(&root) +} + +#[test] +fn math_properties_round_trip() { + for m in [ + MathProps::default(), + MathProps { brk_bin: BrkBin::After, brk_bin_sub: BrkBinSub::PlusMinus, ..Default::default() }, + MathProps { brk_bin: BrkBin::Repeat, brk_bin_sub: BrkBinSub::MinusPlus, ..Default::default() }, + MathProps { wrap_indent: 0.0, ..Default::default() }, + MathProps { wrap_indent: 12.35, ..Default::default() }, + MathProps { wrap_right: true, ..Default::default() }, + ] { + assert_eq!(math_pr_round_trip(&m), m); + } +} + +#[test] +fn math_properties_are_clamped() { + let indent = |v: f32| math_pr_round_trip(&MathProps { wrap_indent: v, ..Default::default() }).wrap_indent; + assert_eq!(indent(5000.0), 1584.0); + assert_eq!(indent(-3.0), 0.0); + assert_eq!(indent(f32::NAN), crate::math::DEFAULT_WRAP_INDENT); + // `wrapIndent` and `wrapRight` are a choice: aligning right drops the indent. + let right = math_pr_round_trip(&MathProps { wrap_right: true, wrap_indent: 10.0, ..Default::default() }); + assert_eq!(right, MathProps { wrap_right: true, ..Default::default() }); +} + +// --- Limits. ------------------------------------------------------------------------------------ + +#[test] +fn matrix_caps_hold_on_save() { + let wide = vec![MNode::Matrix { rows: vec![vec![a("x"); MAX_MATRIX_COLS + 6]; 3], col_jc: vec![] }]; + let back = round_trip(&wide); + let [MNode::Matrix { rows, col_jc }] = &back[..] else { panic!("{back:?}") }; + assert_eq!((rows.len(), rows[0].len(), col_jc.len()), (3, MAX_MATRIX_COLS, MAX_MATRIX_COLS)); + let tall = vec![MNode::Matrix { rows: vec![vec![a("x")]; MAX_MATRIX_ROWS + 5], col_jc: vec![] }]; + let back = round_trip(&tall); + let [MNode::Matrix { rows, .. }] = &back[..] else { panic!("{back:?}") }; + assert_eq!(rows.len(), MAX_MATRIX_ROWS); +} + +fn fraction_chain(depth: usize) -> Arg { + let mut cur = a("LEAF"); + for _ in 0..depth { + cur = vec![MNode::Frac { kind: FracKind::Bar, num: cur, den: a("d") }]; + } + cur +} + +#[test] +fn a_tree_past_the_depth_cap_writes_well_formed_xml() { + for depth in [MAX_DEPTH, MAX_DEPTH + 1, 4 * MAX_DEPTH] { + let out = xml(&fraction_chain(depth)); + assert!(craft_xml::Options::default().strict().parse(out.as_bytes()).is_ok(), "depth {depth}"); + } + assert!(!xml(&fraction_chain(MAX_DEPTH + 1)).contains("LEAF"), "the writer stops at MAX_DEPTH"); +} + +// --- Golden XML: element order and what is left out. -------------------------------------------- + +const CTRL: &str = r#""#; + +/// `m:r` for `x` with no properties of its own. +fn rx(t: &str) -> String { + format!(r#"{t}"#) +} + +/// The golden string with `{C}` standing for [`CTRL`] and `{a}`… for [`rx`] runs. +fn expand(s: &str) -> String { + let mut out = s.replace("{C}", CTRL); + for t in ["a", "b", "c", "d", "x", "i", "n", "2", "3", "k"] { + out = out.replace(&format!("{{{t}}}"), &rx(t)); + } + format!("{out}") +} + +#[track_caller] +fn assert_golden(label: &str, nodes: Arg, expected: &str) { + assert_eq!(xml(&nodes), expand(expected), "{label}"); +} + +#[test] +fn golden_runs() { + assert_golden("plain run", a("x"), "{x}"); + let all = MRun { sty: Some(MSty::Bold), scr: MScr::Script, lit: true, brk: Some(2), color: Some(RED), size: Some(11.0), ..MRun::new("x") }; + assert_golden( + "every math run property", + vec![MNode::Run(all)], + r#"x"#, + ); + let nor = MRun { nor: true, font: Some("Arial".into()), brk: Some(0), ..MRun::new("x y") }; + assert_golden( + "normal text", + vec![MNode::Run(nor)], + r#"x y"#, + ); +} + +#[test] +fn golden_fractions_scripts_and_radicals() { + use MNode::*; + assert_golden( + "bar fraction", + vec![Frac { kind: FracKind::Bar, num: a("a"), den: a("b") }], + "{C}{a}{b}", + ); + assert_golden( + "skewed fraction, empty denominator", + vec![Frac { kind: FracKind::Skewed, num: a("a"), den: vec![] }], + r#"{C}{a}"#, + ); + assert_golden( + "sup", + vec![Script { kind: ScriptKind::Sup, base: a("x"), sub: vec![], sup: a("2") }], + "{C}{x}{2}", + ); + assert_golden( + "sub", + vec![Script { kind: ScriptKind::Sub, base: a("x"), sub: a("i"), sup: vec![] }], + "{C}{x}{i}", + ); + assert_golden( + "subsup", + vec![Script { kind: ScriptKind::SubSup, base: a("x"), sub: a("i"), sup: a("2") }], + "{C}{x}{i}{2}", + ); + // CT_SPre: sub, sup, then the base. + assert_golden( + "pre", + vec![Script { kind: ScriptKind::Pre, base: a("x"), sub: a("i"), sup: a("2") }], + "{C}{i}{2}{x}", + ); + assert_golden( + "square root", + vec![Rad { deg: vec![], deg_hide: true, e: a("x") }], + r#"{C}{x}"#, + ); + assert_golden( + "cube root", + vec![Rad { deg: a("3"), deg_hide: false, e: a("x") }], + "{C}{3}{x}", + ); +} + +#[test] +fn golden_operators_and_delimiters() { + use MNode::*; + let nary = |chr, lim_loc, on| Nary { chr, lim_loc, grow: on, sub_hide: on, sup_hide: on, sub: a("i"), sup: a("n"), e: a("x") }; + assert_golden( + "integral", + vec![nary('∫', None, false)], + "{C}{i}{n}{x}", + ); + assert_golden( + "sum, every property", + vec![nary('∑', Some(LimLoc::UndOvr), true)], + r#"{C}{i}{n}{x}"#, + ); + assert_golden("parentheses", vec![delim(Some('('), Some(')'), vec![a("x")])], "{C}{x}"); + assert_golden( + "delimiter, every property", + vec![Delim { beg: Some('['), end: None, sep: Some(';'), grow: false, shp_match: true, elems: vec![a("a"), a("b")] }], + r#"{C}{a}{b}"#, + ); + assert_golden( + "function", + vec![Func { name: a("a"), e: a("x") }], + "{C}{a}{x}", + ); + assert_golden( + "lower limit", + vec![Lim { upper: false, e: a("a"), lim: a("n") }], + "{C}{a}{n}", + ); + assert_golden( + "upper limit", + vec![Lim { upper: true, e: a("a"), lim: a("k") }], + "{C}{a}{k}", + ); +} + +#[test] +fn golden_accents_bars_and_boxes() { + use MNode::*; + assert_golden("accent", vec![Acc { chr: '\u{302}', e: a("x") }], "{C}{x}"); + assert_golden("overbar", vec![Bar { top: true, e: a("x") }], r#"{C}{x}"#); + assert_golden("underbar", vec![Bar { top: false, e: a("x") }], r#"{C}{x}"#); + assert_golden( + "border box", + vec![BorderBox { hide: [false; 4], strike: [false; 4], e: a("x") }], + "{C}{x}", + ); + assert_golden( + "border box, every property", + vec![BorderBox { hide: [true; 4], strike: [true; 4], e: a("x") }], + r#"{C}{x}"#, + ); + assert_golden("box", vec![Boxed { e: a("x") }], "{C}{x}"); + assert_golden( + "underbrace", + vec![GroupChr { chr: '\u{23DF}', top: false, e: a("x") }], + "{C}{x}", + ); + assert_golden( + "overbrace", + vec![GroupChr { chr: '\u{23DE}', top: true, e: a("x") }], + "{C}{x}", + ); + assert_golden( + "phantom", + vec![Phant { show: true, zero_wid: false, zero_asc: false, zero_desc: false, e: a("x") }], + r#"{C}{x}"#, + ); + assert_golden( + "phantom, every property", + vec![Phant { show: false, zero_wid: true, zero_asc: true, zero_desc: true, e: a("x") }], + r#"{C}{x}"#, + ); +} + +#[test] +fn golden_arrays() { + use MNode::*; + assert_golden("eqarr", vec![EqArr { rows: vec![a("a"), a("b")] }], "{C}{a}{b}"); + assert_golden( + "numbered eqarr", + vec![EqArr { rows: vec![vec![r("a"), r("#")]] }], + r#"{C}{a}#"#, + ); + assert_golden( + "matrix", + vec![Matrix { rows: vec![vec![a("a"), a("b")], vec![a("c")]], col_jc: vec![ColJc::Left] }], + r#"{C}{a}{b}{c}"#, + ); +} + +#[test] +fn golden_display_and_settings() { + let out = write(&Math { nodes: a("x"), jc: MathJc::Left, ..Default::default() }, "", true, None); + assert_eq!(out, format!(r#"{}"#, expand("{x}"))); + assert_eq!(write(&math(a("x")), "", true, None), format!("{}", expand("{x}"))); + let pr = |m: &MathProps| { + let mut w = W::default(); + math_pr(&mut w, m); + w.s + }; + assert_eq!(pr(&MathProps::default()), r#""#); + assert_eq!( + pr(&MathProps { brk_bin: BrkBin::After, brk_bin_sub: BrkBinSub::PlusMinus, wrap_right: true, ..Default::default() }), + r#""# + ); +} + +/// The run helper is used by every golden: a run with no properties is exactly `rx`. +#[test] +fn golden_helpers_match_the_writer() { + assert_eq!(xml(&a("x")), format!("{}", rx("x"))); + assert!(expand("{C}").contains("m:ctrlPr")); +}