Repository navigation
Description
Problem
The invariant at stake: ast::print_eqn's output must be text Expr0::new accepts. The engine re-parses print_eqn output constantly -- LTM partial-equation synthesis (ltm_augment.rs, ~15 call sites), patch.rs:983's equation normalization, conveyor_compile.rs:1951, builtins_visitor.rs implicit-module argument text, and the MDL writer's equation_to_mdl. When print_eqn emits text the parser rejects, LTM emits a warning and drops the variable (its link score reads a constant 0), and the MDL writer takes its raw-text fallback (#912).
Fixing #912 / #863 closed the stacked-unary and unary-exponent-operand cases in the parser, and the If-under-an-operator case in the printer. Three more instances of the same class remain. All three empirically confirmed against Expr0::new(s, LexerType::Equation).
1. print_eqn emits !a for a unary not, which the equation lexer cannot tokenize
src/simlin-engine/src/ast/mod.rs PrintVisitor's Op1 arm renders UnaryOp::Not => "!", producing !a. But src/simlin-engine/src/lexer/mod.rs never lexes a bare ! at all (only <> becomes Neq; there is no ! character rule). parse_eq("!a") fails. There is even a comment in src/simlin-engine/src/parser/tests.rs saying "The lexer doesn't support '!' as a character - only the keyword not produces Token::Not". So print_eqn(Op1(Not, x)) is unconditionally unparseable.
Suggested fix: print not {inner} (with a space). Note test_print_eqn in ast/mod.rs currently pins the broken "!a" output and would need updating.
2. print_eqn emits a != b for BinaryOp::Neq, which the lexer also rejects
Same file, PrintVisitor's Op2 arm: BinaryOp::Neq => "!=". parse_eq("a != b") fails; the lexer only produces Neq from <>.
Suggested fix: print <> (the form the lexer accepts, and the one the MDL writer already emits).
3. print_eqn renders a right-nested ^ without parens, but the XMILE parser is left-associative -- so the printed text re-parses to a DIFFERENT AST
needs_parens_for_op (src/simlin-engine/src/ast/mod.rs:294) only parenthesizes an equal-precedence right child for Sub/Div/Mod. So Op2(Exp, a, Op2(Exp, b, c)) prints a ^ b ^ c, which parse_exponentiation (documented "left associative per current grammar") re-parses as Op2(Exp, Op2(Exp, a, b), c) -- i.e. (a^b)^c, value 64 where the AST meant 512.
This is a silent semantic round-trip corruption, not merely a parse failure, so it is the most serious of the three.
Note the MDL reader's own mdl::parser::parse_power (src/simlin-engine/src/mdl/parser.rs:1228) is RIGHT-associative, and Vensim/Stella treat ^ as right-associative -- so the two parsers in this repo disagree about a ^ b ^ c today.
Two candidate fixes, needing a deliberate decision:
- (a) make
parse_exponentiationright-associative to match the MDL reader, Vensim, and every mainstream language. A behavior change for any existing model containinga^b^c, and it also closes the parser-disagreement. - (b) keep left-associativity and make
needs_parens_for_opadd parens for an equal-precedenceExpright child.
Suggested common guard
A proptest over Expr0 asserting parse(print_eqn(e)) == e (AST equality after strip_loc) -- strictly stronger than the text-fixpoint property mdl/writer_proptest.rs has. #912's fix added Expr0::new(print_eqn(e)).is_ok() as an assertion in that proptest, but not the AST-equality half. Item 3 is exactly what the missing half would catch (both spellings re-print identically, so the whole-text fixpoint assertion cannot see the divergence).
Component(s)
src/simlin-engine/src/ast/mod.rs(print_eqn,needs_parens_for_op)src/simlin-engine/src/lexer/mod.rssrc/simlin-engine/src/parser/mod.rs(parse_exponentiation)
Activity
bpowers commentedon Jul 9, 2026
All three items in this issue -- plus a fourth found while fixing them -- are addressed in the #912 branch:
print_eqnemitsnot a(was!a) anda <> b(wasa != b); both are now lexable.Transposearm ofPrintVisitor(and ofLatexVisitor) routes throughparen_if_necessary, soOp1(Transpose, a + b)prints(a + b)'rather thana + b'.^re-parsing to a different AST) was fixed at the root:parser::parse_exponentiationis now RIGHT-associative, matching the XMILE spec 3.3.1, Vensim,mdl::parser::parse_power, andtest/test-models/tests/arithmetics/output.tab(cons4^cons3^cons2 == 262144).needs_parens_for_opcorrespondingly parenthesizes the LEFT^child;paren_if_necessaryparenthesizes a prefixed^base ((-a) ^ b, else the text re-parses as the sign-flipped-(a^b)).print_eqnreassociated floating-point sums, printingOp2(Add, a, Op2(Add, b, c))as the barea + b + c. Every left-associative operator now parenthesizes an equal-precedence right child,+and*included.The suggested guard is implemented:
mdl/writer_proptest.rs'sequation_write_reparse_is_fixpointnow assertsparse(print_eqn(e)) == eon the AST (green at 8192 cases), not merelyis_ok(). The end-to-end consequence --<>ornotinside any SMTH*/DELAY*/TREND argument being a hard compile failure viabuiltins_visitor'sprint_eqn-into-a-helper-aux round trip -- is pinned bybuiltins_visitor::tests::module_backed_builtin_argument_survives_print_and_reparse.Two Vensim precedence fixtures (
test/test-models/tests/arithmetics/,arithmetics_exp/) were in no run set at all, which is why the^associativity divergence went unnoticed; they are now insimulate.rs. Adding them also exposed a VM/wasm parity bug -- the wasm backend's open-codedpowreturned NaN for a negative base -- fixed inwasmgen/math.rs.Filed #914 for the separate (and more serious) finding this work surfaced:
mdl::parser's binary precedence table is inverted vs Vensim, andxmile_compat's precedence-free emission is what silently corrects it.bpowers commentedon Jul 9, 2026
All four printer defects are fixed on the #912/#913 branch, plus a fifth the new property test turned up. Summary of what
print_eqn(and its LaTeX/MDL siblings) used to emit that the engine's own parser rejects or misreads:Op1(Not, a)!a!rulenot aOp2(Neq, a, b)a != b<>a <> bOp1(Transpose, Op2(Add, a, b))a + b'balone(a + b)'Op1(Transpose, Op1(Negative, a))-a'(-a)'Op1(Transpose, App(abs, [a]))abs(a)'parse_appreturns theAppbeforeparse_postfixruns(abs(a))'Row 5 was found by a new property test rather than by inspection.
Blast radius on a real model
These are not cosmetic. Every LTM link score is a ceteris-paribus partial built by re-parsing
print_eqnoutput, andlink_scores.rsdeliberately skips a variable whose partial does not parse (emitting it unwrapped would silently score a constant magnitude of 1). So an unlexable spelling does not crash -- it quietly deletes the attribution.Measured on C-LEARN (
test/xmutil_test_models/C-LEARN v77 for Vensim.mdl), LTM enabled:PartialEquationErrorKind::Parsewarnings -> 50 targets droppedThe 50 recovered targets emit 182 additional link-score variables (
clearn_ltm_var_count_guardrail: 6,709 -> 6,891; per-step result-row width 30,800 -> 31,198 slots, well under the #654 ceiling of 65,536). Most of the 50 wereExpr0::Ifsitting directly under an operator -- the #912 parenthesization fix -- since Vensim'sIF THEN ELSEimports asExpr0::Ifand C-LEARN is full of them.Guards added
ast::print_eqn_proptest::print_eqn_roundtrips_over_the_full_operator_set-- assertsparse(print_eqn(e)) == eon the AST over everyBinaryOpvariant (behind an exhaustiveness guard so a new variant is a compile error) plus all fourUnaryOps. This is what caught row 5. The pre-existing MDL writer proptest cannot cover these operators; its generator is restricted to arithmetic because it re-reads withmdl::parser, whose binary precedence table is mdl: operator precedence differs from Vensim, breaking :NOT: comparisons #914.simulate::clearn_ltm_partials_all_parse(#[ignore]d, release) -- asserts C-LEARN produces zero "did not parse" LTM partial warnings. The var-count pin alone would be satisfied by any change landing on 6,891; this asserts the mechanism.ExportWarningfor a transpose, since Vensim has no transpose operator at all (mdl::parserhas no'token and noTransposenode) -- the export is degraded no matter what text is written, and this PR's theme is that degradation is never silent. The operand is grouped as well, so the emitted text at least denotes the tree the model has.Closable once the PR merges.