Skip to main content

himari/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2
3//! himari core: dimensioned IR / symbolic differentiation / matrix and linear solving / CSE /
4//! Rust emitter.
5//!
6//! LaTeX, matex and paper glyphs are each lowered by a front end into the same IR; this crate
7//! does not guess dialects, it only does algebra, checking, evaluation and code generation.
8
9extern crate alloc;
10#[cfg(test)]
11extern crate std;
12
13#[cfg(test)]
14use std::prelude::v1::*;
15
16pub mod i18n;
17
18pub use i18n::Error;
19pub use i18n::ReservedReason;
20mod math;
21pub mod runtime;
22pub mod wgsl;
23
24/// Fractional part, available in both std and no_std builds.
25pub fn math_fract(value: f64) -> f64 {
26    math::fract(value)
27}
28
29use alloc::boxed::Box;
30use alloc::collections::{BTreeMap, BTreeSet};
31use alloc::format;
32use alloc::string::{String, ToString};
33use alloc::vec;
34use alloc::vec::Vec;
35use core::fmt::Write as _;
36#[cfg(feature = "std")]
37pub use std::collections::HashMap;
38
39#[cfg(not(feature = "std"))]
40pub type HashMap<K, V> = BTreeMap<K, V>;
41
42// ---------------------------------------------------------------- errors
43
44/// Unified front-end error. `line == 0` means "no position" (e.g. a purely semantic error).
45///
46/// The error is identified by a stable code ([`Error::code`]), not by a sentence: `msg` is the
47/// rendering for the locale that was requested (English by default), and `code` is what tests
48/// and callers match on. Messages that have not been catalogued yet carry
49/// `code == Error::Message(..)` with their original text — an explicit staging marker, not a
50/// silent fallback.
51#[derive(Clone, Debug, PartialEq)]
52pub struct FrontError {
53    pub line: usize,
54    pub col: usize,
55    /// Rendering in [`i18n::Locale::En`] unless [`FrontError::in_locale`] produced a copy.
56    pub msg: String,
57    pub code: Box<i18n::Error>,
58    /// Substituted arguments, kept so the message can be re-rendered in another language.
59    args: Vec<String>,
60}
61
62impl FrontError {
63    pub fn new(line: usize, col: usize, msg: impl Into<Error>) -> Self {
64        // Same rule as `plain`: a catalogued error keeps its variant across the front-end, so
65        // `code()` still identifies the failure at the CLI/LSP edges; only a raw string lands as
66        // `Message`.
67        let error: Error = msg.into();
68        let rendered = error.render(i18n::Locale::En);
69        Self {
70            line,
71            col,
72            msg: rendered,
73            code: Box::new(error),
74            args: Vec::new(),
75        }
76    }
77
78    pub fn plain(msg: impl Into<Error>) -> Self {
79        // Keep the variant: a front-end that wraps a catalogued error must not downgrade it to
80        // `Message`, or `code()` would stop identifying the failure once it crosses the parser.
81        let error: Error = msg.into();
82        let msg = error.render(i18n::Locale::En);
83        Self {
84            line: 0,
85            col: 0,
86            msg,
87            code: Box::new(error),
88            args: Vec::new(),
89        }
90    }
91
92    /// A catalogued error: the message is rendered from the code and its arguments.
93    ///
94    /// The arguments are kept, so [`FrontError::in_locale`] can re-render the same error in
95    /// any of the nine languages without the caller having to hold them again.
96    pub fn coded(code: i18n::Error, args: &[&str], line: usize, col: usize) -> Self {
97        Self {
98            line,
99            col,
100            msg: i18n::render(&code, args, i18n::Locale::En),
101            code: Box::new(code),
102            args: args.iter().map(|a| a.to_string()).collect(),
103        }
104    }
105
106    /// Renders this error in `language`. Uncatalogued (`Raw`) errors keep their text.
107    pub fn render_in(&self, language: i18n::Locale) -> String {
108        // Composed variants are handled inside `i18n::render` itself (it recomputes the inner
109        // error at the target locale instead of using stored arguments), so this method stays a
110        // single delegation: one home for the composition rule, not two.
111        let borrowed: Vec<&str> = self.args.iter().map(|a| a.as_str()).collect();
112        i18n::render(&self.code, &borrowed, language)
113    }
114
115    /// Convenience: a copy whose `msg` is rendered in `language`.
116    pub fn in_locale(&self, language: i18n::Locale) -> Self {
117        let mut out = self.clone();
118        out.msg = self.render_in(language);
119        out
120    }
121
122    /// Convenience: a copy rendered in `HIMARI_LANG`/`LC_ALL`/`LANG`, or English under `no_std`.
123    pub fn localized(&self) -> Self {
124        #[cfg(feature = "std")]
125        {
126            self.in_locale(i18n::Locale::from_env())
127        }
128        #[cfg(not(feature = "std"))]
129        {
130            self.clone()
131        }
132    }
133
134    /// Contextual rendering: source line + caret.
135    ///
136    /// Given only `line:col`, the user has to count by hand which character is in column 17;
137    /// quoting that line and drawing a `^` under the position is an editor-grade experience,
138    /// and it costs only a few lines of code.
139    pub fn render_with_source(&self, origin: &str, src: &str) -> String {
140        let head = self.render(origin);
141        if self.line == 0 {
142            return head;
143        }
144        let Some(text) = src.lines().nth(self.line - 1) else {
145            return head;
146        };
147        let gutter = format!("{}", self.line);
148        let pad = " ".repeat(gutter.len());
149        // A tab counts as one character (column numbers are counted that way too); the caret's
150        // indentation matches the display width
151        let mut caret = String::new();
152        for ch in text.chars().take(self.col.saturating_sub(1)) {
153            caret.push(if ch == '\t' { '\t' } else { ' ' });
154        }
155        format!("{head}\n{pad} |\n{gutter} | {text}\n{pad} | {caret}^")
156    }
157
158    pub fn render(&self, origin: &str) -> String {
159        if self.line == 0 {
160            format!("{origin}: {}", self.msg)
161        } else {
162            format!("{origin}:{}:{}: {}", self.line, self.col, self.msg)
163        }
164    }
165}
166
167impl From<Error> for FrontError {
168    // Exactly `plain` with an already-typed argument: the variant is kept, so `code()` still
169    // identifies the failure. This is the spelling `map_err`/`?` must use for already-catalogued
170    // errors (`map_err(FrontError::from)`), so the staging-budget gate can tell a typed
171    // conversion from the string-keeping funnel (`FrontError::plain` as a function reference,
172    // which the gate counts). `plain`'s body is inlined here on purpose: a delegation would be
173    // `Self::plain(<runtime value>)`, the exact funnel shape the gate exists to catch.
174    fn from(code: Error) -> Self {
175        let msg = code.render(i18n::Locale::En);
176        Self {
177            line: 0,
178            col: 0,
179            msg,
180            code: Box::new(code),
181            args: Vec::new(),
182        }
183    }
184}
185
186// ---------------------------------------------------------------- declarations
187
188/// Formula symbol declaration. **The dimension must be given explicitly** — this is where this
189/// scheme pins down LaTeX's semantic ambiguity.
190#[derive(Clone, Debug, PartialEq, Eq)]
191pub struct Decl {
192    pub name: String,
193    pub quantity: String,
194    pub unit: Option<String>,
195}
196
197// ---------------------------------------------------------------- dimensions
198
199/// The 7 base quantities: kg, m, s, A, K, mol, cd.
200///
201/// **Stored internally in units of 1/2** (half-units): each number in `[i16; 7]` is twice the
202/// real exponent (`s^-1/2` is stored as `-1`, `s^-1` as `-2`). This way fractional powers
203/// (√, ^(1/2), ^(3/2)) and integer powers go through the same integer arithmetic, with no need
204/// to introduce a rational type; divide by 2 again when displaying.
205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub struct Dim(pub [i16; 7]);
207
208impl Dim {
209    pub const ZERO: Dim = Dim([0; 7]);
210
211    /// Construct from integer exponents (external API semantics: real exponents).
212    pub fn from_exponents(exps: [i16; 7]) -> Dim {
213        Dim(exps.map(|e| e * 2))
214    }
215
216    /// Real exponents (for display/diagnostics); fractional exponents are truncated to i16 pairs,
217    /// so the caller must handle the half itself.
218    pub fn exponents(&self) -> [i16; 7] {
219        self.0.map(|e| e / 2)
220    }
221
222    pub fn is_zero(&self) -> bool {
223        self.0.iter().all(|v| *v == 0)
224    }
225
226    fn mul_dim(self, o: Dim) -> Dim {
227        let mut r = self.0;
228        for (a, b) in r.iter_mut().zip(o.0) {
229            *a += b;
230        }
231        Dim(r)
232    }
233
234    fn div_dim(self, o: Dim) -> Dim {
235        let mut r = self.0;
236        for (a, b) in r.iter_mut().zip(o.0) {
237            *a -= b;
238        }
239        Dim(r)
240    }
241
242    /// Rational scaling by `p/q` (the `s^(-1/2)` inside a unit string).
243    ///
244    /// If it does not divide evenly, report an error: dimension exponents are **half-lattice
245    /// integers**, `m^(1/3)` does not exist in this algebra — better to reject than to round off a
246    /// fake dimension.
247    pub fn scale_ratio(self, p: i32, q: i32) -> Result<Dim, Error> {
248        if q == 0 {
249            return Err(Error::ExponentZeroDenominator {
250                exponent: format!("{p}/{q}"),
251            });
252        }
253        let mut r = [0i16; 7];
254        for (out, v) in r.iter_mut().zip(self.0) {
255            // i64 intermediate + range check: i32 multiplication overflows (`m^(2000000000)` used
256            // to panic outright in debug and silently wrap into a **wrong dimension** in release).
257            let prod = v as i64 * p as i64;
258            if prod % q as i64 != 0 {
259                return Err(Error::ExponentNotHalfInteger(format!("{p}/{q}")));
260            }
261            let scaled = prod / q as i64;
262            *out = i16::try_from(scaled).map_err(|_| Error::ExponentOutOfRange {
263                exponent: format!("{p}/{q}"),
264            })?;
265        }
266        Ok(Dim(r))
267    }
268
269    pub fn display(&self) -> String {
270        const NAMES: [&str; 7] = ["kg", "m", "s", "A", "K", "mol", "cd"];
271        if self.is_zero() {
272            return "1".to_string();
273        }
274        let mut parts = Vec::new();
275        for (i, n) in NAMES.iter().enumerate() {
276            let half = self.0[i];
277            if half == 0 {
278                continue;
279            }
280            if half % 2 == 0 {
281                let e = half / 2;
282                if e == 1 {
283                    parts.push((*n).to_string());
284                } else {
285                    parts.push(format!("{n}^{e}"));
286                }
287            } else {
288                // Half-lattice: write it as `s^(-7/2)` / `s^(1/2)` (with parentheses, so it is
289                // not read as s^-7 then divided by 2)
290                parts.push(format!("{n}^({half}/2)"));
291            }
292        }
293        parts.join("·")
294    }
295}
296
297/// A unit (dimension + conversion factor to SI base units).
298///
299/// The dimension is a **promise**, the conversion is a **convenience**: the two are stored
300/// separately because "`nF` and `F` have the same dimension" and "`1 nF = 1e-9 F`" are two
301/// different things. `dim_check` uses only `dim`; `convert` uses both.
302#[derive(Clone, Copy, Debug, PartialEq)]
303pub struct UnitSpec {
304    pub dim: Dim,
305    /// Multiplier from this unit to SI base units (`nF` → 1e-9; `kg` → 1).
306    pub scale: f64,
307}
308
309/// SI prefixes (including their symbols), with longer prefixes matched first
310/// (`daN` = daN, not d·aN).
311const SI_PREFIXES: &[(&str, f64)] = &[
312    ("da", 1e1),
313    ("Q", 1e30),
314    ("R", 1e27),
315    ("r", 1e-27),
316    ("q", 1e-30),
317    ("Y", 1e24),
318    ("Z", 1e21),
319    ("E", 1e18),
320    ("P", 1e15),
321    ("T", 1e12),
322    ("G", 1e9),
323    ("M", 1e6),
324    ("k", 1e3),
325    ("h", 1e2),
326    ("d", 1e-1),
327    ("c", 1e-2),
328    ("m", 1e-3),
329    ("\u{00b5}", 1e-6),
330    ("\u{03bc}", 1e-6),
331    ("n", 1e-9),
332    ("p", 1e-12),
333    ("f", 1e-15),
334    ("a", 1e-18),
335    ("z", 1e-21),
336    ("y", 1e-24),
337];
338
339/// Prefixed unit name → (dimension, conversion factor).
340///
341/// The lookup order is **first the full name, then prefix splitting**: `m` is metre and not
342/// "milli-nothing", `mol` is mole and not "milli-ol", `cd` is candela and not "centi-d". When
343/// splitting prefixes, longer prefixes win, so `daN` is ten newtons and `daPa` is ten pascals.
344/// Known but **deliberately rejected** units: offsets (°C/°F) and logarithmic ones (the dB family).
345///
346/// This must be blocked before prefix splitting: otherwise `degC` gets split into prefix + unknown
347/// remainder and reports "unknown unit", pointing people the wrong way — the real cause is "this
348/// unit has no multiplicative dimension".
349fn rejected_unit(name: &str) -> Option<Error> {
350    match name {
351        "degC" | "Celsius" | "degF" | "Fahrenheit" | "degR" => {
352            Some(Error::OffsetUnit(name.to_string()))
353        }
354        "dB" | "dBm" | "dBW" | "dBV" | "neper" => Some(Error::LogUnit(name.to_string())),
355        // Ambiguous symbols are rejected instead of silently picking one reading:
356        // thermochemical (4.184 J) and IT (4.1868 J) calories differ, and `rpm`
357        // would collapse the angle axis that `rad` deliberately keeps dimensionless.
358        "cal" | "Cal" => Some(Error::AmbiguousUnit {
359            name: name.to_string(),
360            why: "cal_th = 4.184 J and cal_IT = 4.1868 J differ".to_string(),
361            remedy: "write the J value explicitly".to_string(),
362        }),
363        "rpm" => Some(Error::AmbiguousUnit {
364            name: name.to_string(),
365            why: "1 rpm = 2*pi/60 rad/s, and rad is dimensionless here".to_string(),
366            remedy: "write `2 * pi * f` with f declared in Hz".to_string(),
367        }),
368        _ => None,
369    }
370}
371
372fn prefixed_unit(name: &str) -> Result<(Dim, f64), Error> {
373    if let Some(error) = rejected_unit(name) {
374        return Err(error);
375    }
376    if let Ok(hit) = unit_base(name) {
377        return Ok(hit);
378    }
379    for (pfx, k) in SI_PREFIXES {
380        if let Some(rest) = name.strip_prefix(pfx) {
381            if rest.is_empty() {
382                continue;
383            }
384            if let Ok((d, base_scale)) = unit_base(rest) {
385                return Ok((d, *k * base_scale));
386            }
387        }
388    }
389    Err(Error::UnknownUnit(name.to_string()))
390}
391
392fn unit_base(name: &str) -> Result<(Dim, f64), Error> {
393    // The table holds **real exponents**; Dim stores half-lattice internally, hence from_exponents
394    let d = |a: [i16; 7]| Dim::from_exponents(a);
395    let one = |a: [i16; 7]| (d(a), 1.0f64);
396    Ok(match name {
397        // Base and derived SI units. `1` at the end of the arm is the factor to
398        // the SI base unit; grams are the one exception (1 g = 1e-3 kg).
399        "kg" => one([1, 0, 0, 0, 0, 0, 0]),
400        "g" => (d([1, 0, 0, 0, 0, 0, 0]), 1e-3),
401        "m" => one([0, 1, 0, 0, 0, 0, 0]),
402        "s" => one([0, 0, 1, 0, 0, 0, 0]),
403        "A" => one([0, 0, 0, 1, 0, 0, 0]),
404        "K" => one([0, 0, 0, 0, 1, 0, 0]),
405        "mol" => one([0, 0, 0, 0, 0, 1, 0]),
406        "cd" => one([0, 0, 0, 0, 0, 0, 1]),
407        "V" => one([1, 2, -3, -1, 0, 0, 0]),
408        "N" => one([1, 1, -2, 0, 0, 0, 0]),
409        "J" => one([1, 2, -2, 0, 0, 0, 0]),
410        "W" => one([1, 2, -3, 0, 0, 0, 0]),
411        "C" => one([0, 0, 1, 1, 0, 0, 0]),
412        "Pa" => one([1, -1, -2, 0, 0, 0, 0]),
413        "Hz" => one([0, 0, -1, 0, 0, 0, 0]),
414        // Derived units electronics cannot avoid: without them EIS is limited to V/A.
415        "F" => one([-1, -2, 4, 2, 0, 0, 0]),
416        "\u{03a9}" | "ohm" => one([1, 2, -3, -2, 0, 0, 0]),
417        "S" => one([-1, -2, 3, 2, 0, 0, 0]),
418        "H" => one([1, 2, -2, -2, 0, 0, 0]),
419        "Wb" => one([1, 2, -2, -1, 0, 0, 0]),
420        "T" => one([1, 0, -2, -1, 0, 0, 0]),
421        "rad" | "1" | "sr" => (Dim::ZERO, 1.0),
422        // Non-SI units with exact definitions (BIPM SI Brochure 9th edition).
423        // Each entry carries its own factor so `convert` stays dimensionally honest.
424        "min" => (d([0, 0, 1, 0, 0, 0, 0]), 60.0),
425        "h" => (d([0, 0, 1, 0, 0, 0, 0]), 3600.0),
426        "d" => (d([0, 0, 1, 0, 0, 0, 0]), 86400.0),
427        "L" | "l" => (d([0, 3, 0, 0, 0, 0, 0]), 1e-3),
428        "deg" => (Dim::ZERO, core::f64::consts::PI / 180.0),
429        "arcmin" => (Dim::ZERO, core::f64::consts::PI / 10_800.0),
430        "arcsec" => (Dim::ZERO, core::f64::consts::PI / 648_000.0),
431        "bar" => (d([1, -1, -2, 0, 0, 0, 0]), 1e5),
432        "atm" => (d([1, -1, -2, 0, 0, 0, 0]), 101_325.0),
433        "eV" => (d([1, 2, -2, 0, 0, 0, 0]), 1.602_176_634e-19),
434        "Wh" => (d([1, 2, -2, 0, 0, 0, 0]), 3600.0),
435        "tonne" => (d([1, 0, 0, 0, 0, 0, 0]), 1000.0),
436        "Da" | "u" => (d([1, 0, 0, 0, 0, 0, 0]), 1.660_539_068_92e-27),
437        "nmi" => (d([0, 1, 0, 0, 0, 0, 0]), 1852.0),
438        "knot" => (d([0, 1, -1, 0, 0, 0, 0]), 1852.0 / 3600.0),
439        "ha" => (d([0, 2, 0, 0, 0, 0, 0]), 1e4),
440        "acre" => (d([0, 2, 0, 0, 0, 0, 0]), 4_046.856_422_4),
441        other => return Err(Error::UnknownUnit(other.to_string())),
442    })
443}
444
445/// Fractional exponent `-1/2` / `1/2` / `3` → (numerator, denominator).
446fn parse_ratio(s: &str) -> Result<(i32, i32), Error> {
447    let (n, d) = match s.trim().split_once('/') {
448        Some((n, d)) => (n, d),
449        None => (s.trim(), "1"),
450    };
451    let n: i32 = n.trim().parse().map_err(|_| {
452        Error::MalformedUnit(
453            s.trim().to_string(),
454            "exponent numerator is not an integer".into(),
455        )
456    })?;
457    let d: i32 = d.trim().parse().map_err(|_| {
458        Error::MalformedUnit(
459            s.trim().to_string(),
460            "exponent denominator is not an integer".into(),
461        )
462    })?;
463    if d == 0 {
464        return Err(Error::ExponentZeroDenominator {
465            exponent: s.trim().to_string(),
466        });
467    }
468    Ok((n, d))
469}
470
471/// Parse unit strings such as `A/m^2`, `kg*m/s^2`, `V/A*s^(-1/2)`.
472pub fn parse_unit(src: &str) -> Result<Dim, Error> {
473    Ok(parse_unit_spec(src)?.dim)
474}
475
476/// Parse a unit string, yielding both the dimension and the conversion factor
477/// (`nF` → (C/V, 1e-9)).
478pub fn parse_unit_spec(src: &str) -> Result<UnitSpec, Error> {
479    let src = src.trim();
480    if src.is_empty() {
481        return Err(Error::MalformedUnit(
482            String::new(),
483            "empty unit string".into(),
484        ));
485    }
486    // Only ASCII plus two micro signs are allowed (U+00B5 / U+03BC)
487    if let Some(c) = src
488        .chars()
489        .find(|c| !c.is_ascii() && !matches!(*c, '\u{00b5}' | '\u{03bc}' | '\u{03a9}' | '\u{00b7}'))
490    {
491        return Err(Error::MalformedUnit(
492            src.to_string(),
493            format!("invalid character `{c}`"),
494        ));
495    }
496    let mut acc = Dim::ZERO;
497    let mut scale = 1.0f64;
498    let mut op = '*';
499    let mut atom = String::new();
500    let flush = |acc: &mut Dim, scale: &mut f64, op: char, atom: &mut String| {
501        if atom.is_empty() {
502            return Err(Error::MalformedUnit(
503                src.to_string(),
504                "empty component".into(),
505            ));
506        }
507        // Exponents accept rationals p/q: `s^(-1/2)` (the textbook unit of the Warburg
508        // coefficient).
509        // The token-macro lane renders punctuation with surrounding spaces, so
510        // `[m^2]` arrives as `m ^ 2 `. Trim before lookup, otherwise every
511        // multi-atom unit becomes "unknown unit `m `" and the formula cannot build.
512        let atom_trimmed = atom.trim().to_string();
513        let (name, p, q) = match atom_trimmed.split_once('^') {
514            Some((n, e)) => {
515                // `s^(-1/2)`: the parentheses are required, otherwise the `/` inside the exponent
516                // cannot be told apart from the unit string's
517                // division sign (the tokenizer only recognizes operators outside parentheses)
518                let e = e.trim();
519                let e = e
520                    .strip_prefix('(')
521                    .and_then(|x| x.strip_suffix(')'))
522                    .unwrap_or(e);
523                let (p, q) = parse_ratio(e)?;
524                (n.trim(), p, q)
525            }
526            None => (atom_trimmed.as_str(), 1, 1),
527        };
528        let (d, k) = prefixed_unit(name)?;
529        let d = d.scale_ratio(p, q)?;
530        // The conversion factor is scaled by the exponent p/q: `(mm)^2` = (1e-3)² = 1e-6
531        let k = math::powf(k, p as f64 / q as f64);
532        *acc = if op == '/' {
533            acc.div_dim(d)
534        } else {
535            acc.mul_dim(d)
536        };
537        *scale = if op == '/' { *scale / k } else { *scale * k };
538        atom.clear();
539        Ok(())
540    };
541    let mut depth = 0i32;
542    for c in src.chars() {
543        match c {
544            '(' => {
545                depth += 1;
546                atom.push(c);
547            }
548            ')' => {
549                depth -= 1;
550                if depth < 0 {
551                    return Err(Error::MalformedUnit(
552                        src.to_string(),
553                        "unbalanced `(`".to_string(),
554                    ));
555                }
556                atom.push(c);
557            }
558            // `·` (U+00B7) is the separator `Dim::display` emits: what is written back must be
559            // readable again,
560            // otherwise "write the display result into a decl" is a broken path
561            '/' | '*' | '\u{00b7}' if depth == 0 => {
562                flush(&mut acc, &mut scale, op, &mut atom)?;
563                op = if c == '/' { '/' } else { '*' };
564            }
565            _ => atom.push(c),
566        }
567    }
568    if depth != 0 {
569        return Err(Error::MalformedUnit(
570            src.to_string(),
571            "unbalanced `(`".to_string(),
572        ));
573    }
574    flush(&mut acc, &mut scale, op, &mut atom)?;
575    Ok(UnitSpec { dim: acc, scale })
576}
577
578/// Unit-aware conversion: `convert(1.0, "nF", "F") == 1e-9`.
579///
580/// Different dimensions → error (no "guessing what you meant to convert"). The inputs of
581/// generated code are always **SI base units**,
582/// conversion happens only at the boundary (reading data / writing reports); hiding the
583/// conversion inside the formula is exactly where dimension accidents come from.
584pub fn convert(value: f64, from: &str, to: &str) -> Result<f64, Error> {
585    let a = parse_unit_spec(from)?;
586    let b = parse_unit_spec(to)?;
587    if a.dim != b.dim {
588        return Err(Error::IncompatibleUnits {
589            from: from.to_string(),
590            to: to.to_string(),
591            from_dim: a.dim.display().to_string(),
592            to_dim: b.dim.display().to_string(),
593        });
594    }
595    Ok(value * a.scale / b.scale)
596}
597
598// ---------------------------------------------------------------- dimensional analysis (Buckingham Π)
599
600/// Exact rationals (used by Gaussian elimination).
601///
602/// Why not `f64`: dimension exponents are half-lattice integers, and `f64` elimination leaves
603/// residue at the 1e-17 level,
604/// so judgments like "this combination is dimensionless" start drifting at random. The dimension
605/// is a promise,
606/// so the judgment must be **exact**.
607#[derive(Clone, Copy, Debug, PartialEq)]
608struct Rat(i128, i128);
609
610impl Rat {
611    fn new(n: i128, d: i128) -> Rat {
612        assert!(d != 0, "有理数分母为零");
613        let g = gcd(n, d);
614        let (n, d) = (n / g, d / g);
615        if d < 0 {
616            Rat(-n, -d)
617        } else {
618            Rat(n, d)
619        }
620    }
621    fn zero() -> Rat {
622        Rat(0, 1)
623    }
624    fn is_zero(self) -> bool {
625        self.0 == 0
626    }
627    fn sub(self, o: Rat) -> Rat {
628        Rat::new(self.0 * o.1 - o.0 * self.1, self.1 * o.1)
629    }
630    fn mul(self, o: Rat) -> Rat {
631        Rat::new(self.0 * o.0, self.1 * o.1)
632    }
633    fn div(self, o: Rat) -> Rat {
634        Rat::new(self.0 * o.1, self.1 * o.0)
635    }
636    fn to_f64(self) -> f64 {
637        self.0 as f64 / self.1 as f64
638    }
639}
640
641#[cfg(test)]
642fn contains_pow_of(e: &Expr, name: &str, k: f64) -> bool {
643    match e {
644        Expr::Pow(a, b) => {
645            (matches!(a.as_ref(), Expr::Var(n) if n == name)
646                && matches!(b.as_ref(), Expr::Num(v) if *v == k))
647                || contains_pow_of(a, name, k)
648                || contains_pow_of(b, name, k)
649        }
650        Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) => {
651            contains_pow_of(a, name, k) || contains_pow_of(b, name, k)
652        }
653        Expr::Neg(a)
654        | Expr::Transpose(a)
655        | Expr::Grad(a)
656        | Expr::Laplacian(a)
657        | Expr::Deriv(a, _) => contains_pow_of(a, name, k),
658        Expr::Call(_, args) => args.iter().any(|a| contains_pow_of(a, name, k)),
659        Expr::Mat(rows) => rows.iter().flatten().any(|c| contains_pow_of(c, name, k)),
660        Expr::MatPattern(p) => p
661            .elements()
662            .into_iter()
663            .any(|c| contains_pow_of(c, name, k)),
664        Expr::Sum {
665            lower, upper, body, ..
666        }
667        | Expr::Integral {
668            lower, upper, body, ..
669        } => {
670            contains_pow_of(lower, name, k)
671                || contains_pow_of(upper, name, k)
672                || contains_pow_of(body, name, k)
673        }
674        _ => false,
675    }
676}
677
678fn gcd(a: i128, b: i128) -> i128 {
679    let (mut a, mut b) = (a.abs(), b.abs());
680    while b != 0 {
681        let t = a % b;
682        a = b;
683        b = t;
684    }
685    if a == 0 {
686        1
687    } else {
688        a
689    }
690}
691
692/// Dimension → exponents of the 7 base quantities (rationals; half-lattice means `/2`).
693fn dim_rat(d: Dim) -> Vec<Rat> {
694    d.0.iter().map(|h| Rat::new(*h as i128, 2)).collect()
695}
696
697/// Row-reduced echelon form of a 7×(n+1) augmented matrix. Returns
698/// (matrix, pivot columns, consistent).
699// The column index `j` is the **semantic index** of the elimination (row swaps are done by column
700// within one row), not a single-set iteration.
701#[allow(clippy::needless_range_loop)]
702fn rref_aug(mut a: Vec<Vec<Rat>>) -> (Vec<Vec<Rat>>, Vec<usize>, bool) {
703    let rows = a.len();
704    let cols = a.first().map(|r| r.len()).unwrap_or(0);
705    let mut pivots: Vec<usize> = Vec::new();
706    let mut r = 0usize;
707    for c in 0..cols.saturating_sub(1) {
708        if r == rows {
709            break;
710        }
711        let Some(p) = (r..rows).find(|&i| !a[i][c].is_zero()) else {
712            continue;
713        };
714        a.swap(r, p);
715        let inv = a[r][c];
716        for j in c..cols {
717            a[r][j] = a[r][j].div(inv);
718        }
719        for i in 0..rows {
720            if i != r && !a[i][c].is_zero() {
721                let f = a[i][c];
722                for j in c..cols {
723                    let sub = f.mul(a[r][j]);
724                    a[i][j] = a[i][j].sub(sub);
725                }
726            }
727        }
728        pivots.push(c);
729        r += 1;
730    }
731    let consistent = !(0..rows).any(|i| {
732        (0..cols.saturating_sub(1)).all(|j| a[i][j].is_zero()) && !a[i][cols - 1].is_zero()
733    });
734    (a, pivots, consistent)
735}
736
737/// Dimensionless groups (Buckingham Π theorem).
738///
739/// Given a set of "variable name + dimension", returns a **basis** of dimensionless
740/// combinations: each element is the exponent vector of the variables (rationals; this facility
741/// goes only down to half-integers); multiplying/dividing the variables by those exponents yields
742/// a pure number.
743/// The number of groups = number of variables − rank of the exponent matrix (the conclusion of the
744/// Π theorem itself, used as an assertion in tests).
745pub fn dimensionless_groups(vars: &[(String, Dim)]) -> Result<Vec<Vec<f64>>, Error> {
746    if vars.is_empty() {
747        return Err(Error::InvalidInput(
748            "dimensionless groups need at least one variable".into(),
749        ));
750    }
751    let n = vars.len();
752    // 7×n exponent matrix + a redundant all-zero augmented column (to reuse the same rref)
753    let mut a: Vec<Vec<Rat>> = (0..7)
754        .map(|row| {
755            let mut r: Vec<Rat> = vars.iter().map(|(_, d)| dim_rat(*d)[row]).collect();
756            r.push(Rat::zero());
757            r
758        })
759        .collect();
760    let (red, pivots, _) = rref_aug(core::mem::take(&mut a));
761    let mut basis: Vec<Vec<f64>> = Vec::new();
762    for f in 0..n {
763        if pivots.contains(&f) {
764            continue;
765        }
766        // Set the free variable f to 1 and back-substitute the pivot variables
767        let mut x = vec![0.0f64; n];
768        x[f] = 1.0;
769        for (i, &pc) in pivots.iter().enumerate() {
770            x[pc] = -red[i][f].to_f64();
771        }
772        // Sign normalization: the sign of a basis vector is representational redundancy (both Π
773        // and its reciprocal are legal groups),
774        // so pinning "the first non-zero exponent is positive" makes the output deterministic and
775        // comparable.
776        if x.iter().find(|e| **e != 0.0).is_some_and(|e| *e < 0.0) {
777            for e in x.iter_mut() {
778                *e = -*e;
779            }
780        }
781        basis.push(x);
782    }
783    Ok(basis)
784}
785
786/// Decide "can the target dimension be formed by multiplying/dividing powers of these
787/// variables?", and if so give one set of exponents.
788///
789/// This and `dimensionless_groups` are two uses of the same system of equations: one solves the
790/// homogeneous case
791/// (forming a dimensionless group), the other the inhomogeneous case (forming the target
792/// dimension).
793pub fn dim_solve(vars: &[(String, Dim)], target: Dim) -> Result<Vec<f64>, Error> {
794    if vars.is_empty() {
795        return if target.is_zero() {
796            Ok(vec![])
797        } else {
798            Err(Error::InvalidInput(format!(
799                "no variables to form the dimension {}",
800                target.display()
801            )))
802        };
803    }
804    let n = vars.len();
805    let t = dim_rat(target);
806    let a: Vec<Vec<Rat>> = (0..7)
807        .map(|row| {
808            let mut r: Vec<Rat> = vars.iter().map(|(_, d)| dim_rat(*d)[row]).collect();
809            r.push(t[row]);
810            r
811        })
812        .collect();
813    let (red, pivots, consistent) = rref_aug(a);
814    if !consistent {
815        return Err(Error::TargetDimensionUnreachable {
816            target: target.display().to_string(),
817            needed: t.iter().filter(|r| !r.is_zero()).count(),
818            spanned: pivots.len(),
819        });
820    }
821    let mut x = vec![0.0f64; n];
822    for (i, &pc) in pivots.iter().enumerate() {
823        x[pc] = red[i][n].to_f64();
824    }
825    Ok(x)
826}
827
828/// Textual form of a dimensionless group: `rho^1·v^1·L^1·mu^-1`.
829pub fn pi_text(names: &[String], exps: &[f64]) -> String {
830    let mut parts: Vec<String> = Vec::new();
831    for (n, e) in names.iter().zip(exps) {
832        if *e == 0.0 {
833            continue;
834        }
835        if *e == 1.0 {
836            parts.push(n.clone());
837        } else {
838            parts.push(format!("{n}^{}", fmt_num(*e)));
839        }
840    }
841    if parts.is_empty() {
842        "1".to_string()
843    } else {
844        parts.join("·")
845    }
846}
847// ---------------------------------------------------------------- boundary guards
848
849/// Maximum nesting depth the IR allows.
850///
851/// After parsing succeeds, **every** downstream stage (`dims` / `diff` / `simplify` / `key` /
852/// `to_latex` / `emit` / `eval`) is implemented recursively — a deliberately deep input
853/// (`((((…x…))))`) can overflow their whole stack, which is a SIGSEGV, not a readable error.
854/// So the depth is **checked once right after lowering**, turning "stack overflow" into "a
855/// rejection carrying a number".
856/// The limit is 2048: a long chain `a + b + c + …` is **left-nested** in the IR, so the depth
857/// equals the number of terms, and long series/long polynomials routinely have thousands of
858/// terms. Recursion with small frames at 2048 levels takes about 1MB on an 8MB stack, which is
859/// safe;
860/// any deeper is rejected explicitly (instead of letting some downstream stage overflow).
861pub const MAX_DEPTH: usize = 2048;
862
863/// Maximum bracket nesting accepted by the front-ends before parsing.
864///
865/// The IR depth limit above is checked *after* a tree exists; parser recursion
866/// happens before that. `pest`'s optional `stack-guard` feature detects the host
867/// stack, but it is unavailable in `no_std` builds, so this byte-level guard is
868/// the portable line of defence. 256 nested groups is far beyond handwritten
869/// formulas yet well inside a default thread stack.
870pub const MAX_PARSE_NESTING: i32 = 256;
871
872/// Upper bound on the explicit loop steps for sums/integrals (a teaching lane, not a numerics
873/// library: do not let it become a DoS).
874pub const MAX_STEPS: u64 = 10_000_000;
875
876/// Source text scan: reject **invisible** and **control** characters.
877///
878/// They do not make the grammar fail (in pest they are mostly rejected outright as unknown
879/// characters, but inside comments/strings they pass silently), yet they can make a formula "look
880/// different from what it actually is" during review:
881/// zero-width spaces, bidirectional overrides and zero-width joiners are real social-engineering
882/// surfaces.
883pub fn scan_source(src: &str) -> Result<(), FrontError> {
884    // Deterministic nesting guard that does not depend on the host stack or on
885    // pest's optional `stack-guard` feature. Both std and no_std builds need it:
886    // without it, deeply nested input aborts the process instead of reporting.
887    let mut depth = 0i32;
888    for (i, c) in src.char_indices() {
889        match c {
890            '(' | '[' | '{' => {
891                depth += 1;
892                if depth > MAX_PARSE_NESTING {
893                    let (line, col) = line_col_at(src, i);
894                    return Err(FrontError::coded(
895                        i18n::Error::NestingTooDeep {
896                            got: depth.to_string(),
897                            limit: MAX_PARSE_NESTING.to_string(),
898                        },
899                        &[],
900                        line,
901                        col,
902                    ));
903                }
904            }
905            ')' | ']' | '}' => depth -= 1,
906            _ => {}
907        }
908    }
909    for (i, c) in src.char_indices() {
910        let forbidden = match c {
911            '\u{0000}' => Some("NUL"),
912            '\u{0009}' | '\u{000a}' | '\u{000d}' => None, // tab/newline are layout
913            c if (c as u32) < 0x20 => Some("control character"),
914            '\u{200b}'..='\u{200f}' => Some("zero-width character"),
915            '\u{2028}' | '\u{2029}' => Some("line/paragraph separator"),
916            '\u{202a}'..='\u{202e}' => Some("bidirectional override"),
917            '\u{2060}'..='\u{2064}' => Some("invisible joiner"),
918            '\u{feff}' => Some("byte order mark"),
919            _ => None,
920        };
921        if let Some(kind) = forbidden {
922            let (line, col) = line_col_at(src, i);
923            let hex = format!("{:04X}", c as u32);
924            return Err(FrontError::coded(
925                i18n::Error::InvisibleCharacter(format!("{hex} ({kind})")),
926                &[],
927                line,
928                col,
929            ));
930        }
931    }
932    Ok(())
933}
934
935fn line_col_at(src: &str, byte: usize) -> (usize, usize) {
936    let mut line = 1usize;
937    let mut col = 1usize;
938    for (i, c) in src.char_indices() {
939        if i >= byte {
940            break;
941        }
942        if c == '\n' {
943            line += 1;
944            col = 1;
945        } else {
946            col += 1;
947        }
948    }
949    (line, col)
950}
951
952/// Expression depth (a leaf = 1). Used as a guard before persisting/before emitting.
953pub fn depth_of(e: &Expr) -> usize {
954    let kids: Vec<&Expr> = match e {
955        Expr::Num(_) | Expr::Var(_) | Expr::Indexed { .. } => Vec::new(),
956        Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
957            vec![a, b]
958        }
959        Expr::Neg(a)
960        | Expr::Transpose(a)
961        | Expr::Grad(a)
962        | Expr::Laplacian(a)
963        | Expr::Deriv(a, _) => {
964            vec![a]
965        }
966        Expr::Call(_, args) => args.iter().collect(),
967        Expr::Mat(rows) => rows.iter().flatten().collect(),
968        Expr::MatPattern(p) => p.elements(),
969        Expr::Sum {
970            lower, upper, body, ..
971        }
972        | Expr::Integral {
973            lower, upper, body, ..
974        } => vec![lower, upper, body],
975    };
976    1 + kids.into_iter().map(depth_of).max().unwrap_or(0)
977}
978
979/// Guard over the whole formula set (called once at the end of the front-end parse):
980/// depth + function arity.
981pub fn check_set_depth(set: &FormulaSet) -> Result<(), FrontError> {
982    // A set with declarations but no formula is a valid AST and an invalid asset: guard it here
983    // so hand-built sets (federation, loaders, tests) get the catalogued error, not a silent
984    // empty success downstream.
985    if set.items.is_empty() {
986        return Err(FrontError::plain(Error::EmptyFormula));
987    }
988    let runtime_shapes = runtime::shapes_of_set(set).map_err(FrontError::from)?;
989    for item in &set.items {
990        check_depth(&item.expr).map_err(FrontError::from)?;
991        check_calls_with_shapes(&item.expr, &runtime_shapes).map_err(FrontError::from)?;
992    }
993    Ok(())
994}
995
996/// Reserved-word collision check for declaration names (`decl { exp : ... }` would shadow the
997/// function name).
998pub fn check_decl_names(set: &FormulaSet) -> Result<(), FrontError> {
999    const RESERVED: &[&str] = &["j"];
1000    for d in &set.decls {
1001        if func_arity(&d.name).is_some() {
1002            // Catalogued variant; the payload is the colliding name and the advice rides in
1003            // the second slot so each locale can phrase it.
1004            return Err(FrontError::plain(Error::ReservedName {
1005                name: d.name.clone(),
1006                reason: i18n::ReservedReason::BuiltinFunction,
1007            }));
1008        }
1009        if RESERVED.contains(&d.name.as_str()) {
1010            return Err(FrontError::plain(Error::ReservedName {
1011                name: d.name.clone(),
1012                reason: i18n::ReservedReason::ImaginaryUnit,
1013            }));
1014        }
1015    }
1016    Ok(())
1017}
1018
1019/// Depth guard: reject outright once `MAX_DEPTH` is exceeded (to avoid downstream recursive stack
1020/// overflow).
1021pub fn check_depth(e: &Expr) -> Result<(), Error> {
1022    let d = depth_of(e);
1023    if d > MAX_DEPTH {
1024        return Err(Error::NestingTooDeep {
1025            got: d.to_string(),
1026            limit: MAX_DEPTH.to_string(),
1027        });
1028    }
1029    Ok(())
1030}
1031
1032// ---------------------------------------------------------------- IR
1033
1034#[derive(Clone, Debug, PartialEq)]
1035pub enum Expr {
1036    Num(f64),
1037    Var(String),
1038    Add(Box<Expr>, Box<Expr>),
1039    Sub(Box<Expr>, Box<Expr>),
1040    Mul(Box<Expr>, Box<Expr>),
1041    Div(Box<Expr>, Box<Expr>),
1042    Pow(Box<Expr>, Box<Expr>),
1043    Neg(Box<Expr>),
1044    Call(String, Vec<Expr>),
1045    Mat(Vec<Vec<Expr>>),
1046    /// A **pattern matrix** with ellipses: a "hand-written sketch" of a dynamic number of rows
1047    /// and columns.
1048    /// Before evaluation it must first be `recognize_pattern`-ed into a builtin shape
1049    /// (identity / diag / tridiag).
1050    MatPattern(MatPattern),
1051    /// Transpose `A^T` / `A'` (file lane only; `'` is a lexical error in the macro token lane).
1052    Transpose(Box<Expr>),
1053    /// ∂u/∂x — symbolic differentiation (not evaluated; dimension = dim(u)/dim(x)).
1054    Deriv(Box<Expr>, String),
1055    /// ∇u — gradient (dimension = dim(u)/m, Cartesian SI metric assumption).
1056    Grad(Box<Expr>),
1057    /// ∇²u / Δu — Laplacian (dimension = dim(u)/m²).
1058    Laplacian(Box<Expr>),
1059    /// Σ_{var=lower}^{upper} body — finite sum (**evaluable**; var is a bound variable).
1060    Sum {
1061        var: String,
1062        lower: Box<Expr>,
1063        upper: Box<Expr>,
1064        body: Box<Expr>,
1065    },
1066    /// ∫_lower^upper body d var — definite integral (evaluated by Simpson's rule;
1067    /// dimension = dim(body)·dim(var)).
1068    Integral {
1069        var: String,
1070        lower: Box<Expr>,
1071        upper: Box<Expr>,
1072        body: Box<Expr>,
1073    },
1074    /// Indexed symbol a_{i,j} — name + index list (the atom of tensor expressions).
1075    Indexed {
1076        name: String,
1077        indices: Vec<String>,
1078    },
1079}
1080
1081/// One cell of a pattern matrix: a concrete element, or an ellipsis (its direction is inferred
1082/// from the neighbours when writing back).
1083#[derive(Clone, Debug, PartialEq)]
1084pub enum PatternCell {
1085    El(Expr),
1086    Dots,
1087}
1088
1089#[derive(Clone, Debug, PartialEq)]
1090pub struct MatPattern {
1091    pub rows: Vec<Vec<PatternCell>>,
1092}
1093
1094impl MatPattern {
1095    /// The set of concrete cells' dimensions (ellipses do not participate).
1096    pub fn elements(&self) -> Vec<&Expr> {
1097        self.rows
1098            .iter()
1099            .flatten()
1100            .filter_map(|c| match c {
1101                PatternCell::El(e) => Some(e),
1102                PatternCell::Dots => None,
1103            })
1104            .collect()
1105    }
1106
1107    pub fn grid(&self) -> Option<(usize, usize)> {
1108        let cols = self.rows.first()?.len();
1109        if self.rows.iter().all(|r| r.len() == cols) {
1110            Some((self.rows.len(), cols))
1111        } else {
1112            None
1113        }
1114    }
1115}
1116
1117/// Builtin matrix shapes that can be generated. A pattern matrix **must** first be recognized as
1118/// one of these;
1119/// if it cannot be recognized, report an error and list the supported shapes — rejection is a
1120/// feature.
1121#[derive(Clone, Debug, PartialEq)]
1122pub enum MatrixKind {
1123    /// `[1 ⋯ 0; ⋯ 1 ⋯; 0 ⋯ 1]` → `identity(n)`
1124    Identity,
1125    /// `[d ⋯ 0; ⋯ d ⋯; 0 ⋯ d]` (same expression on the diagonal) → `diag(d, n)`
1126    Diag(Expr),
1127    /// The diagonal is an index sequence `d_{1} d_{2} d_{3}` → vector parameter `d: &[f64]`
1128    DiagVec(String),
1129    /// `[b c ⋯ 0; a b c ⋯; ⋯ a b c; 0 ⋯ a b]` → `tridiag(a, b, c, n)`
1130    Tridiag { a: Expr, b: Expr, c: Expr },
1131    /// Tridiagonal, but the diagonal is an index sequence → `tridiag_v(a, b: &[f64], c, n)`
1132    TridiagVec { a: Expr, name: String, c: Expr },
1133    /// Upper bidiagonal `[b c; · b c; ⋯ · b]` → `bidiag_u(b, c, n)`
1134    BidiagUpper { b: Expr, c: Expr },
1135    /// Lower bidiagonal `[b · ⋯ 0; a b ·; 0 ⋯ a b]` → `bidiag_l(a, b, n)`
1136    BidiagLower { a: Expr, b: Expr },
1137    /// Block diagonal `[P 0; 0 Q]` → `blockdiag2(P, Q, n, m)` (the two blocks may be equal or
1138    /// different)
1139    BlockDiag2 { p: Expr, q: Expr },
1140    /// Symmetric banded: half-bandwidth k (main diagonal + k sub-diagonals with the same value)
1141    /// → `banded(v, n)`
1142    /// e.g. k=1 is the equal-value tridiagonal special case, k=2 is pentadiagonal.
1143    Banded { v: Expr, half_band: usize },
1144}
1145
1146/// Extract a single index from an Indexed expression.
1147fn as_indexed(e: &Expr) -> Option<(&str, &str)> {
1148    match e {
1149        Expr::Indexed { name, indices } if indices.len() == 1 => {
1150            Some((name.as_str(), indices[0].as_str()))
1151        }
1152        _ => None,
1153    }
1154}
1155
1156/// Whether the diagonal cells form an **index sequence**: same name + indices that are all the
1157/// same letter (general term) or all distinct pure numbers (a sequence).
1158fn indexed_diag(cells: &[&Expr]) -> Option<String> {
1159    let mut name: Option<&str> = None;
1160    let mut letters: Option<&str> = None;
1161    let mut nums: Vec<&str> = Vec::new();
1162    for c in cells {
1163        let (n, idx) = as_indexed(c)?;
1164        match name {
1165            None => name = Some(n),
1166            Some(prev) if prev == n => {}
1167            _ => return None,
1168        }
1169        if idx.chars().all(|ch| ch.is_ascii_digit()) {
1170            if nums.contains(&idx) {
1171                return None;
1172            }
1173            nums.push(idx);
1174        } else if idx.chars().all(|ch| ch.is_ascii_alphabetic()) {
1175            match letters {
1176                None => letters = Some(idx),
1177                Some(prev) if prev == idx => {}
1178                _ => return None,
1179            }
1180        } else {
1181            return None;
1182        }
1183    }
1184    if letters.is_some() && !nums.is_empty() {
1185        return None;
1186    }
1187    name.map(|n| n.to_string())
1188}
1189
1190pub fn num(v: f64) -> Expr {
1191    Expr::Num(v)
1192}
1193pub fn var(s: impl Into<String>) -> Expr {
1194    Expr::Var(s.into())
1195}
1196pub fn add(a: Expr, b: Expr) -> Expr {
1197    Expr::Add(Box::new(a), Box::new(b))
1198}
1199pub fn sub(a: Expr, b: Expr) -> Expr {
1200    Expr::Sub(Box::new(a), Box::new(b))
1201}
1202pub fn mul(a: Expr, b: Expr) -> Expr {
1203    Expr::Mul(Box::new(a), Box::new(b))
1204}
1205pub fn div(a: Expr, b: Expr) -> Expr {
1206    Expr::Div(Box::new(a), Box::new(b))
1207}
1208pub fn pow(a: Expr, b: Expr) -> Expr {
1209    Expr::Pow(Box::new(a), Box::new(b))
1210}
1211pub fn neg(a: Expr) -> Expr {
1212    Expr::Neg(Box::new(a))
1213}
1214pub fn transpose(a: Expr) -> Expr {
1215    // The transpose of a scalar is the identity (treat a scalar as 1×1): normalize here so the IR
1216    // never holds
1217    // `Transpose(Num)` — its write-back `-4'`/`4''` makes the semantics of each side drift
1218    // (the matex grammar allows only one transpose suffix).
1219    match a {
1220        Expr::Num(_) => a,
1221        other => Expr::Transpose(Box::new(other)),
1222    }
1223}
1224pub fn deriv(u: Expr, by: impl Into<String>) -> Expr {
1225    Expr::Deriv(Box::new(u), by.into())
1226}
1227pub fn grad(u: Expr) -> Expr {
1228    Expr::Grad(Box::new(u))
1229}
1230pub fn laplacian(u: Expr) -> Expr {
1231    Expr::Laplacian(Box::new(u))
1232}
1233pub fn sum(var: impl Into<String>, lower: Expr, upper: Expr, body: Expr) -> Expr {
1234    Expr::Sum {
1235        var: var.into(),
1236        lower: Box::new(lower),
1237        upper: Box::new(upper),
1238        body: Box::new(body),
1239    }
1240}
1241pub fn integral(var: impl Into<String>, lower: Expr, upper: Expr, body: Expr) -> Expr {
1242    Expr::Integral {
1243        var: var.into(),
1244        lower: Box::new(lower),
1245        upper: Box::new(upper),
1246        body: Box::new(body),
1247    }
1248}
1249pub fn indexed(name: impl Into<String>, indices: Vec<String>) -> Expr {
1250    Expr::Indexed {
1251        name: name.into(),
1252        indices,
1253    }
1254}
1255
1256// ---------------------------------------------------------------- federated formulas
1257
1258/// One piece of formula source = a declaration block + one or more formulas (the "federation"
1259/// model: later entries may reference the names of earlier ones).
1260#[derive(Clone, Debug, Default, PartialEq)]
1261pub struct FormulaSet {
1262    pub decls: Vec<Decl>,
1263    pub items: Vec<FormulaItem>,
1264    /// Dependencies from `use "relative path"` (in order of appearance). **Parse time only
1265    /// collects them, no IO is done** —
1266    /// the formula front end is a pure string API; filesystem matters belong to the loader lane.
1267    pub uses: Vec<String>,
1268}
1269
1270#[derive(Clone, Debug, PartialEq)]
1271pub struct FormulaItem {
1272    pub name: Option<String>,
1273    pub expr: Expr,
1274    /// Starting line in the source file (1-based; filled in by the front end). 0 = unknown
1275    /// (synthesized/test construction).
1276    pub line: usize,
1277}
1278
1279impl FormulaSet {
1280    /// Convenience accessor for a single formula (compatible with old call sites); errors when
1281    /// there are several.
1282    pub fn single(&self) -> Result<&Expr, Error> {
1283        match self.items.as_slice() {
1284            [one] => Ok(&one.expr),
1285            _ => Err(Error::ExpectedSingleFormula {
1286                got: self.items.len(),
1287            }),
1288        }
1289    }
1290
1291    /// Single-formula compatibility unwrap: (decls, expr). With several formulas it takes the
1292    /// **last** one (federation semantics: the final value).
1293    /// Callers needing strict single-formula semantics should use `single()`.
1294    pub fn into_single(self) -> (Vec<Decl>, Expr) {
1295        let expr = self
1296            .items
1297            .last()
1298            .map(|i| i.expr.clone())
1299            .expect("FormulaSet 至少一条(parse 保证)");
1300        (self.decls, expr)
1301    }
1302}
1303
1304/// Symbolic substitution: replace every occurrence of `name` with `by` (inline expansion of a
1305/// federation reference).
1306pub fn subst(e: &Expr, name: &str, by: &Expr) -> Expr {
1307    match e {
1308        Expr::Num(_) => e.clone(),
1309        Expr::Var(n) => {
1310            if n == name {
1311                by.clone()
1312            } else {
1313                e.clone()
1314            }
1315        }
1316        Expr::Add(a, b) => add(subst(a, name, by), subst(b, name, by)),
1317        Expr::Sub(a, b) => sub(subst(a, name, by), subst(b, name, by)),
1318        Expr::Mul(a, b) => mul(subst(a, name, by), subst(b, name, by)),
1319        Expr::Div(a, b) => div(subst(a, name, by), subst(b, name, by)),
1320        Expr::Pow(a, b) => pow(subst(a, name, by), subst(b, name, by)),
1321        Expr::Neg(a) => neg(subst(a, name, by)),
1322        Expr::Call(n, args) => {
1323            Expr::Call(n.clone(), args.iter().map(|a| subst(a, name, by)).collect())
1324        }
1325        Expr::Mat(rows) => Expr::Mat(
1326            rows.iter()
1327                .map(|r| r.iter().map(|c| subst(c, name, by)).collect())
1328                .collect(),
1329        ),
1330        Expr::MatPattern(p) => Expr::MatPattern(MatPattern {
1331            rows: p
1332                .rows
1333                .iter()
1334                .map(|r| {
1335                    r.iter()
1336                        .map(|c| match c {
1337                            PatternCell::El(e) => PatternCell::El(subst(e, name, by)),
1338                            PatternCell::Dots => PatternCell::Dots,
1339                        })
1340                        .collect()
1341                })
1342                .collect(),
1343        }),
1344        Expr::Transpose(a) => transpose(subst(a, name, by)),
1345        Expr::Deriv(u, by_var) => deriv(subst(u, name, by), by_var.clone()),
1346        Expr::Grad(u) => grad(subst(u, name, by)),
1347        Expr::Laplacian(u) => laplacian(subst(u, name, by)),
1348        Expr::Sum {
1349            var,
1350            lower,
1351            upper,
1352            body,
1353        } => sum(
1354            var.clone(),
1355            subst(lower, name, by),
1356            subst(upper, name, by),
1357            subst(body, name, by),
1358        ),
1359        Expr::Integral {
1360            var,
1361            lower,
1362            upper,
1363            body,
1364        } => integral(
1365            var.clone(),
1366            subst(lower, name, by),
1367            subst(upper, name, by),
1368            subst(body, name, by),
1369        ),
1370        Expr::Indexed { name: n, indices } => indexed(
1371            if n == name {
1372                by_var_name(by)
1373            } else {
1374                n.clone()
1375            },
1376            indices.clone(),
1377        ),
1378    }
1379}
1380
1381/// Naming when the substitution target degenerates to a name (the name slot of Indexed is a
1382/// String, not an Expr).
1383fn by_var_name(by: &Expr) -> String {
1384    match by {
1385        Expr::Var(n) => n.clone(),
1386        other => format!("__sub_{:x}", other as *const _ as usize),
1387    }
1388}
1389
1390/// Federated dimension table: decls as the base, then the names of earlier formulas merged in
1391/// with the dimension of their expressions —
1392/// so referencing `area` inside `vol = area * h` is legal, and dimensions propagate.
1393pub fn dims_of_set(set: &FormulaSet) -> Result<HashMap<String, Dim>, Error> {
1394    let declared_dims = dims_of(&set.decls)?;
1395    let runtime_shapes = runtime::shapes_of_set(set)?;
1396    let mut dims = declared_dims.clone();
1397    // A formula may reuse a decl's name (a = F/m), but the result must honor the dimension already
1398    // declared for that name;
1399    // otherwise s : Pa; s = F/d silently turns the same key into a different physical quantity.
1400    // Duplicate formula names are rejected outright, instead of waiting for rustc to report E0428
1401    // in the generated code.
1402    let mut item_names = BTreeSet::new();
1403    for item in &set.items {
1404        let Some(name) = &item.name else { continue };
1405        if !item_names.insert(name) {
1406            return Err(Error::DuplicateDeclaration {
1407                name: name.clone(),
1408                line: Some(item.line),
1409            });
1410        }
1411    }
1412    // **Federate first, then check**: when a later entry references an earlier name, the check
1413    // must see the expanded expression,
1414    // otherwise structural information such as "shape" (`det` needs the square order) is lost on
1415    // `Var(name)`.
1416    let items = federate_inline(set)?;
1417    for item in &items {
1418        if let Some(name) = &item.name {
1419            // Fold first: exponents such as `^(1/2)` must converge to Num before the dimension check
1420            let d = runtime::dim_check_runtime(&simplify(&item.expr), &dims, &runtime_shapes)?;
1421            if let Some(declared) = declared_dims.get(name) {
1422                if declared != &d {
1423                    return Err(Error::ResultDimensionMismatch {
1424                        name: name.clone(),
1425                        got: d.display(),
1426                        declared: declared.display(),
1427                        line: item.line,
1428                    });
1429                }
1430            }
1431            dims.insert(name.clone(), d);
1432        }
1433    }
1434    Ok(dims)
1435}
1436
1437/// Federation expansion: starting from the second entry, **substitute** earlier named formulas
1438/// into the references (no function calls, each entry self-contained).
1439/// The cost is duplicated computation (the caller's CSE only helps within a single entry); the
1440/// macro inlining lane uses a let chain and pays no such cost.
1441pub fn federate_inline(set: &FormulaSet) -> Result<Vec<FormulaItem>, Error> {
1442    let mut acc: Vec<(String, Expr)> = Vec::new();
1443    let mut out = Vec::new();
1444    for item in &set.items {
1445        let mut e = item.expr.clone();
1446        for (n, v) in &acc {
1447            e = subst(&e, n, v);
1448        }
1449        e = simplify(&e);
1450        if let Some(n) = &item.name {
1451            acc.push((n.clone(), e.clone()));
1452        }
1453        out.push(FormulaItem {
1454            name: item.name.clone(),
1455            expr: e,
1456            line: item.line,
1457        });
1458    }
1459    Ok(out)
1460}
1461
1462// ---------------------------------------------------------------- evaluation
1463
1464pub fn eval(e: &Expr, env: &HashMap<String, f64>) -> Result<f64, Error> {
1465    let v = eval_value(e, env)?;
1466    let c = v.as_scalar().ok_or_else(|| {
1467        Error::MatrixScalarMix("scalar evaluation met a matrix; use eval_value".into())
1468    })?;
1469    if !c.is_real() {
1470        return Err(Error::ComplexEvalResult { re: c.re, im: c.im });
1471    }
1472    Ok(c.re)
1473}
1474
1475/// Parameter order = **declaration order** (not lexicographic): the generated function signature
1476/// must be readable by a human in formula order.
1477///
1478/// Reserved constants (`j` = imaginary unit) **do not go into the parameter list**: the emitter
1479/// supplies `(0, 1)` itself;
1480/// putting it in the signature would be the absurd API of "making the caller pass the imaginary
1481/// unit".
1482pub fn params_in_decl_order(decls: &[Decl], e: &Expr) -> Vec<String> {
1483    // `j` is the reserved imaginary unit only when **not declared**; if the user explicitly
1484    // declared j (e.g. complex current density)
1485    // it must appear in the signature, otherwise code generation and evaluation semantics
1486    // diverge.
1487    let j_reserved = !decls.iter().any(|d| d.name == "j");
1488    let used: Vec<String> = vars_of(e)
1489        .into_iter()
1490        .filter(|n| !(j_reserved && n == "j"))
1491        .collect();
1492    let mut out: Vec<String> = decls
1493        .iter()
1494        .map(|d| d.name.clone())
1495        .filter(|n| used.contains(n))
1496        .collect();
1497    for u in used {
1498        if !out.contains(&u) {
1499            out.push(u);
1500        }
1501    }
1502    out
1503}
1504
1505pub fn vars_of(e: &Expr) -> Vec<String> {
1506    fn go(e: &Expr, out: &mut Vec<String>) {
1507        match e {
1508            Expr::Num(_) => {}
1509            Expr::Var(n) => {
1510                if !out.contains(n) {
1511                    out.push(n.clone());
1512                }
1513            }
1514            Expr::Add(a, b)
1515            | Expr::Sub(a, b)
1516            | Expr::Mul(a, b)
1517            | Expr::Div(a, b)
1518            | Expr::Pow(a, b) => {
1519                go(a, out);
1520                go(b, out);
1521            }
1522            Expr::Neg(a) => go(a, out),
1523            Expr::Call(_, args) => {
1524                for a in args {
1525                    go(a, out);
1526                }
1527            }
1528            Expr::Mat(rows) => {
1529                for r in rows {
1530                    for c in r {
1531                        go(c, out);
1532                    }
1533                }
1534            }
1535            Expr::MatPattern(p) => {
1536                for e in p.elements() {
1537                    go(e, out);
1538                }
1539            }
1540            Expr::Transpose(a) => go(a, out),
1541            Expr::Deriv(u, by) => {
1542                go(u, out);
1543                let _ = by; // the differentiation variable is bound, not free
1544            }
1545            Expr::Grad(u) | Expr::Laplacian(u) => go(u, out),
1546            Expr::Sum {
1547                var,
1548                lower,
1549                upper,
1550                body,
1551            } => {
1552                go(lower, out);
1553                go(upper, out);
1554                go(body, out);
1555                out.retain(|n| n != var); // the summation index is bound
1556            }
1557            Expr::Integral {
1558                var,
1559                lower,
1560                upper,
1561                body,
1562            } => {
1563                go(lower, out);
1564                go(upper, out);
1565                go(body, out);
1566                out.retain(|n| n != var); // the integration variable is bound
1567            }
1568            Expr::Indexed { name, indices } => {
1569                // The indexed symbol itself is a free variable; its indices (i, j) are free
1570                // symbols as well
1571                let mut item = name.clone();
1572                item.push_str("__idx");
1573                let _ = item;
1574                if !out.contains(name) {
1575                    out.push(name.clone());
1576                }
1577                for i in indices {
1578                    // Numeric indices are values, not free parameters. Symbolic indices
1579                    // remain free until the runtime index lane handles them explicitly.
1580                    if i.parse::<usize>().is_err() && !out.contains(i) {
1581                        out.push(i.clone());
1582                    }
1583                }
1584            }
1585        }
1586    }
1587    let mut out = Vec::new();
1588    go(e, &mut out);
1589    out.sort();
1590    out
1591}
1592
1593// ---------------------------------------------------------------- simplification
1594
1595pub fn simplify(e: &Expr) -> Expr {
1596    let e = match e {
1597        Expr::Num(_) | Expr::Var(_) => e.clone(),
1598        Expr::Add(a, b) => add(simplify(a), simplify(b)),
1599        Expr::Sub(a, b) => sub(simplify(a), simplify(b)),
1600        Expr::Mul(a, b) => mul(simplify(a), simplify(b)),
1601        Expr::Div(a, b) => div(simplify(a), simplify(b)),
1602        Expr::Pow(a, b) => pow(simplify(a), simplify(b)),
1603        Expr::Neg(a) => neg(simplify(a)),
1604        Expr::Call(n, args) => Expr::Call(n.clone(), args.iter().map(simplify).collect()),
1605        Expr::Mat(rows) => Expr::Mat(
1606            rows.iter()
1607                .map(|r| r.iter().map(simplify).collect())
1608                .collect(),
1609        ),
1610        Expr::MatPattern(p) => Expr::MatPattern(MatPattern {
1611            rows: p
1612                .rows
1613                .iter()
1614                .map(|r| {
1615                    r.iter()
1616                        .map(|c| match c {
1617                            PatternCell::El(e) => PatternCell::El(simplify(e)),
1618                            PatternCell::Dots => PatternCell::Dots,
1619                        })
1620                        .collect()
1621                })
1622                .collect(),
1623        }),
1624        Expr::Transpose(a) => transpose(simplify(a)),
1625        Expr::Deriv(u, by) => deriv(simplify(u), by.clone()),
1626        Expr::Grad(u) => grad(simplify(u)),
1627        Expr::Laplacian(u) => laplacian(simplify(u)),
1628        Expr::Sum {
1629            var,
1630            lower,
1631            upper,
1632            body,
1633        } => sum(
1634            var.clone(),
1635            simplify(lower),
1636            simplify(upper),
1637            simplify(body),
1638        ),
1639        Expr::Integral {
1640            var,
1641            lower,
1642            upper,
1643            body,
1644        } => integral(
1645            var.clone(),
1646            simplify(lower),
1647            simplify(upper),
1648            simplify(body),
1649        ),
1650        Expr::Indexed { name, indices } => indexed(name.clone(), indices.clone()),
1651    };
1652    fold_const(&e)
1653}
1654
1655fn fold_const(e: &Expr) -> Expr {
1656    let z = |x: &Expr| matches!(x, Expr::Num(v) if *v == 0.0);
1657    let one = |x: &Expr| matches!(x, Expr::Num(v) if *v == 1.0);
1658    match e {
1659        Expr::Neg(a) => match a.as_ref() {
1660            Expr::Num(v) => num(-*v),
1661            Expr::Neg(b) => (**b).clone(),
1662            _ => neg((**a).clone()),
1663        },
1664        Expr::Add(a, b) => {
1665            if let (Expr::Num(x), Expr::Num(y)) = (a.as_ref(), b.as_ref()) {
1666                return num(x + y);
1667            }
1668            if z(a) {
1669                return (**b).clone();
1670            }
1671            if z(b) {
1672                return (**a).clone();
1673            }
1674            add((**a).clone(), (**b).clone())
1675        }
1676        Expr::Sub(a, b) => {
1677            if let (Expr::Num(x), Expr::Num(y)) = (a.as_ref(), b.as_ref()) {
1678                return num(x - y);
1679            }
1680            if z(b) {
1681                return (**a).clone();
1682            }
1683            if z(a) {
1684                return neg((**b).clone());
1685            }
1686            sub((**a).clone(), (**b).clone())
1687        }
1688        Expr::Mul(a, b) => {
1689            if let (Expr::Num(x), Expr::Num(y)) = (a.as_ref(), b.as_ref()) {
1690                return num(x * y);
1691            }
1692            if z(a) || z(b) {
1693                return num(0.0);
1694            }
1695            if one(a) {
1696                return (**b).clone();
1697            }
1698            if one(b) {
1699                return (**a).clone();
1700            }
1701            if let Expr::Num(v) = a.as_ref() {
1702                if *v == -1.0 {
1703                    return neg((**b).clone());
1704                }
1705            }
1706            mul((**a).clone(), (**b).clone())
1707        }
1708        Expr::Div(a, b) => {
1709            if let (Expr::Num(x), Expr::Num(y)) = (a.as_ref(), b.as_ref()) {
1710                return num(x / y);
1711            }
1712            if z(a) {
1713                return num(0.0);
1714            }
1715            if one(b) {
1716                return (**a).clone();
1717            }
1718            div((**a).clone(), (**b).clone())
1719        }
1720        Expr::Pow(a, b) => {
1721            if let (Expr::Num(x), Expr::Num(y)) = (a.as_ref(), b.as_ref()) {
1722                // Negative real base + non-integer exponent: the value layer gives a **complex**
1723                // number (principal branch), and folding it to
1724                // `powf` here would produce NaN — two lanes giving two answers is the worst form of
1725                // defect.
1726                // Do not fold; leave it for the evaluation layer to compute with complex
1727                // semantics.
1728                if *x < 0.0 && math::fract(*y) != 0.0 {
1729                    return e.clone();
1730                }
1731                return num(math::powf(*x, *y));
1732            }
1733            if let Expr::Num(y) = b.as_ref() {
1734                if *y == 1.0 {
1735                    return (**a).clone();
1736                }
1737                if *y == 0.0 && !matrix_ish(a) {
1738                    return num(1.0);
1739                }
1740            }
1741            pow((**a).clone(), (**b).clone())
1742        }
1743        _ => e.clone(),
1744    }
1745}
1746
1747// ---------------------------------------------------------------- complex numbers
1748
1749/// Complex number (real part + imaginary part).
1750///
1751/// The value layer uses `C` **uniformly**, rather than two variants "real scalar / complex
1752/// scalar": in scenarios like EIS
1753/// the matrix elements themselves may be complex, and two variants would immediately degenerate
1754/// into the four quadrants "real scalar / complex scalar /
1755/// real matrix / complex matrix" — a combinatorial explosion with every operation written four
1756/// times. Once unified, only
1757/// the two states "scalar / matrix" remain, and each operation has a single implementation.
1758#[derive(Clone, Copy, Debug, Default, PartialEq)]
1759pub struct C {
1760    pub re: f64,
1761    pub im: f64,
1762}
1763
1764// The method names `add/sub/mul/div/neg` being identical to std::ops is **deliberate**: the
1765// operators of the formula layer
1766// should be called exactly that. But they must not become std trait impls — `Div` cannot return a
1767// `Result`,
1768// and complex division by zero is an error at the formula layer (see `C::div`). So this clippy
1769// lint is explicitly waived here.
1770#[allow(clippy::should_implement_trait)]
1771impl C {
1772    pub const ZERO: C = C { re: 0.0, im: 0.0 };
1773    pub const ONE: C = C { re: 1.0, im: 0.0 };
1774    /// The imaginary unit `j` (the engineering convention; written i in mathematics).
1775    pub const I: C = C { re: 0.0, im: 1.0 };
1776
1777    pub const fn new(re: f64, im: f64) -> Self {
1778        C { re, im }
1779    }
1780
1781    /// Promote a real number to complex (zero imaginary part).
1782    pub const fn real(re: f64) -> Self {
1783        C { re, im: 0.0 }
1784    }
1785
1786    /// Whether it lies on the real axis (imaginary part exactly 0, including -0.0).
1787    pub fn is_real(self) -> bool {
1788        self.im == 0.0
1789    }
1790
1791    pub fn add(self, o: C) -> C {
1792        C::new(self.re + o.re, self.im + o.im)
1793    }
1794    pub fn sub(self, o: C) -> C {
1795        C::new(self.re - o.re, self.im - o.im)
1796    }
1797    pub fn neg(self) -> C {
1798        C::new(-self.re, -self.im)
1799    }
1800    pub fn mul(self, o: C) -> C {
1801        C::new(
1802            self.re * o.re - self.im * o.im,
1803            self.re * o.im + self.im * o.re,
1804        )
1805    }
1806    /// Division. Division by zero is an **error** (not a silent NaN): an error the formula layer
1807    /// can prove should not
1808    /// become runtime noise; the generated-code lane handles IEEE semantics separately (see the
1809    /// emitter comments).
1810    ///
1811    /// Both fast paths are **mandatory**, not optimizations:
1812    /// 1. Real divided by real goes straight to `a/b`. Using `a·b/(b²)` would
1813    ///    overflow to inf when `|a·b|` exceeds 1.8e308, and underflow `b²` to 0 when `|b|` is below
1814    ///    1.5e-162, thus falsely reporting division by zero
1815    ///    (`1e300/1e10` would be computed as inf, `1e-200/1e-200` would report "division by
1816    ///    zero").
1817    /// 2. Complex division uses Smith's algorithm (scaling first by the magnitudes of `|re|` and
1818    ///    `|im|`),
1819    ///    avoiding overflow/underflow of `re²+im²`.
1820    pub fn div(self, o: C) -> Result<C, Error> {
1821        if o.is_real() {
1822            if o.re == 0.0 {
1823                return Err(Error::DivisionByZero);
1824            }
1825            return Ok(C::new(self.re / o.re, self.im / o.re));
1826        }
1827        if o.re.abs() >= o.im.abs() {
1828            let r = o.im / o.re;
1829            let den = o.re + o.im * r;
1830            if den == 0.0 {
1831                return Err(Error::DivisionByZero);
1832            }
1833            Ok(C::new(
1834                (self.re + self.im * r) / den,
1835                (self.im - self.re * r) / den,
1836            ))
1837        } else {
1838            let r = o.re / o.im;
1839            let den = o.re * r + o.im;
1840            if den == 0.0 {
1841                return Err(Error::DivisionByZero);
1842            }
1843            Ok(C::new(
1844                (self.re * r + self.im) / den,
1845                (self.im * r - self.re) / den,
1846            ))
1847        }
1848    }
1849
1850    /// Modulus `|z|`.
1851    pub fn abs(self) -> f64 {
1852        math::hypot(self.re, self.im)
1853    }
1854    /// Argument (principal value, (-π, π]).
1855    pub fn arg(self) -> f64 {
1856        math::atan2(self.im, self.re)
1857    }
1858    pub fn conj(self) -> C {
1859        C::new(self.re, -self.im)
1860    }
1861    /// Exponential. Reals take a fast path: the polar formula, when the real part overflows,
1862    /// yields `(inf·cos0, inf·sin0)` =
1863    /// `(inf, NaN)` — "the exponential of a real number" should not grow a NaN imaginary part.
1864    pub fn exp(self) -> C {
1865        if self.is_real() {
1866            return C::real(math::exp(self.re));
1867        }
1868        let m = math::exp(self.re);
1869        C::new(m * math::cos(self.im), m * math::sin(self.im))
1870    }
1871    /// Principal-value logarithm (negative real → imaginary part π).
1872    pub fn ln(self) -> Result<C, Error> {
1873        if self.re == 0.0 && self.im == 0.0 {
1874            return Err(Error::LogOfZero);
1875        }
1876        Ok(C::new(math::ln(self.abs()), self.arg()))
1877    }
1878
1879    /// Real-exponent power (polar formula). `√s` / `s^(-1/2)` / `(jω)^(1/2)` all share this one.
1880    ///
1881    /// A real base is triaged first; never blindly go polar: `atan2(0, -1.3) = π` and
1882    /// `sin(2π) = -2.4e-16`, so `(-1.3)^2` would pick up a trace of a fake imaginary part,
1883    /// and the "must be real" gate of `eval` would misjudge a purely real formula as complex.
1884    pub fn pow_real(self, p: f64) -> C {
1885        // A non-finite exponent has no "real axis" to speak of: return a NaN real part directly, so
1886        // the polar formula does not
1887        // produce a pseudo-complex number with im=NaN that falsely trips the real gate of `eval`.
1888        if !p.is_finite() {
1889            return C::real(f64::NAN);
1890        }
1891        if self.is_real() {
1892            // Integer exponent: use powi (exact even for a negative base, and `powf` on a negative
1893            // base + integer exponent
1894            // depends on the platform pow's C99 behaviour, which is not worth betting on)
1895            if p == math::trunc(p) && p.abs() <= i32::MAX as f64 {
1896                return C::real(math::powi(self.re, p as i32));
1897            }
1898            if self.re >= 0.0 {
1899                return C::real(math::powf(self.re, p));
1900            }
1901        }
1902        let (r, t) = (self.abs(), self.arg());
1903        let m = math::powf(r, p);
1904        let a = t * p;
1905        C::new(m * math::cos(a), m * math::sin(a))
1906    }
1907
1908    /// Complex-exponent power: `z^w = exp(w·ln z)` (principal branch).
1909    pub fn pow(self, o: C) -> Result<C, Error> {
1910        if o.is_real() {
1911            return Ok(self.pow_real(o.re));
1912        }
1913        Ok(o.mul(self.ln()?).exp())
1914    }
1915
1916    /// Principal-value square root: an **algebraic closed form**, not polar (skipping the three
1917    /// transcendental functions atan2/cos/sin).
1918    ///
1919    /// Closed form of `√(x+iy)`: `r = hypot(x,y)`, `re = √((r+x)/2)`,
1920    /// `im = sign(y)·√((r-x)/2)`. This form is also numerically more stable (r+x does not cancel
1921    /// catastrophically),
1922    /// and it agrees pointwise with the polar form — guarded by the `sqrt² == itself` test.
1923    pub fn sqrt(self) -> C {
1924        if self.is_real() {
1925            // Real: non-negative goes to sqrt, negative gives `0 + √|x|·j` (principal value)
1926            return if self.re >= 0.0 {
1927                C::real(math::sqrt(self.re))
1928            } else {
1929                C::new(0.0, math::sqrt(-self.re))
1930            };
1931        }
1932        let r = self.abs();
1933        let re = math::sqrt(((r + self.re) * 0.5).max(0.0));
1934        let im = math::sqrt(((r - self.re) * 0.5).max(0.0)).copysign(self.im);
1935        C::new(re, im)
1936    }
1937
1938    pub fn sin(self) -> C {
1939        C::new(
1940            math::sin(self.re) * math::cosh(self.im),
1941            math::cos(self.re) * math::sinh(self.im),
1942        )
1943    }
1944    pub fn cos(self) -> C {
1945        C::new(
1946            math::cos(self.re) * math::cosh(self.im),
1947            -math::sin(self.re) * math::sinh(self.im),
1948        )
1949    }
1950    pub fn sinh(self) -> C {
1951        C::new(
1952            math::sinh(self.re) * math::cos(self.im),
1953            math::cosh(self.re) * math::sin(self.im),
1954        )
1955    }
1956    pub fn cosh(self) -> C {
1957        C::new(
1958            math::cosh(self.re) * math::cos(self.im),
1959            math::sinh(self.re) * math::sin(self.im),
1960        )
1961    }
1962    pub fn tan(self) -> Result<C, Error> {
1963        self.sin().div(self.cos())
1964    }
1965    pub fn tanh(self) -> Result<C, Error> {
1966        self.sinh().div(self.cosh())
1967    }
1968}
1969
1970/// Evaluation result: scalar or matrix. Matrix elements are `C`, so a real matrix and a complex
1971/// matrix are the **same**
1972/// variant (the imaginary part of a real number is always 0).
1973#[derive(Clone, Debug, PartialEq)]
1974pub enum Value {
1975    Scalar(C),
1976    Matrix(Vec<Vec<C>>),
1977}
1978
1979impl Value {
1980    /// Scalar view; returns None for a matrix.
1981    pub fn as_scalar(&self) -> Option<C> {
1982        match self {
1983            Value::Scalar(c) => Some(*c),
1984            Value::Matrix(_) => None,
1985        }
1986    }
1987
1988    /// Whether it really carries an imaginary part (for diagnostics).
1989    pub fn is_complex(&self) -> bool {
1990        match self {
1991            Value::Scalar(c) => !c.is_real(),
1992            Value::Matrix(m) => m.iter().flatten().any(|c| !c.is_real()),
1993        }
1994    }
1995}
1996
1997// ---------------------------------------------------------------- matrix algebra (shape arithmetic + evaluation + multiplication generation)
1998
1999/// Static shape: (rows, cols) of a concrete matrix literal. Pattern matrices/symbols return None
2000/// (dynamic shape;
2001/// the first version does not infer shapes); a **concrete matrix with inconsistent shape**
2002/// (jagged rows) is a hard error.
2003pub fn shape_of(e: &Expr) -> Result<Option<(usize, usize)>, Error> {
2004    Ok(match e {
2005        Expr::Mat(rows) => {
2006            let cols = rows.first().map(|r| r.len());
2007            if let Some(n) = cols {
2008                if rows.iter().any(|r| r.len() != n) {
2009                    return Err(Error::ShapeMismatch("matrix literal rows have different lengths (jagged matrices are not supported)".into()));
2010                }
2011            }
2012            Some((rows.len(), cols.unwrap_or(0)))
2013        }
2014        Expr::MatPattern(_) => None, // dynamic: n is a runtime parameter
2015        Expr::Transpose(a) => shape_of(a)?.map(|(m, n)| (n, m)),
2016        _ => None, // scalar / symbol: does not participate in shape arithmetic
2017    })
2018}
2019
2020/// Shape consistency check for matrix operations (operations between literals; symbols return Ok
2021/// and note that they were not checked).
2022/// This and the dimension check are **two orthogonal axes**: dimensions govern "physical meaning",
2023/// shapes govern "algebraic legality".
2024/// Matrix shape: ask the static `shape_of` first, and if that cannot answer, `flatten` (which
2025/// recognizes solve/roots/
2026/// poly_coeffs/products/transpose). Only when neither level can decide is the shape "unknown".
2027fn matrix_shape(e: &Expr) -> Result<Option<(usize, usize)>, Error> {
2028    if let Some(s) = shape_of(e)? {
2029        return Ok(Some(s));
2030    }
2031    Ok(flatten_matrix_value(e).and_then(|m| {
2032        let rows = m.len();
2033        let cols = m.first().map(|r| r.len())?;
2034        if m.iter().all(|r| r.len() == cols) {
2035            Some((rows, cols))
2036        } else {
2037            None
2038        }
2039    }))
2040}
2041
2042pub fn shape_check(e: &Expr) -> Result<(), Error> {
2043    match e {
2044        Expr::Add(a, b) | Expr::Sub(a, b) => {
2045            shape_check(a)?;
2046            shape_check(b)?;
2047            // Matrix-ness uses the **precise** predicate `is_matrix_value` (it goes through
2048            // flatten and recognizes products/transposes/solution vectors);
2049            // `shape_of` is used only to compare shapes, and returns None for matrix expressions
2050            // "whose shape is unknown at compile time".
2051            let (ma, mb) = (is_matrix_value(a), is_matrix_value(b));
2052            // Matrices and scalars cannot be added/subtracted: `3 + roots(...)` would be emitted
2053            // as `3.0 + vec![vec![…]]` (E0277), while the diagnostics used to say "clean".
2054            // Exception for the zero element (the additive identity, usually already gone after
2055            // simplification).
2056            let is_zero = |x: &Expr| matches!(simplify(x), Expr::Num(v) if v == 0.0);
2057            if ma != mb {
2058                let scalar_side = if ma { b } else { a };
2059                if !is_zero(scalar_side) {
2060                    return Err(Error::MatrixScalarMix(
2061                        "matrix vs scalar add/sub: operate element-wise or reshape".to_string(),
2062                    ));
2063                }
2064            } else if ma && mb {
2065                // Both sides are matrices: ask `shape_of` for the shape first, then `flatten`
2066                // (the shape of `roots(...) + roots(...)` exists only after expansion)
2067                let (sa, sb) = (matrix_shape(a)?, matrix_shape(b)?);
2068                if let (Some(sa), Some(sb)) = (sa, sb) {
2069                    if sa != sb {
2070                        return Err(Error::ShapeMismatch(format!(
2071                            "matrix add/sub shapes differ: {sa:?} vs {sb:?}"
2072                        )));
2073                    }
2074                }
2075            }
2076            Ok(())
2077        }
2078        Expr::Mul(a, b) => {
2079            shape_check(a)?;
2080            shape_check(b)?;
2081            // Shape determination must be two-level: `shape_of` only recognizes static shapes
2082            // (matrix literals/pattern matrices),
2083            // while things like `solve/roots/poly_coeffs` are only known **after expansion** —
2084            // checking only the former misses the case
2085            // "neither matrix can be determined → emit as scalars", and the output becomes
2086            // `vec![…] * vec![…]`.
2087            let sa = matrix_shape(a)?;
2088            let sb = matrix_shape(b)?;
2089            match (sa, sb) {
2090                (Some(sa), Some(sb)) => {
2091                    if sa.1 != sb.0 {
2092                        return Err(Error::ShapeMismatch(format!(
2093                "cannot multiply {sa:?} by {sb:?}: columns of the left operand ≠ rows of the right"
2094            )));
2095                    }
2096                }
2097                // One side is a matrix, the other's shape is unknown → undecidable, reject
2098                // explicitly (no guessing)
2099                (Some(_), None) if is_matrix_value(b) => {
2100                    return Err(Error::ShapeMismatch(
2101                "one side of the product has a shape unknown at compile time, so it cannot be checked".into(),
2102            ))
2103                }
2104                (None, Some(_)) if is_matrix_value(a) => {
2105                    return Err(Error::ShapeMismatch(
2106                "one side of the product has a shape unknown at compile time, so it cannot be checked".into(),
2107            ))
2108                }
2109                _ => {}
2110            }
2111            Ok(())
2112        }
2113        Expr::Div(a, b) => {
2114            shape_check(a)?;
2115            // Matrix division (inversion) is unsupported in the first version: a matrix literal as
2116            // the right operand = explicit error
2117            if shape_of(b)?.is_some() {
2118                return Err(Error::MatrixDivisionUnsupported(
2119                    "write an explicit inverse (`inv(A) * b`) or use the solver".to_string(),
2120                ));
2121            }
2122            Ok(())
2123        }
2124        Expr::Neg(a) | Expr::Transpose(a) => shape_check(a),
2125        Expr::Deriv(u, _) | Expr::Grad(u) | Expr::Laplacian(u) => shape_check(u),
2126        Expr::Sum {
2127            lower, upper, body, ..
2128        }
2129        | Expr::Integral {
2130            lower, upper, body, ..
2131        } => {
2132            shape_check(lower)?;
2133            shape_check(upper)?;
2134            shape_check(body)
2135        }
2136        Expr::Indexed { .. } => Ok(()), // an indexed symbol's shape depends on its declaration; the first version lets it through
2137        Expr::Pow(a, b) => {
2138            shape_check(a)?;
2139            shape_check(b)
2140        }
2141        Expr::Call(_, args) => {
2142            for a in args {
2143                shape_check(a)?;
2144            }
2145            Ok(())
2146        }
2147        Expr::Mat(rows) => {
2148            shape_of(e)?;
2149            for r in rows {
2150                for c in r {
2151                    shape_check(c)?;
2152                }
2153            }
2154            Ok(())
2155        }
2156        Expr::MatPattern(p) => {
2157            p.grid().ok_or_else(|| {
2158                Error::ShapeMismatch("pattern matrix rows have inconsistent lengths".into())
2159            })?;
2160            Ok(())
2161        }
2162        _ => Ok(()),
2163    }
2164}
2165
2166/// Structured evaluation: both scalars (real/complex) and matrices can be computed.
2167/// `eval` is its "must be a real scalar" convenience wrapper.
2168pub fn eval_value(e: &Expr, env: &HashMap<String, f64>) -> Result<Value, Error> {
2169    use Expr as E;
2170    Ok(match e {
2171        E::Num(v) => Value::Scalar(C::real(*v)),
2172        // Reserved symbol `j`: the imaginary unit (dimensionless); if `j` is given explicitly in
2173        // env, use env's value
2174        E::Var(n) if n == "j" && !env.contains_key("j") => Value::Scalar(C::I),
2175        E::Var(n) => Value::Scalar(C::real(
2176            *env.get(n).ok_or_else(|| Error::UndeclaredSymbol(n.clone()))?,
2177        )),
2178        E::Neg(a) => match eval_value(a, env)? {
2179            Value::Scalar(c) => Value::Scalar(c.neg()),
2180            Value::Matrix(m) => Value::Matrix(map_mat(&m, |c| c.neg())),
2181        },
2182        E::Add(a, b) => c_bin(a, b, env, |x, y| Ok(x.add(y)))?,
2183        E::Sub(a, b) => c_bin(a, b, env, |x, y| Ok(x.sub(y)))?,
2184        E::Div(a, b) => {
2185            // **Matrix divided by scalar** is element-wise, consistent with the emission lane (the
2186            // Div branch of `flatten_matrix_value`
2187            // divides cell by cell); matrix divided by matrix is still rejected — that is exactly
2188            // the confusing point of "inversion"
2189            // semantics (`*` is the matrix product, so if `/` also did matrix algebra it would
2190            // become a solver).
2191            let (va, vb) = (eval_value(a, env)?, eval_value(b, env)?);
2192            match (va, vb) {
2193                (Value::Matrix(m), Value::Scalar(k)) => {
2194                    let mut rows = Vec::with_capacity(m.len());
2195                    for r in m {
2196                        let mut out = Vec::with_capacity(r.len());
2197                        for c in r {
2198                            out.push(c.div(k)?);
2199                        }
2200                        rows.push(out);
2201                    }
2202                    Value::Matrix(rows)
2203                }
2204                (Value::Matrix(_), Value::Matrix(_)) => {
2205                    return Err(Error::MatrixDivisionUnsupported("write the explicit inverse (`inv(A) * b`) or use a solver".into()))
2206                }
2207                (Value::Scalar(_), Value::Matrix(_)) => {
2208                    return Err(Error::MatrixScalarMix("a scalar divided by a matrix is undefined; write matrix equations as `inv(A) * b`".into()))
2209                }
2210                (x, y) => {
2211                    let (Value::Scalar(x), Value::Scalar(y)) = (x, y) else {
2212                        unreachable!("上面已排除所有含矩阵的情形")
2213                    };
2214                    Value::Scalar(x.div(y)?)
2215                }
2216            }
2217        }
2218        E::Pow(a, b) => {
2219            // Non-negative integer matrix powers (0..=8, power 0 = identity): the same folding
2220            // semantics as the generator.
2221            let base_is_matrix =
2222                matches!(a.as_ref(), Expr::Mat(_) | Expr::MatPattern(_)) || is_matrix_value(a);
2223            if base_is_matrix {
2224                let Expr::Num(k) = b.as_ref() else {
2225                    return Err(Error::InvalidInput(
2226                        "the exponent of a matrix power must be an integer constant".into(),
2227                    ));
2228                };
2229                if !(*k >= 0.0 && math::fract(*k) == 0.0 && *k <= 8.0) {
2230                    return Err(Error::InvalidInput(format!(
2231                        "matrix powers support non-negative integers 0–8, got {k}; write the explicit product or use a numeric library"
2232                    )));
2233                }
2234                let mut acc = eval_value(a, env)?;
2235                if *k == 0.0 {
2236                    let Value::Matrix(m) = acc else {
2237                        return Err(Error::ShapeMismatch(
2238                            "the base of a zero matrix power must be a square matrix".into(),
2239                        ));
2240                    };
2241                    if m.iter().any(|r| r.len() != m.len()) {
2242                        return Err(Error::ShapeMismatch(
2243                            "the base of a zero matrix power must be a square matrix".into(),
2244                        ));
2245                    }
2246                    return Ok(Value::Matrix(
2247                        (0..m.len())
2248                            .map(|i| {
2249                                (0..m.len())
2250                                    .map(|j| C::real(if i == j { 1.0 } else { 0.0 }))
2251                                    .collect()
2252                            })
2253                            .collect(),
2254                    ));
2255                }
2256                for _ in 1..(*k as usize) {
2257                    acc = mat_mul_value_of(acc, eval_value(a, env)?)?;
2258                }
2259                return Ok(acc);
2260            }
2261            // The exponent side uses the **precise predicate** (same shape as the base side):
2262            // `matrix_ish` is an over-approximation
2263            // that would misjudge exponents like `2 ^ det(J)` / `x ^ norm(v)` — "scalar value whose
2264            // parameters involve a matrix" — as matrices
2265            // (the emission lane gets the same expressions right).
2266            let expo_is_matrix =
2267                matches!(b.as_ref(), Expr::Mat(_) | Expr::MatPattern(_)) || is_matrix_value(b);
2268            if expo_is_matrix {
2269                return Err(Error::MatrixScalarMix(
2270                    "a matrix cannot be an exponent".into(),
2271                ));
2272            }
2273            c_bin(a, b, env, |x, y| x.pow(y))?
2274        }
2275        E::Mul(a, b) => {
2276            let (va, vb) = (eval_value(a, env)?, eval_value(b, env)?);
2277            mat_mul_value_of(va, vb)?
2278        }
2279        E::Call(name, args) => {
2280            let Some(arg) = args.first() else {
2281                // The real arity is unknown until the function is identified, so claim only
2282                // what is true: it needs an argument. A `FunctionArity { expected: 1 }` here
2283                // would lie for every multi-argument function (`max()`).
2284                return Err(Error::InvalidInput(format!("`{name}` needs an argument")));
2285            };
2286            if matches!(name.as_str(), "__quad_root_1" | "__quad_root_2") {
2287                if args.len() != 3 {
2288                    return Err(Error::FunctionArity {
2289                name: name.clone(),
2290                expected: 3,
2291                got: args.len(),
2292            });
2293                }
2294                let a = as_c(&eval_value(&args[0], env)?, "the quadratic coefficient")?;
2295                let b = as_c(&eval_value(&args[1], env)?, "the linear coefficient")?;
2296                let c = as_c(&eval_value(&args[2], env)?, "the constant term")?;
2297                return Ok(Value::Scalar(stable_quadratic_root(
2298                    name == "__quad_root_1",
2299                    a,
2300                    b,
2301                    c,
2302                )?));
2303            }
2304            // Dot product/norm: expand into an explicit expression, then evaluate (the same
2305            // strategy as det/trace, only one copy of the math)
2306            if name == "dot" || name == "norm" {
2307                let expanded = expand_call(e).ok_or_else(|| {
2308                    Error::InvalidInput(format!(
2309                        "`{name}` needs a concrete matrix literal (its shape is unknown at compile time)"
2310                    ))
2311                })?;
2312                return eval_value(&expanded, env);
2313            }
2314            // Linear solving / polynomial root finding: expand into an explicit expression first,
2315            // then evaluate (no second solver implementation)
2316            if name == "solve" || name == "roots" || name == "poly_coeffs" {
2317                let expanded = expand_call(e).ok_or_else(|| {
2318                    Error::InvalidInput(
2319                        "`solve` is not applicable here: the second argument must be a variable name and the equations must be linear in it".into(),
2320                    )
2321                })?;
2322                let value = eval_value(&expanded, env)?;
2323                if name == "roots" && !uses_complex(e) && value.is_complex() {
2324                    return Err(Error::UnsupportedOperation(
2325                        "the quadratic has no real roots; write the complex lane explicitly with `j`"
2326                            .into(),
2327                    ));
2328                }
2329                return Ok(value);
2330            }
2331            // Matrix operators: det / trace / conjugate transpose / inverse
2332            if matches!(name.as_str(), "det" | "trace" | "adjoint" | "inv") {
2333                let v = eval_value(arg, env)?;
2334                let m = match v {
2335                    Value::Matrix(m) => m,
2336                    Value::Scalar(_) => {
2337                        return Err(Error::MatrixScalarMix(format!(
2338                            "`{name}` needs a matrix argument, got a scalar"
2339                        )))
2340                    }
2341                };
2342                return match name.as_str() {
2343                    "trace" => {
2344                        if m.len() != m.first().map(|r| r.len()).unwrap_or(0) {
2345                            return Err(Error::ShapeMismatch(
2346                                "`trace` needs a square matrix".into(),
2347                            ));
2348                        }
2349                        let mut acc = C::ZERO;
2350                        for (i, row) in m.iter().enumerate() {
2351                            acc = acc.add(row[i]);
2352                        }
2353                        Ok(Value::Scalar(acc))
2354                    }
2355                    "det" => Ok(Value::Scalar(mat_det(&m)?)),
2356                    // inv goes through IR expansion (the same copy of the math as the emission
2357                    // lane: orders 2 and 3 are both supported).
2358                    // The value layer once had only a 2×2 closed form written, and `himari-eval`
2359                    // failed outright on its own order-3
2360                    // fixture — the two lanes must share the same implementation.
2361                    "inv" => {
2362                        let expanded = expand_matrix_call(e).ok_or_else(|| {
2363                            Error::InvalidInput(
2364                                "`inv` supports only square matrices of order 1 to 3 (use a numeric library for larger orders)".into(),
2365                            )
2366                        })?;
2367                        eval_value(&expanded, env)
2368                    }
2369                    _ => {
2370                        // adjoint = conjugate transpose (a plain transpose over the reals)
2371                        let cols = m.first().map(|r| r.len()).unwrap_or(0);
2372                        let mut t = vec![vec![C::ZERO; m.len()]; cols];
2373                        for (i, row) in m.iter().enumerate() {
2374                            for (j, c) in row.iter().enumerate() {
2375                                t[j][i] = c.conj();
2376                            }
2377                        }
2378                        Ok(Value::Matrix(t))
2379                    }
2380                };
2381            }
2382            if args.len() > 1 {
2383                let mut vals = Vec::with_capacity(args.len());
2384                for a in args {
2385                    vals.push(as_c(
2386                        &eval_value(a, env)?,
2387                        &format!("the argument of `{name}`"),
2388                    )?);
2389                }
2390                return Ok(Value::Scalar(c_call_n(name, &vals)?));
2391            }
2392            let c = as_c(&eval_value(arg, env)?, &format!("the argument of `{name}`"))?;
2393            Value::Scalar(c_call(name, c)?)
2394        }
2395        E::Mat(rows) => {
2396            let mut out = Vec::with_capacity(rows.len());
2397            for r in rows {
2398                let mut row = Vec::with_capacity(r.len());
2399                for cell in r {
2400                    row.push(as_c(&eval_value(cell, env)?, "a matrix element")?);
2401                }
2402                out.push(row);
2403            }
2404            Value::Matrix(out)
2405        }
2406        E::Transpose(a) => match eval_value(a, env)? {
2407            Value::Matrix(m) => {
2408                if m.is_empty() {
2409                    return Ok(Value::Matrix(vec![]));
2410                }
2411                let (r, c) = (m.len(), m[0].len());
2412                let mut t = vec![vec![C::ZERO; r]; c];
2413                for i in 0..r {
2414                    for j in 0..c {
2415                        t[j][i] = m[i][j];
2416                    }
2417                }
2418                Value::Matrix(t)
2419            }
2420            Value::Scalar(_) => {
2421                return Err(Error::MatrixScalarMix(
2422                    "a scalar cannot be transposed".into(),
2423                ))
2424            }
2425        },
2426        E::Sum {
2427            var,
2428            lower,
2429            upper,
2430            body,
2431        } => {
2432            let lo = eval_i(lower, env)?;
2433            let hi = eval_i(upper, env)?;
2434            if hi >= lo && (hi - lo) as u64 > MAX_STEPS {
2435                return Err(Error::InvalidInput(format!(
2436                "the sum would take {} steps (limit {MAX_STEPS}); sums are explicit teaching loops, not a numeric library",
2437                hi - lo + 1
2438            )));
2439            }
2440            let mut acc = C::ZERO;
2441            for k in lo..=hi {
2442                let mut inner = env.clone();
2443                inner.insert(var.clone(), k as f64);
2444                acc = acc.add(as_c(&eval_value(body, &inner)?, "the summand")?);
2445            }
2446            Value::Scalar(acc)
2447        }
2448        E::Integral {
2449            var,
2450            lower,
2451            upper,
2452            body,
2453        } => {
2454            let lo = eval(lower, env)?;
2455            let hi = eval(upper, env)?;
2456            // Composite Simpson (128 panels, weight 4 at odd indices): teaching accuracy, no
2457            // attempt at golub-welsch
2458            let n = 128usize;
2459            let h = (hi - lo) / n as f64;
2460            let f = |x: f64| -> Result<C, Error> {
2461                let mut inner = env.clone();
2462                inner.insert(var.clone(), x);
2463                as_c(&eval_value(body, &inner)?, "the integrand")
2464            };
2465            let mut acc = f(lo)?.add(f(hi)?);
2466            for k in 1..n {
2467                let x = lo + h * k as f64;
2468                let w = if k % 2 == 1 { 4.0 } else { 2.0 };
2469                acc = acc.add(f(x)?.mul(C::real(w)));
2470            }
2471            Value::Scalar(acc.mul(C::real(h / 3.0)))
2472        }
2473        E::Deriv(..) => return Err(Error::UnsupportedOperation(
2474            "`∂` is a symbolic operator: differentiate symbolically first, or use a finite difference".into(),
2475        )),
2476        E::Grad(_) | E::Laplacian(_) => {
2477            return Err(Error::UnsupportedOperation(
2478                "`∇`/`∇²` are symbolic operators: numeric evaluation needs a discretisation (use the code-generation lane)".into(),
2479            ))
2480        }
2481        E::Indexed { .. } => {
2482            return Err(Error::UnsupportedOperation(
2483            "evaluating an indexed symbol needs an index environment, which this version does not provide".into(),
2484        ))
2485        }
2486        E::MatPattern(_) => {
2487            return Err(Error::UnsupportedOperation(
2488                "evaluation does not take pattern matrices (call `recognize_pattern` first, then use the code-generation lane)".into(),
2489            ))
2490        }
2491    })
2492}
2493
2494fn map_mat(m: &[Vec<C>], f: impl Fn(C) -> C) -> Vec<Vec<C>> {
2495    m.iter()
2496        .map(|r| r.iter().map(|c| f(*c)).collect())
2497        .collect()
2498}
2499
2500/// Take the scalar view, otherwise give a **contextual** error (the matrix lane and the scalar
2501/// lane are never mixed).
2502fn as_c(v: &Value, what: &str) -> Result<C, Error> {
2503    v.as_scalar().ok_or_else(|| {
2504        Error::MatrixScalarMix(format!(
2505                "{what} must be a scalar (write matrices element by element; there is no implicit broadcast)"
2506            ))
2507    })
2508}
2509
2510/// Function registry: name → required arity.
2511///
2512/// **Single source of truth**: post-parse arity checking, evaluation, dimensions, emission and
2513/// write-back all consult this one table.
2514/// Previously each lane had its own match, so a defect such as "`arg` is emitted as a method that
2515/// does not exist in the real lane"
2516/// could survive a whole version.
2517pub fn func_arity(name: &str) -> Option<usize> {
2518    match name {
2519        // Unary scalar
2520        "exp" | "ln" | "log" | "sqrt" | "sin" | "cos" | "tan" | "sinh" | "cosh" | "tanh"
2521        | "abs" | "arg" | "conj" | "re" | "im" => Some(1),
2522        // Binary / ternary scalar (clamping and min/max on the game side)
2523        "min" | "max" => Some(2),
2524        "clamp" => Some(3),
2525        // Linear solving: solve(expr, x) solves `expr = 0` into `x = -b/a`
2526        "solve" => Some(2),
2527        "roots" => Some(2),
2528        "poly_coeffs" => Some(2),
2529        // Unary matrix operators
2530        "det" | "trace" | "adjoint" | "inv" | "norm" => Some(1),
2531        // Binary matrix operators (dot product: two equal-length sequences → a scalar)
2532        "dot" => Some(2),
2533        _ => None,
2534    }
2535}
2536
2537/// Edit distance (used only to find "which function you probably meant to write").
2538fn edit_distance(a: &str, b: &str) -> usize {
2539    let (a, b) = (a.as_bytes(), b.as_bytes());
2540    let mut prev: Vec<usize> = (0..=b.len()).collect();
2541    let mut cur = vec![0usize; b.len() + 1];
2542    for i in 1..=a.len() {
2543        cur[0] = i;
2544        for j in 1..=b.len() {
2545            let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
2546            cur[j] = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost);
2547        }
2548        core::mem::swap(&mut prev, &mut cur);
2549    }
2550    prev[b.len()]
2551}
2552
2553/// The function name in the registry closest to `name` (edit distance ≤ 2).
2554/// The **single list** of builtin functions (the truth source for `func_arity`). Used by the
2555/// "registry consistency" test:
2556/// adding an operator means changing only this and `func_arity`; a lane that forgets to register
2557/// it gets caught by the test.
2558pub const FUNC_NAMES: &[&str] = &[
2559    "exp",
2560    "ln",
2561    "log",
2562    "sqrt",
2563    "sin",
2564    "cos",
2565    "tan",
2566    "sinh",
2567    "cosh",
2568    "tanh",
2569    "abs",
2570    "arg",
2571    "conj",
2572    "re",
2573    "im",
2574    "min",
2575    "max",
2576    "clamp",
2577    "det",
2578    "trace",
2579    "adjoint",
2580    "inv",
2581    "solve",
2582    "roots",
2583    "poly_coeffs",
2584    "dot",
2585    "norm",
2586];
2587
2588pub fn closest_func(name: &str) -> Option<&'static str> {
2589    const NAMES: &[&str] = &[
2590        "exp",
2591        "ln",
2592        "log",
2593        "sqrt",
2594        "sin",
2595        "cos",
2596        "tan",
2597        "sinh",
2598        "cosh",
2599        "tanh",
2600        "abs",
2601        "arg",
2602        "conj",
2603        "re",
2604        "im",
2605        "min",
2606        "max",
2607        "clamp",
2608        "det",
2609        "trace",
2610        "adjoint",
2611        "inv",
2612        "solve",
2613        "roots",
2614        "poly_coeffs",
2615        "dot",
2616        "norm",
2617    ];
2618    // A flat "distance <= 2" admits nonsense for short names (`foo` → `log`, `x` → `exp`),
2619    // so short typos must be within one edit; longer names get two.
2620    let max_distance = if name.len() <= 4 { 1 } else { 2 };
2621    NAMES
2622        .iter()
2623        .map(|n| (*n, edit_distance(name, n)))
2624        .filter(|(_, d)| *d <= max_distance)
2625        .min_by_key(|(_, d)| *d)
2626        .map(|(n, _)| n)
2627}
2628
2629/// Arity checking of all function calls in an expression (called once at the end of the front-end
2630/// parse).
2631pub fn check_calls(e: &Expr) -> Result<(), Error> {
2632    check_calls_with_shapes(e, &runtime::RuntimeShapes::new())
2633}
2634
2635/// Validate calls with declaration ranks available, allowing runtime solve(A,b)
2636/// without weakening the existing symbolic solve checks.
2637pub fn check_calls_with_shapes(
2638    e: &Expr,
2639    runtime_shapes: &runtime::RuntimeShapes,
2640) -> Result<(), Error> {
2641    match e {
2642        Expr::Call(name, args) => {
2643            let Some(want) = func_arity(name) else {
2644                // The payload is the bare name; the spelling suggestion is the LSP quick-fix's
2645                // job (`closest_func` there), so the catalogue sentence stays translatable.
2646                // `suggestion` stays EMPTY unless a real near-match exists — echoing the
2647                // user's own typo back as advice is worse than no advice.
2648                let suggestion = closest_func(name).unwrap_or_default().to_string();
2649                return Err(Error::UnknownFunction {
2650                    name: name.clone(),
2651                    suggestion,
2652                });
2653            };
2654            if args.len() != want {
2655                return Err(Error::FunctionArity {
2656                    name: name.clone(),
2657                    expected: want,
2658                    got: args.len(),
2659                });
2660            }
2661            // poly_coeffs(poly, x): the same precondition as roots (a univariate polynomial in x)
2662            if name == "poly_coeffs" {
2663                let Expr::Var(v) = &args[1] else {
2664                    return Err(Error::InvalidInput(
2665                        "`poly_coeffs(poly, x)`: the second argument must be a variable name"
2666                            .into(),
2667                    ));
2668                };
2669                poly_coeffs_vec(&args[0], v)?;
2670            }
2671            // roots(poly, x): the second argument must be a variable name; the degree and
2672            // non-polynomial shapes are rejected right here
2673            if name == "roots" {
2674                let Expr::Var(v) = &args[1] else {
2675                    return Err(Error::InvalidInput(
2676                        "`roots(poly, x)`: the second argument must be a variable name".into(),
2677                    ));
2678                };
2679                solve_poly(&args[0], v)?;
2680            }
2681            // solve: both forms — single-variable `solve(eq, x)` and the system
2682            // `solve([eq…], [x…])` —
2683            // are solved once right at the parse exit (fail fast) — letting
2684            // non-linearity/underdetermination/contradiction blow up only at evaluation or
2685            // emission time amounts to pushing the error further away from the user.
2686            if name == "solve" {
2687                match &args[1] {
2688                    Expr::Var(v) => {
2689                        let is_runtime_solve = runtime::runtime_kind_of(&args[0], runtime_shapes)
2690                            .map(|kind| kind == runtime::RuntimeKind::Matrix)
2691                            .unwrap_or(false)
2692                            && runtime::runtime_kind_of(&args[1], runtime_shapes)
2693                                .map(|kind| kind == runtime::RuntimeKind::Vector)
2694                                .unwrap_or(false);
2695                        if !is_runtime_solve {
2696                            solve_linear(&args[0], v)?;
2697                        }
2698                    }
2699                    Expr::Mat(_) => {
2700                        let vars = mat_var_names(&args[1]).ok_or_else(|| {
2701                            Error::InvalidInput(
2702                                "`solve` expects its second argument to be a list of variable names"
2703                                    .into(),
2704                            )
2705                        })?;
2706                        let eqs = flat_mat_items(&args[0]).ok_or_else(|| {
2707                            Error::InvalidInput(
2708                                "`solve` expects its first argument to be a list of equations, each of the form `expr = 0`".into(),
2709                            )
2710                        })?;
2711                        solve_system(&eqs, &vars)?;
2712                    }
2713                    _ => {
2714                        return Err(Error::InvalidInput(
2715            "`solve(expr, x)`: the second argument must be a variable name or a list of names".into(),
2716        ))
2717                    }
2718                }
2719            }
2720            for a in args {
2721                check_calls_with_shapes(a, runtime_shapes)?;
2722            }
2723            Ok(())
2724        }
2725        Expr::Num(_) | Expr::Var(_) | Expr::Indexed { .. } => Ok(()),
2726        Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
2727            check_calls_with_shapes(a, runtime_shapes)?;
2728            check_calls(b)
2729        }
2730        Expr::Neg(a)
2731        | Expr::Transpose(a)
2732        | Expr::Grad(a)
2733        | Expr::Laplacian(a)
2734        | Expr::Deriv(a, _) => check_calls_with_shapes(a, runtime_shapes),
2735        Expr::Mat(rows) => {
2736            for r in rows {
2737                for c in r {
2738                    check_calls_with_shapes(c, runtime_shapes)?;
2739                }
2740            }
2741            Ok(())
2742        }
2743        Expr::MatPattern(p) => {
2744            for e in p.elements() {
2745                check_calls_with_shapes(e, runtime_shapes)?;
2746            }
2747            Ok(())
2748        }
2749        Expr::Sum {
2750            lower, upper, body, ..
2751        }
2752        | Expr::Integral {
2753            lower, upper, body, ..
2754        } => {
2755            check_calls_with_shapes(lower, runtime_shapes)?;
2756            check_calls_with_shapes(upper, runtime_shapes)?;
2757            check_calls_with_shapes(body, runtime_shapes)
2758        }
2759    }
2760}
2761
2762/// Scalar function registry — reals and complex numbers share one table (a real number is just a
2763/// complex number with zero imaginary part).
2764/// Unregistered names always error: silently falling back to 0 would let wrong formulas pass
2765/// through sick.
2766/// Evaluation of multi-argument/matrix operators (kept apart from the unary scalar table, so
2767/// min/max are not squeezed into the scalar match).
2768fn c_call_n(name: &str, args: &[C]) -> Result<C, Error> {
2769    let real = |v: C| -> Result<f64, Error> {
2770        if v.is_real() {
2771            Ok(v.re)
2772        } else {
2773            Err(Error::InvalidInput(format!(
2774                "`{name}` is defined for real numbers only (got {v:?})"
2775            )))
2776        }
2777    };
2778    Ok(match name {
2779        "min" => C::real(real(args[0])?.min(real(args[1])?)),
2780        "max" => C::real(real(args[0])?.max(real(args[1])?)),
2781        // clamp(v, lo, hi) = v.max(lo).min(hi) (the same shape as in Rust).
2782        // Note that with lo > hi the result is **hi** (max first, then min); no "swap the bounds"
2783        // guess is made —
2784        // guessing the bounds would silently turn a miswritten call into a clamp that "looks
2785        // fine".
2786        "clamp" => C::real(real(args[0])?.max(real(args[1])?).min(real(args[2])?)),
2787        other => {
2788            return Err(Error::InvalidInput(format!(
2789                "`{other}` is not a scalar multi-argument function"
2790            )))
2791        }
2792    })
2793}
2794
2795fn c_call(name: &str, x: C) -> Result<C, Error> {
2796    Ok(match name {
2797        "exp" => x.exp(),
2798        "ln" | "log" => x.ln()?,
2799        "sqrt" => x.sqrt(),
2800        "sin" => x.sin(),
2801        "cos" => x.cos(),
2802        "tan" => x.tan()?,
2803        "sinh" => x.sinh(),
2804        "cosh" => x.cosh(),
2805        "tanh" => x.tanh()?,
2806        // Four complex-specific ones: the result always lies on the real axis
2807        "abs" => C::real(x.abs()),
2808        "arg" => C::real(x.arg()),
2809        "conj" => x.conj(),
2810        "re" => C::real(x.re),
2811        "im" => C::real(x.im),
2812        other => {
2813            return Err(Error::UnsupportedOperation(format!(
2814                "the function `{other}` is not supported during evaluation"
2815            )))
2816        }
2817    })
2818}
2819
2820/// Determinant (complex-aware): recursive cofactor expansion along the first row, up to order 4.
2821///
2822/// The same algorithm as the IR-level `det_of` — if the two implementations disagreed, `det`'s
2823/// evaluation and the generated code
2824/// would give different numbers (that kind of defect is the hardest to find). The tests compare
2825/// numerically for orders 2/3/4.
2826fn mat_det(m: &[Vec<C>]) -> Result<C, Error> {
2827    let n = m.len();
2828    if n == 0 || m.iter().any(|r| r.len() != n) {
2829        return Err(Error::ShapeMismatch(
2830            "`det` needs a non-empty square matrix".into(),
2831        ));
2832    }
2833    if n > 4 {
2834        return Err(Error::InvalidInput(format!(
2835            "`det` supports orders 1–4 only (got {n}); use a numeric library for higher orders"
2836        )));
2837    }
2838    if n == 1 {
2839        return Ok(m[0][0]);
2840    }
2841    let mut acc = C::ZERO;
2842    for (j, cell) in m[0].iter().enumerate() {
2843        let sub: Vec<Vec<C>> = m
2844            .iter()
2845            .skip(1)
2846            .map(|row| {
2847                row.iter()
2848                    .enumerate()
2849                    .filter(|(c, _)| *c != j)
2850                    .map(|(_, x)| *x)
2851                    .collect()
2852            })
2853            .collect();
2854        let term = cell.mul(mat_det(&sub)?);
2855        acc = if j % 2 == 0 {
2856            acc.add(term)
2857        } else {
2858            acc.sub(term)
2859        };
2860    }
2861    Ok(acc)
2862}
2863
2864/// Scalar binary operations (complex-aware) + element-wise matrix operations (shapes must match
2865/// exactly).
2866fn c_bin(
2867    a: &Expr,
2868    b: &Expr,
2869    env: &HashMap<String, f64>,
2870    f: impl Fn(C, C) -> Result<C, Error>,
2871) -> Result<Value, Error> {
2872    let (va, vb) = (eval_value(a, env)?, eval_value(b, env)?);
2873    match (va, vb) {
2874        (Value::Scalar(x), Value::Scalar(y)) => Ok(Value::Scalar(f(x, y)?)),
2875        (Value::Matrix(ma), Value::Matrix(mb)) => {
2876            if ma.len() != mb.len() {
2877                return Err(Error::ShapeMismatch(format!(
2878                    "element-wise rows disagree: {} vs {}",
2879                    ma.len(),
2880                    mb.len()
2881                )));
2882            }
2883            let mut out = Vec::with_capacity(ma.len());
2884            for (ra, rb) in ma.iter().zip(mb.iter()) {
2885                if ra.len() != rb.len() {
2886                    return Err(Error::ShapeMismatch(format!(
2887                        "element-wise operation on matrices with different column counts: {} vs {}",
2888                        ra.len(),
2889                        rb.len()
2890                    )));
2891                }
2892                let mut row = Vec::with_capacity(ra.len());
2893                for (x, y) in ra.iter().zip(rb.iter()) {
2894                    row.push(f(*x, *y)?);
2895                }
2896                out.push(row);
2897            }
2898            Ok(Value::Matrix(out))
2899        }
2900        _ => Err(Error::MatrixScalarMix("write element-wise matrix/scalar operations explicitly (there is no implicit broadcast)".into())),
2901    }
2902}
2903
2904/// Multiplication on evaluated values: matrix×matrix, matrix×scalar, scalar×scalar.
2905fn mat_mul_value_of(a: Value, b: Value) -> Result<Value, Error> {
2906    match (a, b) {
2907        (Value::Scalar(x), Value::Scalar(y)) => Ok(Value::Scalar(x.mul(y))),
2908        (Value::Matrix(ma), Value::Matrix(mb)) => {
2909            let n_inner = ma.first().map(|r| r.len()).unwrap_or(0);
2910            if mb.len() != n_inner {
2911                return Err(Error::ShapeMismatch(format!(
2912                    "cannot multiply: inner dimension {n_inner} ≠ rows {}",
2913                    mb.len()
2914                )));
2915            }
2916            let cols = mb.first().map(|r| r.len()).unwrap_or(0);
2917            let mut out = vec![vec![C::ZERO; cols]; ma.len()];
2918            for (i, row) in ma.iter().enumerate() {
2919                for (j, cell) in out[i].iter_mut().enumerate() {
2920                    let mut acc = C::ZERO;
2921                    for (k, v) in row.iter().enumerate() {
2922                        acc = acc.add(v.mul(mb[k][j]));
2923                    }
2924                    *cell = acc;
2925                }
2926            }
2927            Ok(Value::Matrix(out))
2928        }
2929        (Value::Matrix(m), Value::Scalar(k)) => Ok(Value::Matrix(map_mat(&m, |v| v.mul(k)))),
2930        (Value::Scalar(k), Value::Matrix(m)) => Ok(Value::Matrix(map_mat(&m, |v| v.mul(k)))),
2931    }
2932}
2933
2934/// Evaluate summation bounds: must be integer-valued (the summation index is a counter).
2935fn eval_i(e: &Expr, env: &HashMap<String, f64>) -> Result<i64, Error> {
2936    let v = eval(e, env)?;
2937    if math::fract(v) != 0.0 {
2938        return Err(Error::InvalidInput(format!(
2939            "the sum bounds must be integers, got {v}"
2940        )));
2941    }
2942    Ok(v as i64)
2943}
2944
2945// ---------------------------------------------------------------- symbolic differentiation
2946
2947/// Whether the expression contains `diff`'s "not symbolically differentiable" marker
2948/// (`Num(NaN)`).
2949///
2950/// This is the last gate before emission/generation: once `NaN` is emitted as a literal,
2951/// the output contains an illegal `NaN` identifier, and the error points at the generated code.
2952pub fn contains_nan_expr(e: &Expr) -> bool {
2953    match e {
2954        Expr::Num(v) => v.is_nan(),
2955        Expr::Var(_) | Expr::Indexed { .. } => false,
2956        Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
2957            contains_nan_expr(a) || contains_nan_expr(b)
2958        }
2959        Expr::Neg(a)
2960        | Expr::Transpose(a)
2961        | Expr::Grad(a)
2962        | Expr::Laplacian(a)
2963        | Expr::Deriv(a, _) => contains_nan_expr(a),
2964        Expr::Call(_, args) => args.iter().any(contains_nan_expr),
2965        Expr::Mat(rows) => rows.iter().flatten().any(contains_nan_expr),
2966        Expr::MatPattern(p) => p.elements().into_iter().any(contains_nan_expr),
2967        Expr::Sum {
2968            lower, upper, body, ..
2969        }
2970        | Expr::Integral {
2971            lower, upper, body, ..
2972        } => contains_nan_expr(lower) || contains_nan_expr(upper) || contains_nan_expr(body),
2973    }
2974}
2975
2976/// Whether the expression contains **any** non-finite floating-point constant (inf / NaN).
2977///
2978/// `contains_nan_expr` only checks the NaN marker (diff's sentinel); the pre-emission constant
2979/// check
2980/// needs "any non-finite counts" (`inf` equally cannot be emitted as a legal literal).
2981pub fn contains_nonfinite_expr(e: &Expr) -> bool {
2982    match e {
2983        Expr::Num(v) => !v.is_finite(),
2984        Expr::Var(_) | Expr::Indexed { .. } => false,
2985        Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
2986            contains_nonfinite_expr(a) || contains_nonfinite_expr(b)
2987        }
2988        Expr::Neg(a)
2989        | Expr::Transpose(a)
2990        | Expr::Grad(a)
2991        | Expr::Laplacian(a)
2992        | Expr::Deriv(a, _) => contains_nonfinite_expr(a),
2993        Expr::Call(_, args) => args.iter().any(contains_nonfinite_expr),
2994        Expr::Mat(rows) => rows.iter().flatten().any(contains_nonfinite_expr),
2995        Expr::MatPattern(p) => p.elements().into_iter().any(contains_nonfinite_expr),
2996        Expr::Sum {
2997            lower, upper, body, ..
2998        }
2999        | Expr::Integral {
3000            lower, upper, body, ..
3001        } => {
3002            contains_nonfinite_expr(lower)
3003                || contains_nonfinite_expr(upper)
3004                || contains_nonfinite_expr(body)
3005        }
3006    }
3007}
3008
3009/// Names of functions/operators `diff` cannot symbolically differentiate (for a **named** error,
3010/// instead of just dropping a NaN and leaving the caller to guess).
3011pub fn nondiffable(e: &Expr) -> Vec<String> {
3012    fn go(e: &Expr, out: &mut Vec<String>) {
3013        match e {
3014            Expr::Call(n, args) => {
3015                // det/trace have IR-level expansions (after expansion they are ordinary
3016                // differentiable expressions),
3017                // adjoint is matrix-valued (the derivative lane does not take it anyway), so only
3018                // the following are truly non-differentiable
3019                // inv/adjoint are matrix-valued operators and never enter a scalar Jacobian (when
3020                // they appear in a scalar expression
3021                // they have already been absorbed by the trace/det expansion), so they do not count
3022                // as "non-differentiable"
3023                let named = matches!(n.as_str(), "arg" | "min" | "max" | "clamp");
3024                if named && !out.contains(n) {
3025                    out.push(n.clone());
3026                }
3027                for a in args {
3028                    go(a, out);
3029                }
3030            }
3031            Expr::Deriv(..) | Expr::Sum { .. } | Expr::Integral { .. } | Expr::Indexed { .. } => {
3032                if !out.contains(&"operators/sums/integrals".to_string()) {
3033                    out.push("operators/sums/integrals".to_string());
3034                }
3035            }
3036            Expr::Mat(rows) => {
3037                for r in rows {
3038                    for c in r {
3039                        go(c, out);
3040                    }
3041                }
3042            }
3043            Expr::MatPattern(p) => {
3044                for e in p.elements() {
3045                    go(e, out);
3046                }
3047            }
3048            Expr::Add(a, b)
3049            | Expr::Sub(a, b)
3050            | Expr::Mul(a, b)
3051            | Expr::Div(a, b)
3052            | Expr::Pow(a, b) => {
3053                go(a, out);
3054                go(b, out);
3055            }
3056            Expr::Neg(a) | Expr::Transpose(a) | Expr::Grad(a) | Expr::Laplacian(a) => go(a, out),
3057            _ => {}
3058        }
3059    }
3060    let mut out = Vec::new();
3061    go(e, &mut out);
3062    out
3063}
3064
3065pub fn diff(e: &Expr, x: &str) -> Expr {
3066    match e {
3067        Expr::Num(_) => num(0.0),
3068        Expr::Var(n) => num(if n == x { 1.0 } else { 0.0 }),
3069        Expr::Add(a, b) => add(diff(a, x), diff(b, x)),
3070        Expr::Sub(a, b) => sub(diff(a, x), diff(b, x)),
3071        Expr::Mul(a, b) => add(
3072            mul(diff(a, x), (**b).clone()),
3073            mul((**a).clone(), diff(b, x)),
3074        ),
3075        Expr::Div(a, b) => div(
3076            sub(
3077                mul(diff(a, x), (**b).clone()),
3078                mul((**a).clone(), diff(b, x)),
3079            ),
3080            pow((**b).clone(), num(2.0)),
3081        ),
3082        Expr::Neg(a) => neg(diff(a, x)),
3083        Expr::Pow(a, b) => match b.as_ref() {
3084            Expr::Num(n) => mul(mul(num(*n), pow((**a).clone(), num(n - 1.0))), diff(a, x)),
3085            _ => mul(
3086                pow((**a).clone(), (**b).clone()),
3087                add(
3088                    mul(diff(b, x), Expr::Call("ln".into(), vec![(**a).clone()])),
3089                    div(mul((**b).clone(), diff(a, x)), (**a).clone()),
3090                ),
3091            ),
3092        },
3093        Expr::Call(name, args) => {
3094            let Some(u) = args.first().cloned() else {
3095                return num(f64::NAN);
3096            };
3097            let du = diff(&u, x);
3098            let one = |v: Expr| Expr::Call(name.clone(), vec![v]);
3099            match name.as_str() {
3100                "exp" => mul(one(u), du),
3101                "ln" | "log" => div(du, u),
3102                "sin" => mul(Expr::Call("cos".into(), vec![u]), du),
3103                "cos" => neg(mul(Expr::Call("sin".into(), vec![u]), du)),
3104                "tan" => mul(add(num(1.0), pow(one(u), num(2.0))), du),
3105                "sinh" => mul(Expr::Call("cosh".into(), vec![u]), du),
3106                "cosh" => mul(Expr::Call("sinh".into(), vec![u]), du),
3107                "tanh" => mul(sub(num(1.0), pow(one(u), num(2.0))), du),
3108                "sqrt" => div(du, mul(num(2.0), one(u))),
3109                // |u| over the reals: d|u|/dx = (u/|u|)·u' (not differentiable at u=0, giving NaN
3110                // — that is a mathematical fact)
3111                "abs" => mul(div(u.clone(), Expr::Call("abs".into(), vec![u])), du),
3112                // det / trace: expand into an ordinary expression on the literal first, then
3113                // apply the chain rule
3114                "det" | "trace" | "solve" | "roots" | "dot" | "norm" => match expand_call(e) {
3115                    Some(expanded) => diff(&expanded, x),
3116                    None => num(f64::NAN),
3117                },
3118                // The piecewise selection of min/max/clamp cannot be expressed in the IR (there is
3119                // no comparison operator):
3120                // their derivatives need an "indicator function", and forcing it would produce an
3121                // expression that looks right but is wrong.
3122                "min" | "max" | "clamp" | "inv" => num(f64::NAN),
3123                // Over the reals conj/re/im are all identities, and the chain rule degenerates to
3124                // u'
3125                "conj" | "re" | "im" => du,
3126                // arg over the reals is only 0 or π (a step), not differentiable
3127                "arg" => num(f64::NAN),
3128                _ => num(f64::NAN),
3129            }
3130        }
3131        Expr::Mat(_) | Expr::MatPattern(_) => num(f64::NAN),
3132        Expr::Transpose(a) => transpose(diff(a, x)),
3133        // Chain rules for operators (∂²/ Leibniz) are future work: the first version gives NaN
3134        // explicitly and blocks it before emit
3135        Expr::Deriv(..)
3136        | Expr::Grad(_)
3137        | Expr::Laplacian(_)
3138        | Expr::Sum { .. }
3139        | Expr::Integral { .. }
3140        | Expr::Indexed { .. } => num(f64::NAN),
3141    }
3142}
3143
3144// ---------------------------------------------------------------- dimension checking
3145
3146pub fn dims_of(decls: &[Decl]) -> Result<HashMap<String, Dim>, Error> {
3147    let mut m = HashMap::new();
3148    for d in decls {
3149        let dim = match &d.unit {
3150            Some(u) => parse_unit(u).map_err(|unit| Error::DeclarationUnit {
3151                name: d.name.clone(),
3152                unit: Box::new(unit),
3153            })?,
3154            None => Dim::ZERO,
3155        };
3156        if m.insert(d.name.clone(), dim).is_some() {
3157            // A symbol declared twice with (possibly) different dimensions.
3158            return Err(Error::DuplicateDeclaration {
3159                name: d.name.clone(),
3160                line: None, // decl blocks carry no position; never fabricate line 0
3161            });
3162        }
3163    }
3164    Ok(m)
3165}
3166
3167fn is_zero_lit(e: &Expr) -> bool {
3168    matches!(e, Expr::Num(v) if *v == 0.0)
3169}
3170
3171/// The `+` / `-` arm of the dimension check, shared except for the operator name: the operator
3172/// is carried into the error so the message names the exact mismatch (a bare `{left} vs {right}`
3173/// reads the same for `+` and `-`, which cost a debugging round-trip to tell apart).
3174fn dim_addsub(a: &Expr, b: &Expr, op: &str, dims: &HashMap<String, Dim>) -> Result<Dim, Error> {
3175    // `0` is the zero element of **any** dimension space: the `0 - x` produced by symbolic
3176    // differentiation must not be judged a dimension conflict.
3177    if is_zero_lit(a) {
3178        return dim_check(b, dims);
3179    }
3180    if is_zero_lit(b) {
3181        return dim_check(a, dims);
3182    }
3183    let da = dim_check(a, dims)?;
3184    let db = dim_check(b, dims)?;
3185    if da != db {
3186        return Err(Error::OperatorDimensionMismatch {
3187            operator: op.into(),
3188            left: da.display(),
3189            right: db.display(),
3190        });
3191    }
3192    Ok(da)
3193}
3194
3195pub fn dim_check(e: &Expr, dims: &HashMap<String, Dim>) -> Result<Dim, Error> {
3196    use Expr::*;
3197    Ok(match e {
3198        Num(_) => Dim::ZERO,
3199        // Reserved symbol j = the imaginary unit, always dimensionless (used for EIS complex
3200        // impedance)
3201        Var(n) if n == "j" => Dim::ZERO,
3202        Var(n) => *dims
3203            .get(n)
3204            .ok_or_else(|| Error::UndeclaredSymbol(n.clone()))?,
3205        Neg(a) => dim_check(a, dims)?,
3206        Add(a, b) => dim_addsub(a, b, "+", dims)?,
3207        Sub(a, b) => dim_addsub(a, b, "-", dims)?,
3208        Mul(a, b) => dim_check(a, dims)?.mul_dim(dim_check(b, dims)?),
3209        Div(a, b) => dim_check(a, dims)?.div_dim(dim_check(b, dims)?),
3210        Pow(a, b) => {
3211            let db = dim_check(b, dims)?;
3212            if !db.is_zero() {
3213                return Err(Error::ExponentNotDimensionless(db.display()));
3214            }
3215            let da = dim_check(a, dims)?;
3216            // Rational exponents p/2 (including 0.5 and the **-0.5 produced by symbolic
3217            // differentiation**) are all handled as
3218            // `exp * p / 2`: every dimension exponent must be divisible by 2.
3219            //
3220            // Fold the exponent to a constant first: `f ^ (1/2)`, `T ^ (-1/2)` are **natural
3221            // notations**,
3222            // and requiring the caller to simplify first before passing the gate is a trap
3223            // (everyone forgets).
3224            let folded;
3225            let expo = match b.as_ref() {
3226                Num(n) => Some(*n),
3227                other => {
3228                    // Use recursive simplify rather than a single level of fold_const:
3229                    // notations like `(1+1)/2`,
3230                    // `2*0.5` should pass the gate too
3231                    folded = simplify(other);
3232                    match &folded {
3233                        Num(n) => Some(*n),
3234                        _ => None,
3235                    }
3236                }
3237            };
3238            // When the base is already dimensionless, any (dimensionless) exponent keeps it
3239            // dimensionless: `2^j`, `j^j`
3240            // can be computed at the value layer, so the dimension gate should not block them
3241            // (otherwise "complex powers" would be an empty promise to the outside)
3242            if da.is_zero() {
3243                return Ok(Dim::ZERO);
3244            }
3245            match expo {
3246                Some(n) => {
3247                    let two_n = n * 2.0;
3248                    if math::fract(two_n) != 0.0 || two_n.abs() > 1.0e6 {
3249                        return Err(Error::ExponentNotHalfInteger(format!("{n} is not p/2")));
3250                    }
3251                    let p = two_n as i32;
3252                    let mut r = [0i16; 7];
3253                    for (a, b) in r.iter_mut().zip(da.0) {
3254                        let prod = b as i32 * p;
3255                        if prod % 2 != 0 {
3256                            return Err(Error::InvalidInput(format!(
3257                                "`^{n}` needs every exponent of {} to stay even after scaling by {p}, otherwise the dimension is undefined",
3258                                da.display()
3259                            )));
3260                        }
3261                        *a = (prod / 2) as i16;
3262                    }
3263                    Dim(r)
3264                }
3265                None => {
3266                    return Err(Error::InvalidInput(
3267                        "the exponent must be a numeric constant".into(),
3268                    ))
3269                }
3270            }
3271        }
3272        Call(name, args) => {
3273            let Some(arg0) = args.first() else {
3274                // Same as the eval lane: the real arity is unknown until the function is
3275                // identified, so claim only what is true.
3276                return Err(Error::InvalidInput(format!("`{name}` needs an argument")));
3277            };
3278            // The system form `solve([eq…], [x…])`: `arg0` is a **list of equations**,
3279            // each equation only needs to be **homogeneous under addition/subtraction** on its
3280            // own, and different equations may have different dimensions
3281            // (a force balance is N, a geometric constraint is m — that is a completely legal
3282            // system).
3283            // Going through the generic `Mat` check would require the elements to share a
3284            // dimension, and would wrongly reject such systems.
3285            if name == "solve" && matches!(arg0, Expr::Mat(_)) {
3286                if let Some(eqs) = flat_mat_items(arg0) {
3287                    for eq in &eqs {
3288                        // Homogeneity of a single equation: not required to equal some particular
3289                        // dimension, only to check through
3290                        dim_check(eq, dims)?;
3291                    }
3292                }
3293                return match expand_call(e) {
3294                    Some(x) => dim_check(&x, dims),
3295                    None => Err(Error::InvalidInput(
3296            "`solve` needs its second argument to be a variable name or a list of names, and the equations to be linear in the unknowns".into(),
3297        )),
3298                };
3299            }
3300            if matches!(name.as_str(), "__quad_root_1" | "__quad_root_2") {
3301                if args.len() != 3 {
3302                    return Err(Error::FunctionArity {
3303                        name: name.clone(),
3304                        expected: 3,
3305                        got: args.len(),
3306                    });
3307                }
3308                // When a·x²+b·x+c is homogeneous, both b/a and c/b have x's dimension.
3309                let da = dim_check(&args[0], dims)?;
3310                let db = dim_check(&args[1], dims)?;
3311                return Ok(db.div_dim(da));
3312            }
3313            let d = dim_check(arg0, dims)?;
3314            match name.as_str() {
3315                "exp" | "ln" | "log" | "sin" | "cos" | "tan" | "sinh" | "cosh" | "tanh" => {
3316                    if !d.is_zero() {
3317                        return Err(Error::InvalidInput(format!(
3318                            "`{name}` arguments must be dimensionless, got {}",
3319                            d.display()
3320                        )));
3321                    }
3322                    Dim::ZERO
3323                }
3324                "sqrt" => {
3325                    let mut r = [0i16; 7];
3326                    for (a, b) in r.iter_mut().zip(d.0) {
3327                        if b % 2 != 0 {
3328                            return Err(Error::InvalidInput(format!(
3329                                "`sqrt` needs a dimension whose exponents are all even, got {}",
3330                                d.display()
3331                            )));
3332                        }
3333                        *a = b / 2;
3334                    }
3335                    Dim(r)
3336                }
3337                // The four/five complex ones: modulus / argument / conjugate / real part /
3338                // imaginary part.
3339                // arg is always dimensionless (radians); the rest keep the argument's dimension.
3340                "arg" => Dim::ZERO,
3341                "abs" | "conj" | "re" | "im" => d,
3342                // min/max/clamp: all three arguments must share a dimension, and the result has
3343                // the same dimension
3344                "min" | "max" | "clamp" => {
3345                    for a in &args[1..] {
3346                        let other = dim_check(a, dims)?;
3347                        if other != d {
3348                            return Err(Error::InvalidInput(format!(
3349                                "`{name}` requires all its arguments to have the same dimension: {} vs {}",
3350                                d.display(),
3351                                other.display()
3352                            )));
3353                        }
3354                    }
3355                    d
3356                }
3357                // Matrix operators: det is the n-th power, trace/adjoint keep the same dimension.
3358                // For the order, prefer flatten (which looks through inv/adjoint — after folding
3359                // they are
3360                // literals), so `det(inv(J))` is no longer wrongly rejected by the dimension
3361                // gate.
3362                "det" => {
3363                    let n = match flatten_matrix_value(&args[0]) {
3364                        Some(m) if !m.is_empty() && m.iter().all(|r| r.len() == m.len()) => m.len(),
3365                        _ => match shape_of(&args[0])? {
3366                            Some((r, c)) if r == c && r > 0 => r,
3367                            _ => {
3368                                return Err(Error::InvalidInput("`det` needs a concrete square matrix literal (its shape is unknown, so the dimension cannot be computed)".into()))
3369                            }
3370                        },
3371                    };
3372                    d.scale_ratio(n as i32, 1)?
3373                }
3374                "trace" | "adjoint" => d,
3375                // The dimension of an inverse matrix is the reciprocal
3376                "inv" => d.scale_ratio(-1, 1)?,
3377                // Dot product: both sides must share a dimension, and the result is the square of
3378                // that dimension
3379                "dot" => {
3380                    let d2 = dim_check(&args[1], dims)?;
3381                    if d2 != d {
3382                        return Err(Error::InvalidInput(format!(
3383                            "`dot` requires both arguments to have the same dimension: {} vs {}",
3384                            d.display(),
3385                            d2.display()
3386                        )));
3387                    }
3388                    d.mul_dim(d)
3389                }
3390                // Norm: √Σv² has the same dimension as the elements
3391                "norm" => d,
3392                // Linear solving / root finding / coefficient extraction: the dimension is always
3393                // determined by the expansion (single mathematical source)
3394                "roots" | "solve" | "poly_coeffs" => {
3395                    // A coefficient vector requires **elements of the same dimension** (the value
3396                    // lane of matrix expressions), while for a homogeneous polynomial
3397                    // the c_k have dimension `dim(poly)/dim(x)^k` — they agree only when x is
3398                    // dimensionless.
3399                    // This is not an implementation restriction but an algebraic fact: numbers of
3400                    // different dimensions cannot be arranged into a matrix.
3401                    // So it is explained explicitly here, rather than letting downstream report
3402                    // "inconsistent matrix element dimensions: m vs 1".
3403                    if name == "poly_coeffs" {
3404                        if let Some(Expr::Var(v)) = args.get(1) {
3405                            let dv = dims.get(v).copied().unwrap_or(Dim::ZERO);
3406                            if !dv.is_zero() {
3407                                return Err(Error::InvalidInput(format!(
3408                "`poly_coeffs`: the coefficients of `{v}` have dimension {}, but matrix elements must share one dimension; take coefficients of a dimensionless variable (for example divide by a scale first) or use `roots`",
3409                dv.display()
3410            )));
3411                            }
3412                        }
3413                    }
3414                    match expand_call(e) {
3415                        Some(x) => return dim_check(&x, dims),
3416                        // The error message must use the **actual** function name and criterion:
3417                        // `roots` talks about polynomials,
3418                        // not "the equation is linear in it" (a `roots(exp(x), x)` used to be
3419                        // reported as a solve error).
3420                        None if name == "poly_coeffs" => {
3421                            return Err(Error::InvalidInput(
3422            "`poly_coeffs(poly, x)` needs its second argument to be a variable name and its first to be a univariate polynomial in it".into(),
3423        ))
3424                        }
3425                        None if name == "roots" => {
3426                            return Err(Error::InvalidInput(
3427            "`roots(poly, x)` needs its second argument to be a variable name and its first to be a univariate polynomial in it".into(),
3428        ))
3429                        }
3430                        None => return Err(Error::InvalidInput(
3431            "`solve` needs its second argument to be a variable name and the equation to be linear in it".into(),
3432        )),
3433                    }
3434                }
3435                other => {
3436                    return Err(Error::UnknownFunction {
3437                        name: other.to_string(),
3438                        suggestion: String::new(),
3439                    })
3440                }
3441            }
3442        }
3443        Mat(rows) => {
3444            let mut acc: Option<Dim> = None;
3445            for r in rows {
3446                for c in r {
3447                    if is_zero_lit(c) {
3448                        continue; // the zero element is dimension-polymorphic
3449                    }
3450                    let d = dim_check(c, dims)?;
3451                    match acc {
3452                        None => acc = Some(d),
3453                        Some(prev) if prev == d => {}
3454                        Some(prev) => {
3455                            return Err(Error::InvalidInput(format!(
3456                                "matrix elements must all share one dimension: {} vs {}",
3457                                prev.display(),
3458                                d.display()
3459                            )))
3460                        }
3461                    }
3462                }
3463            }
3464            acc.unwrap_or(Dim::ZERO)
3465        }
3466        MatPattern(p) => {
3467            // A pattern matrix only constrains its **concrete** elements (ellipsis cells do not
3468            // participate).
3469            let grid = p.grid().ok_or_else(|| {
3470                Error::ShapeMismatch("pattern matrix rows have inconsistent lengths".into())
3471            })?;
3472            if grid.0 < 2 || grid.1 < 2 {
3473                return Err(Error::InvalidInput(
3474                    "a pattern matrix must be at least 2×2, otherwise the ellipsis means nothing"
3475                        .into(),
3476                ));
3477            }
3478            let mut acc: Option<Dim> = None;
3479            for e in p.elements() {
3480                if is_zero_lit(e) {
3481                    continue; // the zero element is dimension-polymorphic
3482                }
3483                let d = dim_check(e, dims)?;
3484                match acc {
3485                    None => acc = Some(d),
3486                    Some(prev) if prev == d => {}
3487                    Some(prev) => {
3488                        return Err(Error::InvalidInput(format!(
3489                            "pattern-matrix elements must all share one dimension: {} vs {}",
3490                            prev.display(),
3491                            d.display()
3492                        )))
3493                    }
3494                }
3495            }
3496            acc.unwrap_or(Dim::ZERO)
3497        }
3498        Transpose(a) => dim_check(a, dims)?,
3499        Deriv(u, by) => {
3500            let du = dim_check(u, dims)?;
3501            // The differentiation variable must have a known dimension (implicit function
3502            // differentiation is not in the first version)
3503            let dx = *dims
3504                .get(by)
3505                .ok_or_else(|| Error::UndeclaredSymbol(by.clone()))?;
3506            du.div_dim(dx)
3507        }
3508        Grad(u) => dim_check(u, dims)?.div_dim(parse_unit("m")?), // Cartesian metric assumption
3509        Laplacian(u) => {
3510            let d = dim_check(u, dims)?;
3511            let m2 = parse_unit("m")?.scale_ratio(2, 1)?;
3512            d.div_dim(m2)
3513        }
3514        Sum {
3515            var,
3516            lower,
3517            upper,
3518            body,
3519        } => {
3520            let dl = dim_check(lower, dims)?;
3521            let du = dim_check(upper, dims)?;
3522            if !dl.is_zero() || !du.is_zero() {
3523                return Err(Error::InvalidInput(
3524                    "the sum bounds must be dimensionless (the index is a counter)".into(),
3525                ));
3526            }
3527            let mut inner = dims.clone();
3528            inner.insert(var.clone(), Dim::ZERO); // the bound index is dimensionless
3529            dim_check(body, &inner)?
3530        }
3531        Integral {
3532            var,
3533            lower,
3534            upper,
3535            body,
3536        } => {
3537            let dl = dim_check(lower, dims)?;
3538            let du = dim_check(upper, dims)?;
3539            let dv = *dims
3540                .get(var)
3541                .ok_or_else(|| Error::UndeclaredSymbol(var.clone()))?;
3542            if dl != du {
3543                return Err(Error::DimensionMismatch {
3544                    left: dl.display().to_string(),
3545                    right: du.display().to_string(),
3546                });
3547            }
3548            let db = dim_check(body, dims)?;
3549            db.mul_dim(dv)
3550        }
3551        Indexed { name, indices } => {
3552            let d = *dims
3553                .get(name)
3554                .ok_or_else(|| Error::UndeclaredSymbol(name.clone()))?;
3555            for i in indices {
3556                if !dims.get(i).map(|x| x.is_zero()).unwrap_or(false) {
3557                    return Err(Error::InvalidInput(format!(
3558                "the index `{i}` must be a dimensionless symbol (it is undeclared or carries a dimension)"
3559            )));
3560                }
3561            }
3562            d
3563        }
3564    })
3565}
3566
3567// ---------------------------------------------------------------- structural key (CSE / equality)
3568
3569pub fn key(e: &Expr) -> String {
3570    let mut s = String::new();
3571    key_into(e, &mut s);
3572    s
3573}
3574
3575fn key_into(e: &Expr, s: &mut String) {
3576    match e {
3577        Expr::Num(v) => {
3578            let _ = write!(s, "#{:016x}", v.to_bits());
3579        }
3580        Expr::Var(n) => {
3581            s.push('$');
3582            s.push_str(n);
3583        }
3584        Expr::Add(a, b) => bin(s, 'A', a, b),
3585        Expr::Sub(a, b) => bin(s, 'S', a, b),
3586        Expr::Mul(a, b) => bin(s, 'M', a, b),
3587        Expr::Div(a, b) => bin(s, 'D', a, b),
3588        Expr::Pow(a, b) => bin(s, 'P', a, b),
3589        Expr::Neg(a) => {
3590            s.push_str("(N");
3591            key_into(a, s);
3592            s.push(')');
3593        }
3594        Expr::Call(n, args) => {
3595            s.push_str("(C");
3596            s.push_str(n);
3597            for a in args {
3598                key_into(a, s);
3599            }
3600            s.push(')');
3601        }
3602        Expr::Mat(rows) => {
3603            s.push_str("(T");
3604            for r in rows {
3605                for c in r {
3606                    key_into(c, s);
3607                }
3608                s.push('|');
3609            }
3610            s.push(')');
3611        }
3612        Expr::MatPattern(p) => {
3613            s.push_str("(TP");
3614            for r in &p.rows {
3615                for c in r {
3616                    match c {
3617                        PatternCell::El(e) => key_into(e, s),
3618                        PatternCell::Dots => s.push('\u{b7}'),
3619                    }
3620                }
3621                s.push('|');
3622            }
3623            s.push(')');
3624        }
3625        Expr::Transpose(a) => {
3626            s.push_str("(TR");
3627            key_into(a, s);
3628            s.push(')');
3629        }
3630        Expr::Deriv(u, by) => {
3631            s.push_str("(DV");
3632            key_into(u, s);
3633            s.push('$');
3634            s.push_str(by);
3635            s.push(')');
3636        }
3637        Expr::Grad(u) => {
3638            s.push_str("(GR");
3639            key_into(u, s);
3640            s.push(')');
3641        }
3642        Expr::Laplacian(u) => {
3643            s.push_str("(LP");
3644            key_into(u, s);
3645            s.push(')');
3646        }
3647        Expr::Sum {
3648            var,
3649            lower,
3650            upper,
3651            body,
3652        } => {
3653            s.push_str("(SM$");
3654            s.push_str(var);
3655            key_into(lower, s);
3656            key_into(upper, s);
3657            key_into(body, s);
3658            s.push(')');
3659        }
3660        Expr::Integral {
3661            var,
3662            lower,
3663            upper,
3664            body,
3665        } => {
3666            s.push_str("(IN$");
3667            s.push_str(var);
3668            key_into(lower, s);
3669            key_into(upper, s);
3670            key_into(body, s);
3671            s.push(')');
3672        }
3673        Expr::Indexed { name, indices } => {
3674            s.push_str("(IX$");
3675            s.push_str(name);
3676            for i in indices {
3677                s.push('$');
3678                s.push_str(i);
3679            }
3680            s.push(')');
3681        }
3682    }
3683}
3684
3685fn bin(s: &mut String, tag: char, a: &Expr, b: &Expr) {
3686    s.push('(');
3687    s.push(tag);
3688    key_into(a, s);
3689    key_into(b, s);
3690    s.push(')');
3691}
3692
3693// ---------------------------------------------------------------- LaTeX write-back
3694
3695fn vs(n: &str) -> Expr {
3696    Expr::Var(n.to_string())
3697}
3698
3699pub fn to_latex(e: &Expr) -> String {
3700    to_latex_prec(e, 0)
3701}
3702
3703/// Precedence-aware LaTeX write-back: `(j·ω)^(1/2)` without its parentheses renders as `j·√ω`
3704/// — the write-back is the same single source of truth for doc comments / hover / sidecar, so
3705/// wrong parentheses mean a wrong formula.
3706fn to_latex_prec(e: &Expr, min: u8) -> String {
3707    let (text, p) = to_latex_raw(e);
3708    wrap(text, p, min)
3709}
3710
3711fn to_latex_raw(e: &Expr) -> (String, u8) {
3712    match e {
3713        Expr::Num(v) => (fmt_num(*v), 9),
3714        Expr::Var(n) => (latex_var(n), 9),
3715        Expr::Neg(a) => (format!("-{}", to_latex_prec(a, 5)), 4),
3716        Expr::Add(a, b) => (
3717            format!("{} + {}", to_latex_prec(a, 2), to_latex_prec(b, 3)),
3718            2,
3719        ),
3720        Expr::Sub(a, b) => (
3721            format!("{} - {}", to_latex_prec(a, 2), to_latex_prec(b, 3)),
3722            2,
3723        ),
3724        Expr::Mul(a, b) => (
3725            format!("{} \\cdot {}", to_latex_prec(a, 3), to_latex_prec(b, 4)),
3726            3,
3727        ),
3728        // \frac already groups, so numerator and denominator need no extra parentheses
3729        Expr::Div(a, b) => (
3730            format!(
3731                "\\frac{{{}}}{{{}}}",
3732                to_latex_prec(a, 0),
3733                to_latex_prec(b, 0)
3734            ),
3735            3,
3736        ),
3737        // The superscript braces already group, but if the **base** is itself a power/transpose it
3738        // must get parentheses:
3739        // `x^{2}^{3}` is a TeX double-superscript error (rendering fails outright), and
3740        // `x^{T}^{2}` would also be
3741        // parsed back as Pow(Pow(x,T),2) — the transpose is lost. Hence min is taken as 7 > the
3742        // power precedence 6.
3743        Expr::Pow(a, b) => (
3744            format!("{}^{{{}}}", to_latex_prec(a, 7), to_latex_prec(b, 0)),
3745            6,
3746        ),
3747        Expr::Call(n, args) => {
3748            let inner: Vec<String> = args.iter().map(|x| to_latex_prec(x, 0)).collect();
3749            let text = match n.as_str() {
3750                // This dialect accepts only \sqrt{...} (\sqrt(...) is not LaTeX syntax)
3751                "sqrt" => format!("\\sqrt{{{}}}", inner.join(", ")),
3752                // The complex operators have no fixed glyph (`|z|` is ambiguous with matrix/
3753                // determinant delimiters),
3754                // so they are spelled with \operatorname{...}, ensuring the write-back can be
3755                // consumed verbatim by the parser.
3756                "abs" | "arg" | "conj" | "re" | "im" | "clamp" | "trace" | "adjoint" | "inv"
3757                | "solve" | "roots" | "poly_coeffs" | "norm" | "dot" => {
3758                    format!("\\operatorname{{{}}}({})", n, inner.join(", "))
3759                }
3760                _ => format!("\\{}({})", n.as_str(), inner.join(", ")),
3761            };
3762            (text, 9)
3763        }
3764        Expr::Mat(rows) => {
3765            let body: Vec<String> = rows
3766                .iter()
3767                .map(|r| {
3768                    r.iter()
3769                        .map(|x| to_latex_prec(x, 0))
3770                        .collect::<Vec<_>>()
3771                        .join(" & ")
3772                })
3773                .collect();
3774            (
3775                format!("\\begin{{bmatrix}}{}\\end{{bmatrix}}", body.join(" \\\\ ")),
3776                9,
3777            )
3778        }
3779        Expr::MatPattern(p) => {
3780            let (m, n) = p.grid().unwrap_or((p.rows.len(), 0));
3781            let has_el_row: Vec<bool> = p
3782                .rows
3783                .iter()
3784                .map(|r| r.iter().any(|c| matches!(c, PatternCell::El(_))))
3785                .collect();
3786            let has_el_col: Vec<bool> = (0..n.max(p.rows.first().map(|r| r.len()).unwrap_or(0)))
3787                .map(|j| {
3788                    p.rows
3789                        .iter()
3790                        .any(|r| matches!(r.get(j), Some(PatternCell::El(_))))
3791                })
3792                .collect();
3793            let _ = m;
3794            let body: Vec<String> = p
3795                .rows
3796                .iter()
3797                .enumerate()
3798                .map(|(i, r)| {
3799                    r.iter()
3800                        .enumerate()
3801                        .map(|(j, c)| match c {
3802                            PatternCell::El(e) => to_latex_prec(e, 0),
3803                            PatternCell::Dots => {
3804                                // Direction inference: the row has a concrete element → cdots;
3805                                // otherwise the column has one → vdots; otherwise ddots.
3806                                if has_el_row[i] {
3807                                    "\\cdots".to_string()
3808                                } else if has_el_col[j] {
3809                                    "\\vdots".to_string()
3810                                } else {
3811                                    "\\ddots".to_string()
3812                                }
3813                            }
3814                        })
3815                        .collect::<Vec<_>>()
3816                        .join(" & ")
3817                })
3818                .collect();
3819            (
3820                format!("\\begin{{bmatrix}}{}\\end{{bmatrix}}", body.join(" \\\\ ")),
3821                9,
3822            )
3823        }
3824        Expr::Transpose(a) => (
3825            // If the transpose's base is another transpose: `x^{T}^{T}` is a TeX double-superscript
3826            // error, so it must get parentheses
3827            format!("{}^{{T}}", to_latex_prec(a, 7)),
3828            6,
3829        ),
3830        Expr::Deriv(u, by) => (
3831            format!(
3832                "\\frac{{\\partial {}}}{{\\partial {}}}",
3833                to_latex_prec(u, 0),
3834                to_latex_prec(&vs(by), 0)
3835            ),
3836            3,
3837        ),
3838        // ∇ is a **prefix** operator: when it is the base of a power/transpose it must get
3839        // parentheses, otherwise
3840        // `(∇u)^2` and `∇(u^2)` would be written as the same string (the semantics get
3841        // rewritten). p=5 < 7.
3842        Expr::Grad(u) => (format!("\\nabla {}", to_latex_prec(u, 5)), 5),
3843        Expr::Laplacian(u) => (format!("\\nabla^2 {}", to_latex_prec(u, 5)), 5),
3844        Expr::Sum {
3845            var,
3846            lower,
3847            upper,
3848            body,
3849        } => (
3850            format!(
3851                "\\sum_{{{}={}}}^{{{}}} {}",
3852                to_latex_prec(&vs(var), 0),
3853                to_latex_prec(lower, 0),
3854                to_latex_prec(upper, 0),
3855                to_latex_prec(body, 5)
3856            ),
3857            // Must get parentheses as a power base: `\sum i^{2}` with another superscript is a TeX
3858            // double-superscript error
3859            5,
3860        ),
3861        Expr::Integral {
3862            var,
3863            lower,
3864            upper,
3865            body,
3866        } => (
3867            format!(
3868                "\\int_{{{}}}^{{{}}} {} \\, d{}",
3869                to_latex_prec(lower, 0),
3870                to_latex_prec(upper, 0),
3871                to_latex_prec(body, 5),
3872                to_latex_prec(&vs(var), 0)
3873            ),
3874            5,
3875        ),
3876        Expr::Indexed { name, indices } => {
3877            let idx: Vec<String> = indices.iter().map(|i| to_latex_prec(&vs(i), 0)).collect();
3878            (
3879                format!("{}_{{{}}}", to_latex_prec(&vs(name), 0), idx.join(", ")),
3880                9,
3881            )
3882        }
3883    }
3884}
3885
3886/// Variable name → LaTeX form.
3887///
3888/// Three cases, and the order must not change:
3889/// 1. A single ASCII letter → verbatim (`x`);
3890/// 2. The name is **exactly** a Greek letter name (or its `_subscript` form) → the real glyph
3891///    (`sigma` → `\sigma`);
3892/// 3. Any other multi-letter name → `\mathrm{name}`.
3893///
3894/// The implementation used to be `replace("alpha", "\\alpha").replace("eta", "\\eta")` — that is
3895/// **substring replacement**: `alphabet` became `\alphabet`, `betamax` became `b\etamax`,
3896/// and the more common `sigma` was treated as the product of the five variables s·i·g·m·a. The
3897/// write-back is the same single source of truth for hover/sidecar/doc,
3898/// so being wrong here means the formula is wrong.
3899pub fn latex_var(n: &str) -> String {
3900    const GREEK: &[&str] = &[
3901        "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa",
3902        "lambda", "mu", "nu", "xi", "pi", "rho", "sigma", "tau", "upsilon", "phi", "chi", "psi",
3903        "omega", "Gamma", "Delta", "Theta", "Lambda", "Xi", "Sigma", "Upsilon", "Phi", "Psi",
3904        "Omega",
3905    ];
3906    if n.len() == 1 && n.chars().all(|c| c.is_ascii_alphabetic()) {
3907        return n.to_string();
3908    }
3909    let (head, tail) = match n.split_once('_') {
3910        Some((h, t)) => (h, format!("_{t}")),
3911        None => (n, String::new()),
3912    };
3913    if GREEK.contains(&head) {
3914        return format!("\\{head}{tail}");
3915    }
3916    format!("\\mathrm{{{n}}}")
3917}
3918
3919pub fn fmt_num(v: f64) -> String {
3920    if v == math::trunc(v) && v.abs() < 1e15 {
3921        format!("{v:.0}")
3922    } else {
3923        format!("{v:?}")
3924    }
3925}
3926
3927// ---------------------------------------------------------------- Rust code generation
3928
3929fn wrap(s: String, p: u8, min: u8) -> String {
3930    if p < min {
3931        format!("({s})")
3932    } else {
3933        s
3934    }
3935}
3936
3937fn rust_ident(n: &str) -> String {
3938    let mut s: String = n
3939        .chars()
3940        .map(|c| {
3941            if c.is_ascii_alphanumeric() || c == '_' {
3942                c
3943            } else {
3944                '_'
3945            }
3946        })
3947        .collect();
3948    if s.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(true) {
3949        s.insert(0, '_');
3950    }
3951    s
3952}
3953
3954/// Generate a block expression: named intermediates (one `let tN` per shared subtree) + the final
3955/// expression.
3956///
3957/// The named intermediates are the real source of "readability": debugger / profiler / generated
3958/// code are aligned through them.
3959/// Floating-point width of the generated code. The `f32` variant only swaps the **literal suffix**
3960/// (all other emission rules are identical).
3961#[derive(Clone, Copy, PartialEq)]
3962pub enum Fx {
3963    F64,
3964    F32,
3965    /// `no_std` + `libm`: transcendental functions go through `libm::*`, integer powers through
3966    /// `libm::pow`
3967    /// (`f64::powi` is a std thing, not available in `core`).
3968    F64Libm,
3969}
3970
3971impl Fx {
3972    /// Literal text: `f64` keeps `{:?}` verbatim, `f32` adds a suffix to force type inference.
3973    fn lit(self, v: f64) -> String {
3974        match self {
3975            Fx::F64 | Fx::F64Libm => format!("{v:?}"),
3976            Fx::F32 => format!("{:?}f32", v as f32),
3977        }
3978    }
3979
3980    fn is_libm(self) -> bool {
3981        matches!(self, Fx::F64Libm)
3982    }
3983}
3984
3985/// Function names in `libm::*` (used by the `no_std` lane).
3986fn libm_name(name: &str) -> Option<&'static str> {
3987    Some(match name {
3988        "exp" => "exp",
3989        "ln" | "log" => "log",
3990        "sqrt" => "sqrt",
3991        "sin" => "sin",
3992        "cos" => "cos",
3993        "tan" => "tan",
3994        "sinh" => "sinh",
3995        "cosh" => "cosh",
3996        "tanh" => "tanh",
3997        "abs" => "fabs",
3998        _ => return None,
3999    })
4000}
4001
4002/// The `no_std` (libm) variant block: the same IR, with transcendental functions going through
4003/// `libm::*`.
4004///
4005/// The consumer needs the `libm` dependency (`extern crate libm;` or libm's std compatibility
4006/// layer).
4007/// The output itself is still pure `core` syntax: no `std`, no allocation, no `f64::powi`.
4008pub fn emit_block_libm(root: &Expr) -> String {
4009    emit_block_fx(root, Fx::F64Libm)
4010}
4011
4012pub fn emit_block(root: &Expr) -> String {
4013    emit_block_fx(root, Fx::F64)
4014}
4015
4016/// The `f32` variant block: the same IR, with literals carrying the `f32` suffix.
4017pub fn emit_block_f32(root: &Expr) -> String {
4018    emit_block_fx(root, Fx::F32)
4019}
4020
4021fn emit_block_fx(root: &Expr, fx: Fx) -> String {
4022    // The no_std lane is scalars only: matrix-valued expressions (`vec![…]` needs alloc) are
4023    // rejected as a whole block
4024    if fx.is_libm() && is_matrix_value(root) {
4025        return "{\n        compile_error!(\"the no_std lane does not do matrix-valued formulas (vec! needs alloc): assemble them on the CPU side, or use the std lane\")\n    }"
4026            .to_string();
4027    }
4028    let mut counts: HashMap<String, usize> = HashMap::new();
4029    count_nodes(root, &mut counts);
4030    let mut out: Vec<String> = Vec::new();
4031    let mut names: HashMap<String, String> = HashMap::new();
4032    let mut counter = 0usize;
4033    let (body, _) = emit_node(root, true, &counts, &mut names, &mut out, &mut counter, fx);
4034    let mut s = String::from("{\n");
4035    for line in &out {
4036        let _ = writeln!(s, "        {line}");
4037    }
4038    let _ = writeln!(s, "        {body}");
4039    s.push_str("    }");
4040    s
4041}
4042
4043// ---------------------------------------------------------------- complex code generation
4044//
4045// The complex emission lane is **completely separate** from the real one and does not share
4046// emit_node: the real lane squeezes parentheses to the minimum,
4047// while in the complex lane every operator is one function call (naturally atomic); sharing would
4048// only make both sides uglier.
4049//
4050// Generated values are represented as a **tuple `(f64, f64)` = (re, im)**, rather than defining a
4051// new `struct Cmplx`:
4052// a tuple is a type a block expression can return directly, so the consumer
4053// `let z = formula!(...)` just gets it,
4054// with no named type visible at the call site — this is a hard constraint for the **macro inlining**
4055// lane (a macro cannot
4056// inject type definitions at the call site).
4057
4058/// Whether the expression contains the imaginary unit `j` (deciding whether to take the complex
4059/// emission lane).
4060pub fn uses_complex(e: &Expr) -> bool {
4061    match e {
4062        Expr::Var(n) => n == "j",
4063        Expr::Num(_) | Expr::Indexed { .. } => false,
4064        Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
4065            uses_complex(a) || uses_complex(b)
4066        }
4067        Expr::Neg(a)
4068        | Expr::Transpose(a)
4069        | Expr::Deriv(a, _)
4070        | Expr::Grad(a)
4071        | Expr::Laplacian(a) => uses_complex(a),
4072        Expr::Call(_, args) => args.iter().any(uses_complex),
4073        Expr::Mat(rows) => rows.iter().flatten().any(uses_complex),
4074        Expr::MatPattern(p) => p.elements().into_iter().any(uses_complex),
4075        Expr::Sum {
4076            lower, upper, body, ..
4077        }
4078        | Expr::Integral {
4079            lower, upper, body, ..
4080        } => uses_complex(lower) || uses_complex(upper) || uses_complex(body),
4081    }
4082}
4083
4084/// Source of the complex operator closures. Emitted only when **actually used** — the output must
4085/// pass `clippy -D warnings`, and an unused closure would be judged dead code.
4086fn complex_helper(name: &str) -> &'static str {
4087    // Use a **block-level fn item** rather than a closure: `fn` can carry `#[inline(always)]`,
4088    // a closure cannot.
4089    // Measured: the closure form is 5× slower than "the same thing written out by hand" in batch
4090    // processing — the operators were not inlined,
4091    // so the loop could not be vectorized. After switching to fn items the gap narrows to ~1.3×.
4092    match name {
4093        "__c_add" => "#[inline(always)]\nfn __c_add(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {\n    (a.0 + b.0, a.1 + b.1)\n}",
4094        "__c_sub" => "#[inline(always)]\nfn __c_sub(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {\n    (a.0 - b.0, a.1 - b.1)\n}",
4095        "__c_neg" => "#[inline(always)]\nfn __c_neg(a: (f64, f64)) -> (f64, f64) {\n    (-a.0, -a.1)\n}",
4096        "__c_mul" => "#[inline(always)]\nfn __c_mul(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {\n    (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0)\n}",
4097        // Ordinary magnitudes take the naive form = 1 division; when |b| leaves the safe range,
4098        // scale first and then compute
4099        // (the naive re²+im² overflows for |b| > ~1e154 and underflows to a false division by zero
4100        // for |b| < ~1e-162).
4101        // The same stable algorithm as Smith's at the value layer; extreme bit patterns may differ
4102        // by 1 ulp.
4103        "__c_div" => "#[inline(always)]\nfn __c_div(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {\n    let m = b.0.abs().max(b.1.abs());\n    if m > 1e-150 && m < 1e150 {\n        let d = b.0 * b.0 + b.1 * b.1;\n        ((a.0 * b.0 + a.1 * b.1) / d, (a.1 * b.0 - a.0 * b.1) / d)\n    } else {\n        let (br, bi) = (b.0 / m, b.1 / m);\n        let s = m * (br * br + bi * bi);\n        ((a.0 * br + a.1 * bi) / s, (a.1 * br - a.0 * bi) / s)\n    }\n}",
4104        "__c_abs" => "#[inline(always)]\nfn __c_abs(a: (f64, f64)) -> (f64, f64) {\n    (a.0.hypot(a.1), 0.0)\n}",
4105        "__c_arg" => "#[inline(always)]\nfn __c_arg(a: (f64, f64)) -> (f64, f64) {\n    (a.1.atan2(a.0), 0.0)\n}",
4106        "__c_conj" => "#[inline(always)]\nfn __c_conj(a: (f64, f64)) -> (f64, f64) {\n    (a.0, -a.1)\n}",
4107        "__c_re" => "#[inline(always)]\nfn __c_re(a: (f64, f64)) -> (f64, f64) {\n    (a.0, 0.0)\n}",
4108        "__c_im" => "#[inline(always)]\nfn __c_im(a: (f64, f64)) -> (f64, f64) {\n    (a.1, 0.0)\n}",
4109        "__c_exp" => "#[inline(always)]\nfn __c_exp(a: (f64, f64)) -> (f64, f64) {\n    if a.1 == 0.0 {\n        return (a.0.exp(), 0.0);\n    }\n    let m = a.0.exp();\n    (m * a.1.cos(), m * a.1.sin())\n}",
4110        "__c_ln" => "#[inline(always)]\nfn __c_ln(a: (f64, f64)) -> (f64, f64) {\n    (a.0.hypot(a.1).ln(), a.1.atan2(a.0))\n}",
4111        // Principal-value square root: algebraic closed form. The modulus must use hypot:
4112        // `re²+im²` overflows for |a|>~1e154,
4113        // while the value layer has always used hypot; the generated side must not silently give
4114        // inf here.
4115        "__c_sqrt" => "#[inline(always)]\nfn __c_sqrt(a: (f64, f64)) -> (f64, f64) {\n    if a.1 == 0.0 {\n        return if a.0 >= 0.0 { (a.0.sqrt(), 0.0) } else { (0.0, (-a.0).sqrt()) };\n    }\n    if a.0 == 0.0 {\n        let m = (a.1.abs() * 0.5).sqrt();\n        return (m, m.copysign(a.1));\n    }\n    let r = a.0.hypot(a.1);\n    let re = (((r + a.0) * 0.5).max(0.0)).sqrt();\n    let im = (((r - a.0) * 0.5).max(0.0)).sqrt().copysign(a.1);\n    (re, im)\n}",
4116        // Stable quadratic roots: q/a and c/q, where `first` preserves the original
4117        // (−b−√D)-first return order.
4118        // A zero double root with q=0 falls back to −b/(2a), producing no 0/0.
4119        "__c_quad_root" => "#[inline(always)]\nfn __c_quad_root(a: (f64, f64), b: (f64, f64), c: (f64, f64), first: bool) -> (f64, f64) {\n    let d = __c_sub(__c_mul(b, b), __c_mul((4.0, 0.0), __c_mul(a, c)));\n    let s = __c_sqrt(d);\n    let q_first = __c_mul(__c_conj(b), s).0 >= 0.0;\n    let signed_s = if q_first { s } else { __c_neg(s) };\n    let q = __c_mul((-0.5, 0.0), __c_add(b, signed_s));\n    if q.0 == 0.0 && q.1 == 0.0 {\n        return __c_div(__c_neg(b), __c_mul((2.0, 0.0), a));\n    }\n    let large = __c_div(q, a);\n    let small = __c_div(c, q);\n    if first == q_first { large } else { small }\n}",
4120        // Agrees pointwise with the value layer's `C::pow_real`: an integer power of a negative
4121        // real base must land exactly on the real axis
4122        "__c_powf" => "#[inline(always)]\nfn __c_powf(a: (f64, f64), p: f64) -> (f64, f64) {\n    if !p.is_finite() {\n        return (f64::NAN, 0.0);\n    }\n    if a.1 == 0.0 {\n        if p == p.trunc() && p.abs() <= i32::MAX as f64 {\n            return (a.0.powi(p as i32), 0.0);\n        }\n        if a.0 >= 0.0 {\n            return (a.0.powf(p), 0.0);\n        }\n    }\n    let (r, t) = (a.0.hypot(a.1), a.1.atan2(a.0));\n    let m = r.powf(p);\n    let g = t * p;\n    (m * g.cos(), m * g.sin())\n}",
4123        "__c_pow" => "#[inline(always)]\nfn __c_pow(a: (f64, f64), b: (f64, f64)) -> (f64, f64) {\n    let lr = a.0.hypot(a.1).ln();\n    let li = a.1.atan2(a.0);\n    let (er, ei) = (b.0 * lr - b.1 * li, b.0 * li + b.1 * lr);\n    let m = er.exp();\n    (m * ei.cos(), m * ei.sin())\n}",
4124        "__c_sin" => "#[inline(always)]\nfn __c_sin(a: (f64, f64)) -> (f64, f64) {\n    (a.0.sin() * a.1.cosh(), a.0.cos() * a.1.sinh())\n}",
4125        "__c_cos" => "#[inline(always)]\nfn __c_cos(a: (f64, f64)) -> (f64, f64) {\n    (a.0.cos() * a.1.cosh(), -(a.0.sin() * a.1.sinh()))\n}",
4126        "__c_sinh" => "#[inline(always)]\nfn __c_sinh(a: (f64, f64)) -> (f64, f64) {\n    (a.0.sinh() * a.1.cos(), a.0.cosh() * a.1.sin())\n}",
4127        "__c_cosh" => "#[inline(always)]\nfn __c_cosh(a: (f64, f64)) -> (f64, f64) {\n    (a.0.cosh() * a.1.cos(), a.0.sinh() * a.1.sin())\n}",
4128        "__c_tan" => "#[inline(always)]\nfn __c_tan(a: (f64, f64)) -> (f64, f64) {\n    let s = (a.0.sin() * a.1.cosh(), a.0.cos() * a.1.sinh());\n    let c = (a.0.cos() * a.1.cosh(), -(a.0.sin() * a.1.sinh()));\n    let d = c.0 * c.0 + c.1 * c.1;\n    ((s.0 * c.0 + s.1 * c.1) / d, (s.1 * c.0 - s.0 * c.1) / d)\n}",
4129        "__c_tanh" => "#[inline(always)]\nfn __c_tanh(a: (f64, f64)) -> (f64, f64) {\n    let s = (a.0.sinh() * a.1.cos(), a.0.cosh() * a.1.sin());\n    let c = (a.0.cosh() * a.1.cos(), a.0.sinh() * a.1.sin());\n    let d = c.0 * c.0 + c.1 * c.1;\n    ((s.0 * c.0 + s.1 * c.1) / d, (s.1 * c.0 - s.0 * c.1) / d)\n}",
4130        other => panic!("未登记的复数算子 `{other}`"),
4131    }
4132}
4133
4134struct CEmit {
4135    counts: HashMap<String, usize>,
4136    names: HashMap<String, String>,
4137    helpers: BTreeSet<&'static str>,
4138    temps: Vec<String>,
4139    counter: usize,
4140    /// Bindings that are already `(f64, f64)` (the federation let chain of the macro lane): when
4141    /// referencing them one must **not**
4142    /// wrap them in `(x, 0.0)` again, otherwise it becomes a tuple of tuples.
4143    cx_vars: BTreeSet<String>,
4144}
4145
4146impl CEmit {
4147    fn help(&mut self, name: &'static str) -> &'static str {
4148        self.helpers.insert(name);
4149        name
4150    }
4151
4152    /// CSE: lift a temporary once the same subexpression appears ≥2 times (the same criterion as
4153    /// the real lane).
4154    fn node(&mut self, e: &Expr, is_root: bool) -> String {
4155        let k = key(e);
4156        let shareable = !is_root
4157            && self.counts.get(&k).copied().unwrap_or(0) >= 2
4158            && !matches!(e, Expr::Num(_) | Expr::Var(_));
4159        if shareable {
4160            if let Some(n) = self.names.get(&k) {
4161                return n.clone();
4162            }
4163        }
4164        let text = self.value(e);
4165        if shareable {
4166            let name = format!("__t{}", self.counter);
4167            self.counter += 1;
4168            self.temps.push(format!("let {name} = {text};"));
4169            self.names.insert(k, name.clone());
4170            return name;
4171        }
4172        text
4173    }
4174
4175    fn call1(&mut self, helper: &'static str, e: &Expr) -> String {
4176        let a = self.node(e, false);
4177        let h = self.help(helper);
4178        format!("{h}({a})")
4179    }
4180
4181    fn call2(&mut self, helper: &'static str, a: &Expr, b: &Expr) -> String {
4182        let x = self.node(a, false);
4183        let y = self.node(b, false);
4184        let h = self.help(helper);
4185        format!("{h}({x}, {y})")
4186    }
4187
4188    fn value(&mut self, e: &Expr) -> String {
4189        // Matrix **values** are all folded into literals here and then emitted cell by cell.
4190        // Without this step, `Mat+Mat` / `k*Mat` / `Mat*Mat` fall into `__c_add`/`__c_mul`
4191        // — those two helpers only take `(f64, f64)` scalars, so the output is `error[E0308]`
4192        // (a diagnostic worse than the explicit `compile_error!` it replaced). The real lane always
4193        // goes through
4194        // `flatten_matrix_value`; this is the same strategy in the complex lane.
4195        if !matches!(e, Expr::Mat(_)) {
4196            if let Some(m) = flatten_matrix_value(e) {
4197                if !m.is_empty() {
4198                    let mut parts: Vec<String> = Vec::with_capacity(m.len());
4199                    for r in &m {
4200                        let mut cols: Vec<String> = Vec::with_capacity(r.len());
4201                        for cell in r {
4202                            cols.push(self.node(cell, false));
4203                        }
4204                        parts.push(format!("vec![{}]", cols.join(", ")));
4205                    }
4206                    return format!("vec![{}]", parts.join(", "));
4207                }
4208            }
4209        }
4210        match e {
4211            Expr::Num(v) => format!("({v:?}, 0.0)"),
4212            Expr::Var(n) if n == "j" => "(0.0, 1.0)".to_string(),
4213            Expr::Var(n) if self.cx_vars.contains(n) => rust_ident(n),
4214            Expr::Var(n) => format!("({}, 0.0)", rust_ident(n)),
4215            Expr::Neg(a) => self.call1("__c_neg", a),
4216            Expr::Add(a, b) => self.call2("__c_add", a, b),
4217            Expr::Sub(a, b) => self.call2("__c_sub", a, b),
4218            Expr::Mul(a, b) => self.call2("__c_mul", a, b),
4219            Expr::Div(a, b) => self.call2("__c_div", a, b),
4220            Expr::Pow(a, b) => match b.as_ref() {
4221                Expr::Num(n) if *n == 2.0 => self.call2("__c_mul", a, a),
4222                Expr::Num(n) if *n == 0.5 => self.call1("__c_sqrt", a),
4223                // `z^-1` and `z^-0.5` take "reciprocal / square root first", likewise bypassing
4224                // polar coordinates
4225                Expr::Num(n) if *n == -1.0 => {
4226                    let x = self.node(a, false);
4227                    let h = self.help("__c_div");
4228                    format!("{h}((1.0, 0.0), {x})")
4229                }
4230                Expr::Num(n) if *n == -0.5 => {
4231                    let x = self.node(a, false);
4232                    let s = self.help("__c_sqrt");
4233                    let d = self.help("__c_div");
4234                    format!("{d}((1.0, 0.0), {s}({x}))")
4235                }
4236                Expr::Num(n) => {
4237                    let x = self.node(a, false);
4238                    let h = self.help("__c_powf");
4239                    format!("{h}({x}, {n:?})")
4240                }
4241                _ => self.call2("__c_pow", a, b),
4242            },
4243            Expr::Call(name, args) => {
4244                if matches!(name.as_str(), "__quad_root_1" | "__quad_root_2") {
4245                    if args.len() != 3 {
4246                        return "compile_error!(\"the internal quadratic-root operator needs three coefficients\")".to_string();
4247                    }
4248                    let a = self.node(&args[0], false);
4249                    let b = self.node(&args[1], false);
4250                    let c = self.node(&args[2], false);
4251                    for helper in [
4252                        "__c_add", "__c_sub", "__c_mul", "__c_neg", "__c_div", "__c_conj",
4253                        "__c_sqrt",
4254                    ] {
4255                        self.help(helper);
4256                    }
4257                    let helper = self.help("__c_quad_root");
4258                    let first = if name == "__quad_root_1" {
4259                        "true"
4260                    } else {
4261                        "false"
4262                    };
4263                    return format!("{helper}({a}, {b}, {c}, {first})");
4264                }
4265                let Some(arg0) = args.first() else {
4266                    return "compile_error!(\"the function call is missing its argument\")".to_string();
4267                };
4268                // Expandable operators: the same strategy as the real lane — expand into an
4269                // ordinary expression on the IR first,
4270                // then emit. Without this step, when `emit_block_complex` is called directly (the
4271                // macro lane)
4272                // `det/solve/roots` fall through to the catch-all below and become compile_error,
4273                // while the generator lane happened to be fine because it ran expand_deep first —
4274                // the two lanes were inconsistent.
4275                if matches!(
4276                    name.as_str(),
4277                    "det"
4278                        | "trace"
4279                        | "adjoint"
4280                        | "inv"
4281                        | "solve"
4282                        | "roots"
4283                        | "poly_coeffs"
4284                        | "dot"
4285                        | "norm"
4286                ) {
4287                    return match expand_call(e) {
4288                        Some(x) => self.node(&x, false),
4289                        None => "compile_error!(\"det/trace/adjoint/inv/solve/roots/dot/norm need a concrete matrix literal\")".to_string(),
4290                    };
4291                }
4292                let helper = match name.as_str() {
4293                    "exp" => "__c_exp",
4294                    "ln" | "log" => "__c_ln",
4295                    "sqrt" => "__c_sqrt",
4296                    "sin" => "__c_sin",
4297                    "cos" => "__c_cos",
4298                    "tan" => "__c_tan",
4299                    "sinh" => "__c_sinh",
4300                    "cosh" => "__c_cosh",
4301                    "tanh" => "__c_tanh",
4302                    "abs" => "__c_abs",
4303                    "arg" => "__c_arg",
4304                    "conj" => "__c_conj",
4305                    "re" => "__c_re",
4306                    "im" => "__c_im",
4307                    // Unregistered function name: blow up at compile time, never leave a runtime
4308                    // surprise
4309                    _ => {
4310                        return "compile_error!(\"the complex lane does not support this function (exp/ln/sqrt/sin/cos/tan/sinh/cosh/tanh/abs/arg/conj/re/im)\")".to_string()
4311                    }
4312                };
4313                self.call1(helper, arg0)
4314            }
4315            // Σ with constant bounds: expand at compile time into a __c_add chain (the same
4316            // strategy as the real lane)
4317            Expr::Sum {
4318                var,
4319                lower,
4320                upper,
4321                body,
4322            } => {
4323                if let (Expr::Num(lo), Expr::Num(hi)) = (lower.as_ref(), upper.as_ref()) {
4324                    if math::fract(*lo) == 0.0 && math::fract(*hi) == 0.0 && (hi - lo) < 64.0 {
4325                        let mut parts = Vec::new();
4326                        let mut k = *lo;
4327                        while k <= *hi {
4328                            let b = subst(body, var, &num(k));
4329                            parts.push(self.node(&b, false));
4330                            k += 1.0;
4331                        }
4332                        // Empty interval (lo > hi) = the zero element, consistent with the value
4333                        // layer/real lane
4334                        if parts.is_empty() {
4335                            return "(0.0, 0.0)".to_string();
4336                        }
4337                        let mut acc = parts.remove(0);
4338                        for p in parts {
4339                            let h = self.help("__c_add");
4340                            acc = format!("{h}({acc}, {p})");
4341                        }
4342                        return acc;
4343                    }
4344                }
4345                "compile_error!(\"a non-constant sum bound must go through the .formula file lane\")".to_string()
4346            }
4347            Expr::Integral { .. } => {
4348                "compile_error!(\"definite integrals must go through the .formula file lane (numeric integration is a runtime loop)\")"
4349                    .to_string()
4350            }
4351            // Complex matrix: elements go through the same complex emitter and are wrapped as
4352            // `vec![vec![(re, im), …], …]`.
4353            // The generated function's return type is `Vec<Vec<(f64, f64)>>` (see buildhelper).
4354            // The solution of a "complex linear system" such as AC circuits / EIS is a complex
4355            // column vector — the value layer
4356            // always supported it, while the emission layer used to reject it wholesale; the two
4357            // sides were inconsistent.
4358            Expr::Mat(rows) => {
4359                let mut parts: Vec<String> = Vec::with_capacity(rows.len());
4360                for r in rows {
4361                    let mut cols: Vec<String> = Vec::with_capacity(r.len());
4362                    for cell in r {
4363                        cols.push(self.node(cell, false));
4364                    }
4365                    parts.push(format!("vec![{}]", cols.join(", ")));
4366                }
4367                format!("vec![{}]", parts.join(", "))
4368            }
4369            // Transpose: a plain transpose **does not conjugate** (conjugation is a separate
4370            // `conj`, see the operator table in the README).
4371            // Only matrices that can be flattened into a literal can be transposed; other shapes are
4372            // rejected explicitly.
4373            Expr::Transpose(a) => match flatten_matrix_value(a) {
4374                Some(m) if !m.is_empty() && m.iter().all(|r| r.len() == m[0].len()) => {
4375                    let (nr, nc) = (m.len(), m[0].len());
4376                    let mut parts: Vec<String> = Vec::with_capacity(nc);
4377                    for j in 0..nc {
4378                        let mut cols: Vec<String> = Vec::with_capacity(nr);
4379                        for row in &m {
4380                            cols.push(self.node(&row[j], false));
4381                        }
4382                        parts.push(format!("vec![{}]", cols.join(", ")));
4383                    }
4384                    format!("vec![{}]", parts.join(", "))
4385                }
4386                _ => "compile_error!(\"a transpose in the complex lane needs a matrix literal whose shape is known at compile time\")".to_string(),
4387            },
4388            Expr::MatPattern(_) => {
4389                "compile_error!(\"the complex lane does not take pattern matrices (call `recognize_pattern` first to get a concrete shape)\")"
4390                    .to_string()
4391            }
4392            Expr::Deriv(..) | Expr::Grad(_) | Expr::Laplacian(_) | Expr::Indexed { .. } => {
4393                "compile_error!(\"symbolic operators and indexed symbols must go through the .formula file lane\")".to_string()
4394            }
4395        }
4396    }
4397}
4398
4399/// Emission of a complex block (equivalent to `emit_block`, but values are `(f64, f64)`).
4400///
4401/// The generated block contains only the closures **actually used**, so it passes
4402/// `clippy -D warnings` directly.
4403pub fn emit_block_complex(root: &Expr) -> String {
4404    emit_block_complex_with(root, &[])
4405}
4406
4407/// Complex block emission (with the information "which names are already complex").
4408///
4409/// The macro lane expands federated formulas into a `let` chain, where later entries reference the
4410/// earlier bindings directly —
4411/// at that point `Var(y)` is already `(f64, f64)` and must not be wrapped in another `(y, 0.0)`.
4412pub fn emit_block_complex_with(root: &Expr, complex_vars: &[String]) -> String {
4413    let mut counts: HashMap<String, usize> = HashMap::new();
4414    count_nodes(root, &mut counts);
4415    let mut em = CEmit {
4416        counts,
4417        names: HashMap::new(),
4418        helpers: BTreeSet::new(),
4419        temps: Vec::new(),
4420        counter: 0,
4421        cx_vars: complex_vars.iter().cloned().collect(),
4422    };
4423    let body = em.node(root, true);
4424    let mut s = String::from("{\n");
4425    for h in &em.helpers {
4426        let line = complex_helper(h);
4427        for l in line.lines() {
4428            let _ = writeln!(s, "        {l}");
4429        }
4430    }
4431    for t in &em.temps {
4432        let _ = writeln!(s, "        {t}");
4433    }
4434    let _ = writeln!(s, "        {body}");
4435    s.push_str("    }");
4436    s
4437}
4438
4439fn count_nodes(e: &Expr, counts: &mut HashMap<String, usize>) {
4440    *counts.entry(key(e)).or_insert(0) += 1;
4441    match e {
4442        Expr::Num(_) | Expr::Var(_) => {}
4443        Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
4444            count_nodes(a, counts);
4445            count_nodes(b, counts);
4446        }
4447        Expr::Neg(a) => count_nodes(a, counts),
4448        Expr::Call(_, args) => {
4449            for a in args {
4450                count_nodes(a, counts);
4451            }
4452        }
4453        Expr::Mat(rows) => {
4454            for r in rows {
4455                for c in r {
4456                    count_nodes(c, counts);
4457                }
4458            }
4459        }
4460        Expr::MatPattern(p) => {
4461            for e in p.elements() {
4462                count_nodes(e, counts);
4463            }
4464        }
4465        Expr::Transpose(a) => count_nodes(a, counts),
4466        Expr::Deriv(u, _) | Expr::Grad(u) | Expr::Laplacian(u) => count_nodes(u, counts),
4467        Expr::Sum {
4468            lower, upper, body, ..
4469        }
4470        | Expr::Integral {
4471            lower, upper, body, ..
4472        } => {
4473            count_nodes(lower, counts);
4474            count_nodes(upper, counts);
4475            count_nodes(body, counts);
4476        }
4477        Expr::Indexed { name, indices } => {
4478            *counts.entry(format!("${name}")).or_insert(0) += 1;
4479            let _ = indices;
4480        }
4481    }
4482}
4483
4484fn emit_node(
4485    e: &Expr,
4486    is_root: bool,
4487    counts: &HashMap<String, usize>,
4488    names: &mut HashMap<String, String>,
4489    out: &mut Vec<String>,
4490    counter: &mut usize,
4491    fx: Fx,
4492) -> (String, u8) {
4493    let k = key(e);
4494    let shareable = !is_root
4495        && counts.get(&k).copied().unwrap_or(0) >= 2
4496        && !matches!(e, Expr::Num(_) | Expr::Var(_));
4497    if shareable {
4498        if let Some(n) = names.get(&k) {
4499            return (n.clone(), 9);
4500        }
4501    }
4502    let (text, p) = emit_uncached(e, counts, names, out, counter, fx);
4503    if shareable {
4504        let name = format!("__t{counter}");
4505        *counter += 1;
4506        out.push(format!("let {name} = {text};"));
4507        names.insert(k, name.clone());
4508        return (name, 9);
4509    }
4510    (text, p)
4511}
4512
4513/// Whether it **might** be matrix-valued (unknown shape counts). Used to reject the misjudgment of
4514/// "scalar broadcasting":
4515/// only a side that is definitely not a matrix may be multiplied in as a scalar.
4516fn matrix_ish(e: &Expr) -> bool {
4517    match e {
4518        Expr::Mat(_) | Expr::MatPattern(_) | Expr::Transpose(_) | Expr::Indexed { .. } => true,
4519        Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) | Expr::Pow(a, b) => {
4520            matrix_ish(a) || matrix_ish(b)
4521        }
4522        Expr::Neg(a) => matrix_ish(a),
4523        Expr::Call(_, args) => args.iter().any(matrix_ish),
4524        _ => false,
4525    }
4526}
4527
4528/// Matrix product (element-level IR): `C_ij = Σ_k A_ik·B_kj`. Returns None on a shape mismatch.
4529fn mat_mul_exprs(ma: &[Vec<Expr>], mb: &[Vec<Expr>]) -> Option<Vec<Vec<Expr>>> {
4530    let inner = ma.first()?.len();
4531    if mb.len() != inner {
4532        return None;
4533    }
4534    let cols = mb.first()?.len();
4535    let mut out: Vec<Vec<Expr>> = Vec::with_capacity(ma.len());
4536    for row in ma {
4537        let mut r2: Vec<Expr> = Vec::with_capacity(cols);
4538        // The column index `j` also indexes `mb[k][j]` (k varies in the inner loop) — not a
4539        // single-set iteration
4540        #[allow(clippy::needless_range_loop)]
4541        for j in 0..cols {
4542            let mut acc: Option<Expr> = None;
4543            for (k, x) in row.iter().enumerate() {
4544                let prod = mul(x.clone(), mb[k][j].clone());
4545                acc = Some(match acc {
4546                    None => prod,
4547                    Some(p) => add(p, prod),
4548                });
4549            }
4550            r2.push(acc?);
4551        }
4552        out.push(r2);
4553    }
4554    Some(out)
4555}
4556
4557/// Fold a **statically expandable** matrix expression into a concrete matrix IR
4558/// (element level).
4559///
4560/// Only shapes whose leaves are all concrete literals are accepted: the size of a symbolic matrix
4561/// is unknown at compile time,
4562/// and that is the job of pattern matrices + the generator lane. If it cannot be folded, returns
4563/// None and leaves it to the generic emitter
4564/// to produce a **loud compile error** (better a compile failure than a silent miscalculation).
4565pub fn flatten_matrix_value(e: &Expr) -> Option<Vec<Vec<Expr>>> {
4566    fn same_shape(a: &[Vec<Expr>], b: &[Vec<Expr>]) -> bool {
4567        a.len() == b.len()
4568            && a.first().map(|r| r.len()) == b.first().map(|r| r.len())
4569            && a.iter().zip(b.iter()).all(|(x, y)| x.len() == y.len())
4570    }
4571    fn zip(
4572        a: Vec<Vec<Expr>>,
4573        b: Vec<Vec<Expr>>,
4574        f: fn(Expr, Expr) -> Expr,
4575    ) -> Option<Vec<Vec<Expr>>> {
4576        if !same_shape(&a, &b) {
4577            return None;
4578        }
4579        Some(
4580            a.into_iter()
4581                .zip(b)
4582                .map(|(ra, rb)| ra.into_iter().zip(rb).map(|(x, y)| f(x, y)).collect())
4583                .collect(),
4584        )
4585    }
4586    let scale = |m: Vec<Vec<Expr>>, k: Expr| -> Vec<Vec<Expr>> {
4587        m.into_iter()
4588            .map(|r| r.into_iter().map(|x| mul(k.clone(), x)).collect())
4589            .collect()
4590    };
4591    match e {
4592        Expr::Mat(rows) => Some(rows.clone()),
4593        Expr::Transpose(a) => {
4594            let m = flatten_matrix_value(a)?;
4595            let cols = m.first()?.len();
4596            if m.iter().any(|r| r.len() != cols) {
4597                return None;
4598            }
4599            Some(
4600                (0..cols)
4601                    .map(|j| m.iter().map(|r| r[j].clone()).collect())
4602                    .collect(),
4603            )
4604        }
4605        Expr::Neg(a) => {
4606            let m = flatten_matrix_value(a)?;
4607            Some(
4608                m.into_iter()
4609                    .map(|r| r.into_iter().map(neg).collect())
4610                    .collect(),
4611            )
4612        }
4613        // Matrix / scalar: element-wise division (matrix division is itself rejected explicitly at
4614        // the value layer, so the divisor
4615        // can only be a scalar). **Missing this branch once let the matrix guard miss**
4616        // `([1,2;3,4]/2)*x` —
4617        // it could not tell it was a matrix, so it emitted code like `f64 / Vec<Vec<f64>>` that does
4618        // not compile.
4619        Expr::Div(a, b) => {
4620            if matrix_ish(b) {
4621                return None;
4622            }
4623            let m = flatten_matrix_value(a)?;
4624            Some(
4625                m.into_iter()
4626                    .map(|r| r.into_iter().map(|x| div(x, (**b).clone())).collect())
4627                    .collect(),
4628            )
4629        }
4630        // Matrix operators: only the results of adjoint / inv are still matrices (det/trace/norm/dot
4631        // fold to scalars)
4632        Expr::Call(name, _) if name == "adjoint" || name == "inv" => {
4633            flatten_matrix_value(&expand_matrix_call(e)?)
4634        }
4635        // The result of solving a system is a column vector (single-variable solve is a scalar and
4636        // falls back to None after expansion)
4637        Expr::Call(name, _) if name == "solve" || name == "roots" || name == "poly_coeffs" => {
4638            flatten_matrix_value(&expand_call(e)?)
4639        }
4640        Expr::Add(a, b) => zip(flatten_matrix_value(a)?, flatten_matrix_value(b)?, add),
4641        Expr::Sub(a, b) => zip(flatten_matrix_value(a)?, flatten_matrix_value(b)?, sub),
4642        Expr::Mul(a, b) => match (flatten_matrix_value(a), flatten_matrix_value(b)) {
4643            (Some(ma), Some(mb)) => mat_mul_exprs(&ma, &mb),
4644            // Only a side that is definitely not a matrix may broadcast as a scalar
4645            (Some(ma), None) if !matrix_ish(b) => Some(scale(ma, (**b).clone())),
4646            (None, Some(mb)) if !matrix_ish(a) => Some(scale(mb, (**a).clone())),
4647            _ => None,
4648        },
4649        // Non-negative integer matrix powers: power 0 gives the identity of the same order,
4650        // 1..=8 repeated matrix multiplications;
4651        // negative powers (need the inverse) and fractional powers (need eigendecomposition) are
4652        // explicitly unsupported.
4653        Expr::Pow(a, b) => match b.as_ref() {
4654            Expr::Num(k) if *k == 0.0 => {
4655                let m = flatten_matrix_value(a)?;
4656                if !m.iter().all(|r| r.len() == m.len()) {
4657                    return None;
4658                }
4659                // The zero power of a matrix is the identity of the same order, not the scalar 1.
4660                // The type must still be a matrix too.
4661                Some(
4662                    (0..m.len())
4663                        .map(|i| {
4664                            (0..m.len())
4665                                .map(|j| num(if i == j { 1.0 } else { 0.0 }))
4666                                .collect()
4667                        })
4668                        .collect(),
4669                )
4670            }
4671            Expr::Num(k) if *k >= 1.0 && math::fract(*k) == 0.0 && *k <= 8.0 => {
4672                let m = flatten_matrix_value(a)?;
4673                if !m.iter().all(|r| r.len() == m.len()) {
4674                    return None;
4675                }
4676                let mut acc = m.clone();
4677                for _ in 1..(*k as usize) {
4678                    acc = mat_mul_exprs(&acc, &m)?;
4679                }
4680                Some(acc)
4681            }
4682            _ => None,
4683        },
4684        _ => None,
4685    }
4686}
4687
4688/// Whether the expression contains a given free variable.
4689fn has_var(e: &Expr, var: &str) -> bool {
4690    vars_of(e).iter().any(|v| v == var)
4691}
4692
4693/// Decompose `e` with respect to `var` into `a·var + b` (neither `a` nor `b` contains `var`).
4694///
4695/// Only **linear** expressions are accepted: `var*var`, `var^2`, `sin(var)`, `1/var` all error
4696/// with an explanation.
4697/// Silently returning a wrong coefficient is worse than guessing wrong — an error in the steady-state
4698/// concentration gets taken as the true value downstream.
4699fn lin_coeffs(e: &Expr, var: &str) -> Result<(Expr, Expr), Error> {
4700    use Expr as E;
4701    let zero = || num(0.0);
4702    Ok(match e {
4703        E::Num(_) | E::Indexed { .. } => (zero(), e.clone()),
4704        E::Var(n) => {
4705            if n == var {
4706                (num(1.0), zero())
4707            } else {
4708                (zero(), e.clone())
4709            }
4710        }
4711        E::Add(x, y) => {
4712            let (a1, b1) = lin_coeffs(x, var)?;
4713            let (a2, b2) = lin_coeffs(y, var)?;
4714            (add(a1, a2), add(b1, b2))
4715        }
4716        E::Sub(x, y) => {
4717            let (a1, b1) = lin_coeffs(x, var)?;
4718            let (a2, b2) = lin_coeffs(y, var)?;
4719            (sub(a1, a2), sub(b1, b2))
4720        }
4721        E::Neg(x) => {
4722            let (a, b) = lin_coeffs(x, var)?;
4723            (neg(a), neg(b))
4724        }
4725        E::Mul(x, y) => match (has_var(x, var), has_var(y, var)) {
4726            (false, false) => (zero(), e.clone()),
4727            (true, false) => {
4728                let (a, b) = lin_coeffs(x, var)?;
4729                (mul(a, (**y).clone()), mul(b, (**y).clone()))
4730            }
4731            (false, true) => {
4732                let (a, b) = lin_coeffs(y, var)?;
4733                (mul((**x).clone(), a), mul((**x).clone(), b))
4734            }
4735            (true, true) => {
4736                return Err(Error::NonlinearEquation {
4737                    name: var.to_string(),
4738                    why: "the unknown appears twice in one product".to_string(),
4739                })
4740            }
4741        },
4742        E::Div(x, y) => {
4743            if has_var(y, var) {
4744                return Err(Error::NonlinearEquation {
4745                    name: var.to_string(),
4746                    why: "the unknown appears in a denominator".to_string(),
4747                });
4748            }
4749            let (a, b) = lin_coeffs(x, var)?;
4750            (div(a, (**y).clone()), div(b, (**y).clone()))
4751        }
4752        E::Pow(x, y) => {
4753            // The exponent side may also hide the unknown (`2^x`): checking only the base was a
4754            // historical blind spot —
4755            // back then the whole term was taken as a constant term, the "solution" still carried x,
4756            // and once generated it became
4757            // a legal function "taking the solved-for quantity as an input" that silently returned
4758            // wrong values.
4759            if has_var(y, var) {
4760                return Err(Error::NonlinearEquation {
4761                    name: var.to_string(),
4762                    why: "it appears in an exponent".into(),
4763                });
4764            }
4765            if !has_var(x, var) {
4766                (zero(), e.clone())
4767            } else if matches!(y.as_ref(), E::Num(n) if *n == 1.0) {
4768                lin_coeffs(x, var)?
4769            } else {
4770                return Err(Error::NonlinearEquation {
4771                    name: var.to_string(),
4772                    why: "the unknown appears in a power or exponent".to_string(),
4773                });
4774            }
4775        }
4776        E::Call(name, args) => {
4777            // Check **all** arguments: x hidden in the second argument of `clamp(y, x, 10)` also
4778            // counts as non-linear
4779            // (once only the first was checked, so x leaked into the "solution" and the generator
4780            // listed it back in the parameter list)
4781            if args.iter().any(|a| has_var(a, var)) {
4782                return Err(Error::NonlinearEquation {
4783                    name: var.to_string(),
4784                    why: format!("the unknown appears inside `{name}`"),
4785                });
4786            }
4787            (zero(), e.clone())
4788        }
4789        _ => {
4790            if has_var(e, var) {
4791                return Err(Error::NonlinearEquation {
4792                    name: var.to_string(),
4793                    why: "this construct is not supported by the linear solver".into(),
4794                });
4795            }
4796            (zero(), e.clone())
4797        }
4798    })
4799}
4800
4801/// Linear solving: `solve(expr, x)` → the `x` satisfying `expr = 0` (`expr` must be linear in x).
4802///
4803/// This is the entry point for chemistry/circuit "steady state" style problems:
4804/// `k_on·E·S − (k_off + k_cat)·ES = 0`
4805/// solved for `ES` is the Michaelis complex concentration. The solved expression is still IR, so
4806/// it can continue through dimension checking,
4807/// evaluation, code generation and differentiation — no second mechanism is needed.
4808pub fn solve_linear(e: &Expr, var: &str) -> Result<Expr, Error> {
4809    let (a, b) = lin_coeffs(e, var)?;
4810    // Simplify the coefficients first: the decomposition leaves shapes like
4811    // `Sub(Mul(M, 1.0), 0.0)`,
4812    // which the matrix predicate does not recognize (flatten only recognizes pure matrix
4813    // structures); only after simplification is it M itself.
4814    let (a, b) = (simplify(&a), simplify(&b));
4815    // The coefficients are matrix-valued (`solve(M*x - b, x)`): the solution has the shape
4816    // Div(matrix, matrix),
4817    // and the scalar emission lane would treat it as a vec! division and generate code that does not
4818    // compile — reject explicitly and point to
4819    // the correct form (rejection is a feature).
4820    // The test is "contains a matrix literal" rather than just `is_matrix_value`: for a form like
4821    // `1/Mat` with the **matrix in the
4822    // divisor position**, `flatten_matrix_value` deliberately returns None (matrix division is
4823    // unsupported),
4824    // so `is_matrix_value` is false, and the guard once missed it and returned a matrix-containing
4825    // "solution".
4826    fn has_matrix_literal(e: &Expr) -> bool {
4827        match e {
4828            Expr::Mat(_) | Expr::MatPattern(_) => true,
4829            Expr::Add(x, y)
4830            | Expr::Sub(x, y)
4831            | Expr::Mul(x, y)
4832            | Expr::Div(x, y)
4833            | Expr::Pow(x, y) => has_matrix_literal(x) || has_matrix_literal(y),
4834            Expr::Neg(x) | Expr::Transpose(x) => has_matrix_literal(x),
4835            _ => false,
4836        }
4837    }
4838    if is_matrix_value(&a)
4839        || is_matrix_value(&b)
4840        || has_matrix_literal(&a)
4841        || has_matrix_literal(&b)
4842    {
4843        return Err(Error::MatrixCoefficient(
4844            "`solve` solves scalar equations only; write matrix equations as `inv(A) * b`, or pass a list of scalar equations".into(),
4845        ));
4846    }
4847    // a identically zero ⇒ var is not in the equation at all (identity or contradiction). Simplify
4848    // first:
4849    // the var coefficient inside `a + b` is a foldable shape like `0 + 0`.
4850    if let Expr::Num(v) = simplify(&a) {
4851        if v == 0.0 {
4852            return Err(Error::NonlinearEquation {
4853                name: var.to_string(),
4854                why: "the equation has no linear term in it".into(),
4855            });
4856        }
4857    }
4858    Ok(simplify(&neg(div(b, a))))
4859}
4860
4861/// Split the expression into "signed terms": `(sign, term)`, where a term has no top-level
4862/// addition/subtraction.
4863fn signed_terms(e: &Expr, sign: f64, out: &mut Vec<(f64, Expr)>) {
4864    match e {
4865        Expr::Add(a, b) => {
4866            signed_terms(a, sign, out);
4867            signed_terms(b, sign, out);
4868        }
4869        Expr::Sub(a, b) => {
4870            signed_terms(a, sign, out);
4871            signed_terms(b, -sign, out);
4872        }
4873        Expr::Neg(a) => signed_terms(a, -sign, out),
4874        _ => out.push((sign, e.clone())),
4875    }
4876}
4877
4878/// Split a term into "numeric coefficient × multiset of factors", with the factors sorted by
4879/// their canonical key.
4880///
4881/// Only multiplication/division/negation/integer powers get a **structural** expansion;
4882/// addition/subtraction does not enter (they delimit terms).
4883/// Forms that cannot be split (symbolic divisors, non-integer powers) **do not return None**;
4884/// instead the whole term becomes one atomic
4885/// factor key — identical expressions still share a key (so `x/k − x/k = 0` is provable), while
4886/// different writings get different keys
4887/// (`sqrt(x)` and `x^0.5` cannot be proven equal; that is the conservative direction, which never
4888/// wrongly judges something as zero).
4889fn term_factors(e: &Expr) -> Option<(f64, Vec<String>)> {
4890    // Use the pure functional style "return (coefficient, factor key list)" rather than push/pop
4891    // into a shared buffer:
4892    // the latter produced a real bug with powers — `e^n` pushed only n−1 factors, so `e^n` and
4893    // `e^(n−1)` got the same
4894    // multiset and `a^2 − a` was judged identically zero (the solver then silently returned a wrong
4895    // solution).
4896    fn go(e: &Expr) -> Option<(f64, Vec<String>)> {
4897        match e {
4898            Expr::Num(v) => Some((*v, Vec::new())),
4899            Expr::Neg(a) => go(a).map(|(c, k)| (-c, k)),
4900            Expr::Mul(a, b) => {
4901                let (ca, mut ka) = go(a)?;
4902                let (cb, kb) = go(b)?;
4903                ka.extend(kb);
4904                Some((ca * cb, ka))
4905            }
4906            // Division accepts only a **numeric divisor**: a symbolic divisor cannot be split into
4907            // a factor multiset, so conservatively take the whole term as one atom
4908            Expr::Div(a, b) => match b.as_ref() {
4909                Expr::Num(d) if *d != 0.0 => go(a).map(|(c, k)| (c / d, k)),
4910                _ => Some((1.0, vec![key(e)])),
4911            },
4912            Expr::Pow(a, b) => match b.as_ref() {
4913                // Integer power: the base factors are **repeated n times as a whole**, and the
4914                // numeric coefficient is raised to the n-th power
4915                Expr::Num(n) if *n >= 0.0 && math::fract(*n) == 0.0 && *n <= 8.0 => {
4916                    let (cb, kb) = go(a)?;
4917                    let mut keys = Vec::with_capacity(kb.len() * (*n as usize));
4918                    for _ in 0..(*n as usize) {
4919                        keys.extend(kb.iter().cloned());
4920                    }
4921                    Some((math::powi(cb, *n as i32), keys))
4922                }
4923                // Non-integer powers (`x^0.5`, `x^(-1)`) are not split: the whole term is one atom.
4924                // Identical expressions still share a key (so `x^0.5 − x^0.5 = 0` is provable),
4925                // but it is a different key from `sqrt(x)` — that is merely **unprovable**, not a
4926                // wrong judgment.
4927                _ => Some((1.0, vec![key(e)])),
4928            },
4929            _ => Some((1.0, vec![key(e)])),
4930        }
4931    }
4932    let (coef, mut keys) = go(e)?;
4933    keys.sort();
4934    Some((coef, keys))
4935}
4936
4937/// **Structural zero test**: expressions that are algebraically identically zero and provable as
4938/// such by "combining like terms".
4939///
4940/// Why it is needed: `simplify` only folds constants and 0/1 identities and does **not combine like
4941/// terms**.
4942/// So `k − k`, `k·a − a·k`, `2x − x − x` cannot be folded, and the solver treated "cannot be
4943/// folded"
4944/// as "non-zero", taking rows with zero coefficients as pivots — the consequence is `0/0`: the
4945/// evaluation layer errors,
4946/// the emission layer silently gives NaN, or an underdetermined system is taken as a unique
4947/// solution.
4948///
4949/// Implementation: split into signed terms → split each term into "numeric coefficient × sorted
4950/// factor multiset" →
4951/// add the coefficients sharing a key. The criterion is **sufficient**, not necessary: if zero
4952/// cannot be proven, return false (conservative).
4953pub fn is_structurally_zero(e: &Expr) -> bool {
4954    let s = simplify(e);
4955    if matches!(s, Expr::Num(v) if v == 0.0) {
4956        return true;
4957    }
4958    let mut terms: Vec<(f64, Expr)> = Vec::new();
4959    signed_terms(&s, 1.0, &mut terms);
4960    let mut acc: BTreeMap<String, f64> = BTreeMap::new();
4961    for (sign, t) in terms {
4962        // `term_factors` always gives Some (unsplittable means an atom), so there is no "give up"
4963        // branch here
4964        let Some((coef, keys)) = term_factors(&t) else {
4965            return false;
4966        };
4967        let k = keys.join("\u{1}");
4968        *acc.entry(k).or_insert(0.0) += sign * coef;
4969    }
4970    acc.values().all(|v| *v == 0.0)
4971}
4972
4973/// Multivariate linear coefficient decomposition: `e = Σ_j a_j·v_j + b` (no `a_j` and no `b`
4974/// contains any `v_j`).
4975///
4976/// Semantics are the same as `lin_coeffs`, except the unknowns go from one to a group — the
4977/// coefficient source for solving systems of equations.
4978/// Non-linearity errors must state clearly **which operation** the problem occurred in, the same
4979/// discipline as the single-variable version.
4980// The coefficient vector is located by unknown index (the k-th item is the k-th unknown); this is
4981// a semantic index, not an iteration
4982#[allow(clippy::needless_range_loop)]
4983fn lin_coeffs_multi(e: &Expr, vars: &[String]) -> Result<(Vec<Expr>, Expr), Error> {
4984    use Expr as E;
4985    let n = vars.len();
4986    let zeros = || vec![num(0.0); n];
4987    let hit = |x: &Expr| vars.iter().any(|v| has_var(x, v));
4988    Ok(match e {
4989        E::Num(_) | E::Indexed { .. } => (zeros(), e.clone()),
4990        E::Var(name) => match vars.iter().position(|v| v == name) {
4991            Some(k) => {
4992                let mut a = zeros();
4993                a[k] = num(1.0);
4994                (a, num(0.0))
4995            }
4996            None => (zeros(), e.clone()),
4997        },
4998        E::Add(x, y) => {
4999            let (mut a, b) = lin_coeffs_multi(x, vars)?;
5000            let (a2, b2) = lin_coeffs_multi(y, vars)?;
5001            for k in 0..n {
5002                a[k] = add(a[k].clone(), a2[k].clone());
5003            }
5004            (a, add(b, b2))
5005        }
5006        E::Sub(x, y) => {
5007            let (mut a, b) = lin_coeffs_multi(x, vars)?;
5008            let (a2, b2) = lin_coeffs_multi(y, vars)?;
5009            for k in 0..n {
5010                a[k] = sub(a[k].clone(), a2[k].clone());
5011            }
5012            (a, sub(b, b2))
5013        }
5014        E::Neg(x) => {
5015            let (mut a, b) = lin_coeffs_multi(x, vars)?;
5016            for k in 0..n {
5017                a[k] = neg(a[k].clone());
5018            }
5019            (a, neg(b))
5020        }
5021        E::Mul(x, y) => match (hit(x), hit(y)) {
5022            (false, false) => (zeros(), e.clone()),
5023            (true, true) => {
5024                // Name the unknowns actually involved, not the operation: the template reads
5025                // "is not linear in `{0}`", so `x` or `x, y` belongs in the slot. The old
5026                // "the product" made the sentence say "not linear in the product".
5027                let involved: Vec<&str> = vars
5028                    .iter()
5029                    .filter(|v| has_var(e, v))
5030                    .map(String::as_str)
5031                    .collect();
5032                return Err(Error::NonlinearEquation {
5033                    name: involved.join(", "),
5034                    why: "both factors contain an unknown".into(),
5035                });
5036            }
5037            // The pure-coefficient side multiplies into every unknown's coefficient and the
5038            // constant term
5039            (true, false) => {
5040                let (mut a, b) = lin_coeffs_multi(x, vars)?;
5041                for k in 0..n {
5042                    a[k] = mul(a[k].clone(), (**y).clone());
5043                }
5044                (a, mul(b, (**y).clone()))
5045            }
5046            (false, true) => {
5047                let (mut a, b) = lin_coeffs_multi(y, vars)?;
5048                for k in 0..n {
5049                    a[k] = mul((**x).clone(), a[k].clone());
5050                }
5051                (a, mul((**x).clone(), b))
5052            }
5053        },
5054        E::Div(x, y) => {
5055            if hit(y) {
5056                return Err(Error::NonlinearEquation {
5057                    name: "the equation".into(),
5058                    why: "the unknown appears in a denominator".into(),
5059                });
5060            }
5061            let (mut a, b) = lin_coeffs_multi(x, vars)?;
5062            for k in 0..n {
5063                a[k] = div(a[k].clone(), (**y).clone());
5064            }
5065            (a, div(b, (**y).clone()))
5066        }
5067        E::Pow(x, y) => {
5068            // An unknown hidden in the exponent side (`2^x`) must be **rejected explicitly**: it
5069            // used to be taken as a constant term, with a comment saying
5070            // "it will be conservatively rejected at the rank check" — as long as the same unknown
5071            // also appeared as a
5072            // linear term in that equation it slipped through, and the solved expression did not
5073            // satisfy the original equation at all.
5074            if hit(y) {
5075                return Err(Error::NonlinearEquation {
5076                    name: "the equation".into(),
5077                    why: "the unknown appears in an exponent".into(),
5078                });
5079            }
5080            if !hit(x) {
5081                (zeros(), e.clone())
5082            } else if matches!(y.as_ref(), E::Num(m) if *m == 1.0) {
5083                lin_coeffs_multi(x, vars)?
5084            } else {
5085                return Err(Error::NonlinearEquation {
5086                    name: "the equation".into(),
5087                    why: "the unknown appears in a power".into(),
5088                });
5089            }
5090        }
5091        E::Call(name, args) => {
5092            // Check **all** arguments: x hidden in the second argument of `clamp(y, x, 10)` also
5093            // counts as non-linear
5094            if args.iter().any(&hit) {
5095                return Err(Error::NonlinearEquation {
5096                    name: name.clone(),
5097                    why: "the unknown appears inside a function argument".to_string(),
5098                });
5099            }
5100            (zeros(), e.clone())
5101        }
5102        _ => {
5103            if hit(e) {
5104                return Err(Error::NonlinearEquation {
5105                    name: "the equation".into(),
5106                    why: "this construct is not supported by the linear solver".into(),
5107                });
5108            }
5109            (zeros(), e.clone())
5110        }
5111    })
5112}
5113
5114/// Shape convention for equation / unknown lists: a matrix literal is **flattened** into entries
5115/// (row-major).
5116/// `[e1, e2]` and `[e1; e2]` are the same set of equations — the user need not remember the
5117/// direction.
5118fn flat_mat_items(e: &Expr) -> Option<Vec<Expr>> {
5119    match e {
5120        Expr::Mat(rows) => {
5121            let items: Vec<Expr> = rows.iter().flatten().cloned().collect();
5122            if items.is_empty() {
5123                None
5124            } else {
5125                Some(items)
5126            }
5127        }
5128        _ => None,
5129    }
5130}
5131
5132/// Unknown list: after flattening, every entry must be a bare variable name.
5133fn mat_var_names(e: &Expr) -> Option<Vec<String>> {
5134    let mut out = Vec::new();
5135    for c in flat_mat_items(e)? {
5136        match c {
5137            Expr::Var(n) => out.push(n),
5138            _ => return None,
5139        }
5140    }
5141    Some(out)
5142}
5143
5144/// Linear system solving: `solve([eq1, eq2, …], [x1, x2, …])`, each equation written as
5145/// "expression = 0".
5146///
5147/// Gauss–Jordan elimination runs over the **expression ring**: the coefficients are IR
5148/// subexpressions rather than numbers, and `simplify` normalizes after every row operation. It
5149/// returns the solution vector (column-matrix IR) — eval / emission / dimensions / CSE all go
5150/// through
5151/// the existing lanes, with no second mechanism.
5152///
5153/// Only full rank gives a unique solution: underdetermined and contradictory systems are rejected
5154/// outright here. Removal of redundant equations is **in the foldable sense**:
5155/// if a redundant row with symbolic coefficients cannot be simplified to zero, a "contradiction"
5156/// is reported conservatively (better to refuse than to give a wrong solution).
5157/// Pivot non-zeroness follows the same line — if zero cannot be proven, treat it as non-zero
5158/// (consistent with the single-variable solve trusting `a ≠ 0`).
5159// The Gaussian elimination loops are all row/column semantics (r/c serve as indices and for bounds
5160// checks), not set iteration
5161#[allow(clippy::needless_range_loop)]
5162pub fn solve_system(eqs: &[Expr], vars: &[String]) -> Result<Expr, Error> {
5163    if vars.is_empty() {
5164        return Err(Error::InvalidInput(
5165            "the list of unknowns is empty; at least one is required".into(),
5166        ));
5167    }
5168    if eqs.is_empty() {
5169        return Err(Error::InvalidInput(
5170            "the list of equations is empty; at least one is required".into(),
5171        ));
5172    }
5173    let mut seen = BTreeSet::new();
5174    for v in vars {
5175        if !seen.insert(v.as_str()) {
5176            return Err(Error::InvalidInput(format!(
5177                "the unknown `{v}` appears twice in the list"
5178            )));
5179        }
5180    }
5181    let (m, n) = (eqs.len(), vars.len());
5182    // Augmented matrix [A | −b]: eq_i = Σ_j a_ij·v_j + b_i = 0 ⟺ A·v = −b
5183    let mut aug: Vec<Vec<Expr>> = Vec::with_capacity(m);
5184    for (i, eq) in eqs.iter().enumerate() {
5185        // Propagate the typed error, wrapped with the equation's 1-based position: the
5186        // `InEquation` composition keeps the inner variant catalogued (never downgraded to a
5187        // `Message`) and re-renders the inner message in the target locale, so "which equation"
5188        // survives without losing the nine-language rendering.
5189        let (a, b) = lin_coeffs_multi(eq, vars).map_err(|error| Error::InEquation {
5190            index: i + 1,
5191            error: Box::new(error),
5192        })?;
5193        // Matrix-valued coefficients: the solution would be a matrix division, and the scalar lane
5194        // would generate code like
5195        // `f64 / Vec<Vec<f64>>` that does not compile — the same guard as the single-variable lane
5196        for (j, aj) in a.iter().enumerate() {
5197            if is_matrix_value(&simplify(aj)) {
5198                return Err(Error::InEquation {
5199                    index: i + 1,
5200                    error: Box::new(Error::MatrixCoefficient(vars[j].clone())),
5201                });
5202            }
5203        }
5204        if is_matrix_value(&simplify(&b)) {
5205            // The constant term has no variable name; the wrapper already names the equation.
5206            return Err(Error::InEquation {
5207                index: i + 1,
5208                error: Box::new(Error::MatrixCoefficient("<constant>".into())),
5209            });
5210        }
5211        let mut row = a;
5212        row.push(neg(b));
5213        aug.push(row);
5214    }
5215    // The zero test must use the **structural zero**: `simplify` does not combine like terms, so
5216    // `k − k` cannot be folded,
5217    // and taking it as a pivot yields 0/0 (an error at the evaluation layer / NaN at the emission
5218    // layer) or takes an underdetermined system as unique.
5219    let is_zero = |e: &Expr| is_structurally_zero(e);
5220    let mut pivots = 0usize;
5221    for col in 0..n {
5222        let Some(p) = (pivots..m).find(|&r| !is_zero(&aug[r][col])) else {
5223            return Err(Error::Underdetermined(vars[col].clone()));
5224        };
5225        aug.swap(pivots, p);
5226        // Normalize the pivot row: divide the whole row by the pivot (a symbolic expression can
5227        // serve as a denominator too).
5228        // Set the first element to 1 **explicitly**: `simplify` cannot fold a shape like `piv/piv`
5229        // (it does not combine
5230        // like terms), and leaving it would make later row operations compute fake non-zeros such as
5231        // `x − 1·x`.
5232        let piv = aug[pivots][col].clone();
5233        for c in (col + 1)..=n {
5234            aug[pivots][c] = simplify(&div(aug[pivots][c].clone(), piv.clone()));
5235        }
5236        aug[pivots][col] = num(1.0);
5237        // Eliminate this column from the other rows. Afterwards set that cell to zero
5238        // **explicitly** — this column is mathematically already
5239        // eliminated exactly, and relying on `simplify` to prove `a − a` is zero is unreliable.
5240        for r in 0..m {
5241            if r == pivots || is_zero(&aug[r][col]) {
5242                continue;
5243            }
5244            let f = aug[r][col].clone();
5245            for c in (col + 1)..=n {
5246                aug[r][c] = simplify(&sub(
5247                    aug[r][c].clone(),
5248                    mul(f.clone(), aug[pivots][c].clone()),
5249                ));
5250            }
5251            aug[r][col] = num(0.0);
5252        }
5253        pivots += 1;
5254    }
5255    // After the unknowns run out, the remaining equations must be identities: 0 = non-zero is a
5256    // contradiction
5257    for r in pivots..m {
5258        if !is_zero(&aug[r][n]) {
5259            return Err(Error::Inconsistent);
5260        }
5261    }
5262    // Row j is now exactly `1·v_j = aug[j][n]`
5263    let sols: Vec<Vec<Expr>> = (0..n).map(|j| vec![simplify(&aug[j][n].clone())]).collect();
5264    Ok(Expr::Mat(sols))
5265}
5266
5267/// Coefficient vector of a polynomial (**low degree to high degree**):
5268/// `poly_coeffs_vec(poly, x)` → a `1×n` row vector.
5269///
5270/// Complementary to `roots`: `roots` gives the roots, this gives the coefficients — both
5271/// presuppose "a univariate polynomial in x",
5272/// and non-polynomial shapes are always rejected (no guessing).
5273///
5274/// Dimensions: each coefficient has dimension `dim(the k-th term of poly) / dim(x)^k`, so the
5275/// coefficients have **different dimensions**;
5276/// the result is returned through the **matrix-value lane**, where the matrix elements must share
5277/// a dimension — therefore the polynomial itself must be
5278/// **dimensionally homogeneous** (all terms share a dimension ⇒ the coefficients lose one power of
5279/// x's dimension per degree), and that is checked explicitly.
5280pub fn poly_coeffs_vec(e: &Expr, var: &str) -> Result<Expr, Error> {
5281    let coeffs = poly_coeffs(e, var).ok_or_else(|| Error::NotPolynomial {
5282        var: var.to_string(),
5283    })?;
5284    let n = coeffs.len();
5285    let mut trimmed = coeffs;
5286    while trimmed.len() > 1
5287        && matches!(simplify(&trimmed[trimmed.len() - 1]), Expr::Num(v) if v == 0.0)
5288    {
5289        trimmed.pop();
5290    }
5291    let out: Vec<Expr> = trimmed.into_iter().map(|c| simplify(&c)).collect();
5292    if out.len() == 1 && matches!(out[0], Expr::Num(v) if v == 0.0) {
5293        return Err(Error::InvalidInput(format!(
5294            "`poly_coeffs`: `{var}` is a zero polynomial, so there are no coefficients to report"
5295        )));
5296    }
5297    let _ = n;
5298    // Row vector (1×k): kept distinct from the column vector of `roots`, to avoid the shape
5299    // confusion of "coefficients taken for roots"
5300    Ok(Expr::Mat(vec![out]))
5301}
5302
5303/// Polynomial root finding: `roots(poly, x)` → **all roots** satisfying `poly = 0` (column
5304/// vector).
5305///
5306/// Only up to degree 2: degree 1 is delegated to `solve_linear` (the same copy of the math),
5307/// degree 2 uses the closed-form root formula.
5308/// The Cardano/Ferrari closed forms for degree 3 and above have terrible conditioning in floating
5309/// point and nobody could read what is written anyway —
5310/// rather than giving a "seemingly exact approximation", reject explicitly and state the degree.
5311///
5312/// The dimension of the roots **automatically equals the dimension of `x`**: the equation must be
5313/// dimensionally homogeneous (`dim_check` checks the equation first in the Call branch;
5314/// `Σ aᵢxⁱ` homogeneous ⇒ `dim(aᵢ) + i·dim(x)` constant ⇒ the roots' dimension is dim(x)),
5315/// so no extra dimension derivation is needed here.
5316///
5317/// Multiple roots appear repeated by **multiplicity** (`x² − 2x + 1` gives two 1s), consistent with
5318/// the fundamental theorem of algebra.
5319///
5320/// The real emission lane returns NaN for a negative discriminant (not an exception); a constant
5321/// negative discriminant is rejected before emission.
5322/// The generic `eval_value` is the complex value layer and gives complex roots; the complex
5323/// generation lane requires the formula to contain `j` explicitly.
5324/// The two roots are computed with the stable q/a and c/q, and the return order still corresponds
5325/// to the original (−b−√D), (−b+√D).
5326pub fn solve_poly(e: &Expr, var: &str) -> Result<Expr, Error> {
5327    let coeffs = poly_coeffs(e, var).ok_or_else(|| Error::NotPolynomial {
5328        var: var.to_string(),
5329    })?;
5330    // Drop high-degree zero coefficients: `x^3 - x^3 + x - 1` is still a degree-1 equation
5331    let mut c = coeffs;
5332    while c.len() > 1 && matches!(simplify(&c[c.len() - 1]), Expr::Num(v) if v == 0.0) {
5333        c.pop();
5334    }
5335    // Matrix-valued coefficients (`roots(M*x + b, x)`): the solution would be a matrix division, and
5336    // the scalar lane would generate
5337    // a `vec!` division that does not compile — the same line as `solve`: reject explicitly and
5338    // point to the correct form
5339    let mut normalized = Vec::with_capacity(c.len());
5340    for (k, coef) in c.iter().enumerate() {
5341        let cs = simplify(coef);
5342        if is_matrix_value(&cs) {
5343            return Err(Error::MatrixCoefficient(format!(
5344                "`roots`: the degree-{k} coefficient is matrix-valued; root finding handles scalar coefficients only"
5345            )));
5346        }
5347        normalized.push(cs);
5348    }
5349    c = normalized;
5350    match c.len() - 1 {
5351        0 => Err(Error::NonlinearEquation {
5352                name: var.to_string(),
5353                why: "the equation does not contain it, so there is nothing to solve for".into(),
5354            }),
5355        // Degree 1: `a·x + b = 0 → x = −b/a` (the same math as `solve_linear`).
5356        // Note that the **normalized coefficients** are used here rather than handing the original
5357        // expression to solve_linear: the original may
5358        // still hold high-degree terms that have already cancelled (`x³ − x³ + x − 1`), and
5359        // lin_coeffs would judge
5360        // `x³` as non-linear — even though it clearly cancels. The polynomial normalization path has
5361        // already peeled them off.
5362        1 => Ok(Expr::Mat(vec![vec![simplify(&neg(div(
5363            c[0].clone(),
5364            c[1].clone(),
5365        )))]])),
5366        2 => {
5367            let (a, b, c0) = (c[2].clone(), c[1].clone(), c[0].clone());
5368            // Using (−b±√D)/(2a) directly cancels catastrophically when b²≫4ac.
5369            // Instead use q = −½(b + sign(b)√D), with the large root = q/a and the small root = c/q;
5370            // the two internal scalar nodes keep the original (−b−√D), (−b+√D) return order.
5371            // q=0 only happens in degenerate forms such as a zero double root with b=c=0; both
5372            // evaluation and emission fall back to −b/(2a).
5373            let r1 = Expr::Call(
5374                "__quad_root_1".into(),
5375                vec![a.clone(), b.clone(), c0.clone()],
5376            );
5377            let r2 = Expr::Call("__quad_root_2".into(), vec![a, b, c0]);
5378            Ok(Expr::Mat(vec![vec![r1], vec![r2]]))
5379        }
5380        n => Err(Error::InvalidInput(format!(
5381                "`roots` solves degree 1–2 only (got degree {n}): closed forms above that are unstable in floating point, and this crate does not offer a look-exact approximation — reduce the degree first, or compute the coefficients numerically and use a numeric root finder"
5382            ))),
5383    }
5384}
5385
5386/// Numerically stable quadratic roots (the value layer and both emission lanes share the same
5387/// selection rule).
5388///
5389/// `first=true` corresponds to `(−b−√D)/(2a)` in textbook order, `false` to the other root.
5390/// When choosing `q`, b is added to a signed √D of the same sign, preventing the large root from
5391/// being cancelled first; the small root uses c/q.
5392fn stable_quadratic_root(first: bool, a: C, b: C, c: C) -> Result<C, Error> {
5393    let d = b.mul(b).sub(C::real(4.0).mul(a).mul(c));
5394    let s = d.sqrt();
5395    // When Re(conj(b)·s) ≥ 0, q/a is the first root in the original order; otherwise it is the
5396    // second.
5397    let q_is_first = b.conj().mul(s).re >= 0.0;
5398    let signed_s = if q_is_first { s } else { s.neg() };
5399    let q = b.add(signed_s).mul(C::real(-0.5));
5400    if q.re == 0.0 && q.im == 0.0 {
5401        // b=c=0 (including a zero double root): c/q would become 0/0, but both roots are just
5402        // −b/(2a).
5403        return b.neg().div(C::real(2.0).mul(a));
5404    }
5405    let large = q.div(a)?;
5406    let small = c.div(q)?;
5407    Ok(if first == q_is_first { large } else { small })
5408}
5409
5410/// **Deep expansion**: replace the expandable operators (det/trace/adjoint/inv/solve/roots/
5411/// dot/norm) **anywhere in the tree** with their expanded ordinary IR.
5412///
5413/// Why it is needed: `expand_call` only looks at the root node. In nested forms like
5414/// `2 * solve(...)`,
5415/// the solved-for unknown stays in the parameter list — generating a function
5416/// "asking the caller to pass the solved-for quantity"
5417/// while that parameter is not used in the function body at all (it gets by on
5418/// `#[allow(unused_variables)]`).
5419///
5420/// Termination: the expansion result cannot contain another Call of the same name (`solve`'s
5421/// solution is a Mat, `det` is a scalar expression),
5422/// so the recursion necessarily converges; but to be safe a depth limit is still set, returning the
5423/// input unchanged beyond it.
5424pub fn expand_deep(e: &Expr) -> Expr {
5425    fn go(e: &Expr, depth: usize) -> Expr {
5426        // The cap is aligned with the global depth limit (`check_depth` guarantees the input is ≤
5427        // MAX_DEPTH, so this
5428        // is in practice unreachable). It used to be 64: that meant **silently not expanding**, so a
5429        // `2 * solve(...)` inside a legal 70-level formula left the solved-for parameter behind — and
5430        // MAX_DEPTH is 2048.
5431        if depth > MAX_DEPTH {
5432            return e.clone();
5433        }
5434        // The root node is expandable → keep digging after expansion (the expansion may still hold
5435        // inner operators)
5436        if let Some(x) = expand_call(e) {
5437            return go(&x, depth + 1);
5438        }
5439        match e {
5440            Expr::Num(_) | Expr::Var(_) | Expr::Indexed { .. } => e.clone(),
5441            // The cells of a pattern matrix must be expanded too (cells containing operators must
5442            // not be left as they are)
5443            Expr::MatPattern(p) => Expr::MatPattern(MatPattern {
5444                rows: p
5445                    .rows
5446                    .iter()
5447                    .map(|r| {
5448                        r.iter()
5449                            .map(|c| match c {
5450                                PatternCell::El(x) => PatternCell::El(go(x, depth + 1)),
5451                                PatternCell::Dots => PatternCell::Dots,
5452                            })
5453                            .collect()
5454                    })
5455                    .collect(),
5456            }),
5457            Expr::Add(a, b) => add(go(a, depth + 1), go(b, depth + 1)),
5458            Expr::Sub(a, b) => sub(go(a, depth + 1), go(b, depth + 1)),
5459            Expr::Mul(a, b) => mul(go(a, depth + 1), go(b, depth + 1)),
5460            Expr::Div(a, b) => div(go(a, depth + 1), go(b, depth + 1)),
5461            Expr::Pow(a, b) => pow(go(a, depth + 1), go(b, depth + 1)),
5462            Expr::Neg(a) => neg(go(a, depth + 1)),
5463            Expr::Call(n, args) => {
5464                Expr::Call(n.clone(), args.iter().map(|a| go(a, depth + 1)).collect())
5465            }
5466            Expr::Mat(rows) => Expr::Mat(
5467                rows.iter()
5468                    .map(|r| r.iter().map(|c| go(c, depth + 1)).collect())
5469                    .collect(),
5470            ),
5471            Expr::Transpose(a) => transpose(go(a, depth + 1)),
5472            Expr::Deriv(u, by) => deriv(go(u, depth + 1), by.clone()),
5473            Expr::Grad(u) => grad(go(u, depth + 1)),
5474            Expr::Laplacian(u) => laplacian(go(u, depth + 1)),
5475            Expr::Sum {
5476                var,
5477                lower,
5478                upper,
5479                body,
5480            } => sum(
5481                var.clone(),
5482                go(lower, depth + 1),
5483                go(upper, depth + 1),
5484                go(body, depth + 1),
5485            ),
5486            Expr::Integral {
5487                var,
5488                lower,
5489                upper,
5490                body,
5491            } => integral(
5492                var.clone(),
5493                go(lower, depth + 1),
5494                go(upper, depth + 1),
5495                go(body, depth + 1),
5496            ),
5497        }
5498    }
5499    go(e, 0)
5500}
5501
5502/// Expand the matrix operators (det / trace / adjoint / inv) on **concrete literals** into
5503/// ordinary IR.
5504///
5505/// All three lanes (evaluation/emission/symbolic differentiation) share this one expansion: once
5506/// `det` is expanded into a closed-form scalar expression,
5507/// it becomes an ordinary differentiable expression — far cheaper than "writing a separate chain
5508/// rule for det".
5509// The indexed loops here are all **row/column semantics** (i/j index rows and columns
5510// respectively), not set iteration
5511#[allow(clippy::needless_range_loop)]
5512pub fn expand_matrix_call(e: &Expr) -> Option<Expr> {
5513    let Expr::Call(name, args) = e else {
5514        return None;
5515    };
5516    if args.len() != 1 {
5517        return None;
5518    }
5519    let m = flatten_matrix_value(&args[0])?;
5520    let n = m.len();
5521    if n == 0 {
5522        return None;
5523    }
5524    // The square-matrix check is meaningful only for det/trace/adjoint/inv; `norm` takes
5525    // rectangular input (a vector is just 1×k)
5526    let square = |m: &[Vec<Expr>]| m.iter().all(|r| r.len() == m.len());
5527    match name.as_str() {
5528        "trace" => {
5529            if !square(&m) {
5530                return None;
5531            }
5532            Some(trace_of(&m))
5533        }
5534        "det" => {
5535            if !square(&m) {
5536                return None;
5537            }
5538            det_of(&m)
5539        }
5540        // Norm: `norm(v)` = √Σv² (Frobenius; for a vector it is the 2-norm)
5541        "norm" => {
5542            let mut acc: Option<Expr> = None;
5543            for row in &m {
5544                for x in row {
5545                    let sq = mul(x.clone(), x.clone());
5546                    acc = Some(match acc {
5547                        None => sq,
5548                        Some(a) => add(a, sq),
5549                    });
5550                }
5551            }
5552            Some(Expr::Call("sqrt".into(), vec![acc?]))
5553        }
5554        // adjoint = conjugate transpose. Conjugation is the identity in the real lane and `__c_conj`
5555        // in the complex lane,
5556        // so emitting conj directly here is correct for both lanes.
5557        "adjoint" => {
5558            #[allow(clippy::needless_range_loop)] // the column index j also indexes m[i][j]
5559            let cols = m.first().map(|r| r.len()).unwrap_or(0);
5560            let mut t: Vec<Vec<Expr>> = Vec::with_capacity(cols);
5561            for j in 0..cols {
5562                let mut row: Vec<Expr> = Vec::with_capacity(n);
5563                for i in 0..n {
5564                    row.push(Expr::Call("conj".into(), vec![m[i][j].clone()]));
5565                }
5566                t.push(row);
5567            }
5568            Some(Expr::Mat(t))
5569        }
5570        // Inverse: `M⁻¹ = adj(M)/det(M)`, where the (i,j) entry of the adjugate is
5571        // `(-1)^{i+j}·det(M_{ji})`.
5572        // Only up to order 3: order 4 needs 16 3×3 minors (~100 terms) and the generated code
5573        // explodes;
5574        // 2D/3D isoparametric transforms use exactly orders 2/3.
5575        "inv" => {
5576            if n > 3 || !square(&m) {
5577                return None;
5578            }
5579            let det = det_of(&m)?;
5580            let mut adj: Vec<Vec<Expr>> = Vec::with_capacity(n);
5581            for i in 0..n {
5582                let mut row: Vec<Expr> = Vec::with_capacity(n);
5583                for j in 0..n {
5584                    // Note the transpose: adj[i][j] uses minor(j, i)
5585                    let cof = det_of(&minor(&m, j, i))?;
5586                    let val = if (i + j) % 2 == 0 { cof } else { neg(cof) };
5587                    row.push(div(val, det.clone()));
5588                }
5589                adj.push(row);
5590            }
5591            Some(Expr::Mat(adj))
5592        }
5593        _ => None,
5594    }
5595}
5596
5597fn trace_of(m: &[Vec<Expr>]) -> Expr {
5598    let mut acc = m[0][0].clone();
5599    for (i, row) in m.iter().enumerate().skip(1) {
5600        acc = add(acc, row[i].clone());
5601    }
5602    acc
5603}
5604
5605/// The submatrix with row `i` and column `j` removed.
5606fn minor(m: &[Vec<Expr>], i: usize, j: usize) -> Vec<Vec<Expr>> {
5607    m.iter()
5608        .enumerate()
5609        .filter(|(r, _)| *r != i)
5610        .map(|(_, row)| {
5611            row.iter()
5612                .enumerate()
5613                .filter(|(c, _)| *c != j)
5614                .map(|(_, x)| x.clone())
5615                .collect()
5616        })
5617        .collect()
5618}
5619
5620/// Determinant: cofactor expansion along the first row, recursing down to order 1.
5621///
5622/// Limit of order 4 (4×4 = 24 terms): higher-order expansions are both long and slow, and a
5623/// numerical library is more honest.
5624/// The expanded `det` is an **ordinary scalar expression**, so it is naturally differentiable (FEM
5625/// areas/volumes rely on this).
5626fn det_of(m: &[Vec<Expr>]) -> Option<Expr> {
5627    let n = m.len();
5628    if m.iter().any(|r| r.len() != n) || n > 4 {
5629        return None;
5630    }
5631    // Empty-product convention: the 0×0 determinant is 1 — that is the minor of `inv([[a]])`
5632    if n == 0 {
5633        return Some(num(1.0));
5634    }
5635    if n == 1 {
5636        return Some(m[0][0].clone());
5637    }
5638    let mut acc: Option<Expr> = None;
5639    for (j, cell) in m[0].iter().enumerate() {
5640        let sub = det_of(&minor(m, 0, j))?;
5641        let term = mul(cell.clone(), sub);
5642        let term = if j % 2 == 0 { term } else { neg(term) };
5643        acc = Some(match acc {
5644            None => term,
5645            Some(a) => add(a, term),
5646        });
5647    }
5648    acc
5649}
5650
5651// ---------------------------------------------------------------- polynomials and Horner
5652
5653/// Accepts **polynomials** only (in `var`): returns `coeffs[k]` = the coefficient of `var^k`.
5654///
5655/// Addition/subtraction, multiplication/division by constants, and **polynomial products**
5656/// (coefficient convolution) are supported —
5657/// expansions like `(a·x + b)(x + c)` are very common in physics formulas.
5658/// Numerical root finding (Durand–Kerner iteration): `coeffs` go from **low degree to high
5659/// degree** (`[c₀, c₁, …]`).
5660///
5661/// This is the exit for degree 3 and above: `roots` in the language only does closed forms up to
5662/// degree 2 (high-order closed forms have terrible conditioning in floating point), but
5663/// **numerical** root finding works for any degree, so it lives in the tool layer.
5664///
5665/// Complex numbers use `C` (no third-party numerics library); initial values are powers of
5666/// `0.4+0.9j`, scaled preferentially by the
5667/// geometric mean of the root moduli. DK is capped at 1000 rounds with relative step `1e-10`,
5668/// followed by at most 60 Newton steps to finish;
5669/// finally it is accepted independently by `|p(z)| / Σ|aₖ||z|ᵏ ≤ 1e-8`. **Both non-convergence and
5670/// an excessive residual are errors**.
5671///
5672/// The output only zeroes imaginary noise with `|im| ≤ 1e-12·|z|`; the real part is left alone,
5673/// to avoid wiping out small roots or complex roots.
5674pub fn numeric_roots(coeffs: &[f64]) -> Result<Vec<C>, Error> {
5675    let mut c = coeffs.to_vec();
5676    while c.len() > 1 && c[c.len() - 1] == 0.0 {
5677        c.pop();
5678    }
5679    if c.iter().all(|v| *v == 0.0) {
5680        return Err(Error::InvalidInput(
5681            "zero polynomial: every number is a root, so the solution set is not determined".into(),
5682        ));
5683    }
5684    if c.iter().any(|v| !v.is_finite()) {
5685        return Err(Error::NonFiniteValue(
5686            "the polynomial coefficients contain inf/NaN, so numeric root finding is impossible"
5687                .into(),
5688        ));
5689    }
5690    let n = c.len() - 1;
5691    match n {
5692        0 => {
5693            return Err(Error::InvalidInput(
5694                "a constant polynomial (degree 0) has no roots".into(),
5695            ))
5696        }
5697        1 => {
5698            // The quotient must be finite: even when each coefficient is finite, `c0/c1` can still
5699            // overflow to inf
5700            // (`numeric_roots(&[1e300, 1e-300])` → -inf). Returning Ok(root) amounts to
5701            // promising "this is a usable root", so the same standard applies here as on the
5702            // iteration path.
5703            let r = -c[0] / c[1];
5704            if !r.is_finite() {
5705                return Err(Error::NonFiniteValue(
5706            "the solution of the linear equation overflows (the coefficient ratio exceeds the f64 range); rescale the variable and retry".into(),
5707        ));
5708            }
5709            return Ok(vec![C::new(r, 0.0)]);
5710        }
5711        _ => {}
5712    }
5713    if n > 64 {
5714        return Err(Error::InvalidInput(format!(
5715            "degree {n} exceeds the numeric root-finding limit of 64"
5716        )));
5717    }
5718    let lead = c[n];
5719    let a: Vec<f64> = c.iter().map(|v| v / lead).collect(); // make monic, avoiding magnitude overflow
5720                                                            // Initial radius: try the "geometric mean of the root moduli" (|c₀/cₙ|^(1/n)) first; that is
5721                                                            // roughly where the roots are.
5722                                                            // It used to be 1+max|aᵢ| (the Cauchy bound) — for polynomials like ∏(x−k) whose "roots are far
5723                                                            // smaller than the coefficients",
5724                                                            // the initial values were too far from the roots, 500 iterations did not converge, and healthy
5725                                                            // polynomials were misreported as "ill-conditioned".
5726                                                            // There also used to be an absolute lower bound `geo > 1e-8` here — that pulled every polynomial
5727                                                            // "with roots below 1e-8"
5728                                                            // back to the Cauchy radius (≈1): `x²−1e-50` then started at 1 to look for roots of order 1e-25,
5729                                                            // DK stalled at the noise floor, 40 Newton steps could not rescue it, and it **silently returned
5730                                                            // wrong roots** (off by up to 1e125×).
5731                                                            // The criterion can only be "finite and non-zero", with no absolute threshold.
5732    let geo = if a[0] == 0.0 || !a[0].is_finite() {
5733        0.0
5734    } else {
5735        math::powf(a[0].abs(), 1.0 / n as f64)
5736    };
5737    let radius = if geo.is_finite() && geo > 0.0 {
5738        geo
5739    } else {
5740        1.0 + a[..n].iter().fold(0.0f64, |m, v| m.max(v.abs()))
5741    };
5742    // Initial values: z_k = radius · (0.4 + 0.9j)^k
5743    let seed = C::new(0.4, 0.9);
5744    let mut z: Vec<C> = Vec::with_capacity(n);
5745    let mut p = C::ONE;
5746    for _ in 0..n {
5747        z.push(C::new(p.re * radius, p.im * radius));
5748        p = p.mul(seed);
5749    }
5750    // The magnitude reference shared by the convergence criterion and the Newton stopping criterion
5751    // = the magnitude of the roots
5752    let scale_ref = radius.abs().max(1e-300);
5753    let mut converged = false;
5754    for _ in 0..1000 {
5755        let old = z.clone();
5756        let mut max_delta = 0.0f64;
5757        for i in 0..n {
5758            // p(zᵢ) — Horner, with real coefficients after making it monic
5759            let mut val = C::new(a[n], 0.0);
5760            for k in (0..n).rev() {
5761                val = val.mul(old[i]).add(C::new(a[k], 0.0));
5762            }
5763            // Π_{j≠i} (zᵢ − zⱼ), using the old values of the **same round** (simultaneous update,
5764            // more stable convergence)
5765            let mut den = C::ONE;
5766            for (j, zj) in old.iter().enumerate() {
5767                if j != i {
5768                    den = den.mul(old[i].sub(*zj));
5769                }
5770            }
5771            if den.abs() < 1e-300 {
5772                // Two initial values overlap until the denominator underflows: perturb and continue,
5773                // neither diverging nor returning garbage
5774                z[i] = old[i].add(C::new(1e-6 * (1.0 + i as f64), 1e-6));
5775                max_delta = f64::INFINITY;
5776                continue;
5777            }
5778            let step = val.div(den)?;
5779            z[i] = old[i].sub(step);
5780            if !step.re.is_finite()
5781                || !step.im.is_finite()
5782                || !z[i].re.is_finite()
5783                || !z[i].im.is_finite()
5784            {
5785                // Overflow/ill-conditioning: **declare failure immediately**. `f64::max` returns
5786                // the other side for NaN,
5787                // so a NaN step used to be taken as "converged" and the function returned Ok(all
5788                // NaN) — far worse than an error.
5789                return Err(Error::RootFindingFailed {
5790                    reason: "the iteration produced inf/NaN (divergence)".into(),
5791                });
5792            }
5793            // The criterion is relative to the **magnitude of the roots**, not to 1: the latter,
5794            // for roots of order 1e-50,
5795            // amounts to "absolute 1e-12", declaring convergence while still dozens of orders of
5796            // magnitude away from the root.
5797            let rel = step.abs() / scale_ref;
5798            max_delta = if rel.is_finite() {
5799                max_delta.max(rel)
5800            } else {
5801                f64::INFINITY
5802            };
5803        }
5804        // Loose convergence (1e-10): DK is only responsible for **separating** the points and
5805        // bringing them near the roots; precision is left to Newton + residual acceptance.
5806        // Pushing DK for the last bits is both slow and unstable (things like ∏(x−k) oscillate back
5807        // and forth).
5808        // Using 1e-14 as a hard criterion once made a healthy polynomial (∏(x−k), k≤8) run all 500
5809        // rounds and still be "not converged".
5810        if max_delta <= 1e-10 {
5811            converged = true;
5812            break;
5813        }
5814    }
5815    if !converged {
5816        return Err(Error::RootFindingFailed {
5817            reason: "it did not converge within 1000 iterations".into(),
5818        });
5819    }
5820
5821    // Newton finish: in the simple-root case it goes straight to machine precision; multiple roots
5822    // converge only linearly, but no worse.
5823    // `p'(z)` uses the derivative form of Horner (no extra allocation).
5824    // Indexed loop: `z[i]` is read and written repeatedly in the iteration (in-place Newton), not
5825    // set iteration
5826    #[allow(clippy::needless_range_loop)]
5827    for i in 0..n {
5828        for _ in 0..60 {
5829            let mut p = C::new(a[n], 0.0);
5830            let mut dp = C::ZERO;
5831            for k in (0..n).rev() {
5832                dp = dp.mul(z[i]).add(p);
5833                p = p.mul(z[i]).add(C::new(a[k], 0.0));
5834            }
5835            if dp.abs() < 1e-300 {
5836                break;
5837            }
5838            let Ok(step) = p.div(dp) else { break };
5839            let next = z[i].sub(step);
5840            if !next.re.is_finite() || !next.im.is_finite() {
5841                break;
5842            }
5843            z[i] = next;
5844            // The stopping criterion must be **relative**: for small roots (`x²−1e-26` has roots
5845            // ±1e-13), the absolute
5846            // criterion `1e-16·(1+|z|)` stops at a relative error of 1e-3 — a 22% error.
5847            let scale = z[i].abs().max(scale_ref * 1e-6).max(1e-300);
5848            if step.abs() <= 1e-15 * scale {
5849                break;
5850            }
5851        }
5852    }
5853
5854    // Residual acceptance: `|p(z)|` must be small enough relative to the magnitudes of the
5855    // coefficients and z.
5856    // This step keeps out the case "the iteration finished but the result is meaningless" — DK does
5857    // not guarantee convergence to roots,
5858    // only fewer errors when it converges; the criterion must be independent of the iteration
5859    // itself.
5860    for zi in &z {
5861        let mut p = C::new(a[n], 0.0);
5862        for k in (0..n).rev() {
5863            p = p.mul(*zi).add(C::new(a[k], 0.0));
5864        }
5865        // The denominator of the relative backward error must be **Σ|a_k|·|z|^k** (including the
5866        // k=n term).
5867        // It used to be written as "|a_n| + Σ_{k<n}|a_k||z|^k", which for small |z| degenerates to
5868        // the constant |a_n|,
5869        // so `x²−1e-100` at z=4e-25 (off by a factor of 4e25) still had a residual ratio < 1e-49 —
5870        // the acceptance was a formality.
5871        let mut scale = 0.0f64;
5872        let mut pw = 1.0f64;
5873        // `pw` is the rolling value of |z|^k, in one-to-one correspondence with a[k] (a semantic
5874        // index, not set iteration)
5875        #[allow(clippy::needless_range_loop)]
5876        for k in 0..=n {
5877            scale += a[k].abs() * pw;
5878            pw *= zi.abs();
5879        }
5880        // Relative residual; when scale is zero (all-zero coefficients) fall back to the absolute
5881        // criterion
5882        let rel = if scale > 0.0 {
5883            p.abs() / scale
5884        } else {
5885            p.abs()
5886        };
5887        if rel > 1e-8 {
5888            return Err(Error::UnstableResidual {
5889                residual: rel,
5890                limit: 1e-8,
5891            });
5892        }
5893    }
5894
5895    // Zero out numerical noise: **the imaginary part only**. A converged real root carries imaginary
5896    // residue of order 1e-16
5897    // (`1 + 1e-38j`), which is an iteration artifact; but a small real part may be a **real** root
5898    // (`x² − 1e-26` has the two roots ±1e-13) — zeroing it amounts to reporting a fake root.
5899    // The criterion is `|im| ≤ 1e-12·|z|`; the bound is documented.
5900    // The criterion must be **relative** to `|z|`: an absolute threshold (it used to be
5901    // `1e-12·(1+|re|)`) would wipe
5902    // the whole imaginary part of "complex roots with modulus below 1e-12" as residue — and that is
5903    // all the information those roots have.
5904    // The three roots of `x³−1e-60` are `1e-20` and `−5e-21 ± 8.66e-21j`; the absolute criterion
5905    // would turn the latter two
5906    // into two real roots (relative error 0.87) without reporting an error. The relative criterion
5907    // is insensitive to magnitude.
5908    for c in z.iter_mut() {
5909        let mag = c.abs();
5910        if mag > 0.0 && c.im.abs() <= 1e-12 * mag {
5911            c.im = 0.0;
5912        }
5913    }
5914    // Deterministic output: sort by (real part, imaginary part)
5915    z.sort_by(|a, b| {
5916        a.re.partial_cmp(&b.re)
5917            .unwrap_or(core::cmp::Ordering::Equal)
5918            .then(
5919                a.im.partial_cmp(&b.im)
5920                    .unwrap_or(core::cmp::Ordering::Equal),
5921            )
5922    });
5923    Ok(z)
5924}
5925
5926pub fn poly_coeffs(e: &Expr, var: &str) -> Option<Vec<Expr>> {
5927    use Expr as E;
5928    match e {
5929        E::Num(_) | E::Indexed { .. } => Some(vec![e.clone()]),
5930        E::Var(n) => {
5931            if n == var {
5932                Some(vec![num(0.0), num(1.0)])
5933            } else {
5934                Some(vec![e.clone()])
5935            }
5936        }
5937        E::Neg(a) => Some(poly_coeffs(a, var)?.into_iter().map(neg).collect()),
5938        E::Add(a, b) | E::Sub(a, b) => {
5939            let (ca, cb) = (poly_coeffs(a, var)?, poly_coeffs(b, var)?);
5940            let n = ca.len().max(cb.len());
5941            let mut out = Vec::with_capacity(n);
5942            for k in 0..n {
5943                let x = ca.get(k).cloned().unwrap_or_else(|| num(0.0));
5944                let y = cb.get(k).cloned().unwrap_or_else(|| num(0.0));
5945                out.push(if matches!(e, E::Add(..)) {
5946                    add(x, y)
5947                } else {
5948                    sub(x, y)
5949                });
5950            }
5951            Some(out)
5952        }
5953        E::Mul(a, b) => {
5954            let (ca, cb) = (poly_coeffs(a, var)?, poly_coeffs(b, var)?);
5955            // Coefficient convolution = polynomial multiplication
5956            let mut out = vec![num(0.0); ca.len() + cb.len() - 1];
5957            for (i, x) in ca.iter().enumerate() {
5958                for (j, y) in cb.iter().enumerate() {
5959                    let prod = mul(x.clone(), y.clone());
5960                    out[i + j] = add(core::mem::replace(&mut out[i + j], num(0.0)), prod);
5961                }
5962            }
5963            Some(out)
5964        }
5965        E::Div(a, b) => {
5966            if has_var(b, var) {
5967                return None;
5968            }
5969            Some(
5970                poly_coeffs(a, var)?
5971                    .into_iter()
5972                    .map(|c| div(c, (**b).clone()))
5973                    .collect(),
5974            )
5975        }
5976        E::Pow(a, b) => match b.as_ref() {
5977            E::Num(n) if *n >= 0.0 && math::fract(*n) == 0.0 && *n <= 16.0 => {
5978                let c = poly_coeffs(a, var)?;
5979                let mut acc = vec![num(1.0)];
5980                for _ in 0..(*n as usize) {
5981                    let mut next = vec![num(0.0); acc.len() + c.len() - 1];
5982                    for (i, x) in acc.iter().enumerate() {
5983                        for (j, y) in c.iter().enumerate() {
5984                            let prod = mul(x.clone(), y.clone());
5985                            next[i + j] = add(core::mem::replace(&mut next[i + j], num(0.0)), prod);
5986                        }
5987                    }
5988                    acc = next;
5989                }
5990                Some(acc)
5991            }
5992            _ => None,
5993        },
5994        // Function calls/matrices/operators: they can only be a constant term if they contain no var
5995        // at all
5996        _ => {
5997            if has_var(e, var) {
5998                None
5999            } else {
6000                Some(vec![e.clone()])
6001            }
6002        }
6003    }
6004}
6005
6006/// Whether it is an "explicit polynomial": the base of every Pow is the variable itself (`x^k`),
6007/// with none of the `(u-1)^3` kind.
6008fn is_explicit_poly(e: &Expr, var: &str) -> bool {
6009    match e {
6010        Expr::Pow(a, b) => {
6011            let base_is_var = matches!(a.as_ref(), Expr::Var(n) if n == var);
6012            let expo_num =
6013                matches!(b.as_ref(), Expr::Num(n) if *n >= 0.0 && math::fract(*n) == 0.0);
6014            base_is_var && expo_num
6015        }
6016        Expr::Num(_) | Expr::Var(_) | Expr::Indexed { .. } => true,
6017        Expr::Neg(a) => is_explicit_poly(a, var),
6018        Expr::Add(a, b) | Expr::Sub(a, b) | Expr::Mul(a, b) | Expr::Div(a, b) => {
6019            is_explicit_poly(a, var) && is_explicit_poly(b, var)
6020        }
6021        _ => !has_var(e, var),
6022    }
6023}
6024
6025/// Horner form: `c₀ + c₁x + c₂x² + …` → `(…((cₙx + cₙ₋₁)x + cₙ₋₂)x … + c₀)`.
6026///
6027/// Why it is worth it: a degree-n polynomial drops from `2n-1` multiplications to `n`, and the
6028/// magnitudes of intermediates do not blow up
6029/// (there is no large power like `x^n`). Both numerical stability and speed improve, at the cost of
6030/// more parentheses.
6031pub fn horner_in(e: &Expr, var: &str) -> Option<Expr> {
6032    // Only apply Horner to expressions "already written in the source as c₀ + c₁x + c₂x² …".
6033    // Compact forms like `(u-1)^3` are **not expanded** — expanding them is only harder to read (and
6034    // no faster).
6035    if !is_explicit_poly(e, var) {
6036        return None;
6037    }
6038    let coeffs = poly_coeffs(e, var)?;
6039    // Below degree 1 it is pointless (the coefficients are already the simplest form)
6040    if coeffs.len() <= 2 {
6041        return None;
6042    }
6043    // Drop the highest zero coefficients (like `0*x^3`)
6044    let mut last = coeffs.len() - 1;
6045    while last > 0 && matches!(&coeffs[last], Expr::Num(v) if *v == 0.0) {
6046        last -= 1;
6047    }
6048    if last < 2 {
6049        return None;
6050    }
6051    let x = var.to_string();
6052    let x = Expr::Var(x);
6053    let mut acc = coeffs[last].clone();
6054    for k in (0..last).rev() {
6055        acc = add(mul(acc, x.clone()), coeffs[k].clone());
6056    }
6057    Some(simplify(&acc))
6058}
6059
6060/// Expand `dot(a, b)` into `Σaᵢbᵢ` (both operands must be concrete and have the same number of
6061/// elements).
6062pub fn expand_dot(e: &Expr) -> Option<Expr> {
6063    let Expr::Call(name, args) = e else {
6064        return None;
6065    };
6066    if name != "dot" || args.len() != 2 {
6067        return None;
6068    }
6069    let (a, b) = (
6070        flatten_matrix_value(&args[0])?,
6071        flatten_matrix_value(&args[1])?,
6072    );
6073    // Flatten row by row (the row count and each row's length must match)
6074    if a.len() != b.len() {
6075        return None;
6076    }
6077    let mut acc: Option<Expr> = None;
6078    for (ra, rb) in a.iter().zip(b.iter()) {
6079        if ra.len() != rb.len() {
6080            return None;
6081        }
6082        for (x, y) in ra.iter().zip(rb.iter()) {
6083            let prod = mul(x.clone(), y.clone());
6084            acc = Some(match acc {
6085                None => prod,
6086                Some(p) => add(p, prod),
6087            });
6088        }
6089    }
6090    acc
6091}
6092
6093/// Unified unary/binary operator expansion: matrix operators + linear solving.
6094///
6095/// Every lane (evaluation / emission / differentiation) asks it once first, and only takes its own
6096/// rejection path if it cannot expand.
6097pub fn expand_call(e: &Expr) -> Option<Expr> {
6098    let Expr::Call(name, args) = e else {
6099        return None;
6100    };
6101    match name.as_str() {
6102        "det" | "trace" | "adjoint" | "inv" | "norm" => expand_matrix_call(e),
6103        "dot" => expand_dot(e),
6104        "poly_coeffs" => {
6105            if args.len() != 2 {
6106                return None;
6107            }
6108            let Expr::Var(v) = &args[1] else {
6109                return None;
6110            };
6111            poly_coeffs_vec(&args[0], v).ok()
6112        }
6113        "roots" => {
6114            if args.len() != 2 {
6115                return None;
6116            }
6117            let Expr::Var(v) = &args[1] else {
6118                return None;
6119            };
6120            solve_poly(&args[0], v).ok()
6121        }
6122        "solve" => {
6123            if args.len() != 2 {
6124                return None;
6125            }
6126            // Two forms: single-variable `solve(eq, x)` solves to a scalar; a system
6127            // `solve([eq…], [x…])` solves to a column vector — both expand here, single
6128            // mathematical source
6129            match &args[1] {
6130                Expr::Var(v) => solve_linear(&args[0], v).ok(),
6131                Expr::Mat(_) => {
6132                    let vars = mat_var_names(&args[1])?;
6133                    let eqs = flat_mat_items(&args[0])?;
6134                    solve_system(&eqs, &vars).ok()
6135                }
6136                _ => None,
6137            }
6138        }
6139        _ => None,
6140    }
6141}
6142
6143/// Whether the expression is **statically expandable** into a concrete matrix (decides the return
6144/// type of the generated function).
6145pub fn is_matrix_value(e: &Expr) -> bool {
6146    flatten_matrix_value(e).is_some()
6147}
6148
6149/// Emission of a concrete matrix: `vec![vec![a, b], vec![c, d]]` (elements go through the scalar
6150/// emitter, CSE as usual).
6151///
6152/// `Vec<Vec<f64>>` is used rather than fixed-size arrays: the `n` of the generator lane (pattern
6153/// matrices) is a runtime parameter,
6154/// and the two lanes must return **the same type**, otherwise downstream would have to write two
6155/// copies of the code for "literal matrices" and "generated matrices".
6156fn emit_mat_literal(
6157    rows: &[Vec<Expr>],
6158    counts: &HashMap<String, usize>,
6159    names: &mut HashMap<String, String>,
6160    out: &mut Vec<String>,
6161    counter: &mut usize,
6162    fx: Fx,
6163) -> String {
6164    let mut parts = Vec::new();
6165    for r in rows {
6166        let mut cols = Vec::new();
6167        for c in r {
6168            let (s, _) = emit_node(c, false, counts, names, out, counter, fx);
6169            cols.push(s);
6170        }
6171        parts.push(format!("vec![{}]", cols.join(", ")));
6172    }
6173    format!("vec![{}]", parts.join(", "))
6174}
6175
6176fn emit_uncached(
6177    e: &Expr,
6178    counts: &HashMap<String, usize>,
6179    names: &mut HashMap<String, String>,
6180    out: &mut Vec<String>,
6181    counter: &mut usize,
6182    fx: Fx,
6183) -> (String, u8) {
6184    match e {
6185        Expr::Num(v) => (fx.lit(*v), 9),
6186        Expr::Var(n) => (rust_ident(n), 9),
6187        Expr::Neg(a) => {
6188            if let Some(m) = flatten_matrix_value(e) {
6189                return (emit_mat_literal(&m, counts, names, out, counter, fx), 9);
6190            }
6191            let (s, p) = emit_node(a, false, counts, names, out, counter, fx);
6192            (format!("-{}", wrap(s, p, 5)), 4)
6193        }
6194        Expr::Add(a, b) => {
6195            // Element-wise matrix add/subtract: fold into a literal (scalar addition takes the
6196            // precedence path below as usual)
6197            if let Some(m) = flatten_matrix_value(e) {
6198                return (emit_mat_literal(&m, counts, names, out, counter, fx), 9);
6199            }
6200            // `x + (-3)` is written as `x - 3`: simplify folds out negative constants, and emitting
6201            // them as an addition is ugly
6202            if let Expr::Num(v) = b.as_ref() {
6203                if *v < 0.0 {
6204                    let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6205                    return (format!("{} - {}", wrap(l, lp, 2), fx.lit(-*v)), 2);
6206                }
6207            }
6208            let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6209            let (r, rp) = emit_node(b, false, counts, names, out, counter, fx);
6210            (format!("{} + {}", wrap(l, lp, 2), wrap(r, rp, 3)), 2)
6211        }
6212        Expr::Sub(a, b) => {
6213            // Element-wise matrix add/subtract: fold into a literal (scalar addition takes the
6214            // precedence path below as usual)
6215            if let Some(m) = flatten_matrix_value(e) {
6216                return (emit_mat_literal(&m, counts, names, out, counter, fx), 9);
6217            }
6218            let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6219            let (r, rp) = emit_node(b, false, counts, names, out, counter, fx);
6220            (format!("{} - {}", wrap(l, lp, 2), wrap(r, rp, 3)), 2)
6221        }
6222        Expr::Mul(a, b) => {
6223            // Concrete matrix multiply / broadcast multiply: fold into a 2-D array literal (the
6224            // direct path at teaching scale;
6225            // large matrices go through pattern matrices + the loop generation lane)
6226            if let Some(m) = flatten_matrix_value(e) {
6227                return (emit_mat_literal(&m, counts, names, out, counter, fx), 9);
6228            }
6229            // Strength reduction: `x * -1` → `-x`, `x * 1` → `x`.
6230            // This is not just cosmetics: `* -1.0` triggers clippy::neg_multiply,
6231            // and the output must pass `clippy -D warnings`.
6232            if let Expr::Num(n) = a.as_ref() {
6233                if *n == -1.0 {
6234                    let (r, rp) = emit_node(b, false, counts, names, out, counter, fx);
6235                    return (format!("-{}", wrap(r, rp, 5)), 4);
6236                }
6237                if *n == 1.0 {
6238                    return emit_node(b, false, counts, names, out, counter, fx);
6239                }
6240            }
6241            if let Expr::Num(n) = b.as_ref() {
6242                if *n == -1.0 {
6243                    let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6244                    return (format!("-{}", wrap(l, lp, 5)), 4);
6245                }
6246                if *n == 1.0 {
6247                    return emit_node(a, false, counts, names, out, counter, fx);
6248                }
6249            }
6250            let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6251            let (r, rp) = emit_node(b, false, counts, names, out, counter, fx);
6252            (format!("{} * {}", wrap(l, lp, 3), wrap(r, rp, 4)), 3)
6253        }
6254        Expr::Div(a, b) => {
6255            let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6256            let (r, rp) = emit_node(b, false, counts, names, out, counter, fx);
6257            (format!("{} / {}", wrap(l, lp, 3), wrap(r, rp, 4)), 3)
6258        }
6259        Expr::Pow(a, b) => {
6260            // Integer matrix powers (1..=8): try folding first — exactly isomorphic to
6261            // Neg/Add/Sub/Mul/Transpose.
6262            // The guard used to be placed before the folding, so M², which is supported, got
6263            // rejected too.
6264            if let Some(m) = flatten_matrix_value(e) {
6265                return (emit_mat_literal(&m, counts, names, out, counter, fx), 9);
6266            }
6267            // Folding failed but the base is **provably** a matrix (negative/fractional/out-of-range
6268            // power, non-square):
6269            // emit compile_error, never `vec![…] * vec![…]` / `(vec![…]).sqrt()`.
6270            // The test uses the precise predicate — `matrix_ish` is the over-approximation used for
6271            // broadcast decisions, and would
6272            // misjudge **scalars** like `det(J)^2` / `norm(v)^2` / `s(i)^2` as matrix powers.
6273            let base_is_matrix =
6274                matches!(a.as_ref(), Expr::Mat(_) | Expr::MatPattern(_)) || is_matrix_value(a);
6275            if base_is_matrix {
6276                return (
6277                    "compile_error!(\"write a matrix power as an explicit matrix product (the generator supports non-negative integer powers up to 8)\")"
6278                        .to_string(),
6279                    9,
6280                );
6281            }
6282            // Decidably non-real at compile time: negative constant base + non-integer exponent. The
6283            // value layer takes the complex principal branch,
6284            // while the real lane's `powf`/`sqrt` only give NaN — reject directly, do not emit a
6285            // silent wrong value.
6286            if let (Expr::Num(bv), Expr::Num(ev)) = (a.as_ref(), b.as_ref()) {
6287                if *bv < 0.0 && math::fract(*ev) != 0.0 {
6288                    return (
6289                        "compile_error!(\"a non-integer power of a negative number has no real value (the value layer is complex): rewrite the formula or use the complex lane\")"
6290                            .to_string(),
6291                        9,
6292                    );
6293                }
6294            }
6295            let (l, lp) = emit_node(a, false, counts, names, out, counter, fx);
6296            match b.as_ref() {
6297                Expr::Num(n) if *n == 2.0 => {
6298                    let lw = wrap(l.clone(), lp, 4);
6299                    (format!("{lw} * {lw}"), 3)
6300                }
6301                Expr::Num(n) if *n == 0.5 => {
6302                    // no_std: `f64::sqrt` is from std, so go through libm
6303                    if fx.is_libm() {
6304                        (format!("libm::sqrt({})", wrap(l, lp, 3)), 9)
6305                    } else {
6306                        (format!("({}).sqrt()", wrap(l, lp, 3)), 9)
6307                    }
6308                }
6309                // Integer power: std goes through `powi`; the no_std lane has no `powi` → `libm::pow`
6310                Expr::Num(n) if math::fract(*n) == 0.0 && n.abs() < 1e9 => {
6311                    if fx.is_libm() {
6312                        (format!("libm::pow({}, {})", wrap(l, lp, 3), fx.lit(*n)), 9)
6313                    } else {
6314                        (format!("({}).powi({})", wrap(l, lp, 3), *n as i64), 9)
6315                    }
6316                }
6317                _ => {
6318                    let (r, rp) = emit_node(b, false, counts, names, out, counter, fx);
6319                    // no_std: `powf` does not exist → `libm::pow`
6320                    if fx.is_libm() {
6321                        (
6322                            format!("libm::pow({}, {})", wrap(l, lp, 3), wrap(r, rp, 3)),
6323                            9,
6324                        )
6325                    } else {
6326                        (format!("({}).powf({})", wrap(l, lp, 3), wrap(r, rp, 3)), 9)
6327                    }
6328                }
6329            }
6330        }
6331        Expr::Call(n, args) => {
6332            if matches!(n.as_str(), "__quad_root_1" | "__quad_root_2") {
6333                if args.len() != 3 {
6334                    return (
6335                        "compile_error!(\"the internal quadratic-root operator needs three coefficients\")".to_string(),
6336                        9,
6337                    );
6338                }
6339                if let [Expr::Num(a), Expr::Num(b), Expr::Num(c)] = args.as_slice() {
6340                    if b * b - 4.0 * a * c < 0.0 {
6341                        return (
6342                            "compile_error!(\"the quadratic discriminant is negative: the real lane has no real roots, use the complex lane\")"
6343                                .to_string(),
6344                            9,
6345                        );
6346                    }
6347                }
6348                let (a, _) = emit_node(&args[0], false, counts, names, out, counter, fx);
6349                let (b, _) = emit_node(&args[1], false, counts, names, out, counter, fx);
6350                let (c, _) = emit_node(&args[2], false, counts, names, out, counter, fx);
6351                let (two, four, half) = (fx.lit(2.0), fx.lit(4.0), fx.lit(0.5));
6352                let first = n == "__quad_root_1";
6353                let large = if first {
6354                    "__q_q / __q_a"
6355                } else {
6356                    "__q_c / __q_q"
6357                };
6358                let small = if first {
6359                    "__q_c / __q_q"
6360                } else {
6361                    "__q_q / __q_a"
6362                };
6363                let text = format!(
6364                    "{{ let __q_a = {a}; let __q_b = {b}; let __q_c = {c}; \
6365                     let __q_s = (__q_b * __q_b - {four} * __q_a * __q_c).sqrt(); \
6366                     let __q_first = __q_b >= 0.0; \
6367                     let __q_q = if __q_first {{ -{half} * (__q_b + __q_s) }} else {{ -{half} * (__q_b - __q_s) }}; \
6368                     if __q_q == 0.0 {{ -__q_b / ({two} * __q_a) }} else if __q_first {{ {large} }} else {{ {small} }} }}"
6369                );
6370                return (text, 9);
6371            }
6372            let Some(arg0) = args.first() else {
6373                return (
6374                    "compile_error!(\"the function call is missing its argument: every function in this dialect is unary\")".to_string(),
6375                    9,
6376                );
6377            };
6378            if n == "sqrt" && matches!(arg0, Expr::Num(v) if *v < 0.0) {
6379                return (
6380                    "compile_error!(\"the square root of a negative number has no real value (the value layer is complex): rewrite the formula or use the complex lane\")"
6381                        .to_string(),
6382                    9,
6383                );
6384            }
6385            let (a, ap) = emit_node(arg0, false, counts, names, out, counter, fx);
6386            let wrapped = wrap(a, ap, 3);
6387            // no_std lane: the same name goes through `libm::*` (`fabs` is libm's abs)
6388            if fx.is_libm() {
6389                if let Some(m) = libm_name(n) {
6390                    return (format!("libm::{m}({wrapped})"), 9);
6391                }
6392            }
6393            match n.as_str() {
6394                "log" | "ln" => (format!("({wrapped}).ln()"), 9),
6395                "exp" | "sin" | "cos" | "tan" | "sinh" | "cosh" | "tanh" | "sqrt" | "abs" => {
6396                    (format!("({wrapped}).{n}()"), 9)
6397                }
6398                // min/max/clamp: std's min/max (clamping follows the semantics of
6399                // clamp(v, lo, hi))
6400                "min" | "max" => {
6401                    let (b, bp) = emit_node(&args[1], false, counts, names, out, counter, fx);
6402                    (format!("({wrapped}).{n}({})", wrap(b, bp, 3)), 9)
6403                }
6404                "clamp" => {
6405                    let (lo, lp) = emit_node(&args[1], false, counts, names, out, counter, fx);
6406                    let (hi, hp) = emit_node(&args[2], false, counts, names, out, counter, fx);
6407                    (
6408                        format!(
6409                            "({wrapped}).max({}).min({})",
6410                            wrap(lo, lp, 3),
6411                            wrap(hi, hp, 3)
6412                        ),
6413                        9,
6414                    )
6415                }
6416                // Matrix operators: uniformly go through the IR-level expansion (det/trace become
6417                // scalar expressions, adjoint becomes a matrix literal),
6418                // then hand the result to the same emitter — no separate string-level expansion
6419                "det" | "trace" | "adjoint" | "inv" | "solve" | "roots" | "poly_coeffs" | "dot"
6420                | "norm" => {
6421                    match expand_call(e) {
6422                    // Report back the **real** precedence: in `det(J)/2` the expanded det is a
6423                    // subtraction (p=2),
6424                    // and if atomicity were claimed falsely here, the parent would not add
6425                    // parentheses and the division would slip into the last term
6426                    Some(x) => emit_node(&x, false, counts, names, out, counter, fx),
6427                    None => (
6428                        "compile_error!(\"det/trace/adjoint/inv/norm/dot need a concrete matrix literal (det only goes up to order 3)\")"
6429                            .to_string(),
6430                        9,
6431                    ),
6432                    }
6433                }
6434                // Over the reals these three are identities: `re(x) = the part other than im` = x,
6435                // `conj(x) = x`.
6436                // Complex formulas take the complex lane, so emitting them this way is **exact**,
6437                // not an approximation.
6438                "re" | "im" | "conj" => (wrapped, ap),
6439                // `arg` has no meaningful value over the reals (0 or π depending on the sign); do
6440                // not guess
6441                "arg" => (
6442                    "compile_error!(\"arg is only defined for complex values: write the sign test out explicitly in a real formula\")"
6443                        .to_string(),
6444                    9,
6445                ),
6446                // Unregistered function names always fail at compile time (never emit a call to a
6447                // method that does not exist;
6448                // that kind of error points at the generated code, making debugging absurdly
6449                // expensive)
6450                _ => (
6451                    "compile_error!(\"unknown function: the real lane supports exp/ln/log/sin/cos/tan/sinh/cosh/tanh/sqrt/abs/re/im/conj\")"
6452                        .to_string(),
6453                    9,
6454                ),
6455            }
6456        }
6457        Expr::Mat(rows) => (emit_mat_literal(rows, counts, names, out, counter, fx), 9),
6458        // Symbolic operators (∂/∇/∇²) and indexed symbols: not expressible in inline emission, so
6459        // point explicitly to the file lane
6460        Expr::Deriv(..) | Expr::Grad(_) | Expr::Laplacian(_) | Expr::Indexed { .. } => (
6461            "compile_error!(\"symbolic operators and indexed symbols must go through the .formula file lane (the generator needs the context)\")"
6462                .to_string(),
6463            9,
6464        ),
6465        // Σ: with constant bounds, **fully expand** (compile-time summation); otherwise point to
6466        // the file lane
6467        Expr::Sum {
6468            var,
6469            lower,
6470            upper,
6471            body,
6472        } => {
6473            if let (Expr::Num(lo), Expr::Num(hi)) = (lower.as_ref(), upper.as_ref()) {
6474                if math::fract(*lo) == 0.0 && math::fract(*hi) == 0.0 && (hi - lo) < 64.0 {
6475                    let mut parts = Vec::new();
6476                    let mut k = *lo;
6477                    while k <= *hi {
6478                        let b = subst(body, var, &num(k));
6479                        let (t, _) = emit_node(&b, false, counts, names, out, counter, fx);
6480                        parts.push(t);
6481                        k += 1.0;
6482                    }
6483                    // Empty interval (lo > hi) = the zero element: this used to emit an empty
6484                    // string, producing a `{ }` that does not compile
6485                    if parts.is_empty() {
6486                        return ("0.0".to_string(), 9);
6487                    }
6488                    return (parts.join(" + "), 2);
6489                }
6490            }
6491            (
6492                "compile_error!(\"a non-constant sum bound must go through the .formula file lane\")".to_string(),
6493                9,
6494            )
6495        }
6496        // ∫: numerical integration is not inlined (it is a runtime loop), so point to the file
6497        // lane
6498        Expr::Integral { .. } => (
6499            "compile_error!(\"definite integrals must go through the .formula file lane (numeric integration is a runtime loop)\")".to_string(),
6500            9,
6501        ),
6502        // A pattern matrix cannot be emitted directly as a value expression: it must first go
6503        // through the recognize_pattern →
6504        // emit_matrix_ctor lane; reaching here means an upper layer skipped the triage.
6505        Expr::MatPattern(_) => (
6506            "compile_error!(\"a pattern matrix must go through the generator lane; it cannot be emitted inline\")".to_string(),
6507            9,
6508        ),
6509        // Transpose: a concrete literal can be folded into a literal (see flatten_matrix above);
6510        // the shape of a
6511        // symbolic matrix is unknown at compile time, so point explicitly to "write a concrete
6512        // matrix first" or the pattern matrix lane.
6513        Expr::Transpose(a) => {
6514            if let Some(m) = flatten_matrix_value(e) {
6515                return (emit_mat_literal(&m, counts, names, out, counter, fx), 9);
6516            }
6517            let _ = a;
6518            (
6519                "compile_error!(\"the transpose operand must be a concrete matrix literal (the shape of a symbolic matrix is unknown at compile time)\")"
6520                    .to_string(),
6521                9,
6522            )
6523        }
6524    }
6525}
6526
6527// ---------------------------------------------------------------- pattern recognition
6528
6529/// Recognize a pattern matrix as one of the builtin shapes. Failure to recognize = an error plus a
6530/// list of the supported shapes.
6531///
6532/// This is another case of "rejection is a feature": automatically expanding an arbitrary pattern
6533/// matrix is a research-level problem,
6534/// so the first version supports only three **provably correct** shapes and rejects the rest
6535/// explicitly.
6536/// Banded detection: every cell with |i-j| ≤ k is the **same expression**, and the rest are blank (0
6537/// or an ellipsis).
6538/// Only unambiguous k is accepted (m ≥ 2k+1 is needed to tell "banded" from "full matrix").
6539fn try_banded(p: &MatPattern, m: usize) -> Option<MatrixKind> {
6540    let cell = |i: usize, j: usize| -> Option<&PatternCell> { p.rows.get(i)?.get(j) };
6541    let blank = |i: usize, j: usize| -> bool {
6542        match cell(i, j) {
6543            Some(PatternCell::Dots) => true,
6544            Some(PatternCell::El(Expr::Num(v))) => *v == 0.0,
6545            _ => false,
6546        }
6547    };
6548    let el = |i: usize, j: usize| -> Option<&Expr> {
6549        match cell(i, j)? {
6550            PatternCell::El(e) => Some(e),
6551            PatternCell::Dots => None,
6552        }
6553    };
6554    // Try k from large to small (prefer the wider bandwidth interpretation)
6555    for k in (1..=(m / 2)).rev() {
6556        // Leave at least 2 rows "outside the band", otherwise it is indistinguishable from a full
6557        // matrix
6558        if m < 2 * k + 1 {
6559            continue;
6560        }
6561        let mut val: Option<&Expr> = None;
6562        let mut ok = true;
6563        let mut concrete = 0usize;
6564        for i in 0..m {
6565            for j in 0..m {
6566                let inside = i.abs_diff(j) <= k;
6567                if inside {
6568                    match el(i, j) {
6569                        Some(e) => {
6570                            concrete += 1;
6571                            match val {
6572                                None => val = Some(e),
6573                                Some(v) if key(v) == key(e) => {}
6574                                _ => {
6575                                    ok = false;
6576                                }
6577                            }
6578                        }
6579                        None => ok = false,
6580                    }
6581                } else if !blank(i, j) {
6582                    ok = false;
6583                }
6584                if !ok {
6585                    break;
6586                }
6587            }
6588            if !ok {
6589                break;
6590            }
6591        }
6592        // At least k+1 per row, and the total must match a banded shape (avoid recognizing a weird
6593        // sparse shape as banded)
6594        let expect: usize = (0..m)
6595            .map(|i| {
6596                let lo = i.saturating_sub(k);
6597                let hi = (i + k).min(m - 1);
6598                hi - lo + 1
6599            })
6600            .sum();
6601        if ok && concrete == expect {
6602            if let Some(v) = val {
6603                return Some(MatrixKind::Banded {
6604                    v: v.clone(),
6605                    half_band: k,
6606                });
6607            }
6608        }
6609    }
6610    None
6611}
6612
6613/// 4×4 block-diagonal detection: the top-left 2×2 is all P, the bottom-right 2×2 is all Q,
6614/// and both the top-right and bottom-left 2×2 blocks are all 0 or ellipses (0 and an ellipsis are
6615/// equivalent — both mean "no coupling outside the block").
6616fn try_blockdiag(p: &MatPattern) -> Option<MatrixKind> {
6617    let cell = |i: usize, j: usize| -> Option<&PatternCell> { p.rows.get(i)?.get(j) };
6618    let el = |i: usize, j: usize| -> Option<&Expr> {
6619        match cell(i, j)? {
6620            PatternCell::El(e) => Some(e),
6621            PatternCell::Dots => None,
6622        }
6623    };
6624    // "Blank" = an ellipsis or a literal 0 (no coupling outside the block / no off-diagonal terms
6625    // inside it; the two are equivalent)
6626    let blank = |i: usize, j: usize| -> bool {
6627        match cell(i, j) {
6628            Some(PatternCell::Dots) => true,
6629            Some(PatternCell::El(Expr::Num(v))) => *v == 0.0,
6630            _ => false,
6631        }
6632    };
6633    // Both 2×2 blocks outside must be entirely blank
6634    for (i, j) in [
6635        (0, 2),
6636        (0, 3),
6637        (1, 2),
6638        (1, 3),
6639        (2, 0),
6640        (2, 1),
6641        (3, 0),
6642        (3, 1),
6643    ] {
6644        if !blank(i, j) {
6645            return None;
6646        }
6647    }
6648    // Shape inside the block = p·I₂: both diagonal cells share an expression, both off-diagonal
6649    // cells are blank
6650    let block = |a: (usize, usize), b: (usize, usize), o1: (usize, usize), o2: (usize, usize)| {
6651        let da = el(a.0, a.1)?;
6652        let db = el(b.0, b.1)?;
6653        if key(da) != key(db) {
6654            return None;
6655        }
6656        if !blank(o1.0, o1.1) || !blank(o2.0, o2.1) {
6657            return None;
6658        }
6659        Some(da.clone())
6660    };
6661    let pv = block((0, 0), (1, 1), (0, 1), (1, 0))?;
6662    let qv = block((2, 2), (3, 3), (2, 3), (3, 2))?;
6663    Some(MatrixKind::BlockDiag2 { p: pv, q: qv })
6664}
6665
6666/// 4×4 bidiagonal detection (upper/lower), structure-adaptive: all main-diagonal keys identical +
6667/// the corresponding side all ellipses.
6668fn try_bidiag(p: &MatPattern) -> Option<MatrixKind> {
6669    let el = |i: usize, j: usize| -> Option<&Expr> {
6670        match p.rows.get(i)?.get(j)? {
6671            PatternCell::El(e) => Some(e),
6672            PatternCell::Dots => None,
6673        }
6674    };
6675    let is_dots = |i: usize, j: usize| {
6676        matches!(
6677            p.rows.get(i).and_then(|r| r.get(j)),
6678            Some(PatternCell::Dots)
6679        )
6680    };
6681
6682    let diag: Option<Vec<&Expr>> = (0..4).map(|i| el(i, i)).collect();
6683    let diag = diag?;
6684    if key(diag[0]) != key(diag[1]) || key(diag[1]) != key(diag[2]) || key(diag[2]) != key(diag[3])
6685    {
6686        return None;
6687    }
6688
6689    // Upper bidiagonal: the three entries of the superdiagonal (i,i+1) are concrete, the whole
6690    // lower triangle is ellipses
6691    let upper: Option<Vec<&Expr>> = (0..3).map(|i| el(i, i + 1)).collect();
6692    if let Some(up) = upper {
6693        let lower_dots = is_dots(1, 0)
6694            && is_dots(2, 0)
6695            && is_dots(2, 1)
6696            && is_dots(3, 0)
6697            && is_dots(3, 1)
6698            && is_dots(3, 2);
6699        let upper_same = key(up[0]) == key(up[1]) && key(up[1]) == key(up[2]);
6700        if lower_dots && upper_same {
6701            return Some(MatrixKind::BidiagUpper {
6702                b: diag[0].clone(),
6703                c: up[0].clone(),
6704            });
6705        }
6706    }
6707
6708    // Lower bidiagonal: the three entries of the subdiagonal (i+1,i) are concrete, the whole upper
6709    // triangle is ellipses
6710    let lower: Option<Vec<&Expr>> = (0..3).map(|i| el(i + 1, i)).collect();
6711    if let Some(lo) = lower {
6712        let upper_dots = is_dots(0, 1)
6713            && is_dots(0, 2)
6714            && is_dots(0, 3)
6715            && is_dots(1, 2)
6716            && is_dots(1, 3)
6717            && is_dots(2, 3);
6718        let lower_same = key(lo[0]) == key(lo[1]) && key(lo[1]) == key(lo[2]);
6719        if upper_dots && lower_same {
6720            return Some(MatrixKind::BidiagLower {
6721                a: lo[0].clone(),
6722                b: diag[0].clone(),
6723            });
6724        }
6725    }
6726    None
6727}
6728
6729pub fn recognize_pattern(p: &MatPattern) -> Result<MatrixKind, Error> {
6730    let (m, n) = p.grid().ok_or_else(|| {
6731        Error::ShapeMismatch("pattern matrix rows have inconsistent lengths".into())
6732    })?;
6733
6734    let el = |i: usize, j: usize| -> Option<&Expr> {
6735        match p.rows.get(i)?.get(j)? {
6736            PatternCell::El(e) => Some(e),
6737            PatternCell::Dots => None,
6738        }
6739    };
6740    let is_dots = |i: usize, j: usize| {
6741        matches!(
6742            p.rows.get(i).and_then(|r| r.get(j)),
6743            Some(PatternCell::Dots)
6744        )
6745    };
6746
6747    // ---- 3×3 family: identity / diag ----
6748    if m == 3 && n == 3 {
6749        // Corners and centre: [[x, ·, z], [·, y, ·], [w, ·, v]]
6750        let all_dots_off = [(0, 1), (1, 0), (1, 2), (2, 1)]
6751            .iter()
6752            .all(|&(i, j)| is_dots(i, j));
6753        if all_dots_off {
6754            let get = |i: usize, j: usize| el(i, j).cloned();
6755            let (x, z, y, w, v) = (get(0, 0), get(0, 2), get(1, 1), get(2, 0), get(2, 2));
6756            if let (Some(x), Some(z), Some(y), Some(w), Some(v)) = (x, z, y, w, v) {
6757                let is_zero = |e: &Expr| matches!(e, Expr::Num(v) if *v == 0.0);
6758                let is_one = |e: &Expr| matches!(e, Expr::Num(v) if *v == 1.0);
6759                // identity: [[1,·,0],[·,1,·],[0,·,1]]
6760                if is_one(&x) && is_zero(&z) && is_one(&y) && is_zero(&w) && is_one(&v) {
6761                    return Ok(MatrixKind::Identity);
6762                }
6763                // Indexed diagonals take priority: the general term d_{1}d_{2}d_{3} / d_{i} →
6764                // vector parameter
6765                if let Some(name) = indexed_diag(&[&x, &y, &v]) {
6766                    if is_zero(&z) && is_zero(&w) {
6767                        return Ok(MatrixKind::DiagVec(name));
6768                    }
6769                }
6770                // diag: the three diagonal entries share an expression, the two anti-diagonal
6771                // entries are 0
6772                let same_diag = key(&x) == key(&y) && key(&y) == key(&v);
6773                if same_diag && is_zero(&z) && is_zero(&w) {
6774                    return Ok(MatrixKind::Diag(x));
6775                }
6776            }
6777        }
6778    }
6779
6780    // ---- banded (k=2 is unambiguous only when m≥5; for 4×4, k=2 degenerates to a full matrix) ----
6781    if m == n && m >= 5 {
6782        if let Some(kind) = try_banded(p, m) {
6783            return Ok(kind);
6784        }
6785    }
6786
6787    // ---- 4×4: bidiag / tridiag ----
6788    if m == 4 && n == 4 {
6789        // Block diagonal first: top-left 2×2 = P, bottom-right 2×2 = Q, both off-diagonal blocks
6790        // all 0/ellipses
6791        //   P · | 0 0        P 0 | 0 0
6792        //   · P | 0 0  or   0 P | 0 0
6793        //   ----+----       -----+-----
6794        //   0 0 | Q ·        0 0 | Q 0
6795        //   0 0 | · Q        0 0 | 0 Q
6796        if let Some(kind) = try_blockdiag(p) {
6797            return Ok(kind);
6798        }
6799        // Bidiagonal first (structure-adaptive, not depending on the concrete cell template of
6800        // tridiag)
6801        if let Some(kind) = try_bidiag(p) {
6802            return Ok(kind);
6803        }
6804
6805        // tridiag template (the expected concrete cells; the rest must be Dots):
6806        //   b c · 0
6807        //   a b c ·
6808        //   · a b c
6809        //   0 · a b
6810        let concrete = [
6811            (0, 0),
6812            (0, 1),
6813            (0, 3),
6814            (1, 0),
6815            (1, 1),
6816            (1, 2),
6817            (2, 1),
6818            (2, 2),
6819            (2, 3),
6820            (3, 0),
6821            (3, 2),
6822            (3, 3),
6823        ];
6824        let dots_at = [(0, 2), (1, 3), (2, 0), (3, 1)];
6825        let structure_ok = dots_at.iter().all(|&(i, j)| is_dots(i, j))
6826            && concrete.iter().all(|&(i, j)| el(i, j).is_some());
6827        if structure_ok {
6828            let grab = |i: usize, j: usize| el(i, j).cloned().unwrap();
6829            let is_zero = |e: &Expr| matches!(e, Expr::Num(v) if *v == 0.0);
6830            let (b1, c1, z1) = (grab(0, 0), grab(0, 1), grab(0, 3));
6831            let (a1, b2, c2) = (grab(1, 0), grab(1, 1), grab(1, 2));
6832            let (a2, b3, c3) = (grab(2, 1), grab(2, 2), grab(2, 3));
6833            let (z2, a3, b4) = (grab(3, 0), grab(3, 2), grab(3, 3));
6834
6835            // Indexed diagonals take priority: the general term b_{i} has identical keys and would
6836            // be intercepted by the scalar branch —
6837            // but the intent of the Indexed form (a vector) is more explicit than "the same
6838            // expression" (scalar broadcasting).
6839            if let Some(name) = indexed_diag(&[&b1, &b2, &b3, &b4]) {
6840                if key(&a1) == key(&a2)
6841                    && key(&a2) == key(&a3)
6842                    && key(&c1) == key(&c2)
6843                    && key(&c2) == key(&c3)
6844                    && is_zero(&z1)
6845                    && is_zero(&z2)
6846                {
6847                    return Ok(MatrixKind::TridiagVec { a: a1, name, c: c1 });
6848                }
6849            }
6850            let diag_same = key(&b1) == key(&b2) && key(&b2) == key(&b3) && key(&b3) == key(&b4);
6851            let sub_same = key(&a1) == key(&a2) && key(&a2) == key(&a3);
6852            let sup_same = key(&c1) == key(&c2) && key(&c2) == key(&c3);
6853            if diag_same && sub_same && sup_same && is_zero(&z1) && is_zero(&z2) {
6854                return Ok(MatrixKind::Tridiag {
6855                    a: a1,
6856                    b: b1,
6857                    c: c1,
6858                });
6859            }
6860            return Err(Error::InvalidInput(
6861            "this 4×4 pattern looks tridiagonal, but the main and off-diagonals are not the same expression, or the far corners are not 0".into(),
6862        ));
6863        }
6864    }
6865
6866    Err(Error::InvalidInput(format!(
6867        "the pattern matrix ({m}×{n}) does not match any built-in shape. Supported:\n  \
6868         identity(n)                  [1 ⋯ 0; ⋮ 1 ⋮; 0 ⋯ 1]\n  \
6869         diag(d, n) / diag_v(d[i], n) one expression on the diagonal / an index sequence\n  \
6870         tridiag(a,b,c,n) / tridiag_v(...)  tridiagonal (the corners must be ellipses)\n  \
6871         bidiag_u(b,c,n) / bidiag_l(a,b,n)  upper/lower bidiagonal\n  \
6872         blockdiag2(p,q,n,m)          block diagonal diag(p·I₂, q·I₂)\n  \
6873         banded(v,k,n)                symmetric banded (unambiguous only when m≥2k+1)\n\
6874         Note: a sketch without ellipses IS a **concrete matrix** and is emitted as a literal\n\
6875         (which beats the generator: constants fold, no allocation loop) — write the ellipses if\
6876         you want the generator lane."
6877    )))
6878}
6879
6880/// Rust source of the generated matrix constructor (parameterized by shape: n is the runtime size).
6881/// The signature is derived from the pattern's **free variables** (`k: f64, ..., n: usize`), without
6882/// hard-coded parameter names.
6883pub fn emit_matrix_ctor(fname: &str, kind: &MatrixKind) -> String {
6884    match kind {
6885        MatrixKind::Identity => format!(
6886            "/// Identity matrix I_n (generated from a pattern matrix)\n#[allow(non_snake_case)]\npub fn {fname}(n: usize) -> Vec<Vec<f64>> {{\n    vec![vec![0.0; n]; n]\n        .into_iter()\n        .enumerate()\n        .map(|(i, mut row)| {{ row[i] = 1.0; row }})\n        .collect()\n}}\n"
6887        ),
6888        MatrixKind::Diag(d) => {
6889            let body = emit_block(d);
6890            let params = sig_of(core::slice::from_ref(d));
6891            format!(
6892                "/// Diagonal matrix diag(d)·I_n (generated from a pattern matrix; d is broadcast as a scalar)\n#[allow(non_snake_case)]\npub fn {fname}({params}, n: usize) -> Vec<Vec<f64>> {{\n    let mut m = vec![vec![0.0; n]; n];\n    for __row in 0..n {{ m[__row][__row] = {body}; }}\n    m\n}}\n"
6893            )
6894        }
6895        MatrixKind::DiagVec(name) => {
6896            let id = rust_ident(name);
6897            format!(
6898                "/// Diagonal matrix (generated from an indexed pattern matrix; d is a **vector** whose length must be ≥ n)\n#[allow(non_snake_case)]\npub fn {fname}({id}: &[f64], n: usize) -> Vec<Vec<f64>> {{\n    let mut m = vec![vec![0.0; n]; n];\n    for __row in 0..n {{\n        m[__row][__row] = {id}[__row];\n    }}\n    m\n}}\n"
6899            )
6900        }
6901        MatrixKind::TridiagVec { a, c, .. } => {
6902            let ba = emit_block(a);
6903            let bc = emit_block(c);
6904            format!(
6905                "/// Tridiagonal matrix (generated from an indexed pattern matrix; b is a **vector** whose length must be ≥ n)\n#[allow(non_snake_case)]\npub fn {fname}(a: f64, b: &[f64], c: f64, n: usize) -> Vec<Vec<f64>> {{\n    let av = {ba};\n    let cv = {bc};\n    let mut m = vec![vec![0.0; n]; n];\n    for __row in 0..n {{\n        m[__row][__row] = b[__row];\n        let __next = __row + 1;\n        if __next < n {{\n            m[__row][__next] = cv;\n            m[__next][__row] = av;\n        }}\n    }}\n    m\n}}\n"
6906            )
6907        }
6908        MatrixKind::BlockDiag2 { p, q } => {
6909            let bp = emit_block(p);
6910            let bq = emit_block(q);
6911            format!(
6912                "/// Block diagonal matrix diag(P·I₂, Q·I₂) (generated from a pattern matrix)\n#[allow(non_snake_case, clippy::needless_range_loop)]\npub fn {fname}(p: f64, q: f64, n: usize) -> Vec<Vec<f64>> {{\n    // n is the **total** dimension; each block takes half (the lower-right block takes the odd one)\n    let pv = {bp};\n    let qv = {bq};\n    let half = n / 2;\n    let mut m = vec![vec![0.0; n]; n];\n    for __row in 0..half {{\n        m[__row][__row] = pv;\n        m[n - 1 - __row][n - 1 - __row] = qv;\n    }}\n    if n % 2 == 1 {{\n        m[half][half] = qv;\n    }}\n    m\n}}\n"
6913            )
6914        }
6915        MatrixKind::Banded { v, half_band } => {
6916            let bv = emit_block(v);
6917            let k = *half_band;
6918            format!(
6919                "/// Symmetric banded matrix (half-bandwidth {k}: the main diagonal and {k} off-diagonals share one value)\n#[allow(non_snake_case, clippy::needless_range_loop)]\npub fn {fname}(v: f64, n: usize) -> Vec<Vec<f64>> {{\n    let vv = {bv};\n    let mut m = vec![vec![0.0; n]; n];\n    for __row in 0..n {{\n        let __hi = (__row + {k}).min(n - 1);\n        for __col in __row..=__hi {{\n            m[__row][__col] = vv;\n            m[__col][__row] = vv;\n        }}\n    }}\n    m\n}}\n"
6920            )
6921        }
6922        MatrixKind::BidiagUpper { b, c } => {
6923            let bb = emit_block(b);
6924            let bc = emit_block(c);
6925            format!(
6926                "/// Upper bidiagonal matrix (main diagonal b plus the superdiagonal c)\n#[allow(non_snake_case, clippy::needless_range_loop)]\npub fn {fname}(b: f64, c: f64, n: usize) -> Vec<Vec<f64>> {{\n    let bv = {bb};\n    let cv = {bc};\n    let mut m = vec![vec![0.0; n]; n];\n    for __row in 0..n {{\n        m[__row][__row] = bv;\n        let __next = __row + 1;\n        if __next < n {{\n            m[__row][__next] = cv;\n        }}\n    }}\n    m\n}}\n"
6927            )
6928        }
6929        MatrixKind::BidiagLower { a, b } => {
6930            let ba = emit_block(a);
6931            let bb = emit_block(b);
6932            format!(
6933                "/// Lower bidiagonal matrix (main diagonal b plus the subdiagonal a)\n#[allow(non_snake_case, clippy::needless_range_loop)]\npub fn {fname}(a: f64, b: f64, n: usize) -> Vec<Vec<f64>> {{\n    let av = {ba};\n    let bv = {bb};\n    let mut m = vec![vec![0.0; n]; n];\n    for __row in 0..n {{\n        m[__row][__row] = bv;\n        let __next = __row + 1;\n        if __next < n {{\n            m[__next][__row] = av;\n        }}\n    }}\n    m\n}}\n"
6934            )
6935        }
6936        MatrixKind::Tridiag { a, b, c } => {
6937            let ba = emit_block(a);
6938            let bb = emit_block(b);
6939            let bc = emit_block(c);
6940            let params = sig_of(&[a.clone(), b.clone(), c.clone()]);
6941            format!(
6942                "/// Tridiagonal matrix tridiag(a,b,c)_n (generated from a pattern matrix)\n#[allow(non_snake_case, clippy::too_many_arguments)]\npub fn {fname}({params}, n: usize) -> Vec<Vec<f64>> {{\n    let av = {ba};\n    let bv = {bb};\n    let cv = {bc};\n    let mut m = vec![vec![0.0; n]; n];\n    #[allow(clippy::needless_range_loop)]\n    for __row in 0..n {{\n        m[__row][__row] = bv;\n        let __next = __row + 1;\n        if __next < n {{\n            m[__row][__next] = cv;\n            m[__next][__row] = av;\n        }}\n    }}\n    m\n}}\n"
6943            )
6944        }
6945    }
6946}
6947
6948/// Generator signature: the union of the pattern's free variables (sorted and deduplicated), e.g.
6949/// `k: f64`.
6950fn sig_of(exprs: &[Expr]) -> String {
6951    let mut names: Vec<String> = exprs.iter().flat_map(vars_of).collect();
6952    names.sort();
6953    names.dedup();
6954    names
6955        .iter()
6956        .map(|n| format!("{}: f64", rust_ident(n)))
6957        .collect::<Vec<_>>()
6958        .join(", ")
6959}
6960
6961// ---------------------------------------------------------------- MathML rendering (shared by the L1 IDE / web)
6962
6963/// IR → MathML Core (presentation). Pure string generation, zero dependencies — this is the
6964/// first building block of the rendering assets: the single source of truth distributed to VS Code
6965/// hover, hikari components and the docs site.
6966pub fn to_mathml(e: &Expr) -> String {
6967    format!("<math>{}</math>", mm(e))
6968}
6969
6970fn mm(e: &Expr) -> String {
6971    match e {
6972        Expr::Num(v) => format!("<mn>{}</mn>", fmt_num(*v)),
6973        Expr::Var(n) => format!("<mi>{}</mi>", xml_escape(n)),
6974        Expr::Add(a, b) => format!("<mrow>{}<mo>+</mo>{}</mrow>", mm(a), mm(b)),
6975        Expr::Sub(a, b) => format!("<mrow>{}<mo>-</mo>{}</mrow>", mm(a), mm(b)),
6976        Expr::Mul(a, b) => format!("<mrow>{}<mo>\u{2062}</mo>{}</mrow>", mm(a), mm(b)),
6977        Expr::Div(a, b) => format!("<mfrac>{}{}</mfrac>", mm(a), mm(b)),
6978        Expr::Pow(a, b) => format!("<msup>{}{}</msup>", mm(a), mm(b)),
6979        Expr::Neg(a) => format!("<mrow><mo>-</mo>{}</mrow>", mm(a)),
6980        Expr::Call(name, args) => {
6981            // Multiple arguments are separated by `<mo>,</mo>` (otherwise `min(a,b)` renders as
6982            // `min(a b)`).
6983            let inner: String = args
6984                .iter()
6985                .map(mm)
6986                .collect::<Vec<_>>()
6987                .join("<mo>,</mo>");
6988            format!(
6989                "<mrow><mi>{}</mi><mo>\u{2061}</mo><mo>(</mo>{}<mo>)</mo></mrow>",
6990                xml_escape(name),
6991                inner
6992            )
6993        }
6994        Expr::Transpose(a) => format!("<msup>{}<mi>T</mi></msup>", mm(a)),
6995        Expr::Deriv(u, by) => format!(
6996            "<mfrac><mrow><mo>\u{2202}</mo>{}</mrow><mrow><mo>\u{2202}</mo><mi>{}</mi></mrow></mfrac>",
6997            mm(u),
6998            xml_escape(by)
6999        ),
7000        Expr::Grad(u) => format!("<mrow><mo>\u{2207}</mo>{}</mrow>", mm(u)),
7001        Expr::Laplacian(u) => format!("<mrow><msup><mo>\u{2207}</mo><mn>2</mn></msup>{}</mrow>", mm(u)),
7002        Expr::Sum { var, lower, upper, body } => format!(
7003            "<mrow><munderover><mo>\u{2211}</mo><mrow><mi>{}</mi><mo>=</mo>{}</mrow>{}</munderover>{}</mrow>",
7004            xml_escape(var),
7005            mm(lower),
7006            mm(upper),
7007            mm(body)
7008        ),
7009        Expr::Integral { var, lower, upper, body } => format!(
7010            "<mrow><munderover><mo>\u{222b}</mo>{}{}</munderover>{}<mi>{}d</mi></mrow>",
7011            mm(lower),
7012            mm(upper),
7013            mm(body),
7014            xml_escape(var)
7015        ),
7016        Expr::Indexed { name, indices } => {
7017            let sub: String = indices
7018                .iter()
7019                .map(|i| format!("<mi>{}</mi>", xml_escape(i)))
7020                .collect();
7021            format!("<msub><mi>{}</mi><mrow>{}</mrow></msub>", xml_escape(name), sub)
7022        }
7023        Expr::Mat(rows) => mat_mathml(&rows.iter().map(|r| r.iter().map(mm_cell).collect::<Vec<_>>()).collect::<Vec<_>>()),
7024        Expr::MatPattern(p) => mat_mathml(
7025            &p.rows
7026                .iter()
7027                .map(|r| r.iter().map(mm_pattern_cell).collect::<Vec<_>>())
7028                .collect::<Vec<_>>(),
7029        ),
7030    }
7031}
7032
7033fn mm_cell(e: &Expr) -> String {
7034    format!("<mtd>{}</mtd>", mm(e))
7035}
7036
7037fn mm_pattern_cell(c: &PatternCell) -> String {
7038    match c {
7039        PatternCell::El(e) => format!("<mtd>{}</mtd>", mm(e)),
7040        PatternCell::Dots => "<mtd><mo>\u{22ef}</mo></mtd>".to_string(),
7041    }
7042}
7043
7044fn mat_mathml(rows: &[Vec<String>]) -> String {
7045    let rows_xml: String = rows
7046        .iter()
7047        .map(|r| format!("<mtr>{}</mtr>", r.concat()))
7048        .collect();
7049    format!("<mtable>{rows_xml}</mtable>")
7050}
7051
7052fn xml_escape(s: &str) -> String {
7053    s.replace('&', "&amp;")
7054        .replace('<', "&lt;")
7055        .replace('>', "&gt;")
7056}
7057
7058// ---------------------------------------------------------------- canonical write-back (matlab side)
7059
7060/// Canonical matlab-side write-back: parenthesized by operator precedence, matrices aligned by
7061/// column.
7062/// This is the single source of truth for the formatter (``fmt``) — humans may use any amount of
7063/// whitespace, the machine output is constant.
7064pub fn to_matex(e: &Expr) -> String {
7065    to_matex_raw_matex(e).0
7066}
7067
7068fn wrap_matex(e: &Expr, min: u8) -> String {
7069    let (s, p) = to_matex_raw_matex(e);
7070    if p < min {
7071        format!("({s})")
7072    } else {
7073        s
7074    }
7075}
7076
7077/// Precedence-aware matex emission: **precedence lives only in this one match** (a second
7078/// `matex_prec` used to drift from it — Transpose rose to 6 while it still said 9, so
7079/// transpose-of-transpose
7080/// lost its parentheses and `x''` could not be read back).
7081fn to_matex_raw_matex(e: &Expr) -> (String, u8) {
7082    match e {
7083        Expr::Num(v) => (fmt_num(*v), 9),
7084        Expr::Var(n) => (n.clone(), 9),
7085        Expr::Neg(a) => (format!("-{}", wrap_matex(a, 5)), 4),
7086        Expr::Add(a, b) => (format!("{} + {}", wrap_matex(a, 2), wrap_matex(b, 3)), 2),
7087        Expr::Sub(a, b) => (format!("{} - {}", wrap_matex(a, 2), wrap_matex(b, 3)), 2),
7088        Expr::Mul(a, b) => (format!("{} * {}", wrap_matex(a, 3), wrap_matex(b, 4)), 3),
7089        Expr::Div(a, b) => (format!("{} / {}", wrap_matex(a, 3), wrap_matex(b, 4)), 3),
7090        // Exponentiation is **right-associative** and non-stacking: `x ^ 2 ^ 3` re-parses as
7091        // `(x^2)^3` (x⁸ becomes x⁶),
7092        // so if the base or the exponent is itself a power/transpose it always gets parentheses
7093        Expr::Pow(a, b) => (format!("{} ^ {}", wrap_matex(a, 7), wrap_matex(b, 7)), 6),
7094        Expr::Call(name, args) => (
7095            format!(
7096                "{}({})",
7097                name,
7098                args.iter().map(to_matex).collect::<Vec<_>>().join(", ")
7099            ),
7100            9,
7101        ),
7102        Expr::Transpose(a) => (format!("{}'", wrap_matex(a, 7)), 6),
7103        Expr::Deriv(u, by) => (format!("\u{2202}({}, {})", to_matex(u), by), 9),
7104        Expr::Grad(u) => (format!("\u{2207}({})", to_matex(u)), 9),
7105        Expr::Laplacian(u) => (format!("\u{2207}^2({})", to_matex(u)), 9),
7106        Expr::Sum {
7107            var,
7108            lower,
7109            upper,
7110            body,
7111        } => (
7112            format!(
7113                "\u{2211}({}, {}, {}, {})",
7114                var,
7115                to_matex(lower),
7116                to_matex(upper),
7117                to_matex(body)
7118            ),
7119            9,
7120        ),
7121        Expr::Integral {
7122            var,
7123            lower,
7124            upper,
7125            body,
7126        } => (
7127            format!(
7128                "\u{222b}({}, {}, {}, {})",
7129                var,
7130                to_matex(lower),
7131                to_matex(upper),
7132                to_matex(body)
7133            ),
7134            9,
7135        ),
7136        // The canonical form of an indexed symbol = `a(i, k)`: the same shape as matex's index
7137        // entry point,
7138        // so "format → re-parse" closes. It used to be written `a[i, k]`, which the grammar could
7139        // not read back
7140        // (the formatting gate defeated itself: after --write, --check is red forever).
7141        Expr::Indexed { name, indices } => (format!("{}({})", name, indices.join(", ")), 9),
7142        Expr::Mat(rows) => (format_matex_rows(&rows_payload(rows)), 9),
7143        Expr::MatPattern(p) => {
7144            let cells: Vec<Vec<Option<String>>> = p
7145                .rows
7146                .iter()
7147                .map(|r| {
7148                    r.iter()
7149                        .map(|c| match c {
7150                            PatternCell::El(e) => Some(to_matex(e)),
7151                            PatternCell::Dots => None,
7152                        })
7153                        .collect()
7154                })
7155                .collect();
7156            (format_matex_rows(&cells), 9)
7157        }
7158    }
7159}
7160
7161fn rows_payload(rows: &[Vec<Expr>]) -> Vec<Vec<Option<String>>> {
7162    rows.iter()
7163        .map(|r| r.iter().map(|c| Some(to_matex(c))).collect())
7164        .collect()
7165}
7166
7167/// Canonical matrix layout: each column's width = the widest content in that column + at least 1
7168/// space;
7169/// every row ends with `;` (except the last row); `...` is aligned with the content in its column.
7170#[allow(clippy::needless_range_loop)] // the column index j is layout semantics (a width-table index), not an iteration index
7171pub fn format_matex_rows(cells: &[Vec<Option<String>>]) -> String {
7172    let cols = cells.iter().map(|r| r.len()).max().unwrap_or(0);
7173    let dots = "...".to_string();
7174    let mut widths = vec![0usize; cols];
7175    for r in cells {
7176        for (j, c) in r.iter().enumerate() {
7177            let w = c.as_ref().unwrap_or(&dots).chars().count();
7178            widths[j] = widths[j].max(w);
7179        }
7180    }
7181    // Column separator = comma: the canonical form must be unambiguous (hand-written code may omit
7182    // commas and use spaces,
7183    // but a space before `-k` is swallowed by binary subtraction — the round-trip would break).
7184    let mut lines = Vec::new();
7185    for (i, r) in cells.iter().enumerate() {
7186        let mut line = String::new();
7187        for j in 0..cols {
7188            let cell = r
7189                .get(j)
7190                .and_then(|x| x.clone())
7191                .unwrap_or_else(|| dots.clone());
7192            line.push_str(&cell);
7193            if j + 1 < cols {
7194                line.push(',');
7195            }
7196            let pad = widths[j] + 1 - cell.chars().count();
7197            line.push_str(&" ".repeat(pad));
7198        }
7199        let mut line = line.trim_end().to_string();
7200        if i + 1 < cells.len() {
7201            line.push_str(" ;");
7202        }
7203        lines.push(line);
7204    }
7205    format!("[ {} ]", lines.join("\n  "))
7206}
7207
7208/// Canonical text of the whole formula set (declarations on multiple lines + formulas one by one +
7209/// matrix alignment).
7210pub fn format_set(set: &FormulaSet) -> String {
7211    let mut out = String::new();
7212    // `use` must come first: canonicalization **must never drop dependency declarations**
7213    // (dropping them raises no error, it only says "undeclared symbol" on the next build — the
7214    // hardest kind to trace)
7215    for u in &set.uses {
7216        out.push_str(&format!("use \"{u}\"\n"));
7217    }
7218    if !set.uses.is_empty() {
7219        out.push('\n');
7220    }
7221    if !set.decls.is_empty() {
7222        out.push_str("decl {\n");
7223        for d in &set.decls {
7224            match &d.unit {
7225                Some(u) => out.push_str(&format!("    {} : {} [{}];\n", d.name, d.quantity, u)),
7226                None => out.push_str(&format!("    {} : {};\n", d.name, d.quantity)),
7227            }
7228        }
7229        out.push_str("}\n");
7230    }
7231    for item in &set.items {
7232        let body = to_matex(&item.expr);
7233        match &item.name {
7234            Some(n) => out.push_str(&format!("{n} = {body}\n")),
7235            None => out.push_str(&format!("{body}\n")),
7236        }
7237    }
7238    out
7239}
7240
7241// ---------------------------------------------------------------- unit tests
7242
7243#[cfg(test)]
7244mod tests {
7245    use super::*;
7246
7247    #[test]
7248    fn units() {
7249        assert_eq!(
7250            parse_unit("A/m^2").unwrap(),
7251            Dim::from_exponents([0, -2, 0, 1, 0, 0, 0])
7252        );
7253        assert_eq!(
7254            parse_unit("V").unwrap(),
7255            Dim::from_exponents([1, 2, -3, -1, 0, 0, 0])
7256        );
7257        assert_eq!(parse_unit("kg*m/s^2").unwrap(), parse_unit("N").unwrap());
7258        assert!(parse_unit("A/m^x").is_err());
7259    }
7260
7261    #[test]
7262    fn units_fractional_exponents() {
7263        // Ω·s^(-1/2): the textbook unit of the Warburg coefficient. The parentheses are required —
7264        // without them the `/` in the exponent is confused with the unit string's division sign.
7265        let w = parse_unit("V/A*s^(-1/2)").unwrap();
7266        assert_eq!(w.display(), "kg·m^2·s^(-7/2)·A^-2");
7267        assert_eq!(
7268            w,
7269            parse_unit("V/A")
7270                .unwrap()
7271                .mul_dim(parse_unit("s").unwrap().scale_ratio(-1, 2).unwrap())
7272        );
7273        // Equivalent writing: the root and the power come from the same source
7274        assert_eq!(
7275            parse_unit("s^(1/2)").unwrap().scale_ratio(2, 1).unwrap(),
7276            parse_unit("s").unwrap()
7277        );
7278        // Anything outside the half-lattice algebra is rejected: m^(1/3) does not exist in these
7279        // dimensions
7280        assert!(parse_unit("m^(1/3)").is_err());
7281        // Unbalanced parentheses / zero denominator
7282        assert!(parse_unit("s^(-1/2").is_err());
7283        assert!(parse_unit("s^(1/0)").is_err());
7284        // A fractional exponent without parentheses is taken as the unit string's division sign
7285        // (a deliberate, explainable failure)
7286        assert!(parse_unit("V/A*s^-1/2").is_err());
7287    }
7288
7289    #[test]
7290    fn complex_arithmetic_basics() {
7291        let z = C::new(0.7, -1.3);
7292        // sqrt² = itself (principal branch)
7293        let s = z.sqrt();
7294        let back = s.mul(s);
7295        assert!((back.re - z.re).abs() < 1e-15 && (back.im - z.im).abs() < 1e-15);
7296        // exp∘ln = itself
7297        let e = z.ln().unwrap().exp();
7298        assert!((e.re - z.re).abs() < 1e-15 && (e.im - z.im).abs() < 1e-15);
7299        // An integer power of a negative real must **stay exactly on the real axis** (polar
7300        // coordinates would give a trace of a fake imaginary part)
7301        let sq = C::real(-1.3).pow_real(2.0);
7302        assert!(sq.is_real(), "负底整数幂必须落在实轴上:{sq:?}");
7303        assert!((sq.re - 1.69).abs() < 1e-15, "{}", sq.re);
7304        // A half-integer power of a negative real takes the principal branch: √(-4) = 2j
7305        let i2 = C::real(-4.0).sqrt();
7306        assert!(i2.re.abs() < 1e-15 && (i2.im - 2.0).abs() < 1e-15);
7307        // Division by zero is an error, not NaN
7308        assert!(C::ONE.div(C::ZERO).is_err());
7309        assert!(C::ZERO.ln().is_err());
7310        // Complex power: i^i = e^(-π/2) (a hard check against the analytic form)
7311        let i = C::I.pow(C::I).unwrap();
7312        assert!((i.re - (-core::f64::consts::FRAC_PI_2).exp()).abs() < 1e-15);
7313        assert!(i.im.abs() < 1e-15);
7314    }
7315
7316    #[test]
7317    fn si_prefixes_and_conversion() {
7318        // Lookup order: full name first, then prefix splitting (`m` is metre, `mol` is mole, `cd` is
7319        // candela)
7320        assert_eq!(parse_unit("mm").unwrap(), parse_unit("m").unwrap());
7321        assert_eq!(parse_unit("mol").unwrap(), parse_unit("mol").unwrap());
7322        assert_eq!(parse_unit("GHz").unwrap(), parse_unit("Hz").unwrap());
7323        assert!((parse_unit_spec("nF").unwrap().scale - 1e-9).abs() < 1e-20);
7324        assert!((parse_unit_spec("mm").unwrap().scale - 1e-3).abs() < 1e-18);
7325        assert!((parse_unit_spec("km").unwrap().scale - 1e3).abs() < 1e-9);
7326        // Prefixes scale by the exponent: (mm)^2 = 1e-6
7327        assert!((parse_unit_spec("mm^2").unwrap().scale - 1e-6).abs() < 1e-20);
7328        // Composite units: the conversion factor of mV/mm is 1 (1e-3 / 1e-3)
7329        assert!((parse_unit_spec("mV/mm").unwrap().scale - 1.0).abs() < 1e-18);
7330        // Longer prefixes win: daN is ten newtons, not "deci-attonewton"
7331        assert!((parse_unit_spec("daN").unwrap().scale - 10.0).abs() < 1e-12);
7332        // Conversion: the dimensions must agree
7333        assert!((convert(1.0, "nF", "F").unwrap() - 1e-9).abs() < 1e-24);
7334        assert!((convert(1500.0, "mV", "V").unwrap() - 1.5).abs() < 1e-12);
7335        assert!((convert(1.0, "kHz", "Hz").unwrap() - 1000.0).abs() < 1e-9);
7336        // The SI base unit of mass is kg: g and every prefixed gram must be computed from
7337        // 1 g = 1e-3 kg.
7338        assert_eq!(convert(1.0, "g", "kg").unwrap(), 1e-3);
7339        assert_eq!(convert(1.0, "kg", "g").unwrap(), 1000.0);
7340        assert_eq!(convert(1.0, "mg", "kg").unwrap(), 1e-6);
7341        assert_eq!(convert(1.0, "Mg", "kg").unwrap(), 1000.0);
7342        assert_eq!(convert(1.0, "mg", "g").unwrap(), 1e-3);
7343        assert!(matches!(
7344            convert(1.0, "nF", "V").unwrap_err(),
7345            Error::IncompatibleUnits {
7346                ref from,
7347                ref to,
7348                ..
7349            } if from == "nF" && to == "V"
7350        ));
7351        // CGPM 2022 prefixes (R/Q large, r/q small).
7352        assert_eq!(convert(1.0, "Qm", "m").unwrap(), 1e30);
7353        assert_eq!(convert(1.0, "Rm", "m").unwrap(), 1e27);
7354        assert_eq!(convert(1.0, "rm", "m").unwrap(), 1e-27);
7355        assert_eq!(convert(1.0, "qm", "m").unwrap(), 1e-30);
7356        // Non-SI units with exact definitions.
7357        assert_eq!(convert(1.0, "min", "s").unwrap(), 60.0);
7358        assert_eq!(convert(2.0, "h", "min").unwrap(), 120.0);
7359        assert_eq!(convert(1.0, "d", "h").unwrap(), 24.0);
7360        assert_eq!(convert(1.0, "L", "m^3").unwrap(), 1e-3);
7361        assert_eq!(convert(1.0, "mL", "L").unwrap(), 1e-3);
7362        assert_eq!(convert(1.0, "bar", "Pa").unwrap(), 1e5);
7363        assert_eq!(convert(1.0, "atm", "Pa").unwrap(), 101_325.0);
7364        assert_eq!(convert(1.0, "tonne", "kg").unwrap(), 1000.0);
7365        assert_eq!(convert(1.0, "nmi", "m").unwrap(), 1852.0);
7366        assert_eq!(convert(1.0, "ha", "m^2").unwrap(), 1e4);
7367        assert_eq!(convert(1.0, "acre", "m^2").unwrap(), 4_046.856_422_4);
7368        assert!((convert(1.0, "knot", "m/s").unwrap() - 1852.0 / 3600.0).abs() < 1e-15);
7369        assert!(
7370            (convert(1.0, "deg", "rad").unwrap() - core::f64::consts::PI / 180.0).abs() < 1e-15
7371        );
7372        assert!((convert(1.0, "eV", "J").unwrap() - 1.602_176_634e-19).abs() < 1e-34);
7373        assert_eq!(convert(1.0, "Wh", "J").unwrap(), 3600.0);
7374        // Ambiguous or angle-dependent symbols are refused, not guessed.
7375        let Error::AmbiguousUnit { why, remedy, .. } = parse_unit("cal").unwrap_err() else {
7376            panic!("cal must be AmbiguousUnit")
7377        };
7378        assert!(why.contains("4.184") && why.contains("4.1868"), "{why}");
7379        assert!(remedy.contains("J"), "{remedy}");
7380        let Error::AmbiguousUnit { why, remedy, .. } = parse_unit("rpm").unwrap_err() else {
7381            panic!("rpm must be AmbiguousUnit")
7382        };
7383        assert!(why.contains("rad/s"), "{why}");
7384        assert!(remedy.contains("Hz"), "{remedy}");
7385        // Both spellings of the micro sign are accepted; the ASCII `u` is not guessed
7386        assert!((parse_unit_spec("\u{00b5}F").unwrap().scale - 1e-6).abs() < 1e-20);
7387        assert!((parse_unit_spec("\u{03bc}F").unwrap().scale - 1e-6).abs() < 1e-20);
7388        assert!(parse_unit("uF").is_err());
7389        // Offset / logarithmic units: rejected explicitly (silently treating them as K /
7390        // dimensionless would compute wrong values)
7391        assert!(matches!(
7392            parse_unit("degC").unwrap_err(),
7393            Error::OffsetUnit(_)
7394        ));
7395        assert!(matches!(parse_unit("dBm").unwrap_err(), Error::LogUnit(_)));
7396        // Solid angle and radian are dimensionless
7397        assert!(parse_unit("sr").unwrap().is_zero());
7398    }
7399
7400    #[test]
7401    fn formula_names_must_respect_declared_dimensions_and_be_unique() {
7402        let set = FormulaSet {
7403            decls: vec![
7404                Decl {
7405                    name: "F".into(),
7406                    quantity: "force".into(),
7407                    unit: Some("N".into()),
7408                },
7409                Decl {
7410                    name: "d".into(),
7411                    quantity: "distance".into(),
7412                    unit: Some("m".into()),
7413                },
7414                Decl {
7415                    name: "s".into(),
7416                    quantity: "stress".into(),
7417                    unit: Some("Pa".into()),
7418                },
7419            ],
7420            items: vec![FormulaItem {
7421                name: Some("s".into()),
7422                expr: div(var("F"), var("d")),
7423                line: 7,
7424            }],
7425            uses: vec![],
7426        };
7427        let err = dims_of_set(&set).unwrap_err();
7428        // Stable variant, not a sentence: name, both dimensions and the line are all payload.
7429        let Error::ResultDimensionMismatch {
7430            name,
7431            got,
7432            declared,
7433            line,
7434        } = err
7435        else {
7436            panic!("expected ResultDimensionMismatch: {err}")
7437        };
7438        assert_eq!(name, "s");
7439        assert_eq!(got, "kg·s^-2");
7440        assert_eq!(declared, "kg·m^-1·s^-2");
7441        assert_eq!(line, 7);
7442
7443        // The same name is itself legal: the result of a = F/m exactly honors the acceleration
7444        // dimension in the decl.
7445        let mut compatible = set.clone();
7446        compatible.decls[2].unit = Some("N/m".into());
7447        // Once the same name is accepted, later entries reference the formula binding (s=F/d), not
7448        // an unexplainable dummy symbol.
7449        compatible.items.push(FormulaItem {
7450            name: Some("t".into()),
7451            expr: mul(var("s"), var("d")),
7452            line: 8,
7453        });
7454        let dims = dims_of_set(&compatible).unwrap();
7455        assert_eq!(dims["s"], parse_unit("N/m").unwrap());
7456        assert_eq!(dims["t"], parse_unit("N").unwrap());
7457
7458        let duplicate = FormulaSet {
7459            decls: vec![],
7460            items: vec![
7461                FormulaItem {
7462                    name: Some("q".into()),
7463                    expr: num(1.0),
7464                    line: 1,
7465                },
7466                FormulaItem {
7467                    name: Some("q".into()),
7468                    expr: num(2.0),
7469                    line: 2,
7470                },
7471            ],
7472            uses: vec![],
7473        };
7474        let err = dims_of_set(&duplicate).unwrap_err();
7475        assert_eq!(err.code(), "duplicate-declaration", "{err}");
7476    }
7477
7478    #[test]
7479    fn complex_division_survives_extremes() {
7480        // Regression: the naive `d = re²+im²` overflows or underflows when |b| is large/small,
7481        // so `1e300/1e10` became inf and `1e-200/1e-200` was falsely reported as division by
7482        // zero.
7483        assert_eq!(
7484            C::div(C::real(1e300), C::real(1e10)).unwrap().re,
7485            1e300 / 1e10
7486        );
7487        assert!((C::div(C::real(1e200), C::real(1e200)).unwrap().re - 1.0).abs() < 1e-15);
7488        assert!((C::div(C::real(1e-200), C::real(1e-200)).unwrap().re - 1.0).abs() < 1e-15);
7489        assert!(C::div(C::ONE, C::ZERO).is_err());
7490        // Complex: Smith's algorithm must not degenerate to NaN at extreme magnitudes either
7491        let big = C::new(1e300, 1e300);
7492        let q = C::div(big, big).unwrap();
7493        assert!((q.re - 1.0).abs() < 1e-12 && q.im.abs() < 1e-12, "{q:?}");
7494        // Real divided by real stays exact (does not take the complex formula)
7495        assert_eq!(C::div(C::real(1.0), C::real(4.0)).unwrap().re, 0.25);
7496    }
7497
7498    #[test]
7499    fn unit_exponent_overflow_is_rejected_not_wrapped() {
7500        // Regression: i32 multiplication overflow (panic in debug, wrapping into a **wrong
7501        // dimension** in release)
7502        assert!(parse_unit("m^(20000)").is_err());
7503        assert!(parse_unit("m^(2000000000)").is_err());
7504        assert!(parse_unit("V^(1000000000)").is_err());
7505        // Within the legal range, as before
7506        assert_eq!(
7507            parse_unit("m^2").unwrap(),
7508            Dim::from_exponents([0, 2, 0, 0, 0, 0, 0])
7509        );
7510    }
7511
7512    #[test]
7513    fn dim_display_round_trips_through_parse() {
7514        // Regression: `Dim::display` separates with `·` while parse_unit used to reject non-ASCII,
7515        // so "write the display back into a decl" was a broken path
7516        // Note that `J/(mol*K)` is not this dialect's notation: parentheses are used only for
7517        // **exponents**,
7518        // and grouping in a unit string relies on `/` being left-associative (`J/mol/K` =
7519        // J/(mol·K))
7520        for u in ["V/A*s^(-1/2)", "kg/m^3", "Pa*s", "J/mol/K", "m/s^2"] {
7521            let d = parse_unit(u).unwrap();
7522            let printed = d.display();
7523            let back = parse_unit(&printed).unwrap_or_else(|e| panic!("{u} → {printed}: {e}"));
7524            assert_eq!(d, back, "{u} 的回写 {printed} 不一致");
7525        }
7526    }
7527
7528    #[test]
7529    fn nondifferentiable_operators_are_named() {
7530        // arg is not differentiable over the reals: `diff` gives NaN, but the caller must be able to
7531        // know **which** one is not differentiable
7532        let e = Expr::Call("arg".into(), vec![var("x")]);
7533        assert!(contains_nan_expr(&diff(&e, "x")));
7534        assert_eq!(nondiffable(&e), vec!["arg".to_string()]);
7535        // abs / conj / re / im are now symbolic-differentiable (real abs is differentiable)
7536        for f in ["abs", "conj", "re", "im"] {
7537            let e = Expr::Call(f.into(), vec![pow(var("x"), num(2.0))]);
7538            let d = diff(&e, "x");
7539            assert!(!contains_nan_expr(&d), "`{f}` 的导数不该是 NaN:{d:?}");
7540        }
7541        // d|u|/dx = u/|u| · u': at x=1 it should be 2 (u = x², u' = 2x)
7542        let e = Expr::Call("abs".into(), vec![pow(var("x"), num(2.0))]);
7543        let d = simplify(&diff(&e, "x"));
7544        let mut env = HashMap::new();
7545        env.insert("x".to_string(), 1.0);
7546        assert!((eval(&d, &env).unwrap() - 2.0).abs() < 1e-12);
7547    }
7548
7549    #[test]
7550    fn display_and_precedence_edge_cases() {
7551        // Power of a power: both sides must add parentheses, otherwise the round-trip changes the
7552        // association order
7553        let nested = pow(pow(var("x"), num(2.0)), num(3.0));
7554        assert!(
7555            to_latex(&nested).contains("(x^{2})^{3}"),
7556            "{}",
7557            to_latex(&nested)
7558        );
7559        assert!(
7560            to_matex(&nested).contains("(x ^ 2) ^ 3"),
7561            "{}",
7562            to_matex(&nested)
7563        );
7564        // The exponent is a power: `x^(2^3)`
7565        let e = pow(var("x"), pow(num(2.0), num(3.0)));
7566        assert!(to_matex(&e).contains("x ^ (2 ^ 3)"), "{}", to_matex(&e));
7567        // ∇ is a prefix operator: it must get parentheses as a base, otherwise (∇u)² and ∇(u²) look
7568        // the same
7569        let g = pow(grad(var("u")), num(2.0));
7570        assert!(to_latex(&g).contains("(\\nabla u)^{2}"), "{}", to_latex(&g));
7571        // Transpose as the base
7572        let t = pow(transpose(var("a")), num(2.0));
7573        assert!(to_latex(&t).contains("(a^{T})^{2}"), "{}", to_latex(&t));
7574    }
7575
7576    #[test]
7577    fn matrix_division_is_rejected() {
7578        let a = Expr::Mat(vec![vec![num(2.0), num(4.0)]]);
7579        let b = Expr::Mat(vec![vec![num(2.0), num(2.0)]]);
7580        // Matrix / matrix = inversion, semantically confusing → reject
7581        let err = eval_value(&div(a.clone(), b), &HashMap::new()).unwrap_err();
7582        assert_eq!(err.code(), "matrix-division-unsupported", "{err}");
7583        assert!(err.render(crate::i18n::Locale::En).contains("inv"), "{err}");
7584        // Matrix / scalar = element-wise division: consistent with the emission lane (the Div branch
7585        // of `flatten` divides cell by cell)
7586        match eval_value(&div(a.clone(), num(2.0)), &HashMap::new()).unwrap() {
7587            Value::Matrix(m) => {
7588                assert_eq!(m.len(), 1);
7589                assert_eq!((m[0][0].re, m[0][1].re), (1.0, 2.0), "逐元素除");
7590            }
7591            other => panic!("矩阵除以标量应得矩阵,得到 {other:?}"),
7592        }
7593        // Scalar / matrix is undefined
7594        let err = eval_value(&div(num(2.0), a), &HashMap::new()).unwrap_err();
7595        let text = err.to_string();
7596        assert!(text.contains("inv"), "{text}");
7597    }
7598
7599    #[test]
7600    fn empty_sum_is_the_zero_element() {
7601        // An empty interval (lo > hi) is zero in all three places: the value layer, the real lane and
7602        // the complex lane
7603        let s = sum("i", num(5.0), num(3.0), var("i"));
7604        assert_eq!(eval(&s, &HashMap::new()).unwrap(), 0.0);
7605        assert!(emit_block(&s).contains("0.0"));
7606        assert!(emit_block_complex(&s).contains("(0.0, 0.0)"));
7607    }
7608
7609    #[test]
7610    fn declared_j_keeps_its_parameter_slot() {
7611        // `j` is a reserved constant only when undeclared; if the user declared it, it must appear
7612        // in the signature
7613        let decls = vec![Decl {
7614            name: "j".into(),
7615            quantity: "current_density".into(),
7616            unit: Some("A/m^2".into()),
7617        }];
7618        let e = mul(var("j"), num(2.0));
7619        assert_eq!(params_in_decl_order(&decls, &e), vec!["j".to_string()]);
7620        // When undeclared it is excluded as before
7621        let r = vec![Decl {
7622            name: "r".into(),
7623            quantity: "resistance".into(),
7624            unit: Some("V/A".into()),
7625        }];
7626        assert!(params_in_decl_order(&r, &add(var("r"), var("j"))).contains(&"r".to_string()));
7627    }
7628
7629    #[test]
7630    fn error_render_points_at_the_column() {
7631        let src = "decl { x : d; }\nx + undeclared_symbol";
7632        let e = FrontError::new(2, 5, "未声明的符号 `undeclared_symbol`");
7633        let text = e.render_with_source("demo.formula", src);
7634        // Three lines: header / source line (with a line-number gutter) / caret line
7635        let lines: Vec<&str> = text.lines().collect();
7636        assert_eq!(lines.len(), 4, "{text}");
7637        assert!(lines[0].contains("demo.formula:2:5"), "{text}");
7638        assert!(lines[2].contains("x + undeclared_symbol"), "{text}");
7639        // The caret lands exactly on column 5 (4 spaces for zero-based + `^`)
7640        assert!(lines[3].ends_with("    ^"), "{text:?}");
7641        // With no position (line = 0) it falls back to the plain header
7642        let plain = FrontError::plain("语义错误").render_with_source("demo", src);
7643        assert_eq!(plain, "demo: 语义错误");
7644    }
7645
7646    #[test]
7647    fn hostile_sources_are_rejected_not_crashed() {
7648        // 1) Invisible characters: zero-width spaces / bidirectional overrides / NUL are always
7649        // rejected (not as vague as "unknown character")
7650        for (src, payload) in [
7651            (
7652                "decl { x : d; } x\u{200b} + 1",
7653                "200B (zero-width character)",
7654            ),
7655            (
7656                "decl { x : d; } x + 1\u{202e}",
7657                "202E (bidirectional override)",
7658            ),
7659            ("decl { x : d; } x + 1\u{0}", "0000 (NUL)"),
7660            ("decl { x : d; } x + 1\u{feff}", "FEFF (byte order mark)"),
7661        ] {
7662            // Assert the stable code and the typed payload (code point + class) — not the
7663            // rendered sentence, whose wording is per-locale.
7664            let err = scan_source(src).unwrap_err();
7665            assert_eq!(err.code.code(), "invisible-character", "{src:?}");
7666            match &*err.code {
7667                i18n::Error::InvisibleCharacter(p) => assert_eq!(p, payload, "{src:?}"),
7668                other => panic!("{src:?} → {other:?}"),
7669            }
7670        }
7671        // Normal tabs and newlines must pass
7672        assert!(scan_source("decl {\n\tx : d;\n}\nx + 1").is_ok());
7673
7674        // 2) Depth limit: excessively deep nesting gives a **numeric error**, not a stack overflow
7675        // (the same guard at the parse layer is covered by the latex front-end unit tests — the
7676        // dependency direction can only be latex → core)
7677        let mut deep = var("x");
7678        for _ in 0..MAX_DEPTH + 5 {
7679            deep = neg(deep);
7680        }
7681        let err = check_depth(&deep).unwrap_err();
7682        let text = err.to_string();
7683        assert!(text.contains("nesting too deep"), "{text}");
7684        assert!(depth_of(&var("x")) == 1);
7685        let mut ok = var("x");
7686        for _ in 0..50 {
7687            ok = neg(ok);
7688        }
7689        assert!(check_depth(&ok).is_ok(), "50 层应放行");
7690    }
7691
7692    #[test]
7693    fn sum_step_cap_prevents_dos() {
7694        // Σ(i, 1, 1e9) used to "run all night"; now it is an explicit error
7695        let s = sum("i", num(1.0), num(1.0e9), var("i"));
7696        let err = eval_value(&s, &HashMap::new()).unwrap_err();
7697        assert_eq!(err.code(), "invalid-input", "{err}");
7698        assert!(
7699            err.render(crate::i18n::Locale::En).contains("limit"),
7700            "{err}"
7701        );
7702        // Small intervals as usual
7703        let small = sum("i", num(1.0), num(10.0), var("i"));
7704        assert_eq!(eval(&small, &HashMap::new()).unwrap(), 55.0);
7705    }
7706
7707    #[test]
7708    fn scalar_valued_matrix_ops_work_as_exponents_and_det_args() {
7709        // Regression: the exponent side used matrix_ish (an over-approximation), so `2 ^ det(J)` was
7710        // wrongly rejected —
7711        // while the emission lane got the same expression right. Both sides now use the same
7712        // (precise) predicate.
7713        let j = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
7714        let env = HashMap::new();
7715        // det(J) = -2 → 2^det = 0.25
7716        let e = pow(num(2.0), Expr::Call("det".into(), vec![j.clone()]));
7717        let v = eval_value(&e, &env).unwrap().as_scalar().unwrap();
7718        assert!((v.re - 0.25).abs() < 1e-12, "{v:?}");
7719        // norm(v) as the exponent
7720        let vv = Expr::Mat(vec![vec![num(3.0), num(4.0)]]);
7721        let e = pow(num(2.0), Expr::Call("norm".into(), vec![vv]));
7722        let v = eval_value(&e, &env).unwrap().as_scalar().unwrap();
7723        assert!((v.re - 32.0).abs() < 1e-12, "2^5 = 32:{v:?}");
7724        // A genuine matrix as the exponent → still rejected
7725        let bad = pow(num(2.0), j.clone());
7726        let err = eval_value(&bad, &env).unwrap_err();
7727        assert_eq!(err.code(), "matrix-scalar-mix", "{err}");
7728        assert!(err
7729            .render(crate::i18n::Locale::En)
7730            .contains("cannot be an exponent"));
7731        // Dimension penetration of det(inv(J)): dim(inv(J)) = J⁻¹, det = J⁻²
7732        let decls = vec![Decl {
7733            name: "c".into(),
7734            quantity: "cell".into(),
7735            unit: Some("m".into()),
7736        }];
7737        let dims = dims_of(&decls).unwrap();
7738        let cells = Expr::Mat(vec![vec![var("c"), var("c")], vec![var("c"), var("c")]]);
7739        let inner = Expr::Call("inv".into(), vec![cells]);
7740        let d = dim_check(&Expr::Call("det".into(), vec![inner]), &dims).unwrap();
7741        assert_eq!(d, parse_unit("m^-2").unwrap(), "det(inv(J)) 量纲 = m^-2");
7742    }
7743
7744    #[test]
7745    fn canonical_form_keeps_use_directives() {
7746        // Regression: canonicalization used to drop the whole `use "..."` line — raising no error,
7747        // it only said "undeclared symbol" on the next build, the hardest kind of accident to
7748        // trace.
7749        let mut set = FormulaSet::default();
7750        set.uses.push("lib/atmosphere.formula".into());
7751        set.decls.push(Decl {
7752            name: "x".into(),
7753            quantity: "d".into(),
7754            unit: None,
7755        });
7756        set.items.push(FormulaItem {
7757            name: Some("y".into()),
7758            expr: var("x"),
7759            line: 2,
7760        });
7761        let text = format_set(&set);
7762        let use_pos = text
7763            .find("use \"lib/atmosphere.formula\"")
7764            .expect("use 必须保留");
7765        let decl_pos = text.find("decl {").expect("decl 必须在");
7766        assert!(use_pos < decl_pos, "`use` 必须排在声明之前:\n{text}");
7767    }
7768
7769    #[test]
7770    fn linear_solve_works_and_rejects_nonlinearity() {
7771        // a·x + b = 0 → x = -b/a
7772        // Check the solution **numerically** (simplify rearranges the tree, so keys cannot compare
7773        // equivalent expressions)
7774        let mut env = HashMap::new();
7775        env.insert("a".to_string(), 2.0);
7776        env.insert("b".to_string(), -6.0);
7777        env.insert("k1".to_string(), 3.0);
7778        env.insert("k2".to_string(), 4.0);
7779        env.insert("x".to_string(), 0.0);
7780        let e = add(mul(var("a"), var("x")), var("b"));
7781        let x = solve_linear(&e, "x").unwrap();
7782        // a·x + b = 0 → x = -b/a = 3
7783        assert!((eval(&x, &env).unwrap() - 3.0).abs() < 1e-12, "{x:?}");
7784        // k1·a − k2·x = 0 → x = k1·a/k2 = 1.5
7785        let e2 = sub(mul(var("k1"), var("a")), mul(var("k2"), var("x")));
7786        let x2 = solve_linear(&e2, "x").unwrap();
7787        assert!((eval(&x2, &env).unwrap() - 1.5).abs() < 1e-12, "{x2:?}");
7788        // Substituting back into the original must give zero (the real criterion for "solved
7789        // correctly")
7790        env.insert("x".to_string(), eval(&x2, &env).unwrap());
7791        assert!(eval(&e2, &env).unwrap().abs() < 1e-12);
7792
7793        // Non-linearity: must error and state clearly which kind it is
7794        for (src, want) in [
7795            (mul(var("x"), var("x")), "twice in one product"),
7796            (div(num(1.0), var("x")), "denominator"),
7797            (pow(var("x"), num(2.0)), "power"),
7798            (Expr::Call("exp".into(), vec![var("x")]), "inside `exp`"),
7799        ] {
7800            // Every one of these is the **same** catalogued variant; the differing part is its
7801            // `why` payload, which is what this loop asserts.
7802            let err = solve_linear(&src, "x").unwrap_err();
7803            assert_eq!(err.code(), "nonlinear-equation", "{err}");
7804            assert!(
7805                err.render(i18n::Locale::En).contains(want),
7806                "expected `{want}` in {err}"
7807            );
7808        }
7809        // The equation has no first-degree term in x: it must be rejected (not solved), and the
7810        // message must name the variable it could not solve for. (Staging: this site is not yet
7811        // a catalogue variant — pinned by payload, not by "is still staging".)
7812        let err = solve_linear(&add(var("a"), var("b")), "x").unwrap_err();
7813        assert!(
7814            err.render(i18n::Locale::En).contains('x'),
7815            "the rejection must name the variable: {err}"
7816        );
7817    }
7818
7819    #[test]
7820    fn solve_system_solves_and_roundtrips_to_zero() {
7821        // Two-mass spring: (k1+k2)x1 − k2·x2 = F1; −k2·x1 + (k2+k3)·x2 = F2
7822        let k1 = var("k1");
7823        let k2 = var("k2");
7824        let k3 = var("k3");
7825        let f1 = var("F1");
7826        let f2 = var("F2");
7827        let (x, y) = (var("x1"), var("x2"));
7828        let eq1 = sub(
7829            sub(
7830                mul(k1.clone(), x.clone()),
7831                mul(k2.clone(), sub(y.clone(), x.clone())),
7832            ),
7833            f1.clone(),
7834        );
7835        let eq2 = sub(
7836            add(
7837                mul(k2.clone(), sub(y.clone(), x.clone())),
7838                mul(k3.clone(), y.clone()),
7839            ),
7840            f2.clone(),
7841        );
7842        let sol = solve_system(&[eq1.clone(), eq2.clone()], &["x1".into(), "x2".into()]).unwrap();
7843        let Expr::Mat(rows) = &sol else {
7844            panic!("解必须是列向量矩阵,得到 {sol:?}");
7845        };
7846        assert_eq!(rows.len(), 2);
7847        assert!(rows.iter().all(|r| r.len() == 1), "列向量形状 2×1");
7848
7849        // The solved entries must not still contain unknowns (otherwise it is "asking for it while
7850        // requiring it as input")
7851        for r in rows {
7852            for name in vars_of(&r[0]) {
7853                assert!(
7854                    !["x1", "x2"].contains(&name.as_str()),
7855                    "解里还含未知数 `{name}`"
7856                );
7857            }
7858        }
7859
7860        // Numeric substitution: plugging the solution into the original equations must give ≈ 0 (the
7861        // real criterion for "solved correctly")
7862        let mut env = HashMap::new();
7863        env.insert("k1".to_string(), 1.0);
7864        env.insert("k2".to_string(), 2.0);
7865        env.insert("k3".to_string(), 3.0);
7866        env.insert("F1".to_string(), 10.0);
7867        env.insert("F2".to_string(), 20.0);
7868        env.insert("x1".to_string(), eval(&rows[0][0], &env).unwrap());
7869        env.insert("x2".to_string(), eval(&rows[1][0], &env).unwrap());
7870        assert!(
7871            eval(&eq1, &env).unwrap().abs() < 1e-12,
7872            "eq1 残差 {}",
7873            eval(&eq1, &env).unwrap()
7874        );
7875        assert!(
7876            eval(&eq2, &env).unwrap().abs() < 1e-12,
7877            "eq2 残差 {}",
7878            eval(&eq2, &env).unwrap()
7879        );
7880
7881        // Consistent with a hand calculation by Cramer's rule:
7882        // det = (k1+k2)(k2+k3) − k2² = 3·5 − 4 = 11
7883        // x1 = [F1(k2+k3) + F2·k2]/det = (50 + 40)/11 = 90/11
7884        // x2 = [F2(k1+k2) + F1·k2]/det = (60 + 20)/11 = 80/11
7885        let det = 3.0 * 5.0 - 2.0 * 2.0;
7886        assert!((env["x1"] - 90.0 / det).abs() < 1e-12, "x1 = {}", env["x1"]);
7887        assert!((env["x2"] - 80.0 / det).abs() < 1e-12, "x2 = {}", env["x2"]);
7888    }
7889
7890    #[test]
7891    fn roots_solves_linear_and_quadratic_exactly() {
7892        let mut env = HashMap::new();
7893        for (k, v) in [("a", 2.0), ("b", -6.0), ("k", 3.0), ("F", 12.0)] {
7894            env.insert(k.to_string(), v);
7895        }
7896        // Degree 1: 2x − 6 = 0 → [3] (a 1×1 column vector)
7897        let lin = solve_poly(&sub(mul(var("a"), var("x")), num(6.0)), "x").unwrap();
7898        let Expr::Mat(r) = &lin else {
7899            panic!("必须是矩阵")
7900        };
7901        assert_eq!((r.len(), r[0].len()), (1, 1));
7902        assert!((eval(&r[0][0], &env).unwrap() - 3.0).abs() < 1e-12);
7903
7904        // Degree 2: x² − 5x + 6 = 0 → 2 and 3 (order: −b−√D first)
7905        let quad = solve_poly(
7906            &add(
7907                sub(pow(var("x"), num(2.0)), mul(num(5.0), var("x"))),
7908                num(6.0),
7909            ),
7910            "x",
7911        )
7912        .unwrap();
7913        let Expr::Mat(r) = &quad else {
7914            panic!("必须是矩阵")
7915        };
7916        assert_eq!((r.len(), r[0].len()), (2, 1), "两个根,列向量");
7917        let mut got: Vec<f64> = r.iter().map(|row| eval(&row[0], &env).unwrap()).collect();
7918        got.sort_by(|a, b| a.partial_cmp(b).unwrap());
7919        assert!((got[0] - 2.0).abs() < 1e-12, "{got:?}");
7920        assert!((got[1] - 3.0).abs() < 1e-12, "{got:?}");
7921
7922        // Plugging the roots back into the **original polynomial** must give zero (independent of
7923        // the correctness of the root formula itself)
7924        for g in &got {
7925            let mut e2 = env.clone();
7926            e2.insert("x".to_string(), *g);
7927            let orig = add(
7928                sub(pow(var("x"), num(2.0)), mul(num(5.0), var("x"))),
7929                num(6.0),
7930            );
7931            assert!(eval(&orig, &e2).unwrap().abs() < 1e-12, "代回残差");
7932        }
7933
7934        // Multiple root: x² − 2x + 1 = 0 → two 1s (repeated by multiplicity)
7935        let dbl = solve_poly(
7936            &add(
7937                sub(pow(var("x"), num(2.0)), mul(num(2.0), var("x"))),
7938                num(1.0),
7939            ),
7940            "x",
7941        )
7942        .unwrap();
7943        let Expr::Mat(r) = &dbl else { panic!() };
7944        for row in r {
7945            let v = eval(&row[0], &env).unwrap();
7946            assert!((v - 1.0).abs() < 1e-12, "{v}");
7947        }
7948
7949        // High-degree zero coefficients must be peeled off: x³ − x³ + x − 1 is still degree 1
7950        let cancel = sub(
7951            add(
7952                sub(pow(var("x"), num(3.0)), pow(var("x"), num(3.0))),
7953                var("x"),
7954            ),
7955            num(1.0),
7956        );
7957        let Expr::Mat(r) = &solve_poly(&cancel, "x").unwrap() else {
7958            panic!("必须是矩阵")
7959        };
7960        assert_eq!(r.len(), 1, "高阶项抵消后是 1 次");
7961        assert!((eval(&r[0][0], &env).unwrap() - 1.0).abs() < 1e-12);
7962    }
7963
7964    #[test]
7965    fn quadratic_roots_are_stable_and_preserve_the_documented_order() {
7966        let poly = add(
7967            add(
7968                mul(var("a"), pow(var("x"), num(2.0))),
7969                mul(var("b"), var("x")),
7970            ),
7971            var("c"),
7972        );
7973        let roots = solve_poly(&poly, "x").unwrap();
7974        let Expr::Mat(rows) = roots else {
7975            panic!("roots must be a column vector")
7976        };
7977        let eval_at = |a: f64, b: f64, c: f64, index: usize| {
7978            let env = HashMap::from([
7979                ("a".to_string(), a),
7980                ("b".to_string(), b),
7981                ("c".to_string(), c),
7982            ]);
7983            eval_value(&rows[index][0], &env)
7984                .unwrap()
7985                .as_scalar()
7986                .unwrap()
7987        };
7988        // −b−√D first: with b<0 the small root comes first, with b>0 the large root comes first. The
7989        // order is not swapped by the stabilization.
7990        let small = eval_at(1.0, -1.0e8, 1.0, 0);
7991        assert!((small.re - 1.0e-8).abs() / 1.0e-8 < 1.0e-12, "{small:?}");
7992        assert!(small.im == 0.0);
7993        assert_eq!(eval_at(1.0, -1.0e8, 1.0, 1).re, 1.0e8);
7994        assert!((eval_at(1.0, 1.0e8, 1.0, 0).re + 1.0e8).abs() / 1.0e8 < 1.0e-15);
7995        assert!((eval_at(1.0, 1.0e8, 1.0, 1).re + 1.0e-8).abs() / 1.0e-8 < 1.0e-12);
7996        // Neither a zero double root nor an ordinary double root may take the 0/0 branch of c/q.
7997        assert_eq!(eval_at(1.0, 0.0, 0.0, 0), C::ZERO);
7998        assert_eq!(eval_at(1.0, 0.0, 0.0, 1), C::ZERO);
7999        assert_eq!(eval_at(1.0, 2.0, 1.0, 0).re, -1.0);
8000        assert_eq!(eval_at(1.0, 2.0, 1.0, 1).re, -1.0);
8001        // x²+1: the complex value layer still gives −j, +j (consistent with the original formula
8002        // order).
8003        assert!(eval_at(1.0, 0.0, 1.0, 0).im < 0.0);
8004        assert!(eval_at(1.0, 0.0, 1.0, 1).im > 0.0);
8005    }
8006
8007    #[test]
8008    fn numeric_roots_finds_all_roots_including_complex() {
8009        // (x−1)(x−2)(x−3) = x³ − 6x² + 11x − 6
8010        let r = numeric_roots(&[-6.0, 11.0, -6.0, 1.0]).unwrap();
8011        assert_eq!(r.len(), 3, "三次必须有三个根(含重数)");
8012        let mut re: Vec<f64> = r.iter().map(|c| c.re).collect();
8013        re.sort_by(|a, b| a.partial_cmp(b).unwrap());
8014        for (got, want) in re.iter().zip([1.0, 2.0, 3.0]) {
8015            assert!((got - want).abs() < 1e-10, "实根 {got} ≠ {want}");
8016        }
8017        assert!(r.iter().all(|c| c.im.abs() < 1e-10), "应当全是实根");
8018
8019        // x² + 1 → ±j (purely imaginary roots must really be computed)
8020        let r2 = numeric_roots(&[1.0, 0.0, 1.0]).unwrap();
8021        assert_eq!(r2.len(), 2);
8022        let ims: Vec<f64> = r2.iter().map(|c| c.im).collect();
8023        assert!(ims.iter().any(|v| (*v - 1.0).abs() < 1e-12), "{ims:?}");
8024        assert!(ims.iter().any(|v| (*v + 1.0).abs() < 1e-12), "{ims:?}");
8025        assert!(r2.iter().all(|c| c.re.abs() < 1e-12));
8026
8027        // x³ + 1 → one real root −1 and a pair of complex roots (angles ±60°)
8028        let r3 = numeric_roots(&[1.0, 0.0, 0.0, 1.0]).unwrap();
8029        assert_eq!(r3.len(), 3);
8030        assert!(r3
8031            .iter()
8032            .any(|c| (c.re + 1.0).abs() < 1e-10 && c.im.abs() < 1e-10));
8033        // Substitute back: |z³ + 1| must be zero
8034        for z in &r3 {
8035            let z2 = z.mul(*z);
8036            let z3 = z2.mul(*z);
8037            let res = z3.add(C::ONE);
8038            assert!(res.abs() < 1e-8, "z³+1 残差 {res:?}");
8039        }
8040
8041        // Multiple root: (x−2)² = x² − 4x + 4 (numerical root finding on multiple roots is a
8042        // well-known difficulty, so a looser criterion is allowed)
8043        let r4 = numeric_roots(&[4.0, -4.0, 1.0]).unwrap();
8044        assert_eq!(r4.len(), 2);
8045        for z in &r4 {
8046            assert!((z.re - 2.0).abs() < 1e-6, "重根 {z:?}");
8047        }
8048
8049        // Boundaries: zero polynomial / constant / linear
8050        assert!(numeric_roots(&[0.0, 0.0]).is_err());
8051        assert!(numeric_roots(&[5.0]).is_err());
8052        let lin = numeric_roots(&[3.0, 2.0]).unwrap();
8053        assert!((lin[0].re + 1.5).abs() < 1e-15);
8054        // High-degree zero coefficients are peeled off
8055        assert_eq!(numeric_roots(&[3.0, 2.0, 0.0, 0.0]).unwrap().len(), 1);
8056        // Non-finite coefficients
8057        assert!(numeric_roots(&[f64::NAN, 1.0]).is_err());
8058    }
8059
8060    #[test]
8061    fn numeric_roots_never_reports_garbage() {
8062        // Four counterexamples from an independent review; all must "either give the right numbers or
8063        // report an error":
8064        // ① after overflow, f64::max swallowed the NaN, once returning Ok(all NaN)
8065        // ② noise zeroing once zeroed the **real part** too, wiping a real small root to 0
8066        // ③ with the Cauchy bound as the initial radius, healthy polynomials were misreported as
8067        // "ill-conditioned"
8068        // ④ the behavior of the zeroing criterion on small purely imaginary roots
8069
8070        // ① Wilkinson type: ∏(x−k), k=1..20 (coefficients reach 20!, with wildly different
8071        // magnitudes after making it monic)
8072        let mut coeffs = vec![1.0f64];
8073        for k in 1..=20 {
8074            let mut next = vec![0.0; coeffs.len() + 1];
8075            for (i, c) in coeffs.iter().enumerate() {
8076                next[i] += -(k as f64) * c;
8077                next[i + 1] += c;
8078            }
8079            coeffs = next;
8080        }
8081        match numeric_roots(&coeffs) {
8082            Ok(rs) => {
8083                // If results are given, every root must be finite and the substitution residual
8084                // controllable
8085                for z in &rs {
8086                    assert!(
8087                        z.re.is_finite() && z.im.is_finite(),
8088                        "根必须是有限数:{z:?}"
8089                    );
8090                    let mut acc = C::new(coeffs[coeffs.len() - 1], 0.0);
8091                    for c in coeffs.iter().rev().skip(1) {
8092                        acc = acc.mul(*z).add(C::new(*c, 0.0));
8093                    }
8094                    assert!(acc.abs() < 1e-4, "根 {z:?} 代回残差 {}", acc.abs());
8095                }
8096                assert_eq!(rs.len(), 20);
8097            }
8098            // An error is acceptable (degree 20 is a deliberately hard case), but it **must not
8099            // return NaN**
8100            Err(e) => {
8101                assert!(
8102                    matches!(e, Error::RootFindingFailed { .. }),
8103                    "a failed run must be catalogued: {e:?}"
8104                );
8105                let text = e.render(i18n::Locale::En);
8106                assert!(text.contains("root finding failed"), "{text}")
8107            }
8108        }
8109
8110        // ② A real small root must not be wiped to 0: the roots of x² − 1e-26 are ±1e-13
8111        let small = numeric_roots(&[-1e-26, 0.0, 1.0]).unwrap();
8112        assert_eq!(small.len(), 2);
8113        for z in &small {
8114            // The criterion is "not wiped to 0 and of the right magnitude", without demanding the
8115            // last bit (at this scale the relative error
8116            // is of order 1e-4 anyway)
8117            assert!(
8118                (z.re.abs() - 1e-13).abs() / 1e-13 < 1e-2,
8119                "小根被抹平了:{z:?}(应为 ±1e-13 量级)"
8120            );
8121        }
8122
8123        // ③ Healthy polynomials must not be judged ill-conditioned: ∏(x−k), k=1..8
8124        let mut c8 = vec![1.0f64];
8125        for k in 1..=8 {
8126            let mut next = vec![0.0; c8.len() + 1];
8127            for (i, c) in c8.iter().enumerate() {
8128                next[i] += -(k as f64) * c;
8129                next[i + 1] += c;
8130            }
8131            c8 = next;
8132        }
8133        let r8 = numeric_roots(&c8).expect("∏(x−k), k=1..8 是健康多项式,不该报病态");
8134        let mut re8: Vec<f64> = r8.iter().map(|z| z.re).collect();
8135        re8.sort_by(|a, b| a.partial_cmp(b).unwrap());
8136        for (k, got) in re8.iter().enumerate() {
8137            assert!((got - (k as f64 + 1.0)).abs() < 1e-6, "第 {k} 个根 {got}");
8138        }
8139
8140        // ④ Small purely imaginary roots: x² + 1e-26 → ±1e-13j (the imaginary part is a real value
8141        // and must not be cleared as residue)
8142        let imag = numeric_roots(&[1e-26, 0.0, 1.0]).unwrap();
8143        for z in &imag {
8144            assert!(
8145                (z.im.abs() - 1e-13).abs() / 1e-13 < 1e-2,
8146                "纯虚小根被清掉了:{z:?}"
8147            );
8148        }
8149    }
8150
8151    #[test]
8152    fn numeric_roots_handles_tiny_roots_exactly_or_refuses() {
8153        // S0 from the third review round: the denominator of the residual acceptance was wrong (it
8154        // stopped at |a_n|), and together with the
8155        // absolute lower bound on the initial radius (geo > 1e-8), small-root polynomials were
8156        // **silently returned with wrong roots**
8157        // — `x²−1e-100` once returned 4.03e-25 (off by 4e25×) without reporting an error.
8158        for (eps, want) in [
8159            (1e-26f64, 1e-13f64),
8160            (1e-45, 3.1622776601683793e-23),
8161            (1e-50, 1e-25),
8162            (1e-60, 1e-30),
8163            (1e-100, 1e-50),
8164            (1e-300, 1e-150),
8165        ] {
8166            let r = match numeric_roots(&[-eps, 0.0, 1.0]) {
8167                Ok(r) => r,
8168                Err(_) => continue, // an error is acceptable; silently giving a wrong value is not
8169            };
8170            for z in &r {
8171                let rel = (z.re.abs() - want).abs() / want;
8172                assert!(rel < 1e-6, "eps={eps:e}:根 {z:?} 与真值 {want:e} 不符");
8173            }
8174        }
8175        // Larger genuine roots must be right as well
8176        let r = numeric_roots(&[-1e-12, 0.0, 1.0]).unwrap();
8177        for z in &r {
8178            assert!((z.re.abs() - 1e-6).abs() / 1e-6 < 1e-9, "{z:?}");
8179        }
8180        // A linear equation overflow must error (it once returned Ok(-inf))
8181        let err = numeric_roots(&[1e300, 1e-300]).unwrap_err();
8182        assert_eq!(err.code(), "non-finite-value", "{err}");
8183        let en = err.render(i18n::Locale::En);
8184        assert!(en.contains("overflows") && en.contains("rescale"), "{en}");
8185    }
8186
8187    #[test]
8188    fn poly_coeffs_extracts_low_to_high_and_round_trips_with_roots() {
8189        let mut env = HashMap::new();
8190        env.insert("a".to_string(), 2.0);
8191        env.insert("b".to_string(), 3.0);
8192        env.insert("c".to_string(), 1.0);
8193        // a·x² − b·x + c = 2x² − 3x + 1 → coefficients [1, −3, 2] (low degree to high degree)
8194        let poly = add(
8195            sub(
8196                mul(var("a"), pow(var("x"), num(2.0))),
8197                mul(var("b"), var("x")),
8198            ),
8199            var("c"),
8200        );
8201        let Expr::Mat(rows) = poly_coeffs_vec(&poly, "x").unwrap() else {
8202            panic!("系数应是 1×k 行向量")
8203        };
8204        assert_eq!(rows.len(), 1, "行向量");
8205        let got: Vec<f64> = rows[0].iter().map(|e| eval(e, &env).unwrap()).collect();
8206        assert_eq!(got, vec![1.0, -3.0, 2.0], "低次到高次");
8207
8208        // Complementary to roots: coefficients → find roots → substitute back to get zero
8209        let r = solve_poly(&poly, "x").unwrap();
8210        let Expr::Mat(rr) = &r else { panic!() };
8211        let mut roots: Vec<f64> = rr.iter().map(|row| eval(&row[0], &env).unwrap()).collect();
8212        roots.sort_by(|a, b| a.partial_cmp(b).unwrap());
8213        assert!((roots[0] - 0.5).abs() < 1e-12, "{roots:?}");
8214        assert!((roots[1] - 1.0).abs() < 1e-12, "{roots:?}");
8215
8216        // High-degree zero coefficients must be peeled off: x³ − x³ − 2x + 1 → [1, −2]
8217        let cancel = add(
8218            sub(
8219                sub(pow(var("x"), num(3.0)), pow(var("x"), num(3.0))),
8220                mul(num(2.0), var("x")),
8221            ),
8222            num(1.0),
8223        );
8224        let Expr::Mat(rows) = poly_coeffs_vec(&cancel, "x").unwrap() else {
8225            panic!()
8226        };
8227        let got: Vec<f64> = rows[0]
8228            .iter()
8229            .map(|e| eval(e, &HashMap::new()).unwrap())
8230            .collect();
8231        assert_eq!(got, vec![1.0, -2.0], "高次抵消后是 1 次");
8232
8233        // Non-polynomials / the zero polynomial must be rejected
8234        for bad in [
8235            Expr::Call("sin".into(), vec![var("x")]),
8236            div(num(1.0), var("x")),
8237        ] {
8238            let err = poly_coeffs_vec(&bad, "x").unwrap_err();
8239            assert_eq!(err.code(), "not-polynomial", "{err}");
8240            assert!(
8241                err.render(i18n::Locale::En)
8242                    .contains("univariate polynomial"),
8243                "{err}"
8244            );
8245        }
8246        assert!(poly_coeffs_vec(&mul(num(0.0), var("x")), "x").is_err());
8247    }
8248
8249    #[test]
8250    fn numeric_roots_keeps_imaginary_parts_of_small_complex_roots() {
8251        // S0 from the fourth review round: zeroing the imaginary part used an **absolute** threshold
8252        // `1e-12·(1+|re|)`,
8253        // and for complex roots with modulus below 1e-12 the imaginary part is all the information
8254        // the root has, so it was wiped entirely:
8255        // `x³−1e-60` once returned three real roots (the latter two with relative error 0.87) without
8256        // reporting an error.
8257        let r = numeric_roots(&[-1e-60, 0.0, 0.0, 1.0]).expect("三次应可解");
8258        assert_eq!(r.len(), 3);
8259        let real_count = r.iter().filter(|c| c.im == 0.0).count();
8260        assert_eq!(real_count, 1, "x³−1e-60 只有一个实根:{r:?}");
8261        // All three roots must satisfy z³ = 1e-60 (relative criterion)
8262        for z in &r {
8263            let z3 = z.mul(*z).mul(*z);
8264            let rel = z3.sub(C::new(1e-60, 0.0)).abs() / 1e-60;
8265            assert!(rel < 1e-6, "根 {z:?} 代回相对残差 {rel}");
8266        }
8267        // Likewise for degree five: x⁵−1e-100 has 4 complex roots
8268        let r5 = numeric_roots(&[-1e-100, 0.0, 0.0, 0.0, 0.0, 1.0]).expect("五次应可解");
8269        let re5 = r5.iter().filter(|c| c.im == 0.0).count();
8270        assert_eq!(re5, 1, "x⁵−1e-100 只有一个实根:{r5:?}");
8271        for z in &r5 {
8272            let mut acc = *z;
8273            for _ in 0..4 {
8274                acc = acc.mul(*z);
8275            }
8276            let rel = acc.sub(C::new(1e-100, 0.0)).abs() / 1e-100;
8277            assert!(rel < 1e-5, "根 {z:?} 代回相对残差 {rel}");
8278        }
8279        // Ordinary real roots must still be cleaned completely (switching to a relative criterion
8280        // must not leave 1e-16 noise behind)
8281        let r2 = numeric_roots(&[-6.0, 5.0, 1.0]).unwrap(); // x²+5x−6 → 1 与 −6
8282        assert!(r2.iter().all(|c| c.im == 0.0), "{r2:?}");
8283    }
8284
8285    #[test]
8286    fn roots_rejects_high_degree_and_non_polynomial() {
8287        // Degree 3: rejected explicitly and the degree reported (no Cardano approximation)
8288        let cubic = add(pow(var("x"), num(3.0)), num(1.0));
8289        let err = solve_poly(&cubic, "x").unwrap_err();
8290        assert_eq!(err.code(), "invalid-input", "{err}");
8291        let en = err.render(i18n::Locale::En);
8292        assert!(en.contains("degree 3") && en.contains("degree 1–2"), "{en}");
8293        // Non-polynomial: x inside a function argument / in the denominator / at a non-integer
8294        // power
8295        for bad in [
8296            Expr::Call("sin".into(), vec![var("x")]),
8297            div(num(1.0), var("x")),
8298            pow(var("x"), num(-1.0)),
8299        ] {
8300            let err = solve_poly(&bad, "x").unwrap_err();
8301            assert_eq!(err.code(), "not-polynomial", "{err}");
8302            assert!(
8303                err.render(i18n::Locale::En)
8304                    .contains("univariate polynomial"),
8305                "{err}"
8306            );
8307        }
8308        // The equation has no x
8309        let err = solve_poly(&add(var("a"), var("b")), "x").unwrap_err();
8310        assert_eq!(err.code(), "nonlinear-equation", "{err}");
8311        assert!(
8312            err.render(i18n::Locale::En).contains("does not contain"),
8313            "{err}"
8314        );
8315    }
8316
8317    #[test]
8318    fn solve_system_rejects_nonuniq_and_nonlinear() {
8319        let (x, y) = (var("x"), var("y"));
8320        // Underdetermined: 1 equation, 2 unknowns
8321        let err =
8322            solve_system(&[sub(x.clone(), y.clone())], &["x".into(), "y".into()]).unwrap_err();
8323        let text = err.to_string();
8324        assert_eq!(err.code(), "underdetermined", "{text}");
8325        // Contradiction: x − 1 and x − 2 holding at the same time
8326        let err = solve_system(
8327            &[sub(x.clone(), num(1.0)), sub(x.clone(), num(2.0))],
8328            &["x".into()],
8329        )
8330        .unwrap_err();
8331        assert_eq!(err.code(), "inconsistent", "{err}");
8332        // Non-linear: x·y appears on both sides of a multiplication — wrapped with the equation
8333        // position (equation 1), inner variant preserved
8334        let err = solve_system(
8335            &[sub(mul(x.clone(), y.clone()), num(1.0))],
8336            &["x".into(), "y".into()],
8337        )
8338        .unwrap_err();
8339        assert_eq!(err.code(), "in-equation", "{err}");
8340        assert!(
8341            err.render(i18n::Locale::En).contains("in equation 1:"),
8342            "{err}"
8343        );
8344        let Error::InEquation { error: inner, .. } = &err else {
8345            panic!("{err:?}")
8346        };
8347        assert_eq!(inner.code(), "nonlinear-equation", "{err:?}");
8348        // Duplicate unknown names
8349        let err = solve_system(&[sub(x.clone(), num(1.0))], &["x".into(), "x".into()]).unwrap_err();
8350        assert_eq!(err.code(), "invalid-input", "{err}");
8351        assert!(err.render(i18n::Locale::En).contains("twice"), "{err}");
8352        // Empty list
8353        let err = solve_system(&[sub(x.clone(), num(1.0))], &[]).unwrap_err();
8354        assert_eq!(err.code(), "invalid-input", "{err}");
8355        assert!(
8356            err.render(i18n::Locale::En).contains("at least one"),
8357            "{err}"
8358        );
8359        // A numerically redundant equation (a third one of the form 2·eq1): after elimination to
8360        // zero it should still give a unique solution
8361        let eq1 = sub(add(x.clone(), y.clone()), num(3.0));
8362        let eq2 = sub(x.clone(), y.clone());
8363        let eq3 = sub(mul(num(2.0), add(x.clone(), y.clone())), num(6.0));
8364        let sol = solve_system(&[eq1, eq2, eq3], &["x".into(), "y".into()]).unwrap();
8365        let Expr::Mat(rows) = &sol else {
8366            panic!("解必须是矩阵");
8367        };
8368        let mut env = HashMap::new();
8369        env.insert("x".to_string(), eval(&rows[0][0], &env).unwrap());
8370        env.insert("y".to_string(), eval(&rows[1][0], &env).unwrap());
8371        // x + y = 3, x − y = 0 → (1.5, 1.5)
8372        assert!((env["x"] - 1.5).abs() < 1e-12 && (env["y"] - 1.5).abs() < 1e-12);
8373    }
8374
8375    #[test]
8376    fn solve_rejects_hidden_unknown_in_exponent() {
8377        // Review S0-1: the x in `2^x` used to be taken as a constant term — as long as that unknown
8378        // also appeared as a
8379        // linear term in the same equation, the whole term ended up in the "solution":
8380        // solve([x + 2^x - 3], [x]) once gave 3−2^x,
8381        // which once generated became a legal function "taking the solved-for quantity as an input"
8382        // that silently returned wrong values.
8383        let (x, y) = (var("x"), var("y"));
8384        // The system lane
8385        let err = solve_system(
8386            &[sub(add(x.clone(), pow(num(2.0), x.clone())), num(3.0))],
8387            &["x".into()],
8388        )
8389        .unwrap_err();
8390        match &err {
8391            // The multi-variable lane wraps the per-equation failure with its position; the
8392            // inner variant stays catalogued, so only the reason is pinned here.
8393            Error::InEquation {
8394                index,
8395                error: inner,
8396            } => {
8397                assert_eq!(*index, 1, "{err:?}");
8398                let Error::NonlinearEquation { why, .. } = &**inner else {
8399                    panic!("the inner variant must survive the wrap: {err:?}")
8400                };
8401                assert!(why.contains("exponent"), "{why}");
8402            }
8403            other => panic!("{other:?}"),
8404        }
8405        // The single-variable lane has the same disease (a pre-existing defect, fixed in the same
8406        // place)
8407        let err = solve_linear(
8408            &sub(add(x.clone(), pow(num(2.0), x.clone())), num(3.0)),
8409            "x",
8410        )
8411        .unwrap_err();
8412        assert!(
8413            matches!(
8414                &err,
8415                Error::NonlinearEquation { why, .. } if why.contains("exponent")
8416            ),
8417            "{err}"
8418        );
8419        // But `2^y` contains no x: solving for x is itself legal (x = 2^y is the true solution)
8420        let ok = solve_system(&[sub(x.clone(), pow(num(2.0), y.clone()))], &["x".into()])
8421            .expect("2^y 不含 x,应可解");
8422        let Expr::Mat(m) = &ok else {
8423            panic!("应是列向量")
8424        };
8425        let mut env = HashMap::new();
8426        env.insert("y".to_string(), 3.0);
8427        assert!((eval(&m[0][0], &env).unwrap() - 8.0).abs() < 1e-12);
8428    }
8429
8430    #[test]
8431    fn solve_system_detects_structurally_zero_coefficients() {
8432        // Review S0-2: `simplify` does not combine like terms, so `k2 − k2` cannot be folded, and
8433        // rows with zero coefficients were taken as pivots → 0/0 (an error at the evaluation layer /
8434        // NaN at the emission layer) or an underdetermined system taken as unique.
8435        let (x, y) = (var("x"), var("y"));
8436        let k2 = var("k2");
8437        // A: the redundant row `(k2−k2)·y + x − 1` is identical to `x − 1` → only x is pinned, y is
8438        // free → underdetermined
8439        let err = solve_system(
8440            &[
8441                sub(x.clone(), num(1.0)),
8442                sub(
8443                    add(mul(sub(k2.clone(), k2.clone()), y.clone()), x.clone()),
8444                    num(1.0),
8445                ),
8446            ],
8447            &["x".into(), "y".into()],
8448        )
8449        .unwrap_err();
8450        let text = err.to_string();
8451        assert_eq!(err.code(), "underdetermined", "{text}");
8452        // B: the second = the first × k → equally underdetermined (not 0/0)
8453        let k = var("k");
8454        let err = solve_system(
8455            &[
8456                sub(add(x.clone(), y.clone()), num(1.0)),
8457                sub(mul(k.clone(), add(x.clone(), y.clone())), k.clone()),
8458            ],
8459            &["x".into(), "y".into()],
8460        )
8461        .unwrap_err();
8462        let text = err.to_string();
8463        assert_eq!(err.code(), "underdetermined", "{text}");
8464        // The structural zero test itself: several forms of combining like terms
8465        assert!(is_structurally_zero(&sub(k2.clone(), k2.clone())), "k−k");
8466        assert!(
8467            is_structurally_zero(&sub(mul(k.clone(), x.clone()), mul(x.clone(), k.clone()))),
8468            "k·x − x·k"
8469        );
8470        assert!(
8471            is_structurally_zero(&sub(sub(mul(num(2.0), x.clone()), x.clone()), x.clone())),
8472            "2x − x − x"
8473        );
8474        assert!(
8475            is_structurally_zero(&sub(
8476                mul(x.clone(), pow(x.clone(), num(2.0))),
8477                pow(x.clone(), num(3.0))
8478            )),
8479            "x·x² − x³"
8480        );
8481        // A power differing by one degree must **never** be judged zero: `a²−a = a(a−1)` is
8482        // genuinely non-zero.
8483        // (The power branch of the first `term_factors` pushed only n−1 factors, so both of these
8484        // were judged identically zero,
8485        //   and the solver then silently gave solutions that do not satisfy the original equations —
8486        // an S0 caught by the independent review.)
8487        for (bad, why) in [
8488            (sub(pow(k2.clone(), num(2.0)), k2.clone()), "a²−a"),
8489            (
8490                sub(
8491                    pow(mul(num(2.0), k2.clone()), num(2.0)),
8492                    mul(num(2.0), k2.clone()),
8493                ),
8494                "(2a)²−2a",
8495            ),
8496            (
8497                sub(
8498                    pow(mul(x.clone(), k2.clone()), num(2.0)),
8499                    mul(x.clone(), k2.clone()),
8500                ),
8501                "(xy)²−xy",
8502            ),
8503            (pow(k2.clone(), num(3.0)), "a³(单项非零)"),
8504        ] {
8505            assert!(!is_structurally_zero(&bad), "{why} 被误判为恒零");
8506        }
8507        // Equal powers really are zero (a positive case, so that we do not switch the whole power
8508        // path off)
8509        assert!(
8510            is_structurally_zero(&sub(pow(k2.clone(), num(2.0)), mul(k2.clone(), k2.clone()))),
8511            "a² − a·a"
8512        );
8513        assert!(
8514            is_structurally_zero(&sub(
8515                pow(mul(num(2.0), k2.clone()), num(2.0)),
8516                mul(num(4.0), pow(k2.clone(), num(2.0)))
8517            )),
8518            "(2a)² − 4a²"
8519        );
8520        // Non-zero must not be misjudged as zero
8521        assert!(!is_structurally_zero(&sub(k2.clone(), var("k3"))));
8522        assert!(!is_structurally_zero(&sub(x.clone(), num(1.0))));
8523        // Identical subexpressions can be proven zero (coefficients sharing a key add up)
8524        assert!(is_structurally_zero(&sub(
8525            Expr::Call("exp".into(), vec![x.clone()]),
8526            Expr::Call("exp".into(), vec![x.clone()])
8527        )));
8528        // Identical subexpressions (including a symbolic divisor) are of course zero: the whole term
8529        // is one atom, and keys add up
8530        let kv = var("k");
8531        assert!(is_structurally_zero(&sub(
8532            div(x.clone(), kv.clone()),
8533            div(x.clone(), kv.clone())
8534        )));
8535        // But an identity that needs **algebraic expansion** to prove cannot be proven → return
8536        // false conservatively (no guessing)
8537        let (a, b) = (var("a"), var("b"));
8538        let expandable = sub(
8539            pow(add(a.clone(), b.clone()), num(2.0)),
8540            add(
8541                add(
8542                    pow(a.clone(), num(2.0)),
8543                    mul(num(2.0), mul(a.clone(), b.clone())),
8544                ),
8545                pow(b.clone(), num(2.0)),
8546            ),
8547        );
8548        assert!(
8549            !is_structurally_zero(&expandable),
8550            "(a+b)² − (a²+2ab+b²) 需要展开,证不出就该返回 false"
8551        );
8552    }
8553
8554    #[test]
8555    fn solve_system_allows_equations_with_different_dimensions() {
8556        // Review S1-1: going through the generic `Mat` check, `dim_check` would require **all
8557        // equations to share a dimension**,
8558        // wrongly rejecting a completely legal system such as "force balance (N) + geometric
8559        // constraint (m)".
8560        let dims = dims_of(&[
8561            Decl {
8562                name: "k".into(),
8563                quantity: "stiffness".into(),
8564                unit: Some("N/m".into()),
8565            },
8566            Decl {
8567                name: "F".into(),
8568                quantity: "load".into(),
8569                unit: Some("N".into()),
8570            },
8571            Decl {
8572                name: "x".into(),
8573                quantity: "d1".into(),
8574                unit: Some("m".into()),
8575            },
8576            Decl {
8577                name: "L".into(),
8578                quantity: "len".into(),
8579                unit: Some("m".into()),
8580            },
8581            Decl {
8582                name: "y".into(),
8583                quantity: "d2".into(),
8584                unit: Some("m".into()),
8585            },
8586        ])
8587        .unwrap();
8588        // k·(x − y) − F = 0 (N) and x − L = 0 (m): two legal equations of different dimensions
8589        let sys = Expr::Call(
8590            "solve".into(),
8591            vec![
8592                Expr::Mat(vec![
8593                    vec![sub(mul(var("k"), sub(var("x"), var("y"))), var("F"))],
8594                    vec![sub(var("x"), var("L"))],
8595                ]),
8596                Expr::Mat(vec![vec![var("x")], vec![var("y")]]),
8597            ],
8598        );
8599        let d = dim_check(&sys, &dims).expect("量纲不同的方程应被接受");
8600        assert_eq!(d, parse_unit("m").unwrap(), "解的每个分量都是位移");
8601        // But a **single equation** that is not homogeneous must still be rejected
8602        let bad = Expr::Call(
8603            "solve".into(),
8604            vec![
8605                Expr::Mat(vec![
8606                    vec![sub(var("x"), var("F"))], // m vs N
8607                ]),
8608                Expr::Mat(vec![vec![var("x")]]),
8609            ],
8610        );
8611        let err = dim_check(&bad, &dims).unwrap_err();
8612        assert_eq!(err.code(), "operator-dimension-mismatch", "{err}");
8613        assert!(err.render(i18n::Locale::En).contains("`-`"), "{err}");
8614    }
8615
8616    #[test]
8617    fn matrix_and_scalar_cannot_be_added() {
8618        // Review counterexample: `3 + roots(...)` / `3 + poly_coeffs(...)` were once emitted as
8619        // `3.0 + vec![vec![…]]` (E0277), while `--diagnose` reported it clean.
8620        let mat = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
8621        for bad in [
8622            add(num(3.0), mat.clone()),
8623            sub(mat.clone(), num(3.0)),
8624            add(mat.clone(), var("x")),
8625        ] {
8626            let err = shape_check(&bad).unwrap_err();
8627            // Stable code, not a sentence: the wording is per-locale.
8628            assert_eq!(err.code(), "matrix-scalar-mix", "{err}");
8629        }
8630        // Zero-element exception: `M + 0` is the additive identity and must not be judged wrong
8631        assert!(shape_check(&add(mat.clone(), num(0.0))).is_ok());
8632        assert!(shape_check(&sub(mat.clone(), num(0.0))).is_ok());
8633        // Matrix + matrix (same shape) is still legal
8634        assert!(shape_check(&add(mat.clone(), mat.clone())).is_ok());
8635        // Inconsistent shapes must still be reported
8636        let other = Expr::Mat(vec![vec![num(1.0), num(2.0), num(3.0)]]);
8637        let err = shape_check(&add(mat, other)).unwrap_err();
8638        assert_eq!(err.code(), "shape-mismatch", "{err}");
8639        // A matrix product taking part in an addition: `is_matrix_value` recognizes it, so it must
8640        // not be misjudged as a scalar
8641        let prod = mul(
8642            Expr::Mat(vec![vec![num(1.0), num(0.0)], vec![num(0.0), num(1.0)]]),
8643            Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]),
8644        );
8645        assert!(
8646            shape_check(&add(prod.clone(), num(0.0))).is_ok(),
8647            "矩阵乘积 + 0 应合法"
8648        );
8649        let err = shape_check(&add(prod, num(1.0))).unwrap_err();
8650        assert_eq!(err.code(), "matrix-scalar-mix", "{err}");
8651    }
8652
8653    #[test]
8654    fn matrix_shapes_are_checked_even_when_only_flatten_knows_them() {
8655        // Review counterexample: the shapes of `roots(...) + roots(...)` and
8656        // `poly_coeffs(...) * roots(...)`
8657        // are known only to `flatten_matrix_value` (`shape_of` returns None for Call),
8658        // so the whole check was skipped → emitting `vec![…] + vec![…]` / `vec![…] * vec![…]` (which
8659        // does not compile),
8660        // while `--diagnose` reported it clean.
8661        let x = var("x");
8662        // 1×1 + 2×1: inconsistent shapes, must be rejected
8663        let r1 = Expr::Call("roots".into(), vec![sub(x.clone(), num(1.0)), x.clone()]);
8664        let r2 = Expr::Call(
8665            "roots".into(),
8666            vec![sub(pow(x.clone(), num(2.0)), num(1.0)), x.clone()],
8667        );
8668        let err = shape_check(&add(r1.clone(), r2.clone())).unwrap_err();
8669        assert_eq!(err.code(), "shape-mismatch", "{err}");
8670        // 1×(n+1) coefficients × n×1 roots: the same polynomial never matches, so it must be
8671        // rejected (no vec*vec emission)
8672        let coeffs = Expr::Call(
8673            "poly_coeffs".into(),
8674            vec![add(pow(x.clone(), num(2.0)), x.clone()), x.clone()],
8675        );
8676        // Matrix×matrix with mismatched inner dims: the sentence names both factors, so assert
8677        // the payload rather than merely "something failed".
8678        let err = shape_check(&mul(coeffs.clone(), r2.clone())).unwrap_err();
8679        match &err {
8680            Error::ShapeMismatch(why) => assert!(
8681                why.contains("cannot multiply") && why.contains("1, 3"),
8682                "the sentence must name both factors: {why}"
8683            ),
8684            other => panic!("{other:?}"),
8685        }
8686        // Legal shapes still pass: 2×2 times 2×1
8687        let m = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
8688        let col = Expr::Mat(vec![vec![num(1.0)], vec![num(2.0)]]);
8689        assert!(shape_check(&mul(m.clone(), col.clone())).is_ok());
8690        // 2×2 + 2×2 passes
8691        assert!(shape_check(&add(m.clone(), m.clone())).is_ok());
8692        // Adding 2×2 and 2×1 must be rejected
8693        let err = shape_check(&add(m, col)).unwrap_err();
8694        assert_eq!(err.code(), "shape-mismatch", "{err}");
8695    }
8696
8697    #[test]
8698    fn solve_system_rejects_matrix_coefficients() {
8699        // Review S1-2: the system lane used to let matrix coefficients through, emitting
8700        // `f64 / Vec<Vec<f64>>`
8701        let mat = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
8702        let x = var("x");
8703        let err =
8704            solve_system(&[sub(mul(mat.clone(), x.clone()), var("b"))], &["x".into()]).unwrap_err();
8705        assert_eq!(err.code(), "in-equation", "{err}");
8706        let Error::InEquation {
8707            index,
8708            error: inner,
8709        } = &err
8710        else {
8711            panic!("{err:?}")
8712        };
8713        assert_eq!(*index, 1, "{err:?}");
8714        assert_eq!(inner.code(), "matrix-coefficient", "{err:?}");
8715        // A matrix-valued constant term is rejected likewise — the wrapper names the equation,
8716        // so the constant coefficient no longer has to name it itself
8717        let err = solve_system(&[sub(x.clone(), mat)], &["x".into()]).unwrap_err();
8718        assert_eq!(err.code(), "in-equation", "{err}");
8719        let Error::InEquation { error: inner, .. } = &err else {
8720            panic!("{err:?}")
8721        };
8722        let Error::MatrixCoefficient(name) = &**inner else {
8723            panic!("{err:?}")
8724        };
8725        assert_eq!(name, "<constant>", "{err:?}");
8726    }
8727
8728    #[test]
8729    fn expand_deep_reaches_nested_operators() {
8730        // Review S1-3: `expand_call` only looks at the root node, so in `2 * solve(...)` the
8731        // solved-for unknown
8732        // stays in the parameter list (generating a function "asking the caller to pass the
8733        // solved-for quantity").
8734        let x = var("x");
8735        let a = var("a");
8736        let c = var("c");
8737        let nested = mul(
8738            num(2.0),
8739            Expr::Call(
8740                "solve".into(),
8741                vec![sub(mul(a.clone(), x.clone()), c.clone()), x.clone()],
8742            ),
8743        );
8744        // The root is a Mul, so top-level expand_call leaves it alone — exactly the gap the review
8745        // pointed out
8746        assert!(expand_call(&nested).is_none(), "顶层展开不该命中嵌套算子");
8747        let deep = expand_deep(&nested);
8748        assert!(
8749            !vars_of(&deep).contains(&"x".to_string()),
8750            "深度展开后不该再有被求解的 x:{deep:?}"
8751        );
8752        // det nested inside an addition can be expanded too
8753        let det_nested = add(
8754            Expr::Call(
8755                "det".into(),
8756                vec![Expr::Mat(vec![
8757                    vec![num(1.0), num(2.0)],
8758                    vec![num(3.0), num(4.0)],
8759                ])],
8760            ),
8761            num(1.0),
8762        );
8763        let d = simplify(&expand_deep(&det_nested));
8764        assert!(matches!(d, Expr::Num(_)), "det(A)+1 应折成常数,得到 {d:?}");
8765        assert!((eval(&d, &HashMap::new()).unwrap() - (-1.0)).abs() < 1e-12);
8766    }
8767
8768    #[test]
8769    fn solve_system_routes_through_expand_and_flatten() {
8770        let (x, y) = (var("x"), var("y"));
8771        let sys = Expr::Call(
8772            "solve".into(),
8773            vec![
8774                Expr::Mat(vec![
8775                    vec![sub(x.clone(), num(4.0))],
8776                    vec![sub(y.clone(), num(1.0))],
8777                ]),
8778                Expr::Mat(vec![vec![x.clone(), y.clone()]]),
8779            ],
8780        );
8781        // expand_call: the system form → a column vector; the single-variable form → a scalar
8782        let expanded = expand_call(&sys).expect("方程组应可展开");
8783        let Expr::Mat(rows) = &expanded else {
8784            panic!("展开结果应是矩阵,得到 {expanded:?}");
8785        };
8786        assert_eq!(rows.len(), 2);
8787        assert!((eval(&rows[0][0], &HashMap::new()).unwrap() - 4.0).abs() < 1e-12);
8788        // Matrix-value determination: the system is a true matrix; the single-variable solve is
8789        // not
8790        assert!(is_matrix_value(&sys), "方程组 solve 应是矩阵值");
8791        let single = Expr::Call(
8792            "solve".into(),
8793            vec![sub(mul(var("a"), var("x")), num(6.0)), var("x")],
8794        );
8795        assert!(!is_matrix_value(&single), "单变量 solve 是标量值");
8796        // A single-variable solve with matrix coefficients must be rejected (the scalar lane would
8797        // generate a vec! division)
8798        let mat_coeff = Expr::Call(
8799            "solve".into(),
8800            vec![
8801                sub(
8802                    mul(
8803                        Expr::Mat(vec![vec![num(1.0), num(0.0)], vec![num(0.0), num(1.0)]]),
8804                        x.clone(),
8805                    ),
8806                    y.clone(),
8807                ),
8808                x,
8809            ],
8810        );
8811        let Expr::Call(_, mat_args) = &mat_coeff else {
8812            panic!("构造的应是 Call");
8813        };
8814        let err = solve_linear(&mat_args[0], "x").unwrap_err();
8815        assert_eq!(err.code(), "matrix-coefficient", "{err}");
8816    }
8817
8818    #[test]
8819    fn typo_suggestions_and_multiarg_mathml() {
8820        // A mistyped function name → suggest the closest name (edit distance ≤ 2)
8821        assert_eq!(closest_func("sqrtt"), Some("sqrt"));
8822        // Short names are naturally confusable (`mn` is close to both ln and min): the assertions
8823        // here use **long names**,
8824        // and preserve the semantics "do not guess when it really is ambiguous"
8825        assert_eq!(closest_func("clampx"), Some("clamp"));
8826        assert_eq!(closest_func("adjiont"), Some("adjoint"));
8827        assert_eq!(closest_func("dett"), Some("det"));
8828        // Completely unrelated names get no suggestion
8829        assert_eq!(closest_func("foobar"), None);
8830        let e = Expr::Call("sqrtt".into(), vec![var("x")]);
8831        let err = check_calls(&e).unwrap_err();
8832        let text = err.to_string();
8833        assert!(text.contains("sqrt"), "{text}");
8834
8835        // Multi-argument MathML must be comma-separated (otherwise the preview panel renders
8836        // `min(a b)`).
8837        let m = Expr::Call("min".into(), vec![var("a"), var("b")]);
8838        let xml = to_mathml(&m);
8839        assert!(xml.contains("<mo>,</mo>"), "{xml}");
8840        assert!(xml.contains("<mi>min</mi>"), "{xml}");
8841    }
8842
8843    #[test]
8844    fn horner_matches_power_form_and_only_touches_explicit_polynomials() {
8845        // Explicit polynomial: a·x³ + b·x → Horner
8846        // (the source is `a*x^3 + b*x`; every base is x itself)
8847        let e = add(
8848            mul(var("a"), pow(var("x"), num(3.0))),
8849            mul(var("b"), var("x")),
8850        );
8851        let h = horner_in(&e, "x").expect("显式多项式应可 Horner");
8852        assert!(!matches!(h, Expr::Num(_)));
8853        // Pointwise equal values (Horner only changes the association order, not the math)
8854        let case = [
8855            (0.0f64, 2.0f64, 3.0f64),
8856            (-1.5, 0.3, -2.0),
8857            (7.25, 1.0, 0.5),
8858        ];
8859        for (x, a, b) in case {
8860            let mut env = HashMap::new();
8861            env.insert("x".to_string(), x);
8862            env.insert("a".to_string(), a);
8863            env.insert("b".to_string(), b);
8864            let want = eval(&e, &env).unwrap();
8865            let got = eval(&h, &env).unwrap();
8866            assert!(
8867                (got - want).abs() <= 1e-12 * (1.0 + want.abs()),
8868                "x={x} Horner {got} vs 幂次 {want}"
8869            );
8870        }
8871        // Fewer multiplications: no third power should remain in the Horner form
8872        assert!(!contains_pow_of(&h, "x", 3.0), "Horner 后不该有 x^3:{h:?}");
8873
8874        // The compact form `(u-1)^3` is **not** expanded (expansion is harder to read and no faster)
8875        let compact = pow(sub(var("u"), num(1.0)), num(3.0));
8876        assert!(horner_in(&compact, "u").is_none());
8877
8878        // Below degree 1 it is pointless
8879        let lin = add(mul(var("a"), var("x")), var("b"));
8880        assert!(horner_in(&lin, "x").is_none());
8881    }
8882
8883    #[test]
8884    fn libm_lane_uses_libm_calls_and_rejects_alloc() {
8885        // x^0.5 → libm::sqrt (not f64::sqrt — it is not in core)
8886        let e = pow(var("x"), num(0.5));
8887        let w = emit_block_libm(&e);
8888        assert!(w.contains("libm::sqrt"), "{w}");
8889        assert!(!w.contains(".sqrt()"), "{w}");
8890        // x^2.5 → libm::pow (there is no powf)
8891        let e = pow(var("x"), num(2.5));
8892        let w = emit_block_libm(&e);
8893        assert!(w.contains("libm::pow"), "{w}");
8894        // Integer powers also go through libm::pow (powi is from std)
8895        let e = pow(var("x"), num(3.0));
8896        let w = emit_block_libm(&e);
8897        assert!(w.contains("libm::pow"), "{w}");
8898        // Transcendental functions → libm::exp
8899        let e = Expr::Call("exp".into(), vec![var("x")]);
8900        let w = emit_block_libm(&e);
8901        assert!(w.contains("libm::exp"), "{w}");
8902        // abs → libm::fabs
8903        let e = Expr::Call("abs".into(), vec![var("x")]);
8904        let w = emit_block_libm(&e);
8905        assert!(w.contains("libm::fabs"), "{w}");
8906        // Matrix-valued formulas are rejected as a whole block (vec! needs alloc)
8907        let m = Expr::Mat(vec![vec![num(1.0), num(2.0)]]);
8908        let w = emit_block_libm(&m);
8909        assert!(w.contains("no_std"), "{w}");
8910        // clamp **works** in no_std: min/max are core methods (not std-only)
8911        let e = Expr::Call("clamp".into(), vec![var("x"), num(0.0), num(1.0)]);
8912        let w = emit_block_libm(&e);
8913        assert!(w.contains(".max(0.0).min(1.0)"), "{w}");
8914        // Genuinely outside the libm whitelist: arg (complex-only, no counterpart in core)
8915        let e = Expr::Call("arg".into(), vec![var("x")]);
8916        let w = emit_block_libm(&e);
8917        assert!(w.contains("compile_error!"), "{w}");
8918    }
8919
8920    #[test]
8921    fn negative_base_fractional_power_is_not_folded_to_nan() {
8922        // Regression: fold_const used to fold (-8)^(1/3) to NaN while the value layer gives a
8923        // complex number —
8924        // two lanes, two answers. Now it is not folded, leaving it to the evaluation layer.
8925        let e = pow(num(-8.0), div(num(1.0), num(3.0)));
8926        let folded = simplify(&e);
8927        assert!(
8928            !matches!(folded, Expr::Num(v) if v.is_nan()),
8929            "不该折叠成 NaN:{folded:?}"
8930        );
8931        // Evaluation takes the complex principal branch: (-8)^(1/3) = 1 + 1.732j
8932        let v = eval_value(&folded, &HashMap::new())
8933            .unwrap()
8934            .as_scalar()
8935            .unwrap();
8936        assert!((v.re - 1.0).abs() < 1e-12, "{v:?}");
8937        assert!((v.im - 3.0f64.sqrt()).abs() < 1e-12, "{v:?}");
8938        // Positive bases / integer exponents are folded as before
8939        assert!(matches!(simplify(&pow(num(4.0), num(0.5))), Expr::Num(v) if v == 2.0));
8940        assert!(matches!(simplify(&pow(num(-2.0), num(3.0))), Expr::Num(v) if v == -8.0));
8941    }
8942
8943    #[test]
8944    fn negative_literal_sqrt_is_rejected_by_real_emission_not_deferred_to_nan() {
8945        let e = Expr::Call("sqrt".into(), vec![num(-4.0)]);
8946        let real = emit_block(&e);
8947        assert!(real.contains("compile_error!"), "{real}");
8948        // The same mathematical object is still the principal value 2j in the complex lane; it must
8949        // not be caught by the real guard.
8950        let complex = emit_block_complex(&e);
8951        assert!(
8952            complex.contains("__c_sqrt") && !complex.contains("compile_error!"),
8953            "{complex}"
8954        );
8955        let value = eval_value(&e, &HashMap::new())
8956            .unwrap()
8957            .as_scalar()
8958            .unwrap();
8959        assert_eq!(value, C::new(0.0, 2.0));
8960    }
8961
8962    #[test]
8963    fn matrix_power_folds_to_explicit_products_or_rejects() {
8964        // M² = M·M (the flatten layer does repeated matrix multiplication)
8965        let m = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
8966        let sq = Expr::Pow(Box::new(m.clone()), Box::new(num(2.0)));
8967        assert!(is_matrix_value(&sq), "整数幂的矩阵应可折叠");
8968        // Numeric check: [[1,2],[3,4]]² = [[7,10],[15,22]]
8969        // **Both** the value layer and the generator support it (the same folding semantics; himari-eval
8970        // is no longer behind)
8971        let want = [[7.0f64, 10.0], [15.0, 22.0]];
8972        match eval_value(&sq, &HashMap::new()).unwrap() {
8973            Value::Matrix(mm) => {
8974                for r in 0..2 {
8975                    for c in 0..2 {
8976                        assert_eq!(mm[r][c].re, want[r][c], "值层 [{r}][{c}]");
8977                    }
8978                }
8979            }
8980            other => panic!("{other:?}"),
8981        }
8982        let flat = flatten_matrix_value(&sq).unwrap();
8983        match eval_value(&Expr::Mat(flat), &HashMap::new()).unwrap() {
8984            Value::Matrix(mm) => {
8985                for r in 0..2 {
8986                    for c in 0..2 {
8987                        assert_eq!(mm[r][c].re, want[r][c], "折叠 [{r}][{c}]");
8988                    }
8989                }
8990            }
8991            other => panic!("{other:?}"),
8992        }
8993        // Fractional power / non-square → not folded (is_matrix_value = false)
8994        assert!(!is_matrix_value(&Expr::Pow(
8995            Box::new(m.clone()),
8996            Box::new(num(2.5))
8997        )));
8998        let row = Expr::Mat(vec![vec![num(1.0), num(2.0)]]);
8999        assert!(!is_matrix_value(&Expr::Pow(
9000            Box::new(row),
9001            Box::new(num(2.0))
9002        )));
9003        // For a rejected matrix power the emitter emits compile_error (not a vec!*vec! compile
9004        // accident)
9005        let code = emit_block(&Expr::Pow(Box::new(m.clone()), Box::new(num(2.5))));
9006        assert!(code.contains("compile_error!"), "{code}");
9007    }
9008
9009    #[test]
9010    fn matrix_zero_power_is_identity_not_the_scalar_one() {
9011        let m = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
9012        let e = pow(m, num(0.0));
9013        let folded = simplify(&e);
9014        assert!(is_matrix_value(&folded), "M^0 必须保持矩阵类型:{folded:?}");
9015        let want = Value::Matrix(vec![vec![C::ONE, C::ZERO], vec![C::ZERO, C::ONE]]);
9016        assert_eq!(eval_value(&folded, &HashMap::new()).unwrap(), want);
9017        assert_eq!(
9018            eval_value(
9019                &Expr::Mat(flatten_matrix_value(&folded).unwrap()),
9020                &HashMap::new()
9021            )
9022            .unwrap(),
9023            want
9024        );
9025        let code = emit_block(&folded);
9026        assert!(
9027            code.contains("vec![vec![1.0, 0.0], vec![0.0, 1.0]]"),
9028            "{code}"
9029        );
9030    }
9031
9032    #[test]
9033    fn dot_and_norm_are_expanded_from_literals() {
9034        // dot([1,2],[3,4]) = 11
9035        let a = Expr::Mat(vec![vec![num(1.0), num(2.0)]]);
9036        let b = Expr::Mat(vec![vec![num(3.0), num(4.0)]]);
9037        let d = Expr::Call("dot".into(), vec![a.clone(), b.clone()]);
9038        let v = eval_value(&d, &HashMap::new())
9039            .unwrap()
9040            .as_scalar()
9041            .map(|c| c.re);
9042        assert_eq!(v, Some(11.0));
9043        // norm([3,4]) = 5 (3-4-5)
9044        let n = Expr::Call("norm".into(), vec![a.clone()]);
9045        let v = eval_value(&n, &HashMap::new())
9046            .unwrap()
9047            .as_scalar()
9048            .map(|c| c.re);
9049        assert_eq!(v, Some(5.0f64.sqrt()));
9050        // Dimensions: dot is the square of the dimension, norm matches the elements' dimension
9051        let decls = vec![Decl {
9052            name: "v".into(),
9053            quantity: "velocity".into(),
9054            unit: Some("m/s".into()),
9055        }];
9056        let dims = dims_of(&decls).unwrap();
9057        let ve = Expr::Mat(vec![vec![var("v"), var("v")]]);
9058        let dot = Expr::Call("dot".into(), vec![ve.clone(), ve.clone()]);
9059        assert_eq!(
9060            dim_check(&dot, &dims).unwrap(),
9061            parse_unit("m^2/s^2").unwrap(),
9062            "dot 的量纲是平方"
9063        );
9064        let norm = Expr::Call("norm".into(), vec![ve]);
9065        assert_eq!(
9066            dim_check(&norm, &dims).unwrap(),
9067            parse_unit("m/s").unwrap(),
9068            "norm 与元素同量纲"
9069        );
9070        // Inconsistent shapes → expansion fails (no silent computation)
9071        let c = Expr::Mat(vec![vec![num(1.0), num(2.0), num(3.0)]]);
9072        assert!(expand_dot(&Expr::Call("dot".into(), vec![a, c])).is_none());
9073        // The generated code contains an ordinary scalar expression
9074        let code = emit_block(&Expr::Call(
9075            "dot".into(),
9076            vec![
9077                Expr::Mat(vec![vec![num(1.0), num(2.0)]]),
9078                Expr::Mat(vec![vec![var("x"), var("y")]]),
9079            ],
9080        ));
9081        assert!(code.contains("x") && code.contains("y"), "{code}");
9082    }
9083
9084    #[test]
9085    fn determinant_and_inverse_reach_the_documented_orders() {
9086        // Both the order-2 and order-3 inverse can be expanded (2D/3D isoparametric transforms)
9087        let m2 = Expr::Mat(vec![vec![var("a"), var("b")], vec![var("c"), var("d")]]);
9088        let inv2 = Expr::Call("inv".into(), vec![m2.clone()]);
9089        assert_eq!(flatten_matrix_value(&inv2).expect("2 阶逆").len(), 2);
9090        let m3 = Expr::Mat(vec![
9091            vec![var("a"), var("b"), var("c")],
9092            vec![var("d"), var("e"), var("f")],
9093            vec![var("g"), var("h"), var("i")],
9094        ]);
9095        let inv3 = Expr::Call("inv".into(), vec![m3.clone()]);
9096        let flat3 = flatten_matrix_value(&inv3).expect("3 阶逆");
9097        assert_eq!(flat3.len(), 3);
9098        // The order-4 inverse is explicitly not done (16 3×3 minors ≈ 100 terms; the generated code
9099        // explodes)
9100        let m4 = Expr::Mat(vec![
9101            vec![num(1.0), num(2.0), num(3.0), num(4.0)],
9102            vec![num(5.0), num(6.0), num(7.0), num(8.0)],
9103            vec![num(9.0), num(10.0), num(11.0), num(12.0)],
9104            vec![num(13.0), num(14.0), num(15.0), num(16.0)],
9105        ]);
9106        assert!(flatten_matrix_value(&Expr::Call("inv".into(), vec![m4.clone()])).is_none());
9107
9108        // det up to order 4: an upper-triangular 4×4 → det = 1·2·3·4 = 24
9109        let tri = Expr::Mat(vec![
9110            vec![num(1.0), num(5.0), num(6.0), num(7.0)],
9111            vec![num(0.0), num(2.0), num(8.0), num(9.0)],
9112            vec![num(0.0), num(0.0), num(3.0), num(10.0)],
9113            vec![num(0.0), num(0.0), num(0.0), num(4.0)],
9114        ]);
9115        let d4 = eval_value(&Expr::Call("det".into(), vec![tri]), &HashMap::new())
9116            .unwrap()
9117            .as_scalar()
9118            .map(|c| c.re);
9119        assert_eq!(d4, Some(24.0));
9120        // Order 5 is rejected
9121        let five: Vec<Vec<Expr>> = (0..5)
9122            .map(|i| (0..5).map(|j| num((i * 5 + j) as f64)).collect())
9123            .collect();
9124        let err = eval_value(
9125            &Expr::Call("det".into(), vec![Expr::Mat(five)]),
9126            &HashMap::new(),
9127        )
9128        .unwrap_err();
9129        assert_eq!(err.code(), "invalid-input", "{err}");
9130        assert!(err.to_string().contains("1–4"), "{err}");
9131
9132        // Numeric check of the order-3 inverse: M·M⁻¹ = I
9133        let mut env = HashMap::new();
9134        for (k, v) in [
9135            ("a", 2.0),
9136            ("b", -1.0),
9137            ("c", 0.0),
9138            ("d", -1.0),
9139            ("e", 2.0),
9140            ("f", -1.0),
9141            ("g", 0.0),
9142            ("h", -1.0),
9143            ("i", 2.0),
9144        ] {
9145            env.insert(k.to_string(), v);
9146        }
9147        let flat = flatten_matrix_value(&inv3).unwrap();
9148        let m_val = match eval_value(&m3, &env).unwrap() {
9149            Value::Matrix(m) => m,
9150            other => panic!("{other:?}"),
9151        };
9152        let inv_val = match eval_value(&Expr::Mat(flat), &env).unwrap() {
9153            Value::Matrix(m) => m,
9154            other => panic!("{other:?}"),
9155        };
9156        // All three are **matrix index semantics** (i/j/k traverse rows/columns/the inner dimension
9157        // respectively), not set iteration
9158        #[allow(clippy::needless_range_loop)]
9159        for r in 0..3 {
9160            #[allow(clippy::needless_range_loop)]
9161            for c in 0..3 {
9162                let mut acc = C::ZERO;
9163                for k in 0..3 {
9164                    acc = acc.add(m_val[r][k].mul(inv_val[k][c]));
9165                }
9166                let want = if r == c { 1.0 } else { 0.0 };
9167                assert!((acc.re - want).abs() < 1e-12, "M·M⁻¹[{r}][{c}] = {acc:?}");
9168            }
9169        }
9170        // Evaluating a singular matrix errors (not inf)
9171        let mut sing = HashMap::new();
9172        for (k, v) in [("a", 1.0), ("b", 1.0), ("c", 1.0), ("d", 1.0)] {
9173            sing.insert(k.to_string(), v);
9174        }
9175        // After IR expansion, a singular matrix reports division by zero at the "divide by det" step
9176        // (still an explicit error, not inf)
9177        let err = eval_value(&inv2, &sing).unwrap_err();
9178        assert_eq!(err.code(), "division-by-zero", "{err}");
9179        assert!(matches!(err, Error::DivisionByZero), "{err}");
9180    }
9181
9182    #[test]
9183    fn buckingham_pi_recovers_reynolds() {
9184        let vars = vec![
9185            ("rho".to_string(), parse_unit("kg/m^3").unwrap()),
9186            ("v".to_string(), parse_unit("m/s").unwrap()),
9187            ("L".to_string(), parse_unit("m").unwrap()),
9188            ("mu".to_string(), parse_unit("Pa*s").unwrap()),
9189        ];
9190        let g = dimensionless_groups(&vars).unwrap();
9191        assert_eq!(g.len(), 1, "4 变量 / 秩 3 → 1 个无量纲群");
9192        let names: Vec<String> = vars.iter().map(|(n, _)| n.clone()).collect();
9193        assert_eq!(pi_text(&names, &g[0]), "rho·v·L·mu^-1");
9194        // Verify term by term: the dimension after weighting by the exponents must be 1
9195        let mut acc = Dim::ZERO;
9196        for ((_, d), e) in vars.iter().zip(&g[0]) {
9197            acc = acc.mul_dim(d.scale_ratio((e * 2.0) as i32, 2).unwrap());
9198        }
9199        assert!(acc.is_zero(), "Π 必须无量纲:{}", acc.display());
9200    }
9201
9202    #[test]
9203    fn buckingham_pi_group_count_matches_theorem() {
9204        // Five base quantities → rank 5 → 0 groups
9205        let mut base: Vec<(String, Dim)> = ["kg", "m", "s", "A", "K"]
9206            .iter()
9207            .map(|u| (u.to_string(), parse_unit(u).unwrap()))
9208            .collect();
9209        assert_eq!(dimensionless_groups(&base).unwrap().len(), 0);
9210        // Adding a derived quantity (force = kg·m/s²) does not increase the rank: 6 variables /
9211        // rank 5 → 1 group
9212        // (this is exactly what the Π theorem says: the number of groups = number of variables −
9213        // rank)
9214        base.push(("F".to_string(), parse_unit("N").unwrap()));
9215        let g1 = dimensionless_groups(&base).unwrap();
9216        assert_eq!(g1.len(), 1, "6 变量 / 秩 5 → 1 个群");
9217        assert_eq!(
9218            pi_text(
9219                &base.iter().map(|(n, _)| n.clone()).collect::<Vec<_>>(),
9220                &g1[0]
9221            ),
9222            "kg·m·s^-2·F^-1",
9223            "F/(kg·m/s²) 的那个群"
9224        );
9225        // Adding energy too (J = kg·m²/s²): the rank is unchanged → 7 variables / rank 5 → 2
9226        // groups
9227        let mut v = base.clone();
9228        v.push(("E".to_string(), parse_unit("J").unwrap()));
9229        assert_eq!(
9230            dimensionless_groups(&v).unwrap().len(),
9231            2,
9232            "7 变量 / 秩 5 → 2 个群"
9233        );
9234    }
9235
9236    #[test]
9237    fn dim_solve_finds_target_dimension() {
9238        let vars = vec![
9239            ("mass".to_string(), parse_unit("kg").unwrap()),
9240            ("acc".to_string(), parse_unit("m/s^2").unwrap()),
9241        ];
9242        // F = m·a: exponents of 1 each
9243        assert_eq!(
9244            dim_solve(&vars, parse_unit("N").unwrap()).unwrap(),
9245            vec![1.0, 1.0]
9246        );
9247        // A dimension that cannot be formed must error, and say so clearly
9248        let volt = parse_unit("V").unwrap();
9249        let err = dim_solve(&vars, volt).unwrap_err();
9250        // Catalogued: the stable code, and the payload carries the requested dimension
9251        // (in its base-dimension display form).
9252        assert_eq!(err.code(), "target-dimension-unreachable", "{err}");
9253        match &err {
9254            Error::TargetDimensionUnreachable { target, .. } => {
9255                assert_eq!(*target, volt.display().to_string());
9256            }
9257            other => panic!("{other:?}"),
9258        }
9259        assert!(
9260            err.to_string().contains(&volt.display().to_string()),
9261            "{err}"
9262        );
9263        // A dimensionless target gives the all-zero solution
9264        let zero = dim_solve(&vars, Dim::ZERO).unwrap();
9265        assert_eq!(zero, vec![0.0, 0.0]);
9266    }
9267
9268    #[test]
9269    fn matrix_expression_codegen_matches_value_layer() {
9270        // Differential check: evaluating the **folded literal** must equal evaluating the **original
9271        // expression**.
9272        // The emitter's folding (including transpose/add/subtract/scalar broadcast/matrix multiply)
9273        // and the value layer are two independent implementations,
9274        // and it only counts as really correct if they agree.
9275        let a = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
9276        let b = Expr::Mat(vec![vec![num(5.0), num(6.0)], vec![num(7.0), num(8.0)]]);
9277        let row = Expr::Mat(vec![vec![num(1.0), num(2.0), num(3.0)]]);
9278        let cases = vec![
9279            transpose(row.clone()),
9280            add(a.clone(), b.clone()),
9281            sub(a.clone(), b.clone()),
9282            mul(a.clone(), b.clone()),
9283            mul(var("k"), a.clone()),
9284            neg(a.clone()),
9285            transpose(mul(a.clone(), b.clone())),
9286        ];
9287        let mut env = HashMap::new();
9288        env.insert("k".to_string(), 2.5);
9289        for e in &cases {
9290            let folded = flatten_matrix_value(e).unwrap_or_else(|| panic!("应可折叠:{e:?}"));
9291            let v1 = eval_value(e, &env).unwrap();
9292            let v2 = eval_value(&Expr::Mat(folded), &env).unwrap();
9293            assert_eq!(v1, v2, "折叠与值层不同值:{e:?}");
9294            assert!(is_matrix_value(e));
9295            assert!(
9296                emit_block(e).contains("vec!["),
9297                "矩阵值必须发射成 vec![...]"
9298            );
9299        }
9300        // The transposed 1×3 becomes a 3×1 literal
9301        assert_eq!(
9302            emit_block(&transpose(row)).trim(),
9303            "{\n        vec![vec![1.0], vec![2.0], vec![3.0]]\n    }"
9304        );
9305        // Cases that are not folded: inconsistent shapes / symbolic matrices of unknown shape /
9306        // scalar expressions
9307        let jag = Expr::Mat(vec![vec![num(1.0)], vec![num(2.0)]]);
9308        let small = Expr::Mat(vec![vec![num(1.0)]]);
9309        assert!(!is_matrix_value(&add(small.clone(), jag)));
9310        assert!(!is_matrix_value(&transpose(var("A"))));
9311        assert!(!is_matrix_value(&add(num(1.0), var("k"))));
9312        // A bare symbol is a **scalar** (a matrix can only come from a literal or the pattern
9313        // generator):
9314        // so `A * [1, 2]` is scalar broadcasting, not a matrix product
9315        assert!(is_matrix_value(&mul(var("A"), small)));
9316    }
9317
9318    #[test]
9319    fn reserved_j_is_not_a_parameter() {
9320        // `j` is the reserved imaginary unit: it does not enter the parameter list (otherwise the
9321        // signature would become "please pass the imaginary unit")
9322        let decls = vec![Decl {
9323            name: "r".into(),
9324            quantity: "resistance".into(),
9325            unit: Some("V/A".into()),
9326        }];
9327        let e = add(var("r"), mul(var("j"), num(2.0)));
9328        assert_eq!(params_in_decl_order(&decls, &e), vec!["r".to_string()]);
9329        assert!(uses_complex(&e));
9330        let code = emit_block_complex(&e);
9331        assert!(
9332            code.contains("__c_add") && code.contains("(0.0, 1.0)"),
9333            "{code}"
9334        );
9335        assert!(!code.contains("__c_sqrt"), "未用到的算子不该被发射:{code}");
9336        // A purely real expression does not take the complex lane
9337        assert!(!uses_complex(&add(var("r"), num(2.0))));
9338    }
9339
9340    #[test]
9341    fn diff_matches_finite_difference() {
9342        // f = exp(2x) * sin(x) / (1 + x^2)
9343        let f = div(
9344            mul(
9345                Expr::Call("exp".into(), vec![mul(num(2.0), var("x"))]),
9346                Expr::Call("sin".into(), vec![var("x")]),
9347            ),
9348            add(num(1.0), pow(var("x"), num(2.0))),
9349        );
9350        let df = simplify(&diff(&f, "x"));
9351        let mut env = HashMap::new();
9352        for x in [-1.3, -0.2, 0.4, 1.7] {
9353            env.insert("x".to_string(), x);
9354            let h = 1e-6;
9355            env.insert("x".to_string(), x + h);
9356            let fp = eval(&f, &env).unwrap();
9357            env.insert("x".to_string(), x - h);
9358            let fm = eval(&f, &env).unwrap();
9359            env.insert("x".to_string(), x);
9360            let analytic = eval(&df, &env).unwrap();
9361            let numeric = (fp - fm) / (2.0 * h);
9362            assert!(
9363                (analytic - numeric).abs() < 1e-5 * (1.0 + numeric.abs()),
9364                "x={x} analytic={analytic} numeric={numeric}"
9365            );
9366        }
9367    }
9368
9369    #[test]
9370    fn dim_check_catches_mismatch() {
9371        let decls = vec![
9372            Decl {
9373                name: "a".into(),
9374                quantity: "length".into(),
9375                unit: Some("m".into()),
9376            },
9377            Decl {
9378                name: "t".into(),
9379                quantity: "time".into(),
9380                unit: Some("s".into()),
9381            },
9382        ];
9383        let dims = dims_of(&decls).unwrap();
9384        assert!(dim_check(&div(var("a"), var("t")), &dims).is_ok());
9385        assert!(dim_check(&add(var("a"), var("t")), &dims).is_err());
9386        assert!(dim_check(&var("nope"), &dims).is_err());
9387    }
9388
9389    // ---------------- matrix patterns ----------------
9390
9391    fn pat(rows: Vec<Vec<PatternCell>>) -> MatPattern {
9392        MatPattern { rows }
9393    }
9394    fn el(e: Expr) -> PatternCell {
9395        PatternCell::El(e)
9396    }
9397    const D: PatternCell = PatternCell::Dots;
9398
9399    #[test]
9400    fn recognize_identity() {
9401        // [[1, ·, 0], [·, 1, ·], [0, ·, 1]]
9402        let p = pat(vec![
9403            vec![el(num(1.0)), D, el(num(0.0))],
9404            vec![D, el(num(1.0)), D],
9405            vec![el(num(0.0)), D, el(num(1.0))],
9406        ]);
9407        assert_eq!(recognize_pattern(&p).unwrap(), MatrixKind::Identity);
9408    }
9409
9410    #[test]
9411    fn recognize_diag() {
9412        let p = pat(vec![
9413            vec![el(var("d")), D, el(num(0.0))],
9414            vec![D, el(var("d")), D],
9415            vec![el(num(0.0)), D, el(var("d"))],
9416        ]);
9417        assert!(matches!(
9418            recognize_pattern(&p).unwrap(),
9419            MatrixKind::Diag(_)
9420        ));
9421        // The diagonal is not the same expression → reject
9422        let bad = pat(vec![
9423            vec![el(var("d")), D, el(num(0.0))],
9424            vec![D, el(var("e")), D],
9425            vec![el(num(0.0)), D, el(var("d"))],
9426        ]);
9427        assert!(recognize_pattern(&bad).is_err());
9428    }
9429
9430    #[test]
9431    fn recognize_tridiag() {
9432        let p = pat(vec![
9433            vec![el(var("b")), el(var("c")), D, el(num(0.0))],
9434            vec![el(var("a")), el(var("b")), el(var("c")), D],
9435            vec![D, el(var("a")), el(var("b")), el(var("c"))],
9436            vec![el(num(0.0)), D, el(var("a")), el(var("b"))],
9437        ]);
9438        match recognize_pattern(&p).unwrap() {
9439            MatrixKind::Tridiag { .. } => {}
9440            other => panic!("期望 Tridiag,得到 {other:?}"),
9441        }
9442        // Different diagonals → explicit error (not a silent downgrade)
9443        let mut bad = p;
9444        if let PatternCell::El(e) = &mut bad.rows[1][1] {
9445            *e = var("z");
9446        }
9447        assert!(matches!(
9448            recognize_pattern(&bad).unwrap_err(),
9449            Error::InvalidInput(ref why) if why.contains("tridiagonal")
9450        ));
9451    }
9452
9453    #[test]
9454    fn half_integer_dimensions() {
9455        // √(m²) = m: integer powers are still correct
9456        let decls = vec![Decl {
9457            name: "a".into(),
9458            quantity: "area".into(),
9459            unit: Some("m^2".into()),
9460        }];
9461        let dims = dims_of(&decls).unwrap();
9462        let root = Expr::Call("sqrt".into(), vec![var("a")]);
9463        assert_eq!(dim_check(&root, &dims).unwrap(), parse_unit("m").unwrap());
9464
9465        // √(s) = s^1/2: half-integer exponents (previously rejected)
9466        let decls2 = vec![Decl {
9467            name: "t".into(),
9468            quantity: "time".into(),
9469            unit: Some("s".into()),
9470        }];
9471        let dims2 = dims_of(&decls2).unwrap();
9472        let root2 = Expr::Call("sqrt".into(), vec![var("t")]);
9473        let half = dim_check(&root2, &dims2).unwrap();
9474        assert_eq!(half.display(), "s^(1/2)");
9475        // Ω·s^-1/2: σ is V/A, multiplied by s^-1/2
9476        let sigma = var("sigma");
9477        let d_sigma = dim_check(
9478            &sigma,
9479            &dims_of(&[Decl {
9480                name: "sigma".into(),
9481                quantity: "warburg_coefficient".into(),
9482                unit: Some("V/A".into()),
9483            }])
9484            .unwrap(),
9485        )
9486        .unwrap();
9487        // Then multiply by s^-1/2 (expressed as 1/√s)
9488        let inv_sqrt_s = div(num(1.0), root2.clone());
9489        let d_inv = dim_check(&inv_sqrt_s, &dims2).unwrap();
9490        let combined = d_sigma.mul_dim(d_inv);
9491        // V/A = kg·m²·s⁻³·A⁻², then multiplied by s^(-1/2)
9492        assert_eq!(
9493            combined.display(),
9494            "kg·m^2·s^(-7/2)·A^-2",
9495            "Ω·s^(-1/2) 量纲"
9496        );
9497    }
9498
9499    #[test]
9500    fn complex_impedance_arithmetic() {
9501        // Z = R + j*X (j is the reserved imaginary unit, dimensionless)
9502        let z = add(var("R"), mul(var("j"), var("X")));
9503        let mut env = HashMap::new();
9504        env.insert("R".to_string(), 3.0);
9505        env.insert("X".to_string(), -4.0);
9506        match eval_value(&z, &env).unwrap() {
9507            Value::Scalar(c) => {
9508                assert_eq!((c.re, c.im), (3.0, -4.0));
9509            }
9510            other => panic!("期望标量,得到 {other:?}"),
9511        }
9512        // |Z| = √(R²+X²) = 5
9513        let mag = Expr::Call(
9514            "sqrt".into(),
9515            vec![add(pow(var("R"), num(2.0)), pow(var("X"), num(2.0)))],
9516        );
9517        assert_eq!(eval(&mag, &env).unwrap(), 5.0);
9518
9519        // Dimensions: j is dimensionless, so both sides of Z = R + jX share a dimension (Ω)
9520        let decls = vec![
9521            Decl {
9522                name: "R".into(),
9523                quantity: "resistance".into(),
9524                unit: Some("V/A".into()),
9525            },
9526            Decl {
9527                name: "X".into(),
9528                quantity: "reactance".into(),
9529                unit: Some("V/A".into()),
9530            },
9531        ];
9532        let dims = dims_of(&decls).unwrap();
9533        assert_eq!(
9534            dim_check(&z, &dims).unwrap(),
9535            parse_unit("V/A").unwrap(),
9536            "复阻抗量纲应仍是 Ω"
9537        );
9538
9539        // Complex division: Z1/Z2, with both real and imaginary parts correct
9540        let q = div(
9541            add(num(1.0), mul(var("j"), num(1.0))),
9542            add(num(1.0), mul(var("j"), num(-1.0))),
9543        );
9544        match eval_value(&q, &HashMap::new()).unwrap() {
9545            Value::Scalar(c) => {
9546                assert!(c.re.abs() < 1e-15, "re={}", c.re);
9547                assert!((c.im - 1.0).abs() < 1e-15, "im={}", c.im);
9548            }
9549            other => panic!("期望标量,得到 {other:?}"),
9550        }
9551    }
9552
9553    #[test]
9554    fn recognize_banded_k2() {
9555        // 5×5 k=2: every cell with |i-j|<=2 is v, everything outside the band is 0
9556        let mk = |blank_at: &[(usize, usize)]| {
9557            let mut rows = Vec::new();
9558            for i in 0..5usize {
9559                let mut r = Vec::new();
9560                for j in 0..5usize {
9561                    r.push(if i.abs_diff(j) <= 2 {
9562                        el(var("v"))
9563                    } else if blank_at.contains(&(i, j)) {
9564                        D
9565                    } else {
9566                        el(num(0.0))
9567                    });
9568                }
9569                rows.push(r);
9570            }
9571            pat(rows)
9572        };
9573        match recognize_pattern(&mk(&[])).unwrap() {
9574            MatrixKind::Banded { half_band, .. } => assert_eq!(half_band, 2),
9575            other => panic!("期望 Banded k=2,得到 {other:?}"),
9576        }
9577        // Ellipses standing in for 0 are recognized too
9578        match recognize_pattern(&mk(&[(0, 3), (0, 4), (3, 0), (4, 0)])).unwrap() {
9579            MatrixKind::Banded { half_band, .. } => assert_eq!(half_band, 2),
9580            other => panic!("省略号形态应为 Banded,得到 {other:?}"),
9581        }
9582        // A concrete non-zero placed outside the band → not banded
9583        let mut bad = mk(&[]);
9584        bad.rows[0][4] = el(var("w"));
9585        assert!(!matches!(
9586            recognize_pattern(&bad),
9587            Ok(MatrixKind::Banded { .. })
9588        ));
9589        // For 4×4, k=2 degenerates to a full matrix → not handled by the banded branch (only
9590        // attempted when m≥5)
9591    }
9592
9593    #[test]
9594    fn recognize_blockdiag2() {
9595        // Block diagonal = diag(p·I₂, q·I₂): the block diagonal is p, the block off-diagonal is
9596        // blank, everything outside the blocks is blank
9597        let bd = pat(vec![
9598            vec![el(var("p")), D, el(num(0.0)), el(num(0.0))],
9599            vec![D, el(var("p")), el(num(0.0)), el(num(0.0))],
9600            vec![el(num(0.0)), el(num(0.0)), el(var("q")), D],
9601            vec![el(num(0.0)), el(num(0.0)), D, el(var("q"))],
9602        ]);
9603        match recognize_pattern(&bd).unwrap() {
9604            MatrixKind::BlockDiag2 { .. } => {}
9605            other => panic!("期望 BlockDiag2,得到 {other:?}"),
9606        }
9607        // The all-ellipsis form (both inside and outside the blocks denoted by ⋯) is equivalent
9608        let bd2 = pat(vec![
9609            vec![el(var("p")), D, D, D],
9610            vec![D, el(var("p")), D, D],
9611            vec![D, D, el(var("q")), D],
9612            vec![D, D, D, el(var("q"))],
9613        ]);
9614        match recognize_pattern(&bd2).unwrap() {
9615            MatrixKind::BlockDiag2 { .. } => {}
9616            other => panic!("省略号形态应为 BlockDiag2,得到 {other:?}"),
9617        }
9618        // Coupling outside the blocks → not block diagonal
9619        let bad = pat(vec![
9620            vec![el(var("p")), D, el(var("c")), el(num(0.0))],
9621            vec![D, el(var("p")), el(num(0.0)), el(num(0.0))],
9622            vec![el(num(0.0)), el(num(0.0)), el(var("q")), D],
9623            vec![el(num(0.0)), el(num(0.0)), D, el(var("q"))],
9624        ]);
9625        assert!(!matches!(
9626            recognize_pattern(&bad),
9627            Ok(MatrixKind::BlockDiag2 { .. })
9628        ));
9629    }
9630
9631    #[test]
9632    fn recognize_bidiag_both_orientations() {
9633        // Upper bidiagonal: main diagonal b + superdiagonal c, the whole lower triangle is
9634        // ellipses
9635        let up = pat(vec![
9636            vec![el(var("b")), el(var("c")), D, D],
9637            vec![D, el(var("b")), el(var("c")), D],
9638            vec![D, D, el(var("b")), el(var("c"))],
9639            vec![D, D, D, el(var("b"))],
9640        ]);
9641        match recognize_pattern(&up).unwrap() {
9642            MatrixKind::BidiagUpper { .. } => {}
9643            other => panic!("期望 BidiagUpper,得到 {other:?}"),
9644        }
9645        // Lower bidiagonal: main diagonal b + subdiagonal a, the whole upper triangle is
9646        // ellipses
9647        let lo = pat(vec![
9648            vec![el(var("b")), D, D, D],
9649            vec![el(var("a")), el(var("b")), D, D],
9650            vec![D, el(var("a")), el(var("b")), D],
9651            vec![D, D, el(var("a")), el(var("b"))],
9652        ]);
9653        match recognize_pattern(&lo).unwrap() {
9654            MatrixKind::BidiagLower { .. } => {}
9655            other => panic!("期望 BidiagLower,得到 {other:?}"),
9656        }
9657        // Generated source: both orientations land in the right positions
9658        let su = emit_matrix_ctor(
9659            "BU",
9660            &MatrixKind::BidiagUpper {
9661                b: var("b"),
9662                c: var("c"),
9663            },
9664        );
9665        assert!(
9666            su.contains("m[__row][__next] = cv;") && !su.contains("m[__next]"),
9667            "{su}"
9668        );
9669        let sl = emit_matrix_ctor(
9670            "BL",
9671            &MatrixKind::BidiagLower {
9672                a: var("a"),
9673                b: var("b"),
9674            },
9675        );
9676        assert!(sl.contains("m[__next][__row] = av;"), "{sl}");
9677    }
9678
9679    #[test]
9680    fn recognize_unknown_shape_rejected_with_guidance() {
9681        // 2×2 has no meaningful ellipses; 3×3 but with a jumbled diagonal → an error listing the
9682        // three supported shapes
9683        let p = pat(vec![
9684            vec![el(var("x")), D, el(var("y"))],
9685            vec![D, el(var("q")), D],
9686            vec![el(var("z")), D, el(var("w"))],
9687        ]);
9688        let text = recognize_pattern(&p).unwrap_err().render(i18n::Locale::En);
9689        assert!(
9690            text.contains("identity") && text.contains("diag") && text.contains("tridiag"),
9691            "{text}"
9692        );
9693    }
9694
9695    #[test]
9696    fn to_latex_dots_directions() {
9697        let p = Expr::MatPattern(pat(vec![
9698            vec![el(var("a")), D, el(var("b"))],
9699            vec![D, D, D],
9700            vec![el(var("c")), D, el(var("d"))],
9701        ]));
9702        let tex = to_latex(&p);
9703        assert!(tex.contains("\\cdots"), "{tex}");
9704        assert!(tex.contains("\\vdots"), "{tex}");
9705        assert!(tex.contains("\\ddots"), "{tex}");
9706        assert!(tex.contains("bmatrix"), "{tex}");
9707    }
9708
9709    #[test]
9710    fn solve_system_dimensions_are_checked_on_both_sides() {
9711        // An equation is legal only if it is **dimensionally homogeneous** (both sides of the
9712        // addition/subtraction share a dimension): this is where "dimension is a promise"
9713        // lands in the solving lane. Previously it was only a by-product of dim_check checking arg0
9714        // first,
9715        // and here it is pinned down as a contract — if someone changes the order of the Call
9716        // branch, this turns red.
9717        let dims = dims_of(&[
9718            Decl {
9719                name: "k".into(),
9720                quantity: "stiffness".into(),
9721                unit: Some("N/m".into()),
9722            },
9723            Decl {
9724                name: "F".into(),
9725                quantity: "load".into(),
9726                unit: Some("N".into()),
9727            },
9728            Decl {
9729                name: "x".into(),
9730                quantity: "displacement".into(),
9731                unit: Some("m".into()),
9732            },
9733        ])
9734        .unwrap();
9735        // k·x − F = 0: both sides are N → legal, and the solved x has dimension N/(N/m) = m
9736        let good = Expr::Call(
9737            "solve".into(),
9738            vec![
9739                Expr::Mat(vec![vec![sub(mul(var("k"), var("x")), var("F"))]]),
9740                Expr::Mat(vec![vec![var("x")]]),
9741            ],
9742        );
9743        assert_eq!(
9744            dim_check(&good, &dims).unwrap(),
9745            parse_unit("m").unwrap(),
9746            "解的列向量元素量纲应是位移"
9747        );
9748        // x − F = 0: m vs N → dimensions not homogeneous, must be rejected (not "make do by solving
9749        // for an F")
9750        let bad = Expr::Call(
9751            "solve".into(),
9752            vec![
9753                Expr::Mat(vec![vec![sub(var("x"), var("F"))]]),
9754                Expr::Mat(vec![vec![var("x")]]),
9755            ],
9756        );
9757        let err = dim_check(&bad, &dims).unwrap_err();
9758        assert_eq!(err.code(), "operator-dimension-mismatch", "{err}");
9759        assert!(err.render(i18n::Locale::En).contains("`-`"), "{err}");
9760    }
9761
9762    #[test]
9763    fn roots_dimension_equals_variable_dimension() {
9764        // The roots' dimension must be **the variable's own** dimension — no extra derivation is
9765        // needed: the equation must be dimensionally
9766        // homogeneous (every term of Σ aᵢxⁱ shares a dimension), and homogeneity directly implies
9767        // dim(roots) = dim(x).
9768        // This test pins that reasoning down.
9769        let dims = dims_of(&[
9770            Decl {
9771                name: "a".into(),
9772                quantity: "inv_len".into(),
9773                unit: Some("1/m".into()),
9774            },
9775            Decl {
9776                name: "b".into(),
9777                quantity: "one".into(),
9778                unit: Some("1".into()),
9779            },
9780            Decl {
9781                name: "c".into(),
9782                quantity: "len".into(),
9783                unit: Some("m".into()),
9784            },
9785            Decl {
9786                name: "x".into(),
9787                quantity: "position".into(),
9788                unit: Some("m".into()),
9789            },
9790        ])
9791        .unwrap();
9792        // a·x² + b·x + c (every term is m) → dim(roots) = m
9793        let poly = add(
9794            sub(
9795                mul(var("a"), pow(var("x"), num(2.0))),
9796                mul(var("b"), var("x")),
9797            ),
9798            var("c"),
9799        );
9800        let call = Expr::Call("roots".into(), vec![poly, var("x")]);
9801        assert_eq!(
9802            dim_check(&call, &dims).unwrap(),
9803            parse_unit("m").unwrap(),
9804            "二次方程的根应是长度"
9805        );
9806        // Wrong variable dimension: if x is declared as s, the same polynomial is no longer
9807        // homogeneous → must be rejected
9808        let mut bad = dims.clone();
9809        bad.insert("x".to_string(), parse_unit("s").unwrap());
9810        let err = dim_check(&call, &bad).unwrap_err();
9811        assert_eq!(err.code(), "operator-dimension-mismatch", "{err}");
9812    }
9813
9814    #[test]
9815    fn poly_coeffs_requires_a_dimensionless_variable() {
9816        // The coefficients of a homogeneous polynomial have different dimensions per degree
9817        // (c_k = dim(poly)/dim(x)^k),
9818        // while a matrix requires elements of the same dimension — so coefficients can only be
9819        // extracted for a dimensionless variable.
9820        // This check must be **explained at the parse/diagnosis stage**; downstream must not report
9821        // "inconsistent matrix element dimensions".
9822        let dims = dims_of(&[
9823            Decl {
9824                name: "k".into(),
9825                quantity: "stiffness_quad".into(),
9826                // k·x² and the constant term F share a dimension (N): the polynomial itself is
9827                // homogeneous, but the **coefficients** have different dimensions
9828                unit: Some("N/m^2".into()),
9829            },
9830            Decl {
9831                name: "F".into(),
9832                quantity: "load".into(),
9833                unit: Some("N".into()),
9834            },
9835            Decl {
9836                name: "x".into(),
9837                quantity: "len".into(),
9838                unit: Some("m".into()),
9839            },
9840            Decl {
9841                name: "s".into(),
9842                quantity: "norm".into(),
9843                unit: Some("1".into()),
9844            },
9845        ])
9846        .unwrap();
9847        // A dimensioned variable → reject, with an actionable message
9848        let poly = add(mul(var("k"), pow(var("x"), num(2.0))), var("F"));
9849        let call = Expr::Call("poly_coeffs".into(), vec![poly, var("x")]);
9850        let err = dim_check(&call, &dims).unwrap_err();
9851        assert_eq!(err.code(), "invalid-input", "{err}");
9852        let en = err.render(crate::i18n::Locale::En);
9853        assert!(
9854            en.contains("dimension") && en.contains("dimensionless"),
9855            "{en}"
9856        );
9857        // A dimensionless variable → pass, and the result is a dimensionless matrix
9858        let ok = Expr::Call(
9859            "poly_coeffs".into(),
9860            vec![
9861                add(
9862                    mul(num(2.0), pow(var("s"), num(2.0))),
9863                    mul(num(3.0), var("s")),
9864                ),
9865                var("s"),
9866            ],
9867        );
9868        assert_eq!(dim_check(&ok, &dims).unwrap(), Dim::ZERO);
9869    }
9870
9871    #[test]
9872    fn dim_check_matrix_family() {
9873        let decls = vec![
9874            Decl {
9875                name: "a".into(),
9876                quantity: "l".into(),
9877                unit: Some("m".into()),
9878            },
9879            Decl {
9880                name: "b".into(),
9881                quantity: "l".into(),
9882                unit: Some("m".into()),
9883            },
9884            Decl {
9885                name: "t".into(),
9886                quantity: "t".into(),
9887                unit: Some("s".into()),
9888            },
9889        ];
9890        let dims = dims_of(&decls).unwrap();
9891        // Concrete matrix: elements share a dimension → OK
9892        let m = Expr::Mat(vec![vec![var("a"), var("b")], vec![var("b"), var("a")]]);
9893        assert_eq!(dim_check(&m, &dims).unwrap(), parse_unit("m").unwrap());
9894        // Inconsistent element dimensions → reject
9895        let bad = Expr::Mat(vec![vec![var("a")], vec![var("t")]]);
9896        assert!(dim_check(&bad, &dims).is_err());
9897        // Pattern matrix: the concrete elements agree → OK; Dots do not participate
9898        let pm = Expr::MatPattern(pat(vec![
9899            vec![el(var("a")), D, el(num(0.0))],
9900            vec![D, el(var("a")), D],
9901            vec![el(num(0.0)), D, el(var("a"))],
9902        ]));
9903        assert!(dim_check(&pm, &dims).is_ok());
9904        let pbad = Expr::MatPattern(pat(vec![
9905            vec![el(var("a")), D, el(num(0.0))],
9906            vec![D, el(var("t")), D],
9907            vec![el(num(0.0)), D, el(var("a"))],
9908        ]));
9909        assert!(dim_check(&pbad, &dims).is_err());
9910    }
9911
9912    #[test]
9913    fn mathml_shapes() {
9914        // Fraction
9915        let x = to_mathml(&div(var("a"), var("b")));
9916        assert!(x.contains("<mfrac>"), "{x}");
9917        // Superscript
9918        let p = to_mathml(&pow(var("x"), num(2.0)));
9919        assert!(x.contains("<mn>2</mn>") || p.contains("<msup>"), "{p}");
9920        // Indexed symbol
9921        let ix = to_mathml(&indexed("a", vec!["i".into(), "j".into()]));
9922        assert!(ix.contains("<msub>") && ix.contains("<mi>j</mi>"), "{ix}");
9923        // Summation (bounds)
9924        let sm = to_mathml(&sum("i", num(1.0), num(3.0), pow(var("i"), num(2.0))));
9925        assert!(sm.contains("<munderover>"), "{sm}");
9926        // Escaping
9927        let esc = to_mathml(&var("a<b"));
9928        assert!(esc.contains("&lt;"), "{esc}");
9929    }
9930
9931    #[test]
9932    fn matrix_mul_eval_and_shapes() {
9933        use Value::Matrix;
9934        // [1 2; 3 4] × [5 6; 7 8] = [19 22; 43 50]
9935        let a = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0), num(4.0)]]);
9936        let b = Expr::Mat(vec![vec![num(5.0), num(6.0)], vec![num(7.0), num(8.0)]]);
9937        let prod = mul(a.clone(), b.clone());
9938        shape_check(&prod).unwrap();
9939        match eval_value(&prod, &HashMap::new()).unwrap() {
9940            Matrix(m) => {
9941                let got: Vec<Vec<f64>> =
9942                    m.iter().map(|r| r.iter().map(|c| c.re).collect()).collect();
9943                assert_eq!(got, vec![vec![19.0, 22.0], vec![43.0, 50.0]]);
9944                assert!(
9945                    m.iter().flatten().all(|c| c.is_real()),
9946                    "实数矩阵不应带虚部"
9947                );
9948            }
9949            _ => panic!("期望矩阵"),
9950        }
9951        // Transposed shape
9952        assert_eq!(shape_of(&transpose(a.clone())).unwrap(), Some((2, 2)));
9953        let row = Expr::Mat(vec![vec![num(1.0), num(2.0), num(3.0)]]);
9954        assert_eq!(shape_of(&transpose(row)).unwrap(), Some((3, 1)));
9955    }
9956
9957    #[test]
9958    fn matrix_shape_violations_rejected() {
9959        // 2×3 × 2×3 is not multipliable
9960        let a = Expr::Mat(vec![
9961            vec![num(1.0), num(2.0), num(3.0)],
9962            vec![num(4.0), num(5.0), num(6.0)],
9963        ]);
9964        let b = a.clone();
9965        let err = shape_check(&mul(a, b)).unwrap_err();
9966        assert_eq!(err.code(), "shape-mismatch", "{err}");
9967        // The payload names both factors, so assert it rather than merely the code.
9968        match &err {
9969            Error::ShapeMismatch(why) => {
9970                assert!(
9971                    why.contains("cannot multiply") && why.contains("2"),
9972                    "{why}"
9973                );
9974            }
9975            other => panic!("{other:?}"),
9976        }
9977        // Inconsistent shapes for addition
9978        let r2 = Expr::Mat(vec![vec![num(1.0)], vec![num(2.0)]]);
9979        let r3 = Expr::Mat(vec![vec![num(1.0)], vec![num(2.0)], vec![num(3.0)]]);
9980        assert_eq!(
9981            shape_check(&add(r2, r3)).unwrap_err().code(),
9982            "shape-mismatch"
9983        );
9984        // Jagged matrix
9985        let jag = Expr::Mat(vec![vec![num(1.0), num(2.0)], vec![num(3.0)]]);
9986        assert!(shape_of(&jag).is_err());
9987        // Matrix division is rejected explicitly
9988        let m = Expr::Mat(vec![vec![num(1.0)]]);
9989        let s = Expr::Mat(vec![vec![num(2.0)]]);
9990        assert_eq!(
9991            shape_check(&div(m, s)).unwrap_err().code(),
9992            "matrix-division-unsupported"
9993        );
9994    }
9995
9996    #[test]
9997    fn federate_inline_substitutes_in_order() {
9998        // a = x + 1; b = a * 2; c = b - a → substituted entry by entry
9999        let set = FormulaSet {
10000            decls: vec![Decl {
10001                name: "x".into(),
10002                quantity: "d".into(),
10003                unit: None,
10004            }],
10005            uses: vec![],
10006            items: vec![
10007                FormulaItem {
10008                    name: Some("a".into()),
10009                    expr: add(var("x"), num(1.0)),
10010                    line: 0,
10011                },
10012                FormulaItem {
10013                    name: Some("b".into()),
10014                    expr: mul(var("a"), num(2.0)),
10015                    line: 0,
10016                },
10017                FormulaItem {
10018                    name: Some("c".into()),
10019                    expr: sub(var("b"), var("a")),
10020                    line: 0,
10021                },
10022            ],
10023        };
10024        let fed = federate_inline(&set).unwrap();
10025        let mut env = HashMap::new();
10026        env.insert("x".to_string(), 3.0);
10027        // c = (x+1)*2 - (x+1) = 8 - 4 = 4
10028        assert_eq!(eval(&fed[2].expr, &env).unwrap(), 4.0);
10029        // The expression of b no longer references a
10030        assert!(!vars_of(&fed[1].expr).contains(&"a".to_string()));
10031    }
10032
10033    #[test]
10034    fn matrix_ctors_compile_shape() {
10035        let src = emit_matrix_ctor(
10036            "M",
10037            &MatrixKind::Tridiag {
10038                a: var("a"),
10039                b: var("b"),
10040                c: var("c"),
10041            },
10042        );
10043        assert!(
10044            src.contains("pub fn M(a: f64, b: f64, c: f64, n: usize)"),
10045            "{src}"
10046        );
10047        assert!(src.contains("m[__row][__next] = cv;"), "{src}");
10048        let src_i = emit_matrix_ctor("I", &MatrixKind::Identity);
10049        assert!(src_i.contains("pub fn I(n: usize)"), "{src_i}");
10050    }
10051
10052    #[test]
10053    fn cse_emits_shared_lets() {
10054        let shared = add(var("a"), var("b"));
10055        let e = add(mul(shared.clone(), shared.clone()), shared.clone());
10056        let code = emit_block(&e);
10057        assert_eq!(code.matches("let __t0 = a + b;").count(), 1, "{code}");
10058        // 1 definition + 3 uses
10059        assert_eq!(code.matches("__t0").count(), 4, "{code}");
10060    }
10061
10062    // ---------------- retired string-staging sites (the staging-budget H-10 batch) ----------------
10063    // Every laundering shape this batch retired must ALSO be pinned here: reverting the typed
10064    // construction back to a staged string has to go red in this file, not only at the gate
10065    // (the gate is the last line of defence, not the only one).
10066
10067    #[test]
10068    fn from_error_for_fronterror_is_field_identical_to_plain() {
10069        // The typed conversion must stay field-identical to `plain`: same rendered message,
10070        // same code, same zero origin position. The R3 mutation round moved line/col in the
10071        // impl and nothing went red — this pin makes that drift red.
10072        let cases = vec![
10073            Error::NotPolynomial { var: "x".into() },
10074            Error::Inconsistent,
10075            Error::MalformedUnit("m^3/2".into(), "detail".into()),
10076        ];
10077        for err in cases {
10078            assert_eq!(
10079                FrontError::from(err.clone()),
10080                FrontError::plain(err.clone()),
10081                "{err:?}"
10082            );
10083        }
10084    }
10085
10086    #[test]
10087    fn a_missing_eval_variable_is_undeclared_symbol() {
10088        let err = eval(&var("x"), &HashMap::new()).unwrap_err();
10089        assert_eq!(err.code(), "undeclared-symbol", "{err}");
10090        assert!(err.render(crate::i18n::Locale::En).contains("`x`"), "{err}");
10091    }
10092
10093    #[test]
10094    fn a_jagged_pattern_matrix_is_a_shape_mismatch_in_every_lane() {
10095        let p = pat(vec![vec![el(num(1.0)), el(num(2.0))], vec![el(num(3.0))]]);
10096        let err = recognize_pattern(&p).unwrap_err();
10097        assert_eq!(err.code(), "shape-mismatch", "{err}");
10098        let err = dim_check(&Expr::MatPattern(p), &HashMap::new()).unwrap_err();
10099        assert_eq!(err.code(), "shape-mismatch", "{err}");
10100    }
10101
10102    #[test]
10103    fn the_unit_exponent_grid_range_and_numerator_are_typed() {
10104        // The numerator must be an integer.
10105        let err = parse_ratio("3/x").unwrap_err();
10106        assert_eq!(err.code(), "malformed-unit", "{err}");
10107        // An exact p/q that does not fit the i16 half-integer grid.
10108        let err = parse_unit("s")
10109            .unwrap()
10110            .scale_ratio(2_000_000_000, 2)
10111            .unwrap_err();
10112        assert_eq!(err.code(), "exponent-out-of-range", "{err}");
10113        assert!(
10114            err.render(crate::i18n::Locale::En)
10115                .contains("dimension grid range"),
10116            "{err}"
10117        );
10118    }
10119
10120    #[test]
10121    fn each_dim_lane_symbol_lookup_is_undeclared_symbol() {
10122        let mut dims = HashMap::new();
10123        dims.insert("u".to_string(), parse_unit("Pa").unwrap());
10124        dims.insert("t".to_string(), Dim::ZERO);
10125        // ∂: the differentiation variable must be declared.
10126        let err = dim_check(&Expr::Deriv(Box::new(var("u")), "nope".into()), &dims).unwrap_err();
10127        assert_eq!(err.code(), "undeclared-symbol", "{err}");
10128        // ∫: the integration variable must be declared.
10129        let err = dim_check(
10130            &Expr::Integral {
10131                var: "nope".into(),
10132                lower: Box::new(var("t")),
10133                upper: Box::new(var("t")),
10134                body: Box::new(var("u")),
10135            },
10136            &dims,
10137        )
10138        .unwrap_err();
10139        assert_eq!(err.code(), "undeclared-symbol", "{err}");
10140        // a_{i,j}: the indexed symbol itself must be declared.
10141        let err = dim_check(
10142            &Expr::Indexed {
10143                name: "nope".into(),
10144                indices: vec!["i".into()],
10145            },
10146            &dims,
10147        )
10148        .unwrap_err();
10149        assert_eq!(err.code(), "undeclared-symbol", "{err}");
10150    }
10151
10152    #[test]
10153    fn mismatched_integral_bounds_are_a_dimension_mismatch() {
10154        let mut dims = HashMap::new();
10155        dims.insert("u".to_string(), parse_unit("Pa").unwrap());
10156        dims.insert("t".to_string(), Dim::ZERO);
10157        let err = dim_check(
10158            &Expr::Integral {
10159                var: "u".into(),
10160                lower: Box::new(var("t")),
10161                upper: Box::new(var("u")),
10162                body: Box::new(var("t")),
10163            },
10164            &dims,
10165        )
10166        .unwrap_err();
10167        assert_eq!(err.code(), "dimension-mismatch", "{err}");
10168    }
10169
10170    #[test]
10171    fn a_dimensional_argument_to_a_transcendental_is_rejected() {
10172        let mut dims = HashMap::new();
10173        dims.insert("u".to_string(), parse_unit("Pa").unwrap());
10174        let err = dim_check(&Expr::Call("sin".into(), vec![var("u")]), &dims).unwrap_err();
10175        assert_eq!(err.code(), "invalid-input", "{err}");
10176        assert!(
10177            err.render(crate::i18n::Locale::En)
10178                .contains("must be dimensionless"),
10179            "{err}"
10180        );
10181    }
10182
10183    #[test]
10184    fn elementwise_matrix_rows_must_agree() {
10185        let a = Expr::Mat(vec![vec![num(1.0), num(2.0)]]);
10186        let b = Expr::Mat(vec![vec![num(3.0)], vec![num(4.0)]]);
10187        let err = eval_value(&add(a, b), &HashMap::new()).unwrap_err();
10188        assert_eq!(err.code(), "shape-mismatch", "{err}");
10189        assert!(
10190            err.render(crate::i18n::Locale::En)
10191                .contains("rows disagree"),
10192            "{err}"
10193        );
10194    }
10195
10196    #[test]
10197    fn the_solve_and_inv_guards_are_typed_rejections() {
10198        // `solve` with a non-variable second argument.
10199        let eqs = Expr::Mat(vec![vec![add(var("x"), num(-1.0))]]);
10200        let junk = Expr::Mat(vec![vec![num(1.0)]]);
10201        let err = eval_value(
10202            &Expr::Call("solve".into(), vec![eqs.clone(), junk]),
10203            &HashMap::new(),
10204        )
10205        .unwrap_err();
10206        assert_eq!(err.code(), "invalid-input", "{err}");
10207        assert!(
10208            err.render(crate::i18n::Locale::En)
10209                .contains("second argument"),
10210            "{err}"
10211        );
10212        // `solve` whose equations are not linear in the unknown.
10213        let nonlin = Expr::Mat(vec![vec![Expr::Call("sin".into(), vec![var("x")])]]);
10214        let unknowns = Expr::Mat(vec![vec![var("x")]]);
10215        let err = eval_value(
10216            &Expr::Call("solve".into(), vec![nonlin, unknowns.clone()]),
10217            &HashMap::new(),
10218        )
10219        .unwrap_err();
10220        assert_eq!(err.code(), "invalid-input", "{err}");
10221        assert!(
10222            err.render(crate::i18n::Locale::En).contains("linear"),
10223            "{err}"
10224        );
10225        // `solve` whose first argument is not a list of equations.
10226        let err = eval_value(
10227            &Expr::Call("solve".into(), vec![var("x"), unknowns.clone()]),
10228            &HashMap::new(),
10229        )
10230        .unwrap_err();
10231        assert_eq!(err.code(), "invalid-input", "{err}");
10232        let big = Expr::Mat(vec![
10233            vec![num(1.0), num(0.0), num(0.0), num(0.0)],
10234            vec![num(0.0), num(1.0), num(0.0), num(0.0)],
10235            vec![num(0.0), num(0.0), num(1.0), num(0.0)],
10236            vec![num(0.0), num(0.0), num(0.0), num(1.0)],
10237        ]);
10238        let err = eval_value(&Expr::Call("inv".into(), vec![big]), &HashMap::new()).unwrap_err();
10239        assert_eq!(err.code(), "invalid-input", "{err}");
10240        assert!(
10241            err.render(crate::i18n::Locale::En).contains("order 1 to 3"),
10242            "{err}"
10243        );
10244        let _ = eqs;
10245    }
10246    // ---------------- coverage pins for the ledger's remaining H items ----------------
10247    // Each catalogued branch that the staging gate was the ONLY pin for gets a behavior test
10248    // here: the branch's identity is asserted by `code()` plus a distinctive fragment, so
10249    // reverting the construction goes red in this file.
10250
10251    #[test]
10252    fn a_zero_argument_call_names_the_function() {
10253        // H-4a: the arity is unknown before the function is identified, so the message claims
10254        // only what is true (`FunctionArity { expected: 1 }` lied for every multi-argument fn).
10255        let err = eval_value(&Expr::Call("max".into(), vec![]), &HashMap::new()).unwrap_err();
10256        assert_eq!(err.code(), "invalid-input", "{err}");
10257        assert!(err.render(i18n::Locale::En).contains("`max`"), "{err}");
10258        let dims = HashMap::new();
10259        let err = dim_check(&Expr::Call("sin".into(), vec![]), &dims).unwrap_err();
10260        assert_eq!(err.code(), "invalid-input", "{err}");
10261        assert!(err.render(i18n::Locale::En).contains("`sin`"), "{err}");
10262    }
10263
10264    #[test]
10265    fn an_empty_unit_string_and_a_zero_scale_denominator_are_typed() {
10266        // H-3: both branches were pinned only by the staging gate before this test.
10267        let err = parse_unit_spec("").unwrap_err();
10268        assert_eq!(err.code(), "malformed-unit", "{err}");
10269        assert!(
10270            err.render(i18n::Locale::En).contains("empty unit string"),
10271            "{err}"
10272        );
10273        let err = convert(1.0, "", "m").unwrap_err();
10274        assert_eq!(err.code(), "malformed-unit", "{err}");
10275        let err = parse_unit("m").unwrap().scale_ratio(1, 0).unwrap_err();
10276        assert_eq!(err.code(), "exponent-zero-denominator", "{err}");
10277    }
10278
10279    #[test]
10280    fn trace_rejects_a_non_square_matrix() {
10281        // H-5: the squareness guard.
10282        let m = Expr::Mat(vec![
10283            vec![num(1.0), num(2.0)],
10284            vec![num(3.0), num(4.0)],
10285            vec![num(5.0), num(6.0)],
10286        ]);
10287        let err = eval_value(&Expr::Call("trace".into(), vec![m]), &HashMap::new()).unwrap_err();
10288        assert_eq!(err.code(), "shape-mismatch", "{err}");
10289        assert!(err.render(i18n::Locale::En).contains("square"), "{err}");
10290    }
10291
10292    #[test]
10293    fn incompatible_units_reports_its_code() {
10294        // H-5: the code string had no pin (renaming it left `cargo test` green).
10295        let err = convert(1.0, "nF", "V").unwrap_err();
10296        assert_eq!(err.code(), "incompatible-units", "{err}");
10297        assert!(
10298            err.render(i18n::Locale::En).contains("cannot convert `nF`"),
10299            "{err}"
10300        );
10301    }
10302
10303    #[test]
10304    fn the_shape_lane_rejects_matrix_division_itself() {
10305        // H-5: the `shape_check` `Div` branch — the runtime site had a test, this lane did not.
10306        let a = Expr::Mat(vec![vec![num(2.0), num(4.0)]]);
10307        let b = Expr::Mat(vec![vec![num(2.0), num(2.0)]]);
10308        let err = shape_check(&div(a, b)).unwrap_err();
10309        assert_eq!(err.code(), "matrix-division-unsupported", "{err}");
10310        assert!(err.render(i18n::Locale::En).contains("inv(A) * b"), "{err}");
10311    }
10312
10313    #[test]
10314    fn quad_root_arity_guards_bite_in_both_lanes() {
10315        // H-6: the two `__quad_root_*` arity guards (evaluation and dimension lanes).
10316        let dims = HashMap::new();
10317        let one = eval_value(
10318            &Expr::Call("__quad_root_1".into(), vec![var("x")]),
10319            &HashMap::new(),
10320        )
10321        .unwrap_err();
10322        assert_eq!(one.code(), "function-arity", "{one}");
10323        let four = eval_value(
10324            &Expr::Call(
10325                "__quad_root_2".into(),
10326                vec![var("x"), var("y"), var("z"), var("w")],
10327            ),
10328            &HashMap::new(),
10329        )
10330        .unwrap_err();
10331        assert_eq!(four.code(), "function-arity", "{four}");
10332        let one_d =
10333            dim_check(&Expr::Call("__quad_root_1".into(), vec![var("x")]), &dims).unwrap_err();
10334        assert_eq!(one_d.code(), "function-arity", "{one_d}");
10335        let four_d = dim_check(
10336            &Expr::Call(
10337                "__quad_root_2".into(),
10338                vec![var("x"), var("y"), var("z"), var("w")],
10339            ),
10340            &dims,
10341        )
10342        .unwrap_err();
10343        assert_eq!(four_d.code(), "function-arity", "{four_d}");
10344    }
10345
10346    #[test]
10347    fn sum_bounds_must_be_dimensionless() {
10348        // H-6: the sum-bound guard.
10349        let mut dims = HashMap::new();
10350        dims.insert("u".to_string(), parse_unit("Pa").unwrap());
10351        dims.insert("t".to_string(), Dim::ZERO);
10352        let err = dim_check(
10353            &Expr::Sum {
10354                var: "u".into(),
10355                lower: Box::new(var("t")),
10356                upper: Box::new(var("u")),
10357                body: Box::new(var("t")),
10358            },
10359            &dims,
10360        )
10361        .unwrap_err();
10362        assert_eq!(err.code(), "invalid-input", "{err}");
10363        assert!(
10364            err.render(i18n::Locale::En).contains("dimensionless"),
10365            "{err}"
10366        );
10367    }
10368
10369    #[test]
10370    fn an_unknown_function_in_the_dim_lane_falls_back_without_suggestion() {
10371        // H-6: the dim lane's `UnknownFunction` fallback (the eval lane's typo path was pinned;
10372        // this lane's was not). The fallback constructs an empty suggestion on purpose.
10373        let mut dims = HashMap::new();
10374        dims.insert("t".to_string(), Dim::ZERO);
10375        let err = dim_check(&Expr::Call("no_such_fn".into(), vec![var("t")]), &dims).unwrap_err();
10376        assert_eq!(err.code(), "unknown-function", "{err}");
10377        let Error::UnknownFunction { name, suggestion } = &err else {
10378            panic!("{err:?}")
10379        };
10380        assert_eq!(name, "no_such_fn");
10381        assert!(suggestion.is_empty(), "{suggestion:?}");
10382    }
10383
10384    #[test]
10385    fn a_nonlinear_product_names_the_unknowns_it_involves() {
10386        // The name slot takes unknowns, not operations: "not linear in `x`" / "in `x, y`".
10387        let err =
10388            solve_system(&[sub(mul(var("x"), var("x")), num(1.0))], &["x".into()]).unwrap_err();
10389        let en = err.render(i18n::Locale::En);
10390        assert!(en.contains("not linear in `x`"), "{en}");
10391        assert!(!en.contains("the product"), "{en}");
10392        // Two different unknowns are both named, in declaration order.
10393        let err = solve_system(
10394            &[sub(mul(var("x"), var("y")), num(1.0))],
10395            &["x".into(), "y".into()],
10396        )
10397        .unwrap_err();
10398        let en = err.render(i18n::Locale::En);
10399        assert!(en.contains("not linear in `x, y`"), "{en}");
10400        // A declared unknown that the product does NOT mention must not be named: without this
10401        // case, "name every declared unknown" and "name the involved ones" are
10402        // indistinguishable (a mutation dropping the `has_var` filter survived until it existed).
10403        let err = solve_system(
10404            &[sub(mul(var("x"), var("x")), num(1.0))],
10405            &["x".into(), "z".into()],
10406        )
10407        .unwrap_err();
10408        let en = err.render(i18n::Locale::En);
10409        assert!(en.contains("not linear in `x`"), "{en}");
10410        assert!(!en.contains("`x, z`"), "{en}");
10411    }
10412
10413    #[test]
10414    fn solve_system_names_the_failing_equation_in_both_frames() {
10415        // H-7: "which equation" is back — without downgrading the inner variant to a `Message`.
10416        let linear = sub(var("x"), num(1.0));
10417        let nonlinear = mul(var("x"), var("y")); // x·y is linear in neither unknown alone
10418        let err = solve_system(&[linear, nonlinear], &["x".into(), "y".into()]).unwrap_err();
10419        assert_eq!(err.code(), "in-equation", "{err}");
10420        let en = err.render(i18n::Locale::En);
10421        assert!(en.contains("in equation 2:"), "{en}");
10422        assert!(en.contains("not linear in"), "{en}");
10423        // The composed variant re-renders the INNER message in the target locale: frame and
10424        // inner are Japanese together (the property the retired `map_err`-to-`String` design
10425        // could not provide).
10426        let ja = err.render(i18n::Locale::Ja);
10427        assert!(ja.contains("2 番目の方程式:"), "{ja}");
10428        assert!(ja.contains("線形ではありません"), "{ja}");
10429        // `in_locale` goes through the same composite path (`FrontError::render_in`).
10430        let front = FrontError::plain(err);
10431        let ja_front = front.in_locale(i18n::Locale::Ja);
10432        assert!(
10433            ja_front.msg.contains("線形ではありません"),
10434            "{}",
10435            ja_front.msg
10436        );
10437    }
10438
10439    #[test]
10440    fn in_equation_renders_the_inner_in_the_target_locale() {
10441        let composed = Error::InEquation {
10442            index: 3,
10443            error: Box::new(Error::UndeclaredSymbol("k".into())),
10444        };
10445        assert_eq!(composed.code(), "in-equation");
10446        let ja = composed.render(i18n::Locale::Ja);
10447        assert!(ja.contains("3 番目の方程式:"), "{ja}");
10448        assert!(ja.contains("`k`"), "{ja}");
10449        let en = composed.render(i18n::Locale::En);
10450        assert!(en.contains("in equation 3:"), "{en}");
10451        assert!(en.contains("`k`"), "{en}");
10452    }
10453    #[test]
10454    fn the_eval_lane_refuses_operators_and_patterns_with_typed_variants() {
10455        // Two sites used to launder `("…".to_string()).into()` into `Error::Message` (the
10456        // `From<String>` channel the gate cannot type-check). They are `UnsupportedOperation`
10457        // now, and the payload renders in every locale.
10458        let err = eval_value(&Expr::Grad(Box::new(var("u"))), &HashMap::new()).unwrap_err();
10459        assert_eq!(err.code(), "unsupported-operation", "{err}");
10460        assert!(
10461            err.render(i18n::Locale::En).contains("symbolic operators"),
10462            "{err}"
10463        );
10464        let p = pat(vec![vec![el(num(1.0)), D], vec![D, el(num(1.0))]]);
10465        let err = eval_value(&Expr::MatPattern(p), &HashMap::new()).unwrap_err();
10466        assert_eq!(err.code(), "unsupported-operation", "{err}");
10467        assert!(
10468            err.render(i18n::Locale::En).contains("pattern matrices"),
10469            "{err}"
10470        );
10471    }
10472
10473    #[test]
10474    fn a_diverging_dk_iteration_is_catalogued() {
10475        // H-9a: the DK inf/NaN divergence arm had no input reaching it — `1e308 + x²` blows the
10476        // iteration up immediately (a leading coefficient at the f64 ceiling makes every
10477        // intermediate non-finite).
10478        let err = numeric_roots(&[1e308, 0.0, 1.0]).unwrap_err();
10479        assert_eq!(err.code(), "root-finding-failed", "{err}");
10480        let en = err.render(i18n::Locale::En);
10481        assert!(en.contains("inf/NaN"), "{en}");
10482    }
10483}