From 2407b5237485f47f0bfa0571ff8860a0bf07d389 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 06:03:34 -0500 Subject: [PATCH 1/4] fix(render): C# and Rust render dotted names, list length and zero as TypeScript does C# resolves a dotted name whole against each context, innermost outward, through Stubble's value getters (Stubble's Context is sealed): a context that holds only the first segment no longer hides an outer match, and a path that resolves to a present null stops there, as mustache.js does. The Rust metaobjects-render crate renders with its own Mustache engine over its tag scanner in place of mustache-ng, following the reference renderer's whole-path lookup, JavaScript properties (a list's length and index), truthiness (0 is falsy and still prints 0) and standalone-line rule. Closes the render-conformance drift entries render-shadowed-dotted-prefix (C#, Rust), render-list-length and render-zero-falsiness (Rust); both ledgers are now empty. --- AGENTS.md | 2 +- CHANGELOG.md | 10 + docs/CONFORMANCE.md | 16 +- docs/features/templates-and-payloads.md | 10 +- docs/ports/rust.md | 4 +- .../RenderConformanceTests.cs | 1 - .../MetaObjects.Render.Tests/RenderTests.cs | 23 + server/csharp/MetaObjects.Render/Renderer.cs | 54 ++- server/rust/Cargo.lock | 17 - server/rust/metaobjects-render/Cargo.toml | 3 - server/rust/metaobjects-render/README.md | 5 +- server/rust/metaobjects-render/src/lib.rs | 6 +- .../rust/metaobjects-render/src/mustache.rs | 430 ++++++++++++++++++ server/rust/metaobjects-render/src/render.rs | 122 +---- .../tests/render_conformance.rs | 20 +- 15 files changed, 548 insertions(+), 175 deletions(-) create mode 100644 server/rust/metaobjects-render/src/mustache.rs diff --git a/AGENTS.md b/AGENTS.md index d6277f7059..fa64da40ea 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,7 +75,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. **Cross-port conformance corpora** (every port runs the shared corpus): - Metamodel: `fixtures/conformance/` (584 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. -- Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python byte-identical; C# and Rust each carry a `KnownDrift` render ledger, recorded in `docs/CONFORMANCE.md`. +- Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python / C# / Rust byte-identical; the C# and Rust drift ledgers are empty (`docs/CONFORMANCE.md`). - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (the Node reference helper writes them; a native tool is equally first-class, ADR-0015 Amendment 2). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. - YAML / verify corpora green across the ports that ship those layers. diff --git a/CHANGELOG.md b/CHANGELOG.md index bce70b0d66..c824b18037 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,16 @@ here.** ## [Unreleased] +- **C# and Rust render dotted names, a list's `length` and `0` as TypeScript does.** C# resolves a + dotted name whole against each context, innermost outward, so a context holding only the first + segment no longer hides an outer match (`render-shadowed-dotted-prefix`). The Rust + `metaobjects-render` crate now renders with its own Mustache engine in place of `mustache-ng`: + the same whole-path lookup, a list's `length` as a number, and `0` falsy for a section while it + still prints as `0` (`render-list-length`, `render-zero-falsiness`). Both render-conformance + drift ledgers are empty. A Rust template that printed a list or an object now writes it as + JavaScript does (`1,2` / `[object Object]`) instead of nothing, and the U+FDD0 / U+FDD1 + characters are no longer refused. + ## [1.3.0] — 2026-12-01 diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index d023591f9b..1002bfd0f8 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -30,7 +30,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | 18 / 19 (1 ledgered: `yaml-ref-root-escape`, the ADR-0059 root-level `::` rules) | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | — | -| [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 26 | ✓ | ✓ | inherits via Java | 25 / 26 (1 ledgered: `render-shadowed-dotted-prefix`, Stubble stops a dotted name at the first context holding its first segment) | ✓ | 23 / 26 (3 ledgered: `render-shadowed-dotted-prefix`, `render-list-length`, `render-zero-falsiness`, `mustache-ng`'s lookup, data model and truthiness) | +| [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 26 | ✓ | ✓ | inherits via Java | ✓ | ✓ | ✓ | | [`fixtures/jinja-render-conformance/`](../fixtures/jinja-render-conformance/) (ADR-0061 — Jinja bodies render the same in jinja2 and nunjucks) | 16 | ✓ (nunjucks) | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | refuses, via Java | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | ✓ (jinja2) | refuses Jinja (`ERR_TEMPLATE_ENGINE_UNSUPPORTED`) | | [`fixtures/jinja-verify-conformance/`](../fixtures/jinja-verify-conformance/) (ADR-0061 — the payload check over a Jinja body) | 31 | ✓ | refuses Jinja | refuses, via Java | refuses Jinja | ✓ | refuses Jinja | | [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | ✓ | @@ -499,14 +499,12 @@ that must refuse carries `expected-error.txt` in place of `expected.txt`, holdin the render must raise (`render verify failed: ERR_VAR_NOT_ON_PAYLOAD ()`). Every port that runs this corpus reads that convention; every port requires it to appear in the raised message (Python's jinja runner compares it exactly). -Two engines read a case differently from the shared baseline (the TypeScript renderer on -mustache.js), and each runner ledgers the case instead of skipping it, asserting it STILL -differs so the ledger only shrinks. C# (Stubble) ledgers `render-shadowed-dotted-prefix`: it stops -a dotted name at the first context holding its first segment. Rust (`mustache-ng`) ledgers that -case, `render-list-length` (a list's `length` is not a property of its data) and -`render-zero-falsiness` (numbers reach the engine as text, so 0 is truthy). Closing a Rust entry -means resolving names and truthiness in the crate instead of the engine, which is larger than a -localized change and is not done here. +Every port renders every case byte-identical to the shared baseline (the TypeScript renderer on +mustache.js). The C# and Rust runners keep a drift ledger, empty today: a case an engine reads +differently is ledgered rather than skipped, and asserted to STILL differ, so the ledger only +shrinks. C# resolves a dotted name whole against each context through Stubble's value getters; +the Rust crate renders with its own Mustache engine, which follows the baseline's name lookup, +truthiness and whitespace rules. ### `fixtures/jinja-render-conformance/` (16) and `fixtures/jinja-verify-conformance/` (31) diff --git a/docs/features/templates-and-payloads.md b/docs/features/templates-and-payloads.md index 473edd2839..528576717d 100644 --- a/docs/features/templates-and-payloads.md +++ b/docs/features/templates-and-payloads.md @@ -834,12 +834,10 @@ via their respective conformance runners (Kotlin on the Java engine), and so doe `metaobjects-render` crate. See [`docs/CONFORMANCE.md`](../CONFORMANCE.md) for the per-port pass/skip ledger. -Two renderers still drift on a case their engine reads differently, and ledger it rather than -skip it: C# on `render-shadowed-dotted-prefix` (Stubble stops a dotted name at the first context -holding its first part), and Rust on that case, `render-list-length` and `render-zero-falsiness` -(the `mustache-ng` engine's own name lookup, data model and truthiness). A ledgered case must -still differ from the baseline, so an engine that comes into agreement fails its runner until the -entry leaves the ledger. +Every port renders every case the same. The C# and Rust runners keep a drift ledger, empty +today: a case an engine reads differently is ledgered rather than skipped, and must still differ +from the baseline, so an engine that comes into agreement fails its runner until the entry leaves +the ledger. **Jinja bodies (Python and TypeScript, ADR-0061)** diff --git a/docs/ports/rust.md b/docs/ports/rust.md index c8313e0147..a313f949a2 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -30,7 +30,7 @@ The loader is the `metaobjects` crate, and the workspace at `server/rust/` adds | Registry | The type registry and the built-in providers. It is strict and sealed after bootstrap, with the same `ERR_*` codes as the other ports. | | Validation | All 41 validation passes the TypeScript loader runs, in the same order, the business-rules pass among them (operations, permission names and lifecycles, [ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)). The ordered list is `PASSES` in `server/rust/metaobjects/src/validate/mod.rs`. | | Serializer | The canonical serializer. A tree it loads serializes to the same bytes the other ports write. | -| Prompt rendering | `metaobjects_render::render` renders a `template.*` body over a JSON payload as every port does: partials expanded ahead of time, each `{{value}}` escaped for the template's format (`text`, `markdown`, `html`, `xml`, `csv`, `spreadsheet`, `json`), derived `has` and `-last` accessors, and a fail-closed `maxChars` budget. The Mustache engine underneath is the `mustache-ng` crate. | +| Prompt rendering | `metaobjects_render::render` renders a `template.*` body over a JSON payload as every port does: partials expanded ahead of time, each `{{value}}` escaped for the template's format (`text`, `markdown`, `html`, `xml`, `csv`, `spreadsheet`, `json`), derived `has` and `-last` accessors, and a fail-closed `maxChars` budget. The Mustache engine is the crate's own, following the reference renderer's name lookup, truthiness and whitespace rules. | | Reply parser | `metaobjects_render::extract::extract` reads a typed answer out of a model's reply (FR-010, FR-011): fences, prose, comments, trailing commas and cut-off values tolerated, every declared field classified (`EXTRACTED`, `DEFAULTED`, `LOST_OPTIONAL`, `LOST_REQUIRED`, `MALFORMED`) and coerced to its kind, under a `STRICT`, `NORMAL` or `LOOSE` tolerance. `metaobjects_render::prompt::render_output_format` writes the output-format fragment that asks for that answer, in the `guide`, `inline` and `exampleOnly` styles. | | Frozen tree | The loader freezes the tree when it finishes. A frozen tree memoizes its resolved reads (effective children, attributes and array-ness), so many readers can share one. | | Timings | Every load records how long each phase and each validation pass took (`LoadResult::timings`). | @@ -630,7 +630,7 @@ outright. | `template-output-render-conformance` | the welcome page and email, the nested payload and the cross-package payloads, rendered through generated `render-helper` crates that a probe builds; the drift cases fail `gen`, and a body edited after generation fails the render | | `verify-conformance` | all 45 cases, through `metaobjects_render::verify`, the check `cargo meta verify --templates` runs, with no ledgered case and no Rust expectation file | | `generator-registry-conformance` | the shipped generators are exactly the registry's `rust` entries, with its tier and layer, and the eject contract's census, completeness and depth hold (ADR-0034 Amendment 8) | -| `render-conformance` | every case but the three the ledger holds — `render-shadowed-dotted-prefix`, `render-list-length`, `render-zero-falsiness` (`mustache-ng` has its own name lookup, data model and truthiness); a ledgered case must still differ, the rest render byte-identical through `metaobjects_render::render` (the Mustache engine underneath is `mustache-ng`) | +| `render-conformance` | every case, byte-identical through `metaobjects_render::render` (the crate's own Mustache engine); the drift ledger is empty, and a case added to it must still differ | | `response-verify-conformance` | all 7 cases: the reply check the template gate adds — `ERR_RESPONSE_UNRESOLVED`, and, for an xml prompt, `ERR_RESPONSE_TAG_UNDECLARED` | | `extract-conformance` | all 58 cases, through `metaobjects_render::extract::extract` | | `output-prompt-conformance` | all 17 cases in all three `@promptStyle` styles, with the extract round trip, through `metaobjects_render::prompt::render_output_format` | diff --git a/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs b/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs index 8ec1754aa8..c9b2cf5d3e 100644 --- a/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs +++ b/server/csharp/MetaObjects.Render.Tests/RenderConformanceTests.cs @@ -23,7 +23,6 @@ public class RenderConformanceTests /// private static readonly HashSet KnownDrift = new(StringComparer.Ordinal) { - "render-shadowed-dotted-prefix", }; private static string CorpusRoot() diff --git a/server/csharp/MetaObjects.Render.Tests/RenderTests.cs b/server/csharp/MetaObjects.Render.Tests/RenderTests.cs index ddc7239ea7..124d9b3be1 100644 --- a/server/csharp/MetaObjects.Render.Tests/RenderTests.cs +++ b/server/csharp/MetaObjects.Render.Tests/RenderTests.cs @@ -142,4 +142,27 @@ public void Deterministic_same_inputs_identical_output() Assert.Equal(a, b); Assert.Equal("1|2|3|", a); } + + // A dotted name is tried WHOLE against each context, innermost outward (mustache.js). Where the + // whole path resolves to a present null, that context wins: it renders empty and is falsy, and + // the outer value is NOT reached. + [Fact] + public void A_dotted_path_resolving_to_a_present_null_stops_at_that_context() + { + var payload = Obj( + ("a", Obj(("b", Obj(("v", 1L))))), + ("items", new List { Obj(("a", Obj(("b", Obj(("v", null)))))) })); + Assert.Equal("[]none", Render("text", payload, P(), + template: "{{#items}}[{{a.b.v}}]{{^a.b.v}}none{{/a.b.v}}{{/items}}")); + } + + [Fact] + public void A_shadowed_dotted_prefix_falls_through_in_triple_ampersand_and_changed_delimiters() + { + var payload = Obj( + ("a", Obj(("b", "<1>"))), + ("items", new List { Obj(("a", Obj(("c", 2L)))) })); + Assert.Equal("<1>|<1>|<1>", Render("html", payload, P(), + template: "{{#items}}{{{a.b}}}|{{& a.b}}|{{=<% %>=}}<% a.b %><%={{ }}=%>{{/items}}")); + } } diff --git a/server/csharp/MetaObjects.Render/Renderer.cs b/server/csharp/MetaObjects.Render/Renderer.cs index aae4dcef09..d25e1b08ac 100644 --- a/server/csharp/MetaObjects.Render/Renderer.cs +++ b/server/csharp/MetaObjects.Render/Renderer.cs @@ -114,7 +114,9 @@ public static string Render(RenderRequest request) .SetEncodingFunction(v => escaper(v)) .AddValueGetter(PayloadAccessors.ViewType, PayloadAccessors.ViewLookup) .AddValueGetter(typeof(List), (value, key, ignoreCase) => - key == LengthProperty ? ((System.Collections.IList)value).Count : elementAt(value, key, ignoreCase))) + key == LengthProperty ? ((System.Collections.IList)value).Count : elementAt(value, key, ignoreCase)) + .AddValueGetter(typeof(object), WholePathGetter) + .AddTruthyCheck(_ => false)) .Build(); // Derived `has` accessors are part of the payload contract, not of the @@ -122,7 +124,7 @@ public static string Render(RenderRequest request) // resolves the same way it does against a generated JVM payload record. object? view = PayloadAccessors.WithDerivedAccessors(request.Payload); FailOnMissingVariable(expanded, view); - string result = stubble.Render(expanded, view); + string result = stubble.Render(JoinDottedNames(expanded), view); if (request.MaxChars is int cap && result.Length > cap) throw new RenderException( @@ -236,4 +238,52 @@ private static bool TryProperty(object? ctx, string key, out object? value) } private const string LengthProperty = "length"; + + // Stubble walks a dotted name segment by segment and STOPS at the first context that holds its + // first segment, where mustache.js tries the whole path against each context from the innermost + // outward. Stubble's Context is sealed, so the whole-path rule is installed through its value + // getters instead: every dotted name the engine will look up is handed to it as ONE key, its + // dots replaced by PathSeparator, so Stubble's own context walk (innermost outward, first hit + // wins) asks each context for the whole path and WholePathGetter resolves it with TryWalk, the + // same walk the missing-variable check uses. A private-use character, so no authored name holds it. + private const char PathSeparator = '\uE000'; + + private static string JoinDottedNames(string template) + { + List tags; + try { tags = MustacheTags.Scan(template); } + catch (MustacheSyntaxException) { return template; } // the engine reports a malformed template itself + var sb = new System.Text.StringBuilder(template); + foreach (var tag in tags) + { + if (tag.Kind is not (MustacheTagKind.Name or MustacheTagKind.Triple or MustacheTagKind.Amp + or MustacheTagKind.Section or MustacheTagKind.Inverted or MustacheTagKind.Close)) continue; + string name = tag.Value.Trim('{', '}').Trim(); + if (name.IndexOf('.') <= 0) continue; // "." and ".x" are not dotted paths to the engine either + int at = template.IndexOf(name, tag.Start, tag.End - tag.Start, StringComparison.Ordinal); + if (at < 0) continue; + for (int i = at; i < at + name.Length; i++) + if (sb[i] == '.') sb[i] = PathSeparator; + } + return sb.ToString(); + } + + private static readonly RendererSettingsDefaults.ValueGetterDelegate ObjectMember = + RendererSettingsDefaults.DefaultValueGetters()[typeof(object)]; + + private static object? WholePathGetter(object value, string key, bool ignoreCase) + { + if (key.IndexOf(PathSeparator) < 0) return ObjectMember(value, key, ignoreCase); + if (!TryWalk(value, key.Split(PathSeparator), out object? found)) return null; // try the next context out + return found ?? ResolvedNull.Instance; + } + + /// A whole path that resolved to a present null. Stubble reads a null from a getter as + /// "not here" and moves on to the next context out; mustache.js stops at the context where the path + /// resolved, so the null is handed over as this marker, which renders empty and is falsy. + private sealed class ResolvedNull + { + internal static readonly ResolvedNull Instance = new(); + public override string ToString() => ""; + } } diff --git a/server/rust/Cargo.lock b/server/rust/Cargo.lock index 05e3eda173..2d82574b22 100644 --- a/server/rust/Cargo.lock +++ b/server/rust/Cargo.lock @@ -86,12 +86,6 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" -[[package]] -name = "log" -version = "0.4.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" - [[package]] name = "memchr" version = "2.8.3" @@ -136,7 +130,6 @@ name = "metaobjects-render" version = "1.3.0" dependencies = [ "indexmap", - "mustache-ng", "serde", "serde_json", ] @@ -147,16 +140,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" -[[package]] -name = "mustache-ng" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26ccc530f826bda40b9e9cb2014feac34984d23aec58a559a6b4232a7f1e133b" -dependencies = [ - "log", - "serde", -] - [[package]] name = "num-traits" version = "0.2.19" diff --git a/server/rust/metaobjects-render/Cargo.toml b/server/rust/metaobjects-render/Cargo.toml index 34fe8d6ec4..5992cd38be 100644 --- a/server/rust/metaobjects-render/Cargo.toml +++ b/server/rust/metaobjects-render/Cargo.toml @@ -13,9 +13,6 @@ keywords = ["metadata", "prompt", "mustache", "template", "llm"] categories = ["template-engine", "text-processing"] [dependencies] -# The maintained fork of the `mustache` crate (MIT/Apache-2.0). Its library name is -# still `mustache`, so the code says `use mustache::`. -mustache-ng = "0.10.0" serde_json.workspace = true serde.workspace = true indexmap.workspace = true diff --git a/server/rust/metaobjects-render/README.md b/server/rust/metaobjects-render/README.md index a54a357f64..09392defd4 100644 --- a/server/rust/metaobjects-render/README.md +++ b/server/rust/metaobjects-render/README.md @@ -10,8 +10,9 @@ in every MetaObjects port: - a payload carries derived `has` booleans and a `-last` flag on each object element of a list; - `maxChars` is a fail-closed budget: an over-budget render is an error, never a truncation. -The Mustache engine underneath is [`mustache-ng`](https://crates.io/crates/mustache-ng). The -behaviour is held to the shared `fixtures/render-conformance/` corpus that every port runs. +The Mustache engine is the crate's own: it resolves names, reads truthiness and removes standalone +lines as the reference renderer does, so a template renders the same bytes as in every other port. +The behaviour is held to the shared `fixtures/render-conformance/` corpus that every port runs. The other half of a prompt is the answer. `extract::extract` reads a typed answer out of a model's reply, tolerating fences, prose, comments, trailing commas and cut-off values, and reports how each diff --git a/server/rust/metaobjects-render/src/lib.rs b/server/rust/metaobjects-render/src/lib.rs index e33a50df25..9fed0f0cdb 100644 --- a/server/rust/metaobjects-render/src/lib.rs +++ b/server/rust/metaobjects-render/src/lib.rs @@ -4,8 +4,9 @@ //! same way every MetaObjects port does: partials expanded ahead of time, every //! `{{value}}` escaped for the template's format, derived `has` and `-last` //! accessors on the payload, a fail-closed `maxChars` budget, and a variable missing from -//! the payload refused rather than rendered empty (`ERR_VAR_NOT_ON_PAYLOAD`). The engine underneath is -//! the `mustache-ng` crate; what is specific to MetaObjects sits here, on top of it. The +//! the payload refused rather than rendered empty (`ERR_VAR_NOT_ON_PAYLOAD`). The Mustache engine +//! is this crate's own, following the reference renderer's name lookup, truthiness and +//! whitespace rules, so a template renders the same bytes here as in every other port. The //! shared `fixtures/render-conformance/` corpus holds this crate to the other ports. //! //! [`extract`] is the other half of a prompt: the tolerant reply parser that reads a typed @@ -30,6 +31,7 @@ pub mod accessors; pub mod escapers; pub mod extract; pub mod filesystem; +mod mustache; pub mod presence; pub mod prompt; pub mod render; diff --git a/server/rust/metaobjects-render/src/mustache.rs b/server/rust/metaobjects-render/src/mustache.rs new file mode 100644 index 0000000000..e03072f399 --- /dev/null +++ b/server/rust/metaobjects-render/src/mustache.rs @@ -0,0 +1,430 @@ +//! The Mustache engine: a template's tags rendered over a JSON payload, by the rules the reference +//! renderer (the TypeScript port, on mustache.js) follows. +//! +//! The crate owns this rather than handing the template to a general Mustache engine, because +//! what a render produces is decided here and has to agree, byte for byte, with every other port: +//! +//! - **Lookup.** A name is tried against each context from the innermost outward, and the first +//! context on which it resolves wins. A dotted name is tried WHOLE against each context: one that +//! holds the first segment but not the rest, or whose walk reaches a null, is skipped, not a stop. +//! A present `null` resolves (it renders empty, and it stops the walk outward). +//! - **Properties.** An object's key, a list's index and a list's `length`, as a JavaScript property +//! read finds them; a string's `length` and indices too, when they end a dotted name. +//! - **Truthiness.** `false`, `null`, `0`, `NaN` and `""` are falsy; a list renders its body once +//! per element; any object is truthy. A number keeps its value for printing, so `0` is falsy +//! for a section and still prints as `0`. +//! - **Whitespace.** A line holding only whitespace and tags that print nothing (sections, closes, +//! comments), and at least one of them, is removed whole, its newline included. +//! - **Printing.** A number prints in its shortest form, a whole float as an integer; a boolean as +//! `true` / `false`; `null` as nothing; a list as its elements joined with `,` and an object as +//! `[object Object]`, as JavaScript writes them. A string is escaped for the format, unless the +//! tag is raw (`{{{x}}}`, `{{&x}}`); a number is never escaped. +//! +//! Partials are expanded before this runs and set-delimiter tags are refused, so neither reaches it. + +use std::borrow::Cow; + +use serde_json::Value; + +use crate::escapers; +use crate::tags::{Tag, TagKind}; + +/// The current-context name. +const IMPLICIT_ITERATOR: &str = "."; +/// The list and string property a JavaScript read finds. +const LENGTH: &str = "length"; + +/// Render the scanned `tags` of `text` over `payload`, escaping each `{{value}}` for `format`. +/// +/// # Errors +/// `format` is not a registered render format. +pub(crate) fn render( + text: &str, + tags: &[Tag], + payload: &Value, + format: &str, +) -> Result { + if !escapers::is_format(format) { + return Err(format!("unknown render format \"{format}\"")); + } + let tokens = tokenize(text, tags); + let mut out = String::with_capacity(text.len()); + let mut stack = vec![Cow::Borrowed(payload)]; + render_tokens(&tokens, &mut stack, format, &mut out); + Ok(out) +} + +/// A piece of the template: literal text (already stripped of standalone lines) or a tag. +enum Token<'t> { + Text(String), + Tag(&'t Tag), +} + +/// The template as text and tags, with every standalone line removed. +/// +/// The rule is the reference engine's: on each line, every whitespace character of the text is +/// removed, the newline included, when the line holds at least one tag and neither a +/// non-whitespace character nor an interpolation. +fn tokenize<'t>(text: &str, tags: &'t [Tag]) -> Vec> { + // Byte offsets of the whitespace characters to drop. + let mut dropped = vec![false; text.len()]; + let mut line = LineState::default(); + let mut pos = 0; + for tag in tags { + line.text(&text[pos..tag.start], pos, &mut dropped); + line.has_tag = true; + if matches!(tag.kind, TagKind::Name | TagKind::Triple | TagKind::Amp) { + line.non_space = true; + } + pos = tag.end; + } + line.text(&text[pos..], pos, &mut dropped); + line.strip(&mut dropped); + + let kept = |from: usize, to: usize| -> String { + text[from..to] + .char_indices() + .filter(|(i, _)| !dropped[from + i]) + .map(|(_, c)| c) + .collect() + }; + let mut tokens = Vec::with_capacity(tags.len() * 2 + 1); + let mut pos = 0; + for tag in tags { + tokens.push(Token::Text(kept(pos, tag.start))); + tokens.push(Token::Tag(tag)); + pos = tag.end; + } + tokens.push(Token::Text(kept(pos, text.len()))); + tokens +} + +/// What the standalone rule tracks about the current line. +#[derive(Default)] +struct LineState { + has_tag: bool, + non_space: bool, + /// Byte offsets of the line's whitespace characters. + spaces: Vec, +} + +impl LineState { + fn text(&mut self, segment: &str, offset: usize, dropped: &mut [bool]) { + for (i, c) in segment.char_indices() { + if is_js_whitespace(c) { + self.spaces.push(offset + i); + } else { + self.non_space = true; + } + if c == '\n' { + self.strip(dropped); + } + } + } + + fn strip(&mut self, dropped: &mut [bool]) { + if self.has_tag && !self.non_space { + for &at in &self.spaces { + dropped[at] = true; + } + } + self.spaces.clear(); + self.has_tag = false; + self.non_space = false; + } +} + +/// JavaScript's `\s`: Unicode white space, plus the byte-order mark. +fn is_js_whitespace(c: char) -> bool { + c.is_whitespace() || c == '\u{FEFF}' +} + +fn render_tokens<'a>( + tokens: &[Token<'_>], + stack: &mut Vec>, + format: &str, + out: &mut String, +) { + let mut i = 0; + while i < tokens.len() { + match &tokens[i] { + Token::Text(text) => out.push_str(text), + Token::Tag(tag) => match tag.kind { + TagKind::Name => { + if let Some(value) = lookup(&tag.value, stack) { + print(&value, Some(format), out); + } + } + TagKind::Triple | TagKind::Amp => { + if let Some(value) = lookup(&tag.value, stack) { + print(&value, None, out); + } + } + TagKind::Section | TagKind::Inverted => { + let close = matching_close_token(tokens, i); + let body = &tokens[i + 1..close]; + let value = lookup(&tag.value, stack); + if tag.kind == TagKind::Inverted { + if value.as_deref().is_none_or(is_falsy_or_empty) { + render_tokens(body, stack, format, out); + } + } else if let Some(value) = value.filter(|v| is_truthy(v)) { + render_section(value, body, stack, format, out); + } + i = close; + } + TagKind::Close | TagKind::Partial | TagKind::Comment | TagKind::Delimiters => {} + }, + } + i += 1; + } +} + +/// A truthy section's body: once per element of a list, once with the value as the context for an +/// object, a string or a number, and once in the current context for `true`. +fn render_section<'a>( + value: Cow<'a, Value>, + body: &[Token<'_>], + stack: &mut Vec>, + format: &str, + out: &mut String, +) { + match value { + Cow::Borrowed(Value::Array(items)) => { + for item in items { + stack.push(Cow::Borrowed(item)); + render_tokens(body, stack, format, out); + stack.pop(); + } + } + Cow::Owned(Value::Array(items)) => { + for item in items { + stack.push(Cow::Owned(item)); + render_tokens(body, stack, format, out); + stack.pop(); + } + } + Cow::Borrowed(Value::Bool(_)) | Cow::Owned(Value::Bool(_)) => { + render_tokens(body, stack, format, out); + } + other => { + stack.push(other); + render_tokens(body, stack, format, out); + stack.pop(); + } + } +} + +/// The token index of the close that ends the section opened at `open`. +fn matching_close_token(tokens: &[Token<'_>], open: usize) -> usize { + let mut depth = 0usize; + for (offset, token) in tokens[open + 1..].iter().enumerate() { + let Token::Tag(tag) = token else { continue }; + match tag.kind { + TagKind::Section | TagKind::Inverted => depth += 1, + TagKind::Close if depth == 0 => return open + 1 + offset, + TagKind::Close => depth -= 1, + _ => {} + } + } + tokens.len() +} + +/// `name` resolved against the context stack, innermost first. `None` means absent. +pub(crate) fn lookup<'a>(name: &str, stack: &[Cow<'a, Value>]) -> Option> { + if name == IMPLICIT_ITERATOR { + return stack.last().cloned(); + } + let dotted = name.find('.').is_some_and(|at| at > 0); + stack.iter().rev().find_map(|context| { + if dotted { + resolve_path(context, name) + } else { + // An undotted name is looked up only on an object or a list, as JavaScript's `in`. + match context.as_ref() { + Value::Object(_) | Value::Array(_) => property(context, name), + _ => None, + } + } + }) +} + +/// A dotted name walked from `context`: it resolves when its last segment is a property of the +/// value the leading segments reach. +fn resolve_path<'a>(context: &Cow<'a, Value>, name: &str) -> Option> { + let mut value = context.clone(); + for segment in name.split('.') { + value = property(&value, segment)?; + } + Some(value) +} + +/// One property of a JSON value, as a JavaScript property read finds it. +fn property<'a>(value: &Cow<'a, Value>, key: &str) -> Option> { + match value { + Cow::Borrowed(v) => borrowed_property(v, key), + Cow::Owned(v) => borrowed_property(v, key).map(|p| Cow::Owned(p.into_owned())), + } +} + +fn borrowed_property<'a>(value: &'a Value, key: &str) -> Option> { + match value { + Value::Object(map) => map.get(key).map(Cow::Borrowed), + Value::Array(items) if key == LENGTH => Some(Cow::Owned(Value::from(items.len()))), + Value::Array(items) => array_index(key) + .and_then(|i| items.get(i)) + .map(Cow::Borrowed), + Value::String(s) if key == LENGTH => { + Some(Cow::Owned(Value::from(s.encode_utf16().count()))) + } + Value::String(s) => array_index(key) + .and_then(|i| { + let unit = *s.encode_utf16().collect::>().get(i)?; + Some(String::from_utf16_lossy(&[unit])) + }) + .map(|c| Cow::Owned(Value::String(c))), + _ => None, + } +} + +/// `key` as a JavaScript array index: a canonical non-negative integer. +fn array_index(key: &str) -> Option { + let i = key.parse::().ok()?; + (i.to_string() == key).then_some(i) +} + +/// JavaScript truthiness: `false`, `null`, `0`, `NaN` and `""` are falsy, everything else truthy. +fn is_truthy(value: &Value) -> bool { + match value { + Value::Null => false, + Value::Bool(b) => *b, + Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()), + Value::String(s) => !s.is_empty(), + Value::Array(_) | Value::Object(_) => true, + } +} + +/// What an inverted section renders for: a falsy value or an empty list. +fn is_falsy_or_empty(value: &Value) -> bool { + !is_truthy(value) || value.as_array().is_some_and(Vec::is_empty) +} + +/// Write `value` as the reference engine prints it; `escape_for` is the format of an escaped tag. +fn print(value: &Value, escape_for: Option<&str>, out: &mut String) { + match value { + Value::Null => {} + // A number is never escaped, as the reference engine writes it. + Value::Number(n) => out.push_str(&number_text(n)), + other => { + let text = js_string(other); + match escape_for.and_then(|format| escapers::escape(format, &text)) { + Some(escaped) => out.push_str(&escaped), + None => out.push_str(&text), + } + } + } +} + +/// `String(value)` as JavaScript writes it. +fn js_string(value: &Value) -> String { + match value { + Value::Null => String::new(), + Value::Bool(b) => b.to_string(), + Value::Number(n) => number_text(n), + Value::String(s) => s.clone(), + Value::Array(items) => items + .iter() + .map(|item| match item { + Value::Null => String::new(), + other => js_string(other), + }) + .collect::>() + .join(","), + Value::Object(_) => "[object Object]".to_string(), + } +} + +/// A number in its shortest text, with a whole float written as an integer (`2.0` -> `2`), as +/// the other ports write them. +pub(crate) fn number_text(n: &serde_json::Number) -> String { + if n.is_i64() || n.is_u64() { + return n.to_string(); + } + match n.as_f64() { + Some(f) if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e21 => format!("{f:.0}"), + Some(f) => f.to_string(), + None => n.to_string(), + } +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use crate::escapers::FORMAT_TEXT; + use crate::tags::scan; + + fn run(template: &str, payload: &Value) -> String { + super::render( + template, + &scan(template).expect("scan"), + payload, + FORMAT_TEXT, + ) + .expect("render") + } + + #[test] + fn a_dotted_name_is_tried_whole_against_each_context() { + let p = json!({ "a": { "b": 1 }, "items": [{ "a": { "c": 2 } }, { "a": { "b": 8 } }, { "a": null }] }); + assert_eq!(run("{{#items}}[{{a.b}}]{{/items}}", &p), "[1][8][1]"); + } + + #[test] + fn a_present_null_stops_the_walk_outward() { + let p = json!({ "v": 1, "a": { "b": 1 }, "items": [{ "v": null, "a": { "b": null } }] }); + assert_eq!(run("{{#items}}[{{v}}|{{a.b}}]{{/items}}", &p), "[|]"); + } + + #[test] + fn length_and_index_read_as_javascript_properties() { + let p = json!({ "xs": [[1, 2], []], "s": "héllo", "ys": ["a", "b"] }); + assert_eq!(run("{{#xs}}{{length}};{{/xs}}", &p), "2;0;"); + assert_eq!(run("{{s.length}} {{s.1}} {{ys.1}} {{ys.01}}", &p), "5 é b "); + } + + #[test] + fn zero_and_nan_free_numbers_follow_javascript_truthiness() { + let p = json!({ "z": 0, "f": 0.0, "n": 2.5, "e": "" }); + assert_eq!( + run( + "{{#z}}y{{/z}}{{^z}}n{{/z}}{{#f}}y{{/f}}{{^f}}n{{/f}}{{#n}}[{{.}}]{{/n}}{{^e}}empty{{/e}}", + &p + ), + "nn[2.5]empty" + ); + } + + #[test] + fn lists_and_objects_print_as_javascript_writes_them() { + let p = json!({ "xs": [1, null, "a", [2, 3]], "o": {}, "t": true }); + assert_eq!( + run("{{xs}}|{{o}}|{{t}}", &p), + "1,,a,2,3|[object Object]|true" + ); + } + + #[test] + fn standalone_lines_are_removed_whole() { + let p = json!({ "items": [1, 2] }); + assert_eq!( + run( + "start\n {{#items}}\n- {{.}}\n {{/items}} \n{{! note }}\nend", + &p + ), + "start\n- 1\n- 2\nend" + ); + // A line that also interpolates keeps its whitespace. + assert_eq!(run(" {{#items}}{{.}}{{/items}}\n", &p), " 12\n"); + } +} diff --git a/server/rust/metaobjects-render/src/render.rs b/server/rust/metaobjects-render/src/render.rs index 92d6878283..e0dbb7e8c8 100644 --- a/server/rust/metaobjects-render/src/render.rs +++ b/server/rust/metaobjects-render/src/render.rs @@ -1,26 +1,23 @@ //! The render pipeline for `template.*` (FR-004). //! //! Resolve the body (inline, or by reference through a [`Provider`]), expand partials ahead -//! of time (cycle-guarded, at most [`MAX_DEPTH`] deep), render the result with the -//! `mustache-ng` engine over the payload and its derived accessors, escaping every -//! `{{value}}` for the template's format, then apply the `maxChars` budget, which fails -//! rather than truncates. +//! of time (cycle-guarded, at most [`MAX_DEPTH`] deep), render the result with this +//! crate's Mustache engine ([`crate::mustache`]) over the payload and its derived accessors, +//! escaping every `{{value}}` for the template's format, then apply the `maxChars` budget, +//! which fails rather than truncates. //! //! Expanding partials first gives the same whitespace in every port and keeps cycle -//! detection here. The engine's own HTML escaping is never used: each escaped tag is -//! rewritten to a raw one between two marker characters, and the text between the markers -//! is escaped for the format once the engine has finished. Set-delimiter tags are refused, -//! as the Python and C# renderers refuse them. +//! detection here. Set-delimiter tags are refused, as the Python and C# renderers refuse them. use std::collections::HashMap; use std::fmt; -use mustache::Data; use serde::Serialize; use serde_json::Value; use crate::accessors::with_derived_accessors; use crate::escapers::{self, FORMAT_TEXT}; +use crate::mustache; use crate::presence::{ERR_VAR_NOT_ON_PAYLOAD, first_missing}; use crate::tags::{self, TagKind}; use crate::verify::{self, PayloadField, VerifyOptions}; @@ -28,12 +25,6 @@ use crate::verify::{self, PayloadField, VerifyOptions}; /// How deep partials may nest before the render fails. pub const MAX_DEPTH: usize = 32; -/// Opens an escaped value in the engine's output. U+FDD0 and U+FDD1 are Unicode -/// noncharacters, reserved for exactly this kind of internal use. -const OPEN_MARK: char = '\u{FDD0}'; -/// Closes an escaped value in the engine's output. -const CLOSE_MARK: char = '\u{FDD1}'; - /// File extensions of Jinja templates (ADR-0061), which this renderer does not run. const JINJA_EXTENSIONS: [&str; 2] = [".jinja", ".j2"]; @@ -153,9 +144,8 @@ impl<'a> RenderRequest<'a> { /// /// # Errors /// An unknown format, an unresolved body or partial, a partial cycle or one nested deeper -/// than [`MAX_DEPTH`], a Jinja partial, a template syntax error, a set-delimiter tag, a -/// marker character in the template or payload, an interpolated name the payload does -/// not carry (`ERR_VAR_NOT_ON_PAYLOAD`), or output over the `maxChars` budget. +/// than [`MAX_DEPTH`], a Jinja partial, a template syntax error, a set-delimiter tag, an +/// interpolated name the payload does not carry (`ERR_VAR_NOT_ON_PAYLOAD`), or output over the `maxChars` budget. pub fn render(request: &RenderRequest<'_>) -> Result { if !escapers::is_format(request.format) { return err(format!("unknown render format \"{}\"", request.format)); @@ -181,14 +171,7 @@ pub fn render(request: &RenderRequest<'_>) -> Result { "render verify failed: {ERR_VAR_NOT_ON_PAYLOAD} ({name})" )); } - let source = mark_escaped_tags(&expanded, request.format)?; - let data = to_data(&payload)?; - let template = mustache::compile_str(&source) - .map_err(|e| RenderError(format!("template syntax error: {e}")))?; - let raw = template - .render_data_to_string(&data) - .map_err(|e| RenderError(format!("render failed: {e}")))?; - let out = escape_marked(&raw, request.format)?; + let out = mustache::render(&expanded, &found, &payload, request.format).map_err(RenderError)?; check_budget(out, request.max_chars) } @@ -344,92 +327,6 @@ fn pre_expand_partials( Ok(out) } -/// Rewrite every escaped `{{name}}` as a raw `{{&name}}`, between the markers unless the -/// format escapes nothing. Raw tags stay as they are. -fn mark_escaped_tags(text: &str, format: &str) -> Result { - if text.contains([OPEN_MARK, CLOSE_MARK]) { - return err("template contains a reserved character (U+FDD0 or U+FDD1)"); - } - let found = tags::scan(text).map_err(|e| syntax(&e))?; - let identity = escapers::is_identity(format); - let mut out = String::with_capacity(text.len() + 16); - let mut pos = 0; - for tag in found.iter().filter(|t| t.kind == TagKind::Name) { - out.push_str(&text[pos..tag.start]); - if identity { - out.push_str(&format!("{{{{&{}}}}}", tag.value)); - } else { - out.push(OPEN_MARK); - out.push_str(&format!("{{{{&{}}}}}", tag.value)); - out.push(CLOSE_MARK); - } - pos = tag.end; - } - out.push_str(&text[pos..]); - Ok(out) -} - -fn escape_marked(raw: &str, format: &str) -> Result { - if escapers::is_identity(format) { - return Ok(raw.to_string()); - } - let mut out = String::with_capacity(raw.len()); - let mut rest = raw; - while let Some(open) = rest.find(OPEN_MARK) { - out.push_str(&rest[..open]); - let after = &rest[open + OPEN_MARK.len_utf8()..]; - let Some(close) = after.find(CLOSE_MARK) else { - return err("internal: unterminated escape marker"); - }; - let escaped = escapers::escape(format, &after[..close]) - .ok_or_else(|| RenderError(format!("unknown render format \"{format}\"")))?; - out.push_str(&escaped); - rest = &after[close + CLOSE_MARK.len_utf8()..]; - } - out.push_str(rest); - Ok(out) -} - -/// The payload as the engine's data. Numbers become their shortest text, with a whole -/// float written as an integer (`2.0` -> `2`), as the other ports write them. -fn to_data(value: &Value) -> Result { - Ok(match value { - Value::Null => Data::Null, - Value::Bool(b) => Data::Bool(*b), - Value::Number(n) => Data::String(number_text(n)), - Value::String(s) => { - if s.contains([OPEN_MARK, CLOSE_MARK]) { - return err("payload contains a reserved character (U+FDD0 or U+FDD1)"); - } - // An empty string is falsy for a section AND for an inverted section. The - // engine skips `{{#x}}` over "" but also skips `{{^x}}`, so "" goes in as - // null, which renders the same in every other position. - if s.is_empty() { - Data::Null - } else { - Data::String(s.clone()) - } - } - Value::Array(items) => Data::Vec(items.iter().map(to_data).collect::>()?), - Value::Object(map) => Data::Map( - map.iter() - .map(|(k, v)| Ok((k.clone(), to_data(v)?))) - .collect::>()?, - ), - }) -} - -fn number_text(n: &serde_json::Number) -> String { - if n.is_i64() || n.is_u64() { - return n.to_string(); - } - match n.as_f64() { - Some(f) if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e21 => format!("{f:.0}"), - Some(f) => f.to_string(), - None => n.to_string(), - } -} - #[cfg(test)] mod tests { use super::*; @@ -486,7 +383,6 @@ mod tests { let p = json!({}); assert!(run("{{=<% %>=}}", &p, "text").is_err()); assert!(run("x", &p, "yaml").is_err()); - assert!(run("\u{FDD0}", &p, "text").is_err()); let provider = InMemoryProvider::default(); assert!(render(&RenderRequest::new(Body::Ref("t.jinja"), &p, &provider)).is_err()); } diff --git a/server/rust/metaobjects-render/tests/render_conformance.rs b/server/rust/metaobjects-render/tests/render_conformance.rs index 3211f02b49..0675c6d86b 100644 --- a/server/rust/metaobjects-render/tests/render_conformance.rs +++ b/server/rust/metaobjects-render/tests/render_conformance.rs @@ -19,23 +19,9 @@ use serde_json::Value; use metaobjects_render::{Body, InMemoryProvider, RenderRequest, render}; -/// Cases the `mustache-ng` engine renders differently from the shared baseline, each with the -/// rule it does not implement. Closing them means resolving names and section truthiness in this -/// crate instead of the engine. -const KNOWN_DRIFT: &[(&str, &str)] = &[ - ( - "render-shadowed-dotted-prefix", - "the engine stops a dotted name at the first context holding its first segment", - ), - ( - "render-list-length", - "a list's `length` is not a property of the engine's data", - ), - ( - "render-zero-falsiness", - "numbers reach the engine as text, so 0 is truthy", - ), -]; +/// Cases this crate's engine renders differently from the shared baseline, each with the rule it +/// does not implement. None today. +const KNOWN_DRIFT: &[(&str, &str)] = &[]; fn corpus() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/render-conformance") From 5d737c49ecc2fead8d489c89eeff625e24be6160 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 08:06:13 -0500 Subject: [PATCH 2/4] no-mistakes(review): apply reviewer inline fixes --- server/rust/metaobjects-render/src/render.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/rust/metaobjects-render/src/render.rs b/server/rust/metaobjects-render/src/render.rs index e0dbb7e8c8..1fec93a7a3 100644 --- a/server/rust/metaobjects-render/src/render.rs +++ b/server/rust/metaobjects-render/src/render.rs @@ -7,7 +7,8 @@ //! which fails rather than truncates. //! //! Expanding partials first gives the same whitespace in every port and keeps cycle -//! detection here. Set-delimiter tags are refused, as the Python and C# renderers refuse them. +//! detection here. Set-delimiter tags are refused, as the Python renderer refuses them (the C# +//! renderer refuses them only in a template that also uses partials). use std::collections::HashMap; use std::fmt; From df606b2f2be5f94bacc8fc331007613169f5d8c4 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 08:09:20 -0500 Subject: [PATCH 3/4] no-mistakes(review): Fix C# list-index lookup and Rust presence parity --- .../MetaObjects.Render.Tests/RenderTests.cs | 29 ++++ server/csharp/MetaObjects.Render/Renderer.cs | 28 +++- .../rust/metaobjects-render/src/mustache.rs | 13 +- .../rust/metaobjects-render/src/presence.rs | 125 ++++++------------ server/rust/metaobjects-render/src/render.rs | 19 +++ 5 files changed, 125 insertions(+), 89 deletions(-) diff --git a/server/csharp/MetaObjects.Render.Tests/RenderTests.cs b/server/csharp/MetaObjects.Render.Tests/RenderTests.cs index 124d9b3be1..9822f186d8 100644 --- a/server/csharp/MetaObjects.Render.Tests/RenderTests.cs +++ b/server/csharp/MetaObjects.Render.Tests/RenderTests.cs @@ -165,4 +165,33 @@ public void A_shadowed_dotted_prefix_falls_through_in_triple_ampersand_and_chang Assert.Equal("<1>|<1>|<1>", Render("html", payload, P(), template: "{{#items}}{{{a.b}}}|{{& a.b}}|{{=<% %>=}}<% a.b %><%={{ }}=%>{{/items}}")); } + + // A list index is a property to mustache.js (`"0" in arr`), so a dotted name reads through it; + // a non-canonical index (`01`) is not a property, so it is a missing variable, as in TS. + [Fact] + public void A_dotted_name_reads_a_list_element_by_index() + { + var payload = Obj(("items", new List { Obj(("name", "x")) })); + Assert.Equal("First: x", Render("text", payload, P(), + template: "{{#items.0}}First: {{name}}{{/items.0}}")); + Assert.Equal("x", Render("text", payload, P(), template: "{{items.0.name}}")); + var ex = Assert.Throws(() => Render("text", payload, P(), template: "{{items.01}}")); + Assert.Equal("render verify failed: ERR_VAR_NOT_ON_PAYLOAD (items.01)", ex.Message); + } + + private sealed class Dynamic : System.Dynamic.DynamicObject + { + public override IEnumerable GetDynamicMemberNames() => ["x"]; + + public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object? result) + { + result = binder.Name == "x" ? "42" : null; + return binder.Name == "x"; + } + } + + [Fact] + public void A_dotted_name_through_a_dynamic_object_reads_its_member() => + Assert.Equal("42", Render("text", Obj(("obj", Obj(("dyn", new Dynamic())))), P(), + template: "{{obj.dyn.x}}")); } diff --git a/server/csharp/MetaObjects.Render/Renderer.cs b/server/csharp/MetaObjects.Render/Renderer.cs index d25e1b08ac..ceeb9c5245 100644 --- a/server/csharp/MetaObjects.Render/Renderer.cs +++ b/server/csharp/MetaObjects.Render/Renderer.cs @@ -225,18 +225,38 @@ private static bool TryWalk(object? ctx, string[] segs, out object? value) return true; } - // One property read, as JavaScript finds it: a payload member, or a list's `length`. + // One property read, as JavaScript finds it: a payload member, a list's `length`, or a list's + // index (a canonical non-negative integer, so `0` and not `01`). A dynamic object cannot say + // which members it lacks, so every name on it is present, with the value it reads as. private static bool TryProperty(object? ctx, string key, out object? value) { - if (PayloadAccessors.TryLookup(ctx, key, out value)) return true; - if (key == LengthProperty && ctx is ICollection list and not IDictionary) + if (ctx is System.Dynamic.IDynamicMetaObjectProvider) { - value = list.Count; + value = DynamicMember(ctx, key, false); return true; } + if (PayloadAccessors.TryLookup(ctx, key, out value)) return true; + if (ctx is IList items and not IDictionary) + { + if (key == LengthProperty) + { + value = items.Count; + return true; + } + if (int.TryParse(key, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int index) + && index.ToString(System.Globalization.CultureInfo.InvariantCulture) == key + && index < items.Count) + { + value = items[index]; + return true; + } + } return false; } + private static readonly RendererSettingsDefaults.ValueGetterDelegate DynamicMember = + RendererSettingsDefaults.DefaultValueGetters()[typeof(System.Dynamic.IDynamicMetaObjectProvider)]; + private const string LengthProperty = "length"; // Stubble walks a dotted name segment by segment and STOPS at the first context that holds its diff --git a/server/rust/metaobjects-render/src/mustache.rs b/server/rust/metaobjects-render/src/mustache.rs index e03072f399..01a10128ae 100644 --- a/server/rust/metaobjects-render/src/mustache.rs +++ b/server/rust/metaobjects-render/src/mustache.rs @@ -134,9 +134,9 @@ impl LineState { } } -/// JavaScript's `\s`: Unicode white space, plus the byte-order mark. +/// JavaScript's `\s`: Unicode white space except NEL (U+0085), plus the byte-order mark. fn is_js_whitespace(c: char) -> bool { - c.is_whitespace() || c == '\u{FEFF}' + (c.is_whitespace() && c != '\u{0085}') || c == '\u{FEFF}' } fn render_tokens<'a>( @@ -294,7 +294,7 @@ fn array_index(key: &str) -> Option { } /// JavaScript truthiness: `false`, `null`, `0`, `NaN` and `""` are falsy, everything else truthy. -fn is_truthy(value: &Value) -> bool { +pub(crate) fn is_truthy(value: &Value) -> bool { match value { Value::Null => false, Value::Bool(b) => *b, @@ -305,7 +305,7 @@ fn is_truthy(value: &Value) -> bool { } /// What an inverted section renders for: a falsy value or an empty list. -fn is_falsy_or_empty(value: &Value) -> bool { +pub(crate) fn is_falsy_or_empty(value: &Value) -> bool { !is_truthy(value) || value.as_array().is_some_and(Vec::is_empty) } @@ -426,5 +426,10 @@ mod tests { ); // A line that also interpolates keeps its whitespace. assert_eq!(run(" {{#items}}{{.}}{{/items}}\n", &p), " 12\n"); + // NEL is not white space to JavaScript's `\s`, so its line is not standalone. + assert_eq!( + run("a\n{{#items}}\u{0085}\n{{/items}}b", &p), + "a\n\u{0085}\n\u{0085}\nb" + ); } } diff --git a/server/rust/metaobjects-render/src/presence.rs b/server/rust/metaobjects-render/src/presence.rs index d456dfc0b9..dc5ffffb99 100644 --- a/server/rust/metaobjects-render/src/presence.rs +++ b/server/rust/metaobjects-render/src/presence.rs @@ -16,56 +16,53 @@ //! - Only what would render is checked: the body of a falsy section and of a truthy //! inverted section is skipped, and a list section checks its body once per element. +use std::borrow::Cow; + use serde_json::Value; +use crate::mustache; use crate::tags::{Tag, TagKind}; /// The error code every port raises for a variable that is not on the payload. pub const ERR_VAR_NOT_ON_PAYLOAD: &str = "ERR_VAR_NOT_ON_PAYLOAD"; -/// The current-context name. -const IMPLICIT_ITERATOR: &str = "."; - /// The first interpolated name in `tags` that the payload does not carry, if any. #[must_use] pub fn first_missing(tags: &[Tag], payload: &Value) -> Option { - let mut stack = vec![payload]; + let mut stack = vec![Cow::Borrowed(payload)]; walk(tags, &mut stack) } -fn walk<'a>(tags: &[Tag], stack: &mut Vec<&'a Value>) -> Option { +/// Names resolve through the engine's own lookup and truthiness, so this check and the render +/// cannot disagree on what is present or on which bodies render. +fn walk<'a>(tags: &[Tag], stack: &mut Vec>) -> Option { let mut i = 0; while i < tags.len() { let tag = &tags[i]; match tag.kind { TagKind::Name | TagKind::Triple | TagKind::Amp => { - if lookup(&tag.value, stack).is_none() { + if mustache::lookup(&tag.value, stack).is_none() { return Some(tag.value.clone()); } } TagKind::Section | TagKind::Inverted => { let close = matching_close(tags, i); let body = &tags[i + 1..close]; - let value = lookup(&tag.value, stack); - let truthy = value.is_some_and(is_truthy); - if tag.kind == TagKind::Inverted { - let missing = if truthy { None } else { walk(body, stack) }; - if missing.is_some() { - return missing; + let value = mustache::lookup(&tag.value, stack); + let missing = if tag.kind == TagKind::Inverted { + if value.as_deref().is_none_or(mustache::is_falsy_or_empty) { + walk(body, stack) + } else { + None } - } else if let Some(value) = value.filter(|v| is_truthy(v)) { - let contexts: Vec<&'a Value> = match value { - Value::Array(items) => items.iter().collect(), - other => vec![other], - }; - for context in contexts { - stack.push(context); - let missing = walk(body, stack); - stack.pop(); - if missing.is_some() { - return missing; - } + } else { + match value.filter(|v| mustache::is_truthy(v)) { + Some(value) => walk_section(value, body, stack), + None => None, } + }; + if missing.is_some() { + return missing; } i = close; } @@ -76,6 +73,29 @@ fn walk<'a>(tags: &[Tag], stack: &mut Vec<&'a Value>) -> Option { None } +/// A truthy section's body, with the contexts the engine renders it in. +fn walk_section<'a>( + value: Cow<'a, Value>, + body: &[Tag], + stack: &mut Vec>, +) -> Option { + let contexts: Vec> = match value { + Cow::Borrowed(Value::Array(items)) => items.iter().map(Cow::Borrowed).collect(), + Cow::Owned(Value::Array(items)) => items.into_iter().map(Cow::Owned).collect(), + Cow::Borrowed(Value::Bool(_)) | Cow::Owned(Value::Bool(_)) => return walk(body, stack), + other => vec![other], + }; + for context in contexts { + stack.push(context); + let missing = walk(body, stack); + stack.pop(); + if missing.is_some() { + return missing; + } + } + None +} + /// The index of the close tag that ends the section opened at `open`. The scanner has /// already refused unbalanced sections, so a close always exists; the end of the list is /// the fallback. @@ -92,63 +112,6 @@ pub(crate) fn matching_close(tags: &[Tag], open: usize) -> usize { tags.len() } -/// `name` resolved against the context stack, innermost first. `None` means absent. -fn lookup<'a>(name: &str, stack: &[&'a Value]) -> Option<&'a Value> { - if name == IMPLICIT_ITERATOR { - return stack.last().copied(); - } - let segments: Vec<&str> = name.split('.').collect(); - stack - .iter() - .rev() - .find_map(|context| resolve(context, &segments)) -} - -fn resolve<'a>(context: &'a Value, segments: &[&str]) -> Option<&'a Value> { - segments.iter().try_fold(context, |value, segment| { - property(value, segment).or_else(|| { - let items = value.as_array().filter(|_| *segment == LENGTH)?; - Some(if items.is_empty() { - &LENGTH_ZERO - } else { - &LENGTH_NONZERO - }) - }) - }) -} - -/// The list property JavaScript exposes and the reference check therefore treats as present. -const LENGTH: &str = "length"; - -/// One property of a JSON value, as a JavaScript property read would find it: an object's -/// key, or a list's index. (A list's `length` is handled by `resolve`.) -fn property<'a>(value: &'a Value, key: &str) -> Option<&'a Value> { - match value { - Value::Object(map) => map.get(key), - Value::Array(items) => key.parse::().ok().and_then(|i| items.get(i)), - _ => None, - } -} - -/// Placeholders for a list's `length`, which is a property in JavaScript and so is present to the -/// reference check. The value is never rendered; only presence and truthiness matter, so an empty -/// list's length stands as falsy and any other as a truthy `true`. -static LENGTH_ZERO: Value = Value::Bool(false); -static LENGTH_NONZERO: Value = Value::Bool(true); - -/// Mustache truthiness as the reference engine reads it: `false`, `null`, `0`, `""` and an -/// empty list are falsy. -fn is_truthy(value: &Value) -> bool { - match value { - Value::Null => false, - Value::Bool(b) => *b, - Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0), - Value::String(s) => !s.is_empty(), - Value::Array(items) => !items.is_empty(), - Value::Object(_) => true, - } -} - #[cfg(test)] mod tests { use serde_json::json; diff --git a/server/rust/metaobjects-render/src/render.rs b/server/rust/metaobjects-render/src/render.rs index 1fec93a7a3..0d933356b4 100644 --- a/server/rust/metaobjects-render/src/render.rs +++ b/server/rust/metaobjects-render/src/render.rs @@ -379,6 +379,25 @@ mod tests { assert_eq!(e.0, "unresolved partial: nope"); } + #[test] + fn the_missing_variable_check_reads_names_as_the_engine_does() { + let p = json!({ "ys": ["a", "b"], "s": "hello" }); + assert_eq!( + run("{{ys.01}}", &p, "text").unwrap_err().0, + "render verify failed: ERR_VAR_NOT_ON_PAYLOAD (ys.01)" + ); + assert_eq!( + run("{{ys.1}} {{s.length}} {{s.0}}", &p, "text").unwrap(), + "b 5 h" + ); + assert_eq!( + run("{{#s.length}}{{missing}}{{/s.length}}", &p, "text") + .unwrap_err() + .0, + "render verify failed: ERR_VAR_NOT_ON_PAYLOAD (missing)" + ); + } + #[test] fn refuses_what_it_does_not_run() { let p = json!({}); From 76ea89261828f32944f2ee5e04f40792f9490632 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 2 Dec 2026 08:26:30 -0500 Subject: [PATCH 4/4] no-mistakes(document): ADR-0065 amended; gen-check.lock regenerated but mustache-ng still pinned --- .../metaobjects-codegen/tests/gen-check.lock | 5 +---- .../ADR-0065-rust-is-the-sixth-port.md | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/server/rust/metaobjects-codegen/tests/gen-check.lock b/server/rust/metaobjects-codegen/tests/gen-check.lock index 7d204303ac..52c35b99d8 100644 --- a/server/rust/metaobjects-codegen/tests/gen-check.lock +++ b/server/rust/metaobjects-codegen/tests/gen-check.lock @@ -703,7 +703,7 @@ checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ "allocator-api2", "equivalent", - "foldhash 0.1.5", + "foldhash", ] [[package]] @@ -1804,8 +1804,6 @@ version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ - "foldhash 0.2.0", - "indexmap", "itoa", "memchr", "serde", @@ -2265,7 +2263,6 @@ dependencies = [ "mio", "pin-project-lite", "socket2", - "tokio-macros", "windows-sys 0.61.2", ] diff --git a/spec/decisions/ADR-0065-rust-is-the-sixth-port.md b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md index 28e9896315..7209efbaca 100644 --- a/spec/decisions/ADR-0065-rust-is-the-sixth-port.md +++ b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md @@ -387,3 +387,24 @@ to infer it. with a lifecycle and a policy. The `rust` lane checks its committed generated crates with a forced `verify` and runs its HTTP test. It stands in for an adopter estate until one runs the Rust port; it is not one, and G3d (ADR-0035 Amendment 3) is not met by it. + +## Amendment 8: the render engine is the crate's own (2026-12-02) + +Decision 2 says `metaobjects-render` renders "over the `mustache-ng` crate". It no longer does. The +crate renders with its own Mustache engine, `server/rust/metaobjects-render/src/mustache.rs`, and +depends on no Mustache crate. The `mustache-ng` dependency is gone; `mustache.rs` is the only +engine in the crate. + +Why the crate owns the engine: cross-port render parity with the TypeScript reference, which is the +render output of record. `mustache-ng`'s lookup, its text-only number data model and its truthiness +could not match TypeScript on three points, and the render conformance ledger carried each one as a +difference: + +- dotted-name lookup: a dotted name is tried whole against each context before it is split, as the + TypeScript renderer does (`{{#items.0}}`, `{{a.b}}` where `a.b` is a key); +- zero falsiness: a numeric `0` is falsy in a section, as in TypeScript, where `mustache-ng` received + numbers as text and treated `0` as truthy; +- a list's `length`, readable from a dotted path. + +Decision 2's layout is otherwise unchanged. The `render-shadowed-dotted-prefix`, `render-list-length` +and `render-zero-falsiness` fixtures run in Rust without a ledger entry (`docs/CONFORMANCE.md`).