Skip to content

engine: three more print_eqn/parser asymmetries (unary !, !=, and right-nested ^ re-parsing to a different AST) #913

Closed

Description

@bpowers

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_exponentiation right-associative to match the MDL reader, Vensim, and every mainstream language. A behavior change for any existing model containing a^b^c, and it also closes the parser-disagreement.
  • (b) keep left-associativity and make needs_parens_for_op add parens for an equal-precedence Exp right 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.rs
  • src/simlin-engine/src/parser/mod.rs (parse_exponentiation)

Activity

  1. bpowers commented on Jul 9, 2026

    @bpowers
    OwnerAuthor

    All three items in this issue -- plus a fourth found while fixing them -- are addressed in the #912 branch:

    • print_eqn emits not a (was !a) and a <> b (was a != b); both are now lexable.
    • The Transpose arm of PrintVisitor (and of LatexVisitor) routes through paren_if_necessary, so Op1(Transpose, a + b) prints (a + b)' rather than a + b'.
    • Item 3 (right-nested ^ re-parsing to a different AST) was fixed at the root: parser::parse_exponentiation is now RIGHT-associative, matching the XMILE spec 3.3.1, Vensim, mdl::parser::parse_power, and test/test-models/tests/arithmetics/output.tab (cons4^cons3^cons2 == 262144). needs_parens_for_op correspondingly parenthesizes the LEFT ^ child; paren_if_necessary parenthesizes a prefixed ^ base ((-a) ^ b, else the text re-parses as the sign-flipped -(a^b)).
    • Fourth, found by the strengthened property: print_eqn reassociated floating-point sums, printing Op2(Add, a, Op2(Add, b, c)) as the bare a + b + c. Every left-associative operator now parenthesizes an equal-precedence right child, + and * included.

    The suggested guard is implemented: mdl/writer_proptest.rs's equation_write_reparse_is_fixpoint now asserts parse(print_eqn(e)) == e on the AST (green at 8192 cases), not merely is_ok(). The end-to-end consequence -- <> or not inside any SMTH*/DELAY*/TREND argument being a hard compile failure via builtins_visitor's print_eqn-into-a-helper-aux round trip -- is pinned by builtins_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 in simulate.rs. Adding them also exposed a VM/wasm parity bug -- the wasm backend's open-coded pow returned NaN for a negative base -- fixed in wasmgen/math.rs.

    Filed #914 for the separate (and more serious) finding this work surfaced: mdl::parser's binary precedence table is inverted vs Vensim, and xmile_compat's precedence-free emission is what silently corrects it.

  2. bpowers commented on Jul 9, 2026

    @bpowers
    OwnerAuthor

    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:

    # AST was printed problem now
    1 Op1(Not, a) !a lexer has no ! rule not a
    2 Op2(Neq, a, b) a != b lexer accepts only <> a <> b
    3 Op1(Transpose, Op2(Add, a, b)) a + b' transposes b alone (a + b)'
    4 Op1(Transpose, Op1(Negative, a)) -a' negates the transpose (-a)'
    5 Op1(Transpose, App(abs, [a])) abs(a)' hard parse error -- parse_app returns the App before parse_postfix runs (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_eqn output, and link_scores.rs deliberately 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:

    • before: 50 PartialEquationErrorKind::Parse warnings -> 50 targets dropped
    • after: 0

    The 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 were Expr0::If sitting directly under an operator -- the #912 parenthesization fix -- since Vensim's IF THEN ELSE imports as Expr0::If and C-LEARN is full of them.

    Guards added

    • ast::print_eqn_proptest::print_eqn_roundtrips_over_the_full_operator_set -- asserts parse(print_eqn(e)) == e on the AST over every BinaryOp variant (behind an exhaustiveness guard so a new variant is a compile error) plus all four UnaryOps. 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 with mdl::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.
    • The MDL writer now emits an ExportWarning for a transpose, since Vensim has no transpose operator at all (mdl::parser has no ' token and no Transpose node) -- 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions