Skip to content

engine: add MDL writer for Vensim .mdl file export - #324

Merged
bpowers merged 19 commits into
mainfrom
mdl-writer
Feb 25, 2026
Merged

bpowers merged 19 commits into
mainfrom
mdl-writer

Conversation

@bpowers

@bpowers bpowers commented Feb 25, 2026

Copy link
Copy Markdown
Owner

Summary

  • Add complete MDL (Vensim) file writer to simlin-engine, enabling export from datamodel::Project to .mdl format
  • Implements expression conversion (Expr0 to MDL text), function name mapping (17 renames), argument reordering (3 functions), 9 pattern recognizers for reversible XMILE expansions, variable/equation serialization, sketch/view serialization, settings section, and full file assembly
  • Provides project_to_mdl() API and to_mdl() compat wrapper matching the existing to_xmile() pattern
  • 97 unit tests and 3 integration tests covering 42 MDL roundtrip files, 18 XMILE cross-format roundtrip files, and 5 sketch roundtrip files

Test plan

  • cargo test -p simlin-engine mdl::writer -- 97/97 unit tests pass
  • cargo test -p simlin-engine --test mdl_roundtrip -- 3/3 integration tests pass (42 MDL, 18 XMILE, 5 view roundtrip files)
  • Full engine test suite: 2314 passed, 0 failed
  • Pre-commit hooks pass (fmt, clippy, test, TypeScript, pysimlin)
  • Manual Vensim validation -- human test plan at docs/test-plans/2026-02-24-mdl-writer.md

@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review: engine: add MDL writer for Vensim .mdl file export

Thorough and well-tested PR. The pattern recognizers, function name mapping, argument reordering, and sketch serialization all look correct. 97 unit tests and 3 integration tests covering 42+18+5 roundtrip files is solid coverage. One bug found:

[P2] Duplicate ///---\\\ separator between sketch and settings sections

File: src/simlin-engine/src/mdl/writer.rs, lines 1098 and 1165

write_sketch_section() ends by emitting ///---\\\ (line 1098), and write_settings_section() starts by emitting the same ///---\\\ (line 1165). Since write_project() calls them sequentially, the generated MDL file contains a doubled separator:

...sketch elements...
///---\\\
///---\\\
:L<%^E!@

Real Vensim MDL files (e.g., test/test-models/samples/SIR/SIR.mdl lines 113-114) have only a single ///---\\\ before :L<%^E!@. The automated roundtrip tests still pass because the MDL parser is tolerant, but Vensim itself may reject or misparse files with the extra separator line — which would surface during the manual Vensim validation step (Phase 2 of the test plan). The fix is to remove the separator from either write_sketch_section or write_settings_section (not both).


Overall correctness: Correct — the patch is well-structured and the roundtrip tests validate semantic preservation. The duplicate separator is a non-blocking formatting issue that is unlikely to break the parser but should be fixed before manual Vensim validation.

@codecov

codecov Bot commented Feb 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 60.44304% with 125 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.59%. Comparing base (d667c5a) to head (a8e3193).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
src/simlin-engine/tests/mdl_roundtrip.rs 56.70% 113 Missing ⚠️
src/simlin-cli/src/main.rs 0.00% 6 Missing ⚠️
src/simlin-engine/src/ast/mod.rs 83.33% 6 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #324      +/-   ##
==========================================
+ Coverage   79.33%   79.59%   +0.25%     
==========================================
  Files         132      134       +2     
  Lines       31574    32534     +960     
==========================================
+ Hits        25049    25894     +845     
- Misses       6525     6640     +115     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review: engine: add MDL writer for Vensim .mdl file export

Findings

[P2] Duplicate ///---\\\ separator between sketch and settings sections

File: src/simlin-engine/src/mdl/writer.rs, lines 1270 and 1337

write_sketch_section() writes ///---\\\ as its terminator (line 1270), and write_settings_section() writes another ///---\\\ as its opening separator (line 1337). When called back-to-back in write_project(), this produces two consecutive ///---\\\ lines in the output. Real Vensim MDL files (e.g. test/test-models/samples/SIR/SIR.mdl line 113) have exactly one ///---\\\ between the last sketch element and :L<%^E!@. The automated roundtrip tests still pass because the parser is permissive (it searches for :L<%^E!@ anywhere in the remaining source) and the semantic equivalence checks don't compare raw text. However, the non-standard output could cause issues when files are opened in Vensim. The fix is to remove the self.buf.push_str("///---\\\\\\\n"); line from write_settings_section, since that separator already belongs to the sketch section's terminator.


Overall Correctness

Correct, with a minor format issue. The core logic — function name mappings, argument reordering, all 9 pattern recognizers, operator precedence/parenthesization, and control point computation — is verified to be correct and properly inverts the corresponding reader transformations. The duplicate separator is the only issue found; it does not break parsing or tests, but produces output that deviates from the Vensim MDL convention.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9efbd492d8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/simlin-engine/src/mdl/writer.rs Outdated
Comment on lines +104 to +105
Expr0::Op2(parent_op, _, _, _) => match child {
Expr0::Op2(child_op, _, _, _) => parent_op.precedence() > child_op.precedence(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve grouping for equal-precedence binary children

mdl_paren_if_necessary only adds parentheses when the child precedence is lower, so right-hand children with equal precedence are emitted unparenthesized. That changes semantics for non-associative forms during export/reparse (for example, a - (b - c) is written as a - b - c, and a / (b / c) as a / b / c), which can alter simulation results after MDL roundtrip.

Useful? React with 👍 / 👎.

Comment thread src/simlin-engine/src/mdl/writer.rs Outdated
/// the variable gets the flow's uid.
fn write_flow_element(buf: &mut String, flow: &view_element::Flow) {
let name = underbar_to_space(&flow.name);
let valve_uid = flow.uid - 1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Generate non-colliding valve UIDs for flow sketch output

Assigning valve_uid as flow.uid - 1 can produce duplicate sketch UIDs whenever another element already uses that value (which is common with contiguous IDs from imported models). Duplicate UIDs make the exported MDL sketch ambiguous and lead to element/link loss when the file is parsed back, corrupting view fidelity even though equations still parse.

Useful? React with 👍 / 👎.

@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review

[P2] Duplicate ///---\\\ separator between sketch and settings sections

File: src/simlin-engine/src/mdl/writer.rs, lines 1148 and 1218

write_sketch_section appends ///---\\\ as a sketch terminator (line 1148), and write_settings_section also prepends ///---\\\ as a settings separator (line 1218). Since write_project calls both sequentially, the assembled output contains two consecutive ///---\\\ lines where real MDL files (e.g. test/test-models/samples/SIR/SIR.mdl) have exactly one. The existing MDL parser is permissive enough to re-parse this, so roundtrip tests pass, but the output is non-standard and could trip up Vensim or third-party MDL parsers. The fix is to remove the line from one of the two methods.


Overall Correctness

Correct. The duplicate separator is the only concrete bug identified. The roundtrip tests (42 MDL, 18 XMILE, 5 sketch) all pass with the current parser, and the remaining logic — expression conversion, function name mapping, argument reordering, pattern recognizers, sketch serialization, and settings emission — is thorough and well-tested. The parenthesization logic in mdl_paren_if_necessary mirrors the existing child_needs_parens macro, so it does not introduce new behavior differences. Existing code and tests will not break.

Add writer.rs with expr0_to_mdl() that converts Expr0 AST nodes to
Vensim MDL-format equation text, and a project_to_mdl() stub in mod.rs.
The writer uses MDL operator syntax (MOD, <>, :AND:, :OR:) and converts
underscored identifiers back to spaced MDL names.
Add unit tests verifying XMILE Expr0 to MDL text conversion for
constants, NaN, variable references with name transformation,
arithmetic operators, precedence-driven parenthesization, and
unary operators.
UnaryOp::Not was emitting `!` (XMILE/C-style syntax) instead of
`:NOT:` which is what the MDL lexer recognizes. Added a test case
to cover this path.

Added a comment to project_to_mdl() explaining why ErrorKind::Import
is used for an export operation -- there is no Export variant in
ErrorKind, so Import is the closest available option.
Add xmile_to_mdl_function_name() that reverses the forward
format_function_name() table from xmile_compat.rs, mapping XMILE
canonical names (smth1, safediv, init, etc.) back to their Vensim
MDL equivalents (SMOOTH, ZIDZ, ACTIVE INITIAL, etc.).

Also add argument reordering for DELAY N, SMOOTH N, and RANDOM
NORMAL -- the three functions whose XMILE and MDL argument orders
differ.
Add recognize_vensim_patterns() pre-pass that collapses known XMILE
structural expansion shapes back to their compact Vensim builtin
forms before mechanical conversion.  Recognizers implemented for
all 9 reversible patterns: PULSE, PULSE TRAIN, QUANTUM, SAMPLE IF
TRUE, ALLOCATE BY PRIORITY, TIME BASE, RANDOM POISSON, LOG 2-arg,
and RANDOM 0 1.

Unrecognized expressions fall through to the standard mechanical
conversion path without error (AC2.5).
Add write_variable_entry() for serializing datamodel::Variable into
MDL format, handling Scalar, ApplyToAll, and Arrayed equation variants.
Includes lookup table formatting, subscript bracket notation with
underscore-to-space conversion, dimension definitions (named, indexed,
mapped), and data equation detection for the := operator.
Replace the project_to_mdl() stub with a real implementation that
validates the project (single model, no Module variables) and assembles
the full equations section. The MdlWriter struct orchestrates dimension
definitions, grouped and ungrouped variables, sim spec control variables
(INITIAL TIME, FINAL TIME, TIME STEP, SAVEPER), and the section
terminator.
Adds sketch section serialization to the MDL writer, converting
datamodel views back to Vensim sketch format:

- Type 10 (Variable): Aux, Stock, and Alias (ghost) elements
- Type 11 (Valve) + Type 10 (attached): Flow elements
- Type 12 (Comment): Cloud elements
- Type 1 (Connector): Link elements with arc angle transformation

The arc angle transformation reverses angle_from_points() by computing
a control point from the canvas-space arc angle using the tangent
direction at the start point and the chord geometry.

The complete sketch section includes the V300 header, view title,
font settings, all elements, and the terminator. A roundtrip test
verifies that teacup.mdl can be parsed, its sketch section
re-serialized, and the output re-parsed successfully.
MultiPoint connectors now emit all intermediate control points with the
correct npoints count, rather than silently discarding all points after
the first one.

build_element_positions now also registers the synthetic valve UID
(flow.uid - 1) emitted by write_flow_element, so that any connector
whose endpoint resolves to the valve position can find it without
falling back to (0,0).

The "View 1" hardcoded title gets an explanatory comment noting that
datamodel::StockFlow carries no view title and "View 1" matches
Vensim's default.

The unused _type11_count and _type12_count variables in the teacup
roundtrip test are renamed and wired into assertions covering valves
and clouds.
Complete the MDL writer by adding write_settings_section() which emits
the :L<%^E!@ marker, Type 15 (integration method), Type 22 (unit
equivalences), and standard Vensim defaults (Types 4, 19, 24-42).

Wire up write_project() to call all three sections (equations, sketch,
settings) in order. Add to_mdl() compat wrapper matching the to_xmile()
pattern.
Add tests/mdl_roundtrip.rs with three test suites:
- mdl_to_mdl_roundtrip: 55 MDL files parsed, written, re-parsed and
  compared for semantic equivalence (variable names, equations, sim specs,
  dimensions).
- xmile_to_mdl_roundtrip: 18 XMILE files converted to MDL and re-parsed,
  checking structural equivalence with canonical name normalization.
- view_element_roundtrip: 5 MDL files with sketch sections verified for
  variable name and link count preservation.
- write_mdl_for_vensim_validation (ignored): produces files for manual
  Vensim validation.

Fix in writer.rs: zero-argument XMILE builtins that are bare keywords in
MDL (Time, TIME STEP, INITIAL TIME, FINAL TIME) are now emitted without
parentheses. Previously TIME was written as TIME() which the MDL parser
rejects.
…rtions

mdl_bare_keyword() was missing "time_step" as an alias for "dt", even
though is_0_arity_builtin_fn() recognizes both. Without this, any Expr0
containing "time_step" would emit as TIME_STEP() instead of TIME STEP.

count_view_elements() returned a 6-tuple but call sites destructured only
the link count, silently discarding stocks/flows/auxes/clouds/aliases.
Strengthen the view_element_roundtrip assertion to compare all six element
type counts at once, so any roundtrip regression in any element type is
caught immediately.
Every other integration test file in tests/ is listed in the Tests
section. Add the new mdl_roundtrip.rs entry to keep documentation
consistent with the maintenance note at the top of the file.
The code review identified two uncovered acceptance criteria in the MDL
writer:

- AC2.2: no standalone test for the :AND:/:OR: logical operator
  conversion path (XMILE `and`/`or` -> MDL `:AND:`/`:OR:`).
- AC2.4: no test exercising recognize_allocate, the pattern that
  collapses the XMILE allocate() builtin back to MDL ALLOCATE BY
  PRIORITY. Adds both the subscripted form (demand[region.*] ->
  demand[region]) and the plain-variable fallback.
…lve UID allocation

Three bugs identified during code review:

1. is_data_equation() only checked for underscore-separated GET function
   names (GET_DIRECT, GET_XLS), but the normalizer produces space-separated
   forms ({GET DIRECT DATA(...)}). Now accepts both forms.

2. equation_to_mdl() ran data equation placeholders through Expr0 parsing,
   which would fail and fall back to underbar_to_space(), mangling content
   inside quoted literals. Data equations are now emitted verbatim with
   outer braces stripped.

3. Valve UIDs were computed as flow.uid - 1, which can collide with adjacent
   element UIDs (e.g., stock uid=1, flow uid=2 -> valve uid=1 = collision).
   Now allocates valve UIDs starting from max(all_element_uids) + 1.

Also narrows write_project() visibility from pub to pub(super) since it
should only be called through project_to_mdl().
…ITIAL

The MDL reader decomposes stock equations: INTEG(flow, init) is stored
as equation=init with separate inflows/outflows fields.  The writer was
emitting just the initial value, losing stock dynamics.  Now reconstructs
the full INTEG(net_flow, initial) expression from the decomposed fields.

Similarly, ACTIVE INITIAL(expr, init) is decomposed into equation=expr
with compat.active_initial=init.  The writer now wraps these back into
init(expr, init) in XMILE form, which equation_to_mdl converts to
ACTIVE INITIAL(...) in the MDL output.
@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review: engine: add MDL writer for Vensim .mdl file export

This is a well-structured and thoroughly tested MDL writer. The pattern recognizers for reversing XMILE structural expansions are particularly well done, and the 97 unit tests + 3 integration tests provide excellent coverage. Two issues noted below.

[P2] Duplicate ///---\\\ separator between sketch and settings sections

File: src/simlin-engine/src/mdl/writer.rs, lines ~1386 and ~1456

write_sketch_section ends by emitting ///---\\\ (the sketch terminator), and then write_settings_section begins by also emitting ///---\\\. When write_project calls both in sequence, the output contains two consecutive ///---\\\ lines before :L<%^E!@. Real MDL files (e.g. SIR.mdl, teacup.mdl) have exactly one. The automated roundtrip tests pass because the Simlin settings parser is permissive (it searches for :L<%^E!@ without validating the separator), but Vensim itself may reject or misinterpret the extra line. Since the manual Vensim validation (AC6.1) is still pending, this is worth fixing. The fix is to remove the ///---\\\ from either the end of write_sketch_section or the start of write_settings_section.

[P2] mdl_paren_if_necessary drops parentheses for right operands at equal precedence

File: src/simlin-engine/src/mdl/writer.rs, lines ~271-283

The function adds parentheses only when parent_op.precedence() > child_op.precedence(), but it does not distinguish whether the child is the left or right operand. For right operands of non-commutative operators (Sub, Div, Mod) where the child has the same precedence, this silently drops required parentheses. For example, the AST for a - (b + c) would be emitted as a - b + c, which re-parses as (a - b) + c — a different expression. Same issue applies to a / (b * c) → a / b * c. This mirrors the same limitation in ast::paren_if_necessary, so the author may have copied the behavior intentionally. However, since the MDL writer's primary use case is roundtrip fidelity, any equation containing these patterns would have its semantics silently altered. The fix would be to accept an is_right_child: bool parameter and add parens when is_right_child && parent_op.precedence() == child_op.precedence() for non-commutative parent operators.


Overall correctness: Correct. The patch is well-tested, internally consistent, and the integration roundtrip tests pass across 42 MDL files and 18 XMILE files. The duplicate separator is cosmetic for the Simlin parser and the parenthesization issue affects only a narrow class of expressions unlikely to appear in the current test suite. Neither issue would break existing tests or code.

@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review

[P2] Double ///---\\\ separator between sketch and settings sections

File: src/simlin-engine/src/mdl/writer.rs, lines 1214 and 1284

write_sketch_section emits ///---\\\ as its final line (line 1214), and write_settings_section emits another ///---\\\ as its first line (line 1284). This produces two consecutive ///---\\\ lines in the output, but every real Vensim MDL file in the test corpus (teacup.mdl, SIR.mdl, Lotka_Volterra.mdl, etc.) has exactly one ///---\\\ immediately followed by :L<%^E!@. The simlin parser is lenient enough that the internal roundtrip tests pass, but Vensim itself may reject or misparse the extra separator line since it deviates from the format produced by Vensim's own writer. The fix is to remove the ///---\\\ push from one of the two methods — either delete line 1214 from write_sketch_section or line 1284 from write_settings_section.


Overall Correctness

The patch is correct for internal simlin use — the 42 MDL roundtrip tests, 18 XMILE cross-format tests, and 97 unit tests all validate the core functionality. The single issue above is a format-level deviation that may only surface during manual Vensim validation (AC6.1). Beyond the double separator, the expression conversion, pattern recognizers, argument reordering, sketch serialization, and settings emission are well-implemented and thoroughly tested.

…s separator

Two bugs from PR review:

1. mdl_paren_if_necessary used strict > for precedence comparison on both
   children, so a - (b - c) was emitted as a - b - c (changing semantics).
   Now adds parens for right children of non-commutative same-precedence
   operators (-, /, MOD).

2. Both write_sketch_section and write_settings_section emitted ///---\\\,
   producing a duplicate separator in the output. Real MDL files have
   exactly one. Removed the duplicate from write_settings_section.
@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review: engine: add MDL writer for Vensim .mdl file export

Well-structured PR with extensive test coverage. The expression-to-MDL conversion, pattern recognizers, sketch serialization, and settings section all look correct. The argument reordering for DELAY N, SMOOTH N, and RANDOM NORMAL correctly inverts the xmile_compat transformations, and the precedence/parenthesization logic is sound.

Findings

[P2] write_stock_variable silently produces invalid MDL for arrayed/subscripted stocks

File: src/simlin-engine/src/mdl/writer.rs, lines 704–707

The initial value extraction only handles Equation::Scalar, returning an empty string for ApplyToAll and Arrayed variants. This produces invalid MDL like INTEG(net_flow, ) with no dimension subscript on the variable name. The MDL converter itself creates Variable::Stock with Equation::Arrayed at src/simlin-engine/src/mdl/convert/variables.rs:437, so this path is reachable for any model with subscripted stocks. The non-stock variable code paths (write_single_entry, write_arrayed_entries) correctly handle all equation types. The fix would be to either handle ApplyToAll/Arrayed in write_stock_variable (mirroring the aux/flow paths while reconstructing the INTEG wrapper) or return an error when encountering non-scalar stock equations, rather than silently emitting invalid output.

let initial = match &stock.equation {
    Equation::Scalar(eqn) => equation_to_mdl(eqn),
    _ => String::new(),  // <-- loses initial value and dimension info for arrayed stocks
};

Overall Correctness

Correct for the currently tested scope (scalar models and the 42+18+5 roundtrip test files). The arrayed-stock issue is a real bug but limited to subscripted stock variables, which are not in the current roundtrip test list. All other logic — expression conversion, function renaming, argument reordering, pattern recognition, sketch serialization, and settings emission — is correct and well-tested.

Port the right-child parenthesization fix from the MDL writer to the
XMILE equation printer (ast/mod.rs). Both paren_if_necessary and
paren_if_necessary1 now correctly preserve parens for right children
of non-commutative same-precedence operators (-, /, mod). Replaces
the child_needs_parens macros with shared needs_parens_for_op function.

Also add --to-mdl flag to simlin-cli convert subcommand, enabling
easy format conversion: `simlin convert --to-mdl input.xmile -o out.mdl`
@claude

claude Bot commented Feb 25, 2026

Copy link
Copy Markdown

Code Review: engine: add MDL writer for Vensim .mdl file export

Summary

This PR adds a complete MDL (Vensim) file writer to simlin-engine, enabling export from datamodel::Project to .mdl format. It includes expression conversion, function name mapping, argument reordering, 9 pattern recognizers for reversing XMILE structural expansions, variable/equation/sketch serialization, and full file assembly. It also fixes a pre-existing bug in parenthesization for right children of non-commutative operators in ast/mod.rs.

Findings

No bugs found. The implementation is thorough and correct for the cases it handles:

  • The parenthesization fix in ast/mod.rs (needs_parens_for_op) correctly adds parens for right children of Sub, Div, and Mod at equal precedence, preventing a - (b - c) from being erroneously printed as a - b - c. This applies consistently to both the XMILE PrintVisitor, LatexVisitor, and the new MdlPrintVisitor.
  • The 9 pattern recognizers (PULSE, PULSE TRAIN, QUANTUM, SAMPLE IF TRUE, LOG 2-arg, RANDOM 0 1, TIME BASE, RANDOM POISSON, ALLOCATE BY PRIORITY) correctly match the specific XMILE expansions generated by the codebase and collapse them back to their Vensim forms.
  • Function name mapping and argument reordering (DELAY N, SMOOTH N, RANDOM NORMAL) correctly invert the XMILE compat layer.
  • The sketch serializer correctly allocates non-conflicting valve UIDs, handles all element types (aux, stock, flow valve+variable, cloud, alias, link), and supports straight/arc/multipoint connectors.
  • Edge cases in compute_control_point (coincident endpoints, nearly-straight arcs) degrade gracefully.

The test coverage is excellent: 97 unit tests, 42 MDL roundtrip files, 18 XMILE cross-format roundtrip files, and 5 sketch roundtrip files.

Verdict

Correct. The patch introduces no bugs, existing tests continue to pass, and the new functionality is well-tested. The parenthesization change in ast/mod.rs is a legitimate bug fix that improves correctness of both existing and new printers.

@bpowers

bpowers commented Feb 25, 2026

Copy link
Copy Markdown
Owner Author

Review Cycle Summary

Four iterations of automated code review (Codex + Claude) identified and resolved several correctness issues:

Bugs fixed during review:

  • Right-child parenthesization (a - (b - c) was emitted as a - b - c): Fixed in both the MDL writer and the XMILE equation printer (ast/mod.rs) with a shared needs_parens_for_op() function
  • Stock INTEG reconstruction: The MDL reader decomposes INTEG(flow, init) into separate fields; the writer now reconstructs the full INTEG equation from inflows/outflows + initial value
  • ACTIVE INITIAL preservation: Variables with compat.active_initial are now wrapped back into ACTIVE INITIAL(expr, init) during export
  • Data equation detection: Now accepts both space-separated ({GET DIRECT DATA(...)}) and underscore-separated forms from the normalizer
  • Data equation content preservation: Data equations skip Expr0 parsing and emit verbatim to avoid mangling quoted literals
  • Valve UID collisions: Replaced flow.uid - 1 with proper UID allocation starting from max(all_uids) + 1
  • Duplicate ///---\\\ separator: Removed the extra separator between sketch and settings sections

Also added:

  • --to-mdl flag for simlin convert CLI command
  • to_mdl() re-exported from simlin_engine crate root

Deferred to follow-up issues (edge cases not exercised by any test model):

@bpowers
bpowers merged commit b714008 into main Feb 25, 2026
11 of 12 checks passed
@bpowers
bpowers deleted the mdl-writer branch February 25, 2026 17:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant