
Himari
Formula assets: one source of truth, three surfaces, compiled into Rust.
NOTICE: This software includes code generated by artificial intelligence. See the LICENSE file for the Synthetic Source License terms, including model disclosure requirements. Every line of source in this repository was generated by AI models under human direction; not one line was written by hand. The models involved are listed at the end of LICENSE.txt. Every capability claimed in this README is backed by tests in this repository and went through six rounds of independent adversarial review — but AI review is not a substitute for human review, and as of writing the mathematical content has not been reviewed by a mathematician. The name comes from Himari Akayama (Millennium Science School · Veritas) of Blue Archive — turning ideas into machines that run. Neither the crates.io name nor the org repo name collides with anything (checked 2026-11-23).
What this is
- You write one formula (LaTeX subset / paper notation / MATLAB style, your pick); it lowers to the same dimensioned IR, then compiles into a Rust function with named intermediates and source comments.
- Dimensions (the seven base quantities kg·m·s·A·K·mol·cd) are enforced at compile time: m + s simply does not compile.
- Symbolic differentiation, CSE and constant folding are built in; analytic partials are pinned by tests against central differences.
- Matrices are first-class: concrete matrices are fully checked; pattern matrices (with ellipses) express dynamic sizes — the textbook [b c ⋯ 0; a b c ⋯; ⋯ a b c; 0 ⋯ a b] is source code as written.
Federation and multi-line writing (second ruling of 2026-11-23)
One macro block can hold a whole group of formulas that reference each other ("federation"):
formula_matlab!
// expands to a let chain: let accel = F / m; let mech = (accel * r).sqrt(); mech
- Item separator = semicolon or newline, and this holds in all three lanes (the token lane reconstructs newlines from proc-macro span line numbers, and those line numbers are aligned to the source file, so diagnostics point at the same line).
- Later items may reference earlier ones: dimensions propagate with the name (accel's m/s² joins the symbol table); the build.rs lane inlines the substitution at generation time.
- The name is the contract: when a formula reuses a decl name, its result dimension must match that declaration (a = F/m is fine, s : Pa; s = F/d is rejected); duplicate formula names within one formula set or one generation directory are always rejected.
- Operator continuation model: operators must sit at end of line (x +⏎ y ✓); a leading -/+ on the next line starts a new item's sign, it is not a line-continued subtraction — that is the disambiguation ruling.
- Implicit multiplication (juxtaposition) on the LaTeX surface must stay on one line: juxtaposing across lines swallows the next formula as a multiplicative term.
Matrix multi-line writing (one physical line per row; column spacing is free, no alignment required):
[ 2*k, -k, ..., 0 ;
-k, 2*k, -k, ... ;
..., -k, 2*k, -k ;
0, ..., -k, 2*k ]
- Row separator = ; or newline (mixable, optionally trailing); column separator = comma or space (≥1, any number).
- An ellipsis ... / ⋯ / … in a cell means "omitted at that position" (horizontal/vertical/diagonal is inferred when writing back).
- A - written without a space before it is a sign, a preceding space starts a new column (MATLAB semantics): [k-1] is one column, [k -1] is two.
Complex numbers: piped end to end from the value layer to code generation (2026-11-23)
- j is the reserved imaginary unit (always dimensionless, never declared, never in the parameter list). Z = R_s + j*X is writable directly.
- The value layer has exactly two variants: Value::Scalar(C) / Value::Matrix(Vec<Vec<C>>), with C = {re, im}. A real number is a complex number with a zero imaginary part ⇒ complex matrices, transposition, multiplication, addition and subtraction are all elementwise true for free; there is no need for a "real matrix / complex matrix" quadrant split.
- Transcendental functions share one table for real and complex: exp ln sqrt sin cos tan sinh cosh tanh + abs arg conj re im (the last four always land back on the real axis). Complex powers go through exp(w·ln z) on the principal branch.
- eval reports an explicit error on complex values (it does not quietly drop the imaginary part); use eval_value whenever you want complex values.
- Code generation has a separate complex lane: when a formula contains j it is emitted as -> (f64, f64) = (real, imaginary), and of the block-local helpers (__c_mul / __c_sqrt …) only the ones actually used are emitted (otherwise clippy -D warnings goes red). The batch entry is out: &mut [(f64, f64)], directly usable for EIS frequency sweeps. The macro lane (formula! etc.) triages the same way: j does not degrade into a free variable at the call site; a binding that is already complex inside a federated let chain is inherited correctly (emit_block_complex_with). The complex lane does not generate analytic derivatives: abs/arg/conj/re/im are not complex-analytic, so the chain rule does not hold.
- Generated code and the value layer must agree point by point is a hard constraint: __c_powf copies C::pow_real's integer triage (an integer power of a negative real base must land exactly on the real axis), and __c_sqrt uses hypot like the value layer to avoid overflow at large magnitudes; that __c_div follows IEEE while the value layer errors is deliberate — each of these is guarded by a per-operator comparison test in the fixtures.
- Unit strings accept rational exponents: [V/A*s^(-1/2)] (the brackets are mandatory — otherwise the / in the exponent cannot be told apart from the division sign of the unit string); an exponent that does not divide evenly (m^(1/3)) is rejected explicitly. Write [1] for a dimensionless quantity (gain / count / mole fraction must all be declarable; they may not smuggle themselves in by "omitting the unit").
- himari-fmt --diff <file>: read-only preview that prints a --- current / +++ canonical unified diff (no change → no output and exit 0; changes → exit 1).
- The semantic boundary between real and complex (deliberate, not an oversight): 1/0 used to give inf and now errors; ln(0) likewise; (-2)^0.5 reports "the result is complex, use eval_value". Generated code follows IEEE semantics instead (division by zero gives inf/NaN): the hot path carries no error path, and anything the formula layer can statically prove wrong is caught by the dim/shape gates.
- python3 scripts/fmt_check.py --fix: one command to re-lay out the canonical form and regenerate the sidecars.
Units: SI prefixes, conversion, dimensionless groups (2026-11-23)
- Look up the full name before splitting a prefix: m is the metre (not "milli-nothing"), mol is the mole, cd is the candela, daN is the decanewton (longest prefix wins). nF / GHz / mm^2 / mV/mm / µF / Ω all work. The derived units cover the six electronics cannot avoid: F Ω (or ohm) S H Wb T.
- Dimension and conversion factor are stored separately: parse_unit gives only the dimension; parse_unit_spec additionally gives the →SI conversion factor; convert(v, "nF", "F") = 1e-9 F, and a dimension mismatch errors out. The mass base unit is kg: g = 1e-3 kg, mg = 1e-6 kg, Mg = 1000 kg; prefixes count from the gram (pinned by a regression test). Parameters of generated functions are always SI base units, a prefix in the declaration only affects readability — the doc comment of the generated code spells out the conversion factor per parameter (quoted verbatim from a real generated doc comment: ⚠ 参数 C_dl 声明为 µF:入参是 SI 基单位(1 µF = 0.000001 …)).
- CGPM 2022 prefixes are in the table: Q (1e30), R (1e27), r (1e-27), q (1e-30), alongside the existing da … Y / d … y.
- Non-SI units with exact definitions (unit_base carries each factor so convert stays dimensionally honest): min, h, d, L (or l; mL decomposes as a prefix on L), deg, arcmin, arcsec, bar, atm, eV, Wh, tonne, Da (or u), nmi, knot, ha, acre.
- Offset / logarithmic units are rejected explicitly: degC (offset) and dBm (a ratio) are stopped before prefix splitting, reporting the "true cause" rather than "unknown unit" — silently treating them as K or as dimensionless computes the wrong value. Ambiguous symbols are rejected the same way, not guessed: cal / Cal differ between the thermochemical (4.184 J) and IT (4.1868 J) calories, so both are refused with a pointer to write J; rpm needs an angle axis (1 rpm = 2π/60 rad/s) while this facility treats rad as dimensionless, so it is refused with a pointer to write 2 * pi * f with a [Hz] declaration.
- Dimensionless groups (Buckingham Π): dimensionless_groups eliminates with exact rationals (f64 drifts), and gives the dimensionless combinations of a basis directly from "variable names + dimensions"; the count = (number of variables) − rank (Π theorem as an assertion). The classic check: {rho, v, L, mu} → 1 group rho·v·L·mu^-1 (the Reynolds number). dim_solve is the inhomogeneous use of the same system: {kg, m/s²} → N gives exponents [1, 1], and a dimension that cannot be formed reports "cannot form it" plus how many dimensions are short.
Dimensions: half-integer exponents (2026-11-23)
Dim stores internally in units of 1/2 ([i16;7] holds twice the true exponent), so fractional and integral powers go through the same integer arithmetic: √s = s^(1/2), f^(-1/2), Ω·s^(-1/2) are all legal, and display uses the parenthesised form like s^(-7/2). The Warburg impedance therefore returns to the textbook form Z = σ·f^(-1/2), with no reference-frequency non-dimensionalisation needed. dim_check's power exponent folds constants first, so the natural writing f ^ (1/2) passes the gate without calling simplify first.
Function families: extremum / clamp / matrix operators (2026-11-23)
The single source of truth for function arity is func_arity (in core); all four lanes (arity check / evaluation / dimension / emission / write-back) consult it — previously each lane carried its own match, which is how "arg emitted as a nonexistent method in the real lane" survived a release.
| family | functions | notes |
|---|---|---|
| unary scalar | exp ln log sqrt sin cos tan sinh cosh tanh | the same table for real and complex |
| complex | abs arg conj re im | arg is dimensionless; in the real lane re/im/conj are the identity |
| extremum/clamp | min(a,b) max(a,b) clamp(v,lo,hi) | same shape as Rust: v.max(lo).min(hi); all three arguments must share one dimension |
| matrix operators | det trace adjoint inv | only accept concrete matrix literals; det/inv up to order 4/3 (enough for both 2D and 3D isoparametric elements), adjoint = conjugate transpose |
det/inv use cofactor recursion (det ≤ 4, inv ≤ 3): enough for the isoparametric maps of 2D triangles and 3D tetrahedra, with numerical checks for J·J⁻¹ = I and det(J)=1; a 4×4 inverse would need 16 3×3 cofactors (≈100 terms) and would blow up the generated code, so it is rejected explicitly with a pointer to a numerical library. det/trace expand before differentiating in diff — the expansion is an ordinary differentiable expression, so FEM's area = det(J)/2 has both a value and an analytic derivative (∂area/∂x₂ = (y₃-y₁)/2). The piecewise selection in min/max/clamp is not expressible in the IR (there is no comparison operator), so no derivatives are generated; a comment line in the generated code explains why (it no longer panics). Extremum and clamp follow f64::min/max's NaN rule (they may return the other operand); callers that require NaN to propagate should check is_finite at the boundary.
Built-in shapes at a glance
identity / diag(d) / diag_v(d[i]) / tridiag(a,b,c) / tridiag_v(b[i]) / bidiag_u(b,c) / bidiag_l(a,b) / blockdiag2(p,q) = diag(p·I₂, q·I₂) / banded(v, k) = symmetric banded with half-bandwidth k (k=2 is only unambiguous from 5×5; at 4×4 it degenerates into a dense matrix).
These names describe the recognised IR shape; they are not functions you can call from a formula. The entry point is the matrix sketch with ellipses, and anything unrecognised is rejected explicitly.
Block diagonal semantics inside a block = scalar × identity (p on the diagonal, off-diagonal inside the block empty), outside the blocks must be empty (0 and ... are equivalent); with an odd total dimension the centre cell goes to the bottom-right block.
Complex-lane performance: the honest side (measured 2026-11-23)
bin/bench.rs now measures four lanes. The complex one, Z_c (EIS frequency sweep), is slower than hand-written; recorded as-is:
| form | ns/point | relative to hand-written |
|---|---|---|
| hand-written specialisation (σ/√ω·e^{-jπ/4}, branch-free, vectorisable) | 2.3 | 1× |
| same-form transcription (the generated code's operator sequence copied into one loop) | 2.9 | 1.3× |
| generated code · scalar direct call | 6.4 | 2.8× |
| generated code · batch entry | 12.8 | 5.5× |
Breakdown: the generic complex √/÷ costs about 2.2× more than the hand-written specialisation (1 sqrt vs 3 sqrt + one division), and the batch wrapper costs about 2.5× more again (tuple-slice writes + branching keep the loop from vectorising).
Optimisations already done (each one genuinely narrowed the gap):
- __c_sqrt went from polar form (atan2+cos+sin, 4 transcendental functions) to an algebraic closed form;
- pure-imaginary fast path √(iy) = √(|y|/2)(1+sign·j) (just 1 sqrt — the everyday shape in EIS);
- __c_div uses the naive form at ordinary magnitudes (1 division);
- the complex helpers moved from closures to block-local #[inline(always)] fn (15.5 → 11.9 ns/point).
Conclusion (written into the README instead of hidden): the complex lane is good for "computes correctly + fast enough", and is not worth chasing the limit of a hand-written specialisation; for the genuinely hot loop of an EIS sweep, hand-write the specialisation and keep the formula in the .formula file as the source of truth and dimension check. The real lane does not have this problem (scalar 1.11×, on par with hand-written).
Batch entries: fixed length wins, slices lose (measured)
The generator emits two batch entries per formula:
| form | signature | measured (BV, 100k points) |
|---|---|---|
| slice version | bv__batch(p0: &[f64], …, out: &mut [f64]) | 24.1 ns/point = 0.82× of scalar (22% slower) |
| fixed-length version | bv__batch_n<const N: usize>(p: &[f64; N], …, out: &mut [f64; N]) | 19.3 ns/point = 1.03× of scalar (3% faster) |
Conclusion: if you want performance, put the length into a type parameter. The slice version's eight per-point bounds checks sit inside the loop and LLVM cannot fully elide them; computing the common length once (a .min() chain) or switching to zip iterators only reaches 0.83×. The slice version is kept as the convenient form (variable-length data); use the fixed-length version on hot paths. (bench source: fixtures/three/src/bin/bench.rs; the two methodology traps we hit — building vectors inside the timed region, and constant vectors letting the scalar path be constant-folded — are recorded in the source comments.)
Matrix algebra (shape + evaluation + generation)
Dimensions and shapes are two orthogonal checking axes: dimensions govern physical meaning, shapes govern algebraic legality.
| capability | behaviour |
|---|---|
| shape_of | concrete matrix → (rows, cols); transpose swaps; symbolic/pattern matrix → None (no dynamic inference) |
| shape_check | matrix add/sub requires equal shapes, matrix product requires left cols = right rows, jagged matrices rejected, matrix division rejected explicitly |
| eval_value | unified evaluation of scalars/matrices, matrix product as C_ij = Σ_k A_ik·B_kj |
| flatten_matrix_value | folds a statically expandable matrix expression into a concrete matrix IR (transpose/add/sub/negate/scalar broadcast/matrix product) |
| emission | a folded matrix → a vec![vec![…], …] constant literal; large matrices go through the pattern-matrix + loop lane |
[1, 2; 3, 4] * [5, 6; 7, 8] → [[19.0, 22.0], [43.0, 50.0]]
[1, 2, 3]' → 3×1 column vector (emitted as vec![vec![1.0], vec![2.0], vec![3.0]])
A * [1, 2] → scalar broadcast (a bare symbol is a scalar: matrices only come from literals/pattern generators)
[1, 2, 3] * [1, 2, 3] → compile-time rejection: matrix multiply impossible: (1, 3) × (1, 3)
Generic runtime A,b still has to be declared as such: decl names with a quantity ending in _matrix/_vector (or equal to matrix/vector) become matrix/vector parameters, which is what the runtime lane below uses. Every other bare symbol is a scalar, so A * x over matrices whose shapes are not part of the declaration is still expressed with literals, statically expandable expressions, or pattern generators. For general large-scale Ax=b, runtime size inference, or ill-conditioned systems, use a numerical linear algebra library.
Non-negative integer matrix powers: [a, b; c, d] ^ 2 is folded by the generator into explicit matrix multiplications (0–8 times), M ^ 0 is the identity matrix of the same order (the return type is still a matrix, not the scalar 1). The end-to-end numerical check is in matrix_power.formula. A failed fold (negative/fractional power, out of range, non-square) emits compile_error! rather than a compile accident like vec![…] * vec![…]; the value layer (himari-eval) gives the same result for the same form.
Two independent implementations must agree: matrix expression code generation (flatten_matrix_value + literal emission) and value-layer evaluation (eval_value) are written separately, so a differential test keeps the two sides aligned — evaluating the folded literal must equal evaluating the unfolded expression cell by cell (mat-expr-fold).
A matrix sketch without ellipses is a concrete matrix: it goes through the literal lane (constants fold, no allocation loop), which beats the generator; to use the generator lane (where n is a runtime parameter) you must write the ellipses.
The runtime matrix/vector lane (2026-11-23)
Everything above is static: shapes are known when the formula compiles. The runtime lane is the separate answer for parameters whose sizes only exist at run time — a solver consuming user data, an FEM assembly, anything that receives A and b as values.
- Declaration is the only switch: a decl whose quantity ends in _matrix/_vector (or equals matrix/vector) becomes a matrix/vector parameter — A : stiffness_matrix [N/m] arrives as &[Vec<f64>], b : load_vector [N] as &[f64]. Names that never opt in stay scalars, so existing formulas are unaffected (Decl::runtime_kind).
- Generated functions are fallible: they return Result<_, himari::runtime::NumericError>, an alias of the crate's single error enum himari::Error (InvalidInput / ShapeError / NonFiniteValue / SingularMatrix / IllConditioned / UnstableResidual / NoRealRoots). There is no silent NaN contract on this lane.
- solve(A,b) is LU with partial pivoting, then two independent gates before any answer is returned: an rcond estimate (1/(‖A‖∞·‖A⁻¹‖∞), requiring rcond ≥ f64::EPSILON·64·n) and a relative residual check (≤ 1e-9). The inverse is formed only for the condition estimate, never as the way x is obtained. A singular pivot, an ill-conditioned matrix and a solution with a large residual are three distinct errors, not one "failed".
- Also supported on this lane: inv, det (literal arguments only — a runtime det is rejected because its dimension needs a static matrix order), A*x, dot, norm, and indexing with A(i, j) using 1-based indices ([I,J]; out-of-range and zero are errors, not panics).
- What it emits: the body is a checked expression over in-scope let chains inside the generated function, and the return type follows the value kind (Result<f64, _>, Result<Vec<f64>, _>, Result<Vec<Vec<f64>>, _>). Runtime-lane formulas emit no analytic Jacobian, no __f32 variant and no batch entries (those need a scalar, sized signature).
- Answers are checked against independent references: runtime_matrix.formula verifies solve(A,b) against a separate pivoted Gaussian elimination, A*x against b, A·inv(A) against the identity columns, one-based indexing, and a deliberately tiny-epsilon system ([[1e-17, 1], [1, 1]]) that only pivoting gets right — all to 2e-12/2e-15 tolerances.
- Macro lane: formula_matlab! accepts runtime formulas too, but only one formula per block (a runtime chain stays on the build.rs lane with an explicit message); complex runtime matrix parameters are refused for now.
Code generation quality (2026-11-23)
- Integer powers emit powi: x^3 → (x).powi(3) (previously it emitted a nonexistent internal method, so any x^3 failed to compile with the error pointing into the generated code). The fixture has a compile gate for x^3.
- Unknown functions fail at compile time: the real lane's functions are a whitelist; arg(x) is meaningless over the reals → compile_error!; re/im/conj are the identity over the reals (exact, not approximate). Multi-argument calls are rejected at parse time (the emitter only looked at args[0], and silently dropping the rest computes a wrong value).
- System Jacobian: each .formula file additionally produces {filename}__jacobian(all params), rows = real scalar formulas that participate in differentiation (matrix-valued / complex / non-differentiable items are skipped), columns = parameters (declaration order), and a row that does not depend on a parameter is 0 in that column throughout. This is the shape implicit solvers / Newton iterations / FEM assembly need.
- Non-finite constants fail hard: emitting inf / NaN would produce an illegal identifier, so it panics before generation with the origin named (contains_nan_expr is the single source of truth).
- Parentheses around powers: (x^2)^3 and x^(2^3) get parentheses on both surfaces — x ^ 2 ^ 3 re-parses as (x^2)^3 (x⁸ → x⁶, i.e. canonical formatting would change the mathematics).
Formatting (canonical)
himari-fmt: cargo run -p himari-check --bin himari-fmt -- [--check|--write] <file>.
- Multi-line decls (one symbol per line); one formula per line; matrix columns aligned (each column = widest content + ≥1 space, comma as the column boundary).
- Standalone comment lines all float to the head of the file (order preserved) — comments are for humans and never enter the IR.
- --check = the drift gate (wired into just fmt-check / CI); canonical output is round-trip idempotent.
- Canonical keeps the commas: space-only separation and binary subtraction are indistinguishable on write-back (-k would be swallowed as a subtraction term), so the comma is the unambiguous boundary; writing without commas by hand is fine, formatting puts them back.
Lanes (user ruling of 2026-11-23)
| lane | usage | suitable for |
|---|---|---|
| inline macro | formula_matlab!{ decl { a : l [m]; b : l [m]; } a / b } | simple formulas |
| string macro | formula_latex!{ r"decl { … } \frac{a}{b}" } | simple formulas (LaTeX surface) |
| external file macro | formula_file!("formulas/bv.formula", matlab) | complex formulas (the dialect must be given explicitly) |
| build.rs | see packages/check/fixtures/three/ | checked-in generated code + drift gate (the formal lane) |
decl inside a macro only supplies symbol information for the dimension check; it does not create Rust local variables: a/b at the call site must already be let a = …; let b = …; by the caller. For a complete compilable example see inline_macro_example() in examples/common/src/main.rs.
⚠️ Known limitation: a proc-macro reading files is not tracked by cargo (tracked_path is still nightly), so after editing a .formula you need a touch to trigger a rebuild; for production use the build.rs lane (rerun-if-changed). ⚠️ The constructor lane for pattern matrices/transposes only exists for files / build.rs (it needs a filename and a generator); inline macros report an explicit error with a pointer when they meet them, they never degrade silently.
Surface languages (three, one IR)
| paper | LaTeX | MATLAB style | |
|---|---|---|---|
| Greek letters | α·x | \alpha \cdot x | alpha*x |
| ellipsis | ⋯ … | \cdots \vdots \ddots | ... |
| matrix | [a, ⋯, b; ⋮ ⋱ ⋮; c, ⋯, d] | \begin{bmatrix}…\end{bmatrix} | [a, ..., b; ...] |
| transpose | A', A′, A^T | A^T | same as left |
| dimension decls | decl { v : velocity [m/s]; } | same as left | same as left |
Rules (rejection is a feature):
- Every symbol must be declared with its dimension first; undeclared = compile error, no glyph inference.
- Ambiguous or purely typographic notation such as \sin^2 x, \left(\right), $…$, x .* y is rejected outright.
- Implicit multiplication holds only on the LaTeX/paper surfaces (the single-letter system is unambiguous by construction); the MATLAB surface requires an explicit *.
- Pattern matrices only support three provably correct shapes: identity(n), diag(d, n), tridiag(a, b, c, n); anything unrecognised = error + a list of those three.
- Sources may be handwritten (combining marks and so on), but the IR must be normalised — combining characters never enter the IR.
Vector algebra / Horner / no_std (2026-11-23)
dot(a,b) / norm(v): expanded only on concrete literals (shape known at compile time); dot's dimension is the product of both sides, norm has the same dimension as its elements. dot([x,y],[x,y]) (x=3,y=4) → 25, norm → 5. Mismatched shapes are rejected outright.
Automatic Horner conversion: an explicit polynomial written as c₀ + c₁x + c₂x² + … in the source is converted before emission into (…((cₙx + cₙ₋₁)x + …) + c₀) — the multiplication count drops from 2n-1 to n, and large powers like x^n disappear (numerically more stable). a*x^3 + b*x → (a * x * x + b) * x. Compact forms are not expanded: (u-1)^3 stays as written (expanding it only makes it harder to read); derivatives are also taken on the pre-Horner original (differentiating the Horner form yields a chain of cancelling products).
no_std lane: himari_buildhelper::generate_dir_libm produces code that uses only core + libm (transcendentals → libm::exp etc., integer powers → libm::pow; f64::powi is a std thing). That refers to the generated code being no_std-usable — and since 2026-11-23 the compile-time stack is too: himari, himari-latex and himari-matlab are no_std + alloc behind a default std feature (std is on unless you turn it off). The loader, buildhelper, macros and check crates (file IO, proc-macro host, tooling) remain std and enable the feature explicitly. The generated code keeps its own libm lane, which is what a bare-metal consumer actually links against. Gate: a #![no_std] fixture crate ([lib] test = false, because the test harness needs std) that both compiles generated code and exercises the parser chain (himari_matlab::parse → dims_of_set → shapes_of_set → dim_check_runtime → format_set) without std. cargo build passing = the generated code and the front-end do not secretly reach for std. Verified bare-metal targets: riscv32imc-unknown-none-elf (core only — no atomics available), thumbv7em-none-eabi, and x86_64-unknown-none (parser chain). This lane emits no Jacobian (it needs alloc) and no f32 variant (f32 transcendentals are libm's *f family, and we refuse to ship half a lane); for partials, use the __d_* functions per formula (pure scalar, zero allocation).
Cross-file formula libraries: use "..." (2026-11-23)
use "lib/atmosphere.formula" % file header, may span several lines
decl { ... }
v_terminal = sqrt(2 * m * g / (rho * Cd * A))
- Parsing only collects, IO belongs to the loader: the front-end stays a pure string API (FormulaSet.uses), and himari-loader handles reading files, recursive inlining, cycle detection and conflict resolution.
- Merge semantics (simple and predictable): the referenced decls/items are placed first → federation works as usual (later items can reference earlier ones); identical duplicate decls are de-duplicated, differing spellings error out; duplicate item names always error (no "last write wins"); cycles error out and print the file-name chain around the cycle.
- A library is "substituted", not "called": once rho is expanded into the caller, the parameter list contains rho_0 / h / H. This is deliberate (no hidden state, statically differentiable); the cost is a longer parameter list.
- Directory convention: generate_dir scans only the top level *.formula, so formulas/lib/*.formula naturally exists only as libraries and is never generated twice as a top-level formula.
- The dialect comes from the macro, not a guess (user ruling of 2026-11-24, "the macro is the dialect"): whichever macro wraps the formula
decides which grammar reads it.
macro dialect formula!(…) matex (canonical surface; the entry name is kept, the semantics are settled) formula_latex!(…) LaTeX formula_matlab!(…) matex (synonymous with formula!, more self-explanatory to read) formula_file!("f.formula", latex) decided by the mandatory second argument formula_file! does not make the dialect argument optional: the file content cannot be inferred from the macro name, and making the macro guess would only hide the ambiguity somewhere else.
Why this is not just a style preference — it removes a real silent wrong value. When si is declared, si * x: matex reads it as si·x, LaTeX reads it as s·i·x. Measured on the same file with the same inputs (s=3, i=5, x=2, si=100):
text12old AUTO (try matex first, use if it succeeds) → 200 without reporting any error explicit LaTeX → 30The two differ by nearly a factor of seven. AUTO had no way to know which one the author meant — what it "guessed" was merely which parser succeeded first. That is why the macro lane's Dialect enum has no Auto variant: the type system guarantees the guessing cannot come back.
Quick start: examples/reentry (a minimal runnable project)
examples/reentry/
formulas/entry.formula % terminal velocity / dynamic pressure / drag (aerospace side)
formulas/structures.formula % static displacement = solve(k·x − F, x)
build.rs % three lines: generate_dir("formulas", "src/generated.rs")
src/main.rs % prints the table + physical invariant self-checks
src/generated.rs % the checked-in generated code (reviewable, covered by the drift gate)
cargo run -p himari-example-reentry prints a velocity→dynamic-pressure→drag table and verifies:
- Physical invariant: drag(v_terminal) == m·g (relative difference 1.6e-16 — this is not a fit, it is the definition)
- Analytic derivative vs difference quotient: ∂drag/∂v agrees to a relative difference of 1.2e-8 across the two paths
- Symbolic solve: x_static comes from solve(k·x − F, x), and ∂x/∂F = 1/k holds automatically
- The f32 variant and the system Jacobian of a library-inlined formula are both in the same generated file
A consumer now only needs himari-buildhelper::generate_dir(dir, out) — the whole build.rs lane (parse / federation / dimensions / shapes / derivatives / f32 / batch entries / Jacobian / source LaTeX) collapses into one function, so every project no longer copies 300 lines.
Common examples: examples/common (real generation + independent numerical references)
| formula file | example | generated entry and verification | ||
|---|---|---|---|---|
| matrices.formula | rotation, transpose, AᵀA, 2×2 inverse, A·A⁻¹, matrix times column | rotation_orthogonality / N / stiffness_inverse / nodal_forces; cell-by-cell against hand computation | ||
| springs.formula | three-node spring equilibrium system solve([…],[u₁,u₂,u₃]) | displacements against a separate Rust Gaussian elimination with partial pivoting | ||
| runtime_matrix.formula | runtime A/b: solve(A,b), A*x, inv(A), one-based indexing | runtime_displacements / runtime_traction / runtime_inverse / runtime_element; every call fallible (Result), pivoting proven on [[1e-17,1],[1,1]] | ||
| least_squares.formula | normal equations of a straight-line fit | line_fit against the direct least-squares closed form, giving y=1.04+1.99x | ||
| roots.formula | the quadratic and the small root for b²≫4ac | quadratic_roots checks 1,2 and 10⁻⁸,10⁸ (guard against cancellation); returns Result, and a negative discriminant is Error::NoRealRoots | ||
| circuit.formula | I=V/(R+j·2πfL) | current / current_magnitude check ` | I | =0.995037 A; 2π` is written out explicitly |
| dynamic_matrix.formula | dynamic n×n tridiagonal stencil | diffusion_stencil(k,n) cell by cell against a loop-built reference | ||
| inline macro (src/main.rs) | formula_matlab! with a/b, and solve(a, b) on runtime shapes | Rust local variables passed for real; m/m=1 checked at compile time; the runtime solve checked numerically |
These examples prove that the currently supported forms really go from .formula to executable Rust; they do not pass solve off as a general numerical solver, and the static examples do not require runtime matrix parameters. The generated src/generated.rs is checked in and protected by the drift gate.
Standards lane: himari-standards (2026-11-23)
packages/standards turns a handful of published engineering standards into typed calculators, one clause-level relation per module, each carrying its own PROVENANCE (standard id, edition, the clause the formula comes from, and what is not modelled). Nothing here quotes standard prose, and none of it claims conformance with the standard — it restates the formula as a plain expression. Unit conversion is deliberately absent: callers pass SI base units.
| module | standard | edition | computed |
|---|---|---|---|
| iso_6506_1_2014 | ISO 6506-1 | 2014 | Brinell hardness HBW (plus mean indentation pressure in Pa) |
| iso_6892_1_2019 | ISO 6892-1 | 2019 | tensile strength Rm, percentage elongation A, modulus E |
| iso_2533_1975 | ISO 2533 | 1975 | troposphere T, p, rho and the geopotential conversion (0 … 11 000 m, and it refuses above rather than extrapolating) |
| gb_t_231_1_2018 | GB/T 231.1 | 2018 | Brinell hardness HBW; current edition, replaces GB/T 231.1-2009, modifies and adopts ISO 6506-1:2014 |
| gb_t_228_1_2021 | GB/T 228.1 | 2021 | tensile strength Rm, elongation A, modulus E; current edition (effective 2022-07-01) |
| gb_t_8170_2008 | GB/T 8170 | 2008 | decimal rounding, round-half-even, decided on decimal strings — f64 never takes part in a rounding decision |
The two GB mechanical-testing modules reuse the ISO arithmetic (same tested evaluation) but keep their own id, edition and provenance, so a response can never be labelled with the wrong standard. For GB/T 228.1-2021 the adoption degree of any ISO document was not independently verified, so the module explicitly claims no equivalence — only the three definitions are implemented. Editions were checked against the National Standard Information Public Service Platform, and each module records the check in its provenance notes.
The CLI himari-standard evaluates one request and prints one stable-shaped response document (JSON), reading the request as JSON or TOML — from --input <path> or stdin, with --format json|toml to force the parser and --list for the exact ids and editions:
Those three example requests under packages/standards/examples/ are exercised by the test suite, so the documented invocations cannot rot.
Unknown keys are refused rather than ignored; every failure returns the same document with values set to null and the cause in errors (exit 1, with a one-line diagnostic on stderr); exit 2 is reserved for command-line misuse. Requests whose decimals take part in a rounding decision must carry those numbers as decimal strings, because a binary float has already lost the trailing digit by the time the crate sees it.
Proof lane: himari-lean (2026-11-23)
packages/lean is a Lean 4 co-process: it generates a self-contained proof obligation, hands it to a real lean executable over stdin (lean --stdin --json -T <heartbeats> -M <MB>), and reports what happened in a structured document. No Lake project, no package index, no network; the generated file has no imports.
- Dynamic data only ever becomes literal integers of a named example theorem statement — never a data definition, an axiom or an identifier.
- Kernel-checked, by decide: the obligation is closed over Int and discharged by by decide. No native_decide, #eval, implemented_by, extern, partial, sorry or user axioms are emitted, and a test asserts the generated text against that list.
- Axiom gate: #print axioms output is parsed and only propext, Classical.choice and Quot.sound are tolerated; an unreadable report is a violation, never a pass. The absence of a report is not evidence of a clean one.
- An independent oracle: the same determinant is computed in Rust with a different expansion, so Lean is never the only witness.
- lean_missing is a first-class non-success: it means the toolchain was not there and nothing was checked. It is never rendered as "verified" and never exits 0. Statuses and exit codes: success 0, lean_missing 3, invalid_request 4, proof_failed 5, resource_exhausted 6, axiom_violation 7, oracle_mismatch 8.
Verified against a real toolchain (Lean 4.36.0, commit 611c117b). The milestone obligation is accepted by the kernel and reports no axioms at all:
status = success verified = true exit = 0
lean_message: 'det3_example' does not depend on any axioms
oracle: rust-i128-permutation det3([1,2,3,4,5,6,7,8,10]) = -3
The negative controls behave as designed with the same binary: a request that asserts expected = -306 returns oracle_mismatch (exit 8) and is never reported as verified, and the stub-process suite covers the proof_failed / axiom_violation / resource_exhausted paths.
Provisioning is external to this repository and stays a one-off: install elan, pin leanprover/lean4:v4.36.0, then either put lean on PATH or point HIMARI_LEAN_BIN at it. just lean-verify emits the obligation and runs the real-Lean test. Without a toolchain the lane degrades to lean_missing (a non-success) and --emit still writes a reviewable .lean file — absence of Lean is never reported as verification.
Robustness and adversarial input (2026-11-23)
- Depth limit 2048: every parsing exit checks the IR depth once (check_depth), and anything over the limit reports "formula nested too deeply (N levels > limit 2048)" instead of letting some downstream recursive stack overflow (SIGSEGV). pest's own stack limit also fires and its message is translated into plain words too. Known boundary: a long chain a + b + c + … is left-nested in the IR, so the depth equals the number of terms; one formula's term count is therefore capped at about 2048. A separate deterministic bracket-nesting guard (256 levels, MAX_PARSE_NESTING) runs before parsing, because it must also hold where pest's optional stack-guard feature is unavailable (no_std).
- Invisible characters are always rejected: zero-width space / bidirectional override / zero-width joiner / BOM / NUL are all named and refused before parsing (scan_source) — they can make a formula "look different when reviewed than what it is".
- Sum/integral step limit 10^7: Σ(i,1,1e9) goes from "runs overnight" to one error line.
- A function call with missing arguments no longer panics through args[0] indexing: all three lanes (evaluation/emission/dimension) reject it explicitly.
- Structured property tests (not random character soup): 600 random expressions each pass three gates — canonical write-back re-parses to the same tree, LaTeX write-back re-parses to the same tree, and simplify preserves the value. All three currently show 0 inequivalences (prop-roundtrip); a large input summing 1500 terms completes in under 100 ms.
Single precision (f32) lane (2026-11-23)
Every real scalar formula additionally produces {name}__f32(p: f32) -> f32 — the same formula, the same emission rules, with only the literals switched to the f32 suffix (Fx::F32, the single switch threaded through the emitter). Measured f32/f64 = 1.44× (SIMD 8 lanes vs 4 lanes + half the bandwidth), which game engines / audio DSP / real-time SDR benefit from directly.
Complex and matrix-valued formulas do not produce an f32 variant: the complex lane's (f64, f64) tuple and the matrix's Vec<Vec<f64>> are a different type contract in single precision; that can come later (we refuse to ship half a lane).
Developer tools (2026-11-23)
Three entry points ship together (all in the himari-check package, sharing one parser):
| entry point | purpose |
|---|---|
| himari-fmt --diff | show only the difference between canonical and current form (no rewrite) |
| himari-fmt --diagnose | parse + dimension + shape diagnostics only (silent with exit code 0 when clean) |
| himari-fmt --symbols | list decl names and formula names (the data source for editor completion) |
| himari-eval <file> --set k=v … | evaluate: Re = 200000 [1]; --groups also prints the Buckingham Π groups; --json for machines |
| python3 scripts/fmt_check.py --fix | one command to re-lay out canonical form + regenerate sidecars |
Errors carry carets: FrontError::render_with_source prints the source line and draws a ^ under the offending column (all three lanes — build.rs / fmt / eval — go through it) — no more counting to column 17 yourself.
The VS Code extension (packages/vscode) has two channels:
| channel | trigger | data source |
|---|---|---|
| CLI (default, zero install) | open / save | himari-fmt --diagnose + --symbols |
| LSP (optional) | errors while you type | himari-lsp (stdio JSON-RPC) |
himari-lsp is a hand-written minimal server (no LSP framework dependency): initialize / didOpen / didChange / completion / codeAction / shutdown, with incremental text sync. Its diagnostics carry the same himari::Error as the library, rendered in the locale chosen by HIMARI_LANG (falling back to LC_ALL, LANG, then English); all nine project languages are available. The protocol layer handles state and JSON-RPC parameters as pure functions, and there is an end-to-end test that really starts a process and really sends Content-Length frames. Set himari.lspPath in the settings to switch (leave it empty = CLI channel).
Completion candidates = the file's decl names + formula names + the unary function table (including det/inv/solve/dot/norm etc.).
Errors: one enum, nine languages
Every error the crate returns is one enum, himari::Error. It is not a bag of strings: each catalogued failure is a variant that carries its own data, which gives three things at once.
- A stable code — err.code() returns a kebab-case identifier (dimension-mismatch, undeclared-symbol, no-real-roots, ...). Tests and callers assert the code, so a wording change or a translation can never break them.
- A rendering per language — err.render(locale) and Display (English) produce the sentence from the catalogue in i18n.rs. HIMARI_LANG / LC_ALL / LANG select it at the CLI and LSP edges; the nine locales are the organization's (en, zh-Hans, zh-Hant, ja, ko, fr, es, ru, ar).
- anyhow compatibility — Error implements core::error::Error (so std::error::Error
under std) and is Send + Sync + 'static, with no wrapper:rust123456789101112131415
use Context as _;tests/anyhow_compat.rs pins all of it: ? propagation, the Send + Sync + 'static bound, downcast_ref::<himari::Error>() after anyhow::Context, and the rule that every locale renders the same error differently while the code stays identical.
Error::Message(String) remains for messages that never enter the catalogue; it renders verbatim in every language. The staging debt it represents is measured by a gate, not by prose — and that debt is currently zero:
It is an AST walk (tools/staging-budget, built on syn), so the count never depends on line layout, whitespace, or comments, and a pattern such as matches!(e, Error::Message(m) if …) is never mistaken for a construction. Twelve buckets in three families are counted across every production tree in the workspace (packages/, examples/, tools/): the six literal construction shapes (Error::from(, Error::Message(, and the front-ends' FrontError::plain("…") / plain(format!(…)) / FrontError::new(…, "…")), the value-laundering funnels (plain / new with a runtime-value payload, and FrontError::plain passed as a function reference, both repo-wide), and the string-staging shapes (ok_or/ok_or_else/map_err producing staged strings, and Err(format!(…))) inside the catalogue crate itself. Items compiled only under test and the catalogue are skipped; a catalogued variant built with a string payload (e.g. Error::SyntaxError(text)) is not staging and is not counted. The gate fails if the total exceeds the recorded ceiling (the ceiling lives in tools/staging-budget/src/ceiling.txt and may only go down; it stands at 0). The ceiling may only go down, and that is enforced: CI (and just verify) run the gate with --against-git, which reads tools/staging-budget/src/ceiling.txt at the merge base with the remote trunk and fails if the working-tree ceiling is higher — so new sites cannot be snuck in together with a raised ceiling. The bare command above checks only the count. Every catalogue variant is pinned by catalogue_completeness_tests, which constructs all 51 variants (50 catalogue variants plus the staging Message) and renders each in the nine locales (non-empty, no leaked {n} placeholder). The LSP's quick-fix titles are also still Chinese; its diagnostics are localized.
LaTeX surface: multi-letter names need \mathrm (2026-11-23)
In LaTeX math mode a bare sigma is five multiplied variables s·i·g·m·a (implicit multiplication), so multi-letter names in this dialect must be written \mathrm{sigma_0} — and write-back emits them the same way. Greek letter names (sigma, omega…) are written back as the real glyphs \sigma, keeping the subscript (\sigma_0). The implementation used to be substring replacement, so alphabet became \alphabet and betamax became b\etamax, while sigma rendered as five italic letters — wrong in three places at once (hover / sidecar / documentation source of truth). Fixed (latex_var).
Editor integration (LSP)
himari-lsp is a hand-written LSP service (the protocol layer is pure functions, with unit tests + an end-to-end stdio test):
| capability | description |
|---|---|
| diagnostics | push publishDiagnostics after didOpen/didChange (undeclared symbols, dimension mismatches, syntax errors) |
| completion | the file's decl names + formula names + the unary function table (det/inv/solve/roots/...) |
| quick-fix | textDocument/codeAction: undeclared symbol → ① respell to the nearest declared name ② add a line to the decl block; misspelled function name → the name from the registry |
| sync | incremental sync (textDocumentSync: 2, sliced by range); full changes are accepted too, so old clients do not break |
A quick-fix only offers a replacement when the name occurs exactly once (if it occurs several times it only offers "add the declaration", never guesses which occurrence); out-of-range values are always clamped rather than dropping the change (dropping one would permanently desynchronise the buffer from the editor).
Formula-library content locks: when a library changes it must speak up
use "lib/…" inlines the library file, so when the library changes, downstream generated code changes with it — exactly the kind of regression that is easiest to miss. --lock writes a fingerprint of every referenced file into <entry>.lock, and from then on the lock is verified on every load:
$ himari-fmt --lock formulas/entry.formula
已写入 formulas/entry.formula.lock(4 行)
$ himari-eval formulas/entry.formula # someone quietly changed the library
himari-eval: 公式库与锁文件不一致(formulas/entry.formula.lock):
内容变了(声明版本 1.4.2 → 2.0.0):lib/atmosphere.formula
复核改动后运行 `himari-fmt --lock <入口>` 重新生成锁。
(CLI output is quoted verbatim: the tool still prints in Chinese. In English: the library and its lock file disagree — lib/atmosphere.formula changed its declared version 1.4.2 → 2.0.0 — re-run himari-fmt --lock <entry> after reviewing the change.)
- sha256 content hash (not a semver range): for a dependency shape like "inlined source", a content hash is the stronger guarantee — any change is caught, no version-resolution policy is needed, no pre-release rules.
- Plain text, deterministic, paths relative to the entry directory: it can go into git, the diff is readable, and it is comparable across machines.
- Closed gate: scripts/fmt_check.py runs --lock-check on files that have a .lock (and re-locks automatically under --fix) — a stale lock goes red in the gate, without waiting for someone to load the file.
- opt-in: with no .lock nothing is verified (zero impact on existing repositories). Once a lock exists, a new reference also fails (whitelist semantics); re-lock to accept it.
- An unreadable lock is also a failure: not UTF-8 (saved as UTF-16 by an editor), insufficient permissions, or a directory path are all hard errors — these may never be treated as "no lock", which would silently switch the protection off.
- --fix has three stages (format everything first → then re-lock everything → finally regenerate every sidecar): sidecars verify the lock when they load, so the lock must be final first; both also depend on the final content of the referenced libraries, and mixing them into one loop leaves stale artefacts.
- %! version: 1.2.0 is only the human-readable column (it is locked and a changed version is reported); the semantic guarantee rests on the hash.
- Why no semver ranges: that would need a whole resolution/pinning/pre-release policy, while this repository's dependency shape is "inlined source". To express "allow minor drift", re-locking is the more direct statement.
Dialect directives: the file lane's counterpart of "the macro is the dialect"
A file has no macro to wrap it, so the corresponding rule is: matex by default; declare LaTeX explicitly. Both lanes share one principle — no guessing, the author (not the parser) decides the semantics.
%! dialect: latex
decl {
s : d;
i : d;
si : d;
x : d;
}
q = si * x % LaTeX semantics: s·i·x (not the declared si·x)
- Supports %! dialect: latex (or tex) and %! dialect: matex (or matlab).
- No directive = matex. There used to be an AUTO fallback here (if matex parsing failed and the source contained \, try LaTeX), and it produced exactly the silent 200-vs-30 wrong value above — it has been removed.
- LaTeX-only notation without a dialect directive → parsed as the default matex → error (never a silently wrong value); the error offers a way out (write %! dialect: latex) but does not guess on your behalf.
- It only takes effect before the first non-comment line (a %! inside body comments does not change the dialect).
- An unrecognised value is an error.
- With a directive, errors are reported in that dialect: a syntax error under a LaTeX directive is a LaTeX error.
- It is implemented in exactly one place (himari_loader::parse_source), so the build.rs lane, himari-fmt, himari-eval and LSP diagnostics all agree. (LSP diagnostics render in the language chosen by HIMARI_LANG; see the "Errors" section.)
Division on the LaTeX surface (once missing)
a / b and a \div b are now real division, synonymous with \frac{a}{b}, at the same precedence as multiplication and left-associative. Previously the LaTeX surface had no division operator at all — only \frac{a}{b} was accepted, and a / b was a syntax error. That was throwing out the baby with the bathwater: / is the most ordinary way to write division and there was no reason to refuse it. (The AUTO fallback above had actually been covering for this defect: it made a / b "happen to work" while bringing the silent wrong value along. Fix the defect and the fallback has no reason to exist.)
Symbolic linear solve solve (2026-11-23)
The single-variable form solve(equation, variable) solves equation = 0 as variable = -b/a (the equation must be linear in that variable).
ES_ss = solve(k_on * E * S - (k_off + k_cat) * ES, ES)
→ ES_ss = k_on·E·S/(k_off + k_cat) % Michaelis–Menten steady state
- The solution is still IR: so it keeps dimension checking, evaluation, code generation, analytic derivatives and the Jacobian — no second mechanism is needed. The partials and Jacobian rows of ES_ss come out automatically.
- The parameter list = the variables the emitted expression actually uses: the solved-for ES does not appear in ES_ss's parameters ("ask for it yet must pass it" is fixed). Sidecar / hover / completion read the same parameter list.
- Nonlinearity is rejected explicitly: x·x, 1/x, x^2, sin(x) error at the parsing exit and name the kind involved; no numerical approximation, no dubious answer. Getting a chemical steady state wrong costs far more than typing a few more characters.
The system form solve([equations…], [unknowns…])
When both arguments are lists the linear system lane is entered, and the solution is a column vector (the matrix-expression value lane, returning Vec<Vec<f64>>):
x = solve([(k1 + k2) * x1 - k2 * x2 - F1,
-k2 * x1 + (k2 + k3) * x2 - F2], [x1, x2])
→ x = 2×1 column vector, dimension [m] % two-mass spring statics
- Symbolic elimination: Gauss–Jordan elimination runs over the expression ring (the coefficients are IR subexpressions, not numbers), simplified to normal form at every step. Each solved component is still IR and goes through dimensions/evaluation/emission as usual. But a system solution is matrix-valued: matrix-valued formulas do not generate analytic derivatives (elementwise partials are not a matrix; the Jacobian is), and do not generate an f32 variant — that is the existing limit of the matrix-valued lane, not specific to solve.
- Shape convention: the equation and unknown lists are flattened row-major, so [e1, e2] and [e1; e2] are equivalent — users do not have to remember an orientation. Entries of the unknown list must be bare variable names.
- Unknowns need declared dimensions: what that buys is checking the dimension of the result (the spring example solves m = N/(N/m)), as well as the homogeneity check of the equations themselves (x1 − F1, adding m to N, is rejected at parse time). Solved unknowns do not enter the parameter list (the generated function takes only real parameters).
- Rejection is a feature: underdetermined (not full rank), inconsistent (after elimination 0 = nonzero), nonlinear (the unknown appears on both sides of a multiplication / in a denominator or exponent / inside a function argument) are all reported at the parsing exit. Dimension-related rejections happen in dims_of_set / the generation stage (the parser itself does no dimension checking). Redundant equations are removed "in the foldable sense": a redundant row with symbolic coefficients that does not fold to zero is conservatively reported as inconsistent — better to refuse than to return a wrong solution.
- Pivot non-vanishing and the numerical boundary: same convention as single-variable solve, something that cannot be proven zero is treated as nonzero (we trust a ≠ 0). Elimination happens at compile time in expression order and does not reorder rows by |pivot| at run time; at extreme scales the closed form cancels, a singular parameter reports division by zero in the value layer and gives inf/NaN per IEEE in generated code — that is not an exception. Ill-conditioned systems, or systems that need a pivoting strategy, must go to a numerical library.
- Boundaries (four, all rejected at the parsing exit or as compile-time errors):
- A coefficient or constant term that is matrix-valued (solve(M*x - b, x), solve([M*x - b], [x])) → rejected explicitly with a pointer to inv(A) * b — otherwise the scalar lane would generate vec! division, which does not compile.
- Equations may have different dimensions (a force balance in N plus a geometric constraint in m is a legal system), but every equation must be homogeneous on its own; and every component of the solution must share one dimension (mixed-dimension unknowns — solving for a current and a resistance at once — are not supported yet; that is a limit of the matrix-valued lane).
- The complex lane (with j) works in the value layer and the emission layer (completed 2026-11-23): a complex column vector is emitted as Vec<Vec<(f64, f64)>>, elements being (real, imaginary). AC circuit nodal analysis and EIS-style "complex equation systems" can therefore be generated directly into code.
- The zero test on redundant rows is a sufficient condition: zeros that like-term combination can prove (k−k, k·a−a·k, x·x²−x³) are recognised; a complex identity that cannot be proven zero is treated as a nonzero coefficient (conservative — it may falsely report underdetermined/inconsistent, but it will not return a wrong solution).
Polynomial roots roots(poly, x)
solve gives a linear closed form; roots gives all roots of a polynomial (as a column vector):
roots_quad = roots(a * x ^ 2 + b * x + c, x)
% q = −(b + sign(b)·√(b²−4ac))/2; large root = q/a, small root = c/q
% Return order still matches the original formula (−b−√Δ first); it does not depend on sorting the roots by size.
- Only degree 1–2: degree 1 is the same mathematics as solve; degree 2 is the closed-form root formula. Degree 3 and above is rejected explicitly with the actual degree reported — Cardano/Ferrari are terribly conditioned in floating point, and this repository will not hand out a "looks precise" approximation. For roots of degree three and above, first compute the coefficients numerically and then use a numerical library.
- Repeated roots are repeated by multiplicity (x² − 2x + 1 gives two 1s), consistent with the fundamental theorem of algebra; the q=0 fallback for a zero root is -b/(2a) and does not go through 0/0.
- Avoiding cancellation in the quadratic formula: using (−b±√Δ)/(2a) directly loses the small root when b²≫4ac (x²−10⁸x+1 once computed 10⁻⁸ as about 7.45×10⁻⁹). It now uses the stable q/a and c/q, and the acceptance line for the small root's relative error in generated code is 1e-12; both sign directions and the complex lane have regressions.
- Dimensions come out automatically: the equation must be dimensionally homogeneous, and homogeneity directly implies "the dimension of a root = the dimension of the variable", so no extra dimension derivation is needed (a contract test guards this reasoning).
- Negative discriminant in the real lane: generated code returns a typed error, not NaN — the real quadratic roots entry now returns Result<_, himari::Error> and a negative discriminant is Error::NoRealRoots { discriminant }. There is no silent NaN contract any more, so is_nan/is_finite checks are no longer the way to detect this case; a constant discriminant that is provably negative at compile time is still rejected outright. eval_value is the general complex value layer and still returns complex roots for the same expression in the complex lane; a complex lane needs an explicit j.
- Higher-order terms that cancel are stripped: x³ − x³ + x − 1 is treated as degree 1 (not "rejected because an x³ appears in the polynomial").
- Non-polynomials are rejected explicitly: x inside a function argument, in a denominator, or at a non-integer power — each with its reason given.
- Matrix-valued coefficients are rejected (same convention as solve, otherwise the scalar lane would generate vec! division).
Coefficient vector poly_coeffs(poly, x)
roots's complement: it gives the coefficients (low to high degree), returning a 1×k row vector.
coeffs = poly_coeffs(2 * s ^ 2 - 3 * s + 1, s) → [[1, −3, 2]]
- The variable must be dimensionless. The dimension of the degree-k coefficient of a homogeneous polynomial is dim(poly)/dim(x)^k, and they differ; but a matrix requires elements of one dimension — so taking coefficients of a dimensioned variable is algebraically impossible in that form. This check explains that directly at the diagnostic stage and offers a way out (divide by a characteristic quantity, or use roots) rather than letting downstream report "matrix element dimensions differ".
- High-degree zero coefficients are stripped (x³ − x³ − 2x + 1 is degree 1); the zero polynomial is rejected.
- Non-polynomials (sin(x), 1/x, non-integer powers) are rejected.
- It shares the same poly_coeffs extractor as roots — one definition of coefficient semantics, two users.
Roots above degree three: himari-eval --roots
Rejecting degree ≥ 3 in the language is a forced trade-off, but numerical root finding works for any degree, so it lives in the tool layer:
$ himari-eval cubic.formula --roots
cubic = 1, 2, 3 [1] (degree 3, 3 roots)
cplx = -1, 0.5-0.8660254037844387j, 0.5+0.8660254037844386j [1] (degree 3, 3 roots)
- Durand–Kerner iteration (reusing the core's C for complex arithmetic, no third-party numerical library): initial values are powers of 0.4 + 0.9j, the radius is the geometric mean of the root magnitudes |c₀/cₙ|^(1/n) (falling back to the Cauchy bound 1+max|cᵢ| only in degenerate cases); at most 1000 iterations; the DK criterion is |Δz| ≤ 1e-10·radius (relative to the magnitude of the roots, not relative to 1); followed by 60 Newton polishing steps (relative stopping criterion 1e-15·|z|).
- Non-convergence is an error, never a not-yet-converged approximation returned as a result; inf/NaN during iteration is also an immediate error (f64::max returns the other side for NaN, which once made a NaN step look like "converged" and returned 20 NaNs).
- Residual acceptance: after iterating, the relative backward error |p(z)| / Σ|aₖ|·|z|ᵏ must be small enough (threshold 1e-8), otherwise it errors — DK does not guarantee convergence to a root, and the criterion must be independent of the iteration itself. The denominator must include the k=n term: without it the denominator degenerates to the constant |a_n| at small |z|, and x²−1e-100 would pass while being wrong by a factor of 4e25 (a real regression).
- Newton polishing (relative criterion): a simple root reaches machine precision; a multiple root converges only linearly, so x²−2x+1 and the like have a relative error in the 1e-9 range and do not error — that is a property of the algorithm, not a bug; do not treat a multiple root as a simple one.
- Degree limit 16 (poly_coeffs's polynomial expansion limit; numeric_roots itself supports up to 64).
- Monic normalisation before iterating (divide by the leading coefficient) to avoid magnitude overflow; degree limit 64; inf/NaN coefficients rejected.
- Noise zeroing clears only the imaginary part, and the criterion is relative: a real root carries 1e-16-scale imaginary residue, which is an iteration artefact; the criterion is |im| ≤ 1e-12·|z|. The real part is never touched (the roots of x²−1e-50 are ±1e-25), and an absolute threshold is no good either — for a complex root whose magnitude is below 1e-12, the imaginary part is the entire information in the root (x³−1e-60 was once smeared into three real roots on that basis, relative error 0.87, without an error).
- Coefficients must evaluate to numbers under the parameters given by --set; when the variable is omitted it is inferred as "the only declared symbol in the formula", and several candidates require --var.
- The output carries the degree and the number of roots; complex roots are written a+bj.
Complex matrices and complex equation systems (2026-11-23)
Complexity is not only scalar: matrix elements and solution vectors can be complex too, and the value layer and the emission layer agree. The generated function's return type is Vec<Vec<(f64, f64)>> (element = (real, imaginary)):
// I = solve([Z*I1 - V, Z*I1 - R*I2], [I1, I2]) with Z = R + jωL
- Typical uses are AC circuit nodal analysis and EIS modelling: the unknowns are complex currents/potentials.
- Transposition is plain transposition (no conjugation) — conjugation is the separate conj operator; do not confuse them.
- adjoint is the conjugate transpose; only literals whose shape is known at compile time can be expanded.
- In the complex lane det/trace/adjoint/inv/solve/roots/dot/norm likewise expand at the IR level before emission (a historical asymmetry: the real lane expanded while the complex lane went straight to compile_error!).
- Still unsupported: the no_std/libm lane for complex formulas (the closures depend on std), analytic derivatives for complex formulas (abs/arg/conj/re/im are not complex-analytic, that needs Wirtinger calculus), and the f32 variant for complex formulas.
WGSL (GPU) lane: subset + validation boundary (2026-11-23)
himari-fmt --wgsl <file.formula> emits a real-scalar formula as an f32 kernel:
// Generated by himari (f32 scalar lane; really compiled and validated by naga)
fn q(rho: f32, v: f32) -> f32 {
return 0.5f * rho * (v * v);
}
Supported subset (deliberately small): + - * /, sqrt, exp/log (this repo's ln) sin cos tan sinh cosh tanh abs min max clamp, plus powers 2/3, square root, and power -1. Explicitly rejected: complex (j), matrices, det/inv/solve, Σ/∫, symbolic operators, other powers, and symbols colliding with WGSL reserved words — each with a reason (we do not emit a kernel that does not compile).
Validation has two layers (since 2026-11-24 the WGSL lane has compiler-level evidence):
- Real compile gate (authoritative): cargo test -p himari-check --features wgsl-compile hands every emitted kernel in the fixtures to naga (wgpu's shader compiler, one of the authoritative implementations of the WGSL spec) for real parsing + real validation. naga is a pure-CPU dev-dependency — no GPU needed, and it never enters the runtime dependency tree.
- Static gate (fast screening, wgsl::validate_wgsl): bracket balance, a -> f32 signature, exactly one
return, float literals carrying f, no ^/**, no non-finite constants. Its value is "catching coarse errors in environments without naga
- error messages closer to this lane"; it is not a proof of correctness.
Why a real compile gate is mandatory — a concrete lesson: every kernel of this WGSL lane used to be invalid. WGSL has no expression-bodied functions; the body must be return expr;, while the emitter always emitted a bare expression; worse, the static gate forbade return — because the rule was written without knowing that part of the spec, turning the misunderstanding into "the rule". A static gate's structural blind spot is not "it will miss things" but "it does not know what it missed, and it can even judge correct code wrong". The first naga run exposed the whole class. Another corrected belief: return 2.5; is legal in naga (abstract-float lands as f32 by context) — so "floats must carry f" is a style convention of this lane, not the WGSL spec.
Validation boundary (stated honestly): naga validates syntax and types only; the numeric side is now measured by just gpu-verify — the emitted kernel runs through a real Vulkan driver path (Mesa lavapipe on this host) and its results are compared with the f64 CPU lane (four formulas, sixteen points, worst relative error 3.2e-7; swapping one emitter operator makes the lane fail). What that run does not cover: a hardware GPU (vendor f32 rounding, workgroup scheduling, driver bugs — this host's only Vulkan device is a software implementation, and node-3's RTX 5880 is still pending hookup), and the four formulas are a sample, not the whole emittable language. Also, tint (Chrome/Dawn's implementation) and naga differ on a few edge rules; this repository is responsible to naga only.
Choosing a lane by domain (one table)
| scenario | suggested lane | notes |
|---|---|---|
| large-scale scientific HPC / numerical libraries | .formula + build.rs, real scalars | on par with hand-written (1.0×); the fixed-length batch variant removes bounds checks |
| game engines / audio DSP | same + {name}__f32 | measured 1.44× SIMD gain; clamp with clamp/min/max |
| real-time SDR | real or complex lane + batch | convolution/channel matrices as literals (constants fold) |
| EIS / electrochemistry | complex lane (j + (f64,f64)) | phase is a physical commitment; use batch for sweeps; hand-write the hot loop |
| FEM / finite elements | matrix operators det/trace/inv + Jacobian | det to order 4, inv to order 3; higher orders via a numerical library |
| runtime-sized linear systems | runtime lane (_matrix/_vector decls) | solve(A,b) is checked (rcond + residual); returns Result |
| dimension exploration | himari-eval --groups | Buckingham Π groups: no hand-deriving the Reynolds number |
Everything this repository emits — generated doc comments, compile_error! payloads, the proc-macro's FORMULA-ERROR diagnostics, the WGSL header — is English. The one exception left is the LSP's quick-fix titles (its diagnostics are localized); that is a UI string, not an error-catalogue path. The catalogue's staging debt is zero, and the staging-budget gate above (twelve construction families, conditionals and string-producing map_err references included, ceiling enforced against the merge base) is what keeps it there.
Errors with carets, suggestions for misspelled function names (closest_func, edit distance ≤ 2), rejection of invisible characters, depth/step limits — these are not garnish, they are the bar for "daring to let a colleague use this".
Status
The repository lives on the org (celestia-island/himari, single squashed master). 0.1.0 is published: all eight library crates (himari, himari-latex, himari-matlab, himari-loader, himari-buildhelper, himari-macros, himari-standards, himari-lean) are on crates.io since 2026-11-25, uploaded in topological order through the publish.yml lane (CRATES_IO_API_TOKEN, idempotent per crate). Future releases follow the same lane: a v* tag on master or a workflow_dispatch re-run. Examples, fixtures and the tooling crates (himari-check, himari-staging-budget, himari-gpu-verify) stay unpublished. cargo add himari himari-macros is the supported way to consume the macro lane; docs.rs builds each crate's documentation on publish. History of the roadmap and trade-offs: _reports/math-formula-20261122/ (REPORT / SPIKE-S0 / SYMBOLS-AND-PAPER).
Verification
The gates cover core algebra, real generated-code compilation and numerical invariants, independently written consumer examples, real naga compilation of WGSL, and canonical/sidecar/lock and generated-code drift. The exact test count is whatever the current cargo test --workspace output says; the performance numbers describe only this repository's bench environment and are not a cross-platform guarantee.
Not claimed
These are scope limits, not a to-do list that is nearly done. Say "not claimed" where it says "not claimed".
- No runtime pivoting in the symbolic lane: the symbolic solve eliminates in expression order and trusts a ≠ 0; it does not reorder rows by pivot magnitude. Ill-conditioned or pivoting-sensitive systems belong to the runtime lane (solve(A,b) above) or a numerical library.
- Pattern matrices only via the file lane: the constructor lane for pattern matrices needs a filename and a generator, so inline macros reject them with a pointer; there is no automatic expansion of arbitrary pattern matrices (research-grade — anything outside the built-in shapes is rejected explicitly with the supported list).
- WGSL numeric validation is measured, but on a software device: just gpu-verify compiles the emitted kernel to SPIR-V, executes it through Vulkan and compares the results with the f64 CPU lane (four formulas, sixteen points, worst relative error 3.2e-7 on Mesa lavapipe; swapping one operator makes the lane fail). That is a real driver path executing real SPIR-V, so it catches wrong indexing, constants and precedence — it does not measure vendor-specific f32 rounding, workgroup scheduling or driver bugs, and no hardware-GPU run has been made.
- Lean verification has not succeeded: no toolchain is installed on this host, so only the stub-process tests ran. There is no claim that Lean accepts the generated proof obligations.
- Published 0.1.0 is immutable: the eight library crates are on crates.io (2026-11-25); a yank only hides a version, it never frees the number — so 0.1.x fixes ship as 0.1.1+, never by re-publishing 0.1.0. See Status.
- no_std scope: himari, himari-latex and himari-matlab are no_std + alloc; the loader/buildhelper/macros/check crates are not. Generated code keeps its own libm lane, and complex formulas are not part of the no_std lane.
- No complex analytic derivatives, no f32 variant for complex or matrix-valued formulas, no analytic derivative for matrix-valued formulas.
- roots covers degrees 1–2 only in the language; higher degrees only via himari-eval --roots numerically.
- General LaTeX (macros/catcode/typesetting) — undecidable semantics; typesetting belongs to the rendering layer.
- No inference of semantics from glyphs, and no xy multiplication on the MATLAB surface. No \sin^2 x, no .*, no $…$ (ambiguous or purely typographic notation: parsing and rendering are two different jobs and one parser should not do both).
- No runtime JIT on real-time/safety-critical paths; no AGPL dependencies, ever (evalexpr ≥12 and friends are out).
- The himari-standards modules are clause-level calculators, not conformance claims: they do not model specimen geometry, force-level selection, dwell time, uncertainty budgets, or the standards' own reporting rules, and they are not a general units library.
- The himari-lean lane proves one small closed integer obligation (a 3×3 determinant example); it is not a general theorem prover, and its axiom gate is a parser over Lean's own output, not a soundness argument.