diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index 81c8556ad6..e72e5684ca 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -3,6 +3,7 @@ paths: - "server/csharp/**" - "server/java/**" - "server/python/**" + - "server/rust/**" - "server/typescript/**" - "client/web/**" - "spec/**" @@ -15,7 +16,7 @@ paths: Preserve the following contracts exactly across all language ports: -**Metamodel subtype vocabularies (must be identical across languages):** the `registry-conformance` gate (`fixtures/registry-conformance/`) is the structural enforcer of this rule — each port emits its registry as a canonical manifest byte-matched to `expected-registry.json`. **All five ports (TS / C# / Java / Kotlin / Python) are live + green** (SP-G Java/Kotlin reconciliation complete; the JVM runners compose from the defined metamodel provider set so codegen-base/om classpath SPI does not pollute the measured vocabulary). See `fixtures/registry-conformance/README.md`. +**Metamodel subtype vocabularies (must be identical across languages):** the `registry-conformance` gate (`fixtures/registry-conformance/`) is the structural enforcer of this rule — each port emits its registry as a canonical manifest byte-matched to `expected-registry.json`. **All five shipped ports (TS / C# / Java / Kotlin / Python) plus Rust in preview (ADR-0065, byte-identical) are live + green** (SP-G Java/Kotlin reconciliation complete; the JVM runners compose from the defined metamodel provider set so codegen-base/om classpath SPI does not pollute the measured vocabulary). See `fixtures/registry-conformance/README.md`. - Filter operators: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `like`, `isNull` - Object subtypes: `entity` (owns data: own identity, writable sources, lifecycle), `value` (pure shape: NO identity, NO source, ever; constructed — by caller/embedding — never populated; may `extends` entity fields for shape; a value-hosted field may carry `origin.passthrough` but never an assembly origin), `projection` (derived read-only representation: fields `extends`-bound / origin-derived / self-declared-under-external-assembly, all read-only at subtype level; identity optional and MUST extend an entity identity; sources restricted to read-only `@kind`s; the declared field set IS the exposure — inclusive list, fail-closed). A field carrying `origin.*` is derived ⇒ read-only wherever it lives (incl. on entities). An entity's primary source must be a writable `@kind` (read-only kinds only in read role). See [ADR-0028](spec/decisions/ADR-0028-object-taxonomy-projection-value-purity.md). (FR-024 Phase E — `object.projection`/`value` are registered in `expected-registry.json` and the projection/value validation passes [identity pass-through, value-purity, projection-licensing, `@via` inference/cardinality, extends/origin agreement, derived-field providability] are enforced cross-port in all 5 ports. The **B4b** entity-primary-source-readonly cutover [the "writable `@kind`" clause above — `ERR_ENTITY_PRIMARY_SOURCE_READONLY`] + the projection codegen fan-out (read-only DTOs for view-kind projections; FR-015 proc-callables for proc-kind projections in TypeScript, C# and Kotlin ONLY — Java and Python ship no callable generator at all, so the cross-port claim does NOT cover that clause; api-docs label `object.projection` units as `projection` and document their generated `Dto`) are now shipped cross-port; the remaining FR-024 work is the declared-API surface — tracked in #10.) **`report` (FR-044 Plan 1)** is a root object subtype registered in all five ports, with the `dimension.attribute` / `dimension.time` / `measure.aggregate` / `measure.ratio` / `segment.filter` children on `object.entity` and the relative-date filter value — loader-validated (`ERR_INVALID_DIMENSION` / `ERR_INVALID_MEASURE` / `ERR_INVALID_REPORT` / `ERR_REPORT_FOREIGN_MEASURE`, plus `ERR_BAD_ATTR_FILTER` for relative dates off a reporting host) and, since FR-044 Plan 2, **lowered only when it declares a read-only `source.rdb` of `@kind: view`**: `meta migrate` creates that view (TypeScript only, ADR-0015), every port reads it (persistence corpus, `report-shapes.json`), C# generates its typed row and Kotlin its Exposed table object, and, since FR-044 Plan 3, every port's generators **serve it as a keyless read-only projection** (GET list with filter/sort/paging on every derived field that has a filter band, `POST` 405, no `/{id}`; row type + filter allowlist + route/controller per port, gated by the api-contract `report/` sub-corpus in the generated lane). The client UI tier (hooks, grids, forms) and a report with no view source at all stay inert, gated by the 43 `reporting` conformance fixtures and the `codegen-noop` corpus. A served report is the predicate `servedReport` (TS) / `ReportRows.IsViewBacked` (C#) / `RestSurfaceGate.isServedReport` (Java, Kotlin) / `is_served_report` (Python): concrete, read source `@kind: view`. See [docs/features/reporting.md](docs/features/reporting.md). - Source subtypes: `rdb` (paradigm; ADR-0007). The pre-v2 `dbTable`/`dbView` subtypes are RETIRED — `source.rdb` + `@kind: table|view|materializedView|storedProc|tableFunction` is the form, with read-only-ness derived from `@kind`. Multi-source via `@role` (exactly one `primary` per object). Source physical name = `@table` (NOT `@name`); field physical name = `@column` (renamed from `@dbColumn`). Referential actions on relationships: `@onDelete` / `@onUpdate`. diff --git a/.github/workflows/local-ci.yml b/.github/workflows/local-ci.yml index 9acd7ba41e..2f7b43ca51 100644 --- a/.github/workflows/local-ci.yml +++ b/.github/workflows/local-ci.yml @@ -83,7 +83,7 @@ jobs: elif [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ "${{ inputs.tier }}" = "affected" ]; then ports="$(scripts/ci-ports-to-run.sh "$GITHUB_SHA~1" "$GITHUB_SHA")" else - ports="ts java python csharp" + ports="ts java python csharp rust" fi echo "selected ports: '$ports'" echo "ports=$ports" >> "$GITHUB_OUTPUT" @@ -314,8 +314,25 @@ jobs: METAOBJECTS_TEST_PG_URL: postgres://metaobjects:metaobjects@localhost:${{ job.services.postgres.ports['5432'] }}/metaobjects_test run: scripts/ci-local.sh --only csharp --strict-toolchains + # The Rust port (preview, ADR-0065): fmt, clippy and the crate's tests, which run the + # registry and metamodel corpora. No database, so no sidecar. The runner service's PATH + # may not include Cargo's default bin directory, so the step adds it; rust-toolchain.toml + # pins the compiler, and rustup installs it on first use. + rust: + needs: detect + if: contains(needs.detect.outputs.ports, 'rust') + runs-on: [self-hosted, linux] + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - run: | + export PATH="$HOME/.cargo/bin:$PATH" + scripts/ci-local.sh --only rust --strict-toolchains + notify: - needs: [detect, gates, ts-fast, ts-unit, ts-slow, java-slow, python, csharp] + needs: [detect, gates, ts-fast, ts-unit, ts-slow, java-slow, python, csharp, rust] if: always() && contains(needs.*.result, 'failure') runs-on: [self-hosted, linux] steps: diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.yml index 08dda900dc..b2cd16ac75 100644 --- a/.github/workflows/pr-ci.yml +++ b/.github/workflows/pr-ci.yml @@ -23,6 +23,7 @@ name: pr-ci # java — java-slow: the full reactor build with tests on, which already holds the # java and kotlin conformance classes # python / csharp — the port's full test suite and conformance +# rust — fmt, clippy and the crate's tests (registry + metamodel corpora); preview # # THE REQUIRED CHECK: the final job, `pr-ci`, is the name to put in branch protection # when a maintainer decides to (it is not required yet; `leak-scan` is). It always runs @@ -176,10 +177,34 @@ jobs: ${{ runner.os }}-nuget- - run: scripts/ci-local.sh --only csharp --no-integration --strict-toolchains + rust: + needs: detect + if: contains(format(' {0} ', needs.detect.outputs.ports), ' rust ') + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Install the pinned toolchain + # The hosted image carries rustup; this reads server/rust/rust-toolchain.toml. + run: ( cd server/rust && rustup toolchain install && rustup show active-toolchain ) + - name: Cache Cargo registry and build + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + server/rust/target + key: ${{ runner.os }}-cargo-${{ hashFiles('server/rust/Cargo.lock', 'server/rust/rust-toolchain.toml') }} + restore-keys: | + ${{ runner.os }}-cargo- + - run: scripts/ci-local.sh --only rust --no-integration --strict-toolchains + # The stable required-check name. Runs even when lanes are skipped or failed. pr-ci: if: always() - needs: [detect, gates, ts, java, python, csharp] + needs: [detect, gates, ts, java, python, csharp, rust] runs-on: ubuntu-latest steps: - name: Every selected lane passed diff --git a/AGENTS.md b/AGENTS.md index c613f3f098..3b60cc2827 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -166,7 +166,7 @@ metaobjects/ ├── fixtures/conformance/ # cross-language test fixtures │ ├── server/ # runs on a server -│ ├── typescript/ java/ python/ csharp/ +│ ├── typescript/ java/ python/ csharp/ rust/ (preview, ADR-0065) │ └── client/ # runs on an end-user device ├── web/ # browser (TS-only — the browser is TS-native) @@ -380,7 +380,7 @@ it is correct because the conformance corpus passes. 🔗 Full vocabulary tables, the retired pre-v2 subtypes, and the per-contract traps: [.claude/rules/cross-language-porting.md](.claude/rules/cross-language-porting.md) (auto-loads on -`server/{csharp,java,python,typescript}/**`, `client/web/**`, `spec/**`, `fixtures/**conformance**/**`, +`server/{csharp,java,python,rust,typescript}/**`, `client/web/**`, `spec/**`, `fixtures/**conformance**/**`, `docs/ports/**`). Per-language notes live in [docs/ports/](docs/ports/). ## Design judgment (durable principles) diff --git a/CHANGELOG.md b/CHANGELOG.md index 839c935a51..1b79327ee4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,24 @@ here.** ## [Unreleased] +### Added + +- **Rust port foundation, in preview (ADR-0065).** `server/rust/` is a Cargo workspace with a + pinned toolchain and one crate, `metaobjects`: the node model, the type registry and the + built-in providers (strict, sealed after bootstrap, the same `ERR_*` codes), and a JSON loader + that reads packages, children, subtypes, attributes, `extends` and references, with the + canonical serializer. The loader freezes the tree when it finishes, and a frozen tree memoizes + its resolved reads (effective children, attrs and array-ness) for many concurrent readers, as + the other ports do. It passes `registry-conformance` byte for byte and 256 of the 510 + metamodel fixtures; the other 254 are on a ledger that may only shrink (the validation passes, + merge warnings, the reporting short-name rule and `script.json` fixtures it does not run yet). + While the port is in preview, a new fixture that fails in Rust and is not on the ledger prints a + warning and does not fail the lane; a fixture that passed and regresses still fails it, because + the ledger records how many fixtures must pass. Nothing is published and there is no codegen + or `cargo meta` command yet. A `rust` lane runs `cargo fmt --check`, clippy and the tests in + `scripts/ci-local.sh --only rust`, `pr-ci` and `local-ci`, selected by changes under + `server/rust/`. + ## [1.3.0] — 2026-11-17 _npm `1.3.0` (full lockstep across all 14 `@metaobjectsdev/*` publish candidates)._ diff --git a/README.md b/README.md index c253871fe9..fcb9ee9dd4 100644 --- a/README.md +++ b/README.md @@ -329,7 +329,8 @@ metaobjects/ │ ├── typescript/ # the reference port │ ├── java/ # Java port (incl. codegen-kotlin + metadata-ktx) │ ├── csharp/ # C# port -│ └── python/ # Python port +│ ├── python/ # Python port +│ └── rust/ # Rust port (preview, ADR-0065 — unpublished; no codegen yet) │ └── client/ └── web/ # universal browser packages (React, TanStack, Angular, framework-agnostic) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 9358247b29..d2b273b373 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -69,6 +69,17 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 19 cases (14 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the `explorer.json` data spine: `meta export --effective` + `meta verify --format json` + the generated-file manifest in, one explorer document out) | 1 case (`shop`) | ✓ (the builder is TypeScript, and reads only port-neutral inputs) | — | — | — | — | +**Rust (preview, ADR-0065) is not a column yet.** The sixth port runs two corpora +today: `registry-conformance` (byte-identical manifest) and the metamodel corpus, 256 +of 510 green with the rest on `server/rust/metaobjects/tests/conformance-expected-failures.json` +(validation passes, merge warnings, the reporting short-name rule and the `script.json` +fixtures, none of them built yet). That ledger may only shrink. While the port is in +preview, a new fixture that fails in Rust and is not on the ledger prints a warning and does +not fail the lane; it becomes a hard failure when the port leaves preview. A regression still +fails: the ledger's `minPassing` (256) is the number of fixtures known to pass, and the run +fails when fewer do. The column joins this table when the port leaves +preview. + A ✓ means the port runs the corpus green; an explicit `n / m` is used where a port carries a ledgered divergence. The two ledgered YAML fixtures are documented library-vs-pipeline divergences (see the `_comment` block in each port's @@ -357,6 +368,7 @@ Per-port runners + commands: | Kotlin | `cd server/java && mvn -pl codegen-kotlin test` (snapshot suite) | `mvn -f server/java/integration-tests-kotlin/pom.xml test` (needs Docker) | `mvn -f server/java/integration-tests-kotlin/pom.xml test -Dtest=ApiContractConformanceTest` (needs Docker) | | C# | `dotnet test` (per project) | `scripts/integration-test.sh csharp` (needs Docker) | `dotnet test server/csharp/MetaObjects.IntegrationTests/MetaObjects.IntegrationTests.csproj --filter "FullyQualifiedName~ApiContractConformanceTest"` (needs Docker) | | Python | `pytest` (per package) | `scripts/integration-test.sh python` (needs Docker) | `cd server/python && uv run --extra integration pytest tests/integration/test_api_contract.py` (needs Docker) | +| Rust (preview) | `cd server/rust && cargo test` (registry + metamodel corpora) | — | — | The `persistence-conformance` corpus is intentionally **on-demand** — none of the unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. diff --git a/fixtures/registry-conformance/README.md b/fixtures/registry-conformance/README.md index 81ed98be3f..e3bcb5ba6e 100644 --- a/fixtures/registry-conformance/README.md +++ b/fixtures/registry-conformance/README.md @@ -2,8 +2,8 @@ A structural gate for the cross-language contract that **the metamodel subtype vocabularies must be identical across languages** (see CLAUDE.md → -"Cross-language porting"). Each of the five ports (TypeScript, C#, Java, Kotlin, -Python) walks its own type registry and serializes the **logical metamodel +"Cross-language porting"). Each of the six ports (TypeScript, C#, Java, Kotlin, +Python, and Rust in preview, ADR-0065) walks its own type registry and serializes the **logical metamodel vocabulary** as a canonical, fully-sorted, byte-stable JSON manifest. A conformance runner asserts that manifest is **byte-identical** to the single committed canonical, [`expected-registry.json`](./expected-registry.json). diff --git a/scripts/check-metamodel-version.mjs b/scripts/check-metamodel-version.mjs index fb7844cdd8..ba0a7c8c39 100755 --- a/scripts/check-metamodel-version.mjs +++ b/scripts/check-metamodel-version.mjs @@ -56,7 +56,7 @@ const MANIFEST = "fixtures/registry-conformance/expected-registry.json"; /** * Every site that declares the metamodel version. The manifest is the one the - * conformance corpus byte-matches; the four port constants are what each port EMITS + * conformance corpus byte-matches; the five port constants are what each port EMITS * into its own manifest, so a partial edit is caught by `registry-conformance` — but * only in the lane for the port you forgot. `--set` writes all of them at once so that * failure mode does not need catching. (Kotlin has no constant of its own: it emits @@ -80,6 +80,10 @@ const SITES = [ path: "server/csharp/MetaObjects/RegistryManifest.cs", re: /(public const string MetamodelVersion = ")([^"]+)(")/, }, + { + path: "server/rust/metaobjects/src/manifest.rs", + re: /(pub const METAMODEL_VERSION: &str = ")([^"]+)(")/, + }, ]; // --------------------------------------------------------------------------- diff --git a/scripts/ci-affected-ports.sh b/scripts/ci-affected-ports.sh index 35db674e65..b4d5234c6e 100755 --- a/scripts/ci-affected-ports.sh +++ b/scripts/ci-affected-ports.sh @@ -2,7 +2,7 @@ # Map a pushed commit range to the set of language ports local-ci must test. # # Usage: scripts/ci-affected-ports.sh -# Prints a space-separated subset of: ts java python csharp +# Prints a space-separated subset of: ts java python csharp rust # (empty output = a push touching only the root prose files: run just the cheap shared gates). # # Fail-open policy: an unknown base (force-push zeros), an unresolvable @@ -15,7 +15,7 @@ # one — read that file before changing selection behaviour here. set -uo pipefail -ALL="ts java python csharp" +ALL="ts java python csharp rust" # The path -> lane rules are scripts/ci-lane-map.txt, read through ci-select-lanes.sh, so # the no-mistakes gate (`ci-local.sh --affected`) and the hosted workflows share ONE table. diff --git a/scripts/ci-lane-map.txt b/scripts/ci-lane-map.txt index 675f3e5676..8e31bb0fef 100644 --- a/scripts/ci-lane-map.txt +++ b/scripts/ci-lane-map.txt @@ -10,7 +10,7 @@ # space-separated lane names, or one of two words: # ALL every lane below # NONE no test lane (the `gates` lane still runs; see below) -# Lanes: ts-fast ts-unit java-slow python csharp. These are the ci-local sections a +# Lanes: ts-fast ts-unit java-slow python csharp rust. These are the ci-local sections a # change can select. ts-slow, cube and mutation are not selectable here: # the first two need docker, and mutation is diff-scoped # inside ts-fast already (gate_completeness_diff in ci-local.sh), which this map neither @@ -40,6 +40,7 @@ client/web/* | ts-fast ts-unit | the universal web client, built and te server/java/* | java-slow | the Java and Kotlin ports (the reactor holds both conformance suites) server/python/* | python | the Python port server/csharp/* | csharp | the C# port +server/rust/* | rust | the Rust port (preview, ADR-0065) fixtures/* | ALL | shared corpora every port runs spec/* | ALL | the metamodel spec every port implements scripts/* | ALL | CI scripts and tooling, this map included diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index e370f8e55b..ded0dc449a 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -69,6 +69,10 @@ # # python → full python test suite + integration-tests # # csharp → full csharp codegen suite + conformance # # + integration-tests +# # rust → the Rust port (preview): cargo fmt +# # --check, clippy -D warnings, and its +# # tests, which run the registry and +# # metamodel corpora. No docker half. # # cube → the cube-model live check: a real Cube # # (cubejs/cube, pinned) over a private # # Postgres, both in docker (FR-044). Its @@ -84,7 +88,7 @@ # # rule each path matched, then runs the selected ones as # # `--only ... --no-integration` would. The # # selectable lanes are ts-fast, ts-unit, java-slow, -# # python and csharp; a change confined to one port +# # python, csharp and rust; a change confined to one port # # selects that port, anything shared, any path the map # # does not claim, or no resolvable base selects all of # # them, and a change to only the root prose files @@ -118,7 +122,7 @@ # write into the tree first, in order: install, the drift gates, one workspace build. # Then it runs the rest as independent LANES side by side, at most MO_CI_JOBS at once # (default 8): java (the reactor, which already holds every java/kotlin conformance -# class), python, mutation, csharp, ts, ts-integ, java-integ and kotlin-integ (both +# class), python, mutation, csharp, rust, ts, ts-integ, java-integ and kotlin-integ (both # after java, which installs the jars they read), showcase (after java and csharp), cube # and gates. Each lane writes to its own log; the log prints as one block when the lane # ends, so output never interleaves. The summary lists every step with its time, the @@ -177,8 +181,8 @@ while [ $# -gt 0 ]; do --no-integration) NO_INTEG=1 ;; --integration-only) INTEG_ONLY=1 ;; --only) shift; case "${1:-}" in - gates|leak-scan|ts|ts-fast|ts-unit|ts-slow|mutation|java|java-fast|java-slow|python|csharp|cube) ONLY="$ONLY ${1}" ;; - *) echo "--only expects gates|leak-scan|ts|ts-fast|ts-unit|ts-slow|mutation|java|java-fast|java-slow|python|csharp|cube, got '${1:-}'" >&2; exit 2 ;; + gates|leak-scan|ts|ts-fast|ts-unit|ts-slow|mutation|java|java-fast|java-slow|python|csharp|rust|cube) ONLY="$ONLY ${1}" ;; + *) echo "--only expects gates|leak-scan|ts|ts-fast|ts-unit|ts-slow|mutation|java|java-fast|java-slow|python|csharp|rust|cube, got '${1:-}'" >&2; exit 2 ;; esac ;; -h|--help) awk 'NR==1{next} /^set -uo/{exit} {sub(/^# ?/,""); print}' "$0"; exit 0 ;; *) echo "unknown arg: $1 (see --help)" >&2; exit 2 ;; @@ -813,6 +817,16 @@ gate_conf_python() { if [ "$NO_INTEG" -eq 1 ] || ! docker info >/dev/null 2>&1; then skip_integ=""; fi ( cd server/python && uv run --extra integration pytest tests/ $skip_integ -q -n "${MO_CI_PY_WORKERS:-8}" ) } +# The Rust port (preview, ADR-0065). The whole crate suite, not a cherry-pick: it is the +# registry-conformance and metamodel corpora plus the unit tests, ~1s once built. --locked +# so a stale Cargo.lock fails here instead of being rewritten. The build goes to the +# workspace's own target/ (gitignored); never a CARGO_TARGET_DIR shared between checkouts. +gate_conf_rust() { + ( cd server/rust \ + && cargo fmt --all --check \ + && cargo clippy --locked --all-targets -q -- -D warnings \ + && cargo test --locked -q -- --nocapture ) +} gate_conf_kotlin() { ( cd server/java \ && mvn -pl codegen-kotlin -am install -DskipTests -q \ @@ -1441,13 +1455,14 @@ run_ts_serial_steps() { # One function per other port, shared by the serial heavy tier and the parallel --affected lanes. run_csharp_steps() { if want csharp; then step_if dotnet "conformance: csharp" gate_conf_csharp; fi; } run_python_steps() { if want python; then step_if uv "conformance: python" gate_conf_python; fi; } +run_rust_steps() { if want rust; then step_if cargo "conformance: rust" gate_conf_rust; fi; } run_java_reactor_steps() { if want_any java java-slow; then step_if mvn "java-reactor (install)" gate_java_reactor; fi; } # ── --affected, several ports: run their lanes side by side ─────────────────── # Run one after another, a change touching every port would take the SUM of the ports' # times, slower than the full run's parallel lanes, so more than one selected port group # runs as lanes exactly as the flagless run does (at most MO_CI_JOBS at once). The groups -# share no files: the ts lane owns node_modules/ and dist/, and java, python and csharp +# share no files: the ts lane owns node_modules/ and dist/, and java, python, csharp and rust # use no bun, which is also how pr-ci.yml runs them, as separate jobs. A single selected # group runs serially, unchanged. TypeScript's two lanes stay one group, in order, because # ts-unit builds into the dist/ that ts-fast's build writes. @@ -1455,7 +1470,7 @@ AFFECTED_PARALLEL=0 if [ "$AFFECTED" -eq 1 ]; then _groups=0 in_lane_any ts-fast ts-unit && _groups=$((_groups + 1)) - for _g in java-slow python csharp; do in_lane "$_g" && _groups=$((_groups + 1)); done + for _g in java-slow python csharp rust; do in_lane "$_g" && _groups=$((_groups + 1)); done [ "$_groups" -gt 1 ] && AFFECTED_PARALLEL=1 fi @@ -1506,6 +1521,7 @@ if [ "$AFFECTED_PARALLEL" -eq 1 ]; then in_lane java-slow && lane java "" run_java_reactor_steps in_lane python && lane python "" run_python_steps in_lane csharp && lane csharp "" run_csharp_steps + in_lane rust && lane rust "" run_rust_steps in_lane_any ts-fast ts-unit && lane ts "" run_ts_serial_steps run_or_list_lanes elif [ "$PARALLEL" -eq 0 ]; then @@ -1523,11 +1539,11 @@ elif [ "$PARALLEL" -eq 0 ]; then if [ "$QUICK" -eq 1 ]; then echo "" - echo "── ⊘ --quick: SKIPPING the other-language ports (csharp/java/python/kotlin)," + echo "── ⊘ --quick: SKIPPING the other-language ports (csharp/java/python/kotlin/rust)," echo " the full Java reactor, the docker integration suite and the cube live" echo " check. Run the full \`scripts/ci-local.sh\` (no flag) before opening/merging" echo " a PR or tagging." - record SKIP 0 "csharp/java/python/kotlin conformance (--quick)" + record SKIP 0 "csharp/java/python/kotlin/rust conformance (--quick)" record SKIP 0 "java-reactor (--quick)" record SKIP 0 "integration-tests (--quick)" record SKIP 0 "cube-model live check (--quick)" @@ -1542,6 +1558,7 @@ elif [ "$PARALLEL" -eq 0 ]; then run_csharp_steps if want_any java java-fast; then step_if mvn "conformance: java" gate_conf_java; fi run_python_steps + run_rust_steps if want_any java java-fast; then step_if mvn "conformance: kotlin" gate_conf_kotlin; fi run_java_reactor_steps # --no-integration drops the docker half; --integration-only keeps ONLY it, which is @@ -1638,6 +1655,7 @@ else lane kotlin-integ java lane_kotlin_integ lane java-integ java lane_java_integ lane showcase java,csharp lane_showcase + lane rust "" run_rust_steps lane cube "" lane_cube lane gates "" lane_gates diff --git a/scripts/ci-ports-to-run.sh b/scripts/ci-ports-to-run.sh index 338002c527..6abe85abf3 100755 --- a/scripts/ci-ports-to-run.sh +++ b/scripts/ci-ports-to-run.sh @@ -22,10 +22,10 @@ # when the shrink is certain. # # Usage: scripts/ci-ports-to-run.sh -# Prints a space-separated subset of: ts java python csharp +# Prints a space-separated subset of: ts java python csharp rust set -uo pipefail -ALL="ts java python csharp" +ALL="ts java python csharp rust" # Resolve the sibling by the script's own location, never by the caller's cwd — the # workflow happens to run from the repo root, and a relative call would keep working @@ -49,11 +49,12 @@ lane_port() { java-slow) echo java ;; python) echo python ;; csharp) echo csharp ;; + rust) echo rust ;; *) echo "" ;; esac } -all_lanes() { echo "ts-fast ts-unit ts-slow java-slow python csharp"; } +all_lanes() { echo "ts-fast ts-unit ts-slow java-slow python csharp rust"; } # Canonical order, deduplicated, unknown tokens dropped. The order is FIXED rather than # sorted because the workflow tests the result with `contains(..., 'ts')` — a substring diff --git a/scripts/ci-select-lanes.sh b/scripts/ci-select-lanes.sh index 6ebcf4a512..e4373174ab 100755 --- a/scripts/ci-select-lanes.sh +++ b/scripts/ci-select-lanes.sh @@ -21,7 +21,7 @@ CI_SELECT_HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" CI_LANE_MAP="${MO_CI_LANE_MAP:-$CI_SELECT_HERE/ci-lane-map.txt}" # The lanes a change can select, in the order they run. The map's `ALL` means exactly this. -CI_SELECTABLE_LANES="ts-fast ts-unit java-slow python csharp" +CI_SELECTABLE_LANES="ts-fast ts-unit java-slow python csharp rust" # The port each lane belongs to, for callers that think in ports (the hosted workflows). lane_to_port() { @@ -30,6 +30,7 @@ lane_to_port() { java-slow) echo java ;; python) echo python ;; csharp) echo csharp ;; + rust) echo rust ;; esac } diff --git a/scripts/test-ci-affected-ports.sh b/scripts/test-ci-affected-ports.sh index 792bb13fd2..543b6e123d 100755 --- a/scripts/test-ci-affected-ports.sh +++ b/scripts/test-ci-affected-ports.sh @@ -23,16 +23,17 @@ check "java" "server/java/metadata/src/main/java/A.java" check "java" "server/java/codegen-kotlin/src/main/kotlin/B.kt" check "python" "server/python/src/metaobjects/loader.py" check "csharp" "server/csharp/MetaObjects/Loader.cs" -check "ts java python csharp" "fixtures/conformance/foo/meta.json" -check "ts java python csharp" "spec/metamodel.md" -check "ts java python csharp" "scripts/ci-local.sh" -check "ts java python csharp" ".github/workflows/local-ci.yml" -check "ts java python csharp" "agent-context/skills/x.md" -check "ts java python csharp" "weird-new-toplevel/file.txt" # unmapped -> fail open -check "ts java python csharp" "docs/recipes/generators/python/json_schema.py" # executed by port tests -> not docs -check "ts java python csharp" "docs/features/cli.md" # port tests read docs/ -> all +check "rust" "server/rust/metaobjects/src/loader.rs" +check "ts java python csharp rust" "fixtures/conformance/foo/meta.json" +check "ts java python csharp rust" "spec/metamodel.md" +check "ts java python csharp rust" "scripts/ci-local.sh" +check "ts java python csharp rust" ".github/workflows/local-ci.yml" +check "ts java python csharp rust" "agent-context/skills/x.md" +check "ts java python csharp rust" "weird-new-toplevel/file.txt" # unmapped -> fail open +check "ts java python csharp rust" "docs/recipes/generators/python/json_schema.py" # executed by port tests -> not docs +check "ts java python csharp rust" "docs/features/cli.md" # port tests read docs/ -> all check "" "README.md" "CHANGELOG.md" # md-only -> gates only check "ts python" "server/typescript/a.ts" "server/python/b.py" -check "ts java python csharp" "docs/x.md" "fixtures/y.json" # mixed: fixtures wins +check "ts java python csharp rust" "docs/x.md" "fixtures/y.json" # mixed: fixtures wins [ "$fails" -eq 0 ] && echo "ALL PASS" || { echo "$fails failure(s)"; exit 1; } diff --git a/scripts/test-ci-lane-selection.sh b/scripts/test-ci-lane-selection.sh index cbbe530d78..8e351c1df5 100755 --- a/scripts/test-ci-lane-selection.sh +++ b/scripts/test-ci-lane-selection.sh @@ -23,7 +23,7 @@ check() { # check "" "" "" } lanes() { select_lanes "$@"; echo "$SELECTED_LANES"; } -ALL="ts-fast ts-unit java-slow python csharp" +ALL="ts-fast ts-unit java-slow python csharp rust" # ── 1. change sets ──────────────────────────────────────────────────────────── check "ts-fast ts-unit" "$(lanes server/typescript/packages/cli/src/x.ts)" "one port: typescript" @@ -31,6 +31,7 @@ check "ts-fast ts-unit" "$(lanes client/web/packages/react/src/y.tsx)" check "java-slow" "$(lanes server/java/metadata/src/main/java/A.java server/java/codegen-kotlin/src/main/kotlin/B.kt)" "one port: java and kotlin" check "python" "$(lanes server/python/src/metaobjects/loader.py)" "one port: python" check "csharp" "$(lanes server/csharp/MetaObjects/Loader.cs)" "one port: csharp" +check "rust" "$(lanes server/rust/metaobjects/src/loader.rs)" "one port: rust" check "ts-fast ts-unit python" "$(lanes server/python/b.py server/typescript/a.ts)" "two ports, given out of order, run in lane order" check "ts-fast ts-unit java-slow python csharp" "$(lanes server/csharp/a.cs server/java/b.java server/python/c.py server/typescript/d.ts)" "all four ports touched" check "$ALL" "$(lanes fixtures/conformance/foo/meta.json)" "shared fixtures run everything" @@ -104,7 +105,7 @@ check "$ALL" "$(run MO_CI_AFFECTED_BASE=no-such-ref)" "an unresolvable base sele # lanes, so a change to every port is not slower than the full run; one group stays serial. plan() { ( cd "$tmp/repo" && env MO_CI_AFFECTED_BASE=main MO_CI_LIST_ONLY=1 "$@" scripts/ci-local.sh --affected 2>&1 ); } lane_blocks() { { grep -o '^── lane [a-z]*' || true; } | sed 's/^── lane //' | sort | paste -sd' ' -; } -check "csharp java python ts" "$(plan MO_CI_FULL=1 | lane_blocks)" "every port selected: one parallel lane per port group" +check "csharp java python rust ts" "$(plan MO_CI_FULL=1 | lane_blocks)" "every port selected: one parallel lane per port group" check "python ts" "$(plan | lane_blocks)" "python and typescript selected: two parallel lanes" check "yes" "$(plan | grep 'run as parallel lanes' >/dev/null && echo yes || echo no)" "several groups are announced as parallel" check "" "$(plan MO_CI_AFFECTED_BASE=HEAD~2 | lane_blocks)" "one group (typescript, the docs adds none) stays serial" @@ -118,7 +119,7 @@ mkdir -p "$tmp/repo/agent-context/skills" "$tmp/repo/server/java" echo s > "$tmp/repo/agent-context/skills/x.md"; commit shared git -C "$tmp/repo" mv agent-context/skills/x.md server/java/x.md; commit rename-into-java ports() { ( cd "$tmp/repo" && scripts/ci-affected-ports.sh "$(git rev-parse HEAD~1)" HEAD ); } -check "ts java python csharp" "$(ports)" "git: a rename out of agent-context still selects every port" +check "ts java python csharp rust" "$(ports)" "git: a rename out of agent-context still selects every port" git -C "$tmp/repo" mv server/java/x.md server/python/x.py; commit rename-java-to-python check "java python" "$(ports)" "git: a rename between ports selects both" diff --git a/scripts/test-ci-ports-to-run.sh b/scripts/test-ci-ports-to-run.sh index 06b7e0568c..44a85dbecf 100755 --- a/scripts/test-ci-ports-to-run.sh +++ b/scripts/test-ci-ports-to-run.sh @@ -16,8 +16,8 @@ check() { # check "" "" "" } # ── union_ports: canonical order, deduplicated ──────────────────────────────── -check "ts java python csharp" "$(union_ports ts java python csharp)" "union all" -check "ts java python csharp" "$(union_ports csharp python java ts)" "union reorders to canonical" +check "ts java python csharp rust" "$(union_ports ts java python csharp rust)" "union all" +check "ts java python csharp rust" "$(union_ports rust csharp python java ts)" "union reorders to canonical" check "ts java" "$(union_ports java ts java ts)" "union deduplicates" check "python" "$(union_ports python)" "union single" check "" "$(union_ports)" "union empty" @@ -25,39 +25,39 @@ check "ts" "$(union_ports ts bogus)" "union dro # ── not_green_ports: newest verdict per lane wins ───────────────────────────── all_green() { - printf '%s\tsuccess\n' ts-fast ts-unit ts-slow java-slow python csharp + printf '%s\tsuccess\n' ts-fast ts-unit ts-slow java-slow python csharp rust } check "" "$(all_green | not_green_ports)" "every lane green -> nothing to re-run" # The defect this file exists for: a docs-only run SKIPS the code lanes, so the # newest run says nothing about them and the verdict must come from the run before. -check "java" "$( { printf '%s\tskipped\n' ts-fast ts-unit ts-slow java-slow python csharp - printf '%s\tsuccess\n' ts-fast ts-unit ts-slow python csharp +check "java" "$( { printf '%s\tskipped\n' ts-fast ts-unit ts-slow java-slow python csharp rust + printf '%s\tsuccess\n' ts-fast ts-unit ts-slow python csharp rust printf '%s\tfailure\n' java-slow; } | not_green_ports )" \ "docs-only run skips a red java -> java still not green" -check "ts" "$( { printf '%s\tsuccess\n' ts-fast ts-unit java-slow python csharp +check "ts" "$( { printf '%s\tsuccess\n' ts-fast ts-unit java-slow python csharp rust printf 'ts-slow\tfailure\n'; } | not_green_ports )" \ "one red ts lane selects the whole ts port" # `skipped` is walked past, never counted as a verdict — it describes the # selection, not the code. check "" "$( { printf 'ts-fast\tskipped\n' - printf '%s\tsuccess\n' ts-fast ts-unit ts-slow java-slow python csharp; } | not_green_ports )" \ + printf '%s\tsuccess\n' ts-fast ts-unit ts-slow java-slow python csharp rust; } | not_green_ports )" \ "skipped is walked past to the real verdict" # A lane that was cancelled was never verified. cancel-in-progress makes this # common, so counting it as green would reopen the hole from the other side. -check "csharp" "$( { printf '%s\tsuccess\n' ts-fast ts-unit ts-slow java-slow python +check "csharp" "$( { printf '%s\tsuccess\n' ts-fast ts-unit ts-slow java-slow python rust printf 'csharp\tcancelled\n'; } | not_green_ports )" \ "cancelled is not green" # No verdict at all in the window is UNKNOWN, and unknown must widen. -check "python" "$(printf '%s\tsuccess\n' ts-fast ts-unit ts-slow java-slow csharp | not_green_ports)" \ +check "python" "$(printf '%s\tsuccess\n' ts-fast ts-unit ts-slow java-slow csharp rust | not_green_ports)" \ "a lane with no verdict in the window is not green" -check "ts java python csharp" "$(printf '' | not_green_ports)" "no history at all -> everything" +check "ts java python csharp rust" "$(printf '' | not_green_ports)" "no history at all -> everything" # ── the lane map must cover every port-testing job in the workflow ──────────── # A new lane absent from lane_port() would be invisible to the known-green check diff --git a/server/rust/Cargo.lock b/server/rust/Cargo.lock new file mode 100644 index 0000000000..e7a15d74ad --- /dev/null +++ b/server/rust/Cargo.lock @@ -0,0 +1,136 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "metaobjects" +version = "0.1.0" +dependencies = [ + "indexmap", + "serde_json", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/server/rust/Cargo.toml b/server/rust/Cargo.toml new file mode 100644 index 0000000000..27a039904d --- /dev/null +++ b/server/rust/Cargo.toml @@ -0,0 +1,29 @@ +# The Rust port of MetaObjects (preview). ADR-0065 records why it exists and how it +# differs from the other five ports. +# +# One crate today: `metaobjects` (metamodel registry, JSON loader, canonical +# serializer). The codegen engine (`metaobjects-codegen`) and the `cargo meta` +# command (`metaobjects-cli`) join this workspace in later steps; no placeholder +# crates are created for them ahead of time. +[workspace] +resolver = "3" +members = ["metaobjects"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/metaobjectsdev/metaobjects" + +[workspace.dependencies] +# `preserve_order` keeps object keys in document order, which the loader needs: +# children, attrs and error paths all follow authoring order, as JSON.parse does. +serde_json = { version = "1.0.140", features = ["preserve_order"] } +indexmap = "2.7" + +[workspace.lints.rust] +unsafe_code = "forbid" + +[workspace.lints.clippy] +all = { level = "warn", priority = -1 } diff --git a/server/rust/metaobjects/Cargo.toml b/server/rust/metaobjects/Cargo.toml new file mode 100644 index 0000000000..a2f453b242 --- /dev/null +++ b/server/rust/metaobjects/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "metaobjects" +description = "MetaObjects metamodel registry, loader and canonical serializer for Rust (preview)." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +# Not published yet: the first crates.io release is a separate, approved step. +publish = false + +[dependencies] +serde_json.workspace = true +indexmap.workspace = true + +[lints] +workspace = true diff --git a/server/rust/metaobjects/examples/load_bench.rs b/server/rust/metaobjects/examples/load_bench.rs new file mode 100644 index 0000000000..cf8f17fb59 --- /dev/null +++ b/server/rust/metaobjects/examples/load_bench.rs @@ -0,0 +1,118 @@ +//! Load-time benchmark on a 20-times model built in memory from the public +//! conformance fitness model (`fixtures/persistence-conformance/canonical/meta.fitness.json`). +//! +//! Each copy keeps every name and gets its own root package (`fitness_x00` ... +//! `fitness_x19`), so the copies never collide and every bare reference still +//! resolves inside its own copy. Nothing is written to disk. +//! +//! Run it in release mode: +//! +//! ```text +//! cargo run --release --example load_bench [-- ] +//! ``` + +use std::time::{Duration, Instant}; + +use metaobjects::loader::Loader; +use metaobjects::node::{NodeId, Tree}; +use metaobjects::providers::default_registry; +use metaobjects::serializer::canonical_serialize; + +const FITNESS: &str = + include_str!("../../../../fixtures/persistence-conformance/canonical/meta.fitness.json"); +const ROOT_PACKAGE: &str = "\"package\": \"fitness\""; + +fn median(mut v: Vec) -> Duration { + v.sort(); + v[v.len() / 2] +} + +/// One pass of every memoized resolving read over every node: the read path a +/// runtime caller exercises. The first pass on a frozen tree fills the caches. +fn read_pass(tree: &Tree) -> usize { + let mut n = 0; + for i in 0..tree.len() { + let id = NodeId::from_index(i); + n += tree.children(id).len() + tree.attrs(id).len(); + n += usize::from(tree.resolved_is_array(id)); + } + n +} + +fn main() { + let mut args = std::env::args().skip(1); + let copies: usize = args + .next() + .map_or(20, |a| a.parse().expect("copies is a number")); + let iterations: usize = args + .next() + .map_or(15, |a| a.parse().expect("iterations is a number")); + assert!( + FITNESS.contains(ROOT_PACKAGE), + "the fitness model declares its root package" + ); + let sources: Vec<(String, String)> = (0..copies) + .map(|i| { + let text = FITNESS.replacen( + ROOT_PACKAGE, + &format!("\"package\": \"fitness_x{i:02}\""), + 1, + ); + (format!("meta.fitness_x{i:02}.json"), text) + }) + .collect(); + let bytes: usize = sources.iter().map(|(_, t)| t.len()).sum(); + + let t = Instant::now(); + let registry = default_registry().expect("the built-in providers compose"); + let compose = t.elapsed(); + + let loader = Loader::new(®istry); + let mut loads = Vec::with_capacity(iterations); + let mut serializes = Vec::with_capacity(iterations); + let mut cold_reads = Vec::with_capacity(iterations); + let mut warm_reads = Vec::with_capacity(iterations); + let mut nodes = 0; + for _ in 0..iterations { + let t = Instant::now(); + let result = loader.load_sources(&sources); + loads.push(t.elapsed()); + assert!( + result.errors.is_empty(), + "the scaled model loads clean: {:?}", + result.errors.first() + ); + nodes = result.tree.len(); + let t = Instant::now(); + std::hint::black_box(read_pass(&result.tree)); + cold_reads.push(t.elapsed()); + let t = Instant::now(); + std::hint::black_box(read_pass(&result.tree)); + warm_reads.push(t.elapsed()); + let t = Instant::now(); + let out = canonical_serialize(&result.tree, result.root); + serializes.push(t.elapsed()); + std::hint::black_box(out); + } + println!( + "model: {copies} copies of the fitness model, {} KiB of JSON, {nodes} nodes", + bytes / 1024 + ); + println!("registry compose: {compose:?}"); + println!( + "load (parse, merge, extends, references), median of {iterations}: {:?}", + median(loads) + ); + println!( + "resolved reads of every node (children, attrs, is_array), first pass fills the cache, median of {iterations}: {:?}", + median(cold_reads) + ); + println!( + "resolved reads of every node, from the cache, median of {iterations}: {:?}", + median(warm_reads) + ); + println!( + "canonical serialize, median of {iterations}: {:?}", + median(serializes) + ); +} diff --git a/server/rust/metaobjects/src/errors.rs b/server/rust/metaobjects/src/errors.rs new file mode 100644 index 0000000000..d99bc54e97 --- /dev/null +++ b/server/rust/metaobjects/src/errors.rs @@ -0,0 +1,122 @@ +//! Error codes shared by every port, and the error type this crate returns. +//! +//! The codes are the cross-port contract in `fixtures/conformance/ERROR-CODES.json`; +//! a test in this module fails if one used here is missing from that file. + +use std::fmt; + +use crate::source::ErrorSource; + +pub const ERR_MALFORMED_JSON: &str = "ERR_MALFORMED_JSON"; +pub const ERR_TOP_LEVEL_NOT_OBJECT: &str = "ERR_TOP_LEVEL_NOT_OBJECT"; +pub const ERR_UNKNOWN_TYPE: &str = "ERR_UNKNOWN_TYPE"; +pub const ERR_UNKNOWN_SUBTYPE: &str = "ERR_UNKNOWN_SUBTYPE"; +pub const ERR_MISSING_SUBTYPE: &str = "ERR_MISSING_SUBTYPE"; +pub const ERR_ABSTRACT_SUBTYPE_AUTHORED: &str = "ERR_ABSTRACT_SUBTYPE_AUTHORED"; +pub const ERR_CHILD_NOT_OBJECT: &str = "ERR_CHILD_NOT_OBJECT"; +pub const ERR_UNKNOWN_ATTR: &str = "ERR_UNKNOWN_ATTR"; +pub const ERR_RESERVED_ATTR: &str = "ERR_RESERVED_ATTR"; +pub const ERR_BAD_ATTR_VALUE: &str = "ERR_BAD_ATTR_VALUE"; +pub const ERR_MISSING_REQUIRED_ATTR: &str = "ERR_MISSING_REQUIRED_ATTR"; +pub const ERR_CHILD_NOT_ALLOWED: &str = "ERR_CHILD_NOT_ALLOWED"; +pub const ERR_UNRESOLVED_SUPER: &str = "ERR_UNRESOLVED_SUPER"; +pub const ERR_EXTENDS_TARGET_MISMATCH: &str = "ERR_EXTENDS_TARGET_MISMATCH"; +pub const ERR_REGISTRY_SEALED: &str = "ERR_REGISTRY_SEALED"; +pub const ERR_EXTEND_REQUIRED_ATTR: &str = "ERR_EXTEND_REQUIRED_ATTR"; +pub const ERR_PROVIDER_ATTR_CONFLICT: &str = "ERR_PROVIDER_ATTR_CONFLICT"; +pub const ERR_PROVIDER_ATTR_SHADOW: &str = "ERR_PROVIDER_ATTR_SHADOW"; +pub const ERR_PROVIDER_DUPLICATE_ID: &str = "ERR_PROVIDER_DUPLICATE_ID"; +pub const ERR_PROVIDER_MISSING_DEPENDENCY: &str = "ERR_PROVIDER_MISSING_DEPENDENCY"; +pub const ERR_PROVIDER_DEPENDENCY_CYCLE: &str = "ERR_PROVIDER_DEPENDENCY_CYCLE"; +pub const ERR_OVERLAY_NO_TARGET: &str = "ERR_OVERLAY_NO_TARGET"; + +/// The code reported for a failure that carries none (a programming error in a +/// provider definition, say). +pub const ERR_UNKNOWN: &str = "ERR_UNKNOWN"; + +/// Every shared code this crate can report. +pub const ALL_CODES: &[&str] = &[ + ERR_MALFORMED_JSON, + ERR_TOP_LEVEL_NOT_OBJECT, + ERR_UNKNOWN_TYPE, + ERR_UNKNOWN_SUBTYPE, + ERR_MISSING_SUBTYPE, + ERR_ABSTRACT_SUBTYPE_AUTHORED, + ERR_CHILD_NOT_OBJECT, + ERR_UNKNOWN_ATTR, + ERR_RESERVED_ATTR, + ERR_BAD_ATTR_VALUE, + ERR_MISSING_REQUIRED_ATTR, + ERR_CHILD_NOT_ALLOWED, + ERR_UNRESOLVED_SUPER, + ERR_EXTENDS_TARGET_MISMATCH, + ERR_REGISTRY_SEALED, + ERR_EXTEND_REQUIRED_ATTR, + ERR_PROVIDER_ATTR_CONFLICT, + ERR_PROVIDER_ATTR_SHADOW, + ERR_PROVIDER_DUPLICATE_ID, + ERR_PROVIDER_MISSING_DEPENDENCY, + ERR_PROVIDER_DEPENDENCY_CYCLE, + ERR_OVERLAY_NO_TARGET, + ERR_UNKNOWN, +]; + +/// A failure with a shared error code, a message for people, and where it happened. +#[derive(Debug, Clone, PartialEq)] +pub struct MetaError { + pub code: &'static str, + pub message: String, + /// Boxed so a `Result<_, MetaError>` stays small on the happy path. + pub source: Box, +} + +impl MetaError { + /// An error raised while building the registry: it has no document location. + pub fn code(code: &'static str, message: impl Into) -> Self { + Self { + code, + message: message.into(), + source: Box::new(ErrorSource::Code), + } + } + + /// An `ERR_UNKNOWN` with no source: a registry or provider definition problem. + pub fn unknown(message: impl Into) -> Self { + Self::code(ERR_UNKNOWN, message) + } + + /// An error located in a document. + pub fn at(code: &'static str, message: impl Into, source: ErrorSource) -> Self { + Self { + code, + message: message.into(), + source: Box::new(source), + } + } +} + +impl fmt::Display for MetaError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}: {}", self.code, self.message) + } +} + +impl std::error::Error for MetaError {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_code_is_in_the_shared_catalogue() { + let raw = include_str!("../../../../fixtures/conformance/ERROR-CODES.json"); + let doc: serde_json::Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for code in ALL_CODES { + assert!( + codes.contains_key(*code), + "{code} is not in ERROR-CODES.json" + ); + } + } +} diff --git a/server/rust/metaobjects/src/json.rs b/server/rust/metaobjects/src/json.rs new file mode 100644 index 0000000000..cc09e92de5 --- /dev/null +++ b/server/rust/metaobjects/src/json.rs @@ -0,0 +1,212 @@ +//! JSON output that matches `JSON.stringify(value, null, 2)` byte for byte. +//! +//! Every port's canonical output and registry manifest is compared as text against +//! files the TypeScript port wrote, so two details of JavaScript's serializer are +//! reproduced here rather than left to `serde_json`: +//! +//! - **Key order.** A JavaScript object lists integer-like keys first, in ascending +//! numeric order, then the remaining keys in insertion order. +//! - **Numbers.** JavaScript has one number type and prints `1.0` as `1`, switching +//! to exponent notation below `1e-6` and at or above `1e21`. + +use serde_json::{Map, Number, Value}; + +/// Serialize `value` as `JSON.stringify(value, null, 2)` would. +pub fn to_js_pretty(value: &Value) -> String { + let mut out = String::new(); + write_value(&mut out, value, 0); + out +} + +fn write_value(out: &mut String, value: &Value, depth: usize) { + match value { + Value::Null => out.push_str("null"), + Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }), + Value::Number(n) => out.push_str(&js_number(n)), + Value::String(s) => write_string(out, s), + Value::Array(items) => { + if items.is_empty() { + out.push_str("[]"); + return; + } + out.push('['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push(','); + } + newline(out, depth + 1); + write_value(out, item, depth + 1); + } + newline(out, depth); + out.push(']'); + } + Value::Object(map) => { + if map.is_empty() { + out.push_str("{}"); + return; + } + out.push('{'); + for (i, (key, item)) in js_key_order(map).into_iter().enumerate() { + if i > 0 { + out.push(','); + } + newline(out, depth + 1); + write_string(out, key); + out.push_str(": "); + write_value(out, item, depth + 1); + } + newline(out, depth); + out.push('}'); + } + } +} + +fn newline(out: &mut String, depth: usize) { + out.push('\n'); + for _ in 0..depth { + out.push_str(" "); + } +} + +/// The order a JavaScript object enumerates its own string keys in. +pub fn js_key_order(map: &Map) -> Vec<(&String, &Value)> { + let mut indexed: Vec<(u32, &String, &Value)> = Vec::new(); + let mut rest: Vec<(&String, &Value)> = Vec::new(); + for (k, v) in map { + match array_index(k) { + Some(i) => indexed.push((i, k, v)), + None => rest.push((k, v)), + } + } + if indexed.is_empty() { + return rest; + } + indexed.sort_by_key(|(i, _, _)| *i); + let mut out: Vec<(&String, &Value)> = indexed.into_iter().map(|(_, k, v)| (k, v)).collect(); + out.extend(rest); + out +} + +/// A canonical array index (`0`, `17`, never `017` or `-1`) below 2^32 - 1. +fn array_index(key: &str) -> Option { + if key.is_empty() || key.len() > 10 || !key.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + if key.len() > 1 && key.starts_with('0') { + return None; + } + let n: u64 = key.parse().ok()?; + if n < u64::from(u32::MAX) { + u32::try_from(n).ok() + } else { + None + } +} + +fn write_string(out: &mut String, s: &str) { + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\u{08}' => out.push_str("\\b"), + '\u{0c}' => out.push_str("\\f"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); +} + +/// `String(n)` for a JSON number. +pub fn js_number(n: &Number) -> String { + if let Some(i) = n.as_i64() { + return i.to_string(); + } + if let Some(u) = n.as_u64() { + return js_f64(u as f64); + } + js_f64(n.as_f64().unwrap_or(f64::NAN)) +} + +/// `String(x)` for a double. +pub fn js_f64(x: f64) -> String { + if x.is_nan() { + return "NaN".to_string(); + } + if x.is_infinite() { + return if x > 0.0 { "Infinity" } else { "-Infinity" }.to_string(); + } + if x == 0.0 { + return "0".to_string(); + } + let abs = x.abs(); + if (1e-6..1e21).contains(&abs) { + // Rust's Display gives the shortest round-trip digits without an exponent. + return format!("{x}"); + } + // Exponent form: `{:e}` gives "1e-7" / "1.5e21"; JavaScript writes "1.5e+21". + let s = format!("{x:e}"); + match s.split_once('e') { + Some((mantissa, exp)) if !exp.starts_with('-') => format!("{mantissa}e+{exp}"), + _ => s, + } +} + +/// True when `x` is a whole number JavaScript would print without a fraction. +pub fn is_js_integer(x: f64) -> bool { + x.is_finite() && x.fract() == 0.0 +} + +/// A whole-number double inside JavaScript's safe-integer range, as an `i64`. +pub fn safe_whole_i64(x: f64) -> Option { + #[allow(clippy::cast_possible_truncation)] + (is_js_integer(x) && x.abs() < 9.007_199_254_740_992e15).then_some(x as i64) +} + +/// JavaScript's `String(v)` for a JSON value: a string bare, a number as JS prints it. +pub fn js_display(v: &Value) -> String { + match v { + Value::String(s) => s.clone(), + Value::Number(n) => js_number(n), + Value::Bool(b) => b.to_string(), + Value::Null => "null".to_string(), + other => other.to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn integer_like_keys_come_first() { + let v: Value = serde_json::from_str(r#"{"b":1,"10":2,"a":3,"2":4,"01":5}"#).unwrap(); + assert_eq!( + to_js_pretty(&v), + "{\n \"2\": 4,\n \"10\": 2,\n \"b\": 1,\n \"a\": 3,\n \"01\": 5\n}" + ); + } + + #[test] + fn numbers_print_like_javascript() { + assert_eq!(js_f64(1.0), "1"); + assert_eq!(js_f64(0.5), "0.5"); + assert_eq!(js_f64(1e21), "1e+21"); + assert_eq!(js_f64(1e-7), "1e-7"); + assert_eq!(js_f64(-0.0), "0"); + assert_eq!( + to_js_pretty(&json!([1.0, 2.5, []])), + "[\n 1,\n 2.5,\n []\n]" + ); + } + + #[test] + fn control_characters_escape_like_javascript() { + assert_eq!(to_js_pretty(&json!("a\"\u{1}\n")), "\"a\\\"\\u0001\\n\""); + } +} diff --git a/server/rust/metaobjects/src/lib.rs b/server/rust/metaobjects/src/lib.rs new file mode 100644 index 0000000000..f73418baf8 --- /dev/null +++ b/server/rust/metaobjects/src/lib.rs @@ -0,0 +1,22 @@ +//! MetaObjects for Rust (preview). +//! +//! The metamodel registry, the JSON loader and the canonical serializer. The +//! behaviour is defined by the shared conformance corpora that every port runs; +//! ADR-0065 records how this port differs from the other five. + +pub mod errors; +pub mod json; +pub mod loader; +pub mod manifest; +pub mod node; +pub mod parser; +pub mod providers; +pub mod registry; +pub mod serializer; +pub mod source; + +pub use errors::MetaError; +pub use loader::{LoadResult, Loader}; +pub use node::{Attr, Node, NodeId, Tree}; +pub use providers::{Provider, compose_registry, core_providers, default_registry}; +pub use registry::TypeRegistry; diff --git a/server/rust/metaobjects/src/loader.rs b/server/rust/metaobjects/src/loader.rs new file mode 100644 index 0000000000..596b718a8a --- /dev/null +++ b/server/rust/metaobjects/src/loader.rs @@ -0,0 +1,806 @@ +//! The loader: read files, parse each, merge the roots, resolve `extends` and +//! spell every reference canonically. +//! +//! Order of passes, as in every port: parse → merge → super resolution → +//! (validation, a later step of this port) → reference resolution. +//! +//! Built for speed from the start: each file is read once and parsed straight into +//! one arena, nothing is written to disk, and the passes walk the tree a fixed +//! number of times. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +use crate::errors::{ + ERR_BAD_ATTR_VALUE, ERR_EXTENDS_TARGET_MISMATCH, ERR_MALFORMED_JSON, ERR_OVERLAY_NO_TARGET, + ERR_UNKNOWN, ERR_UNKNOWN_SUBTYPE, ERR_UNKNOWN_TYPE, ERR_UNRESOLVED_SUPER, MetaError, +}; +use crate::node::{Node, NodeId, PACKAGE_SEP, Tree}; +use crate::parser::{SUBTYPE_ROOT, TYPE_METADATA, TYPE_OBJECT, parse_document}; +use crate::registry::TypeRegistry; +use crate::source::ErrorSource; + +/// The extensions a directory load picks up. YAML is a later step of this port; +/// a `.yaml` file is reported rather than silently skipped. +const JSON_SUFFIX: &str = "json"; +const YAML_SUFFIXES: &[&str] = &["yaml", "yml"]; +/// A directory of drafts that a directory load never descends into. +const PENDING_DIR: &str = "_pending"; + +const TYPE_IDENTITY: &str = "identity"; +const IDENTITY_UNIQUE_KEY_SUBTYPES: &[&str] = &["primary", "secondary"]; + +/// Attributes whose value names another top-level object (ADR-0059 R4). +pub const REF_BEARING_ATTR_NAMES: &[&str] = &[ + "objectRef", + "through", + "references", + "from", + "via", + "of", + "parameterRef", + "payloadRef", + "responseRef", + "spine", +]; + +/// One load: the tree, its root, and every error and warning. +#[derive(Debug)] +pub struct LoadResult { + pub tree: Tree, + pub root: NodeId, + pub errors: Vec, + pub warnings: Vec, +} + +/// Loads metadata against one registry. +pub struct Loader<'r> { + registry: &'r TypeRegistry, +} + +/// Every metadata file under `dir`, recursively, sorted by file name as every +/// port's directory source does. `exclude_pending` skips `_pending/` at any depth; +/// it is off at the loader level, as in the other ports, where only the CLI-facing +/// source resolution turns it on. +/// A symlinked directory is followed once: a link back to a directory already +/// walked (a cycle, or a second route to the same files) is skipped. +pub fn metadata_files(dir: &Path, exclude_pending: bool) -> std::io::Result> { + fn walk( + dir: &Path, + exclude_pending: bool, + seen: &mut std::collections::HashSet, + out: &mut Vec, + ) -> std::io::Result<()> { + if !seen.insert(std::fs::canonicalize(dir)?) { + return Ok(()); + } + for entry in std::fs::read_dir(dir)? { + let path = entry?.path(); + if path.is_dir() { + if exclude_pending && path.file_name().is_some_and(|n| n == PENDING_DIR) { + continue; + } + walk(&path, exclude_pending, seen, out)?; + } else if let Some(ext) = path.extension().and_then(|e| e.to_str()) { + let ext = ext.to_ascii_lowercase(); + if ext == JSON_SUFFIX || YAML_SUFFIXES.contains(&ext.as_str()) { + out.push(path); + } + } + } + Ok(()) + } + let mut out = Vec::new(); + walk( + dir, + exclude_pending, + &mut std::collections::HashSet::new(), + &mut out, + )?; + out.sort_by(|a, b| a.file_name().cmp(&b.file_name()).then_with(|| a.cmp(b))); + Ok(out) +} + +impl<'r> Loader<'r> { + pub fn new(registry: &'r TypeRegistry) -> Self { + Self { registry } + } + + /// Load every metadata file under `dir`. A directory that cannot be walked is + /// an `Err`; a file that cannot be read is an error in the result, and the + /// other files still load. + pub fn load_dir(&self, dir: &Path) -> std::io::Result { + let files = metadata_files(dir, false)?; + let mut sources = Vec::with_capacity(files.len()); + let mut unreadable = Vec::new(); + for f in files { + let id = f.to_string_lossy().into_owned(); + match std::fs::read_to_string(&f) { + Ok(text) => sources.push((id, text)), + Err(e) => unreadable.push(MetaError::at( + ERR_UNKNOWN, + format!("{id}: cannot read metadata file: {e}"), + ErrorSource::json(&id, "$"), + )), + } + } + let mut result = self.load_sources(&sources); + unreadable.append(&mut result.errors); + result.errors = unreadable; + Ok(result) + } + + /// Load `(id, text)` pairs, each one JSON document named `id` in errors. + pub fn load_sources(&self, sources: &[(String, String)]) -> LoadResult { + let mut tree = Tree::new(); + let mut errors = Vec::new(); + let mut roots = Vec::new(); + for (id, text) in sources { + let envelope = if id.is_empty() { + ErrorSource::Code + } else { + ErrorSource::json(id, "$") + }; + let lower = id.to_ascii_lowercase(); + if YAML_SUFFIXES + .iter() + .any(|s| lower.ends_with(&format!(".{s}"))) + { + errors.push(MetaError::at( + ERR_UNKNOWN, + format!("{id}: YAML metadata is not supported by the Rust port yet"), + envelope, + )); + continue; + } + let doc: Value = match serde_json::from_str(text) { + Ok(v) => v, + Err(e) => { + errors.push(MetaError::at(ERR_MALFORMED_JSON, e.to_string(), envelope)); + continue; + } + }; + let parsed = parse_document(&doc, self.registry, &mut tree, id); + // An unknown type or subtype drops only that node, so the rest of the + // document is kept; any other parse error drops the document, as the + // TypeScript and Python loaders do. + let keep = parsed + .errors + .iter() + .all(|e| e.code == ERR_UNKNOWN_SUBTYPE || e.code == ERR_UNKNOWN_TYPE); + errors.extend(parsed.errors); + if keep && let Some(root) = parsed.root { + roots.push(root); + } + } + let root = if roots.is_empty() { + tree.add(Node::new(TYPE_METADATA, SUBTYPE_ROOT, "")) + } else { + let root = merge_roots(&mut tree, &roots, &mut errors); + // Neither pass adds, removes or renames a top-level node, so one index serves both. + let top = TopLevel::build(&tree, root); + resolve_supers(&mut tree, root, &top, &mut errors); + resolve_references(&mut tree, root, &top); + root + }; + // The terminal phase: the tree is complete, so it becomes read-only and its + // resolving reads memoize from here on (the other ports freeze at REGISTERED). + tree.freeze(); + LoadResult { + tree, + root, + errors, + warnings: Vec::new(), + } + } +} + +// ---- merge ----------------------------------------------------------------- + +/// The package-qualified identity of a root-level node for merge matching: its own +/// package, else its file's (never the merged root's). +fn root_child_key(tree: &Tree, id: NodeId) -> String { + let n = tree.node(id); + let pkg = n + .package + .as_deref() + .filter(|p| !p.is_empty()) + .or(n.file_default_package.as_deref().filter(|p| !p.is_empty())); + match pkg { + Some(p) => format!("{p}{PACKAGE_SEP}{}", n.name), + None => n.name.clone(), + } +} + +/// The same-type, same-name own child of `target` that `sc` merges into. Unnamed +/// nodes never match: they are always distinct (inline validators, say). +fn find_merge_match(tree: &Tree, target: NodeId, sc: NodeId) -> Option { + let is_root = tree.node(target).parent.is_none(); + let s = tree.node(sc); + if s.name.is_empty() { + return None; + } + let key = is_root.then(|| root_child_key(tree, sc)); + // ADR-0039: own — the merge works on the authored layer, before super resolution. + tree.own_children(target).iter().copied().find(|&c| { + let n = tree.node(c); + n.type_name == s.type_name + && n.name == s.name + && key.as_ref().is_none_or(|k| root_child_key(tree, c) == *k) + }) +} + +/// Fold every root into the first (ADR-0055's two-pass fold): plain declarations +/// merge by type and name, last writer wins; `overlay: true` nodes are applied once +/// every plain declaration is present. +fn merge_roots(tree: &mut Tree, roots: &[NodeId], errors: &mut Vec) -> NodeId { + let target = roots[0]; + let contributions: Vec> = roots + .iter() + // ADR-0039: own — the merge works on the authored layer, before super resolution. + .map(|&r| tree.own_children(r).to_vec()) + .collect(); + tree.take_own_children(target); + // Root-level matches go through an index: a large model has thousands of + // top-level nodes, and a linear scan per node would make the merge quadratic. + let mut index: HashMap<(String, String), NodeId> = HashMap::new(); + let mut pending = Vec::new(); + for (i, children) in contributions.into_iter().enumerate() { + if i > 0 { + let attrs: Vec<_> = tree + // ADR-0039: own — the merge works on the authored layer, before super resolution. + .own_attrs(roots[i]) + .map(|(k, a)| (k.clone(), a.clone())) + .collect(); + for (k, a) in attrs { + tree.set_attr(target, &k, a); + } + } + for sc in children { + if tree.node(sc).is_overlay { + pending.push((target, sc)); + continue; + } + if tree.node(sc).name.is_empty() { + // Unnamed nodes are always distinct. + tree.add_child(target, sc); + defer_nested_overlays(tree, sc, errors, Some(&mut pending)); + continue; + } + let key = (tree.node(sc).type_name.clone(), root_child_key(tree, sc)); + match index.get(&key) { + Some(&tc) => merge_into(tree, tc, sc, errors, Some(&mut pending)), + None => { + index.insert(key, sc); + tree.add_child(target, sc); + defer_nested_overlays(tree, sc, errors, Some(&mut pending)); + } + } + } + } + for (parent, node) in pending { + apply_overlay(tree, parent, node, errors); + } + target +} + +fn merge_child_into( + tree: &mut Tree, + target: NodeId, + sc: NodeId, + errors: &mut Vec, + pending: Option<&mut Vec<(NodeId, NodeId)>>, +) { + if tree.node(sc).is_overlay { + match pending { + Some(p) => p.push((target, sc)), + None => apply_overlay(tree, target, sc, errors), + } + return; + } + match find_merge_match(tree, target, sc) { + Some(tc) => merge_into(tree, tc, sc, errors, pending), + None => { + tree.add_child(target, sc); + defer_nested_overlays(tree, sc, errors, pending); + } + } +} + +fn defer_nested_overlays( + tree: &mut Tree, + node: NodeId, + errors: &mut Vec, + mut pending: Option<&mut Vec<(NodeId, NodeId)>>, +) { + // ADR-0039: own — the merge works on the authored layer, before super resolution. + let children = tree.own_children(node).to_vec(); + if !children.iter().any(|&c| subtree_has_overlay(tree, c)) { + return; + } + let kept: Vec = children + .iter() + .copied() + .filter(|&c| !tree.node(c).is_overlay) + .collect(); + tree.take_own_children(node); + for &c in &kept { + tree.add_child(node, c); + } + for c in children { + if tree.node(c).is_overlay { + match pending.as_deref_mut() { + Some(p) => p.push((node, c)), + None => apply_overlay(tree, node, c, errors), + } + } else { + defer_nested_overlays(tree, c, errors, pending.as_deref_mut()); + } + } +} + +fn subtree_has_overlay(tree: &Tree, id: NodeId) -> bool { + tree.node(id).is_overlay + || tree + // ADR-0039: own — the merge works on the authored layer, before super resolution. + .own_children(id) + .iter() + .any(|&c| subtree_has_overlay(tree, c)) +} + +fn apply_overlay(tree: &mut Tree, parent: NodeId, node: NodeId, errors: &mut Vec) { + match find_merge_match(tree, parent, node) { + Some(tc) => merge_into(tree, tc, node, errors, None), + None => { + let n = tree.node(node); + let p = tree.node(parent); + let referrer = if p.parent.is_none() { + root_child_key(tree, node) + } else { + format!("{}.{}", p.name, n.name) + }; + let target = format!("{}:{}", n.type_name, n.name); + errors.push(MetaError::at( + ERR_OVERLAY_NO_TARGET, + format!("overlay node '{}' has no merge target", n.fqn()), + resolved_source(&n.source, referrer, target), + )); + } + } +} + +fn merge_into( + tree: &mut Tree, + target: NodeId, + src: NodeId, + errors: &mut Vec, + mut pending: Option<&mut Vec<(NodeId, NodeId)>>, +) { + let attrs: Vec<_> = tree + // ADR-0039: own — the merge works on the authored layer, before super resolution. + .own_attrs(src) + .map(|(k, a)| (k.clone(), a.clone())) + .collect(); + for (k, a) in attrs { + tree.set_attr(target, &k, a); + } + // ADR-0039: own — the merge works on the authored layer, before super resolution. + for sc in tree.own_children(src).to_vec() { + merge_child_into(tree, target, sc, errors, pending.as_deref_mut()); + } +} + +/// A `resolved` envelope at `source`'s location. +fn resolved_source(source: &ErrorSource, referrer: String, target: String) -> ErrorSource { + ErrorSource::Resolved { + files: source.files().to_vec(), + json_path: source.json_path().unwrap_or("$").to_string(), + referrer, + target, + } +} + +// ---- references -------------------------------------------------------------- + +const CHILD_REF_SEP: char = '.'; +const PARENT_PREFIX: &str = "..::"; + +/// Split a reference into its owner and any dotted child tail (tail keeps its `.`). +pub fn split_child_tail(raw: &str) -> (&str, &str) { + let seg_start = raw.rfind(PACKAGE_SEP).map_or(0, |i| i + PACKAGE_SEP.len()); + match raw[seg_start..].find(CHILD_REF_SEP) { + Some(dot) => raw.split_at(seg_start + dot), + None => (raw, ""), + } +} + +/// A `..::` reference climbed above the root package. +#[derive(Debug)] +pub struct OverDrop; + +/// The resolution keys an owner reference may bind, in order (ADR-0059 R2). +pub fn owner_candidate_keys(owner: &str, referrer_pkg: &str) -> Result, OverDrop> { + if let Some(rest) = owner.strip_prefix(PACKAGE_SEP) { + return Ok(vec![rest.to_string()]); + } + if owner.starts_with(PARENT_PREFIX) { + let mut rest = owner; + let mut levels = 0; + while let Some(r) = rest.strip_prefix(PARENT_PREFIX) { + levels += 1; + rest = r; + } + let parts: Vec<&str> = if referrer_pkg.is_empty() { + Vec::new() + } else { + referrer_pkg.split(PACKAGE_SEP).collect() + }; + if levels > parts.len() { + return Err(OverDrop); + } + let reduced = parts[..parts.len() - levels].join(PACKAGE_SEP); + return Ok(vec![if reduced.is_empty() { + rest.to_string() + } else { + format!("{reduced}{PACKAGE_SEP}{rest}") + }]); + } + if owner.contains(PACKAGE_SEP) { + return Ok(vec![owner.to_string()]); + } + if referrer_pkg.is_empty() { + Ok(vec![owner.to_string()]) + } else { + Ok(vec![ + format!("{referrer_pkg}{PACKAGE_SEP}{owner}"), + owner.to_string(), + ]) + } +} + +/// The canonical spelling of a resolved owner, from a referrer in `referrer_pkg` +/// (ADR-0059 R6). +pub fn spell_ref(tree: &Tree, target: NodeId, referrer_pkg: &str, tail: &str) -> String { + let key = tree.resolution_key(target); + if !key.contains(PACKAGE_SEP) && !referrer_pkg.is_empty() { + format!("{PACKAGE_SEP}{key}{tail}") + } else { + format!("{key}{tail}") + } +} + +fn is_child_targeting_ref(r: &str) -> bool { + let seg_start = r.rfind(PACKAGE_SEP).map_or(0, |i| i + PACKAGE_SEP.len()); + r[seg_start..].contains(CHILD_REF_SEP) +} + +/// `Owner.child` → `Owner`, keeping any package prefix. +fn owner_ref(r: &str) -> Option { + let seg_start = r.rfind(PACKAGE_SEP).map_or(0, |i| i + PACKAGE_SEP.len()); + let parts: Vec<&str> = r[seg_start..].split(CHILD_REF_SEP).collect(); + if parts.len() < 2 || parts.iter().any(|p| p.is_empty()) { + return None; + } + Some(format!("{}{}", &r[..seg_start], parts[0])) +} + +enum Resolved { + Found(NodeId), + Missing, + OverDrop, +} + +struct SuperResolver<'a> { + tree: &'a mut Tree, + root: NodeId, + index: &'a HashMap, + attempted: HashSet, + errors: &'a mut Vec, +} + +impl SuperResolver<'_> { + fn lookup(&self, r: &str, pkg: &str, referrer_type: Option<&str>) -> Resolved { + if is_child_targeting_ref(r) { + let Some(referrer_type) = referrer_type else { + return Resolved::Missing; + }; + let seg_start = r.rfind(PACKAGE_SEP).map_or(0, |i| i + PACKAGE_SEP.len()); + let parts: Vec<&str> = r[seg_start..].split(CHILD_REF_SEP).collect(); + if parts.len() < 2 || parts.iter().any(|p| p.is_empty()) { + return Resolved::Missing; + } + let owner = format!("{}{}", &r[..seg_start], parts[0]); + let mut current = match self.lookup(&owner, pkg, None) { + Resolved::Found(n) => n, + other => return other, + }; + for seg in &parts[1..parts.len() - 1] { + let matches: Vec = self + .tree + .children(current) + .iter() + .copied() + .filter(|&c| self.tree.node(c).name == *seg) + .collect(); + if matches.len() != 1 { + return Resolved::Missing; + } + current = matches[0]; + } + let last = parts[parts.len() - 1]; + return self + .tree + .children(current) + .iter() + .copied() + .find(|&c| { + let n = self.tree.node(c); + n.name == last && n.type_name == referrer_type + }) + .map_or(Resolved::Missing, Resolved::Found); + } + match owner_candidate_keys(r, pkg) { + Err(OverDrop) => Resolved::OverDrop, + Ok(keys) => keys + .iter() + .find_map(|k| self.index.get(k).copied()) + .map_or(Resolved::Missing, Resolved::Found), + } + } + + /// Record an extends error on `id`. The node's fqn and source are built only here, + /// on the error path, never for an extends that resolves. + fn fail( + &mut self, + id: NodeId, + super_ref: &str, + code: &'static str, + message: impl FnOnce(&str) -> String, + ) { + let node = self.tree.node(id); + let fqn = node.fqn(); + let source = resolved_source(&node.source, fqn.clone(), super_ref.to_string()); + self.errors.push(MetaError::at(code, message(&fqn), source)); + } + + fn resolve(&mut self, id: NodeId) { + let node = self.tree.node(id); + let Some(super_ref) = node.super_ref.clone() else { + return; + }; + if node.super_node.is_some() || !self.attempted.insert(id) { + return; + } + let pkg = self.tree.effective_package(id); + if is_child_targeting_ref(&super_ref) + && let Some(owner) = owner_ref(&super_ref) + && let Resolved::Found(o) = self.lookup(&owner, &pkg, None) + { + self.resolve(o); + } + let referrer_type = self.tree.node(id).type_name.clone(); + match self.lookup(&super_ref, &pkg, Some(&referrer_type)) { + Resolved::OverDrop => self.fail(id, &super_ref, ERR_BAD_ATTR_VALUE, |fqn| { + format!( + "the extends ref '{super_ref}' on {fqn} climbs above the root package — each '..::' drops one segment of the declaring package" + ) + }), + Resolved::Missing => { + let hint = did_you_mean_super_hint(self.tree, self.root, &super_ref); + self.fail(id, &super_ref, ERR_UNRESOLVED_SUPER, |fqn| { + format!("the SuperClass '{super_ref}' does not exist (referenced by {fqn}){hint}") + }); + } + Resolved::Found(target) => { + if is_child_targeting_ref(&super_ref) && !extends_target_compatible(self.tree, id, target) { + let (t, n) = (self.tree.node(target), self.tree.node(id)); + let kinds = format!( + "[{}.{}] but the extending node is [{}.{}]", + t.type_name, t.sub_type, n.type_name, n.sub_type + ); + self.fail(id, &super_ref, ERR_EXTENDS_TARGET_MISMATCH, |fqn| { + format!( + "the dotted extends target '{super_ref}' is {kinds} — a dotted extends must target a node of the same type and subtype — the one exception is an identity, which may extend any UNIQUE key (identity.primary or identity.secondary) (referenced by {fqn})" + ) + }); + } else { + self.tree.node_mut(id).super_node = Some(target); + self.resolve(target); + } + } + } + } +} + +fn extends_target_compatible(tree: &Tree, node: NodeId, target: NodeId) -> bool { + let (n, t) = (tree.node(node), tree.node(target)); + if t.type_name != n.type_name { + return false; + } + if t.sub_type == n.sub_type { + return true; + } + n.type_name == TYPE_IDENTITY + && IDENTITY_UNIQUE_KEY_SUBTYPES.contains(&n.sub_type.as_str()) + && IDENTITY_UNIQUE_KEY_SUBTYPES.contains(&t.sub_type.as_str()) +} + +/// The did-you-mean suffix for an unresolved `extends`: same-short-name objects +/// that exist in other packages, and the spelling to write. +fn did_you_mean_super_hint(tree: &Tree, root: NodeId, r: &str) -> String { + let (owner, _) = split_child_tail(r); + let short = owner.rsplit(PACKAGE_SEP).next().unwrap_or(owner); + let candidates: Vec = tree + .children(root) + .iter() + .copied() + .filter(|&c| { + let n = tree.node(c); + n.type_name == TYPE_OBJECT && n.name == short + }) + .map(|c| tree.resolution_key(c)) + .collect(); + if candidates.is_empty() { + return String::new(); + } + format!( + " An object named \"{short}\" exists in: {}. Qualify it with its package (FQN): write extends: \"{}\".", + candidates.join(", "), + candidates[0] + ) +} + +fn collect_supers(tree: &Tree, id: NodeId, out: &mut Vec) { + if tree.node(id).super_ref.is_some() { + out.push(id); + } + // ADR-0039: own — a whole-tree walk visits each physical node once; inherited children are visited where they are declared. + for &c in tree.own_children(id) { + collect_supers(tree, c, out); + } +} + +/// Resolve every `extends` in the merged tree, independently of load order (#188): +/// a dotted reference to an owner resolves the owner's own chain first. +fn resolve_supers(tree: &mut Tree, root: NodeId, top: &TopLevel, errors: &mut Vec) { + let mut pending = Vec::new(); + collect_supers(tree, root, &mut pending); + let mut r = SuperResolver { + tree, + root, + index: &top.named, + attempted: HashSet::new(), + errors, + }; + for id in pending { + r.resolve(id); + } +} + +/// The root's top-level nodes by resolution key, first declaration winning, built +/// once per pass so each reference is one hash lookup. +struct TopLevel { + named: HashMap, + objects: HashMap, +} + +impl TopLevel { + fn build(tree: &Tree, root: NodeId) -> Self { + let mut named = HashMap::new(); + let mut objects = HashMap::new(); + // ADR-0039: own — the root's top-level nodes are its declared children; a root extends nothing. + for &c in tree.own_children(root) { + let key = tree.resolution_key(c); + if tree.node(c).type_name == TYPE_OBJECT { + objects.entry(key.clone()).or_insert(c); + } + if !tree.node(c).name.is_empty() { + named.entry(key).or_insert(c); + } + } + Self { named, objects } + } + + fn bind(map: &HashMap, owner: &str, pkg: &str) -> Option { + owner_candidate_keys(owner, pkg) + .ok()? + .iter() + .find_map(|k| map.get(k).copied()) + } +} + +/// ADR-0059 R5: rewrite every resolved `extends` and reference attribute to its +/// canonical spelling, keeping the authored value beside it. A reference that does +/// not resolve is left as written. +fn resolve_references(tree: &mut Tree, root: NodeId, top: &TopLevel) { + let mut stack = vec![root]; + while let Some(id) = stack.pop() { + if id != root { + resolve_extends(tree, top, id); + let decl_pkg = tree.effective_package(tree.top_level_of(id)); + let names: Vec = tree + // ADR-0039: own — reference resolution rewrites the value this node declares, not an inherited one. + .own_attrs(id) + .filter(|(k, _)| REF_BEARING_ATTR_NAMES.contains(&k.as_str())) + .map(|(k, _)| k.clone()) + .collect(); + for name in names { + resolve_attr(tree, top, id, &name, &decl_pkg); + } + } + // ADR-0039: own — a whole-tree walk visits each physical node once; inherited children are visited where they are declared. + stack.extend(tree.own_children(id).iter().rev().copied()); + } +} + +fn resolve_one(tree: &Tree, top: &TopLevel, value: &str, pkg: &str) -> Option { + let (owner, tail) = split_child_tail(value); + let target = TopLevel::bind(&top.objects, owner, pkg)?; + Some(spell_ref(tree, target, pkg, tail)) +} + +fn resolve_attr(tree: &mut Tree, top: &TopLevel, id: NodeId, name: &str, pkg: &str) { + // ADR-0039: own — reference resolution rewrites the value this node declares, not an inherited one. + let Some(attr) = tree.own_attr(id, name) else { + return; + }; + let new_value = match &attr.value { + Value::String(s) if !s.is_empty() => resolve_one(tree, top, s, pkg).map(Value::String), + Value::Array(items) if items.iter().all(Value::is_string) => { + let mut any = false; + let out: Vec = items + .iter() + .map(|v| { + let s = v.as_str().unwrap_or_default(); + match (!s.is_empty()) + .then(|| resolve_one(tree, top, s, pkg)) + .flatten() + { + Some(c) => { + any = true; + Value::String(c) + } + None => v.clone(), + } + }) + .collect(); + any.then_some(Value::Array(out)) + } + _ => None, + }; + let Some(new_value) = new_value else { + return; + }; + // ADR-0039: own — reference resolution rewrites the value this node declares, not an inherited one. + if let Some(attr) = tree.own_attr_mut(id, name) + && attr.value != new_value + { + if attr.authored_value.is_none() { + attr.authored_value = Some(attr.value.clone()); + } + attr.value = new_value; + } +} + +fn resolve_extends(tree: &mut Tree, top: &TopLevel, id: NodeId) { + let node = tree.node(id); + let (Some(r), Some(_)) = (node.super_ref.clone(), node.super_node) else { + return; + }; + let pkg = tree.effective_package(id); + let (owner, tail) = split_child_tail(&r); + let Some(owner_node) = TopLevel::bind(&top.named, owner, &pkg) else { + return; + }; + let canonical = spell_ref(tree, owner_node, &pkg, tail); + if canonical == r { + return; + } + let n = tree.node_mut(id); + if n.authored_super_ref.is_none() { + n.authored_super_ref = Some(r); + } + n.super_ref = Some(canonical); +} diff --git a/server/rust/metaobjects/src/manifest.rs b/server/rust/metaobjects/src/manifest.rs new file mode 100644 index 0000000000..1d0a9fa4e9 --- /dev/null +++ b/server/rust/metaobjects/src/manifest.rs @@ -0,0 +1,178 @@ +//! The registry manifest: the registry written as the canonical JSON every port +//! must produce byte for byte (`fixtures/registry-conformance/expected-registry.json`). + +use serde_json::{Map, Value, json}; + +use crate::json::{js_display, to_js_pretty}; +use crate::registry::{AttrSchema, ChildRule, ChildSubType, TypeDefinition, TypeRegistry}; + +/// The metamodel version this build implements. +pub const METAMODEL_VERSION: &str = "1.3"; + +/// Per-type attrs that are structural keywords or common-attr duplicates, so they +/// stay out of the manifest's per-type rows. +const EXCLUDED_PER_TYPE_ATTRS: &[&str] = &[ + "isArray", + "isAbstract", + "extends", + "implements", + "isInterface", + "description", +]; + +fn sorted(list: &[String]) -> Value { + let mut l = list.to_vec(); + l.sort(); + json!(l) +} + +fn manifest_attr(attr: &AttrSchema) -> Value { + let legacy = attr.value_type.as_deref() == Some("stringarray"); + let mut m = Map::new(); + m.insert("name".into(), json!(attr.name)); + let value_type = if legacy { + json!("string") + } else { + attr.value_type.as_ref().map_or(Value::Null, |v| json!(v)) + }; + m.insert("valueType".into(), value_type); + m.insert( + "isArray".into(), + json!(attr.is_array == Some(true) || legacy), + ); + m.insert("required".into(), json!(attr.required)); + if let Some(values) = attr.allowed_values.as_ref().filter(|v| !v.is_empty()) { + m.insert( + "allowedValues".into(), + Value::Array(values.iter().map(|v| json!(js_display(v))).collect()), + ); + } + if let Some(list) = attr.implemented_in.as_ref().filter(|v| !v.is_empty()) { + m.insert("implementedIn".into(), sorted(list)); + } + if let Some(list) = attr.ports.as_ref().filter(|v| !v.is_empty()) { + m.insert("ports".into(), sorted(list)); + } + m.insert("description".into(), json!(attr.description)); + for (key, val) in [ + ("rules", &attr.rules), + ("example", &attr.example), + ("whenToUse", &attr.when_to_use), + ] { + if let Some(v) = val { + m.insert(key.into(), json!(v)); + } + } + Value::Object(m) +} + +fn sub_type_key(sub: &ChildSubType) -> String { + match sub { + ChildSubType::One(s) => s.clone(), + ChildSubType::Many(list) => list.join(","), + } +} + +fn manifest_child(rule: &ChildRule) -> Value { + let mut m = Map::new(); + m.insert("childType".into(), json!(rule.child_type)); + let sub = match &rule.child_sub_type { + ChildSubType::One(s) => json!(s), + ChildSubType::Many(list) => json!(list), + }; + m.insert("childSubType".into(), sub); + m.insert("childName".into(), json!(rule.child_name)); + if let Some(min) = rule.min { + m.insert("min".into(), json!(min)); + } + if let Some(max) = rule.max { + m.insert("max".into(), max.map_or(Value::Null, |v| json!(v))); + } + if let Some(named) = rule.named { + m.insert("named".into(), json!(named)); + } + Value::Object(m) +} + +fn sorted_attrs<'a>(attrs: impl Iterator) -> Vec { + let mut list: Vec<&AttrSchema> = attrs.collect(); + list.sort_by(|a, b| a.name.cmp(&b.name)); + list.into_iter().map(manifest_attr).collect() +} + +fn manifest_type(def: &TypeDefinition) -> Value { + let mut m = Map::new(); + m.insert("type".into(), json!(def.type_name)); + m.insert("subType".into(), json!(def.sub_type)); + if let Some(list) = def.implemented_in.as_ref().filter(|v| !v.is_empty()) { + m.insert("implementedIn".into(), sorted(list)); + } + m.insert("description".into(), json!(def.description)); + for (key, val) in [ + ("rules", &def.rules), + ("example", &def.example), + ("whenToUse", &def.when_to_use), + ] { + if let Some(v) = val { + m.insert(key.into(), json!(v)); + } + } + let attrs = sorted_attrs( + def.attributes + .iter() + .filter(|a| !EXCLUDED_PER_TYPE_ATTRS.contains(&a.name.as_str())), + ); + m.insert("attrs".into(), Value::Array(attrs)); + let mut rules: Vec<&ChildRule> = def.child_rules.iter().collect(); + rules.sort_by(|a, b| { + a.child_type + .cmp(&b.child_type) + .then_with(|| sub_type_key(&a.child_sub_type).cmp(&sub_type_key(&b.child_sub_type))) + .then_with(|| a.child_name.cmp(&b.child_name)) + }); + m.insert( + "children".into(), + Value::Array(rules.into_iter().map(manifest_child).collect()), + ); + if let Some(parents) = def.parents.as_ref().filter(|p| !p.is_empty()) { + m.insert("parents".into(), sorted(parents)); + } + Value::Object(m) +} + +/// Build the manifest as a JSON value. +pub fn build_manifest(registry: &TypeRegistry) -> Value { + let mut defs: Vec<&TypeDefinition> = registry + .all() + .filter(|d| !(d.type_name == "metadata" && d.sub_type == "base")) + .collect(); + defs.sort_by_key(|a| a.key()); + let mut type_names: Vec<&str> = defs.iter().map(|d| d.type_name.as_str()).collect(); + type_names.sort(); + type_names.dedup(); + let mut defaults = Map::new(); + for name in type_names { + if let Some(sub) = registry.default_sub_type_of(name) { + defaults.insert(name.to_string(), json!(sub)); + } + } + let mut m = Map::new(); + m.insert("metamodelVersion".into(), json!(METAMODEL_VERSION)); + m.insert( + "types".into(), + Value::Array(defs.into_iter().map(manifest_type).collect()), + ); + m.insert( + "commonAttrs".into(), + Value::Array(sorted_attrs(registry.common_attrs().iter())), + ); + m.insert("defaultSubTypes".into(), Value::Object(defaults)); + Value::Object(m) +} + +/// The manifest as text, exactly as the shared fixture holds it. +pub fn emit_manifest(registry: &TypeRegistry) -> String { + let mut out = to_js_pretty(&build_manifest(registry)); + out.push('\n'); + out +} diff --git a/server/rust/metaobjects/src/node.rs b/server/rust/metaobjects/src/node.rs new file mode 100644 index 0000000000..c71200db2f --- /dev/null +++ b/server/rust/metaobjects/src/node.rs @@ -0,0 +1,586 @@ +//! The metadata tree: every node lives in one arena and is addressed by a +//! [`NodeId`], so `extends` links and parent links are plain indices. +//! +//! Reads follow ADR-0039. The resolving accessors ([`Tree::attr`], [`Tree::attrs`], +//! [`Tree::children`], [`Tree::resolved_is_array`]) are the default: they see what a +//! node inherits through `extends`. The `own_*` accessors read only the layer a node +//! declares itself, and are for the few passes that work on that layer by definition +//! (the parser, the merge, super resolution and the own-mode serializer). +//! +//! ## The runtime read path: freeze, then memoize +//! +//! A tree has two phases, as in every other port. While the loader builds it, it is +//! mutable and every resolving read walks the `extends` chain afresh. When the loader +//! reaches its terminal phase it calls [`Tree::freeze`], after which the tree can no +//! longer change (every mutator panics) and the resolving accessors memoize their +//! walks, one [`OnceLock`] per node and accessor. Nothing is cached before the freeze, +//! so a value read during the load can never be served stale after a later mutation, +//! and nothing is ever invalidated. The caches are filled on first read and are safe +//! to share between threads: `Tree` is `Sync`, and a racing first read of one entry +//! computes it once while the other readers wait. +//! +//! The memoized set is the one the other ports memoize on their base node: +//! [`Tree::children`], [`Tree::attrs`] (and [`Tree::attr`], which reads through it once +//! frozen, on a node that extends something) and [`Tree::resolved_is_array`]. TypeScript and C# also cache snapshots of a +//! node's own attrs and own children because they copy them; here those accessors +//! already borrow the node's own storage, so there is nothing to save. + +use std::borrow::Cow; +use std::sync::OnceLock; + +use indexmap::IndexMap; +use serde_json::Value; + +use crate::source::ErrorSource; + +/// The package separator in a resolution key (`acme::sales::Customer`). +pub const PACKAGE_SEP: &str = "::"; + +/// The index of a node in its [`Tree`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct NodeId(pub(crate) u32); + +impl NodeId { + pub fn index(self) -> usize { + self.0 as usize + } + + /// The id of the node at `index` in its tree's arena. + pub fn from_index(index: usize) -> Self { + Self(u32::try_from(index).expect("fewer than 2^32 nodes")) + } +} + +/// One attribute value on a node. +#[derive(Debug, Clone, PartialEq)] +pub struct Attr { + /// The attr subtype it was coerced as (`string`, `int`, `base`, ...). + pub sub_type: String, + pub value: Value, + /// The value as written, kept when reference resolution rewrote `value` to its + /// canonical spelling (ADR-0059 R5). + pub authored_value: Option, + pub source: ErrorSource, +} + +/// One node of the tree. +#[derive(Debug, Clone)] +pub struct Node { + pub type_name: String, + pub sub_type: String, + pub name: String, + /// The package this node declares itself (`None` when it inherits its file's). + pub package: Option, + /// The package of the file that declared it, captured at parse time; `Some("")` + /// for a file with no package (ADR-0059 R10). + pub file_default_package: Option, + /// The `extends` value. Canonical once the loader has resolved references. + pub super_ref: Option, + /// The `extends` value as written, kept when it was rewritten. + pub authored_super_ref: Option, + /// The node `extends` resolved to. + pub super_node: Option, + pub is_abstract: bool, + pub is_overlay: bool, + pub is_array: bool, + pub parent: Option, + attrs: IndexMap, + children: Vec, + pub source: ErrorSource, +} + +impl Node { + pub fn new(type_name: &str, sub_type: &str, name: &str) -> Self { + Self { + type_name: type_name.to_string(), + sub_type: sub_type.to_string(), + name: name.to_string(), + package: None, + file_default_package: None, + super_ref: None, + authored_super_ref: None, + super_node: None, + is_abstract: false, + is_overlay: false, + is_array: false, + parent: None, + attrs: IndexMap::new(), + children: Vec::new(), + source: ErrorSource::Code, + } + } + + /// `package::name` when the node declares a package, else its name. + pub fn fqn(&self) -> String { + match self.package.as_deref() { + Some(p) if !p.is_empty() => format!("{p}{PACKAGE_SEP}{}", self.name), + _ => self.name.clone(), + } + } +} + +/// The memoized resolving reads of one node, filled on first read after +/// [`Tree::freeze`]. +#[derive(Debug, Clone, Default)] +struct NodeCache { + children: OnceLock>, + attrs: OnceLock>, + is_array: OnceLock, +} + +/// The arena holding every node of one load. +#[derive(Debug, Clone, Default)] +pub struct Tree { + nodes: Vec, + /// One entry per node once frozen; empty while the tree is still mutable. + cache: Vec, + frozen: bool, +} + +const FROZEN_MUTATION: &str = "cannot mutate a frozen metadata tree"; + +impl Tree { + pub fn new() -> Self { + Self::default() + } + + /// End the load phase: from here on the tree is read-only and the resolving + /// accessors memoize what they compute. Idempotent. + pub fn freeze(&mut self) { + if self.frozen { + return; + } + self.frozen = true; + self.cache = vec![NodeCache::default(); self.nodes.len()]; + } + + /// `true` once [`Tree::freeze`] has ended the load phase. + pub fn is_frozen(&self) -> bool { + self.frozen + } + + fn assert_mutable(&self) { + assert!(!self.frozen, "{FROZEN_MUTATION}"); + } + + /// The node's cache entry, or `None` while the tree is still mutable. + fn cache(&self, id: NodeId) -> Option<&NodeCache> { + self.cache.get(id.index()) + } + + pub fn add(&mut self, node: Node) -> NodeId { + self.assert_mutable(); + let id = NodeId::from_index(self.nodes.len()); + self.nodes.push(node); + id + } + + pub fn node(&self, id: NodeId) -> &Node { + &self.nodes[id.index()] + } + + pub fn node_mut(&mut self, id: NodeId) -> &mut Node { + self.assert_mutable(); + &mut self.nodes[id.index()] + } + + pub fn len(&self) -> usize { + self.nodes.len() + } + + pub fn is_empty(&self) -> bool { + self.nodes.is_empty() + } + + // ---- structure ------------------------------------------------------- + + /// Append `child` to `parent`'s own children. + pub fn add_child(&mut self, parent: NodeId, child: NodeId) { + self.assert_mutable(); + self.nodes[child.index()].parent = Some(parent); + self.nodes[parent.index()].children.push(child); + } + + /// Replace `parent`'s own children wholesale (the merge rebuilds the root's). + pub(crate) fn take_own_children(&mut self, parent: NodeId) -> Vec { + self.assert_mutable(); + std::mem::take(&mut self.nodes[parent.index()].children) + } + + /// The children `id` declares itself, in authoring order. + pub fn own_children(&self, id: NodeId) -> &[NodeId] { + &self.nodes[id.index()].children + } + + /// Effective children: what `id` inherits through `extends`, with each own child + /// replacing the inherited child of the same type and name, and own children that + /// replace nothing appended after. Mirrors the TypeScript reference's append queue. + /// Memoized once the tree is frozen. + pub fn children(&self, id: NodeId) -> Cow<'_, [NodeId]> { + if self.node(id).super_node.is_none() { + return Cow::Borrowed(&self.node(id).children); + } + match self.cache(id) { + Some(c) => Cow::Borrowed(c.children.get_or_init(|| self.compute_children(id).into())), + None => Cow::Owned(self.compute_children(id)), + } + } + + fn compute_children(&self, id: NodeId) -> Vec { + let mut visited = vec![id]; + self.effective_children(id, &mut visited) + } + + fn effective_children(&self, id: NodeId, visited: &mut Vec) -> Vec { + let node = self.node(id); + let Some(sup) = node.super_node.filter(|s| !visited.contains(s)) else { + return node.children.clone(); + }; + visited.push(sup); + let mut result = self.effective_children(sup, visited); + let mut claimed = vec![false; result.len()]; + let mut append = Vec::new(); + for &own in &node.children { + let o = self.node(own); + let hit = result.iter().enumerate().position(|(i, &c)| { + let c = self.node(c); + !claimed[i] && c.type_name == o.type_name && c.name == o.name + }); + match hit { + Some(i) => { + result[i] = own; + claimed[i] = true; + } + None => append.push(own), + } + } + result.extend(append); + result + } + + // ---- attributes ------------------------------------------------------ + + pub fn set_attr(&mut self, id: NodeId, name: &str, attr: Attr) { + self.assert_mutable(); + self.nodes[id.index()].attrs.insert(name.to_string(), attr); + } + + /// The attribute `id` declares itself. + pub fn own_attr(&self, id: NodeId, name: &str) -> Option<&Attr> { + self.nodes[id.index()].attrs.get(name) + } + + pub(crate) fn own_attr_mut(&mut self, id: NodeId, name: &str) -> Option<&mut Attr> { + self.assert_mutable(); + self.nodes[id.index()].attrs.get_mut(name) + } + + /// The attributes `id` declares itself, in authoring order. + pub fn own_attrs(&self, id: NodeId) -> impl Iterator { + self.nodes[id.index()].attrs.iter() + } + + /// `id`, then what it extends, then what that extends, stopping at a cycle. + fn super_chain(&self, id: NodeId) -> Vec { + let mut chain = Vec::new(); + let mut cur = Some(id); + while let Some(n) = cur { + if chain.contains(&n) { + break; + } + chain.push(n); + cur = self.nodes[n.index()].super_node; + } + chain + } + + /// The effective value of attribute `name`: own, else inherited through `extends`. + /// Once frozen it is a lookup in the memoized [`Tree::attrs`] map. + pub fn attr(&self, id: NodeId, name: &str) -> Option<&Value> { + // A node that extends nothing answers from its own map, a borrow, with no cache. + if self.node(id).super_node.is_none() { + return self.compute_attr(id, name); + } + match self.cache(id) { + Some(c) => c.attrs.get_or_init(|| self.compute_attrs(id)).get(name), + None => self.compute_attr(id, name), + } + } + + fn compute_attr(&self, id: NodeId, name: &str) -> Option<&Value> { + self.super_chain(id).into_iter().find_map(|n| { + self.nodes[n.index()] + .attrs + .get(name) + .map(|a| &a.value) + .filter(|v| !v.is_null()) + }) + } + + /// Every effective attribute value of `id`, own winning over inherited. + /// Null values are left out, as an unset attribute is. Memoized once frozen. + pub fn attrs(&self, id: NodeId) -> Cow<'_, IndexMap> { + match self.cache(id) { + Some(c) => Cow::Borrowed(c.attrs.get_or_init(|| self.compute_attrs(id))), + None => Cow::Owned(self.compute_attrs(id)), + } + } + + fn compute_attrs(&self, id: NodeId) -> IndexMap { + let mut out = IndexMap::new(); + for n in self.super_chain(id).into_iter().rev() { + for (k, a) in &self.nodes[n.index()].attrs { + if !a.value.is_null() { + out.insert(k.clone(), a.value.clone()); + } + } + } + out + } + + /// Effective array-ness: the native flag on `id` or anything it extends. + /// Memoized once frozen. + pub fn resolved_is_array(&self, id: NodeId) -> bool { + match self.cache(id) { + Some(c) => *c.is_array.get_or_init(|| self.compute_is_array(id)), + None => self.compute_is_array(id), + } + } + + fn compute_is_array(&self, id: NodeId) -> bool { + self.super_chain(id) + .into_iter() + .any(|n| self.nodes[n.index()].is_array) + } + + // ---- packages and names ---------------------------------------------- + + /// The package `id` resolves under: its own, else its file's, else (for a node + /// built in code) the nearest ancestor's. + pub fn effective_package(&self, id: NodeId) -> String { + let node = self.node(id); + if let Some(p) = node.package.as_deref().filter(|p| !p.is_empty()) { + return p.to_string(); + } + if let Some(p) = node.file_default_package.as_deref() { + return p.to_string(); + } + let mut cur = node.parent; + while let Some(n) = cur { + if let Some(p) = self.node(n).package.as_deref().filter(|p| !p.is_empty()) { + return p.to_string(); + } + cur = self.node(n).parent; + } + String::new() + } + + /// `::`, or the bare name with no package. + pub fn resolution_key(&self, id: NodeId) -> String { + let pkg = self.effective_package(id); + if pkg.is_empty() { + self.node(id).name.clone() + } else { + format!("{pkg}{PACKAGE_SEP}{}", self.node(id).name) + } + } + + /// The top-level node (a direct child of the root) that physically holds `id`. + pub fn top_level_of(&self, id: NodeId) -> NodeId { + let mut cur = id; + while let Some(p) = self.node(cur).parent { + if self.node(p).parent.is_none() { + return cur; + } + cur = p; + } + cur + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::loader::Loader; + use crate::providers::default_registry; + use serde_json::json; + + const FITNESS: &str = + include_str!("../../../../fixtures/persistence-conformance/canonical/meta.fitness.json"); + + fn attr(value: Value) -> Attr { + Attr { + sub_type: "string".into(), + value, + authored_value: None, + source: ErrorSource::Code, + } + } + + /// `Derived extends Base`, each with a field and an attr, `Base` an array. + fn chain() -> (Tree, NodeId, NodeId) { + let mut t = Tree::new(); + let root = t.add(Node::new("metadata", "root", "")); + let base = t.add(Node::new("object", "entity", "Base")); + let derived = t.add(Node::new("object", "entity", "Derived")); + t.add_child(root, base); + t.add_child(root, derived); + for (owner, field) in [ + (base, "id"), + (base, "name"), + (derived, "name"), + (derived, "age"), + ] { + let f = t.add(Node::new("field", "string", field)); + t.add_child(owner, f); + } + t.set_attr(base, "table", attr(json!("base_t"))); + t.set_attr(base, "label", attr(json!("Base"))); + t.set_attr(derived, "label", attr(json!("Derived"))); + t.node_mut(base).is_array = true; + t.node_mut(derived).super_node = Some(base); + (t, base, derived) + } + + fn assert_cached_matches_uncached(t: &Tree) { + for i in 0..t.len() { + let id = NodeId::from_index(i); + assert_eq!( + *t.children(id), + t.compute_children(id)[..], + "children of {i}" + ); + assert_eq!(*t.attrs(id), t.compute_attrs(id), "attrs of {i}"); + assert_eq!( + t.resolved_is_array(id), + t.compute_is_array(id), + "is_array of {i}" + ); + for k in t.compute_attrs(id).keys() { + assert_eq!(t.attr(id, k), t.compute_attr(id, k), "attr {k} of {i}"); + } + assert_eq!(t.attr(id, "noSuchAttr"), None); + } + } + + #[test] + fn nothing_is_cached_before_freeze() { + let (t, _, derived) = chain(); + assert!(!t.is_frozen()); + assert!(matches!(t.children(derived), Cow::Owned(_))); + assert!(matches!(t.attrs(derived), Cow::Owned(_))); + } + + #[test] + fn frozen_reads_are_borrowed_from_the_cache() { + let (mut t, _, derived) = chain(); + t.freeze(); + let first = t.attrs(derived); + assert!(matches!(first, Cow::Borrowed(_))); + assert!(std::ptr::eq(&*first, &*t.attrs(derived)), "one cached map"); + assert!(matches!(t.children(derived), Cow::Borrowed(_))); + assert!(t.resolved_is_array(derived)); + } + + #[test] + fn a_value_read_before_freeze_does_not_survive_a_later_mutation() { + let (mut t, base, derived) = chain(); + // Read every memoized accessor during the load phase ... + assert_eq!(t.attr(derived, "table"), Some(&json!("base_t"))); + assert_eq!(t.attrs(derived).len(), 2); + assert_eq!(t.children(derived).len(), 3); + assert!(t.resolved_is_array(derived)); + // ... then change what they depend on, and freeze. + t.set_attr(base, "table", attr(json!("renamed_t"))); + t.set_attr(derived, "extra", attr(json!(1))); + let more = t.add(Node::new("field", "string", "email")); + t.add_child(base, more); + t.node_mut(base).is_array = false; + t.freeze(); + assert_eq!(t.attr(derived, "table"), Some(&json!("renamed_t"))); + assert_eq!(t.attrs(derived).len(), 3); + assert_eq!(t.children(derived).len(), 4); + assert!(!t.resolved_is_array(derived)); + assert_cached_matches_uncached(&t); + } + + #[test] + fn freeze_is_idempotent_and_keeps_the_cache() { + let (mut t, _, derived) = chain(); + t.freeze(); + let before: *const IndexMap = &*t.attrs(derived); + t.freeze(); + assert!(std::ptr::eq(before, &*t.attrs(derived))); + } + + #[test] + #[should_panic(expected = "cannot mutate a frozen metadata tree")] + fn a_frozen_tree_refuses_mutation() { + let (mut t, base, _) = chain(); + t.freeze(); + t.set_attr(base, "table", attr(json!("late"))); + } + + #[test] + fn cached_reads_equal_uncached_on_a_hand_built_chain() { + let (mut t, _, _) = chain(); + t.freeze(); + assert_cached_matches_uncached(&t); + // A second pass reads only from the cache. + assert_cached_matches_uncached(&t); + } + + #[test] + fn cached_reads_equal_uncached_on_the_fitness_model() { + let registry = default_registry().expect("the built-in providers compose"); + let result = + Loader::new(®istry).load_sources(&[("meta.fitness.json".into(), FITNESS.into())]); + assert!(result.errors.is_empty(), "{:?}", result.errors.first()); + assert!( + result.tree.is_frozen(), + "the loader freezes at its terminal phase" + ); + let t = &result.tree; + let extending = (0..t.len()) + .filter(|&i| t.nodes[i].super_node.is_some()) + .count(); + assert!(extending > 0, "the model exercises extends"); + assert_cached_matches_uncached(&result.tree); + } + + #[test] + fn concurrent_readers_see_the_uncached_values() { + let registry = default_registry().expect("the built-in providers compose"); + let result = + Loader::new(®istry).load_sources(&[("meta.fitness.json".into(), FITNESS.into())]); + let tree = &result.tree; + let ids: Vec = (0..tree.len()).map(NodeId::from_index).collect(); + let expected: Vec<_> = ids + .iter() + .map(|&id| { + ( + tree.compute_children(id), + tree.compute_attrs(id), + tree.compute_is_array(id), + ) + }) + .collect(); + std::thread::scope(|s| { + for worker in 0..8 { + let (ids, expected) = (&ids, &expected); + s.spawn(move || { + // Each worker walks the nodes from a different start, so first reads race. + for round in 0..4 { + for k in 0..ids.len() { + let i = (k + worker * 7 + round) % ids.len(); + let (children, attrs, is_array) = &expected[i]; + assert_eq!(*tree.children(ids[i]), children[..]); + assert_eq!(*tree.attrs(ids[i]), *attrs); + assert_eq!(tree.resolved_is_array(ids[i]), *is_array); + } + } + }); + } + }); + } +} diff --git a/server/rust/metaobjects/src/parser.rs b/server/rust/metaobjects/src/parser.rs new file mode 100644 index 0000000000..ad19e8246c --- /dev/null +++ b/server/rust/metaobjects/src/parser.rs @@ -0,0 +1,644 @@ +//! One JSON document to a subtree of the [`Tree`]. +//! +//! Follows the shared parser contract every port implements (the TypeScript +//! `parser-core.ts` is the reference): a node is a one-key map +//! `{ ".": }`; the KEY is judged before the BODY; reserved +//! structural keys may not be written with `@`; inline `@attrs` are coerced by the +//! registered attr schema; `attr.` children are attributes, not children. + +use serde_json::{Map, Value}; + +use crate::errors::{ + ERR_ABSTRACT_SUBTYPE_AUTHORED, ERR_BAD_ATTR_VALUE, ERR_CHILD_NOT_OBJECT, + ERR_MISSING_REQUIRED_ATTR, ERR_MISSING_SUBTYPE, ERR_RESERVED_ATTR, ERR_TOP_LEVEL_NOT_OBJECT, + ERR_UNKNOWN_SUBTYPE, ERR_UNKNOWN_TYPE, ERR_UNRESOLVED_SUPER, MetaError, +}; +use crate::json::{js_display, safe_whole_i64}; +use crate::node::{Attr, Node, NodeId, PACKAGE_SEP, Tree}; +use crate::registry::{SUBTYPE_BASE, TypeRegistry}; +use crate::source::{ErrorSource, JsonPath}; + +pub const TYPE_METADATA: &str = "metadata"; +pub const SUBTYPE_ROOT: &str = "root"; +pub const TYPE_ATTR: &str = "attr"; +pub const TYPE_FIELD: &str = "field"; +pub const TYPE_OBJECT: &str = "object"; + +pub const KEY_NAME: &str = "name"; +pub const KEY_PACKAGE: &str = "package"; +pub const KEY_EXTENDS: &str = "extends"; +pub const KEY_ABSTRACT: &str = "abstract"; +pub const KEY_OVERLAY: &str = "overlay"; +pub const KEY_IS_ARRAY: &str = "isArray"; +pub const KEY_CHILDREN: &str = "children"; +pub const KEY_VALUE: &str = "value"; +/// The editor-schema key a document may carry beside its wrapper key. +pub const KEY_SCHEMA: &str = "$schema"; + +pub const ATTR_PREFIX: &str = "@"; +pub const FUSED_KEY_SEP: char = '.'; + +/// Attr subtypes the loader coerces or desugars. +pub const ATTR_SUBTYPE_STRING: &str = "string"; +pub const ATTR_SUBTYPE_INT: &str = "int"; +pub const ATTR_SUBTYPE_LONG: &str = "long"; +pub const ATTR_SUBTYPE_FILTER: &str = "filter"; +pub const ATTR_SUBTYPE_PROPERTIES: &str = "properties"; +/// Not a registered subtype: the coercion an array-valued string attr gets +/// (a bare string becomes a one-element list). +pub const ATTR_SUBTYPE_STRINGARRAY: &str = "stringarray"; + +const RESERVED_STRUCTURAL_KEYS: &[&str] = &[ + KEY_NAME, + KEY_PACKAGE, + KEY_EXTENDS, + KEY_ABSTRACT, + KEY_OVERLAY, + KEY_IS_ARRAY, + KEY_CHILDREN, + KEY_VALUE, +]; + +/// What one document produced. +pub struct Parsed { + pub root: Option, + pub errors: Vec, +} + +struct Ctx<'a> { + tree: &'a mut Tree, + registry: &'a TypeRegistry, + file: &'a str, + errors: Vec, +} + +impl Ctx<'_> { + fn here(&self, path: &JsonPath) -> ErrorSource { + if self.file.is_empty() { + ErrorSource::Code + } else { + ErrorSource::json(self.file, path.as_str()) + } + } + + fn error(&mut self, code: &'static str, message: String, path: &JsonPath) { + let source = self.here(path); + self.errors.push(MetaError::at(code, message, source)); + } +} + +/// Parse one document into `tree`. `file` names it in error envelopes. +pub fn parse_document(doc: &Value, registry: &TypeRegistry, tree: &mut Tree, file: &str) -> Parsed { + let mut ctx = Ctx { + tree, + registry, + file, + errors: Vec::new(), + }; + let root_path = JsonPath::root(); + let Some(map) = doc.as_object() else { + ctx.error( + ERR_TOP_LEVEL_NOT_OBJECT, + "top-level is not an object".into(), + &root_path, + ); + return Parsed { + root: None, + errors: ctx.errors, + }; + }; + // `$schema` sits beside the wrapper key for editors; it is not a wrapper. + let wrappers: Vec<(&String, &Value)> = map.iter().filter(|(k, _)| *k != KEY_SCHEMA).collect(); + if wrappers.len() != 1 { + let message = if wrappers.is_empty() { + "Top-level metadata object has no type wrapper key".to_string() + } else { + let keys: Vec<&str> = wrappers.iter().map(|(k, _)| k.as_str()).collect(); + format!( + "Top-level metadata object must have exactly one wrapper key (found: {})", + keys.join(", ") + ) + }; + ctx.error(ERR_TOP_LEVEL_NOT_OBJECT, message, &root_path); + return Parsed { + root: None, + errors: ctx.errors, + }; + } + let (wrapper, body) = wrappers[0]; + let path = root_path.key(wrapper); + let root = build(&mut ctx, wrapper, body, &path, &Scope::root()); + Parsed { + root, + errors: ctx.errors, + } +} + +/// The JSON kind of a value, in the words a metadata author reads. +fn describe_json_kind(value: &Value) -> &'static str { + match value { + Value::Null => "null", + Value::Bool(_) => "a boolean", + Value::String(_) => "a string", + Value::Number(_) => "a number", + Value::Array(_) => "an array", + Value::Object(_) => "an object", + } +} + +fn missing_subtype_message(type_name: &str) -> String { + format!("type '{type_name}' has no default subType; write the full '{type_name}.'") +} + +fn abstract_subtype_message(type_name: &str) -> String { + format!( + "'{type_name}.{SUBTYPE_BASE}' may not be authored — every '{SUBTYPE_BASE}' subtype is an abstract registry anchor that concrete subtypes inherit from, with no runtime semantics of its own. Declare a concrete {type_name} subtype instead." + ) +} + +fn child_not_object_message(wrapper: &str, body: &Value) -> String { + format!( + "child wrapper '{wrapper}' must contain an object — a child is one {{ \".\": {{ …node body… }} }} pair, and this one holds {}. Give it a node body, or remove the entry.", + describe_json_kind(body) + ) +} + +/// Is `.base` an abstract anchor here: does the type register another subtype? +fn is_abstract_anchor_for(registry: &TypeRegistry, type_name: &str) -> bool { + registry + .all_sub_types_of(type_name) + .iter() + .any(|s| s != SUBTYPE_BASE) +} + +/// Expand a `::`-relative package against the declaring file's context package. +pub fn expand_package_for_path(base_pkg: &str, pkg_path: &str) -> String { + if base_pkg.trim().is_empty() || !pkg_path.starts_with(PACKAGE_SEP) { + pkg_path.to_string() + } else { + format!("{base_pkg}{pkg_path}") + } +} + +/// The package context a node is built in. +struct Scope { + ctx_pkg: String, + parent_type: String, + is_root: bool, +} + +impl Scope { + fn root() -> Self { + Self { + ctx_pkg: String::new(), + parent_type: String::new(), + is_root: true, + } + } +} + +fn split_wrapper(wrapper: &str) -> (&str, &str) { + match wrapper.split_once(FUSED_KEY_SEP) { + Some((t, s)) => (t, s), + None => (wrapper, ""), + } +} + +fn build( + ctx: &mut Ctx<'_>, + wrapper: &str, + body: &Value, + path: &JsonPath, + scope: &Scope, +) -> Option { + let (type_name, authored_sub) = split_wrapper(wrapper); + let registry = ctx.registry; + let sub_type = if authored_sub.is_empty() { + registry + .default_sub_type_of(type_name) + .unwrap_or("") + .to_string() + } else { + authored_sub.to_string() + }; + if sub_type.is_empty() && registry.has_type(type_name) { + ctx.error( + ERR_MISSING_SUBTYPE, + missing_subtype_message(type_name), + path, + ); + return None; + } + if sub_type == SUBTYPE_BASE && is_abstract_anchor_for(registry, type_name) { + ctx.error( + ERR_ABSTRACT_SUBTYPE_AUTHORED, + abstract_subtype_message(type_name), + path, + ); + return None; + } + if !registry.has_type(type_name) { + ctx.error( + ERR_UNKNOWN_TYPE, + format!("unknown type '{type_name}'"), + path, + ); + return None; + } + let Some(def) = registry.find(type_name, &sub_type) else { + ctx.error( + ERR_UNKNOWN_SUBTYPE, + format!("unknown subType '{type_name}.{sub_type}'"), + path, + ); + return None; + }; + let Some(body) = body.as_object() else { + if scope.is_root { + ctx.error( + ERR_TOP_LEVEL_NOT_OBJECT, + format!( + "top-level wrapper '{wrapper}' must contain an object, and holds {}", + describe_json_kind(body) + ), + path, + ); + } else { + ctx.error( + ERR_CHILD_NOT_OBJECT, + child_not_object_message(wrapper, body), + path, + ); + } + return None; + }; + + let mut name = match body.get(KEY_NAME) { + Some(Value::String(s)) => s.clone(), + Some(Value::Null) | None => String::new(), + Some(other) => js_display(other), + }; + if name.is_empty() + && def.max_occurs == Some(1) + && let Some(default_name) = &def.default_name + { + name = default_name.clone(); + } + let mut node = Node::new(type_name, &sub_type, &name); + node.source = ctx.here(path); + + let pkg = match body.get(KEY_PACKAGE) { + Some(Value::String(p)) => Some(expand_package_for_path(&scope.ctx_pkg, p)), + None => None, + Some(_) => { + ctx.error( + ERR_BAD_ATTR_VALUE, + format!("\"{KEY_PACKAGE}\" must be a string at {}", path.as_str()), + path, + ); + None + } + }; + let pkg = pkg.filter(|p| !p.is_empty()); + node.file_default_package = Some(pkg.clone().unwrap_or_else(|| scope.ctx_pkg.clone())); + if let Some(p) = &pkg { + node.package = Some(p.clone()); + } else if type_name == TYPE_FIELD + && scope.parent_type != TYPE_OBJECT + && !scope.ctx_pkg.is_empty() + { + // A field outside any object (an abstract field at the root, say) takes + // the context package, as every port does. + node.package = Some(scope.ctx_pkg.clone()); + } + // The structural keys take exact JSON types, as in every port: a string + // `extends` and `package`, a boolean `abstract` and `isArray`, and only a + // literal `true` makes an overlay. + match body.get(KEY_EXTENDS) { + None => {} + Some(Value::String(ext)) => { + if !ext.is_empty() { + node.super_ref = Some(ext.clone()); + } + } + Some(_) => ctx.error( + ERR_UNRESOLVED_SUPER, + format!("\"{KEY_EXTENDS}\" must be a string at {}", path.as_str()), + path, + ), + } + node.is_abstract = structural_bool(ctx, body, KEY_ABSTRACT, path); + node.is_array = structural_bool(ctx, body, KEY_IS_ARRAY, path); + node.is_overlay = body.get(KEY_OVERLAY) == Some(&Value::Bool(true)); + let is_overlay = node.is_overlay; + let own_pkg = node.package.clone(); + let id = ctx.tree.add(node); + + for (key, value) in body { + let Some(attr_name) = key.strip_prefix(ATTR_PREFIX) else { + continue; + }; + if RESERVED_STRUCTURAL_KEYS.contains(&attr_name) { + ctx.error( + ERR_RESERVED_ATTR, + format!( + "node '{wrapper}' uses reserved structural key '{attr_name}' with @-prefix; bare '{attr_name}' is the canonical form" + ), + path, + ); + continue; + } + let schema = def + .attr(attr_name) + .or_else(|| registry.common_attr(attr_name)); + let attr_sub = match schema { + Some(s) if s.is_array == Some(true) => ATTR_SUBTYPE_STRINGARRAY.to_string(), + Some(s) => s + .value_type + .clone() + .unwrap_or_else(|| SUBTYPE_BASE.to_string()), + None if value.is_object() => ATTR_SUBTYPE_PROPERTIES.to_string(), + None => SUBTYPE_BASE.to_string(), + }; + let source = ctx.here(&path.key(key)); + let attr = make_attr(&attr_sub, value, source); + ctx.tree.set_attr(id, attr_name, attr); + } + + let child_ctx_pkg = if is_overlay && !scope.is_root { + scope.ctx_pkg.clone() + } else { + own_pkg.unwrap_or_else(|| scope.ctx_pkg.clone()) + }; + let entries = match body.get(KEY_CHILDREN) { + None => &[][..], + Some(Value::Array(entries)) => entries.as_slice(), + Some(_) => { + ctx.error( + ERR_TOP_LEVEL_NOT_OBJECT, + format!("\"{KEY_CHILDREN}\" must be an array at {}", path.as_str()), + path, + ); + &[][..] + } + }; + { + let children_path = path.key(KEY_CHILDREN); + for (i, entry) in entries.iter().enumerate() { + let entry_path = children_path.index(i); + let Some(entry) = entry.as_object() else { + ctx.error( + ERR_TOP_LEVEL_NOT_OBJECT, + format!("Child at {} must be an object", entry_path.as_str()), + &entry_path, + ); + continue; + }; + if entry.len() != 1 { + let message = if entry.is_empty() { + format!("Child at {} has no type wrapper key", entry_path.as_str()) + } else { + let keys: Vec<&str> = entry.keys().map(String::as_str).collect(); + format!( + "Child at {} has multiple keys ({}) — each child must have exactly one wrapper key", + entry_path.as_str(), + keys.join(", ") + ) + }; + ctx.error(ERR_TOP_LEVEL_NOT_OBJECT, message, &entry_path); + continue; + } + let (cw, cbody) = entry.iter().next().expect("one entry"); + let cpath = entry_path.key(cw); + let (ctype, csub) = split_wrapper(cw); + if ctype == TYPE_ATTR { + parse_attr_child(ctx, id, cw, csub, cbody, &cpath); + } else { + let child_scope = Scope { + ctx_pkg: child_ctx_pkg.clone(), + parent_type: type_name.to_string(), + is_root: false, + }; + if let Some(child) = build(ctx, cw, cbody, &cpath, &child_scope) { + add_or_merge_child(ctx.tree, id, child); + } + } + } + } + Some(id) +} + +fn parse_attr_child( + ctx: &mut Ctx<'_>, + parent: NodeId, + wrapper: &str, + sub: &str, + body: &Value, + path: &JsonPath, +) { + let registry = ctx.registry; + let sub_type = if sub.is_empty() { + registry + .default_sub_type_of(TYPE_ATTR) + .unwrap_or("") + .to_string() + } else { + sub.to_string() + }; + if sub_type.is_empty() { + ctx.error( + ERR_MISSING_SUBTYPE, + missing_subtype_message(TYPE_ATTR), + path, + ); + return; + } + if sub_type == SUBTYPE_BASE && is_abstract_anchor_for(registry, TYPE_ATTR) { + ctx.error( + ERR_ABSTRACT_SUBTYPE_AUTHORED, + abstract_subtype_message(TYPE_ATTR), + path, + ); + return; + } + let Some(body) = body.as_object() else { + ctx.error( + ERR_CHILD_NOT_OBJECT, + child_not_object_message(wrapper, body), + path, + ); + return; + }; + let name = match body.get(KEY_NAME) { + Some(Value::String(s)) if !s.is_empty() => s.clone(), + _ => { + ctx.error( + ERR_MISSING_REQUIRED_ATTR, + "attr child requires a non-empty 'name'".into(), + path, + ); + return; + } + }; + let raw = body.get(KEY_VALUE).cloned().unwrap_or(Value::Null); + let resolved = if registry.has(TYPE_ATTR, &sub_type) { + sub_type + } else { + SUBTYPE_BASE.to_string() + }; + let source = ctx.here(path); + let attr = make_attr(&resolved, &raw, source); + ctx.tree.set_attr(parent, &name, attr); +} + +/// A boolean structural key (`abstract`, `isArray`): absent is false, and any +/// other JSON type is `ERR_BAD_ATTR_VALUE`. +fn structural_bool( + ctx: &mut Ctx<'_>, + body: &Map, + key: &str, + path: &JsonPath, +) -> bool { + match body.get(key) { + None => false, + Some(Value::Bool(b)) => *b, + Some(_) => { + ctx.error( + ERR_BAD_ATTR_VALUE, + format!("\"{key}\" must be a boolean at {}", path.as_str()), + path, + ); + false + } + } +} + +/// Add `child` under `parent`, or fold it into a same-type, same-name sibling the +/// same document already declared (every port merges those during the parse). +/// Unnamed nodes are always distinct, and overlays stay as written for the +/// loader's deferred pass (ADR-0055). +fn add_or_merge_child(tree: &mut Tree, parent: NodeId, child: NodeId) { + let c = tree.node(child); + if c.name.is_empty() || c.is_overlay { + tree.add_child(parent, child); + return; + } + // ADR-0039: own — the merge works on the authored layer, before super resolution. + let existing = tree.own_children(parent).iter().copied().find(|&s| { + let n = tree.node(s); + !n.is_overlay && n.type_name == c.type_name && n.name == c.name + }); + let Some(existing) = existing else { + tree.add_child(parent, child); + return; + }; + // ADR-0039: own — copying the declared layer, last writer wins. + let attrs: Vec<_> = tree + .own_attrs(child) + .map(|(k, a)| (k.clone(), a.clone())) + .collect(); + for (k, a) in attrs { + tree.set_attr(existing, &k, a); + } + // ADR-0039: own — moving the declared children. + for grandchild in tree.own_children(child).to_vec() { + add_or_merge_child(tree, existing, grandchild); + } +} + +/// `String(v)` for a scalar; compact JSON for anything else. +/// Build an attribute of `sub_type` from an authored value: coerce, then desugar. +pub fn make_attr(sub_type: &str, raw: &Value, source: ErrorSource) -> Attr { + Attr { + sub_type: sub_type.to_string(), + value: desugar(sub_type, coerce(sub_type, raw)), + authored_value: None, + source, + } +} + +fn coerce(sub_type: &str, raw: &Value) -> Value { + match sub_type { + ATTR_SUBTYPE_STRING => match raw { + Value::Bool(_) | Value::Number(_) => Value::String(js_display(raw)), + _ => raw.clone(), + }, + ATTR_SUBTYPE_INT | ATTR_SUBTYPE_LONG => match raw { + Value::Number(n) if n.as_i64().is_none() && n.as_u64().is_none() => { + match n.as_f64().and_then(safe_whole_i64) { + Some(i) => Value::from(i), + None => raw.clone(), + } + } + _ => raw.clone(), + }, + ATTR_SUBTYPE_STRINGARRAY => match raw { + Value::Array(items) => Value::Array( + items + .iter() + .map(|el| Value::String(js_display(el))) + .collect(), + ), + Value::String(_) => Value::Array(vec![raw.clone()]), + _ => raw.clone(), + }, + _ => raw.clone(), + } +} + +fn desugar(sub_type: &str, value: Value) -> Value { + if sub_type != ATTR_SUBTYPE_FILTER { + return value; + } + match value { + Value::Object(map) => Value::Object(desugar_filter_object(map)), + other => other, + } +} + +const FILTER_OP_EQ: &str = "eq"; +const FILTER_OP_IN: &str = "in"; +const FILTER_OP_IS_NULL: &str = "isNull"; +const FILTER_COMPOSE_AND: &str = "and"; +const FILTER_COMPOSE_OR: &str = "or"; +const FILTER_RELATIVE_NOW: &str = "now"; + +fn desugar_filter_object(map: Map) -> Map { + let mut out = Map::new(); + for (key, raw) in map { + if key == FILTER_COMPOSE_AND || key == FILTER_COMPOSE_OR { + let v = match raw { + Value::Array(items) => Value::Array( + items + .into_iter() + .map(|sub| match sub { + Value::Object(m) => Value::Object(desugar_filter_object(m)), + other => other, + }) + .collect(), + ), + other => other, + }; + out.insert(key, v); + continue; + } + out.insert(key, desugar_filter_value(raw)); + } + out +} + +fn one(key: &str, v: Value) -> Value { + let mut m = Map::new(); + m.insert(key.to_string(), v); + Value::Object(m) +} + +fn desugar_filter_value(value: Value) -> Value { + match value { + Value::Null => one(FILTER_OP_IS_NULL, Value::Bool(true)), + Value::Array(_) => one(FILTER_OP_IN, value), + Value::Object(ref m) if m.contains_key(FILTER_RELATIVE_NOW) => one(FILTER_OP_EQ, value), + Value::Object(_) => value, + other => one(FILTER_OP_EQ, other), + } +} diff --git a/server/rust/metaobjects/src/providers.rs b/server/rust/metaobjects/src/providers.rs new file mode 100644 index 0000000000..ad8ae16016 --- /dev/null +++ b/server/rust/metaobjects/src/providers.rs @@ -0,0 +1,653 @@ +//! Providers: the units that register vocabulary into a [`TypeRegistry`]. +//! +//! The metamodel itself is data. Every port reads the same `spec/metamodel/*.json` +//! provider definitions, so the vocabulary cannot drift between languages; this +//! module embeds those files at compile time and lowers them exactly as the +//! TypeScript reference does (`provider-data.ts`, `core-types.ts`). + +use std::collections::HashSet; +use std::sync::OnceLock; + +use serde_json::Value; + +use crate::errors::{ + ERR_PROVIDER_DEPENDENCY_CYCLE, ERR_PROVIDER_DUPLICATE_ID, ERR_PROVIDER_MISSING_DEPENDENCY, + MetaError, +}; +use crate::registry::{ + AttrSchema, ChildRule, ChildSubType, ReferenceDescriptor, SUBTYPE_BASE, TypeDefinition, + TypeRegistry, WILDCARD, +}; + +pub const CORE_TYPES_ID: &str = "metaobjects-core-types"; +pub const DB_ID: &str = "metaobjects-db"; +pub const DOCUMENTATION_ID: &str = "metaobjects-documentation"; +pub const PROMPT_ID: &str = "metaobjects-prompt"; +pub const UI_ID: &str = "metaobjects-ui"; +pub const UI_WEB_ID: &str = "metaobjects-ui-web"; + +/// A provider: an id, the providers it builds on, and what it registers. +#[derive(Clone)] +pub struct Provider { + pub id: String, + pub dependencies: Vec, + pub description: String, + pub register: fn(&mut TypeRegistry) -> Result<(), MetaError>, +} + +impl std::fmt::Debug for Provider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Provider") + .field("id", &self.id) + .field("dependencies", &self.dependencies) + .finish() + } +} + +impl Provider { + pub fn new( + id: &str, + dependencies: &[&str], + description: &str, + register: fn(&mut TypeRegistry) -> Result<(), MetaError>, + ) -> Self { + Self { + id: id.to_string(), + dependencies: dependencies.iter().map(|d| d.to_string()).collect(), + description: description.to_string(), + register, + } + } +} + +// --- the embedded metamodel --------------------------------------------------- + +macro_rules! spec { + ($name:literal) => { + ( + $name, + include_str!(concat!("../../../../spec/metamodel/", $name, ".json")), + ) + }; +} + +/// The core families, in the order the core provider registers them. +const CORE_FAMILIES: &[(&str, &str)] = &[ + spec!("object"), + spec!("field"), + spec!("attr"), + spec!("validator"), + spec!("view"), + spec!("layout"), + spec!("source"), + spec!("origin"), + spec!("template"), + spec!("identity"), + spec!("relationship"), + spec!("index"), + spec!("requirement"), + spec!("reporting"), +]; + +const DB_SPEC: (&str, &str) = spec!("db"); +const DOCUMENTATION_SPEC: (&str, &str) = spec!("documentation"); +const PROMPT_SPEC: (&str, &str) = spec!("prompt"); +const UI_SPEC: (&str, &str) = spec!("ui"); +const UI_WEB_SPEC: (&str, &str) = spec!("ui-web"); + +/// One child entry of a provider definition: an attr, or a structural child rule. +#[derive(Debug, Clone)] +struct ChildDef { + type_name: String, + sub_type: Option, + name: String, + min: i64, + max: Option, + named: Option, + description: Option, + rules: Option, + example: Option, + when_to_use: Option, + default: Option, + allowed_values: Option>, + is_array: Option, + ports: Option>, + implemented_in: Option>, +} + +#[derive(Debug, Clone)] +struct TypeDef { + type_name: String, + sub_type: String, + description: String, + data_type: Option, + rules: Option, + example: Option, + when_to_use: Option, + implemented_in: Option>, + children: Vec, + parents: Option>, + extends_base: bool, + max_occurs: Option, + default_name: Option, +} + +#[derive(Debug, Clone)] +struct ExtendDef { + type_name: String, + sub_type: ChildSubType, + children: Vec, +} + +#[derive(Debug, Clone)] +struct ProviderDefinition { + provider: String, + types: Vec, + extends: Vec, +} + +fn s(v: &Value, key: &str) -> Option { + v.get(key).and_then(Value::as_str).map(str::to_string) +} + +fn strings(v: &Value, key: &str) -> Option> { + v.get(key).and_then(Value::as_array).map(|a| { + a.iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect() + }) +} + +fn sub_type_sel(v: Option<&Value>) -> Option { + match v? { + Value::String(s) => Some(ChildSubType::One(s.clone())), + Value::Array(a) => Some(ChildSubType::Many( + a.iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect(), + )), + _ => None, + } +} + +fn parse_child(v: &Value) -> ChildDef { + ChildDef { + type_name: s(v, "type").unwrap_or_default(), + sub_type: sub_type_sel(v.get("subType")), + name: s(v, "name").unwrap_or_default(), + min: v.get("min").and_then(Value::as_i64).unwrap_or(0), + max: v.get("max").and_then(Value::as_i64), + named: v.get("named").and_then(Value::as_bool), + description: s(v, "description"), + rules: s(v, "rules"), + example: s(v, "example"), + when_to_use: s(v, "whenToUse"), + default: v.get("default").cloned(), + allowed_values: v.get("allowedValues").and_then(Value::as_array).cloned(), + is_array: v.get("isArray").and_then(Value::as_bool), + ports: strings(v, "ports"), + implemented_in: strings(v, "implementedIn"), + } +} + +fn children_of(v: &Value) -> Vec { + v.get("children") + .and_then(Value::as_array) + .map(|a| a.iter().map(parse_child).collect()) + .unwrap_or_default() +} + +fn parse_definition(file: &str, raw: &str) -> ProviderDefinition { + let doc: Value = serde_json::from_str(raw) + .unwrap_or_else(|e| panic!("spec/metamodel/{file}.json is not valid JSON: {e}")); + let types = doc + .get("types") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .map(|t| TypeDef { + type_name: s(t, "type").unwrap_or_default(), + sub_type: s(t, "subType").unwrap_or_default(), + description: s(t, "description").unwrap_or_default(), + data_type: s(t, "dataType"), + rules: s(t, "rules"), + example: s(t, "example"), + when_to_use: s(t, "whenToUse"), + implemented_in: strings(t, "implementedIn"), + children: children_of(t), + parents: strings(t, "parents"), + extends_base: t.get("extendsBase").and_then(Value::as_bool) == Some(true), + max_occurs: t.get("maxOccurs").and_then(Value::as_i64), + default_name: s(t, "defaultName"), + }) + .collect() + }) + .unwrap_or_default(); + let extends = doc + .get("extends") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .map(|e| ExtendDef { + type_name: s(e, "type").unwrap_or_default(), + sub_type: sub_type_sel(e.get("subType")) + .unwrap_or(ChildSubType::One(WILDCARD.to_string())), + children: children_of(e), + }) + .collect() + }) + .unwrap_or_default(); + ProviderDefinition { + provider: s(&doc, "provider").unwrap_or_default(), + types, + extends, + } +} + +/// The parsed definitions, parsed once per process. +struct Definitions { + core: Vec, + db: ProviderDefinition, + documentation: ProviderDefinition, + prompt: ProviderDefinition, + ui: ProviderDefinition, + ui_web: ProviderDefinition, +} + +fn definitions() -> &'static Definitions { + static DEFS: OnceLock = OnceLock::new(); + DEFS.get_or_init(|| { + let p = |(name, raw): (&str, &str)| parse_definition(name, raw); + Definitions { + core: CORE_FAMILIES.iter().map(|f| p(*f)).collect(), + db: p(DB_SPEC), + documentation: p(DOCUMENTATION_SPEC), + prompt: p(PROMPT_SPEC), + ui: p(UI_SPEC), + ui_web: p(UI_WEB_SPEC), + } + }) +} + +// --- lowering ------------------------------------------------------------------- + +const ATTR_CHILD_TYPE: &str = "attr"; + +fn is_universal(t: &TypeDef) -> bool { + t.type_name == WILDCARD && t.sub_type == WILDCARD +} + +fn validate_cardinality(provider: &str, key: &str, child: &ChildDef) -> Result<(), MetaError> { + if child.min < 0 { + return Err(MetaError::unknown(format!( + "defineProviderFromData({provider}): child \"{}\" on \"{key}\" has min {} < 0.", + child.name, child.min + ))); + } + if let Some(max) = child.max + && max < child.min + { + return Err(MetaError::unknown(format!( + "defineProviderFromData({provider}): child \"{}\" on \"{key}\" has max {max} < min {}.", + child.name, child.min + ))); + } + if child.type_name == ATTR_CHILD_TYPE && child.max != Some(1) && child.is_array != Some(true) { + return Err(MetaError::unknown(format!( + "defineProviderFromData({provider}): attr \"{}\" on \"{key}\" is single-valued (max must be 1; a list-valued attr sets isArray: true).", + child.name + ))); + } + Ok(()) +} + +fn to_attr_schema(provider: &str, key: &str, child: &ChildDef) -> Result { + let value_type = match &child.sub_type { + None => None, + Some(ChildSubType::One(s)) => Some(s.clone()), + Some(ChildSubType::Many(_)) => { + return Err(MetaError::unknown(format!( + "defineProviderFromData({provider}): attr \"{}\" on \"{key}\" declares a list subType — an attr's value-type is a single subtype.", + child.name + ))); + } + }; + Ok(AttrSchema { + name: child.name.clone(), + value_type, + is_array: child.is_array, + required: child.min >= 1, + default: child.default.clone(), + allowed_values: child.allowed_values.clone(), + ports: child.ports.clone(), + implemented_in: child.implemented_in.clone(), + description: child.description.clone().unwrap_or_default(), + rules: child.rules.clone(), + example: child.example.clone(), + when_to_use: child.when_to_use.clone(), + }) +} + +fn to_child_rule(child: &ChildDef) -> ChildRule { + ChildRule { + child_type: child.type_name.clone(), + child_sub_type: child + .sub_type + .clone() + .unwrap_or(ChildSubType::One(WILDCARD.to_string())), + child_name: child.name.clone(), + min: Some(child.min), + max: Some(child.max), + named: child.named, + } +} + +fn child_rule_id(rule: &ChildRule) -> String { + let sub = match &rule.child_sub_type { + ChildSubType::One(s) => s.clone(), + ChildSubType::Many(list) => { + let mut l = list.clone(); + l.sort(); + l.join("|") + } + }; + let max = match rule.max { + None => String::new(), + Some(None) => "null".to_string(), + Some(Some(m)) => m.to_string(), + }; + format!( + "{} {} {} {} {} {}", + rule.child_type, + sub, + rule.child_name, + rule.min.map(|m| m.to_string()).unwrap_or_default(), + max, + rule.named.map(|n| n.to_string()).unwrap_or_default() + ) +} + +/// Lower a definition's real types (not the universal `*.*` entry) to registry +/// definitions, folding `.base` into subtypes that set `extendsBase`. +fn define_from_data(data: &ProviderDefinition) -> Result, MetaError> { + let real: Vec<&TypeDef> = data.types.iter().filter(|t| !is_universal(t)).collect(); + let mut lowered: Vec<(String, Vec, Vec)> = Vec::new(); + for t in &real { + let key = format!("{}.{}", t.type_name, t.sub_type); + let mut attrs = Vec::new(); + let mut rules = Vec::new(); + for child in &t.children { + validate_cardinality(&data.provider, &key, child)?; + if child.type_name == ATTR_CHILD_TYPE { + attrs.push(to_attr_schema(&data.provider, &key, child)?); + } else { + rules.push(to_child_rule(child)); + } + } + lowered.push((key, attrs, rules)); + } + let mut out = Vec::new(); + for (t, (_, own_attrs, own_rules)) in real.iter().zip(lowered.iter()) { + let mut attributes = own_attrs.clone(); + let mut child_rules = own_rules.clone(); + if t.extends_base && t.sub_type != SUBTYPE_BASE { + let base_key = format!("{}.{SUBTYPE_BASE}", t.type_name); + if let Some((_, base_attrs, base_rules)) = + lowered.iter().find(|(k, _, _)| *k == base_key) + { + let mut have: HashSet = attributes.iter().map(|a| a.name.clone()).collect(); + for a in base_attrs { + if have.insert(a.name.clone()) { + attributes.push(a.clone()); + } + } + let mut have_rule: HashSet = + child_rules.iter().map(child_rule_id).collect(); + for r in base_rules { + if have_rule.insert(child_rule_id(r)) { + child_rules.push(r.clone()); + } + } + } + } + let mut def = TypeDefinition::new(&t.type_name, &t.sub_type, &t.description); + def.attributes = attributes; + def.child_rules = child_rules; + def.data_type = t.data_type.clone(); + def.parents = t.parents.clone(); + def.rules = t.rules.clone(); + def.example = t.example.clone(); + def.when_to_use = t.when_to_use.clone(); + def.implemented_in = t.implemented_in.clone(); + def.max_occurs = t.max_occurs; + def.default_name = t.default_name.clone(); + out.push(def); + } + Ok(out) +} + +fn apply_definition( + registry: &mut TypeRegistry, + data: &ProviderDefinition, +) -> Result<(), MetaError> { + for def in define_from_data(data)? { + registry.register(def)?; + } + if let Some(universal) = data.types.iter().find(|t| is_universal(t)) { + let key = format!("{}.{}", universal.type_name, universal.sub_type); + let mut common = Vec::new(); + for child in &universal.children { + if child.type_name != ATTR_CHILD_TYPE { + return Err(MetaError::unknown(format!( + "applyProviderDefinition({}): the universal \"{key}\" entry may only carry attr children (common attrs); found a structural child \"{}\".", + data.provider, child.type_name + ))); + } + validate_cardinality(&data.provider, &key, child)?; + common.push(to_attr_schema(&data.provider, &key, child)?); + } + if !common.is_empty() { + registry.register_common_attrs(common)?; + } + } + for ext in &data.extends { + let mut attributes = Vec::new(); + for child in &ext.children { + if child.type_name != ATTR_CHILD_TYPE { + return Err(MetaError::unknown(format!( + "applyProviderDefinition({}): extends \"{}\" may only carry attr children; found a structural child \"{}\".", + data.provider, ext.type_name, child.type_name + ))); + } + validate_cardinality(&data.provider, &ext.type_name, child)?; + attributes.push(to_attr_schema(&data.provider, &ext.type_name, child)?); + } + let sub_types = match &ext.sub_type { + ChildSubType::One(s) if s == WILDCARD => registry.all_sub_types_of(&ext.type_name), + ChildSubType::One(s) => vec![s.clone()], + ChildSubType::Many(list) => list.clone(), + }; + for sub in sub_types { + registry.extend(&ext.type_name, &sub, attributes.clone(), Vec::new())?; + } + } + Ok(()) +} + +// --- the built-in providers ------------------------------------------------------ + +fn register_core(registry: &mut TypeRegistry) -> Result<(), MetaError> { + let mut root = TypeDefinition::new("metadata", "root", "Root metadata document"); + root.child_rules = ["object", "field", "validator", "template", "requirement"] + .iter() + .map(|t| ChildRule::wildcard(t)) + .collect(); + registry.register(root)?; + for family in &definitions().core { + for def in define_from_data(family)? { + registry.register(def)?; + } + } + let reference = |attr: &str, dotted: bool, code: &str| ReferenceDescriptor { + attr: attr.to_string(), + target_type: "object".to_string(), + dotted_field_path: dotted, + error_code: code.to_string(), + }; + for sub in registry.all_sub_types_of("relationship") { + if let Some(def) = registry.find_mut("relationship", &sub) { + def.references = vec![reference("objectRef", false, "ERR_INVALID_RELATIONSHIP")]; + } + } + if let Some(def) = registry.find_mut("identity", "reference") { + def.references = vec![reference("references", true, "ERR_INVALID_REFERENCE")]; + } + for sub in ["object", "map"] { + if let Some(def) = registry.find_mut("field", sub) { + def.references = vec![reference("objectRef", false, "ERR_UNRESOLVED_OBJECT_REF")]; + } + } + registry.set_default_sub_type("metadata", "root")?; + registry.set_default_sub_type("object", "entity")?; + Ok(()) +} + +pub fn core_types_provider() -> Provider { + Provider::new( + CORE_TYPES_ID, + &[], + "Core metaobjects metamodel types and subtypes.", + register_core, + ) +} + +pub fn db_provider() -> Provider { + Provider::new( + DB_ID, + &[CORE_TYPES_ID], + "DB-domain attributes: column names, indexes and physical column types.", + |r| apply_definition(r, &definitions().db), + ) +} + +pub fn documentation_provider() -> Provider { + Provider::new( + DOCUMENTATION_ID, + &[CORE_TYPES_ID], + "Universal documentation common attrs accepted on every metatype.", + |r| apply_definition(r, &definitions().documentation), + ) +} + +pub fn prompt_provider() -> Provider { + Provider::new( + PROMPT_ID, + &[CORE_TYPES_ID], + "Prompt, AI and serialization attributes.", + |r| apply_definition(r, &definitions().prompt), + ) +} + +pub fn ui_provider() -> Provider { + Provider::new( + UI_ID, + &[CORE_TYPES_ID], + "Filter and sort field markers for generated query surfaces.", + |r| apply_definition(r, &definitions().ui), + ) +} + +pub fn ui_web_provider() -> Provider { + Provider::new( + UI_WEB_ID, + &[CORE_TYPES_ID], + "Web presentation view attrs.", + |r| apply_definition(r, &definitions().ui_web), + ) +} + +/// The full built-in set, as the registry manifest is built from it. +pub fn core_providers() -> Vec { + vec![ + core_types_provider(), + db_provider(), + documentation_provider(), + prompt_provider(), + ui_provider(), + ui_web_provider(), + ] +} + +/// Look up a built-in provider by id (`metaobjects-template` is the retired name +/// of the prompt provider, kept because older fixtures still use it). +pub fn builtin_provider(id: &str) -> Option { + if id == "metaobjects-template" { + return Some(prompt_provider()); + } + core_providers().into_iter().find(|p| p.id == id) +} + +/// Order providers so each follows its dependencies, then run them into a new +/// registry. The registry is returned unsealed; call [`TypeRegistry::seal`]. +pub fn compose_registry(providers: &[Provider]) -> Result { + let mut ids = HashSet::new(); + for p in providers { + if !ids.insert(p.id.as_str()) { + return Err(MetaError::code( + ERR_PROVIDER_DUPLICATE_ID, + format!("composeRegistry: duplicate provider id \"{}\"", p.id), + )); + } + } + for p in providers { + for dep in &p.dependencies { + if !ids.contains(dep.as_str()) { + return Err(MetaError::code( + ERR_PROVIDER_MISSING_DEPENDENCY, + format!( + "composeRegistry: provider \"{}\" depends on \"{dep}\", which is not in the provider set", + p.id + ), + )); + } + } + } + let mut emitted: HashSet<&str> = HashSet::new(); + let mut ordered: Vec<&Provider> = Vec::new(); + while ordered.len() < providers.len() { + let next = providers.iter().find(|p| { + !emitted.contains(p.id.as_str()) + && p.dependencies.iter().all(|d| emitted.contains(d.as_str())) + }); + let Some(next) = next else { + let stuck: Vec<&str> = providers + .iter() + .filter(|p| !emitted.contains(p.id.as_str())) + .map(|p| p.id.as_str()) + .collect(); + return Err(MetaError::code( + ERR_PROVIDER_DEPENDENCY_CYCLE, + format!( + "composeRegistry: dependency cycle among providers [{}]", + stuck.join(", ") + ), + )); + }; + emitted.insert(next.id.as_str()); + ordered.push(next); + } + let mut registry = TypeRegistry::new(); + for p in ordered { + registry.run_as_provider(&p.id, |r| (p.register)(r))?; + } + Ok(registry) +} + +/// The built-in registry, sealed: what an application loads metadata with. +pub fn default_registry() -> Result { + let mut registry = compose_registry(&core_providers())?; + registry.seal(); + Ok(registry) +} diff --git a/server/rust/metaobjects/src/registry.rs b/server/rust/metaobjects/src/registry.rs new file mode 100644 index 0000000000..351d7186ca --- /dev/null +++ b/server/rust/metaobjects/src/registry.rs @@ -0,0 +1,482 @@ +//! The type registry: every `type.subType` a document may use, the attributes each +//! accepts and the children each may hold. +//! +//! Behaviour follows the TypeScript reference (`registry.ts`), including the +//! provider attribute-ownership rules of ADR-0062 and the sealing of ADR-0023. + +use indexmap::IndexMap; +use serde_json::Value; + +use crate::errors::{ + ERR_EXTEND_REQUIRED_ATTR, ERR_PROVIDER_ATTR_CONFLICT, ERR_PROVIDER_ATTR_SHADOW, + ERR_REGISTRY_SEALED, MetaError, +}; + +/// The wildcard in a child rule (`*` matches any type, subtype or name). +pub const WILDCARD: &str = "*"; +/// The abstract subtype every family's concrete subtypes build on. +pub const SUBTYPE_BASE: &str = "base"; + +/// One attribute a type accepts. +#[derive(Debug, Clone, PartialEq)] +pub struct AttrSchema { + pub name: String, + /// The attr subtype its value has (`string`, `int`, ...); `None` is untyped. + pub value_type: Option, + pub is_array: Option, + pub required: bool, + pub default: Option, + pub allowed_values: Option>, + pub ports: Option>, + pub implemented_in: Option>, + pub description: String, + pub rules: Option, + pub example: Option, + pub when_to_use: Option, +} + +impl AttrSchema { + /// An optional attr with only a name, value type and description. + pub fn simple(name: &str, value_type: Option<&str>, description: &str) -> Self { + Self { + name: name.to_string(), + value_type: value_type.map(str::to_string), + is_array: None, + required: false, + default: None, + allowed_values: None, + ports: None, + implemented_in: None, + description: description.to_string(), + rules: None, + example: None, + when_to_use: None, + } + } +} + +/// The subtype half of a child rule: one subtype (or `*`) or a list. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ChildSubType { + One(String), + Many(Vec), +} + +impl ChildSubType { + pub fn matches(&self, sub_type: &str) -> bool { + match self { + ChildSubType::One(s) => s == WILDCARD || s == sub_type, + ChildSubType::Many(list) => list.iter().any(|s| s == sub_type), + } + } +} + +/// One kind of structural child a type may hold. +#[derive(Debug, Clone, PartialEq)] +pub struct ChildRule { + pub child_type: String, + pub child_sub_type: ChildSubType, + pub child_name: String, + pub min: Option, + /// `Some(None)` is an explicit unbounded maximum (`"max": null`). + pub max: Option>, + pub named: Option, +} + +impl ChildRule { + /// A rule accepting any child of `child_type`. + pub fn wildcard(child_type: &str) -> Self { + Self { + child_type: child_type.to_string(), + child_sub_type: ChildSubType::One(WILDCARD.to_string()), + child_name: WILDCARD.to_string(), + min: None, + max: None, + named: None, + } + } + + pub fn matches(&self, child_type: &str, sub_type: &str, name: &str) -> bool { + (self.child_type == WILDCARD || self.child_type == child_type) + && self.child_sub_type.matches(sub_type) + && (self.child_name == WILDCARD || self.child_name == name) + } +} + +/// An attribute whose value names another node, and the code reported when it +/// does not resolve. Recorded now; the reference pass that reads it is later work. +#[derive(Debug, Clone, PartialEq)] +pub struct ReferenceDescriptor { + pub attr: String, + pub target_type: String, + pub dotted_field_path: bool, + pub error_code: String, +} + +/// Everything the registry knows about one `type.subType`. +#[derive(Debug, Clone, PartialEq)] +pub struct TypeDefinition { + pub type_name: String, + pub sub_type: String, + pub description: String, + pub child_rules: Vec, + pub attributes: Vec, + pub data_type: Option, + pub parents: Option>, + pub rules: Option, + pub example: Option, + pub when_to_use: Option, + pub implemented_in: Option>, + pub max_occurs: Option, + pub default_name: Option, + pub references: Vec, +} + +impl TypeDefinition { + pub fn new(type_name: &str, sub_type: &str, description: &str) -> Self { + Self { + type_name: type_name.to_string(), + sub_type: sub_type.to_string(), + description: description.to_string(), + child_rules: Vec::new(), + attributes: Vec::new(), + data_type: None, + parents: None, + rules: None, + example: None, + when_to_use: None, + implemented_in: None, + max_occurs: None, + default_name: None, + references: Vec::new(), + } + } + + pub fn key(&self) -> String { + format!("{}.{}", self.type_name, self.sub_type) + } + + pub fn attr(&self, name: &str) -> Option<&AttrSchema> { + self.attributes.iter().find(|a| a.name == name) + } +} + +/// The registry. Built by composing providers (see [`crate::providers`]). +#[derive(Debug, Default, Clone)] +pub struct TypeRegistry { + defs: IndexMap, + current_provider: Option, + attr_owners: IndexMap>, + common_attr_owners: IndexMap, + sub_types: IndexMap>, + default_sub_types: IndexMap, + common_attrs: Vec, + sealed: bool, +} + +impl TypeRegistry { + pub fn new() -> Self { + Self::default() + } + + /// Refuse every later registration (ADR-0023). + pub fn seal(&mut self) { + self.sealed = true; + } + + pub fn is_sealed(&self) -> bool { + self.sealed + } + + /// Run `f` with `provider_id` recorded as the owner of what it registers. + pub fn run_as_provider(&mut self, provider_id: &str, f: impl FnOnce(&mut Self) -> T) -> T { + let previous = self.current_provider.replace(provider_id.to_string()); + let out = f(self); + self.current_provider = previous; + out + } + + pub fn attr_owner(&self, type_name: &str, sub_type: &str, name: &str) -> Option<&str> { + self.attr_owners + .get(&format!("{type_name}.{sub_type}")) + .and_then(|m| m.get(name)) + .map(String::as_str) + } + + pub fn common_attr_owner(&self, name: &str) -> Option<&str> { + self.common_attr_owners.get(name).map(String::as_str) + } + + fn stamp_attr_owner(&mut self, type_name: &str, sub_type: &str, name: &str) { + let Some(provider) = self.current_provider.clone() else { + return; + }; + self.attr_owners + .entry(format!("{type_name}.{sub_type}")) + .or_default() + .insert(name.to_string(), provider); + } + + fn check_attr_ownership( + &self, + type_name: &str, + sub_type: &str, + name: &str, + ) -> Result<(), MetaError> { + let Some(claimant) = self.current_provider.as_deref() else { + return Ok(()); + }; + if let Some(owner) = self.common_attr_owners.get(name) + && owner != claimant + { + return Err(MetaError::code( + ERR_PROVIDER_ATTR_CONFLICT, + format!( + "Provider \"{claimant}\" declares attribute \"{name}\" on \"{type_name}.{sub_type}\", but provider \"{owner}\" already registers it as a common attribute, which every node type accepts; provider \"{claimant}\" cannot declare it again (ADR-0062)" + ), + )); + } + let mut related: Vec<&str> = vec![sub_type]; + if sub_type == SUBTYPE_BASE { + for sub in self.sub_types.get(type_name).into_iter().flatten() { + if sub != SUBTYPE_BASE { + related.push(sub); + } + } + } else if self + .defs + .contains_key(&format!("{type_name}.{SUBTYPE_BASE}")) + { + related.push(SUBTYPE_BASE); + } + for sub in related { + let Some(owner) = self.attr_owner(type_name, sub, name) else { + continue; + }; + if owner == claimant { + continue; + } + if sub == sub_type { + return Err(MetaError::code( + ERR_PROVIDER_ATTR_CONFLICT, + format!( + "TypeRegistry.extend: attribute \"{name}\" is already declared on \"{type_name}.{sub_type}\" by provider \"{owner}\"; provider \"{claimant}\" cannot declare it again (ADR-0062)" + ), + )); + } + return Err(MetaError::code( + ERR_PROVIDER_ATTR_SHADOW, + format!( + "Provider \"{claimant}\" declares attribute \"{name}\" on \"{type_name}.{sub_type}\", but provider \"{owner}\" already declares it on the related slot \"{type_name}.{sub}\". Two providers may not claim one attribute name on a type and the type it inherits from; give the second provider its own idiomatic name (ADR-0062)." + ), + )); + } + Ok(()) + } + + fn check_not_sealed(&self, operation: &str) -> Result<(), MetaError> { + if self.sealed { + return Err(MetaError::code( + ERR_REGISTRY_SEALED, + format!( + "TypeRegistry is sealed (ADR-0023): {operation} is not permitted after metamodel bootstrap. Made-up metamodel attributes/types are structurally disallowed — a new metamodel attribute requires a registered provider + human agreement. Downstream apps that need extra vocabulary must compose their own (unsealed) registry." + ), + )); + } + Ok(()) + } + + fn check_value_type(attr: &AttrSchema, context: &str) -> Result<(), MetaError> { + if attr.value_type.as_deref() == Some(SUBTYPE_BASE) { + return Err(MetaError::unknown(format!( + "{context}: attr \"{}\" declares valueType \"{SUBTYPE_BASE}\", which is not valid for attrs. Use no valueType (omit the field) for a polymorphic/untyped attr.", + attr.name + ))); + } + Ok(()) + } + + /// Register a new `type.subType`. A duplicate is an error. + pub fn register(&mut self, def: TypeDefinition) -> Result<(), MetaError> { + let key = def.key(); + self.check_not_sealed(&format!("register(\"{key}\")"))?; + if self.defs.contains_key(&key) { + return Err(MetaError::unknown(format!( + "TypeRegistry: duplicate registration for \"{key}\" (type=\"{}\", subType=\"{}\")", + def.type_name, def.sub_type + ))); + } + for attr in &def.attributes { + Self::check_value_type(attr, &format!("TypeRegistry.register on \"{key}\""))?; + } + for attr in &def.attributes { + self.check_attr_ownership(&def.type_name, &def.sub_type, &attr.name)?; + } + let (type_name, sub_type) = (def.type_name.clone(), def.sub_type.clone()); + let names: Vec = def.attributes.iter().map(|a| a.name.clone()).collect(); + self.defs.insert(key, def); + self.sub_types + .entry(type_name.clone()) + .or_default() + .push(sub_type.clone()); + for name in names { + self.stamp_attr_owner(&type_name, &sub_type, &name); + } + Ok(()) + } + + pub fn find(&self, type_name: &str, sub_type: &str) -> Option<&TypeDefinition> { + self.defs.get(&format!("{type_name}.{sub_type}")) + } + + pub fn find_mut(&mut self, type_name: &str, sub_type: &str) -> Option<&mut TypeDefinition> { + self.defs.get_mut(&format!("{type_name}.{sub_type}")) + } + + pub fn has(&self, type_name: &str, sub_type: &str) -> bool { + self.find(type_name, sub_type).is_some() + } + + /// Every definition, in registration order. + pub fn all(&self) -> impl Iterator { + self.defs.values() + } + + /// The subtypes registered for `type_name`, in registration order. + pub fn all_sub_types_of(&self, type_name: &str) -> Vec { + self.sub_types.get(type_name).cloned().unwrap_or_default() + } + + pub fn has_type(&self, type_name: &str) -> bool { + self.sub_types.contains_key(type_name) + } + + pub fn set_default_sub_type( + &mut self, + type_name: &str, + sub_type: &str, + ) -> Result<(), MetaError> { + self.check_not_sealed(&format!("setDefaultSubType(\"{type_name}\")"))?; + self.default_sub_types + .insert(type_name.to_string(), sub_type.to_string()); + Ok(()) + } + + pub fn default_sub_type_of(&self, type_name: &str) -> Option<&str> { + self.default_sub_types.get(type_name).map(String::as_str) + } + + /// Attributes every node type accepts (the documentation provider's set). + pub fn common_attrs(&self) -> &[AttrSchema] { + &self.common_attrs + } + + pub fn common_attr(&self, name: &str) -> Option<&AttrSchema> { + self.common_attrs.iter().find(|a| a.name == name) + } + + pub fn register_common_attrs(&mut self, attrs: Vec) -> Result<(), MetaError> { + self.check_not_sealed("registerCommonAttrs")?; + if let Some(claimant) = self.current_provider.as_deref() { + for attr in &attrs { + if let Some(owner) = self.common_attr_owners.get(&attr.name) + && owner != claimant + { + return Err(MetaError::code( + ERR_PROVIDER_ATTR_CONFLICT, + format!( + "Provider \"{claimant}\" registers common attribute \"{}\", but provider \"{owner}\" already registers it as a common attribute; provider \"{claimant}\" cannot declare it again (ADR-0062)", + attr.name + ), + )); + } + for (slot, owners) in &self.attr_owners { + if let Some(slot_owner) = owners.get(&attr.name) + && slot_owner != claimant + { + return Err(MetaError::code( + ERR_PROVIDER_ATTR_CONFLICT, + format!( + "Provider \"{claimant}\" registers common attribute \"{}\", which every node type accepts, but provider \"{slot_owner}\" already declares it on \"{slot}\"; provider \"{claimant}\" cannot declare it again (ADR-0062)", + attr.name + ), + )); + } + } + } + } + for attr in attrs { + Self::check_value_type(&attr, "TypeRegistry.registerCommonAttrs")?; + if attr.required { + return Err(MetaError::code( + ERR_EXTEND_REQUIRED_ATTR, + format!( + "TypeRegistry.registerCommonAttrs: attribute \"{}\" is REQUIRED. A common attr is projected onto every registered type, so a required one would vanish from all of them whenever its provider is composed out. Common attrs must be optional (ADR-0050).", + attr.name + ), + )); + } + if self.common_attrs.iter().any(|a| a.name == attr.name) { + continue; + } + if let Some(claimant) = self.current_provider.clone() { + self.common_attr_owners.insert(attr.name.clone(), claimant); + } + self.common_attrs.push(attr); + } + Ok(()) + } + + /// Add optional attributes (and child rules) to a type another provider owns. + pub fn extend( + &mut self, + type_name: &str, + sub_type: &str, + attributes: Vec, + child_rules: Vec, + ) -> Result<(), MetaError> { + self.check_not_sealed(&format!("extend(\"{type_name}.{sub_type}\")"))?; + if !self.has(type_name, sub_type) { + return Err(MetaError::unknown(format!( + "TypeRegistry.extend: no registered type \"{type_name}.{sub_type}\" to extend" + ))); + } + for attr in attributes { + Self::check_value_type( + &attr, + &format!("TypeRegistry.extend on \"{type_name}.{sub_type}\""), + )?; + let exists = self + .find(type_name, sub_type) + .is_some_and(|d| d.attr(&attr.name).is_some()); + self.check_attr_ownership(type_name, sub_type, &attr.name)?; + if exists { + return Err(MetaError::code( + ERR_PROVIDER_ATTR_CONFLICT, + format!( + "TypeRegistry.extend: attribute \"{}\" is already declared on \"{type_name}.{sub_type}\"", + attr.name + ), + )); + } + if attr.required { + return Err(MetaError::code( + ERR_EXTEND_REQUIRED_ATTR, + format!( + "TypeRegistry.extend: attribute \"{}\" being added to \"{type_name}.{sub_type}\" is REQUIRED. A provider may only project OPTIONAL attributes onto a type it does not own — a required attr registered this way disappears, silently, whenever that provider is composed out. Declare it with the type instead (ADR-0050).", + attr.name + ), + )); + } + let name = attr.name.clone(); + if let Some(def) = self.find_mut(type_name, sub_type) { + def.attributes.push(attr); + } + self.stamp_attr_owner(type_name, sub_type, &name); + } + if let Some(def) = self.find_mut(type_name, sub_type) { + def.child_rules.extend(child_rules); + } + Ok(()) + } +} diff --git a/server/rust/metaobjects/src/serializer.rs b/server/rust/metaobjects/src/serializer.rs new file mode 100644 index 0000000000..5bd3fc990c --- /dev/null +++ b/server/rust/metaobjects/src/serializer.rs @@ -0,0 +1,237 @@ +//! The canonical serializer: the fused-key JSON form every port writes, byte for +//! byte (`spec/conformance-tests.md`). +//! +//! Two modes. **Own** writes the layer each node declares (its `extends` stays a +//! reference), so re-loading the output rebuilds the same tree. **Effective** +//! inlines what each node inherits through `extends`. + +use std::borrow::Cow; +use std::collections::BTreeMap; + +use serde_json::{Map, Value}; + +use crate::json::{safe_whole_i64, to_js_pretty}; +use crate::node::{NodeId, Tree}; +use crate::parser::{ + ATTR_PREFIX, KEY_ABSTRACT, KEY_CHILDREN, KEY_EXTENDS, KEY_IS_ARRAY, KEY_NAME, KEY_PACKAGE, + SUBTYPE_ROOT, TYPE_METADATA, +}; + +const TYPE_SOURCE: &str = "source"; +const SOURCE_SUBTYPE_RDB: &str = "rdb"; +const SOURCE_ATTR_KIND: &str = "kind"; +const SOURCE_ATTR_TABLE: &str = "table"; +const DEFAULT_SOURCE_KIND: &str = "table"; + +/// `@kind` → the attribute that holds the physical name for that kind (FR-016). +fn physical_name_attr_for_kind(kind: &str) -> Option<&'static str> { + match kind { + "table" => Some("table"), + "view" => Some("view"), + "materializedView" => Some("materializedView"), + "storedProc" => Some("proc"), + "tableFunction" => Some("function"), + _ => None, + } +} + +/// Canonical (own-mode) serialization of the subtree at `id`. +pub fn canonical_serialize(tree: &Tree, id: NodeId) -> String { + serialize(tree, id, false) +} + +/// Canonical serialization of the effective tree: inherited members inlined. +pub fn canonical_serialize_effective(tree: &Tree, id: NodeId) -> String { + serialize(tree, id, true) +} + +/// The canonical form of the subtree at `id`, as a JSON value. +pub fn to_canonical_value(tree: &Tree, id: NodeId, effective: bool) -> Value { + wrap(tree, id, effective, None) +} + +fn serialize(tree: &Tree, id: NodeId, effective: bool) -> String { + let mut out = to_js_pretty(&to_canonical_value(tree, id, effective)); + out.push('\n'); + out +} + +fn wrap(tree: &Tree, id: NodeId, effective: bool, pkg_slot: Option) -> Value { + let n = tree.node(id); + let mut m = Map::new(); + m.insert( + format!("{}.{}", n.type_name, n.sub_type), + Value::Object(body(tree, id, effective, pkg_slot)), + ); + Value::Object(m) +} + +/// Effective package of a top-level node: own, else its file's, else the root's. +fn top_level_package(tree: &Tree, id: NodeId, root: NodeId) -> String { + let n = tree.node(id); + if let Some(p) = &n.package { + return p.clone(); + } + if let Some(p) = &n.file_default_package { + return p.clone(); + } + tree.node(root).package.clone().unwrap_or_default() +} + +/// ADR-0059 R8, the document package rule. Returns the root's package and whether +/// each top-level node carries its own. +fn document_packages(tree: &Tree, root: NodeId) -> (Option, bool) { + let named: Vec = tree + // ADR-0039: own — the root's top-level nodes are its declared children; a root extends nothing. + .own_children(root) + .iter() + .copied() + .filter(|&c| !tree.node(c).name.is_empty()) + .collect(); + let root_pkg = tree.node(root).package.clone(); + if named.is_empty() { + return (root_pkg, false); + } + let mut pkgs: Vec = named + .iter() + .map(|&c| top_level_package(tree, c, root)) + .collect(); + pkgs.sort(); + pkgs.dedup(); + if pkgs.len() == 1 && !pkgs[0].is_empty() { + let only = pkgs.remove(0); + let self_named = root_pkg.is_none() + && named + .iter() + .all(|&c| tree.node(c).package.as_deref() == Some(only.as_str())); + return (if self_named { None } else { Some(only) }, false); + } + (None, true) +} + +fn body(tree: &Tree, id: NodeId, effective: bool, pkg_slot: Option) -> Map { + let n = tree.node(id); + let mut b = Map::new(); + if !n.name.is_empty() { + b.insert(KEY_NAME.into(), Value::String(n.name.clone())); + } + let is_doc_root = n.type_name == TYPE_METADATA && n.sub_type == SUBTYPE_ROOT; + let doc = is_doc_root.then(|| document_packages(tree, id)); + let pkg = match (&doc, pkg_slot) { + (Some((p, _)), _) => p.clone(), + (None, Some(slot)) => Some(slot), + (None, None) => n.package.clone(), + }; + if let Some(p) = pkg.filter(|p| !p.is_empty()) { + b.insert(KEY_PACKAGE.into(), Value::String(p)); + } + if let Some(s) = n.super_ref.as_deref().filter(|s| !s.is_empty()) { + b.insert(KEY_EXTENDS.into(), Value::String(s.to_string())); + } + if n.is_abstract { + b.insert(KEY_ABSTRACT.into(), Value::Bool(true)); + } + let is_array = if effective { + tree.resolved_is_array(id) || tree.attr(id, KEY_IS_ARRAY) == Some(&Value::Bool(true)) + } else { + n.is_array + }; + if is_array { + b.insert(KEY_IS_ARRAY.into(), Value::Bool(true)); + } + + // ADR-0039: own mode writes the declared layer, effective mode resolves. + let mut attrs: BTreeMap = if effective { + tree.attrs(id) + .iter() + .map(|(k, v)| (k.clone(), v.clone())) + .collect() + } else { + // ADR-0039: own — own-mode serialization writes the declared layer. + tree.own_attrs(id) + .map(|(k, a)| (k.clone(), a.value.clone())) + .collect() + }; + if n.type_name == TYPE_SOURCE && n.sub_type == SOURCE_SUBTYPE_RDB { + rewrite_physical_name(&mut attrs); + } + for (k, v) in attrs { + b.insert(format!("{ATTR_PREFIX}{k}"), normalize(v)); + } + + let children = if effective { + tree.children(id) + } else { + // ADR-0039: own — own-mode serialization writes the declared layer. + Cow::Borrowed(tree.own_children(id)) + }; + if !children.is_empty() { + let per_node = doc.as_ref().is_some_and(|(_, per)| *per); + let items = children + .iter() + .copied() + .map(|c| { + let slot = per_node.then(|| { + if tree.node(c).name.is_empty() { + String::new() + } else { + top_level_package(tree, c, id) + } + }); + wrap(tree, c, effective, slot) + }) + .collect(); + b.insert(KEY_CHILDREN.into(), Value::Array(items)); + } + b +} + +/// FR-016 / ADR-0018: on a non-table `source.rdb`, a legacy `@table` is written as +/// the attribute its kind names (`@view`, `@proc`, ...). +fn rewrite_physical_name(attrs: &mut BTreeMap) { + let kind = attrs + .get(SOURCE_ATTR_KIND) + .and_then(Value::as_str) + .filter(|k| !k.is_empty()) + .unwrap_or(DEFAULT_SOURCE_KIND) + .to_string(); + let Some(alias) = physical_name_attr_for_kind(&kind) else { + return; + }; + if alias == SOURCE_ATTR_TABLE || attrs.contains_key(alias) { + return; + } + if let Some(v) = attrs.remove(SOURCE_ATTR_TABLE) { + if v.is_null() { + attrs.insert(SOURCE_ATTR_TABLE.into(), v); + } else { + attrs.insert(alias.into(), v); + } + } +} + +/// Whole-number doubles print as integers; a map of scalars sorts its keys (the +/// `properties` shape); any other map keeps its order (a filter's clauses do). +fn normalize(v: Value) -> Value { + match v { + Value::Number(n) => { + if n.is_f64() + && let Some(i) = n.as_f64().and_then(safe_whole_i64) + { + return Value::from(i); + } + Value::Number(n) + } + Value::Array(items) => Value::Array(items.into_iter().map(normalize).collect()), + Value::Object(map) => { + let all_scalar = map.values().all(|v| !v.is_array() && !v.is_object()); + if all_scalar { + let sorted: BTreeMap = map.into_iter().collect(); + Value::Object(sorted.into_iter().map(|(k, v)| (k, normalize(v))).collect()) + } else { + Value::Object(map.into_iter().map(|(k, v)| (k, normalize(v))).collect()) + } + } + other => other, + } +} diff --git a/server/rust/metaobjects/src/source.rs b/server/rust/metaobjects/src/source.rs new file mode 100644 index 0000000000..116648d1cd --- /dev/null +++ b/server/rust/metaobjects/src/source.rs @@ -0,0 +1,108 @@ +//! Where an error happened: the file and JSON path, in the shared envelope shape. + +/// The location part of an error envelope. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub enum ErrorSource { + /// Raised by code with no document location (registry composition, say). + #[default] + Code, + /// A location in one JSON document. + Json { + files: Vec, + json_path: String, + }, + /// A reference that did not resolve: the referring node and the reference. + Resolved { + files: Vec, + json_path: String, + referrer: String, + target: String, + }, +} + +impl ErrorSource { + pub fn json(file: &str, json_path: impl Into) -> Self { + ErrorSource::Json { + files: vec![file.to_string()], + json_path: json_path.into(), + } + } + + /// The envelope's `format` value. + pub fn format(&self) -> &'static str { + match self { + ErrorSource::Code => "code", + ErrorSource::Json { .. } => "json", + ErrorSource::Resolved { .. } => "resolved", + } + } + + pub fn files(&self) -> &[String] { + match self { + ErrorSource::Code => &[], + ErrorSource::Json { files, .. } | ErrorSource::Resolved { files, .. } => files, + } + } + + pub fn json_path(&self) -> Option<&str> { + match self { + ErrorSource::Code => None, + ErrorSource::Json { json_path, .. } | ErrorSource::Resolved { json_path, .. } => { + Some(json_path) + } + } + } + + /// Rewrite every file path with `f` (the conformance runner makes them relative). + pub fn map_files(&mut self, f: impl Fn(&str) -> String) { + if let ErrorSource::Json { files, .. } | ErrorSource::Resolved { files, .. } = self { + for file in files.iter_mut() { + *file = f(file); + } + } + } +} + +/// A JSON path built the way every port writes it: `$`, then `[i]` for an index, +/// `.key` for an identifier key and `['key']` for any other key. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct JsonPath(String); + +impl Default for JsonPath { + fn default() -> Self { + JsonPath("$".to_string()) + } +} + +impl JsonPath { + pub fn root() -> Self { + Self::default() + } + + pub fn index(&self, i: usize) -> Self { + JsonPath(format!("{}[{i}]", self.0)) + } + + pub fn key(&self, key: &str) -> Self { + let mut chars = key.chars(); + let ident = chars + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_'); + if ident { + JsonPath(format!("{}.{key}", self.0)) + } else { + JsonPath(format!("{}['{}']", self.0, key.replace('\'', "\\'"))) + } + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Display for JsonPath { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json new file mode 100644 index 0000000000..635c0a9dfd --- /dev/null +++ b/server/rust/metaobjects/tests/conformance-expected-failures.json @@ -0,0 +1,261 @@ +{ + "language": "rust", + "notes": "The Rust port is in preview. This step (the loader core) parses, merges, resolves extends and serializes; it does not yet run the validation passes (the unknown-attr provenance check, ERR_UNKNOWN_ATTR, among them), emit merge warnings, resolve the reporting rule that binds a bare entity name in the package its path already fixes, or run script.json operations. Every fixture listed here fails for one of those reasons and leaves the ledger when the step that covers it lands. The ledger may only shrink. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.", + "minPassing": 256, + "fixtures": [ + "error-agg-all-non-boolean", + "error-agg-any-missing-filter", + "error-agg-collect-element-type-mismatch", + "error-agg-collect-non-array", + "error-attr-bad-allowed-value", + "error-attr-filter-bad-field", + "error-attr-filter-bad-op", + "error-attr-filter-legacy-string", + "error-attr-int-fractional", + "error-attr-missing-required", + "error-attr-wrong-type", + "error-collect-distinct", + "error-collect-member-type-mismatch", + "error-collect-member-unresolved", + "error-collect-no-object-ref", + "error-collect-no-via", + "error-collect-orderby-not-terminal", + "error-collect-ref-not-value", + "error-collect-via-to-one", + "error-column-name-collision", + "error-column-name-collision-derived-view", + "error-column-name-collision-flattened-empty-prefix", + "error-column-name-collision-flattened-member-vs-field", + "error-column-name-collision-table-with-sql-view", + "error-computed-expr-not-object", + "error-computed-op-illegal-operand", + "error-computed-type-mismatch", + "error-computed-unknown-expr-node", + "error-computed-unresolved-field", + "error-data-grid-bad-sort-field", + "error-dbcolumntype-illegal-pairing", + "error-default-non-coercible-int", + "error-derived-field-no-read-source", + "error-dimension-grain-on-date", + "error-dimension-of-jsonb-member", + "error-dimension-of-unresolved", + "error-dimension-over-object", + "error-dimension-time-not-temporal", + "error-dimension-via-base-lacks-field", + "error-dimension-via-to-many", + "error-entity-primary-source-readonly", + "error-enum-chained-extends-values-conflict", + "error-enum-coerce-default-non-member", + "error-enum-default-non-member", + "error-enum-duplicate-member", + "error-enum-empty-values", + "error-enum-extends-intvaluemap-conflict", + "error-enum-extends-values-conflict", + "error-enum-intvaluemap-duplicate-value", + "error-enum-intvaluemap-key-mismatch", + "error-enum-intvaluemap-non-int", + "error-enum-max-length-int-value-map", + "error-enum-missing-values", + "error-enum-non-identifier-member", + "error-enum-normalize-bad-mode", + "error-enum-normalize-collision", + "error-enum-value-exceeds-max-length", + "error-enum-value-exceeds-max-length-every-field", + "error-extends-origin-mismatch", + "error-field-map-objectref-unresolved", + "error-field-mutability-autoset-conflict", + "error-field-mutability-downgrade", + "error-field-mutability-downgrade-writeonce", + "error-field-mutability-readonly-assigned-primary", + "error-field-object-flattened-column-prefix-default-storage", + "error-field-object-flattened-column-prefix-without-flattened-storage", + "error-field-object-no-object-ref", + "error-field-objectref-unresolved", + "error-field-object-storage-flattened-array", + "error-field-object-storage-no-object-ref", + "error-filterable-array-field", + "error-filterable-unsupported-subtype", + "error-filter-with-sql-body", + "error-first-of-type-mismatch", + "error-first-required-field", + "error-identity-key-mismatch", + "error-identity-name-required", + "error-identity-reference-unresolved", + "error-identity-secondary-fields-and-expr", + "error-identity-sequence-start-out-of-range", + "error-identity-sequence-without-increment", + "error-index-fields-and-expr", + "error-kind1-view-unregistered-attr", + "error-m2m-through-value", + "error-measure-all-default-not-boolean", + "error-measure-any-non-boolean", + "error-measure-any-without-condition", + "error-measure-default-non-numeric", + "error-measure-default-not-integer", + "error-measure-default-on-count", + "error-measure-default-on-count-integral-float", + "error-measure-default-on-count-non-numeric", + "error-measure-derived-ambiguous-operand", + "error-measure-derived-default", + "error-measure-derived-malformed-expr", + "error-measure-derived-non-numeric-dimension", + "error-measure-derived-non-numeric-measure", + "error-measure-derived-of-derived", + "error-measure-derived-time-dimension", + "error-measure-derived-unknown-operand", + "error-measure-distinct-not-count", + "error-measure-of-foreign", + "error-measure-of-jsonb-member", + "error-measure-of-member-of-scalar", + "error-measure-of-path-too-deep", + "error-measure-of-unknown-member", + "error-measure-over-object", + "error-measure-segment-unresolved", + "error-measure-sum-non-numeric", + "error-measure-sum-without-of", + "error-measure-tuple-without-distinct", + "error-merge-conflict-attr", + "error-merge-conflict-flattened-column-prefix-empty", + "error-origin-aggregate-no-to-many", + "error-origin-aggregate-value-object", + "error-origin-bad-aggregate-fn", + "error-origin-bad-via-path", + "error-origin-computed-case-mixed-types", + "error-origin-computed-case-non-boolean-when", + "error-origin-computed-case-unknown-key", + "error-origin-computed-cycle", + "error-origin-computed-literal-fractional", + "error-origin-computed-literal-not-enum-member", + "error-origin-computed-literal-wrong-kind", + "error-origin-computed-node-mixed-keys", + "error-origin-computed-now-bad-duration", + "error-origin-correlated-operand-unknown", + "error-origin-passthrough-array-mismatch", + "error-origin-passthrough-reverse-hop", + "error-origin-passthrough-to-many", + "error-origin-passthrough-type-mismatch", + "error-origin-reverse-hop-ambiguous", + "error-origin-segment-flattened-of", + "error-origin-segment-unresolved", + "error-origin-under-sql-body", + "error-origin-via-ambiguous", + "error-parameter-ref-not-value-object", + "error-parameter-ref-on-table-kind", + "error-parameter-ref-passthrough-type-mismatch", + "error-parameter-ref-unresolved", + "error-payload-nested-object-ref-entity", + "error-port-scoped-attr-wrong-type", + "error-projection-extends-entity", + "error-projection-extends-filter-sql-body", + "error-projection-filter-aggregate", + "error-projection-filter-dangling", + "error-projection-filter-path-to-many", + "error-projection-identity-not-extended", + "error-projection-inherited-source", + "error-projection-source-writable", + "error-provided-not-boolean", + "error-ratio-boolean-operand", + "error-ratio-non-numeric-operand", + "error-ratio-operand-not-aggregate", + "error-relationship-m2m-attr-on-1n", + "error-relationship-m2m-junction-unpairable", + "error-relationship-one-refs-ambiguous", + "error-relationship-one-unresolved-objectref-sourceref", + "error-relationship-symmetric-and-sourceref", + "error-relationship-symmetric-on-hetero", + "error-relationship-through-missing-junction-refs", + "error-relationship-unresolved-objectref", + "error-relative-date-bad-duration", + "error-relative-date-bad-startof", + "error-relative-date-datagrid-host", + "error-relative-date-extra-key", + "error-relative-date-non-temporal", + "error-relative-date-non-temporal-field", + "error-relative-date-view-host-malformed", + "error-report-abstract", + "error-report-declares-field", + "error-report-derived-dimension-not-listed", + "error-report-dimension-grain", + "error-report-field-collision", + "error-report-foreign-measure", + "error-report-from-not-entity", + "error-report-measure-unresolved", + "error-report-segment-unresolved", + "error-report-source-kind-materialized-view", + "error-report-source-kind-stored-proc", + "error-report-source-kind-table-function", + "error-report-spine-dimension-off-spine", + "error-report-spine-dimension-other-path", + "error-report-spine-no-dimensions", + "error-report-spine-not-from", + "error-report-spine-to-many", + "error-report-two-unresolved-dimensions", + "error-report-value-object-unit-derived-operand", + "error-report-value-object-unit-not-grouped", + "error-report-value-object-unit-ratio-operand", + "error-report-writable-source", + "error-requirement-level-fractional", + "error-requirement-retired-has-implementors", + "error-requirement-status-abandoned", + "error-requirement-superseded-by-not-retired", + "error-requirement-verified-by-retired", + "error-root-level-field-objectref-unresolved", + "error-segment-filter-bad-field", + "error-sortable-array-field", + "error-source-multiple-primary", + "error-source-no-primary", + "error-source-rdb-multiple-physical-names", + "error-source-rdb-physical-name-empty-string", + "error-source-rdb-physical-name-kind-mismatch", + "error-source-role-reserved", + "error-sql-body-empty", + "error-sql-body-on-writable-kind", + "error-sql-body-with-unmanaged", + "error-template-payload-ref-not-value", + "error-template-payload-ref-sourced-projection", + "error-template-payload-ref-unresolved", + "error-template-prompt-missing-payload-ref", + "error-template-required-slot-missing", + "error-template-response-ref-not-value", + "error-too-many-primary", + "error-tph-discriminator-field-not-found", + "error-tph-discriminator-numeric-equivalent", + "error-tph-discriminator-numeric-trailing-newline", + "error-tph-discriminator-value-duplicate", + "error-tph-discriminator-value-missing", + "error-tph-discriminator-value-type-mismatch", + "error-unknown-attr", + "error-unknown-attr-object", + "error-unknown-attr-requirement", + "error-unknown-attr-validator", + "error-validator-at-least-one-max-unknown", + "error-validator-condition-duration-literal", + "error-validator-condition-now", + "error-validator-condition-type", + "error-validator-condition-unknown-field", + "error-validator-condition-unknown-fields", + "error-validator-exactly-one-one-field", + "error-value-origin-aggregate", + "error-value-origin-computed", + "error-value-origin-first", + "error-value-reference-enforced", + "error-value-reference-unresolved", + "error-value-with-identity-secondary", + "error-value-with-source", + "error-xpkg-ambiguous-objectref", + "error-xpkg-bare-unique-elsewhere", + "error-xpkg-through-bare", + "extends-abstract-base", + "filter-ops-matrix", + "merge-conflict-unmarked-attr-redeclaration", + "projection-identity-borrows-secondary", + "provider-custom-vocabulary-missing-provider-fails", + "reporting-cross-package-short-names", + "source-rdb-legacy-table-for-view-rewrites", + "subtype-entity-missing-primary-warning", + "warning-duplicate-declaration", + "warning-enum-normalize-ambiguous", + "warning-filterable-inherited-without-index", + "warning-filterable-no-index" + ] +} diff --git a/server/rust/metaobjects/tests/loader_edges.rs b/server/rust/metaobjects/tests/loader_edges.rs new file mode 100644 index 0000000000..2f0bd50c78 --- /dev/null +++ b/server/rust/metaobjects/tests/loader_edges.rs @@ -0,0 +1,149 @@ +//! Loader behaviour the shared metamodel corpus does not pin, checked against what +//! the TypeScript reference parser does. + +use metaobjects::loader::{Loader, metadata_files}; +use metaobjects::providers::default_registry; +use metaobjects::serializer::canonical_serialize; + +fn load(sources: &[(&str, &str)]) -> metaobjects::LoadResult { + let registry = default_registry().expect("the built-in providers compose"); + let owned: Vec<(String, String)> = sources + .iter() + .map(|(id, text)| (id.to_string(), text.to_string())) + .collect(); + Loader::new(®istry).load_sources(&owned) +} + +fn codes(result: &metaobjects::LoadResult) -> Vec<&'static str> { + result.errors.iter().map(|e| e.code).collect() +} + +#[test] +fn a_schema_key_beside_the_wrapper_is_not_a_wrapper() { + let r = load(&[( + "meta.a.json", + r#"{"$schema": "https://example.invalid/schema.json", + "metadata.root": {"package": "acme", "children": [ + {"object.entity": {"name": "A"}}]}}"#, + )]); + assert!(r.errors.is_empty(), "{:?}", r.errors); + assert!(canonical_serialize(&r.tree, r.root).contains("\"A\"")); +} + +#[test] +fn two_wrapper_keys_are_refused() { + let r = load(&[( + "meta.a.json", + r#"{"metadata.root": {}, "object.entity": {"name": "A"}}"#, + )]); + assert_eq!(codes(&r), ["ERR_TOP_LEVEL_NOT_OBJECT"]); +} + +#[test] +fn malformed_children_are_errors_not_silent_drops() { + for children in [ + r#"{"object.entity": {"name": "A"}}"#, + r#"[5]"#, + r#"[{}]"#, + r#"[{"object.entity": {"name": "A"}, "object.value": {"name": "B"}}]"#, + ] { + let doc = format!(r#"{{"metadata.root": {{"package": "acme", "children": {children}}}}}"#); + let r = load(&[("meta.a.json", &doc)]); + assert_eq!( + codes(&r), + ["ERR_TOP_LEVEL_NOT_OBJECT"], + "children: {children}" + ); + } +} + +#[test] +fn structural_keys_take_exact_json_types() { + let cases = [ + (r#""abstract": "no""#, "ERR_BAD_ATTR_VALUE"), + (r#""isArray": 1"#, "ERR_BAD_ATTR_VALUE"), + (r#""package": 7"#, "ERR_BAD_ATTR_VALUE"), + (r#""extends": 7"#, "ERR_UNRESOLVED_SUPER"), + ]; + for (key, code) in cases { + let doc = format!( + r#"{{"metadata.root": {{"package": "acme", "children": [ + {{"object.entity": {{"name": "A", {key}}}}}]}}}}"# + ); + let r = load(&[("meta.a.json", &doc)]); + assert!(codes(&r).contains(&code), "{key}: {:?}", r.errors); + } +} + +#[test] +fn only_a_literal_true_makes_an_overlay() { + // `"overlay": "false"` is a plain declaration, so it needs no merge target. + let r = load(&[( + "meta.a.json", + r#"{"metadata.root": {"package": "acme", "children": [ + {"object.entity": {"name": "A", "overlay": "false"}}]}}"#, + )]); + assert!( + !codes(&r).contains(&"ERR_OVERLAY_NO_TARGET"), + "{:?}", + r.errors + ); +} + +#[test] +fn same_named_siblings_in_one_file_merge() { + let r = load(&[( + "meta.a.json", + r#"{"metadata.root": {"package": "acme", "children": [ + {"object.entity": {"name": "A", "children": [ + {"field.string": {"name": "x", "@maxLength": 5}}, + {"field.string": {"name": "x", "@required": true}}]}}]}}"#, + )]); + assert!(r.errors.is_empty(), "{:?}", r.errors); + let out = canonical_serialize(&r.tree, r.root); + assert_eq!(out.matches("\"name\": \"x\"").count(), 1, "{out}"); + assert!(out.contains("\"@maxLength\": 5") && out.contains("\"@required\": true")); +} + +#[test] +fn unnamed_nodes_never_merge() { + let file = |attr: &str| { + format!( + r#"{{"metadata.root": {{"package": "acme", "children": [ + {{"object.entity": {{"name": "A", "children": [ + {{"field.string": {{"name": "x", "children": [ + {{"validator.length": {{"@max": {attr}}}}}]}}}}]}}}}]}}}}"# + ) + }; + let (a, b) = (file("5"), file("9")); + let r = load(&[("meta.a.json", &a), ("meta.b.json", &b)]); + assert!(r.errors.is_empty(), "{:?}", r.errors); + let out = canonical_serialize(&r.tree, r.root); + assert_eq!(out.matches("validator.length").count(), 2, "{out}"); +} + +#[test] +fn the_loader_reads_pending_directories() { + let dir = std::env::temp_dir().join(format!("mo-rust-pending-{}", std::process::id())); + let pending = dir.join("_pending"); + std::fs::create_dir_all(&pending).expect("temp dir"); + std::fs::write(pending.join("meta.p.json"), "{}").expect("write"); + let all = metadata_files(&dir, false).expect("walk"); + let skipped = metadata_files(&dir, true).expect("walk"); + std::fs::remove_dir_all(&dir).expect("clean up"); + assert_eq!((all.len(), skipped.len()), (1, 0)); +} + +#[cfg(unix)] +#[test] +fn a_symlink_cycle_is_walked_once() { + let dir = std::env::temp_dir().join(format!("mo-rust-symlink-{}", std::process::id())); + let sub = dir.join("sub"); + std::fs::create_dir_all(&sub).expect("temp dir"); + std::fs::write(sub.join("meta.a.json"), "{}").expect("write"); + // sub/loop -> .. : a cycle back to the walk's own root. + std::os::unix::fs::symlink("..", sub.join("loop")).expect("symlink"); + let found = metadata_files(&dir, false); + std::fs::remove_dir_all(&dir).expect("clean up"); + assert_eq!(found.expect("walk").len(), 1); +} diff --git a/server/rust/metaobjects/tests/metamodel_conformance.rs b/server/rust/metaobjects/tests/metamodel_conformance.rs new file mode 100644 index 0000000000..2622db9485 --- /dev/null +++ b/server/rust/metaobjects/tests/metamodel_conformance.rs @@ -0,0 +1,417 @@ +//! The shared metamodel corpus (`fixtures/conformance/`): every fixture directory is +//! loaded and checked against the expectation files it declares, as the other +//! ports' runners do. +//! +//! Fixtures this port does not pass yet are listed in +//! `conformance-expected-failures.json` beside this file. The ledger may only +//! shrink: a listed fixture that now passes fails the run until it is removed, and +//! a listed name with no fixture directory fails the run. +//! +//! While the port is in preview (ADR-0065 decision 5), an unlisted fixture that +//! fails prints a warning instead of failing the run, so a new fixture added for +//! another port never turns this lane red. A regression is still caught: the ledger +//! records `minPassing`, the number of fixtures known to pass, and the run fails +//! when fewer pass. Raise it when fixtures leave the ledger; it may only rise. + +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +use metaobjects::errors::MetaError; +use metaobjects::json::{safe_whole_i64, to_js_pretty}; +use metaobjects::loader::Loader; +use metaobjects::providers::{Provider, builtin_provider, compose_registry}; +use metaobjects::registry::{AttrSchema, ChildRule, TypeDefinition, TypeRegistry}; +use metaobjects::serializer::{canonical_serialize_effective, to_canonical_value}; +use metaobjects::source::ErrorSource; + +const DEFAULT_PROVIDERS: &[&str] = &[ + "metaobjects-core-types", + "metaobjects-db", + "metaobjects-documentation", + "metaobjects-prompt", + "metaobjects-ui", + "metaobjects-ui-web", +]; + +fn corpus() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/conformance") +} + +fn ledger_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/conformance-expected-failures.json") +} + +// ---- test-only providers, as in the other ports' adapters -------------------- + +fn noop(_: &mut TypeRegistry) -> Result<(), MetaError> { + Ok(()) +} + +fn required(name: &str, value_type: &str) -> AttrSchema { + let mut a = AttrSchema::simple(name, Some(value_type), ""); + a.required = true; + a +} + +fn register_briefing(r: &mut TypeRegistry) -> Result<(), MetaError> { + let mut def = TypeDefinition::new("template", "briefing", ""); + def.attributes = vec![ + required("payloadRef", "string"), + required("author", "string"), + required("recipient", "string"), + ]; + def.child_rules = vec![ChildRule::wildcard("attr")]; + r.register(def) +} + +fn register_custom_vocabulary(r: &mut TypeRegistry) -> Result<(), MetaError> { + let mut def = TypeDefinition::new("layout", "picker", ""); + def.attributes = vec![AttrSchema::simple("displayField", Some("string"), "")]; + def.child_rules = vec![ChildRule::wildcard("attr")]; + r.register(def)?; + let mut labels = AttrSchema::simple("valueLabels", Some("string"), ""); + labels.is_array = Some(true); + r.extend( + "field", + "string", + vec![ + AttrSchema::simple("searchable", Some("boolean"), ""), + labels, + ], + Vec::new(), + ) +} + +fn provider(id: &str) -> Provider { + if let Some(p) = builtin_provider(id) { + return p; + } + let core = &["metaobjects-core-types"][..]; + match id { + "example-template-briefing" => Provider::new(id, core, "", register_briefing), + "example-custom-vocabulary" => Provider::new(id, core, "", register_custom_vocabulary), + "cycle-a" => Provider::new(id, &["cycle-b"], "", noop), + "cycle-b" => Provider::new(id, &["cycle-a"], "", noop), + "depends-on-missing" => Provider::new(id, &["does-not-exist"], "", noop), + "duplicate-x" | "duplicate-x-clone" => Provider::new("duplicate-x", &[], "", noop), + other => panic!("unknown provider id {other:?}"), + } +} + +// ---- one fixture --------------------------------------------------------------- + +struct Outcome { + errors: Vec, + canonical: Option, + effective: Option, +} + +fn run_load(fixture: &Path) -> Outcome { + let ids: Vec = match std::fs::read_to_string(fixture.join("providers.json")) { + Ok(text) => serde_json::from_str(&text).expect("providers.json is a string array"), + Err(_) => DEFAULT_PROVIDERS.iter().map(|s| s.to_string()).collect(), + }; + let providers: Vec = ids.iter().map(|id| provider(id)).collect(); + let mut registry = match compose_registry(&providers) { + Ok(r) => r, + Err(e) => { + return Outcome { + errors: vec![e], + canonical: None, + effective: None, + }; + } + }; + registry.seal(); + let input = fixture.join("input"); + let result = Loader::new(®istry) + .load_dir(&input) + .expect("fixture input is readable"); + let prefix = format!("{}/", input.to_string_lossy()); + let errors = result + .errors + .into_iter() + .map(|mut e| { + e.source + .map_files(|f| f.strip_prefix(&prefix).unwrap_or(f).replace('\\', "/")); + e + }) + .collect(); + Outcome { + errors, + canonical: Some(to_canonical_value(&result.tree, result.root, false)), + effective: Some(canonical_serialize_effective(&result.tree, result.root)), + } +} + +fn read_json(path: &Path) -> Value { + serde_json::from_str(&std::fs::read_to_string(path).unwrap()) + .unwrap_or_else(|e| panic!("{}: {e}", path.display())) +} + +/// Whole-number doubles as integers, so `1.0` and `1` compare equal as in JSON. +fn normalize_numbers(v: &Value) -> Value { + match v { + Value::Number(n) if n.is_f64() => n + .as_f64() + .and_then(safe_whole_i64) + .map_or_else(|| v.clone(), Value::from), + Value::Array(items) => Value::Array(items.iter().map(normalize_numbers).collect()), + Value::Object(m) => Value::Object( + m.iter() + .map(|(k, v)| (k.clone(), normalize_numbers(v))) + .collect(), + ), + _ => v.clone(), + } +} + +fn check_envelope(i: usize, want: &Value, got: &MetaError, failures: &mut Vec) { + if let Some(needles) = want.get("messageIncludes").and_then(Value::as_array) { + for needle in needles.iter().filter_map(Value::as_str) { + if !got.message.contains(needle) { + failures.push(format!( + "envelope[{i}].message: expected to include {needle:?}, got {:?}", + got.message + )); + } + } + } + let Some(src) = want.get("source").filter(|s| s.is_object()) else { + return; + }; + let format = src["format"].as_str().unwrap_or_default(); + if format != got.source.format() { + failures.push(format!( + "envelope[{i}].source.format: expected {format:?}, got {:?}", + got.source.format() + )); + } + let want_files: Vec<&str> = src["files"] + .as_array() + .map(|a| a.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + if want_files + != got + .source + .files() + .iter() + .map(String::as_str) + .collect::>() + { + failures.push(format!( + "envelope[{i}].source.files: expected {want_files:?}, got {:?}", + got.source.files() + )); + } + if let Some(path) = src.get("jsonPath").and_then(Value::as_str) + && Some(path) != got.source.json_path() + { + failures.push(format!( + "envelope[{i}].source.jsonPath: expected {path:?}, got {:?}", + got.source.json_path() + )); + } + let (referrer, target) = match got.source.as_ref() { + ErrorSource::Resolved { + referrer, target, .. + } => (Some(referrer.as_str()), Some(target.as_str())), + _ => (None, None), + }; + if let Some(r) = src.get("referrer").and_then(Value::as_str) + && Some(r) != referrer + { + failures.push(format!( + "envelope[{i}].source.referrer: expected {r:?}, got {referrer:?}" + )); + } + if let Some(t) = src.get("target").and_then(Value::as_str) + && Some(t) != target + { + failures.push(format!( + "envelope[{i}].source.target: expected {t:?}, got {target:?}" + )); + } +} + +/// Run every check `fixture` declares. An empty list is a pass. +fn check(fixture: &Path) -> Vec { + let has = |f: &str| fixture.join(f).is_file(); + let mut failures = Vec::new(); + if has("script.json") { + failures.push("script.json operations are not implemented in the Rust port yet".into()); + } + let out = run_load(fixture); + let mut codes: Vec<&str> = out.errors.iter().map(|e| e.code).collect(); + codes.sort_unstable(); + + if !has("expected-errors.json") + && (has("expected.json") + || has("expected-effective.json") + || has("expected-warnings.json") + || has("script.json")) + && !codes.is_empty() + { + failures.push(format!( + "happy-path fixture loaded with unexpected error(s): {codes:?}: {}", + out.errors + .iter() + .map(|e| e.message.as_str()) + .collect::>() + .join(" | ") + )); + } + + if has("expected-errors.json") { + let raw = read_json(&fixture.join("expected-errors.json")); + let (wanted, legacy): (Vec, bool) = match &raw { + Value::Array(items) => (items.clone(), true), + Value::Object(m) => ( + m.get("errors") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(), + false, + ), + _ => panic!("expected-errors.json has an unknown shape"), + }; + let mut want: Vec<&str> = wanted.iter().filter_map(|e| e["code"].as_str()).collect(); + want.sort_unstable(); + if want != codes { + failures.push(format!("errors: want {want:?} got {codes:?}")); + } + if !legacy { + if wanted.len() != out.errors.len() { + failures.push(format!( + "envelope length mismatch: expected {}, got {}", + wanted.len(), + out.errors.len() + )); + } else { + for (i, (w, g)) in wanted.iter().zip(&out.errors).enumerate() { + if w["code"].as_str() != Some(g.code) { + failures.push(format!( + "envelope[{i}].code: expected {}, got {}", + w["code"], g.code + )); + continue; + } + check_envelope(i, w, g, &mut failures); + } + } + let want_warnings = raw + .get("warnings") + .and_then(Value::as_array) + .map_or(0, Vec::len); + if want_warnings != 0 { + failures.push(format!("warnings count: expected {want_warnings}, got 0")); + } + } + } + + if has("expected.json") { + let want = normalize_numbers(&read_json(&fixture.join("expected.json"))); + match &out.canonical { + Some(got) if normalize_numbers(got) == want => {} + Some(got) => failures.push(format!( + "canonical serialization mismatch; got:\n{}", + to_js_pretty(got) + )), + None => failures.push("canonical serialization mismatch: no tree".into()), + } + } + + if has("expected-effective.json") { + let want = std::fs::read_to_string(fixture.join("expected-effective.json")).unwrap(); + let got = out.effective.clone().unwrap_or_default(); + if want.trim() != got.trim() { + failures.push(format!("effective serialization mismatch; got:\n{got}")); + } + } + + if has("expected-warnings.json") { + let want = read_json(&fixture.join("expected-warnings.json")); + if want.as_array().is_some_and(|a| !a.is_empty()) { + failures.push(format!("warnings: want {want} got []")); + } + } + failures +} + +#[test] +fn metamodel_corpus() { + let doc = read_json(&ledger_path()); + assert_eq!(doc["language"], "rust", "the ledger names its port"); + let min_passing = doc["minPassing"] + .as_u64() + .expect("the ledger records minPassing"); + let ledger: Vec = { + doc["fixtures"] + .as_array() + .expect("ledger has a fixtures list") + .iter() + .map(|v| v.as_str().expect("fixture names are strings").to_string()) + .collect() + }; + let mut dirs: Vec = std::fs::read_dir(corpus()) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.join("input").is_dir()) + .collect(); + dirs.sort(); + + let names: Vec = dirs + .iter() + .map(|d| d.file_name().unwrap().to_string_lossy().into_owned()) + .collect(); + let stale: Vec<&String> = ledger.iter().filter(|l| !names.contains(l)).collect(); + assert!( + stale.is_empty(), + "these ledger entries name no fixture directory; remove them: {stale:?}" + ); + + let only = std::env::var("MO_FIXTURE").ok(); + let mut passed = 0; + let mut unexpected = Vec::new(); + let mut fixed = Vec::new(); + for dir in &dirs { + let name = dir.file_name().unwrap().to_string_lossy().into_owned(); + if only.as_deref().is_some_and(|o| o != name) { + continue; + } + let failures = check(dir); + let listed = ledger.contains(&name); + match (failures.is_empty(), listed) { + (true, false) => passed += 1, + (true, true) => fixed.push(name), + (false, true) => { + if only.is_some() { + eprintln!("{name} [known gap]: {}", failures.join("; ")); + } + } + (false, false) => unexpected.push(format!("{name}: {}", failures.join("; "))), + } + } + eprintln!( + "metamodel corpus: {passed} of {} fixtures pass; {} on the expected-failures ledger; {} unlisted failures", + dirs.len(), + ledger.len(), + unexpected.len() + ); + for failure in &unexpected { + eprintln!( + "warning: fixture fails in Rust and is not on the ledger (preview port, not a gate failure): {failure}" + ); + } + assert!( + fixed.is_empty(), + "these ledgered fixtures now pass; remove them from the ledger (it may only shrink): {fixed:?}" + ); + if only.is_none() { + assert!( + passed as u64 >= min_passing, + "{passed} fixtures pass but the ledger's minPassing is {min_passing}: a fixture that passed has regressed (see the warnings above)" + ); + } +} diff --git a/server/rust/metaobjects/tests/registry_conformance.rs b/server/rust/metaobjects/tests/registry_conformance.rs new file mode 100644 index 0000000000..2387609646 --- /dev/null +++ b/server/rust/metaobjects/tests/registry_conformance.rs @@ -0,0 +1,48 @@ +//! The registry-conformance gate: the built-in registry, written as a manifest, +//! must match the shared `expected-registry.json` byte for byte. + +use std::path::PathBuf; + +use metaobjects::manifest::emit_manifest; +use metaobjects::providers::{builtin_provider, compose_registry}; + +fn fixture_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/registry-conformance") +} + +#[test] +fn manifest_matches_the_shared_registry_fixture() { + let dir = fixture_dir(); + let providers_doc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(dir.join("providers.json")).unwrap()) + .unwrap(); + // providers.json indexes the logical provider ids; the manifest is built from + // all of them, in the order the file lists them. + let ids: Vec<&str> = providers_doc["providers"] + .as_object() + .expect("providers.json has a providers map") + .keys() + .map(String::as_str) + .collect(); + let providers: Vec<_> = ids + .iter() + .map(|id| builtin_provider(id).unwrap_or_else(|| panic!("unknown provider {id}"))) + .collect(); + let registry = compose_registry(&providers).expect("the built-in providers compose"); + let actual = emit_manifest(®istry); + let expected = std::fs::read_to_string(dir.join("expected-registry.json")).unwrap(); + if actual != expected { + let out = std::env::temp_dir().join("metaobjects-rust-actual-registry.json"); + std::fs::write(&out, &actual).unwrap(); + let line = actual + .lines() + .zip(expected.lines()) + .position(|(a, e)| a != e) + .map_or(actual.lines().count().min(expected.lines().count()), |i| i); + panic!( + "registry manifest differs from expected-registry.json at line {} (actual written to {})", + line + 1, + out.display() + ); + } +} diff --git a/server/rust/rust-toolchain.toml b/server/rust/rust-toolchain.toml new file mode 100644 index 0000000000..4dda7d9445 --- /dev/null +++ b/server/rust/rust-toolchain.toml @@ -0,0 +1,6 @@ +# Pinned so every machine and the CI lane build with the same compiler, rustfmt +# and clippy. Raise it deliberately, in its own commit. +[toolchain] +channel = "1.94.1" +components = ["rustfmt", "clippy"] +profile = "minimal" diff --git a/spec/conformance-tests.md b/spec/conformance-tests.md index 29106b7b07..39b827d21a 100644 --- a/spec/conformance-tests.md +++ b/spec/conformance-tests.md @@ -2,7 +2,7 @@ The MetaObjects standard ships with a conformance test suite that the language implementations run. There are now **seven corpora** spanning loader, YAML desugar, render, verify, codegen-walk, persistence, and API contract; this document specifies the **metamodel (loader) corpus** (`metaobjects/fixtures/conformance/`) — the **shared source of truth** for Loader behavior — and the canonical serializer contract. The other corpora are summarized under [Sibling corpora](#sibling-corpora-render-and-verify). -The loader corpus is run by the four ports that have their own Loader (TS, Java, Python, C#). **Kotlin** is the fifth port; it consumes the Java metadata via the `metadata-ktx` facade rather than re-implementing a Loader, so it participates in the persistence and API-contract corpora but not the loader/YAML/render/verify corpora. +The loader corpus is run by the four ports that have their own Loader (TS, Java, Python, C#). **Kotlin** is the fifth port; it consumes the Java metadata via the `metadata-ktx` facade rather than re-implementing a Loader, so it participates in the persistence and API-contract corpora but not the loader/YAML/render/verify corpora. **Rust** is the sixth port, in preview (ADR-0065): it runs this corpus against a shrink-only expected-failures ledger — see [`docs/CONFORMANCE.md`](../docs/CONFORMANCE.md) for its current coverage. > The full corpus × port run-matrix, known coverage gaps, and a remediation backlog live in [`docs/superpowers/specs/2026-05-29-conformance-hardening-review.md`](../docs/superpowers/specs/2026-05-29-conformance-hardening-review.md). Consult it before treating "all green" as full coverage. diff --git a/spec/decisions/ADR-0065-rust-is-the-sixth-port.md b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md new file mode 100644 index 0000000000..f11a462679 --- /dev/null +++ b/spec/decisions/ADR-0065-rust-is-the-sixth-port.md @@ -0,0 +1,109 @@ +# ADR-0065: Rust is the sixth port + +## Status + +**Proposed** (2026-11-14). Registers no vocabulary: `metamodelVersion` is unchanged. Adds a sixth +language port under `server/rust/`, in preview, and a `rust` CI lane. Amends nothing. + +## Context + +MetaObjects ships five ports (TypeScript, Java, Kotlin, C#, Python), each held to the others by +the shared conformance corpora rather than by a claim in prose. Rust is the obvious missing +server language: it is where a growing share of new backend and tooling work is written, and a +generator written in it is fast enough that regenerating a large model stops being something an +adopter waits for. + +A port is a large, long-lived commitment, so the question is not only "should there be one" but +"what does it promise while it is incomplete, and where does it deliberately differ from the other +five". + +## Decision + +1. **Rust is a full port, built in phases, and it is in preview until it leaves preview by + decision.** It ships the same core as the others (ADR-0034 Amendment 3): the metamodel, + loader, canonical serializer and registry, then runtime metadata access, `verify`, prompt + render and the reply parser. Its generators are reference helpers like every other port's, + and it can eject them. The first slice is the loader core, gated by `registry-conformance` + (byte-identical) and the shared metamodel corpus. + +2. **Layout.** `server/rust/` is one Cargo workspace with a pinned toolchain + (`rust-toolchain.toml`). The first crate is `metaobjects` (node model, registry, providers, + loader, serializer). `metaobjects-codegen` and `metaobjects-cli` join the workspace when they + have code; the workspace carries no empty placeholder crates. + +3. **The command is `cargo meta`.** It is a Cargo subcommand (a `cargo-meta` binary), the way the + other build-tool-hosted ports spell theirs (`dotnet meta`, `mvn metaobjects:...`). A bare `meta` + stays the Node schema CLI's. + +4. **Preview, on a 0.x line, unpublished.** The crates are `publish = false` and nothing goes to + crates.io until the port leaves preview. When it publishes, it starts on its own `0.x` line + rather than joining the lockstep npm/Maven/PyPI/NuGet numbers, the way the source-only Angular + packages keep their own line (ADR-0048). It joins the convergent-publishing rule + (ADR-0035 Amendment 1) when it leaves preview. + +5. **Conformance is the definition of done, and gaps are ledgered, not hidden.** The metamodel + runner keeps an expected-failures ledger in the format the other ports use. A fixture on the + ledger that starts passing fails the run until it is removed, so the ledger can only shrink. + While the port is in preview, a fixture that is not on the ledger and fails in Rust prints a + warning naming the fixture and the reason, and does not fail the run or the `rust` lane, so a + new conformance fixture in a 1.3.0 PR never turns the lane red for a port that has not built + that behavior yet. A regression is still a failure: the ledger records `minPassing`, the number + of fixtures known to pass, which may only rise, and the run fails when fewer pass. When the + preview label comes off, an unlisted failure fails the lane. + +6. **Deliberate differences from the other five.** + - **No `migrate`.** Schema migrations are TypeScript-owned (ADR-0015), as in Java, C# and + Python. The Rust CLI is codegen, `verify` and `fmt`. + - **Jinja is refused.** Template bodies render with the Mustache engine every port shares; a + Jinja body is refused with `ERR_TEMPLATE_ENGINE_UNSUPPORTED`, as in Java, Kotlin and C# + (ADR-0061). + - **Generated code is one crate per MetaObjects package.** A Rust crate is the unit of + compilation and visibility, so a package maps to a crate rather than to a module of one + large crate. Cross-package references become crate dependencies. + +7. **Built for speed from the start.** Generation writes only files whose bytes changed, keeps + no per-file manifest writes on the hot path, and runs no formatter in the generation path + (the emitter writes formatted output, as ADR-0063 rules for every port). A load benchmark over a 20-times copy of the public + fitness model (`cargo run --release --example load_bench`) is kept beside the crate. + +8. **The runtime read path: freeze, then memoize, like the other ports.** Runtime metadata + access reads the same resolved values over and over from many threads, so the tree caches its + `extends`-chain walks the way TypeScript (`cached()`), C# (`Cached`), Python (`_cached`) and + Java (`freeze()`/`useFrozenCache()`, FR-031) do. A tree has a mutable load phase and a frozen + phase. The loader calls `Tree::freeze()` at its terminal phase (where the other ports freeze at + REGISTERED); from then on every mutator panics, and the resolving accessors memoize: one + `OnceLock` per node and accessor, allocated at the freeze. Nothing is cached before the freeze, + so a value read during the load cannot be served stale, and nothing is invalidated. A frozen + `Tree` is `Sync`; a racing first read computes an entry once while the others wait, and a + cached read returns a borrow (`Cow::Borrowed`) rather than a copy. + + The memoized set is the base-node set the other ports share: effective `children`, effective + `attrs` (and `attr`, which reads through that map once frozen) and `resolved_is_array`. + TypeScript and C# also cache snapshots of a node's own attrs and own children because they + copy them; the Rust own accessors already borrow the node's storage, so there is nothing to + memoize. Typed accessors that come with later phases (an object's fields, identities and + relationships, a root's object lookup) memoize through the same per-node cache, keyed the way + the other ports key theirs. Tests in `node.rs` hold the cached reads equal to the uncached + walks, prove a read before the freeze does not survive a later mutation, and read one frozen + tree from eight threads at once. + +## Consequences + +- The shared lane map (`scripts/ci-lane-map.txt`, read by `scripts/ci-select-lanes.sh`) has a + `rust` lane, `server/rust/**` selects it, and the `scripts/ci-affected-ports.sh` and + `scripts/ci-ports-to-run.sh` selectors know six ports. `scripts/ci-local.sh --only rust` runs + `cargo fmt --check`, clippy with warnings denied and the crate's tests, and `pr-ci` and + `local-ci` run it as their own job. +- `docs/CONFORMANCE.md` names the port beside the matrix, not as a column, until it leaves + preview; its column then appears with per-corpus results like the others. +- Every later phase (validation passes, overlays and cross-package references, YAML and source + resolution, runtime access, codegen, `cargo meta`) is held to the same corpora the other ports + run, and lands as its own change. + +## Alternatives considered + +- **Bindings over an existing port** (calling the TypeScript or Java loader from Rust). Rejected: + it adds a second runtime to every adopter's build and gives up the speed that is part of the + reason for the port. +- **A Rust core shared by the other ports.** Out of scope: every port owns its loader by design, + and the corpora, not a shared binary, keep them identical. diff --git a/spec/decisions/README.md b/spec/decisions/README.md index 8872567d61..21985db21d 100644 --- a/spec/decisions/README.md +++ b/spec/decisions/README.md @@ -61,6 +61,7 @@ Write one when a decision is **cross-cutting** (affects more than one language p - [ADR-0062 — Two providers may not claim one attribute name on a node type](ADR-0062-provider-attribute-ownership.md) — *Accepted* (the registry records which provider registered each attribute and refuses a second provider's claim on the same name on the same slot, the shared root or a descendant subtype: `ERR_PROVIDER_ATTR_CONFLICT` for the same slot, new `ERR_PROVIDER_ATTR_SHADOW` for the related slots; each provider keeps its own idiomatic physical-name word, a store without a provider uses `attr.properties`, no wire-name attribute is added) - [ADR-0063 — Generators own their layout; formatters are test oracles only](ADR-0063-generators-own-layout.md) — *Accepted* (a writer in each port lays generated text out and no formatter runs in generation; output aims for clean code, not parity with today's formatting; a syntax-tree ratchet holds generator source to it, with an allowlist that only shrinks) - [ADR-0064 — `gen` skips rendering when the loaded model and its generators are unchanged](ADR-0064-skip-codegen-when-nothing-changed.md) — *Accepted* (every port keys a run on the loaded model and its generator inputs, and a matching key with every generated file unchanged renders and writes nothing; the manifest is written once per run; a local `verify --codegen` may answer from the key) +- [ADR-0065 — Rust is the sixth port](ADR-0065-rust-is-the-sixth-port.md) — *Proposed* (a Rust port under `server/rust/`, in preview and unpublished, on its own 0.x line when it publishes; the command is `cargo meta`; no `migrate`, Jinja refused, generated code as one crate per MetaObjects package; gated by `registry-conformance` and the metamodel corpus with a shrink-only ledger) > **Index gap — ADR-0031 through ADR-0051 are on disk but not listed above.** The index stopped > being maintained after ADR-0030; the files are authoritative, this list is not. Read