craft-math: stacked scripts in the linear format nest to the right (port of wordcraft#6083)

a^b^c built (a^b)^c; Word builds a^(b^c), and the same for a_b_c and x^2^3. After a script
operand, the same script operator now nests inside it. The chain stops at WRAP_DEPTH like every
other wrap, so the #1456 guard holds. a_b^c, a^b_c and (a^b)^c are unchanged.

From the PR's review: sin^2^3 on the function-name path nests to the right too (script_chain for
the first script; a second script joins only when it is the other operator, log_2^3). A level that
would make the whole tree too deep keeps its operator as text, as expr does at its own cap, and a
^ or _ the chain left at its cap isn't taken as the start of a function's operand.

Ported from storytold/wordcraft#6083 (issue wordcraft#6074): its change to math_linear.rs and its
tests/stacked_scripts.rs, with only paths and crate names changed. Its typing test (engine) and
the docs/typing-parity.md note stay in WordCraft.
This commit is contained in:
kiwi4boy
2026-11-12 21:53:35 -05:00
parent 5056c13ef7
commit ef0f27a306
2 changed files with 126 additions and 7 deletions
+41 -7
View File
@@ -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 {
+85
View File
@@ -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<MNode> {
vec![MNode::Run(MRun::new(t))]
}
fn sup(base: Vec<MNode>, s: Vec<MNode>) -> MNode {
MNode::Script { kind: ScriptKind::Sup, base, sub: Vec::new(), sup: s }
}
fn sub(base: Vec<MNode>, s: Vec<MNode>) -> 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<MNode>| 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<MNode> = 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:?}");
}