Repository navigation
engine: add MDL writer for Vensim .mdl file export - #324
Conversation
Code Review: engine: add MDL writer for Vensim .mdl file exportThorough 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
|
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
Code Review: engine: add MDL writer for Vensim .mdl file exportFindings[P2] Duplicate
|
There was a problem hiding this comment.
💡 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".
| Expr0::Op2(parent_op, _, _, _) => match child { | ||
| Expr0::Op2(child_op, _, _, _) => parent_op.precedence() > child_op.precedence(), |
There was a problem hiding this comment.
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 👍 / 👎.
| /// 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; |
There was a problem hiding this comment.
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 👍 / 👎.
Code Review[P2] Duplicate
|
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.
Code Review: engine: add MDL writer for Vensim .mdl file exportThis 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
|
Code Review[P2] Double
|
…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.
Code Review: engine: add MDL writer for Vensim .mdl file exportWell-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]
|
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`
Code Review: engine: add MDL writer for Vensim .mdl file exportSummaryThis PR adds a complete MDL (Vensim) file writer to FindingsNo bugs found. The implementation is thorough and correct for the cases it handles:
The test coverage is excellent: 97 unit tests, 42 MDL roundtrip files, 18 XMILE cross-format roundtrip files, and 5 sketch roundtrip files. VerdictCorrect. The patch introduces no bugs, existing tests continue to pass, and the new functionality is well-tested. The parenthesization change in |
Review Cycle SummaryFour iterations of automated code review (Codex + Claude) identified and resolved several correctness issues: Bugs fixed during review:
Also added:
Deferred to follow-up issues (edge cases not exercised by any test model):
|
Summary
project_to_mdl()API andto_mdl()compat wrapper matching the existingto_xmile()patternTest plan
cargo test -p simlin-engine mdl::writer-- 97/97 unit tests passcargo test -p simlin-engine --test mdl_roundtrip-- 3/3 integration tests pass (42 MDL, 18 XMILE, 5 view roundtrip files)docs/test-plans/2026-02-24-mdl-writer.md