diff --git a/crates/math/src/math_linear.rs b/crates/math/src/math_linear.rs index 39a25ab5d..fe8c8cd52 100644 --- a/crates/math/src/math_linear.rs +++ b/crates/math/src/math_linear.rs @@ -9,7 +9,9 @@ //! an operator or space; a parenthesised operand loses its parentheses). `^`/`_` with nothing //! before them are pre-scripts. A top-level `#` numbers the equation (`E=mc^2#(1)`). -use crate::math::{Arg, FracKind, MAX_DEPTH, MClass, MNode, MRun, ScriptKind, any_too_deep, is_nary_char, math_class, merge_runs, too_deep}; +use crate::math::{ + Arg, FracKind, MAX_DEPTH, MClass, MNode, MRun, ScriptKind, WRAP_DEPTH, any_too_deep, is_nary_char, math_class, merge_runs, too_deep, +}; /// Function names set upright and applied to the following operand. pub const FUNCTION_NAMES: &[&str] = &[ @@ -172,7 +174,7 @@ impl P { out.push(self.prescript(stops)); } else { self.i += 1; - let s = self.script_operand(stops); + let s = self.script_chain(c, stops, 0); if out.last().is_some_and(too_deep) { out.push(text(c)); out.extend(s); @@ -449,11 +451,14 @@ impl P { } Some(c @ ('^' | '_')) => { self.i += 1; - let s = self.script_operand(stops); + // `sin^2^3` nests to the right like any other script (#6074). + let s = self.script_chain(c, stops, 0); let mut n = attach_script(Some(MNode::Run(MRun::plain(word.clone()))), c == '^', s); - if let Some(c2 @ ('^' | '_')) = self.peek() { + // Only the other script joins it, and it nests the same way (`log_2^3`, `sin^2_a_b`); + // the same one again is what the chain left at its depth cap. + if let Some(c2 @ ('^' | '_')) = self.peek().filter(|&c2| c2 != c) { self.i += 1; - let s2 = self.script_operand(stops); + let s2 = self.script_chain(c2, stops, 0); n = attach_script(Some(n), c2 == '^', s2); } vec![n] @@ -465,7 +470,10 @@ impl P { self.i += 1; } let next = self.peek(); - let applies = next.is_some_and(|c| !stops.contains(&c) && !is_closer(c) && (!is_boundary(c) || c == '(' || matches!(c, '−' | '-' | '+'))); + // A `^`/`_` here is what the script chain left at its depth cap: text for `expr`, not an operand. + let applies = next.is_some_and(|c| { + !stops.contains(&c) && !is_closer(c) && !matches!(c, '^' | '_') && (!is_boundary(c) || c == '(' || matches!(c, '−' | '-' | '+')) + }); if !applies { return name; } @@ -584,7 +592,7 @@ impl P { } match c { '^' | '_' => { - let s = self.script_operand(stops); + let s = self.script_chain(c, stops, 0); let b = base(out); out.push(attach_script(b, c == '^', s)); } @@ -601,6 +609,32 @@ impl P { } } + /// A script operand, with the same script operator after it nested inside: `a^b^c` is + /// `a^(b^c)`, as Word builds it (#6074). The chain stops at `WRAP_DEPTH` like every other + /// wrap, so `x^1^1^1…` stays shallow (#1456) and the rest is left to the caller as text. The + /// cap holds for the whole tree too: when the operands are deep themselves, a level that would + /// make it too deep keeps its operator as text, as `expr` does. + fn script_chain(&mut self, op: char, stops: &[char], level: usize) -> Arg { + let s = self.script_operand(stops); + if self.peek() != Some(op) || s.is_empty() || level + 1 >= WRAP_DEPTH || self.tired() || any_too_deep(&s) { + return s; + } + self.i += 1; + self.depth += 1; + let inner = self.script_chain(op, stops, level + 1); + self.depth -= 1; + let (kind, sub, sup) = if op == '^' { (ScriptKind::Sup, Vec::new(), inner) } else { (ScriptKind::Sub, inner, Vec::new()) }; + let node = MNode::Script { kind, base: s, sub, sup }; + if !too_deep(&node) { + return vec![node]; + } + let MNode::Script { base: mut out, sub, sup, .. } = node else { return Vec::new() }; + out.push(text(op)); + out.extend(sub); + out.extend(sup); + out + } + /// A script or limit: a parenthesised group, a structure, a number, a signed operand, a run of /// letters (and digits) or one other character. fn script_operand(&mut self, stops: &[char]) -> Arg { diff --git a/crates/math/tests/stacked_scripts.rs b/crates/math/tests/stacked_scripts.rs new file mode 100644 index 000000000..9b3ffc3a2 --- /dev/null +++ b/crates/math/tests/stacked_scripts.rs @@ -0,0 +1,85 @@ +//! Stacked scripts in the linear format nest to the right, as Word builds them (#6074): the +//! superscript of `a^b^c` is `b^c`, so `a^b^c` is `a^(b^c)`. Mixed scripts still make one +//! sub-superscript, and brackets still group to the left. + +use craft_math::math::{MNode, MRun, ScriptKind, parse_linear}; + +fn a(t: &str) -> Vec { + vec![MNode::Run(MRun::new(t))] +} + +fn sup(base: Vec, s: Vec) -> MNode { + MNode::Script { kind: ScriptKind::Sup, base, sub: Vec::new(), sup: s } +} + +fn sub(base: Vec, s: Vec) -> MNode { + MNode::Script { kind: ScriptKind::Sub, base, sub: s, sup: Vec::new() } +} + +#[test] +fn stacked_scripts_nest_to_the_right() { + assert_eq!(parse_linear("a^b^c"), vec![sup(a("a"), vec![sup(a("b"), a("c"))])]); + assert_eq!(parse_linear("a_b_c"), vec![sub(a("a"), vec![sub(a("b"), a("c"))])]); + assert_eq!(parse_linear("x^2^3"), vec![sup(a("x"), vec![sup(a("2"), a("3"))])]); + assert_eq!(parse_linear("a^b^c^d"), vec![sup(a("a"), vec![sup(a("b"), vec![sup(a("c"), a("d"))])])]); +} + +#[test] +fn mixed_scripts_and_brackets_are_unchanged() { + // `a_b^c` and `a^b_c` are one sub-superscript, as in Word. + let subsup = vec![MNode::Script { kind: ScriptKind::SubSup, base: a("a"), sub: a("b"), sup: a("c") }]; + assert_eq!(parse_linear("a_b^c"), subsup); + let subsup = vec![MNode::Script { kind: ScriptKind::SubSup, base: a("a"), sub: a("c"), sup: a("b") }]; + assert_eq!(parse_linear("a^b_c"), subsup); + // Brackets group to the left, with a visible delimiter, as in Word. + let [MNode::Script { kind: ScriptKind::Sup, base, sup: c, .. }] = &parse_linear("(a^b)^c")[..] else { panic!() }; + assert_eq!(c, &a("c")); + assert!(matches!(&base[..], [MNode::Delim { beg: Some('('), elems, .. }] if elems[0] == vec![sup(a("a"), a("b"))]), "{base:?}"); +} + +#[test] +fn stacked_scripts_on_a_function_name_nest_to_the_right() { + let name = |s: &str| vec![MNode::Run(MRun::plain(s))]; + let func = |n: Vec| vec![MNode::Func { name: n, e: a("x") }]; + assert_eq!(parse_linear("sin^2^3 x"), func(vec![sup(name("sin"), vec![sup(a("2"), a("3"))])])); + assert_eq!(parse_linear("log_a_b x"), func(vec![sub(name("log"), vec![sub(a("a"), a("b"))])])); + // Mixed scripts on a name are still one sub-superscript. + let subsup = MNode::Script { kind: ScriptKind::SubSup, base: name("log"), sub: a("2"), sup: a("3") }; + assert_eq!(parse_linear("log_2^3 x"), func(vec![subsup])); + // The other script nests too, as `x^2_a_b` does, and `x` is still the operand. + let subsup = MNode::Script { kind: ScriptKind::SubSup, base: name("sin"), sub: vec![sub(a("a"), a("b"))], sup: a("2") }; + assert_eq!(parse_linear("sin^2_a_b x"), func(vec![subsup])); + let subsup = MNode::Script { kind: ScriptKind::SubSup, base: name("sin"), sub: a("a"), sup: vec![sup(a("2"), a("3"))] }; + assert_eq!(parse_linear("sin_a^2^3 x"), func(vec![subsup])); +} + +/// The whole chain stays within the parsers' depth cap (#1456), also when every operand is itself a +/// deep chain: the tree survives `serde_json` (its 128-level limit) and the rest is text. +#[test] +fn a_chain_of_deep_operands_stays_shallow() { + std::thread::Builder::new() + .stack_size(512 * 1024) + .spawn(|| { + let group = format!("({}c)", "b^".repeat(30)); + for s in [format!("a{}", format!("^{group}").repeat(40)), format!("sin{} x", format!("^{group}").repeat(40))] { + let n = parse_linear(&s); + let json = serde_json::to_string(&n).unwrap(); + let back: Vec = serde_json::from_str(&json).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(back, n); + } + }) + .unwrap() + .join() + .unwrap(); +} + +/// A script operator the chain leaves at its cap stays text: it isn't taken as a function's operand. +#[test] +fn an_operator_left_at_the_cap_is_not_a_function_operand() { + let n = parse_linear(&format!("sin{} x", "^1".repeat(40))); + let operand_starts_with_a_script = |n: &MNode| match n { + MNode::Func { e, .. } => matches!(e.first(), Some(MNode::Run(r)) if r.text.starts_with(['^', '_'])), + _ => false, + }; + assert!(!n.iter().any(operand_starts_with_a_script), "{n:?}"); +}