From 9e67ec33679b9a8f3f584d65fbf77595f67fdfa1 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:49:02 -0500 Subject: [PATCH 01/18] feat(rust): prompt-tier generators, crates.io release path, generators own their layout Three plan rows on the Rust lane, folded into one branch. - render-helper, output-parser and output-prompt generators over the metaobjects-render crate: a prompts, parsers and formats crate per package, held to the render, template-output and extract corpora; verify --templates checks prompt bodies; eject copies all three. - A6: the Rust crates join scripts/release.mjs as the fifth registry (crates.io after npm, dependency order, changed-since-tag selection, token and free-version preflight); a release-tag gate in ci-local. - W-RS-1 (ADR-0063): a syn-based layout ratchet whose allowlist only shrinks; nine rust writer-conformance cases, each a rustfmt fixed point under the generated crates' rustfmt.toml; generator options in metaobjects.config.json through Generator::configure, refused with ERR_UNKNOWN_GENERATOR_OPTION; a *Parts trait per shipped generator, one default method per output piece. Output is byte-identical except that assign now moves an array right-hand side to the next line where rustfmt does. --- CHANGELOG.md | 29 + docs/CONFORMANCE.md | 18 +- docs/RELEASING.md | 57 +- docs/ports/rust.md | 120 ++- .../registry.json | 12 +- .../expected-drift.rust.json | 1 + .../expected-drift.rust.json | 1 + fixtures/writer-conformance/README.md | 10 +- .../cases/rust-assign-breaks.json | 34 + .../cases/rust-assign-fits.json | 37 + .../cases/rust-assign-next-line.json | 47 ++ .../cases/rust-defaults.json | 81 ++ .../cases/rust-doc-keeps-lines.json | 20 + .../cases/rust-prose-wraps.json | 38 + .../cases/rust-use-fills.json | 30 + .../cases/rust-use-fits.json | 21 + scripts/ci-local.sh | 2 +- scripts/lib/rust-release.mjs | 146 ++++ scripts/release.mjs | 95 ++- scripts/test-rust-release.mjs | 116 +++ server/rust/Cargo.lock | 12 +- server/rust/Cargo.toml | 10 +- server/rust/metaobjects-cli/Cargo.toml | 4 +- server/rust/metaobjects-cli/src/lib.rs | 55 +- server/rust/metaobjects-cli/tests/cli.rs | 72 +- server/rust/metaobjects-codegen/Cargo.toml | 10 +- server/rust/metaobjects-codegen/src/client.rs | 456 +++------- .../rust/metaobjects-codegen/src/commands.rs | 379 +++------ server/rust/metaobjects-codegen/src/eject.rs | 224 +++-- .../src/emitted/client_transport.rs | 265 ++++++ .../src/emitted/command_helpers.rs | 205 +++++ .../metaobjects-codegen/src/emitted/mod.rs | 13 +- server/rust/metaobjects-codegen/src/engine.rs | 66 +- server/rust/metaobjects-codegen/src/entity.rs | 287 +++++-- .../rust/metaobjects-codegen/src/generator.rs | 40 + .../metaobjects-codegen/src/generator_list.rs | 146 +++- .../rust/metaobjects-codegen/src/inbound.rs | 348 ++++++++ server/rust/metaobjects-codegen/src/lib.rs | 13 + server/rust/metaobjects-codegen/src/names.rs | 24 +- .../metaobjects-codegen/src/output_parser.rs | 536 ++++++++++++ .../metaobjects-codegen/src/output_prompt.rs | 427 ++++++++++ .../metaobjects-codegen/src/render_helper.rs | 787 ++++++++++++++++++ server/rust/metaobjects-codegen/src/writer.rs | 140 +++- .../metaobjects-codegen/tests/client_edges.rs | 5 +- .../metaobjects-codegen/tests/common/mod.rs | 80 +- .../rust/metaobjects-codegen/tests/compile.rs | 10 +- .../metaobjects-codegen/tests/gen-check.lock | 96 +-- .../tests/generator_options.rs | 137 +++ .../tests/generator_parts.rs | 123 +++ .../tests/generator_registry.rs | 2 +- .../tests/layout_ratchet.rs | 468 +++++++++++ .../tests/layout_ratchet/allowlist.json | 12 + .../tests/layout_ratchet/analyze.rs | 358 ++++++++ .../tests/output_parser.rs | 219 +++++ .../tests/render_helper_conformance.rs | 306 +++++++ .../rust/metaobjects-codegen/tests/scale.rs | 6 +- .../tests/skip_conformance.rs | 32 +- .../tests/writer_conformance.rs | 55 +- server/rust/metaobjects-render/Cargo.toml | 3 + .../metaobjects-render/src/extract/mod.rs | 72 ++ .../rust/metaobjects-render/src/filesystem.rs | 92 ++ server/rust/metaobjects-render/src/lib.rs | 23 +- server/rust/metaobjects-render/src/render.rs | 83 ++ server/rust/metaobjects-render/src/verify.rs | 414 +++++++++ .../tests/verify_conformance.rs | 135 +++ spec/code-writer.md | 25 +- .../ADR-0063-generators-own-layout.md | 29 + 67 files changed, 7195 insertions(+), 1024 deletions(-) create mode 100644 fixtures/verify-conformance/verify-set-delimiter-clean/expected-drift.rust.json create mode 100644 fixtures/verify-conformance/verify-set-delimiter-drift/expected-drift.rust.json create mode 100644 fixtures/writer-conformance/cases/rust-assign-breaks.json create mode 100644 fixtures/writer-conformance/cases/rust-assign-fits.json create mode 100644 fixtures/writer-conformance/cases/rust-assign-next-line.json create mode 100644 fixtures/writer-conformance/cases/rust-defaults.json create mode 100644 fixtures/writer-conformance/cases/rust-doc-keeps-lines.json create mode 100644 fixtures/writer-conformance/cases/rust-prose-wraps.json create mode 100644 fixtures/writer-conformance/cases/rust-use-fills.json create mode 100644 fixtures/writer-conformance/cases/rust-use-fits.json create mode 100644 scripts/lib/rust-release.mjs create mode 100644 scripts/test-rust-release.mjs create mode 100644 server/rust/metaobjects-codegen/src/emitted/client_transport.rs create mode 100644 server/rust/metaobjects-codegen/src/emitted/command_helpers.rs create mode 100644 server/rust/metaobjects-codegen/src/inbound.rs create mode 100644 server/rust/metaobjects-codegen/src/output_parser.rs create mode 100644 server/rust/metaobjects-codegen/src/output_prompt.rs create mode 100644 server/rust/metaobjects-codegen/src/render_helper.rs create mode 100644 server/rust/metaobjects-codegen/tests/generator_options.rs create mode 100644 server/rust/metaobjects-codegen/tests/generator_parts.rs create mode 100644 server/rust/metaobjects-codegen/tests/layout_ratchet.rs create mode 100644 server/rust/metaobjects-codegen/tests/layout_ratchet/allowlist.json create mode 100644 server/rust/metaobjects-codegen/tests/layout_ratchet/analyze.rs create mode 100644 server/rust/metaobjects-codegen/tests/output_parser.rs create mode 100644 server/rust/metaobjects-codegen/tests/render_helper_conformance.rs create mode 100644 server/rust/metaobjects-render/src/filesystem.rs create mode 100644 server/rust/metaobjects-render/src/verify.rs create mode 100644 server/rust/metaobjects-render/tests/verify_conformance.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index a3f9fec6af..1deac2e1a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -900,6 +900,35 @@ Each item below is described in full under Security, Added, Changed or Fixed; th to build and test it, and the scope of `cargo meta`; the crates.io name `cargo-meta` is held by an unrelated crate, so the CLI crate will publish under another name that installs a `cargo-meta` binary (a plan, not a promise). Nothing is published. +- **Rust port's prompt tier: `render-helper`, `output-parser` and `output-prompt`.** A new + `metaobjects-render` crate renders a declared prompt, reads a reply (the strict JSON parse and the + tolerant `extract`) and writes the output-format fragment, held to the render, template-output + and extract corpora. The three generators write a crate each beside the model crate: + `_prompts` (a typed render function per prompt), `_parsers` (`parse_` + for a JSON reply, `extract_` for any, and the extract schema) and `_formats` + (the fragment and its descriptor), for every prompt with a `@responseRef` (ADR-0052). `cargo meta + verify --templates` checks prompt bodies against their payloads, and `eject` copies all three. + The generated crates depend on `metaobjects-render` at this release's major and minor. +- **The Rust crates join the release path (ADR-0065 Amendment 3).** The workspace version moves to + the shared line (1.3.0), and `scripts/release.mjs` publishes the four crates to crates.io after + npm, behind the same confirm, in dependency order, when a file they ship changed since the last + `rust-v*` tag (or they never shipped, or `expected-registry.json` moved); `--crates=publish|skip` + overrides. Its preflight checks the crates.io token and that the version is free before anything + is bumped. `docs/RELEASING.md` names crates.io as the fifth registry. Nothing is published. +- **Rust generators own their layout, take options and expose their parts (ADR-0063).** A + layout ratchet (`tests/layout_ratchet.rs`) parses every generator source with `syn` and fails + on a hand-typed line break or indentation run; its allowlist can only shrink, and it starts + empty but for six files whose strings are not generated code. Nine `rust` writer-conformance + cases pin the dialect (`use_list`, `doc`, `prose`, `doc_break`, `assign`), each a rustfmt fixed + point under the generated crates' `rustfmt.toml`. An entry in `metaobjects.config.json`'s + `generators` may now be `{"name": ..., "options": {...}}`: `Generator::configure` receives the + options, and the shipped generators take none and refuse any key with + `ERR_UNKNOWN_GENERATOR_OPTION`, also on a run `--generators` narrows. Each shipped generator + has a `*Parts` trait (`EntityParts`, `ClientParts`, `CommandsParts`, `RenderHelperParts`, + `OutputParserParts`, `OutputPromptParts`) with one default method per output piece, so an owned + generator overrides one piece and keeps the rest. Generated output is byte-identical but for + one fix: `assign` now moves an array right-hand side to the next line when that is where + rustfmt puts it under those settings. - **Example and write-up: metadata-driven grids, forms and routes in TypeScript.** `examples/dynamic-grid/` serves and renders every entity of a model from the loaded metadata: one grid component and one form component that take an entity name and read the diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index e1acbb9b21..1873cd9f68 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -81,13 +81,15 @@ green, with every validation pass the TypeScript loader runs, in the same order, `yaml-ref-root-escape`, waits for the ADR-0059 root-level `::` reference rules, which are reference resolution, not a validation pass); `source-resolution-conformance` (all 28 cases); `naming-conformance` (all of it); `codegen-skip-conformance` (ADR-0064), on both its -`gen` and its `verify` columns, for every case the port can meet (the three it cannot, two -about templates and one about the three-way merge, are named with their reason in its -runner); `validation-conformance`, every case, through the generated `validate()`; +`gen` and its `verify` columns, for every case the port can meet, the template cases among +them (the one it cannot, about the three-way merge, is named with its reason in its runner); `validation-conformance`, every case, through the generated `validate()`; `decimal-wire` and `duration-wire`, every vector, against the code the generated support crate carries; `render-conformance`, every case byte-identical, `extract-conformance`, all 58 cases, and `output-prompt-conformance`, all 17 in all three styles with the round trip, in the -`metaobjects-render` crate; the `core` cases of `writer-conformance` (ADR-0063); and +`metaobjects-render` crate; `template-output-render-conformance`, through generated +`render-helper` crates a probe builds; `verify-conformance`, all 45 cases through +`cargo meta verify --templates` (two set-delimiter cases carry a `.rust.json` expectation); +the `core` cases of `writer-conformance` (ADR-0063); and `generator-registry-conformance`, with the eject contract's census, completeness and depth (ADR-0034 Amendment 8). It also runs the codegen-compile gate (below) with every shipped generator, and a scale gate over twenty copies of the fitness model. The ledgers above may @@ -253,7 +255,7 @@ Amendment 8). A gate, not a corpus: it has no fixtures of its own, and reads and emits what the packaged generator emits (depth). TypeScript: `cli/test/eject-contract.test.ts`. C#: `EjectContractTests`. Java: `EjectContractTest` in `maven-plugin`. Kotlin: `EjectContractTest` in `codegen-kotlin`. Python: - `tests/conformance/test_eject_contract.py`. Rust holds its three generators to + `tests/conformance/test_eject_contract.py`. Rust holds its six generators to the same assertions: census, completeness and the reference scan in `metaobjects-codegen/tests/generator_registry.rs`, and the ejected-alone build in `metaobjects-cli/tests/cli.rs`. @@ -347,7 +349,9 @@ manifest contains without moving these boundaries. never executes. - *Rust runs it too*, with `cargo check` and `rustfmt --check`, over every generator it ships: it has no framework-bound route tier to exclude, and its generated - client and commands are driven over HTTP against a local stub in the same test. + client and commands are driven over HTTP against a local stub in the same test. The + generated prompt, parser and format crates build against the workspace's own + `metaobjects-render`. - *Every port excludes its framework-bound route tier* — TS `routesFile`, C# `RoutesGenerator`, Java `SpringControllerGenerator`, Kotlin `KotlinSpringControllerGenerator`. Those imports are not on an in-memory compile's @@ -421,7 +425,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 | `cd server/rust && cargo test` (registry, metamodel, YAML, source-resolution, naming, skip, validation, wire-vector, writer, generator-registry, render, extract and output-prompt corpora; the codegen-compile and scale gates, which run `cargo check` on generated crates and drive the generated client over HTTP against a local stub) | — | — | +| Rust | `cd server/rust && cargo test` (registry, metamodel, YAML, source-resolution, naming, skip, validation, wire-vector, writer, generator-registry, render, extract, output-prompt, template-output-render and verify corpora; the codegen-compile and scale gates, which run `cargo check` on generated crates and drive the generated client over HTTP against a local stub) | — | — | 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/docs/RELEASING.md b/docs/RELEASING.md index ee7a48897c..e6d04ddc9a 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -14,20 +14,23 @@ > first, see the Java procedure). One route per version, never both. > - **NuGet** → keyless OIDC via the `publish-csharp.yml` workflow: `gh workflow run > publish-csharp.yml` (or push a `csharp-v` tag). +> - **crates.io** → `scripts/release.mjs` publishes the four Rust crates after npm, behind the +> same confirm, with the token `cargo login` stores. See +> [Releasing the Rust crates to crates.io](#releasing-the-rust-crates-to-cratesio). > > Run network commands via the sandbox-disabled shell. **Publish what changed; converge the > number when you do (standing policy since 0.24.5, replacing the version-parity rule of > 0.20.13):** a registry publishes only when it has a changed product file, and when it does it > adopts the **current shared `minor.patch`** — skipping the numbers it sat out. npm / PyPI / -> NuGet on `..

`, Maven on `..

` — only the MAJOR differs, and the offset is +> NuGet / crates.io on `..

`, Maven on `..

` — only the MAJOR differs, and the offset is > permanent (`scripts/maven-coordinate.mjs` is the single derivation; every script imports it). > Concretely: npm `0.25.0` is Maven `7.25.0`, and npm `1.0.0` is Maven **`8.0.0`**. Do not type > a literal `7.` anywhere — at the 1.0 cut it asks Central for a version BELOW the last release. > Two carve-outs: the **13 npm packages still move atomically with each other** (they > cross-depend — that is intra-npm lockstep and it is unchanged), and a change to -> `expected-registry.json` / `metamodelVersion` **forces all four**, because that is the +> `expected-registry.json` / `metamodelVersion` **forces all five**, because that is the > cross-port contract — whatever the release's level, so a vocabulary-adding PATCH publishes -> all four too (ADR-0035 Amendment 5). The rest of this doc is the per-registry procedure. +> all five too (ADR-0035 Amendment 5). The rest of this doc is the per-registry procedure. ## Step 0 (all registries): scan for unmerged work before you cut @@ -295,7 +298,7 @@ what they render is generator output and does not.) | Wire-contract / conformance behavior change of already-valid deployments | FR-036 enforcement | **MINOR**, loud notice (pre-1.0 MINOR *is* the breaking slot) | **`metamodelVersion` MAJOR** (Metamodel 2.0) + package MINOR — see the two-contracts rule below | | Wire behavior fixed to match the documented/conformance contract | 0.19.1 `@min` clamp | PATCH | PATCH | | No changed product file in a port | PyPI/NuGet/Maven at 0.24.4 while npm cuts 0.24.5 | **Do not publish that registry.** It sits the release out and keeps its current version. When it next has a changed file it adopts the shared `minor.patch` then current, skipping the numbers between (publish-what-changed policy, standing since 0.24.5) | same | -| A change to `expected-registry.json` / `metamodelVersion` | any vocabulary move, at any release level — a vocabulary-adding PATCH included | **All four registries publish**, changed file or not — the metamodel is the cross-port contract and every port byte-matches the manifest | same | +| A change to `expected-registry.json` / `metamodelVersion` | any vocabulary move, at any release level — a vocabulary-adding PATCH included | **All five registries publish** (npm, PyPI, NuGet, Maven Central, crates.io), changed file or not — the metamodel is the cross-port contract and every port byte-matches the manifest | same | ### The two-contracts rule (post-1.0; ADR-0035 Amendment 2) @@ -904,6 +907,52 @@ Project `metaobjects` → **Settings → Publishing → Add a new GitHub publish dist/*` from `server/python`, and then do not push a `python-v*` tag for that version. 4. **Verify:** `curl -s https://pypi.org/pypi/metaobjects/json | python3 -c "import sys,json;print(json.load(sys.stdin)['info']['version'])"`. +# Releasing the Rust crates to crates.io + +The four Rust crates ([ADR-0065](../spec/decisions/ADR-0065-rust-is-the-sixth-port.md) +Amendment 3) ship to crates.io on the shared `..

` line, from one workspace version +(`[workspace.package]` in [`server/rust/Cargo.toml`](../server/rust/Cargo.toml)): + +| Crate | What it is | +|---|---| +| `metaobjects` | the loader, registry and canonical serializer | +| `metaobjects-render` | prompt render, the reply parser and the output-format fragment | +| `metaobjects-codegen` | the run engine and the shipped generators | +| `metaobjects-cli` | the `cargo-meta` binary (`cargo meta`) | + +**`scripts/release.mjs` publishes them; there is no separate procedure.** The rules it applies +live in [`scripts/lib/rust-release.mjs`](../scripts/lib/rust-release.mjs) and are tested by +`scripts/test-rust-release.mjs` (the `gates` lane runs it): + +1. **Whether they ship.** Publish what changed: the crates publish when a file they ship (a + crate's sources, data, build script or manifest, or the workspace manifest and lockfile, + but not tests, examples, benches or baselines) changed since the newest `rust-v*` tag, and + always when `expected-registry.json` moved. With no `rust-v*` tag they have never shipped, + and the cut publishes them. `--crates=publish` or `--crates=skip` overrides the decision; + the preflight prints the reason either way. +2. **Preflight**, with npm's, before anything is bumped: a crates.io token (from `cargo login` + or `CARGO_REGISTRY_TOKEN`), and the version free on every crate. crates.io versions are + permanent: a yank hides a version from new resolutions and does not free its number. +3. **Bump**: the workspace version and every sibling crate's version requirement move to the + release's, then `cargo update --workspace` updates the lockfile. The commit carries them + with npm's. +4. **Pack-verify**: `cargo publish --dry-run --workspace` packages each crate and builds it + against its siblings' tarballs, so a crate that builds only from a path in the checkout + fails before the confirm. +5. **Publish**, after npm: `cargo publish -p ` in dependency order (`metaobjects`, + `metaobjects-render`, `metaobjects-codegen`, `metaobjects-cli`). cargo waits for each crate + to reach the index before it returns, so the next one resolves it. +6. **Tag** `rust-v` with the other ports' tags, before `finish-release.mjs`. The next + cut compares against it. + +The generated prompt crates name `metaobjects-render` by this release's major and minor +(`metaobjects_render::REQUIREMENT`), so code generated by 1.3.x needs a 1.3 or later render +crate and never resolves to an older one. + +**Nothing is published without the owner's go.** That holds for crates.io as for every +registry. A crate name is reserved only by publishing it, and the CLI's package name is +`metaobjects-cli` because `cargo-meta` is held by an unrelated crate. + # Releasing the Java/Kotlin modules to Maven Central The 14 `com.metaobjects:*` modules (15 artifacts, counting the parent POM) ship to **Maven Central via the Sonatype Central Portal**, diff --git a/docs/ports/rust.md b/docs/ports/rust.md index e4b494e021..eae0d1393c 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -31,7 +31,7 @@ The loader is the `metaobjects` crate, and the workspace at `server/rust/` adds | Reply parser | `metaobjects_render::extract::extract` reads a typed answer out of a model's reply (FR-010, FR-011): fences, prose, comments, trailing commas and cut-off values tolerated, every declared field classified (`EXTRACTED`, `DEFAULTED`, `LOST_OPTIONAL`, `LOST_REQUIRED`, `MALFORMED`) and coerced to its kind, under a `STRICT`, `NORMAL` or `LOOSE` tolerance. `metaobjects_render::prompt::render_output_format` writes the output-format fragment that asks for that answer, in the `guide`, `inline` and `exampleOnly` styles. | | Frozen tree | The loader freezes the tree when it finishes. A frozen tree memoizes its resolved reads (effective children, attributes and array-ness), so many readers can share one. | | Timings | Every load records how long each phase and each validation pass took (`LoadResult::timings`). | -| Code generation (`cargo meta`) | The run engine, three generators (`entity`, `client`, `commands`), the codegen drift gate and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | +| Code generation (`cargo meta`) | The run engine, six generators (`entity`, `client`, `commands`, `render-helper`, `output-parser`, `output-prompt`), the codegen and template drift gates and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | ## The command: `cargo meta` @@ -53,7 +53,8 @@ and the same `git` + `rev` on a `metaobjects` dependency). The candidate log |---|---| | `cargo meta init [--project

]` | Scaffolds `.metaobjects/config.json`, `.metaobjects/.gitignore` (which keeps `.gen-state/.hashes/` committed), a first `metaobjects/meta.app.yaml` and `metaobjects.config.json`, the list of generators to run (see [Choosing generators](#choosing-generators)). It writes only what is missing, and never adds an empty metadata file to a project that already has metadata. | | `cargo meta gen [ENTITY...]` | Generates the crates. It skips the whole run when the model, the project config and the generators are unchanged ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)), writes only files whose bytes changed, removes a generated file nothing emits any more, and refuses to overwrite or delete a generated file that was edited by hand. It prints what it created, updated and removed, and the crates to re-check. | -| `cargo meta verify [--codegen] [--full]` | The codegen drift gate: renders in memory, compares with disk, writes nothing, and exits 1 on drift, naming each file. Locally it may answer from the stored skip key; `--full`, or a set `CI` variable, always renders. `--codegen` runs that gate alone. A bare `verify` also runs the business-rules gate ([ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)) on the loaded model, and prints nothing about it when the model declares no operation and no transition; an error-severity finding (a `rules.permissions.names` of `require`, or `verify.lifecycle.unreachable` of `error`) exits 1. `--db`, `--templates` and `--deps` exit 2 with the reason and where that check lives. | +| `cargo meta verify [--codegen] [--full]` | The codegen drift gate: renders in memory, compares with disk, writes nothing, and exits 1 on drift, naming each file. Locally it may answer from the stored skip key; `--full`, or a set `CI` variable, always renders. `--codegen` runs that gate alone. A bare `verify` also runs the business-rules gate ([ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)) on the loaded model, and prints nothing about it when the model declares no operation and no transition; an error-severity finding (a `rules.permissions.names` of `require`, or `verify.lifecycle.unreachable` of `error`) exits 1. `--db` and `--deps` exit 2 with the reason and where that check lives. | +| `cargo meta verify --templates` | The template gate alone: every `template.*` body, read from the project's `prompts/` (else `templates/`), checked against its payload's field tree, the same check `gen` makes before it writes a render helper. Exits 1 on drift, naming the template, the file and the tag. | | `cargo meta eject ...` | Copies a shipped generator into the project to own. An existing copy is refused; `--force` replaces it with the reference, and leaves a copy that already matches untouched. `--undo` takes back copies still identical to the shipped source; `--list` shows what can be ejected and how each owned copy compares. See [Owning a generator](#owning-a-generator). | `gen` and `verify` share `--project `, `--out ` (default `generated`), `--generators `, @@ -67,14 +68,18 @@ other ports choose theirs (`metaobjects.config.ts`, `codegen/Generators.cs`, the running one, and no eject is needed: ```json -{ "generators": ["entity", "client", "commands"] } +{ "generators": ["entity", "client", "commands", "render-helper", "output-parser", "output-prompt"] } ``` -The file takes that one key and no options: a layer is only a generator, so there are no layer settings. -A project with no such file runs every generator. A generator that leaves the list has its files removed +The file takes that one key: a layer is only a generator, so there are no layer settings. An entry is a +name, or `{"name": "", "options": {...}}` for a generator that takes options; the +generator's `configure` reads them and refuses a key it does not know (`ERR_UNKNOWN_GENERATOR_OPTION`, +naming the options it takes). The shipped generators take none, so any option given to one fails the +run, also a run `--generators` narrows to other generators. A project with no such file runs every +generator. A generator that leaves the list has its files removed on the next `gen` (a file somebody edited is refused by name instead), and the run fails, naming the file, for a name nothing offers, a duplicate, an unknown key, or a generator listed without one it -builds on (`client` needs `entity`; `commands` needs both). `cargo meta gen --list` shows each generator +builds on (`client`, `render-helper` and `output-parser` need `entity`; `commands` needs `entity` and `client`). `cargo meta gen --list` shows each generator as `[configured]` or `[not configured]`, and `--generators` narrows one run to some of the list. **Exit codes** are the ones every port's tool uses: 0 success, 1 the run failed (a model that does not @@ -97,14 +102,21 @@ generated/ shop/ entity the model: structs, enums, create and patch bodies, validate() shop_client/ client a typed HTTP client and list query per served entity shop_cli/ commands clap commands over the client + shop_prompts/ render-helper a typed render function per template (when the package has templates) + shop_parsers/ output-parser a strict parse and a tolerant extract per responding prompt + shop_formats/ output-prompt the output-format fragment per responding prompt meta_support/ entity exact decimals, durations, patch helpers, the validation checks meta_client/ client the HTTP transport (reqwest), errors, the query builder meta_cli/ commands what a command uses to build a body and a query ``` The generated crates depend on each other by path and on ordinary crates.io crates (`serde`, -`serde_json`, `reqwest`, `clap`). **They import nothing from MetaObjects**: the shared code is written -into the three `meta_*` crates as source you can read and change. Add the crates you want to your +`serde_json`, `reqwest`, `clap`). **The model, client and command crates import nothing from +MetaObjects**: the shared code is written into the three `meta_*` crates as source you can read and +change. The three prompt-tier crates import `metaobjects-render`, an ordinary Apache-2.0 library (the +render engine and the reply parser), as every port's prompt tier imports its render package. It is not +on crates.io yet, so until it is, point a `[patch.crates-io]` entry at a checkout's +`server/rust/metaobjects-render`. Add the crates you want to your workspace as path dependencies: ```toml @@ -224,6 +236,61 @@ refused, not dropped. `commands` with `rust` as their only port, so the difference is stated in the one place every port checks itself against, not left to be discovered. +### `render-helper`: a render function per template + +For each `template.output` and `template.prompt` the generator writes a typed function in a +`_prompts` crate. A document template (the default `@kind`, and every prompt) gets +`render_(&payload, &provider) -> Result`, escaped for its `@format` and held +to its `@maxChars`. An email template gets one returning an `EmailDocument`: the subject and the text +body rendered as text, the HTML body as HTML. The payload is the value object's own struct from the +`entity` crate ([ADR-0056](../../spec/decisions/ADR-0056-value-object-types-are-generated-once.md)). + +```rust +use metaobjects_render::FilesystemProvider; + +let provider = FilesystemProvider::new("prompts"); +let text = shop_prompts::render_order_summary(&summary, &provider)?; +``` + +**The drift gate runs when you generate.** Each body is read from the project's template directory +(`prompts/` when it exists, else `templates/`) and checked against the payload's fields, nested value +objects included. A variable the payload does not have fails `cargo meta gen` with +`ERR_VAR_NOT_ON_PAYLOAD`, naming the template, the reference and the variable. The field tree is also +written into the function, and every render checks the body again, so a body edited after generation, +or served by another provider, fails the render instead of rendering a blank. A body is an input of +the generator: editing one regenerates the crate even when the model did not change. + +### `output-parser` and `output-prompt`: the reply to a prompt + +A `template.prompt` with `@responseRef` names the value object its answer is read into +([ADR-0052](../../spec/decisions/ADR-0052-template-direction-outbound-vs-inbound.md)). `output-parser` writes, in a +`_parsers` crate: + +- `parse_(text) -> Result`, the strict parse: the reply must be exactly + the JSON of a `T`. A prompt whose `@responseFormat` is `xml` has none + ([ADR-0053](../../spec/decisions/ADR-0053-inbound-response-format.md)). +- `extract_(text, &opts) -> Extracted`, the tolerant read of a raw model reply. It never + fails: `value` is the answer when the extracted fields make a complete `T`, and `outcome.report` + classifies every field either way. +- `_schema()`, the extract descriptor both read with, derived from the response object as every + port derives it: nested value objects, numeric ranges and element counts from the field's + validators, `@enumAlias`, `@coerceDefault`, `@default`, `@normalize` and `@xmlText`. + +`output-prompt` writes, in a `_formats` crate, `render__format(&overrides) -> String`: +the part of the prompt that tells the model how to shape its answer, in the reply's syntax and the +prompt's `@promptStyle` (`guide`, `inline` or `exampleOnly`), with each field's `@example`, +`@instruction` and `@enumDoc`. Its root is the response object's name, the root the parser looks for. + +```rust +let fragment = shop_formats::render_judge_format(&PromptOverrides::default()); +let reply = call_the_model(&format!("{prompt}\n\n{fragment}"))?; +let got = shop_parsers::extract_judge(&reply, &ExtractOptions::default()); +match got.value { + Some(verdict) => use_it(verdict), + None => log_the_report(&got.outcome.report), +} +``` + ### Owning a generator A generator is a reference helper @@ -246,6 +313,14 @@ transport too. Every file in `codegen/` is an input of the skip key, whether `ej added it (a module beside the generator list, say), so editing any of them regenerates. Only the crate's build directory (`codegen/target`) and its `Cargo.lock` are left out. +An owned generator need not be a copy. Each shipped generator has a parts trait (`EntityParts`, +`ClientParts`, `CommandsParts`, `RenderHelperParts`, `OutputParserParts`, `OutputPromptParts`) with +one default method per piece of its output (a crate's manifest, its `lib.rs`, one entity's file, one +item), and a generator of your own implements it, overrides the piece it changes and returns +`self.render(ctx)` from `generate`; every other file is the shipped generator's, byte for byte. An +override can call the shipped piece, a public function of the same module and name. The traits carry +the same no-stability caveat as the rest of the engine API (ADR-0063 item 7). + `cargo meta gen --list` shows each owned copy as `identical`, or as `DIFFERS` with how many shipped lines it lacks and how many are its own. `cargo meta eject --undo` removes copies that are still identical (`--force` discards an edited one) @@ -276,17 +351,20 @@ outright. | `yaml-conformance` | 18 of 19. The one on the ledger, `yaml-ref-root-escape`, waits for the root-level `::` reference rules of [ADR-0059](../../spec/decisions/ADR-0059-references-resolve-once-after-the-tree.md), which are reference resolution, not a validation pass. | | `source-resolution-conformance` | all 28 cases | | `naming-conformance` | all of it | -| `codegen-skip-conformance` | every case the port can meet, on both columns (what `gen` must do and what a local `verify --codegen` may do), including an edited owned generator and a forced CI verify ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)). The three it cannot meet (two about templates, one about the three-way merge) are named with their reason in the runner. | +| `codegen-skip-conformance` | every case the port can meet, on both columns (what `gen` must do and what a local `verify --codegen` may do), including an edited owned generator and a forced CI verify ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)). The one it cannot meet, about the three-way merge, is named with its reason in the runner; the template cases (a body edited, a body added) run. | | `rules-check-conformance` | all 16 cases: the diagnostics (severity, code, node address, message text) and the summary of the `verify` business-rules gate, under each case's `rules` and `verify` settings | | `validation-conformance` | every case, through the generated `validate()`: each payload is read into the generated create body by a probe the real compiler builds | | `decimal-wire`, `duration-wire` | every vector, against the code the support crate carries | -| `writer-conformance` | every `core` case of the code writer ([ADR-0063](../../spec/decisions/ADR-0063-generators-own-layout.md)) | +| `writer-conformance` | every `core` and `rust` case of the code writer ([ADR-0063](../../spec/decisions/ADR-0063-generators-own-layout.md)); each `rust` case is a rustfmt fixed point | +| `render-conformance` | every case, through `metaobjects_render::render`: escaping per format, partials, `has` and `-last`, the `maxChars` budget | +| `template-output-render-conformance` | the welcome page and email, the nested payload and the cross-package payloads, rendered through generated `render-helper` crates that a probe builds; the drift cases fail `gen`, and a body edited after generation fails the render | +| `verify-conformance` | all 45 cases through `cargo meta verify --templates`'s check. Two (`verify-set-delimiter-clean`, `verify-set-delimiter-drift`) carry a Rust expectation file, as other ports' files do where their engine reads a set-delimiter tag differently. | | `generator-registry-conformance` | the shipped generators are exactly the registry's `rust` entries, with its tier and layer, and the eject contract's census, completeness and depth hold (ADR-0034 Amendment 8) | | `render-conformance` | every case, byte-identical, through `metaobjects_render::render` (the Mustache engine underneath is `mustache-ng`) | | `extract-conformance` | all 58 cases, through `metaobjects_render::extract::extract` | | `output-prompt-conformance` | all 17 cases in all three `@promptStyle` styles, with the extract round trip, through `metaobjects_render::prompt::render_output_format` | -Two gates have no corpus of their own: +Three gates have no corpus of their own: - **The codegen-compile gate.** The small two-package model and the public fitness model are generated by every shipped generator, each into a scratch Cargo workspace that `cargo check` builds and @@ -296,9 +374,15 @@ Two gates have no corpus of their own: when cargo needed a package that lockfile does not name. - **The scale gate.** Twenty copies of the fitness model, each its own package: the output must be exactly twenty times one copy's files and no more than twenty times its bytes, one copy's output has - a byte budget and a longest-file budget, and all sixty-three crates must build. The times are + a byte budget and a longest-file budget, and all hundred and twenty-three crates must build. The times are printed; their ceilings are set far above a normal run and catch a step that stopped scaling, not a slow machine. +- **The layout ratchet** (ADR-0063 item 6, `metaobjects-codegen/tests/layout_ratchet.rs`). It parses + every source file under `metaobjects-codegen/src/` except the writer, which covers the generators and + the fixed text in `emitted/`, and it fails on a line break or an indentation run typed outside the + writer. `tests/layout_ratchet/allowlist.json` names the files that write something other than + generated code (terminal messages, hash input, JSON), each with a reason. The list only shrinks: the + test compares it with the copy at the branch's merge base. Rust is not yet a column in the [per-corpus table](../CONFORMANCE.md#per-corpus-totals); it joins when the port runs the persistence and API-contract corpora, which need a service tier the port does @@ -317,16 +401,14 @@ regeneration, peak memory), so a port's speed can be tracked per feature next to ## What does not exist yet -- **Other generators.** There is no server-side route, ORM or repository generator, no template - generator and no documentation generator. Projections and reports get no client yet. -- **Other gates.** `verify --codegen` and the business-rules gate are the ones it has. There is no - template gate, no requirement gate and no `fmt`. +- **Other generators.** There is no server-side route, ORM or repository generator and no + documentation generator. Projections and reports get no client yet, and a template over a + sourceless `object.projection` payload gets no render function. +- **Other gates.** `verify --codegen`, `verify --templates` and the business-rules gate are the ones + it has. There is no requirement gate and no `fmt`. - **A three-way merge.** A hand-edited generated file is refused by name, as in every port but TypeScript; change the model or own the generator instead. - **The service tier.** No `ObjectManager`, no persistence drivers and no web adapters. -- **Prompt codegen.** The render engine and the reply parser exist as a library; no generator yet - writes a template's payload type or its response parser from the model, and there is no template - gate in `verify`. - **Publication.** The crates are publishable and the lane proves they package (`cargo publish --dry-run`), but nothing is published: there is no crates.io release yet, and publishing waits for the owner's go ([ADR-0065](../../spec/decisions/ADR-0065-rust-is-the-sixth-port.md) Amendment 3). diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index 06727f26e9..5ef25b7491 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -21,21 +21,21 @@ "tier": "native", "layer": "capability", "eject": "full", - "ports": ["typescript", "csharp", "java", "kotlin", "python"] + "ports": ["typescript", "csharp", "java", "kotlin", "python", "rust"] }, "output-prompt": { "concept": "Per-template output-format prompt fragment generator.", "tier": "native", "layer": "capability", "eject": "full", - "ports": ["typescript", "csharp", "java", "kotlin", "python"] + "ports": ["typescript", "csharp", "java", "kotlin", "python", "rust"] }, "render-helper": { - "concept": "Per-renderable-template render helper (typed render wrappers). BOTH template subtypes render (ADR-0052), so on csharp/java/kotlin/python this covers template.output AND template.prompt; on typescript a prompt's render handle is the separate `prompt-render` generator instead, so typescript's render-helper is template.output only. Same stable name, one concept, one per-port split — stated here because the concept line is shared and the split is not.", + "concept": "Per-renderable-template render helper (typed render wrappers). BOTH template subtypes render (ADR-0052), so on csharp/java/kotlin/python/rust this covers template.output AND template.prompt; on typescript a prompt's render handle is the separate `prompt-render` generator instead, so typescript's render-helper is template.output only. Same stable name, one concept, one per-port split — stated here because the concept line is shared and the split is not.", "tier": "native", "layer": "capability", "eject": "full", - "ports": ["typescript", "csharp", "java", "kotlin", "python"] + "ports": ["typescript", "csharp", "java", "kotlin", "python", "rust"] }, "extractor": { "concept": "Per-template typed extract helper: tolerant recovery of the typed response from dirty model text; throws only when a @required field is lost.", @@ -133,7 +133,7 @@ "ports": ["typescript"] }, "prompt-render": { - "concept": "Per-template.prompt render handle over the render engine, aggregated into one module. TYPESCRIPT ONLY by design: the other four ports emit a prompt's render helper from `render-helper` (see its note) rather than a second generator.", + "concept": "Per-template.prompt render handle over the render engine, aggregated into one module. TYPESCRIPT ONLY by design: the other ports emit a prompt's render helper from `render-helper` (see its note) rather than a second generator.", "tier": "native", "layer": "capability", "eject": "full", @@ -601,8 +601,10 @@ "engine": [ "metaobjects_codegen::emitted", "metaobjects_codegen::generator", + "metaobjects_codegen::inbound", "metaobjects_codegen::names", "metaobjects_codegen::plan", + "metaobjects_codegen::render", "metaobjects_codegen::writer" ] } diff --git a/fixtures/verify-conformance/verify-set-delimiter-clean/expected-drift.rust.json b/fixtures/verify-conformance/verify-set-delimiter-clean/expected-drift.rust.json new file mode 100644 index 0000000000..751ee879de --- /dev/null +++ b/fixtures/verify-conformance/verify-set-delimiter-clean/expected-drift.rust.json @@ -0,0 +1 @@ +[ { "code": "ERR_TEMPLATE_SYNTAX", "path": "<% %>" } ] diff --git a/fixtures/verify-conformance/verify-set-delimiter-drift/expected-drift.rust.json b/fixtures/verify-conformance/verify-set-delimiter-drift/expected-drift.rust.json new file mode 100644 index 0000000000..8782129305 --- /dev/null +++ b/fixtures/verify-conformance/verify-set-delimiter-drift/expected-drift.rust.json @@ -0,0 +1 @@ +[ { "code": "ERR_VAR_NOT_ON_PAYLOAD", "path": "nope" }, { "code": "ERR_TEMPLATE_SYNTAX", "path": "<% %>" } ] diff --git a/fixtures/writer-conformance/README.md b/fixtures/writer-conformance/README.md index cc286b3465..46b995ea62 100644 --- a/fixtures/writer-conformance/README.md +++ b/fixtures/writer-conformance/README.md @@ -7,7 +7,7 @@ format are in [`spec/code-writer.md`](../../spec/code-writer.md). - `cases/*.json` with `"dialect": "core"` pin the language-neutral core: indentation, blocks, blank-line requests, snippets, fit-or-break lists, line endings and the error codes. Every port's writer runs them with the options the case states. -- Cases with a language dialect (`"dialect": "typescript"`, `"java"`, `"python"`, `"csharp"`) pin that +- Cases with a language dialect (`"dialect": "typescript"`, `"java"`, `"python"`, `"csharp"`, `"rust"`) pin that language's writer: import or `using` collection and ordering, doc comments and its defaults. A runner runs the `core` cases and its own dialect's, and skips the others by name. @@ -16,7 +16,7 @@ Runners: - TypeScript, `server/typescript/packages/codegen-ts/test/writer-conformance.test.ts` (`core` and `typescript`). - Java, `server/java/codegen-base/src/test/java/com/metaobjects/generator/writer/WriterConformanceTest.java` (`core` and `java`). - Python, `server/python/tests/codegen/test_writer_conformance.py` (`core` and `python`). -- Rust, `server/rust/metaobjects-codegen/tests/writer_conformance.rs` (`core`). +- Rust, `server/rust/metaobjects-codegen/tests/writer_conformance.rs` (`core` and `rust`). - C#, `server/csharp/MetaObjects.Codegen.Tests/WriterConformanceTests.cs` (`core` and `csharp`). The ports without a writer yet (Kotlin) run the `core` cases when their writers @@ -25,3 +25,9 @@ land, and add cases for their own dialect beside these. The `csharp` ops are `header` (lines), `using`, `usingStatic` (a namespace or type), `usingAlias` (alias, target) and `docSummary` (lines), beside the core ops. A `csharp` case may state `"options": {"usingOrder": "sorted"}`; the default order is the order the generator named them. + +The `rust` ops are `use` (a path, then the names), `doc` and `prose` (one text each), +`docBreak` and `assign` (a head, then parts), beside the core ops. A `rust` case states no +options and takes the dialect's defaults. Every `rust` case's expected output is unchanged by +`rustfmt` (edition 2021) under the `rustfmt.toml` every generated crate carries +(`RUSTFMT_TOML` in the Rust writer): rustfmt is the oracle, since generated Rust is held to it. diff --git a/fixtures/writer-conformance/cases/rust-assign-breaks.json b/fixtures/writer-conformance/cases/rust-assign-breaks.json new file mode 100644 index 0000000000..1e3b3c4510 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-assign-breaks.json @@ -0,0 +1,34 @@ +{ + "description": "When the right-hand side fits on neither line, `assign` keeps it on the head's line and breaks its last list.", + "dialect": "rust", + "ops": [ + [ + "assign", + "pub static FIELDS: &[PayloadField] =", + [ + "&", + { + "list": { + "open": "[", + "items": [ + "PayloadField::scalar(\"field_number_00\")", + "PayloadField::scalar(\"field_number_01\")", + "PayloadField::scalar(\"field_number_02\")", + "PayloadField::scalar(\"field_number_03\")" + ], + "close": "]" + } + }, + ";" + ] + ] + ], + "expected": [ + "pub static FIELDS: &[PayloadField] = &[", + " PayloadField::scalar(\"field_number_00\"),", + " PayloadField::scalar(\"field_number_01\"),", + " PayloadField::scalar(\"field_number_02\"),", + " PayloadField::scalar(\"field_number_03\"),", + "];" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-assign-fits.json b/fixtures/writer-conformance/cases/rust-assign-fits.json new file mode 100644 index 0000000000..c92368a9c5 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-assign-fits.json @@ -0,0 +1,37 @@ +{ + "description": "`assign` writes `head rhs` on one line when it fits.", + "dialect": "rust", + "ops": [ + [ + "open", + "fn main() {" + ], + [ + "assign", + "let x =", + [ + "f", + { + "list": { + "open": "(", + "items": [ + "a", + "b" + ], + "close": ")" + } + }, + ";" + ] + ], + [ + "close", + "}" + ] + ], + "expected": [ + "fn main() {", + " let x = f(a, b);", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-assign-next-line.json b/fixtures/writer-conformance/cases/rust-assign-next-line.json new file mode 100644 index 0000000000..27946f9c2c --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-assign-next-line.json @@ -0,0 +1,47 @@ +{ + "description": "When `head rhs` does not fit but the right-hand side alone fits one level in, `assign` writes the head and then the right-hand side on the next line, an array as well as a call, as rustfmt does under the generated crates' settings.", + "dialect": "rust", + "ops": [ + [ + "assign", + "pub static A_RATHER_LONG_STATIC_NAME_FOR_THE_FIELDS_HERE: PayloadField =", + [ + "PayloadField::scalar", + { + "list": { + "open": "(", + "items": [ + "\"first_name\"" + ], + "close": ")" + } + }, + ";" + ] + ], + [ + "assign", + "pub static A_RATHER_LONG_STATIC_NAME_FOR_THE_FIELDS: &[PayloadField] =", + [ + "&", + { + "list": { + "open": "[", + "items": [ + "PayloadField::scalar(\"first_name\")", + "PayloadField::scalar(\"surname\")" + ], + "close": "]" + } + }, + ";" + ] + ] + ], + "expected": [ + "pub static A_RATHER_LONG_STATIC_NAME_FOR_THE_FIELDS_HERE: PayloadField =", + " PayloadField::scalar(\"first_name\");", + "pub static A_RATHER_LONG_STATIC_NAME_FOR_THE_FIELDS: &[PayloadField] =", + " &[PayloadField::scalar(\"first_name\"), PayloadField::scalar(\"surname\")];" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-defaults.json b/fixtures/writer-conformance/cases/rust-defaults.json new file mode 100644 index 0000000000..55448b16b5 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-defaults.json @@ -0,0 +1,81 @@ +{ + "description": "The Rust dialect indents four spaces, breaks at 100 columns and puts a comma after the last item of a broken list, as rustfmt does.", + "dialect": "rust", + "ops": [ + [ + "open", + "fn main() {" + ], + [ + "line", + "let names = ", + { + "list": { + "open": "vec![", + "items": [ + "\"n00\"", + "\"n01\"", + "\"n02\"", + "\"n03\"", + "\"n04\"", + "\"n05\"", + "\"n06\"", + "\"n07\"", + "\"n08\"", + "\"n09\"", + "\"n10\"", + "\"n11\"", + "\"n12\"", + "\"n13\"", + "\"n14\"", + "\"n15\"", + "\"n16\"", + "\"n17\"", + "\"n18\"", + "\"n19\"", + "\"n20\"", + "\"n21\"", + "\"n22\"", + "\"n23\"" + ], + "close": "]" + } + }, + ";" + ], + [ + "close", + "}" + ] + ], + "expected": [ + "fn main() {", + " let names = vec![", + " \"n00\",", + " \"n01\",", + " \"n02\",", + " \"n03\",", + " \"n04\",", + " \"n05\",", + " \"n06\",", + " \"n07\",", + " \"n08\",", + " \"n09\",", + " \"n10\",", + " \"n11\",", + " \"n12\",", + " \"n13\",", + " \"n14\",", + " \"n15\",", + " \"n16\",", + " \"n17\",", + " \"n18\",", + " \"n19\",", + " \"n20\",", + " \"n21\",", + " \"n22\",", + " \"n23\",", + " ];", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-doc-keeps-lines.json b/fixtures/writer-conformance/cases/rust-doc-keeps-lines.json new file mode 100644 index 0000000000..d94e97be37 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-doc-keeps-lines.json @@ -0,0 +1,20 @@ +{ + "description": "`doc` writes an author's text as `///` lines, one per line of the text, a bare `///` for an empty line and never re-wrapped; the text's own leading and trailing blank lines are dropped.", + "dialect": "rust", + "ops": [ + [ + "doc", + "\nThe customer.\n\nSee the billing guide for how a customer is charged, which is a long sentence an author wrote on one line.\n" + ], + [ + "line", + "pub struct Customer;" + ] + ], + "expected": [ + "/// The customer.", + "///", + "/// See the billing guide for how a customer is charged, which is a long sentence an author wrote on one line.", + "pub struct Customer;" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-prose-wraps.json b/fixtures/writer-conformance/cases/rust-prose-wraps.json new file mode 100644 index 0000000000..12a134e8d1 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-prose-wraps.json @@ -0,0 +1,38 @@ +{ + "description": "`prose` writes generated text as `///` lines wrapped at a word boundary so no line passes the width; each line of the text is its own paragraph, and `docBreak` writes the bare `///` between two paragraphs.", + "dialect": "rust", + "ops": [ + [ + "open", + "impl A {" + ], + [ + "prose", + "Parse a reply to the prompt that is exactly the JSON of the response type, with nothing around it at all." + ], + [ + "docBreak" + ], + [ + "prose", + "# Errors" + ], + [ + "line", + "fn f() {}" + ], + [ + "close", + "}" + ] + ], + "expected": [ + "impl A {", + " /// Parse a reply to the prompt that is exactly the JSON of the response type, with nothing", + " /// around it at all.", + " ///", + " /// # Errors", + " fn f() {}", + "}" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-use-fills.json b/fixtures/writer-conformance/cases/rust-use-fills.json new file mode 100644 index 0000000000..d355473f67 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-use-fills.json @@ -0,0 +1,30 @@ +{ + "description": "A `use` past 100 columns breaks after the brace and fills the names onto lines one level in, each followed by a comma, as many to a line as fit, then `};` on its own line.", + "dialect": "rust", + "ops": [ + [ + "use", + "metaobjects_render::extract", + "Name00", + "Name01", + "Name02", + "Name03", + "Name04", + "Name05", + "Name06", + "Name07", + "Name08", + "Name09", + "Name10", + "Name11", + "Name12", + "Name13" + ] + ], + "expected": [ + "use metaobjects_render::extract::{", + " Name00, Name01, Name02, Name03, Name04, Name05, Name06, Name07, Name08, Name09, Name10, Name11,", + " Name12, Name13,", + "};" + ] +} diff --git a/fixtures/writer-conformance/cases/rust-use-fits.json b/fixtures/writer-conformance/cases/rust-use-fits.json new file mode 100644 index 0000000000..e494212fb8 --- /dev/null +++ b/fixtures/writer-conformance/cases/rust-use-fits.json @@ -0,0 +1,21 @@ +{ + "description": "A `use` of several names that fits is one line with the names in braces; a `use` of one name has no braces.", + "dialect": "rust", + "ops": [ + [ + "use", + "serde", + "Serialize" + ], + [ + "use", + "std::collections", + "BTreeMap", + "HashMap" + ] + ], + "expected": [ + "use serde::Serialize;", + "use std::collections::{BTreeMap, HashMap};" + ] +} diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 055675a827..0eb2cea9ae 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -559,7 +559,7 @@ gate_site_reference() { bun_install && bun scripts/build-site-reference.ts --che # exercised) are the ones worth a test at all. See scripts/maven-coordinate.mjs. # And the publish workflows' tag check (scripts/check-release-tag.mjs), whose test also reads # each real manifest, so a layout change fails here rather than on a release tag. -gate_release_tag() { bun test scripts/finish-release.test.ts scripts/eject-release-gate.test.ts && node scripts/test-maven-coordinate.mjs && node scripts/test-prerelease-version.mjs && node scripts/test-check-release-tag.mjs && node scripts/test-changelog-promote.mjs && node scripts/test-release-branch.mjs && bash tools/prerelease/test-prerelease-link.sh && bash tools/prerelease/test-estate-run.sh; } +gate_release_tag() { bun test scripts/finish-release.test.ts scripts/eject-release-gate.test.ts && node scripts/test-maven-coordinate.mjs && node scripts/test-prerelease-version.mjs && node scripts/test-check-release-tag.mjs && node scripts/test-changelog-promote.mjs && node scripts/test-release-branch.mjs && node scripts/test-rust-release.mjs && bash tools/prerelease/test-prerelease-link.sh && bash tools/prerelease/test-estate-run.sh; } # ── repo-root scripts/ typechecks ───────────────────────────────────────────── # `bun test` transpiles per file and never typechecks, and `bun run --filter '*' diff --git a/scripts/lib/rust-release.mjs b/scripts/lib/rust-release.mjs new file mode 100644 index 0000000000..f9857b26eb --- /dev/null +++ b/scripts/lib/rust-release.mjs @@ -0,0 +1,146 @@ +// The Rust crates' part of a release (ADR-0065 Amendment 3): whether this cut publishes them, +// in what order, and the version edit that puts them on the shared line. +// +// Pure functions, so `scripts/test-rust-release.mjs` can hold every rule to cases; +// `scripts/release.mjs` supplies what git, cargo and crates.io answer. +// +// The rules are the ones every registry already follows (docs/RELEASING.md): +// +// - Publish what changed. The crates publish only when a file they ship changed since the last +// `rust-v` tag, and adopt the shared version when they do, skipping the numbers they +// sat out. With no such tag the crates have never shipped, so the cut publishes them. +// - A change to `expected-registry.json` (the vocabulary every port byte-matches) publishes +// every registry, the crates included, changed file or not. +// - The crates publish in dependency order, each after the crates it depends on, because +// crates.io refuses a crate whose dependency is not yet there. + +/** The workspace that holds the crates, relative to the repository root. */ +export const RUST_DIR = "server/rust"; + +/** The tag a release cuts for the crates: `rust-v1.3.0`. */ +export const RUST_TAG_PREFIX = "rust-v"; + +/** The manifest whose change makes every registry publish. */ +export const EXPECTED_REGISTRY = "fixtures/registry-conformance/expected-registry.json"; + +/** What a crate directory holds that is not shipped in it: tests, examples, benches, baselines. */ +const NOT_SHIPPED = new Set(["tests", "examples", "benches", "baselines"]); + +/** + * Whether a repository path is part of what the Rust crates ship: a crate's sources, build + * script, data, manifest, README or licence, or the workspace manifest and lockfile. A + * crate's tests, examples, benches and benchmark baselines are not. + */ +export function isRustProductPath(path) { + const prefix = `${RUST_DIR}/`; + if (!path.startsWith(prefix)) return false; + const parts = path.slice(prefix.length).split("/"); + if (parts.length === 1) return parts[0] === "Cargo.toml" || parts[0] === "Cargo.lock"; + return !NOT_SHIPPED.has(parts[1]); +} + +/** `1.3.0` or `1.3.0-rc.2` as numbers to compare: a final release sorts after its candidates. */ +function versionKey(v) { + const m = v.match(/^(\d+)\.(\d+)\.(\d+)(?:-rc\.(\d+))?$/); + if (!m) return null; + return [Number(m[1]), Number(m[2]), Number(m[3]), m[4] === undefined ? Infinity : Number(m[4])]; +} + +function compareKeys(a, b) { + for (let i = 0; i < 4; i++) if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1; + return 0; +} + +/** The newest `rust-v*` tag among `tags`, or null when the crates have never been tagged. */ +export function newestRustTag(tags) { + let best = null; + for (const t of tags) { + if (!t.startsWith(RUST_TAG_PREFIX)) continue; + const key = versionKey(t.slice(RUST_TAG_PREFIX.length)); + if (key && (best === null || compareKeys(key, best.key) > 0)) best = { tag: t, key }; + } + return best?.tag ?? null; +} + +/** + * Whether this cut publishes the crates. + * + * @param {{lastTag: string|null, changedPaths: string[], mode?: "auto"|"publish"|"skip"}} input + * `changedPaths` are the repository paths changed since `lastTag` (ignored without one); + * `mode` is the release's `--crates` choice, `auto` unless the person cutting it overrode. + * @returns {{publish: boolean, reason: string}} + */ +export function rustPublishDecision({ lastTag, changedPaths, mode = "auto" }) { + if (mode === "publish") return { publish: true, reason: "--crates=publish" }; + if (mode === "skip") return { publish: false, reason: "--crates=skip" }; + if (mode !== "auto") throw new Error(`unknown --crates mode "${mode}" (auto, publish or skip)`); + if (lastTag === null) return { publish: true, reason: "the crates have never been published" }; + if (changedPaths.includes(EXPECTED_REGISTRY)) { + return { publish: true, reason: `${EXPECTED_REGISTRY} changed since ${lastTag}, which publishes every registry` }; + } + const shipped = changedPaths.filter(isRustProductPath); + if (shipped.length > 0) { + const more = shipped.length > 3 ? ` and ${shipped.length - 3} more` : ""; + return { publish: true, reason: `changed since ${lastTag}: ${shipped.slice(0, 3).join(", ")}${more}` }; + } + return { publish: false, reason: `no file the crates ship changed since ${lastTag}` }; +} + +/** + * The publishable workspace crates in the order they must publish: each after every crate it + * depends on. `metadata` is what `cargo metadata --format-version 1 --no-deps` prints. A + * dev-dependency does not order anything: cargo leaves one without a version out of the + * published manifest, and one with a version needs only to exist by the time someone runs + * the crate's tests. Ties break on the name, so the order is the same on every machine. + * + * @throws when the crates depend on each other in a cycle. + */ +export function rustPublishOrder(metadata) { + const members = new Set(metadata.workspace_members ?? []); + const crates = metadata.packages.filter( + (p) => (members.size === 0 || members.has(p.id)) && !(Array.isArray(p.publish) && p.publish.length === 0), + ); + const names = new Set(crates.map((p) => p.name)); + const needs = new Map(crates.map((p) => [p.name, new Set( + p.dependencies + .filter((d) => d.kind !== "dev" && names.has(d.name) && d.name !== p.name) + .map((d) => d.name), + )])); + const order = []; + while (needs.size > 0) { + const ready = [...needs].filter(([, deps]) => [...deps].every((d) => !needs.has(d))).map(([n]) => n).sort(); + if (ready.length === 0) { + throw new Error(`the Rust crates depend on each other in a cycle: ${[...needs.keys()].sort().join(", ")}`); + } + for (const n of ready) { order.push(n); needs.delete(n); } + } + return order; +} + +/** + * A crate manifest with every version the release sets moved to `version`: the + * `[workspace.package]` version, and the version requirement on each dependency given by + * `path` (a sibling crate). Nothing else in the text changes. + */ +export function bumpRustManifest(text, version) { + let out = ""; + let section = ""; + for (const line of text.split(/(?<=\n)/)) { + const header = line.match(/^\s*\[([^\]]+)\]\s*$/); + if (header) section = header[1].trim(); + let next = line; + if (section === "workspace.package") next = next.replace(/^(\s*version\s*=\s*")[^"]*(")/, `$1${version}$2`); + if (/\bpath\s*=/.test(next)) next = next.replace(/(\bversion\s*=\s*")[^"]*(")/, `$1${version}$2`); + out += next; + } + return out; +} + +/** + * Whether crates.io already holds `version` of a crate, from the JSON its + * `/api/v1/crates/` endpoint answers. A crate that does not exist answers 404, which + * the caller reads as free before calling this. + */ +export function crateVersionTaken(json, version) { + return (json.versions ?? []).some((v) => v.num === version); +} diff --git a/scripts/release.mjs b/scripts/release.mjs index b53b0e77e5..99b951d046 100644 --- a/scripts/release.mjs +++ b/scripts/release.mjs @@ -1,10 +1,16 @@ #!/usr/bin/env bun -// One-command lockstep release of the @metaobjectsdev/* npm packages. +// One-command lockstep release of the @metaobjectsdev/* npm packages, and of the Rust crates +// when they have changed (ADR-0065 Amendment 3). // // bun run release # do it (stops for confirm before publish) // bun run release --dry-run # everything except publish/tag/push // bun run release --yes # skip the interactive confirm (CI) // bun run release --preflight-only # run PHASE 0 and stop +// bun run release --crates=publish|skip # override whether the crates ship +// +// The Rust crates publish to crates.io behind the same confirm, after npm, in dependency +// order, when a file they ship changed since the last `rust-v*` tag (or they never shipped, +// or expected-registry.json moved). scripts/lib/rust-release.mjs holds those rules. // // --preflight-only is NOT --dry-run. --dry-run still runs Phase 1, which writes the // new version into every package.json of the lockstep set, rebuilds, and regenerates bun.lock — @@ -32,6 +38,10 @@ import { promoteChangelog } from "./lib/changelog-promote.mjs"; import { createInterface } from "node:readline/promises"; import { publishSet } from "./publish-set.mjs"; import { mavenVersion } from "./maven-coordinate.mjs"; +import { + RUST_DIR, RUST_TAG_PREFIX, bumpRustManifest, crateVersionTaken, newestRustTag, rustPublishDecision, + rustPublishOrder, +} from "./lib/rust-release.mjs"; import { ejectReleaseRefusalAt } from "./eject-release-gate.mjs"; import { releaseBranchRefusal, newestNpmReleaseTag, latestRegressionRefusal, unmergedMaintenanceRefusal, @@ -41,6 +51,7 @@ const VERSION = process.argv[2]; const DRY = process.argv.includes("--dry-run"); const PREFLIGHT_ONLY = process.argv.includes("--preflight-only"); const YES = process.argv.includes("--yes"); +const CRATES_MODE = process.argv.find((a) => a.startsWith("--crates="))?.slice("--crates=".length) ?? "auto"; // A scratch root for the post-publish smoke that no stray node_modules can shadow. // See PHASE 11. Kept beside the other helpers so the reason travels with the call. @@ -158,6 +169,50 @@ if (taken.length) ok(`preflight: on ${branch}, synced, ${VERSION} free on all ${set.length} packages`); ok(`lockstep set @ ${current}: ${set.length} packages → ${VERSION}`); +// --- the Rust crates: do they ship this cut, and can they? ----------------- +// Decided here, with npm's checks, for the same reason: everything after the version bump is +// committed and pushed before the first publish, so a dead token or a taken number found at +// the publish step strands the release half-shipped. +const rustTag = newestRustTag(out("git tag -l").split("\n")); +let rust; +try { + rust = rustPublishDecision({ + lastTag: rustTag, + changedPaths: rustTag ? out(`git diff --name-only ${rustTag} HEAD`).split("\n").filter(Boolean) : [], + mode: CRATES_MODE, + }); +} catch (e) { die(e.message); } +let crates = []; +if (!rust.publish) { + ok(`crates.io: sits this release out (${rust.reason})`); +} else { + crates = rustPublishOrder(JSON.parse(out(`cd ${RUST_DIR} && cargo metadata --format-version 1 --no-deps --locked`))); + // cargo reads a token from CARGO_REGISTRY_TOKEN or from the file `cargo login` writes. + const cargoHome = process.env.CARGO_HOME ?? join(homedir(), ".cargo"); + const credentials = ["credentials.toml", "credentials"].map((f) => join(cargoHome, f)).find(existsSync); + if (!process.env.CARGO_REGISTRY_TOKEN && !(credentials && /\btoken\s*=/.test(readFileSync(credentials, "utf8")))) { + die("crates.io has no token: publishing the crates would fail after the version bump is\n" + + " already committed. Run `cargo login` with a crates.io API token that has the\n" + + " publish-update scope (and publish-new for a crate's first release), or set\n" + + " CARGO_REGISTRY_TOKEN. Pass --crates=skip to cut without the crates."); + } + // crates.io asks automated clients to name themselves in the User-Agent. + const agent = { "user-agent": "metaobjects-release (https://github.com/metaobjectsdev/metaobjects)" }; + const takenCrates = (await Promise.all(crates.map(async (name) => { + try { + const r = await fetch(`https://crates.io/api/v1/crates/${name}`, { headers: agent, signal: AbortSignal.timeout(15_000) }); + if (r.status === 404) return null; // never published = free + if (!r.ok) die(`crates.io answered HTTP ${r.status} for ${name} — cannot verify ${VERSION} is free`); + return crateVersionTaken(await r.json(), VERSION) ? name : null; + } catch { die(`could not reach crates.io to verify ${VERSION} is free (${name})`); } + }))).filter(Boolean); + if (takenCrates.length) { + die(`${VERSION} is already published on crates.io for:\n ${takenCrates.join("\n ")}\n` + + "crates.io versions are permanent (a yank does not free the number) — pick the next free version."); + } + ok(`crates.io: ${crates.length} crates ship (${rust.reason}); ${VERSION} free on all of them`); +} + // The showcase corpus is what metaobjects.dev publishes as "real `meta gen` output", // so a stale tree is a stale claim on a public page. Checked BEFORE the version bump, // which is committed and pushed long before the first publish. @@ -214,6 +269,17 @@ for (const p of set) { writeFileSync(join(p.dir, "package.json"), JSON.stringify(p.pkg, null, 2) + "\n"); } ok(`bumped ${set.length} package.json → ${VERSION}`); +const rustManifests = []; +if (rust.publish) { + const members = JSON.parse(out(`cd ${RUST_DIR} && cargo metadata --format-version 1 --no-deps --locked`)) + .packages.map((p) => p.manifest_path); + for (const manifest of [join(RUST_DIR, "Cargo.toml"), ...members]) { + writeFileSync(manifest, bumpRustManifest(readFileSync(manifest, "utf8"), VERSION)); + rustManifests.push(manifest); + } + sh(`cd ${RUST_DIR} && cargo update --workspace --offline`, { quiet: true }); + ok(`bumped the Rust workspace → ${VERSION} (${rustManifests.length} manifests, Cargo.lock)`); +} // --- PHASE 2+3: clean build + relock -------------------------------------- sh("bun run clean", { quiet: true }); @@ -232,6 +298,15 @@ const bad = Object.entries(pj.dependencies || {}).filter(([k, v]) => k.startsWit if (bad.length) die(`packed cli pins stale/workspace sibling deps: ${JSON.stringify(bad)}`); ok(`packed deps verified: all @metaobjectsdev/* pinned to ${VERSION}`); +// --- pack-verify the crates: each packages and builds from its own tarball ------- +// `--workspace` resolves the sibling crates from the tarballs it just made, so a crate that +// would only build against a path in this checkout fails here, not on crates.io. +// `--allow-dirty` because the version bump above is not committed yet. +if (rust.publish) { + sh(`cd ${RUST_DIR} && cargo publish --dry-run --workspace --locked --allow-dirty`, { quiet: true }); + ok(`crates pack-verified: ${crates.join(", ")} @ ${VERSION}`); +} + // --- promote CHANGELOG [Unreleased] → [VERSION], or date a prepared [VERSION] ---- // The rule and its cases live in scripts/lib/changelog-promote.mjs (tested by // scripts/test-changelog-promote.mjs): a section prepared ahead of the cut carries the date it @@ -266,6 +341,9 @@ ok("site payload regenerated for the new version"); // --- PHASE 6: STOP — confirm before the irreversible publish -------------- console.log(`\n\x1b[1mReady to publish ${VERSION} to npm \`latest\` (IRREVERSIBLE).\x1b[0m`); console.log(` packages: ${set.length} | packed deps: pinned | build: clean`); +console.log(rust.publish + ? ` and ${crates.length} crates to crates.io (IRREVERSIBLE): ${crates.join(", ")}` + : ` crates.io: none (${rust.reason})`); if (DRY) { ok("dry run — stopping before commit/publish/tag (no changes published)"); process.exit(0); } if (!YES) { const rl = createInterface({ input: process.stdin, output: process.stdout }); @@ -276,6 +354,7 @@ if (!YES) { // --- commit the release --------------------------------------------------- sh("git add server/typescript/packages/*/package.json client/web/packages/*/package.json bun.lock CHANGELOG.md examples/showcase/site-payload.json"); +if (rust.publish) sh(`git add ${[...rustManifests, join(RUST_DIR, "Cargo.lock")].join(" ")}`); sh(`git commit -q -m "chore(release): @metaobjectsdev TypeScript packages ${VERSION}"`); ok("committed"); @@ -286,6 +365,15 @@ for (const pkg of ordered) { ok(`published ${pkg.short}@${VERSION}`); } +// --- PHASE 7b: the crates, in dependency order ------------------------------ +// After npm, so a dead npm token (the likelier failure) stops the cut before anything on +// crates.io is permanent. cargo waits for each crate to appear in the index before it +// returns, so the next crate can resolve it. +for (const name of crates) { + sh(`cd ${RUST_DIR} && cargo publish -p ${name} --locked`, { quiet: true }); + ok(`published ${name}@${VERSION} to crates.io`); +} + // --- PHASE 8: push (the tag is NOT cut here) ------------------------------- // This script publishes npm, which is one of FOUR registries. The PyPI/NuGet/Maven // version bump is a separate, later commit — so at this point the branch states the new npm @@ -317,10 +405,11 @@ const v = out(`cd ${sm} && ./node_modules/.bin/meta --version`); if (!v.includes(VERSION)) die(`smoke FAILED: clean install reports ${v}, expected ${VERSION}`); ok(`smoke: clean external install → meta --version = ${v}`); -console.log(`\n\x1b[32m\x1b[1m✅ ${VERSION} is live on npm latest.\x1b[0m`); +console.log(`\n\x1b[32m\x1b[1m✅ ${VERSION} is live on npm latest${rust.publish ? " and crates.io" : ""}.\x1b[0m`); console.log(`\n\x1b[1mNOT DONE — v${VERSION} is not tagged yet, by design.\x1b[0m`); console.log(` 1. Bump PyPI/NuGet/Maven, run \`bun run site:payload\`, commit, push.`); -console.log(` 2. Tag the ports: python-v${VERSION}, csharp-v${VERSION}, java-v${mavenVersion(VERSION)}.`); +console.log(` 2. Tag the ports: python-v${VERSION}, csharp-v${VERSION}, java-v${mavenVersion(VERSION)}` + + (rust.publish ? `, ${RUST_TAG_PREFIX}${VERSION}.` : ".")); console.log(` 3. \`bun scripts/finish-release.mjs ${VERSION}\` — gates the coordinates, then cuts v${VERSION}.`); console.log(` The website pins to v${VERSION}, so tagging before step 1 publishes three stale versions.`); console.log(` Docs version refs are NOT auto-bumped (low-value churn for a patch); batch them when convenient.`); diff --git a/scripts/test-rust-release.mjs b/scripts/test-rust-release.mjs new file mode 100644 index 0000000000..c960982816 --- /dev/null +++ b/scripts/test-rust-release.mjs @@ -0,0 +1,116 @@ +#!/usr/bin/env node +// Tests for scripts/lib/rust-release.mjs — whether a release publishes the Rust crates, in +// what order, and the version edit that puts them on the shared line. +// +// node scripts/test-rust-release.mjs +// +// The oracles are the release rules in docs/RELEASING.md (publish what changed; a change to +// expected-registry.json publishes every registry) and crates.io's own: a crate publishes +// after its dependencies, and a version once taken is taken. + +import { + isRustProductPath, newestRustTag, rustPublishDecision, rustPublishOrder, bumpRustManifest, + crateVersionTaken, EXPECTED_REGISTRY, +} from "./lib/rust-release.mjs"; + +let fails = 0; +const check = (cond, label) => (cond ? console.log(`ok: ${label}`) : (console.error(`FAIL: ${label}`), fails++)); +const throws = (fn) => { try { fn(); return false; } catch { return true; } }; + +// What the crates ship. +check(isRustProductPath("server/rust/metaobjects/src/loader.rs"), "a crate's source is shipped"); +check(isRustProductPath("server/rust/metaobjects/data/library/iam/meta.iam.yaml"), "a crate's embedded data is shipped"); +check(isRustProductPath("server/rust/metaobjects-codegen/build.rs"), "a build script is shipped"); +check(isRustProductPath("server/rust/metaobjects-cli/Cargo.toml"), "a crate manifest is shipped"); +check(isRustProductPath("server/rust/Cargo.toml"), "the workspace manifest is shipped (it sets every crate's version)"); +check(isRustProductPath("server/rust/Cargo.lock"), "the lockfile is shipped (the binary is built from it)"); +check(!isRustProductPath("server/rust/metaobjects-codegen/tests/compile.rs"), "a crate's tests are not shipped"); +check(!isRustProductPath("server/rust/metaobjects/examples/load_bench.rs"), "a crate's examples are not shipped"); +check(!isRustProductPath("server/rust/metaobjects/baselines/load.json"), "benchmark baselines are not shipped"); +check(!isRustProductPath("server/rust/rustfmt.toml"), "a workspace file other than the manifest and lock is not shipped"); +check(!isRustProductPath("server/rustacean/src/x.rs"), "a sibling directory that merely starts with the name is not the workspace"); +check(!isRustProductPath("docs/ports/rust.md"), "the port's docs are not shipped"); + +// The newest tag. +check(newestRustTag([]) === null, "no tag: the crates never shipped"); +check(newestRustTag(["v1.3.0", "python-v1.3.0"]) === null, "other ports' tags are not the crates'"); +check(newestRustTag(["rust-v1.3.0", "rust-v1.10.0", "rust-v1.9.2"]) === "rust-v1.10.0", "versions compare as numbers, not text"); +check(newestRustTag(["rust-v1.3.0-rc.2", "rust-v1.3.0"]) === "rust-v1.3.0", "a final release is newer than its candidates"); +check(newestRustTag(["rust-v1.3.0-rc.2", "rust-v1.3.0-rc.10"]) === "rust-v1.3.0-rc.10", "candidates compare by number"); +check(newestRustTag(["rust-vnext", "rust-v1.3.0"]) === "rust-v1.3.0", "a tag that is not a version is ignored"); + +// Whether the cut publishes. +const decide = (lastTag, changedPaths, mode) => rustPublishDecision({ lastTag, changedPaths, mode }); +check(decide(null, []).publish, "never published: the first cut publishes, changed or not"); +check(!decide("rust-v1.3.0", ["docs/ports/rust.md", "server/rust/metaobjects/tests/x.rs"]).publish, + "only docs and tests changed: the crates sit the release out"); +check(decide("rust-v1.3.0", ["server/rust/metaobjects-render/src/render.rs"]).publish, "a shipped file changed: publish"); +check(decide("rust-v1.3.0", [EXPECTED_REGISTRY]).publish, "expected-registry.json changed: every registry publishes"); +check(decide("rust-v1.3.0", ["server/rust/metaobjects/src/a.rs"]).reason.includes("server/rust/metaobjects/src/a.rs"), + "the reason names the file that changed"); +check(decide("rust-v1.3.0", []).reason.includes("rust-v1.3.0"), "a skip names the tag it compared against"); +check(decide(null, [], "skip").publish === false, "--crates=skip overrides a first publish"); +check(decide("rust-v1.3.0", [], "publish").publish, "--crates=publish overrides an unchanged tree"); +check(throws(() => decide(null, [], "maybe")), "an unknown --crates mode is refused, not read as auto"); + +// The publish order, from what `cargo metadata --no-deps` prints. +const pkg = (name, deps, extra = {}) => ({ + id: `path+file:///ws/${name}#${name}@1.3.0`, name, + dependencies: deps.map(([n, kind]) => ({ name: n, kind: kind ?? null })), ...extra, +}); +const meta = (packages) => ({ packages, workspace_members: packages.map((p) => p.id) }); +const workspace = meta([ + pkg("metaobjects-cli", [["metaobjects"], ["metaobjects-codegen"], ["clap"]]), + pkg("metaobjects-codegen", [["metaobjects"], ["metaobjects-render"], ["serde"]]), + pkg("metaobjects-render", [["mustache-ng"], ["serde_json"]]), + pkg("metaobjects", [["serde_json"], ["indexmap"]]), +]); +check(JSON.stringify(rustPublishOrder(workspace)) + === JSON.stringify(["metaobjects", "metaobjects-render", "metaobjects-codegen", "metaobjects-cli"]), + "each crate after the crates it depends on, ties by name"); +check(JSON.stringify(rustPublishOrder(meta([pkg("b", []), pkg("a", [["b", "dev"]])]))) === JSON.stringify(["a", "b"]), + "a dev-dependency does not order anything"); +check(JSON.stringify(rustPublishOrder(meta([pkg("a", []), pkg("x", [], { publish: [] })]))) === JSON.stringify(["a"]), + "a crate marked publish = false is left out"); +check(JSON.stringify(rustPublishOrder(meta([pkg("a", [["b", "build"]]), pkg("b", [])]))) === JSON.stringify(["b", "a"]), + "a build-dependency orders like a normal one"); +check(throws(() => rustPublishOrder(meta([pkg("a", [["b"]]), pkg("b", [["a"]])]))), "a cycle is refused"); + +// The version edit. +const root = `[workspace] +members = ["metaobjects"] + +[workspace.package] +version = "1.2.0" +edition = "2024" + +[workspace.dependencies] +serde = { version = "1.0" } +`; +const bumpedRoot = bumpRustManifest(root, "1.3.0"); +check(bumpedRoot.includes('[workspace.package]\nversion = "1.3.0"'), "the workspace version moves"); +check(bumpedRoot.includes('serde = { version = "1.0" }'), "a registry dependency's requirement does not"); +check(bumpedRoot.replace('version = "1.3.0"', 'version = "1.2.0"') === root, "nothing else changes"); +const member = `[package] +name = "metaobjects-cli" +version.workspace = true + +[dependencies] +metaobjects = { path = "../metaobjects", version = "1.2.0" } +metaobjects-codegen = { path = "../metaobjects-codegen", version = "1.2.0" } +clap = { version = "4.5", features = ["derive"] } +`; +const bumpedMember = bumpRustManifest(member, "1.3.0-rc.1"); +check(bumpedMember.includes('metaobjects = { path = "../metaobjects", version = "1.3.0-rc.1" }') + && bumpedMember.includes('metaobjects-codegen = { path = "../metaobjects-codegen", version = "1.3.0-rc.1" }'), + "each sibling crate's requirement moves"); +check(bumpedMember.includes('clap = { version = "4.5", features = ["derive"] }'), "a registry dependency is left alone"); +check(bumpedMember.includes("version.workspace = true"), "an inherited version stays inherited"); + +// What crates.io answers. +check(crateVersionTaken({ versions: [{ num: "1.3.0" }, { num: "1.2.0" }] }, "1.3.0"), "a published version is taken"); +check(!crateVersionTaken({ versions: [{ num: "1.3.0-rc.1" }] }, "1.3.0"), "a candidate does not take the final number"); +check(!crateVersionTaken({}, "1.3.0"), "an answer with no versions takes nothing"); + +if (fails) { console.error(`\n${fails} failing`); process.exit(1); } +console.log("\nall rust-release checks pass"); diff --git a/server/rust/Cargo.lock b/server/rust/Cargo.lock index 0115910fce..d023f395be 100644 --- a/server/rust/Cargo.lock +++ b/server/rust/Cargo.lock @@ -100,7 +100,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "metaobjects" -version = "0.1.0" +version = "1.3.0" dependencies = [ "indexmap", "saphyr", @@ -109,7 +109,7 @@ dependencies = [ [[package]] name = "metaobjects-cli" -version = "0.1.0" +version = "1.3.0" dependencies = [ "metaobjects", "metaobjects-codegen", @@ -118,17 +118,20 @@ dependencies = [ [[package]] name = "metaobjects-codegen" -version = "0.1.0" +version = "1.3.0" dependencies = [ "indexmap", "metaobjects", + "metaobjects-render", + "proc-macro2", "serde", "serde_json", + "syn", ] [[package]] name = "metaobjects-render" -version = "0.1.0" +version = "1.3.0" dependencies = [ "indexmap", "mustache-ng", @@ -230,6 +233,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] diff --git a/server/rust/Cargo.toml b/server/rust/Cargo.toml index 56356073ea..0bdd5cc062 100644 --- a/server/rust/Cargo.toml +++ b/server/rust/Cargo.toml @@ -1,18 +1,18 @@ # The Rust port of MetaObjects. ADR-0065 records why it exists and how it differs from the # other ports; its Amendment 3 records that it is a full, publishable language. # -# Four crates: +# Four crates, on the version line every port shares (`scripts/release.mjs` publishes them): # `metaobjects` metamodel registry, loader, canonical serializer. -# `metaobjects-codegen` the run engine (skip key, hash manifest, writer) and the -# `entity` generator. -# `metaobjects-cli` the `cargo-meta` binary, so `cargo meta gen` works. # `metaobjects-render` prompt render, the reply parser and the output-format fragment. +# `metaobjects-codegen` the run engine (skip key, hash manifest, writer) and the shipped +# generators. +# `metaobjects-cli` the `cargo-meta` binary, so `cargo meta gen` works. [workspace] resolver = "3" members = ["metaobjects", "metaobjects-codegen", "metaobjects-cli", "metaobjects-render"] [workspace.package] -version = "0.1.0" +version = "1.3.0" edition = "2024" rust-version = "1.94" license = "Apache-2.0" diff --git a/server/rust/metaobjects-cli/Cargo.toml b/server/rust/metaobjects-cli/Cargo.toml index c4d7b9a5ad..8f06dac972 100644 --- a/server/rust/metaobjects-cli/Cargo.toml +++ b/server/rust/metaobjects-cli/Cargo.toml @@ -24,8 +24,8 @@ name = "cargo-meta" path = "src/main.rs" [dependencies] -metaobjects = { path = "../metaobjects", version = "0.1.0" } -metaobjects-codegen = { path = "../metaobjects-codegen", version = "0.1.0" } +metaobjects = { path = "../metaobjects", version = "1.3.0" } +metaobjects-codegen = { path = "../metaobjects-codegen", version = "1.3.0" } [dev-dependencies] serde_json.workspace = true diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index 4e8afe0f1c..8f5f10f81e 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -25,7 +25,8 @@ use metaobjects_codegen::engine::{ ChangeKind, OWNED_MANIFEST, Outcome, RunError, RunOptions, RunReport, VerifyReport, }; use metaobjects_codegen::generator_list::{self, GENERATOR_LIST_FILE}; -use metaobjects_codegen::{Generator, run, shipped_generators, verify}; +use metaobjects_codegen::project::load_project; +use metaobjects_codegen::{Generator, check_templates, run, shipped_generators, verify}; /// The tool's name in messages. const TOOL: &str = "cargo meta"; @@ -37,6 +38,7 @@ USAGE: cargo meta init [--project ] cargo meta gen [OPTIONS] [ENTITY...] cargo meta verify [--codegen] [--full] [OPTIONS] + cargo meta verify --templates [--project ] [--strict] cargo meta eject ... [--force] [--engine ] cargo meta eject --undo [...] [--force] cargo meta eject --list @@ -74,6 +76,9 @@ OPTIONS (gen): OPTIONS (verify): --codegen The generated-code gate only: no business-rules gate. A bare `verify` runs both. + --templates The template gate only: every template body (read from the + project's prompts/, else templates/) against its payload's + fields. Exits 1 on drift, naming the template, the file and the tag. --full Render and compare even when a local run could answer from the stored key. Always on when CI is set. @@ -359,7 +364,7 @@ fn list_generators( generators: &[Box], ) -> i32 { let listed = match generator_list::read(root) { - Ok(listed) => listed, + Ok(listed) => listed.as_deref().map(generator_list::names), Err(e) => { let _ = writeln!(err, "{TOOL}: {e}"); return 1; @@ -569,16 +574,14 @@ fn cmd_verify( "`{TOOL} verify --db` does not exist: checking a schema against a live database is the Node `meta` command's for every server language (`meta verify --db`, ADR-0015)." ))); } - if s.has("--templates") { - return Err(Usage(format!( - "`{TOOL} verify --templates` does not exist yet: the Rust port ships no prompt or template generator, so it has no template gate. `{TOOL} verify --codegen` is the generated-code gate." - ))); - } if s.has("--deps") { return Err(Usage(format!( "`{TOOL} verify --deps` does not exist: metadata dependencies are resolved and checked by the Node `meta` command (`meta deps check`)." ))); } + if s.has("--templates") { + return Ok(verify_templates(&s, cwd, out, err)); + } let mut options = run_options(&s, cwd, generators)?; options.force = s.has("--full") || ci_forces_render(std::env::var_os("CI")); match verify(&options, generators) { @@ -613,6 +616,43 @@ fn cmd_verify( } } +/// `verify --templates`: every template body against its payload, read from the project's +/// `prompts/` (or `templates/`) directory, the check `gen` makes before it writes a render +/// helper. 0 clean, 1 drift or a model that does not load. +fn verify_templates(s: &Split, cwd: &Path, out: &mut dyn Write, err: &mut dyn Write) -> i32 { + let explicit = s.value("--project").map(|d| cwd.join(d)); + let loaded = match load_project(cwd, explicit.as_deref(), s.has("--strict")) { + Ok(l) => l, + Err(errors) => { + let _ = writeln!(err, "{TOOL} verify --templates: the model did not load:"); + for e in errors { + let _ = writeln!(err, " {e}"); + } + return 1; + } + }; + let r = &loaded.result; + let check = check_templates(&r.tree, r.root, &loaded.collection.config_dir); + for e in &check.errors { + let _ = writeln!(err, "error: {e}"); + } + if check.errors.is_empty() { + let _ = writeln!( + out, + "{TOOL} verify --templates: {} template ref(s) clean.", + check.checked + ); + 0 + } else { + let _ = writeln!( + err, + "{TOOL} verify --templates: {} drift error(s).", + check.errors.len() + ); + 1 + } +} + fn cmd_eject( args: &[String], cwd: &Path, @@ -972,7 +1012,6 @@ mod tests { let (code, _, err) = run_cli(&["meta", "verify", "--db"]); assert_eq!(code, 2); assert!(err.contains("meta verify --db"), "{err}"); - assert_eq!(run_cli(&["meta", "verify", "--templates"]).0, 2); assert_eq!(run_cli(&["meta", "verify", "--deps"]).0, 2); } diff --git a/server/rust/metaobjects-cli/tests/cli.rs b/server/rust/metaobjects-cli/tests/cli.rs index 5396154871..af13e52e77 100644 --- a/server/rust/metaobjects-cli/tests/cli.rs +++ b/server/rust/metaobjects-cli/tests/cli.rs @@ -53,11 +53,15 @@ impl Project { .current_dir(&self.0) // The suite's own environment must not decide what a test sees. .env_remove("CI") - // An owned generator crate is a real cargo build: keep it in the workspace's - // target directory so the engine builds once across runs, and unoptimized. + // An owned generator crate is a real cargo build: keep it under the target + // directory the suite was built into (the workspace's unless one was chosen), so + // the engine builds once across runs, and unoptimized. .env( "CARGO_TARGET_DIR", - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../target/owned-check"), + std::env::var_os("CARGO_TARGET_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../target")) + .join("owned-check"), ) .env("CARGO_PROFILE_DEV_OPT_LEVEL", "0") .env_remove("CARGO_ENCODED_RUSTFLAGS") @@ -255,14 +259,21 @@ fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_availabl let list: serde_json::Value = serde_json::from_str(&p.read("metaobjects.config.json")).unwrap(); assert_eq!( list["generators"], - serde_json::json!(["entity", "client", "commands"]) + serde_json::json!([ + "entity", + "client", + "commands", + "render-helper", + "output-parser", + "output-prompt" + ]) ); let out = ok(&p.run(&["meta", "gen", "--list"])); assert!( - out.contains("metaobjects.config.json runs: entity, client, commands"), + out.contains("metaobjects.config.json runs: entity, client, commands, render-helper, output-parser, output-prompt"), "{out}" ); - assert_eq!(out.matches("[configured]").count(), 3, "{out}"); + assert_eq!(out.matches("[configured]").count(), 6, "{out}"); // An edited list is never overwritten by a second init. p.write( "metaobjects.config.json", @@ -275,7 +286,7 @@ fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_availabl ); let out = ok(&p.run(&["meta", "gen", "--list"])); assert!(out.contains("runs: entity\n"), "{out}"); - assert_eq!(out.matches("[not configured]").count(), 2, "{out}"); + assert_eq!(out.matches("[not configured]").count(), 5, "{out}"); } #[test] @@ -473,7 +484,14 @@ fn an_object_that_goes_away_has_its_files_removed_unless_one_was_edited() { fn gen_list_names_the_generators_and_how_an_owned_copy_compares() { let p = Project::new("list"); let out = ok(&p.run(&["meta", "gen", "--list"])); - for name in ["entity", "client", "commands"] { + for name in [ + "entity", + "client", + "commands", + "render-helper", + "output-parser", + "output-prompt", + ] { assert!( out.lines().any(|l| l.starts_with(&format!("{name} - "))), "{out}" @@ -570,7 +588,7 @@ fn eject_copies_the_generator_never_overwrites_and_undo_takes_back_only_identica assert_eq!(r.status.code(), Some(2)); assert!( text(&r.stderr).contains( - "unknown or non-ejectable generator(s): nope; ejectable: entity, client, commands" + "unknown or non-ejectable generator(s): nope; ejectable: entity, client, commands, render-helper, output-parser, output-prompt" ), "{}", text(&r.stderr) @@ -888,3 +906,39 @@ fn verify_runs_the_rules_gate_and_a_setting_decides_whether_a_finding_fails_it() "{err}" ); } + +#[test] +fn verify_templates_checks_every_body_against_its_payload() { + let p = Project::new("verify-templates"); + p.write( + "metaobjects/meta.ai.json", + r#"{ "metadata.root": { "package": "ai", "children": [ + { "object.value": { "name": "Welcome", "children": [ { "field.string": { "name": "name" } } ] } }, + { "template.output": { "name": "WelcomePage", "@kind": "document", "@payloadRef": "Welcome", "@textRef": "pages/welcome" } } +] } }"#, + ); + p.write("templates/pages/welcome.mustache", "Hello {{name}}"); + let out = ok(&p.run(&["meta", "verify", "--templates"])); + assert!(out.contains("1 template ref(s) clean"), "{out}"); + + // A tag the payload does not have is drift, named down to the tag. + p.write("templates/pages/welcome.mustache", "Hello {{nmae}}"); + let r = p.run(&["meta", "verify", "--templates"]); + assert_eq!(r.status.code(), Some(1)); + let err = text(&r.stderr); + assert!( + err.contains("[WelcomePage] ref 'pages/welcome'") + && err.contains("ERR_VAR_NOT_ON_PAYLOAD: nmae"), + "{err}" + ); + + // A body that is not there is drift too, and `prompts/` wins over `templates/`. + std::fs::create_dir_all(p.0.join("prompts")).unwrap(); + let r = p.run(&["meta", "verify", "--templates"]); + assert_eq!(r.status.code(), Some(1)); + assert!( + text(&r.stderr).contains("missing template"), + "{}", + text(&r.stderr) + ); +} diff --git a/server/rust/metaobjects-codegen/Cargo.toml b/server/rust/metaobjects-codegen/Cargo.toml index dfdc4ad635..f44a881b36 100644 --- a/server/rust/metaobjects-codegen/Cargo.toml +++ b/server/rust/metaobjects-codegen/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "metaobjects-codegen" -description = "MetaObjects code generation for Rust: the run engine and the entity, client and commands generators." +description = "MetaObjects code generation for Rust: the run engine and the shipped generators." version.workspace = true edition.workspace = true rust-version.workspace = true @@ -14,10 +14,16 @@ categories = ["development-tools", "development-tools::build-utils"] build = "build.rs" [dependencies] -metaobjects = { path = "../metaobjects", version = "0.1.0" } +metaobjects = { path = "../metaobjects", version = "1.3.0" } +metaobjects-render = { path = "../metaobjects-render", version = "1.3.0" } serde_json.workspace = true indexmap.workspace = true serde.workspace = true +[dev-dependencies] +# The layout ratchet (tests/layout_ratchet.rs) parses generator source to find hand-typed layout. +syn = { version = "3", default-features = false, features = ["full", "visit", "parsing", "printing", "clone-impls"] } +proc-macro2 = { version = "1", features = ["span-locations"] } + [lints] workspace = true diff --git a/server/rust/metaobjects-codegen/src/client.rs b/server/rust/metaobjects-codegen/src/client.rs index 45e6aea414..22dae76346 100644 --- a/server/rust/metaobjects-codegen/src/client.rs +++ b/server/rust/metaobjects-codegen/src/client.rs @@ -37,12 +37,15 @@ use std::collections::BTreeSet; +use metaobjects_codegen::emitted::CLIENT_TRANSPORT_RS; use metaobjects_codegen::generator::{EmittedFile, GenContext, GenError, Generator}; use metaobjects_codegen::names::{literal, pascal, snake}; use metaobjects_codegen::plan::{ CLIENT_CRATE, CLIENT_SUFFIX, CratePlan, FieldPlan, Plan, Route, SUPPORT_CRATE, StructPlan, Ty, }; -use metaobjects_codegen::writer::{CodeWriter, RUSTFMT_TOML, file, item, list, piece}; +use metaobjects_codegen::writer::{ + CodeWriter, Manifest, RUSTFMT_TOML, file, fixed, item, list, piece, sibling_dep, toml_string, +}; /// Bump when the emitted text changes shape, so a stored skip key never survives it. const FORMAT: u32 = 1; @@ -50,7 +53,7 @@ const FORMAT: u32 = 1; /// The line every generated Rust file starts with. pub const BANNER: &str = "// @generated by the MetaObjects client generator. Do not edit: change the model and run `cargo meta gen`."; -const MANIFEST_BANNER: &str = "# @generated by the MetaObjects client generator. Do not edit: change the model and run `cargo meta gen`.\n"; +const MANIFEST_BANNER: &str = "@generated by the MetaObjects client generator. Do not edit: change the model and run `cargo meta gen`."; /// The client generator. #[derive(Debug, Clone, Copy, Default)] @@ -66,320 +69,123 @@ impl Generator for ClientGenerator { } fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { - let plan = Plan::of(ctx)?; - let selected = plan.selected_crates(ctx.entities)?; - let mut files = Vec::new(); - for (cname, c) in &plan.crates { - if selected.as_ref().is_some_and(|sel| !sel.contains(cname)) { - continue; - } - client_crate(&plan, cname, c, &mut files)?; - } - if !files.is_empty() { - files.extend(transport_crate()); - } - Ok(files) + self.render(ctx) } } -// ---- the transport crate --------------------------------------------------------------- - -/// The crate of HTTP plumbing the client crates share. It is generated, so the output -/// depends on nothing from MetaObjects. -fn transport_crate() -> Vec { - let manifest = format!( - "{MANIFEST_BANNER}[package]\n\ - name = {}\n\ - version = \"0.1.0\"\n\ - edition = \"2021\"\n\ - publish = false\n\ - description = \"The HTTP transport of the generated MetaObjects client crates.\"\n\ - \n\ - [dependencies]\n\ - reqwest = {{ version = \"0.13\", features = [\"json\", \"query\"] }}\n\ - serde = {{ version = \"1\", features = [\"derive\"] }}\n\ - serde_json = \"1\"\n", - literal(CLIENT_CRATE) - ); - let file = |name: &str, text: String| EmittedFile::new(format!("{CLIENT_CRATE}/{name}"), text); - vec![ - file("Cargo.toml", manifest), - file("rustfmt.toml", RUSTFMT_TOML.to_string()), - file("src/lib.rs", format!("{BANNER}\n\n{TRANSPORT_RS}")), - ] -} - -/// `meta_client/src/lib.rs`, in rustfmt's output form under the generated `rustfmt.toml`. -const TRANSPORT_RS: &str = r##"//! The transport every generated client crate uses: one HTTP client, the list query, and -//! the error a call fails with. It follows the REST contract every MetaObjects server -//! generator implements, whatever language the server is written in. - -use std::fmt; - -use serde::de::DeserializeOwned; -use serde::Serialize; - -/// The HTTP library underneath, so a caller can set a client up without naming it as a -/// dependency of its own. -pub use reqwest; - -/// What a call returns. -pub type Result = std::result::Result; - -/// Why a call failed. -#[derive(Debug)] -pub enum Error { - /// The request did not get an answer. - Transport(reqwest::Error), - /// The server refused the request. `code` and `message` are its error body's `error` and - /// `message` members, when it sent them; `body` is the body as it arrived. - Api { status: u16, code: Option, message: Option, body: String }, - /// The server answered, and the body is not what the model says a row looks like. - Decode { status: u16, message: String }, -} - -impl Error { - /// The HTTP status of the answer, when there was one. - pub fn status(&self) -> Option { - match self { - Error::Transport(e) => e.status().map(|s| s.as_u16()), - Error::Api { status, .. } | Error::Decode { status, .. } => Some(*status), - } - } - - /// The server's error code (`not_found`, `validation`, ...), when it sent one. - pub fn code(&self) -> Option<&str> { - match self { - Error::Api { code, .. } => code.as_deref(), - _ => None, - } - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Error::Transport(e) => write!(f, "the request failed: {e}"), - Error::Api { status, code, message, .. } => { - write!(f, "the server answered {status}")?; - if let Some(code) = code { - write!(f, " {code}")?; - } - if let Some(message) = message { - write!(f, ": {message}")?; - } - Ok(()) - } - Error::Decode { status, message } => { - write!(f, "the server answered {status} with a body that does not fit: {message}") - } - } - } -} - -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Error::Transport(e) => Some(e), - _ => None, - } - } -} - -impl From for Error { - fn from(e: reqwest::Error) -> Self { - Error::Transport(e) - } -} - -/// The API's address and the HTTP client that reaches it. -#[derive(Debug, Clone)] -pub struct Client { - http: reqwest::Client, - base: String, -} - -impl Client { - /// A client for the API at `base_url`: the server's address and the prefix its routes - /// are mounted under, as in `https://example.com/api`. - pub fn new(base_url: &str) -> Self { - Self::with_http(reqwest::Client::new(), base_url) - } - - /// The same, over an HTTP client you set up yourself (timeouts, headers, a proxy). - pub fn with_http(http: reqwest::Client, base_url: &str) -> Self { - Self { http, base: base_url.trim_end_matches('/').to_string() } - } - - /// The address every path is taken under. - pub fn base_url(&self) -> &str { - &self.base - } +impl ClientParts for ClientGenerator {} - fn url(&self, path: &str) -> String { - format!("{}/{}", self.base, path) +/// The pieces of the client generator's output, one method each (ADR-0063 item 7). Each +/// default is the shipped piece: implement this for a generator of your own, override the +/// piece you want changed, and have its [`Generator::generate`] return `self.render(ctx)` +/// (the [`crate::entity::EntityParts`] example shows the shape). An override can call the +/// shipped piece, a public function of this module with the same name. Not a stability +/// contract: the methods may change in a minor release, and the CHANGELOG says when. +pub trait ClientParts { + /// Every file: one client crate per package with a served entity, then the transport + /// crate when there is any. + fn render(&self, ctx: &GenContext<'_>) -> Result, GenError> { + render(self, ctx) } - /// `GET path`, read as `T`. - pub async fn get(&self, path: &str) -> Result { - read(self.http.get(self.url(path)).send().await?).await + /// The transport crate's files. + fn transport_crate(&self) -> Vec { + transport_crate() } - /// `GET path?query`, read as `T`. - pub async fn list(&self, path: &str, query: &Query) -> Result { - read(self.http.get(self.url(path)).query(query.pairs()).send().await?).await + /// A client crate's `Cargo.toml`, with a dependency on each model crate it names. + fn manifest(&self, name: &str, c: &CratePlan, deps: &BTreeSet) -> String { + cargo_toml(name, c, deps) } - /// `POST path` with a JSON body, read as `T`. - pub async fn post(&self, path: &str, body: &B) -> Result - where - B: Serialize + ?Sized, - T: DeserializeOwned, - { - read(self.http.post(self.url(path)).json(body).send().await?).await + /// A client crate's `src/lib.rs`: each module and what it exports. + fn lib_file(&self, package: &str, items: &[(String, Vec)]) -> String { + lib_file(package, items) } - /// `PATCH path` with a JSON body, read as `T`. - pub async fn patch(&self, path: &str, body: &B) -> Result - where - B: Serialize + ?Sized, - T: DeserializeOwned, - { - read(self.http.patch(self.url(path)).json(body).send().await?).await + /// One served entity's file: its client, then its query and sort types. + fn entity_file( + &self, + plan: &Plan, + s: &StructPlan, + route: &Route, + deps: &mut BTreeSet, + ) -> Result { + entity_file(self, plan, s, route, deps) } - /// `DELETE path`. - pub async fn delete(&self, path: &str) -> Result<()> { - let response = self.http.delete(self.url(path)).send().await?; - if response.status().is_success() { - return Ok(()); - } - Err(refusal(response).await) + /// One entity's client: the struct and a method per route. + fn client_item( + &self, + plan: &Plan, + s: &StructPlan, + route: &Route, + deps: &mut BTreeSet, + ) -> Result { + client_item(plan, s, route, deps) } -} -async fn read(response: reqwest::Response) -> Result { - let status = response.status(); - if !status.is_success() { - return Err(refusal(response).await); + /// One entity's list query and, when it sorts, its sort type. + fn query_items( + &self, + s: &StructPlan, + route: &Route, + deps: &mut BTreeSet, + ) -> Result, GenError> { + query_items(s, route, deps) } - let text = response.text().await?; - serde_json::from_str(&text) - .map_err(|e| Error::Decode { status: status.as_u16(), message: e.to_string() }) -} - -async fn refusal(response: reqwest::Response) -> Error { - let status = response.status().as_u16(); - let body = response.text().await.unwrap_or_default(); - let parsed: Option = serde_json::from_str(&body).ok(); - let member = |name: &str| { - parsed.as_ref().and_then(|v| v.get(name)).and_then(|v| v.as_str()).map(str::to_string) - }; - Error::Api { status, code: member("error"), message: member("message"), body } -} - -/// The order a sort puts rows in. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Direction { - /// The order the model declares for the field (ascending when it declares none). - Default, - Ascending, - Descending, -} - -/// The query of a list request: filters, a sort and a window. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct Query { - pairs: Vec<(String, String)>, } -impl Query { - pub fn new() -> Self { - Self::default() - } - - /// The query's parameters, in the order they were added, not yet percent-encoded. - pub fn pairs(&self) -> &[(String, String)] { - &self.pairs - } - - fn set(&mut self, name: &str, value: String) { - self.pairs.retain(|(n, _)| n != name); - self.pairs.push((name.to_string(), value)); - } - - /// Keep the rows whose `field` passes `op` against `value`. Filters add up: a row must - /// pass them all. - pub fn filter(&mut self, field: &str, op: &str, value: impl fmt::Display) { - self.pairs.push((format!("filter[{field}][{op}]"), value.to_string())); - } - - /// Keep the rows whose `field` is one of `values`. - pub fn filter_in(&mut self, field: &str, values: impl IntoIterator) { - let joined: Vec = values.into_iter().map(|v| v.to_string()).collect(); - self.filter(field, "in", joined.join(",")); - } - - /// Sort by `field`. A later sort replaces an earlier one: the contract has one sort key. - pub fn sort(&mut self, field: &str, direction: Direction) { - let value = match direction { - Direction::Default => field.to_string(), - Direction::Ascending => format!("{field}:asc"), - Direction::Descending => format!("{field}:desc"), - }; - self.set("sort", value); - } - - /// Return at most `rows` rows. - pub fn limit(&mut self, rows: u64) { - self.set("limit", rows.to_string()); +/// The shipped [`ClientParts::render`], through `parts`. +pub fn render( + parts: &P, + ctx: &GenContext<'_>, +) -> Result, GenError> { + let plan = Plan::of(ctx)?; + let selected = plan.selected_crates(ctx.entities)?; + let mut files = Vec::new(); + for (cname, c) in &plan.crates { + if selected.as_ref().is_some_and(|sel| !sel.contains(cname)) { + continue; + } + client_crate(parts, &plan, cname, c, &mut files)?; } - - /// Skip the first `rows` rows. - pub fn offset(&mut self, rows: u64) { - self.set("offset", rows.to_string()); + if !files.is_empty() { + files.extend(parts.transport_crate()); } - - /// Ask for the `{ rows, total }` answer a [`Page`] reads. - pub fn with_count(&mut self) { - self.set("withCount", "1".to_string()); - } -} - -/// One window of a list, and how many rows the filters match in all. -#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct Page { - pub rows: Vec, - pub total: u64, + Ok(files) } -/// The path of one row: `collection/id`, with the id percent-encoded. -pub fn row(collection: &str, id: impl fmt::Display) -> String { - format!("{collection}/{}", segment(&id.to_string())) -} - -/// The path of the rows related to one row: `collection/id/relation`. -pub fn related(collection: &str, id: impl fmt::Display, relation: &str) -> String { - format!("{}/{relation}", row(collection, id)) -} +// ---- the transport crate --------------------------------------------------------------- -/// One path segment, percent-encoded: everything but RFC 3986's unreserved characters. -pub fn segment(text: &str) -> String { - let mut out = String::with_capacity(text.len()); - for byte in text.bytes() { - if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { - out.push(char::from(byte)); - } else { - out.push_str(&format!("%{byte:02X}")); - } - } - out +/// The crate of HTTP plumbing the client crates share. It is generated, so the output +/// depends on nothing from MetaObjects. +pub fn transport_crate() -> Vec { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, CLIENT_CRATE); + m.entry( + "description", + &toml_string("The HTTP transport of the generated MetaObjects client crates."), + ); + m.blank().table("dependencies"); + m.entry( + "reqwest", + r#"{ version = "0.13", features = ["json", "query"] }"#, + ); + m.entry("serde", r#"{ version = "1", features = ["derive"] }"#); + m.entry("serde_json", &toml_string("1")); + let manifest = m.finish(); + let file = |name: &str, text: String| EmittedFile::new(format!("{CLIENT_CRATE}/{name}"), text); + vec![ + file("Cargo.toml", manifest), + file("rustfmt.toml", RUSTFMT_TOML.to_string()), + file("src/lib.rs", fixed(BANNER, CLIENT_TRANSPORT_RS)), + ] } -"##; // ---- one client crate ------------------------------------------------------------------ -fn client_crate( +fn client_crate( + parts: &P, plan: &Plan, cname: &str, c: &CratePlan, @@ -399,7 +205,7 @@ fn client_crate( exports.push(s.sort_name()); } lib_items.push((s.module(), exports)); - let text = entity_file(plan, s, route, &mut deps)?; + let text = parts.entity_file(plan, s, route, &mut deps)?; files.push(EmittedFile::new( format!("{name}/src/{}.rs", s.module()), text, @@ -408,7 +214,7 @@ fn client_crate( lib_items.sort(); files.push(EmittedFile::new( format!("{name}/Cargo.toml"), - cargo_toml(&name, c, &deps), + parts.manifest(&name, c, &deps), )); files.push(EmittedFile::new( format!("{name}/rustfmt.toml"), @@ -416,61 +222,55 @@ fn client_crate( )); files.push(EmittedFile::new( format!("{name}/src/lib.rs"), - lib_file(&c.package, &lib_items), + parts.lib_file(&c.package, &lib_items), )); Ok(()) } -fn cargo_toml(name: &str, c: &CratePlan, deps: &BTreeSet) -> String { - let mut out = String::from(MANIFEST_BANNER); - out.push_str("[package]\n"); - out.push_str(&format!("name = {}\n", literal(name))); - out.push_str("version = \"0.1.0\"\n"); - out.push_str("edition = \"2021\"\n"); - out.push_str("publish = false\n"); +/// The shipped [`ClientParts::manifest`]. +pub fn cargo_toml(name: &str, c: &CratePlan, deps: &BTreeSet) -> String { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, name); let package = if c.package.is_empty() { "the model's" } else { c.package.as_str() }; - out.push_str(&format!( - "description = {}\n", - literal(&format!( + m.entry( + "description", + &toml_string(&format!( "A client for the REST API of the MetaObjects package {package}." - )) - )); - out.push_str("\n[dependencies]\n"); - out.push_str(&format!( - "{CLIENT_CRATE} = {{ path = \"../{CLIENT_CRATE}\" }}\n" - )); + )), + ); + m.blank().table("dependencies"); + m.entry(CLIENT_CRATE, &sibling_dep(CLIENT_CRATE)); for dep in deps { - out.push_str(&format!("{dep} = {{ path = \"../{dep}\" }}\n")); + m.entry(dep, &sibling_dep(dep)); } - out + m.finish() } -fn lib_file(package: &str, items: &[(String, Vec)]) -> String { - let mut out = format!("{BANNER}\n\n"); +/// The shipped [`ClientParts::lib_file`]. +pub fn lib_file(package: &str, items: &[(String, Vec)]) -> String { + let mut w = CodeWriter::new(); + w.line(BANNER).blank(); if package.is_empty() { - out.push_str( - "//! A client for the REST API of the MetaObjects model that declares no package.\n", - ); + w.line("//! A client for the REST API of the MetaObjects model that declares no package."); } else { - out.push_str(&format!( - "//! A client for the REST API of the MetaObjects package `{package}`.\n" + w.line(format!( + "//! A client for the REST API of the MetaObjects package `{package}`." )); } - out.push('\n'); + w.blank(); for (module, _) in items { - out.push_str(&format!("mod {module};\n")); + w.line(format!("mod {module};")); } - out.push('\n'); + w.blank(); for (module, exports) in items { for e in exports { - out.push_str(&format!("pub use {module}::{e};\n")); + w.line(format!("pub use {module}::{e};")); } } - out + w.finish().expect("a lib.rs opens no block") } // ---- one entity ------------------------------------------------------------------------ @@ -596,7 +396,8 @@ fn filter_method(w: &mut CodeWriter, f: &FieldPlan, op: &str, p: &Param) { }); } -fn query_items( +/// The shipped [`ClientParts::query_items`]. +pub fn query_items( s: &StructPlan, route: &Route, deps: &mut BTreeSet, @@ -735,7 +536,8 @@ fn call(w: &mut CodeWriter, doc: &str, name: &str, args: Vec, returns: & }); } -fn client_item( +/// The shipped [`ClientParts::client_item`]. +pub fn client_item( plan: &Plan, s: &StructPlan, route: &Route, @@ -856,13 +658,15 @@ fn client_item( })?) } -fn entity_file( +/// The shipped [`ClientParts::entity_file`], through `parts`. +pub fn entity_file( + parts: &P, plan: &Plan, s: &StructPlan, route: &Route, deps: &mut BTreeSet, ) -> Result { - let mut items = vec![client_item(plan, s, route, deps)?]; - items.extend(query_items(s, route, deps)?); + let mut items = vec![parts.client_item(plan, s, route, deps)?]; + items.extend(parts.query_items(s, route, deps)?); Ok(file(BANNER, &items)) } diff --git a/server/rust/metaobjects-codegen/src/commands.rs b/server/rust/metaobjects-codegen/src/commands.rs index ac5eaf581c..a90b83e4aa 100644 --- a/server/rust/metaobjects-codegen/src/commands.rs +++ b/server/rust/metaobjects-codegen/src/commands.rs @@ -35,13 +35,17 @@ use std::collections::BTreeSet; +use metaobjects_codegen::emitted::COMMAND_HELPERS_RS; use metaobjects_codegen::generator::{EmittedFile, GenContext, GenError, Generator}; use metaobjects_codegen::names::{literal, pascal, snake}; use metaobjects_codegen::plan::{ CLI_CRATE, CLI_SUFFIX, CLIENT_CRATE, CLIENT_SUFFIX, CratePlan, FieldPlan, Kind, Plan, Presence, Route, SUPPORT_CRATE, StructPlan, Ty, }; -use metaobjects_codegen::writer::{CodeWriter, RUSTFMT_TOML, file, item, list, padded, piece}; +use metaobjects_codegen::writer::{ + CodeWriter, Manifest, RUSTFMT_TOML, file, fixed, item, list, padded, piece, sibling_dep, + toml_string, +}; /// Bump when the emitted text changes shape, so a stored skip key never survives it. const FORMAT: u32 = 1; @@ -49,7 +53,7 @@ const FORMAT: u32 = 1; /// The line every generated Rust file starts with. pub const BANNER: &str = "// @generated by the MetaObjects commands generator. Do not edit: change the model and run `cargo meta gen`."; -const MANIFEST_BANNER: &str = "# @generated by the MetaObjects commands generator. Do not edit: change the model and run `cargo meta gen`.\n"; +const MANIFEST_BANNER: &str = "@generated by the MetaObjects commands generator. Do not edit: change the model and run `cargo meta gen`."; /// The commands generator. #[derive(Debug, Clone, Copy, Default)] @@ -65,261 +69,105 @@ impl Generator for CommandsGenerator { } fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { - let plan = Plan::of(ctx)?; - let selected = plan.selected_crates(ctx.entities)?; - let mut files = Vec::new(); - for (cname, c) in &plan.crates { - if selected.as_ref().is_some_and(|sel| !sel.contains(cname)) { - continue; - } - command_crate(&plan, cname, c, &mut files)?; - } - if !files.is_empty() { - files.extend(helper_crate()); - } - Ok(files) - } -} - -// ---- the helper crate ------------------------------------------------------------------ - -/// The crate of helpers the command crates share. It is generated, so the output depends on -/// nothing from MetaObjects. -fn helper_crate() -> Vec { - let manifest = format!( - "{MANIFEST_BANNER}[package]\n\ - name = {}\n\ - version = \"0.1.0\"\n\ - edition = \"2021\"\n\ - publish = false\n\ - description = \"What the generated MetaObjects command crates build a request with.\"\n\ - \n\ - [dependencies]\n\ - serde = \"1\"\n\ - serde_json = \"1\"\n\ - {CLIENT_CRATE} = {{ path = \"../{CLIENT_CRATE}\" }}\n\ - {SUPPORT_CRATE} = {{ path = \"../{SUPPORT_CRATE}\" }}\n", - literal(CLI_CRATE) - ); - let file = |name: &str, text: String| EmittedFile::new(format!("{CLI_CRATE}/{name}"), text); - vec![ - file("Cargo.toml", manifest), - file("rustfmt.toml", RUSTFMT_TOML.to_string()), - file("src/lib.rs", format!("{BANNER}\n\n{HELPERS_RS}")), - ] -} - -/// `meta_cli/src/lib.rs`, in rustfmt's output form under the generated `rustfmt.toml`. -const HELPERS_RS: &str = r##"//! What every generated command crate uses: the body a command line describes, the query -//! its filters describe, and the error a command fails with. - -use std::fmt; -use std::io::Read; - -use serde::de::DeserializeOwned; -use serde::Serialize; -use serde_json::{Map, Value}; - -/// What a command returns: the server's answer as JSON (`null` when it sent none). -pub type Answer = Result; - -/// Why a command failed. -#[derive(Debug)] -pub enum Error { - /// The command line asks for something the model does not allow, or is not well formed. - Usage(String), - /// The body breaks rules of the model: one message per rule. Nothing was sent. - Invalid(Vec), - /// The call failed. - Api(meta_client::Error), -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Error::Usage(message) => f.write_str(message), - Error::Invalid(messages) => write!(f, "the body is not valid: {}", messages.join("; ")), - Error::Api(e) => e.fmt(f), - } + self.render(ctx) } } -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Error::Api(e) => Some(e), - _ => None, - } +impl CommandsParts for CommandsGenerator {} + +/// The pieces of the commands generator's output, one method each (ADR-0063 item 7). Each +/// default is the shipped piece: implement this for a generator of your own, override the +/// piece you want changed, and have its [`Generator::generate`] return `self.render(ctx)` +/// (the [`crate::entity::EntityParts`] example shows the shape). An override can call the +/// shipped piece, a public function of this module with the same name. Not a stability +/// contract: the methods may change in a minor release, and the CHANGELOG says when. +pub trait CommandsParts { + /// Every file: one command crate per package with a served entity, then the helper + /// crate when there is any. + fn render(&self, ctx: &GenContext<'_>) -> Result, GenError> { + render(self, ctx) } -} - -impl From for Error { - fn from(e: meta_client::Error) -> Self { - Error::Api(e) - } -} -/// The body a `--json` argument gives: a JSON object, read from standard input when the -/// argument is `-`, and empty when there is no argument. -pub fn body(json: Option<&str>) -> Result, Error> { - let text = match json { - None => return Ok(Map::new()), - Some("-") => { - let mut text = String::new(); - std::io::stdin().read_to_string(&mut text).map_err(|e| { - Error::Usage(format!("cannot read the body from standard input: {e}")) - })?; - text - } - Some(text) => text.to_string(), - }; - match serde_json::from_str(&text) { - Ok(Value::Object(body)) => Ok(body), - Ok(_) => Err(Error::Usage("the body must be a JSON object".to_string())), - Err(e) => Err(Error::Usage(format!("the body is not JSON: {e}"))), + /// The helper crate's files. + fn helper_crate(&self) -> Vec { + helper_crate() } -} -/// Refuses a body member the model does not declare: a misspelled name must not be dropped -/// on the way to the server, which would refuse it too under its default setting. -pub fn known(body: &Map, members: &[&str]) -> Result<(), Error> { - let unknown: Vec<&str> = - body.keys().map(String::as_str).filter(|name| !members.contains(name)).collect(); - if unknown.is_empty() { - return Ok(()); + /// A command crate's `Cargo.toml`, with a dependency on each crate in `deps`. + fn manifest(&self, name: &str, c: &CratePlan, deps: &[&str]) -> String { + cargo_toml(name, c, deps) } - Err(Error::Usage(format!( - "the body sets {}, which the model does not declare (it declares: {})", - unknown.join(", "), - members.join(", ") - ))) -} -/// Sets one member of the body from its flag, when the flag was given. -pub fn put( - body: &mut Map, - name: &str, - value: Option, -) -> Result<(), Error> { - if let Some(value) = value { - let value = serde_json::to_value(value) - .map_err(|e| Error::Usage(format!("the value of {name} cannot be sent: {e}")))?; - body.insert(name.to_string(), value); + /// A command crate's `src/lib.rs`: its modules and the `Command` and `run` over them. + /// Each group is a module, its entity's type name and its route path. + fn lib_file( + &self, + package: &str, + groups: &[(String, String, String)], + ) -> Result { + lib_file(package, groups) } - Ok(()) -} -/// Sets one array member of the body from its repeated flag, when it was given at all. -pub fn put_all( - body: &mut Map, - name: &str, - values: Vec, -) -> Result<(), Error> { - if values.is_empty() { - return Ok(()); + /// One served entity's file: its subcommands and how each runs. + fn entity_file( + &self, + s: &StructPlan, + route: &Route, + model_crate: &str, + client_crate: &str, + ) -> Result { + entity_file(s, route, model_crate, client_crate) } - put(body, name, Some(values)) } -/// Reads the finished body as the model's type. -pub fn decode(body: Map) -> Result { - serde_json::from_value(Value::Object(body)) - .map_err(|e| Error::Usage(format!("the body does not fit the model: {e}"))) -} - -/// Refuses a body that breaks rules of the model. -pub fn check(found: Vec) -> Result<(), Error> { - if found.is_empty() { - return Ok(()); - } - Err(Error::Invalid(found.into_iter().map(|v| v.message).collect())) -} - -/// Adds the `--filter` tests to a query. A test is written `field:op=value`, and -/// `field=value` means `field:eq=value`. `allowed` is the model's allowlist. -pub fn filters( - query: &mut meta_client::Query, - tests: &[String], - allowed: &[(&str, &[&str])], -) -> Result<(), Error> { - for test in tests { - let Some((subject, value)) = test.split_once('=') else { - return Err(Error::Usage(format!("--filter {test}: expected field:op=value"))); - }; - let (field, op) = subject.split_once(':').unwrap_or((subject, "eq")); - let Some((_, ops)) = allowed.iter().find(|(name, _)| *name == field) else { - let names: Vec<&str> = allowed.iter().map(|(name, _)| *name).collect(); - return Err(Error::Usage(format!( - "--filter {test}: {field} is not a field this list filters on (it filters on: {})", - names.join(", ") - ))); - }; - if !ops.contains(&op) { - return Err(Error::Usage(format!( - "--filter {test}: {field} does not take {op} (it takes: {})", - ops.join(", ") - ))); +/// The shipped [`CommandsParts::render`], through `parts`. +pub fn render( + parts: &P, + ctx: &GenContext<'_>, +) -> Result, GenError> { + let plan = Plan::of(ctx)?; + let selected = plan.selected_crates(ctx.entities)?; + let mut files = Vec::new(); + for (cname, c) in &plan.crates { + if selected.as_ref().is_some_and(|sel| !sel.contains(cname)) { + continue; } - query.filter(field, op, value); + command_crate(parts, &plan, cname, c, &mut files)?; } - Ok(()) -} - -/// Adds the `--sort` to a query: `field`, `field:asc` or `field:desc`. `allowed` is the -/// model's allowlist. -pub fn sort( - query: &mut meta_client::Query, - spec: Option<&str>, - allowed: &[&str], -) -> Result<(), Error> { - let Some(spec) = spec else { - return Ok(()); - }; - let (field, direction) = match spec.split_once(':') { - None => (spec, meta_client::Direction::Default), - Some((field, "asc")) => (field, meta_client::Direction::Ascending), - Some((field, "desc")) => (field, meta_client::Direction::Descending), - Some(_) => { - return Err(Error::Usage(format!( - "--sort {spec}: expected field, field:asc or field:desc" - ))); - } - }; - if !allowed.contains(&field) { - return Err(Error::Usage(format!( - "--sort {spec}: {field} is not a field this list sorts on (it sorts on: {})", - allowed.join(", ") - ))); + if !files.is_empty() { + files.extend(parts.helper_crate()); } - query.sort(field, direction); - Ok(()) + Ok(files) } -/// Adds the `--limit` and the `--offset` to a query. -pub fn window(query: &mut meta_client::Query, limit: Option, offset: Option) { - if let Some(limit) = limit { - query.limit(limit); - } - if let Some(offset) = offset { - query.offset(offset); - } -} - -/// What the server answered, as the JSON a command returns. -pub fn answer(found: &T) -> Answer { - serde_json::to_value(found) - .map_err(|e| Error::Usage(format!("the answer cannot be written as JSON: {e}"))) -} +// ---- the helper crate ------------------------------------------------------------------ -/// An answer as the text a command prints. -pub fn render(answer: &Value) -> String { - serde_json::to_string_pretty(answer).unwrap_or_else(|_| answer.to_string()) +/// The crate of helpers the command crates share. It is generated, so the output depends on +/// nothing from MetaObjects. +pub fn helper_crate() -> Vec { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, CLI_CRATE); + m.entry( + "description", + &toml_string("What the generated MetaObjects command crates build a request with."), + ); + m.blank().table("dependencies"); + m.entry("serde", &toml_string("1")); + m.entry("serde_json", &toml_string("1")); + m.entry(CLIENT_CRATE, &sibling_dep(CLIENT_CRATE)); + m.entry(SUPPORT_CRATE, &sibling_dep(SUPPORT_CRATE)); + let manifest = m.finish(); + let file = |name: &str, text: String| EmittedFile::new(format!("{CLI_CRATE}/{name}"), text); + vec![ + file("Cargo.toml", manifest), + file("rustfmt.toml", RUSTFMT_TOML.to_string()), + file("src/lib.rs", fixed(BANNER, COMMAND_HELPERS_RS)), + ] } -"##; // ---- one command crate ----------------------------------------------------------------- -fn command_crate( +fn command_crate( + parts: &P, plan: &Plan, cname: &str, c: &CratePlan, @@ -335,14 +183,14 @@ fn command_crate( for s in &served { let route = s.route.as_ref().expect("a served entity has a route"); groups.push((s.module(), s.type_name.clone(), route.path.clone())); - let text = entity_file(s, route, cname, &client_crate)?; + let text = parts.entity_file(s, route, cname, &client_crate)?; files.push(EmittedFile::new( format!("{name}/src/{}.rs", s.module()), text, )); } groups.sort(); - let manifest = cargo_toml(&name, c, &[cname, &client_crate]); + let manifest = parts.manifest(&name, c, &[cname, &client_crate]); files.push(EmittedFile::new(format!("{name}/Cargo.toml"), manifest)); files.push(EmittedFile::new( format!("{name}/rustfmt.toml"), @@ -350,39 +198,35 @@ fn command_crate( )); files.push(EmittedFile::new( format!("{name}/src/lib.rs"), - lib_file(&c.package, &groups)?, + parts.lib_file(&c.package, &groups)?, )); Ok(()) } -fn cargo_toml(name: &str, c: &CratePlan, deps: &[&str]) -> String { - let mut out = String::from(MANIFEST_BANNER); - out.push_str("[package]\n"); - out.push_str(&format!("name = {}\n", literal(name))); - out.push_str("version = \"0.1.0\"\n"); - out.push_str("edition = \"2021\"\n"); - out.push_str("publish = false\n"); +/// The shipped [`CommandsParts::manifest`]. +pub fn cargo_toml(name: &str, c: &CratePlan, deps: &[&str]) -> String { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, name); let package = if c.package.is_empty() { "the model's" } else { c.package.as_str() }; - out.push_str(&format!( - "description = {}\n", - literal(&format!( + m.entry( + "description", + &toml_string(&format!( "Commands over the REST API of the MetaObjects package {package}." - )) - )); - out.push_str("\n[dependencies]\n"); - out.push_str("clap = { version = \"4\", features = [\"derive\"] }\n"); - out.push_str("serde_json = \"1\"\n"); + )), + ); + m.blank().table("dependencies"); + m.entry("clap", r#"{ version = "4", features = ["derive"] }"#); + m.entry("serde_json", &toml_string("1")); for dep in [CLI_CRATE, CLIENT_CRATE] .into_iter() .chain(deps.iter().copied()) { - out.push_str(&format!("{dep} = {{ path = \"../{dep}\" }}\n")); + m.entry(dep, &sibling_dep(dep)); } - out + m.finish() } /// A match arm with one expression for a body: on one line when it fits, and in a block @@ -398,27 +242,27 @@ fn arm(w: &mut CodeWriter, pattern: &str, body: &str) { } } -fn lib_file(package: &str, groups: &[(String, String, String)]) -> Result { - let mut head = String::new(); +/// The shipped [`CommandsParts::lib_file`]. +pub fn lib_file(package: &str, groups: &[(String, String, String)]) -> Result { + let mut w = CodeWriter::new(); if package.is_empty() { - head.push_str( - "//! Commands over the REST API of the MetaObjects model that declares no package.\n", - ); + w.line("//! Commands over the REST API of the MetaObjects model that declares no package."); } else { - head.push_str(&format!( - "//! Commands over the REST API of the MetaObjects package `{package}`.\n" + w.line(format!( + "//! Commands over the REST API of the MetaObjects package `{package}`." )); } - head.push_str( - "//!\n//! Mount `Command` in your own `clap` parser and hand what it parsed to `run`.\n\n", - ); + w.line("//!"); + w.line("//! Mount `Command` in your own `clap` parser and hand what it parsed to `run`."); + w.blank(); for (module, _, _) in groups { - head.push_str(&format!("mod {module};\n")); + w.line(format!("mod {module};")); } - head.push('\n'); + w.blank(); for (module, type_name, _) in groups { - head.push_str(&format!("pub use {module}::{type_name}Command;\n")); + w.line(format!("pub use {module}::{type_name}Command;")); } + let head = w.finish()?; let what = if package.is_empty() { "What to do with the model.".to_string() } else { @@ -580,7 +424,8 @@ fn body_statements(w: &mut CodeWriter, flags: &[Flag<'_>], body_type: &str) { w.line(format!("{CLI_CRATE}::check(body.validate())?;")); } -fn entity_file( +/// The shipped [`CommandsParts::entity_file`]. +pub fn entity_file( s: &StructPlan, route: &Route, model_crate: &str, diff --git a/server/rust/metaobjects-codegen/src/eject.rs b/server/rust/metaobjects-codegen/src/eject.rs index 3ec99ba6a9..b7fcdabef4 100644 --- a/server/rust/metaobjects-codegen/src/eject.rs +++ b/server/rust/metaobjects-codegen/src/eject.rs @@ -28,6 +28,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; use metaobjects_codegen::engine::{OWNED_GENERATORS_DIR, OWNED_MAIN, OWNED_MANIFEST}; +use metaobjects_codegen::writer::{CodeWriter, Manifest, toml_string}; /// A shipped generator `eject` can hand over. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -103,6 +104,41 @@ pub const REFERENCES: &[Reference] = &[ over the client (needs entity and client; Rust only)", source: include_str!("commands.rs"), }, + Reference { + name: "render-helper", + tier: "native", + layer: "capability", + module: "render_helper", + type_name: "RenderHelperGenerator", + needs: &["entity"], + summary: "prompt crates, one per package with templates: a typed render function per \ + template.output and template.prompt, drift-checked against its payload at \ + build time (needs entity)", + source: include_str!("render_helper.rs"), + }, + Reference { + name: "output-parser", + tier: "native", + layer: "capability", + module: "output_parser", + type_name: "OutputParserGenerator", + needs: &["entity"], + summary: "parser crates, one per package with responding prompts: a strict parse and a \ + tolerant extract of each template.prompt's reply into its @responseRef type \ + (needs entity)", + source: include_str!("output_parser.rs"), + }, + Reference { + name: "output-prompt", + tier: "native", + layer: "capability", + module: "output_prompt", + type_name: "OutputPromptGenerator", + needs: &[], + summary: "format crates, one per package with responding prompts: the output-format \ + fragment that tells a model how to shape its answer", + source: include_str!("output_prompt.rs"), + }, ]; /// The shipped generator of that name. @@ -310,10 +346,10 @@ impl EngineSource { } } - /// The dependency line for one engine crate, as written in `codegen/Cargo.toml`. - fn dependency(&self, name: &str) -> String { + /// The requirement on one engine crate, as written in `codegen/Cargo.toml`. + fn requirement(&self, name: &str) -> String { match self { - EngineSource::Registry => format!("{name} = \"={}\"", env!("CARGO_PKG_VERSION")), + EngineSource::Registry => toml_string(&format!("={}", env!("CARGO_PKG_VERSION"))), EngineSource::Path(root) => { // `codegen/Cargo.toml` sits one directory below the project root. let base = if root.is_absolute() { @@ -321,116 +357,120 @@ impl EngineSource { } else { Path::new("..").join(root) }; - format!("{name} = {{ path = {} }}", toml_string(&base.join(name))) + format!("{{ path = {} }}", toml_path(&base.join(name))) } EngineSource::Git { url, rev } => match rev { - Some(r) => format!( - "{name} = {{ git = {}, rev = {} }}", - toml_str(url), - toml_str(r) - ), - None => format!("{name} = {{ git = {} }}", toml_str(url)), + Some(r) => format!("{{ git = {}, rev = {} }}", toml_string(url), toml_string(r)), + None => format!("{{ git = {} }}", toml_string(url)), }, } } - fn note(&self) -> &'static str { + /// The comment above the engine dependencies, one line each. + fn note(&self) -> &'static [&'static str] { match self { - EngineSource::Registry => { - "# The engine is the crates.io release this project ejected from, pinned exactly: an\n\ - # owned copy is that release's source. Upgrade the three versions together, then\n\ - # compare each copy with `cargo meta gen --list`. To build against a checkout or a\n\ - # git revision instead, replace each line with `{ path = \"...\" }` or\n\ - # `{ git = \"...\", rev = \"...\" }`, or eject with `--engine`.\n" - } - EngineSource::Path(_) => { - "# The engine is a checkout of the repository's `server/rust`. Change the three paths\n\ - # if it moves, or point them at a git revision or a crates.io release.\n" - } - EngineSource::Git { .. } => { - "# The engine is a git revision of the repository. Change the three entries to move to\n\ - # another revision, a checkout (`path`) or a crates.io release.\n" - } + EngineSource::Registry => &[ + "The engine is the crates.io release this project ejected from, pinned exactly: an", + "owned copy is that release's source. Upgrade the three versions together, then", + "compare each copy with `cargo meta gen --list`. To build against a checkout or a", + "git revision instead, replace each line with `{ path = \"...\" }` or", + "`{ git = \"...\", rev = \"...\" }`, or eject with `--engine`.", + ], + EngineSource::Path(_) => &[ + "The engine is a checkout of the repository's `server/rust`. Change the three paths", + "if it moves, or point them at a git revision or a crates.io release.", + ], + EngineSource::Git { .. } => &[ + "The engine is a git revision of the repository. Change the three entries to move to", + "another revision, a checkout (`path`) or a crates.io release.", + ], } } } -/// A string as a TOML basic string. -fn toml_str(text: &str) -> String { - format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\"")) -} - -/// A path as a TOML basic string. -fn toml_string(path: &Path) -> String { - let text = path.to_string_lossy().replace('\\', "/"); - toml_str(&text) +/// A path as a TOML basic string, with `/` separators on every platform. +fn toml_path(path: &Path) -> String { + toml_string(&path.to_string_lossy().replace('\\', "/")) } /// The owned crate's manifest, with the engine from `engine`. pub fn scaffold_manifest(engine: &EngineSource) -> String { - format!( - "# The generators this project owns (`cargo meta eject`). This crate is yours.\n\ - # `cargo meta gen` and `cargo meta verify` build and run it while it exists.\n\ - [package]\n\ - name = \"codegen\"\n\ - version = \"0.0.0\"\n\ - edition = \"2024\"\n\ - publish = false\n\ - \n\ - [[bin]]\n\ - name = \"codegen\"\n\ - path = \"main.rs\"\n\ - \n\ - {}\ - [dependencies]\n\ - {}\n\ - {}\n\ - {}\n\ - # What the shipped generators themselves import. Add your own beside it.\n\ - serde_json = {{ version = \"1\", features = [\"preserve_order\"] }}\n\ - \n\ - # The generators run on every `cargo meta gen`: build them optimized, once.\n\ - [profile.dev]\n\ - opt-level = 2\n\ - debug = false\n\ - \n\ - # Its own workspace, so an enclosing one neither claims nor rejects it.\n\ - [workspace]\n", - engine.note(), - engine.dependency("metaobjects"), - engine.dependency("metaobjects-cli"), - engine.dependency("metaobjects-codegen"), - ) + let mut m = Manifest::new(); + m.comment("The generators this project owns (`cargo meta eject`). This crate is yours."); + m.comment("`cargo meta gen` and `cargo meta verify` build and run it while it exists."); + m.table("package"); + m.entry("name", &toml_string("codegen")); + m.entry("version", &toml_string("0.0.0")); + m.entry("edition", &toml_string("2024")); + m.entry("publish", "false"); + m.blank().table("[bin]"); + m.entry("name", &toml_string("codegen")); + m.entry("path", &toml_string("main.rs")); + m.blank(); + for line in engine.note() { + m.comment(line); + } + m.table("dependencies"); + for name in ["metaobjects", "metaobjects-cli", "metaobjects-codegen"] { + m.entry(name, &engine.requirement(name)); + } + m.comment("What the shipped generators themselves import. Add your own beside it."); + m.entry( + "serde_json", + r#"{ version = "1", features = ["preserve_order"] }"#, + ); + m.blank() + .comment("The generators run on every `cargo meta gen`: build them optimized, once."); + m.table("profile.dev"); + m.entry("opt-level", "2"); + m.entry("debug", "false"); + m.blank() + .comment("Its own workspace, so an enclosing one neither claims nor rejects it."); + m.table("workspace"); + m.finish() } /// The owned crate's generator list, with `owned` taken from `generators/` and every other /// generator shipped. pub fn scaffold_main(owned: &[&Reference]) -> String { - let mut out = String::from( - "//! The generators `cargo meta gen` and `cargo meta verify` run for this project.\n\ - //!\n\ - //! This file is yours. Each module under `generators/` is a copy `cargo meta eject` made\n\ - //! of the shipped generator of that name; edit it freely. Keep each generator in the\n\ - //! list once: its owned copy or the shipped one, never both (they write the same files).\n\ - \n\ - use metaobjects_codegen::Generator;\n\ - \n\ - mod generators {\n", + let mut w = CodeWriter::new(); + w.line("//! The generators `cargo meta gen` and `cargo meta verify` run for this project."); + w.line("//!"); + w.line( + "//! This file is yours. Each module under `generators/` is a copy `cargo meta eject` made", ); - for r in owned { - out.push_str(&format!(" pub mod {};\n", r.module)); - } - out.push_str("}\n\nfn main() {\n let generators: Vec> = vec![\n"); - for r in REFERENCES { - let entry = if owned.contains(&r) { - r.owned_entry() - } else { - r.shipped_entry() - }; - out.push_str(&format!(" {entry},\n")); - } - out.push_str(" ];\n std::process::exit(metaobjects_cli::owned_main(generators));\n}\n"); - out + w.line("//! of the shipped generator of that name; edit it freely. Keep each generator in the"); + w.line( + "//! list once: its owned copy or the shipped one, never both (they write the same files).", + ); + w.blank(); + w.line("use metaobjects_codegen::Generator;"); + w.blank(); + w.block("mod generators {", |w| { + for r in owned { + w.line(format!("pub mod {};", r.module)); + } + }); + w.blank(); + w.block("fn main() {", |w| { + w.block_with( + "let generators: Vec> = vec![", + "];", + |w| { + for r in REFERENCES { + let entry = if owned.contains(&r) { + r.owned_entry() + } else { + r.shipped_entry() + }; + w.line(format!("{entry},")); + } + }, + ); + w.line("std::process::exit(metaobjects_cli::owned_main(generators));"); + }); + w.finish() + .expect("the owned main.rs closes every block it opens") } fn write_new(path: &Path, text: &str) -> Result<(), EjectError> { diff --git a/server/rust/metaobjects-codegen/src/emitted/client_transport.rs b/server/rust/metaobjects-codegen/src/emitted/client_transport.rs new file mode 100644 index 0000000000..f94d224900 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/emitted/client_transport.rs @@ -0,0 +1,265 @@ +//! The transport every generated client crate uses: one HTTP client, the list query, and +//! the error a call fails with. It follows the REST contract every MetaObjects server +//! generator implements, whatever language the server is written in. + +use std::fmt; + +use serde::de::DeserializeOwned; +use serde::Serialize; + +/// The HTTP library underneath, so a caller can set a client up without naming it as a +/// dependency of its own. +pub use reqwest; + +/// What a call returns. +pub type Result = std::result::Result; + +/// Why a call failed. +#[derive(Debug)] +pub enum Error { + /// The request did not get an answer. + Transport(reqwest::Error), + /// The server refused the request. `code` and `message` are its error body's `error` and + /// `message` members, when it sent them; `body` is the body as it arrived. + Api { status: u16, code: Option, message: Option, body: String }, + /// The server answered, and the body is not what the model says a row looks like. + Decode { status: u16, message: String }, +} + +impl Error { + /// The HTTP status of the answer, when there was one. + pub fn status(&self) -> Option { + match self { + Error::Transport(e) => e.status().map(|s| s.as_u16()), + Error::Api { status, .. } | Error::Decode { status, .. } => Some(*status), + } + } + + /// The server's error code (`not_found`, `validation`, ...), when it sent one. + pub fn code(&self) -> Option<&str> { + match self { + Error::Api { code, .. } => code.as_deref(), + _ => None, + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Transport(e) => write!(f, "the request failed: {e}"), + Error::Api { status, code, message, .. } => { + write!(f, "the server answered {status}")?; + if let Some(code) = code { + write!(f, " {code}")?; + } + if let Some(message) = message { + write!(f, ": {message}")?; + } + Ok(()) + } + Error::Decode { status, message } => { + write!(f, "the server answered {status} with a body that does not fit: {message}") + } + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Transport(e) => Some(e), + _ => None, + } + } +} + +impl From for Error { + fn from(e: reqwest::Error) -> Self { + Error::Transport(e) + } +} + +/// The API's address and the HTTP client that reaches it. +#[derive(Debug, Clone)] +pub struct Client { + http: reqwest::Client, + base: String, +} + +impl Client { + /// A client for the API at `base_url`: the server's address and the prefix its routes + /// are mounted under, as in `https://example.com/api`. + pub fn new(base_url: &str) -> Self { + Self::with_http(reqwest::Client::new(), base_url) + } + + /// The same, over an HTTP client you set up yourself (timeouts, headers, a proxy). + pub fn with_http(http: reqwest::Client, base_url: &str) -> Self { + Self { http, base: base_url.trim_end_matches('/').to_string() } + } + + /// The address every path is taken under. + pub fn base_url(&self) -> &str { + &self.base + } + + fn url(&self, path: &str) -> String { + format!("{}/{}", self.base, path) + } + + /// `GET path`, read as `T`. + pub async fn get(&self, path: &str) -> Result { + read(self.http.get(self.url(path)).send().await?).await + } + + /// `GET path?query`, read as `T`. + pub async fn list(&self, path: &str, query: &Query) -> Result { + read(self.http.get(self.url(path)).query(query.pairs()).send().await?).await + } + + /// `POST path` with a JSON body, read as `T`. + pub async fn post(&self, path: &str, body: &B) -> Result + where + B: Serialize + ?Sized, + T: DeserializeOwned, + { + read(self.http.post(self.url(path)).json(body).send().await?).await + } + + /// `PATCH path` with a JSON body, read as `T`. + pub async fn patch(&self, path: &str, body: &B) -> Result + where + B: Serialize + ?Sized, + T: DeserializeOwned, + { + read(self.http.patch(self.url(path)).json(body).send().await?).await + } + + /// `DELETE path`. + pub async fn delete(&self, path: &str) -> Result<()> { + let response = self.http.delete(self.url(path)).send().await?; + if response.status().is_success() { + return Ok(()); + } + Err(refusal(response).await) + } +} + +async fn read(response: reqwest::Response) -> Result { + let status = response.status(); + if !status.is_success() { + return Err(refusal(response).await); + } + let text = response.text().await?; + serde_json::from_str(&text) + .map_err(|e| Error::Decode { status: status.as_u16(), message: e.to_string() }) +} + +async fn refusal(response: reqwest::Response) -> Error { + let status = response.status().as_u16(); + let body = response.text().await.unwrap_or_default(); + let parsed: Option = serde_json::from_str(&body).ok(); + let member = |name: &str| { + parsed.as_ref().and_then(|v| v.get(name)).and_then(|v| v.as_str()).map(str::to_string) + }; + Error::Api { status, code: member("error"), message: member("message"), body } +} + +/// The order a sort puts rows in. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Direction { + /// The order the model declares for the field (ascending when it declares none). + Default, + Ascending, + Descending, +} + +/// The query of a list request: filters, a sort and a window. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Query { + pairs: Vec<(String, String)>, +} + +impl Query { + pub fn new() -> Self { + Self::default() + } + + /// The query's parameters, in the order they were added, not yet percent-encoded. + pub fn pairs(&self) -> &[(String, String)] { + &self.pairs + } + + fn set(&mut self, name: &str, value: String) { + self.pairs.retain(|(n, _)| n != name); + self.pairs.push((name.to_string(), value)); + } + + /// Keep the rows whose `field` passes `op` against `value`. Filters add up: a row must + /// pass them all. + pub fn filter(&mut self, field: &str, op: &str, value: impl fmt::Display) { + self.pairs.push((format!("filter[{field}][{op}]"), value.to_string())); + } + + /// Keep the rows whose `field` is one of `values`. + pub fn filter_in(&mut self, field: &str, values: impl IntoIterator) { + let joined: Vec = values.into_iter().map(|v| v.to_string()).collect(); + self.filter(field, "in", joined.join(",")); + } + + /// Sort by `field`. A later sort replaces an earlier one: the contract has one sort key. + pub fn sort(&mut self, field: &str, direction: Direction) { + let value = match direction { + Direction::Default => field.to_string(), + Direction::Ascending => format!("{field}:asc"), + Direction::Descending => format!("{field}:desc"), + }; + self.set("sort", value); + } + + /// Return at most `rows` rows. + pub fn limit(&mut self, rows: u64) { + self.set("limit", rows.to_string()); + } + + /// Skip the first `rows` rows. + pub fn offset(&mut self, rows: u64) { + self.set("offset", rows.to_string()); + } + + /// Ask for the `{ rows, total }` answer a [`Page`] reads. + pub fn with_count(&mut self) { + self.set("withCount", "1".to_string()); + } +} + +/// One window of a list, and how many rows the filters match in all. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Page { + pub rows: Vec, + pub total: u64, +} + +/// The path of one row: `collection/id`, with the id percent-encoded. +pub fn row(collection: &str, id: impl fmt::Display) -> String { + format!("{collection}/{}", segment(&id.to_string())) +} + +/// The path of the rows related to one row: `collection/id/relation`. +pub fn related(collection: &str, id: impl fmt::Display, relation: &str) -> String { + format!("{}/{relation}", row(collection, id)) +} + +/// One path segment, percent-encoded: everything but RFC 3986's unreserved characters. +pub fn segment(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for byte in text.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + out.push(char::from(byte)); + } else { + out.push_str(&format!("%{byte:02X}")); + } + } + out +} diff --git a/server/rust/metaobjects-codegen/src/emitted/command_helpers.rs b/server/rust/metaobjects-codegen/src/emitted/command_helpers.rs new file mode 100644 index 0000000000..4cc5731000 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/emitted/command_helpers.rs @@ -0,0 +1,205 @@ +//! What every generated command crate uses: the body a command line describes, the query +//! its filters describe, and the error a command fails with. + +use std::fmt; +use std::io::Read; + +use serde::de::DeserializeOwned; +use serde::Serialize; +use serde_json::{Map, Value}; + +/// What a command returns: the server's answer as JSON (`null` when it sent none). +pub type Answer = Result; + +/// Why a command failed. +#[derive(Debug)] +pub enum Error { + /// The command line asks for something the model does not allow, or is not well formed. + Usage(String), + /// The body breaks rules of the model: one message per rule. Nothing was sent. + Invalid(Vec), + /// The call failed. + Api(meta_client::Error), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Usage(message) => f.write_str(message), + Error::Invalid(messages) => write!(f, "the body is not valid: {}", messages.join("; ")), + Error::Api(e) => e.fmt(f), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Api(e) => Some(e), + _ => None, + } + } +} + +impl From for Error { + fn from(e: meta_client::Error) -> Self { + Error::Api(e) + } +} + +/// The body a `--json` argument gives: a JSON object, read from standard input when the +/// argument is `-`, and empty when there is no argument. +pub fn body(json: Option<&str>) -> Result, Error> { + let text = match json { + None => return Ok(Map::new()), + Some("-") => { + let mut text = String::new(); + std::io::stdin().read_to_string(&mut text).map_err(|e| { + Error::Usage(format!("cannot read the body from standard input: {e}")) + })?; + text + } + Some(text) => text.to_string(), + }; + match serde_json::from_str(&text) { + Ok(Value::Object(body)) => Ok(body), + Ok(_) => Err(Error::Usage("the body must be a JSON object".to_string())), + Err(e) => Err(Error::Usage(format!("the body is not JSON: {e}"))), + } +} + +/// Refuses a body member the model does not declare: a misspelled name must not be dropped +/// on the way to the server, which would refuse it too under its default setting. +pub fn known(body: &Map, members: &[&str]) -> Result<(), Error> { + let unknown: Vec<&str> = + body.keys().map(String::as_str).filter(|name| !members.contains(name)).collect(); + if unknown.is_empty() { + return Ok(()); + } + Err(Error::Usage(format!( + "the body sets {}, which the model does not declare (it declares: {})", + unknown.join(", "), + members.join(", ") + ))) +} + +/// Sets one member of the body from its flag, when the flag was given. +pub fn put( + body: &mut Map, + name: &str, + value: Option, +) -> Result<(), Error> { + if let Some(value) = value { + let value = serde_json::to_value(value) + .map_err(|e| Error::Usage(format!("the value of {name} cannot be sent: {e}")))?; + body.insert(name.to_string(), value); + } + Ok(()) +} + +/// Sets one array member of the body from its repeated flag, when it was given at all. +pub fn put_all( + body: &mut Map, + name: &str, + values: Vec, +) -> Result<(), Error> { + if values.is_empty() { + return Ok(()); + } + put(body, name, Some(values)) +} + +/// Reads the finished body as the model's type. +pub fn decode(body: Map) -> Result { + serde_json::from_value(Value::Object(body)) + .map_err(|e| Error::Usage(format!("the body does not fit the model: {e}"))) +} + +/// Refuses a body that breaks rules of the model. +pub fn check(found: Vec) -> Result<(), Error> { + if found.is_empty() { + return Ok(()); + } + Err(Error::Invalid(found.into_iter().map(|v| v.message).collect())) +} + +/// Adds the `--filter` tests to a query. A test is written `field:op=value`, and +/// `field=value` means `field:eq=value`. `allowed` is the model's allowlist. +pub fn filters( + query: &mut meta_client::Query, + tests: &[String], + allowed: &[(&str, &[&str])], +) -> Result<(), Error> { + for test in tests { + let Some((subject, value)) = test.split_once('=') else { + return Err(Error::Usage(format!("--filter {test}: expected field:op=value"))); + }; + let (field, op) = subject.split_once(':').unwrap_or((subject, "eq")); + let Some((_, ops)) = allowed.iter().find(|(name, _)| *name == field) else { + let names: Vec<&str> = allowed.iter().map(|(name, _)| *name).collect(); + return Err(Error::Usage(format!( + "--filter {test}: {field} is not a field this list filters on (it filters on: {})", + names.join(", ") + ))); + }; + if !ops.contains(&op) { + return Err(Error::Usage(format!( + "--filter {test}: {field} does not take {op} (it takes: {})", + ops.join(", ") + ))); + } + query.filter(field, op, value); + } + Ok(()) +} + +/// Adds the `--sort` to a query: `field`, `field:asc` or `field:desc`. `allowed` is the +/// model's allowlist. +pub fn sort( + query: &mut meta_client::Query, + spec: Option<&str>, + allowed: &[&str], +) -> Result<(), Error> { + let Some(spec) = spec else { + return Ok(()); + }; + let (field, direction) = match spec.split_once(':') { + None => (spec, meta_client::Direction::Default), + Some((field, "asc")) => (field, meta_client::Direction::Ascending), + Some((field, "desc")) => (field, meta_client::Direction::Descending), + Some(_) => { + return Err(Error::Usage(format!( + "--sort {spec}: expected field, field:asc or field:desc" + ))); + } + }; + if !allowed.contains(&field) { + return Err(Error::Usage(format!( + "--sort {spec}: {field} is not a field this list sorts on (it sorts on: {})", + allowed.join(", ") + ))); + } + query.sort(field, direction); + Ok(()) +} + +/// Adds the `--limit` and the `--offset` to a query. +pub fn window(query: &mut meta_client::Query, limit: Option, offset: Option) { + if let Some(limit) = limit { + query.limit(limit); + } + if let Some(offset) = offset { + query.offset(offset); + } +} + +/// What the server answered, as the JSON a command returns. +pub fn answer(found: &T) -> Answer { + serde_json::to_value(found) + .map_err(|e| Error::Usage(format!("the answer cannot be written as JSON: {e}"))) +} + +/// An answer as the text a command prints. +pub fn render(answer: &Value) -> String { + serde_json::to_string_pretty(answer).unwrap_or_else(|_| answer.to_string()) +} diff --git a/server/rust/metaobjects-codegen/src/emitted/mod.rs b/server/rust/metaobjects-codegen/src/emitted/mod.rs index 01d37dffc6..6acd0bec28 100644 --- a/server/rust/metaobjects-codegen/src/emitted/mod.rs +++ b/server/rust/metaobjects-codegen/src/emitted/mod.rs @@ -1,8 +1,8 @@ -//! Source the `entity` generator writes verbatim into the generated support crate. +//! Source the generators write verbatim into generated crates. //! //! The three modules are real code here, compiled and tested with the engine (the shared //! `decimal-wire` and `duration-wire` vectors and the validation corpus run against them -//! directly), and the generator emits the same bytes as `meta_support/src/`. The generated +//! directly), and the `entity` generator emits the same bytes as `meta_support/src/`. The generated //! crates therefore carry their wire types and validation checks as their own source and //! depend on nothing from MetaObjects. //! @@ -22,3 +22,12 @@ pub const PATTERN_RS: &str = include_str!("pattern.rs"); pub const VALIDATION_RS: &str = include_str!("validation.rs"); /// The text of `src/wire.rs` in a generated crate. pub const WIRE_RS: &str = include_str!("wire.rs"); + +// Two more files are fixed text a generator writes whole but are not compiled here: they are +// written for the dependencies of the crate they land in (`reqwest` for the transport), which +// this crate does not have. The compile gate builds them in a generated workspace. + +/// The text of `meta_client/src/lib.rs`, the transport the `client` generator's crates share. +pub const CLIENT_TRANSPORT_RS: &str = include_str!("client_transport.rs"); +/// The text of `meta_cli/src/lib.rs`, the helpers the `commands` generator's crates share. +pub const COMMAND_HELPERS_RS: &str = include_str!("command_helpers.rs"); diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index e0e18dc1e4..3cecce7697 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -298,6 +298,24 @@ pub const OWNED_MAIN: &str = "codegen/main.rs"; /// Everything a run knows before it renders: the loaded model, where the files go, the /// manifest and the skip key. +/// A generator the run applies: one the host offered, or the one an entry's options +/// constructed in its place. +enum Selected<'g> { + Offered(&'g dyn Generator), + Configured(Box), +} + +impl<'g> std::ops::Deref for Selected<'g> { + type Target = dyn Generator + 'g; + + fn deref(&self) -> &Self::Target { + match self { + Selected::Offered(g) => *g, + Selected::Configured(g) => g.as_ref(), + } + } +} + struct Prepared<'g> { loaded: LoadedProject, project_root: PathBuf, @@ -305,7 +323,7 @@ struct Prepared<'g> { out_rel: String, gen_state: PathBuf, manifest: HashManifest, - selected: Vec<&'g dyn Generator>, + selected: Vec>, cacheable: bool, key: String, stored: Option, @@ -366,7 +384,8 @@ fn prepare<'g>( let start = Instant::now(); // The project's own list narrows what the host offers; `--generators` narrows it again, // but only within the list, so a flag never runs what the project left out. - let listed = generator_list::read(&project_root).map_err(RunError::GeneratorList)?; + let entries = generator_list::read(&project_root).map_err(RunError::GeneratorList)?; + let listed = entries.as_deref().map(generator_list::names); if let Some(names) = &listed { let available: Vec<&str> = generators.iter().map(|g| g.name()).collect(); generator_list::check(names, &available).map_err(RunError::GeneratorList)?; @@ -380,20 +399,35 @@ fn prepare<'g>( listed.join(", ") ))); } - let selected: Vec<&dyn Generator> = generators - .iter() - .map(AsRef::as_ref) - .filter(|g| { - listed - .as_ref() - .is_none_or(|l| l.iter().any(|n| n == g.name())) - }) - .filter(|g| { - opts.generators - .as_ref() - .is_none_or(|names| names.iter().any(|n| n == g.name())) - }) - .collect(); + // An entry with options constructs its generator from them, and that one runs in the + // offered generator's place; a generator refuses an option it does not take. + let mut selected: Vec> = Vec::with_capacity(generators.len()); + for g in generators { + let in_list = listed + .as_ref() + .is_none_or(|l| l.iter().any(|n| n == g.name())); + let flagged = opts + .generators + .as_ref() + .is_none_or(|names| names.iter().any(|n| n == g.name())); + if !in_list { + continue; + } + let options = entries + .as_deref() + .and_then(|es| es.iter().find(|e| e.name == g.name())) + .map(|e| &e.options) + .filter(|o| !o.is_empty()); + // Every listed entry's options are checked, even on a run `--generators` narrows, so + // a misspelt option fails the first run rather than the first one that includes it. + let chosen = match options { + Some(o) => Selected::Configured(g.configure(o).map_err(RunError::Generator)?), + None => Selected::Offered(g.as_ref()), + }; + if flagged { + selected.push(chosen); + } + } let out_dir = normalize(&if opts.out_dir.is_absolute() { opts.out_dir.clone() } else { diff --git a/server/rust/metaobjects-codegen/src/entity.rs b/server/rust/metaobjects-codegen/src/entity.rs index 98b16ddb47..7e407ec53a 100644 --- a/server/rust/metaobjects-codegen/src/entity.rs +++ b/server/rust/metaobjects-codegen/src/entity.rs @@ -56,7 +56,9 @@ use metaobjects_codegen::plan::{ Class, CmpOp, Cond, CratePlan, CrossKind, CrossRule, EnumPlan, FieldPlan, Format, Kind, Literal, NullMembers, Operand, Plan, Presence, SUPPORT_CRATE, StructPlan, Ty, }; -use metaobjects_codegen::writer::{CodeWriter, Piece, RUSTFMT_TOML, file, item, list}; +use metaobjects_codegen::writer::{ + CodeWriter, Manifest, Piece, RUSTFMT_TOML, file, fixed, item, list, sibling_dep, toml_string, +}; /// Bump when the emitted text changes shape, so a stored skip key never survives it. const FORMAT: u32 = 2; @@ -64,7 +66,7 @@ const FORMAT: u32 = 2; /// The line every generated Rust file starts with. pub const BANNER: &str = "// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`."; -const MANIFEST_BANNER: &str = "# @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`.\n"; +const MANIFEST_BANNER: &str = "@generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`."; const VALIDATION: &str = "meta_support::validation"; const WIRE: &str = "meta_support::wire"; @@ -85,46 +87,147 @@ impl Generator for EntityGenerator { } fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { - let plan = Plan::of(ctx)?; - let selected = plan.selected_crates(ctx.entities)?; - let mut files = support_crate(); - for (cname, c) in &plan.crates { - if selected.as_ref().is_some_and(|sel| !sel.contains(cname)) { - continue; - } - model_crate(&plan, cname, c, &mut files)?; + self.render(ctx) + } +} + +impl EntityParts for EntityGenerator {} + +/// The pieces of the entity generator's output, one method each (ADR-0063 item 7). Each +/// default is the shipped piece, so a generator of your own implements this, overrides the +/// piece it wants changed, and keeps taking every other change the shipped generator gets: +/// +/// ```ignore +/// struct MyEntity; +/// +/// impl EntityParts for MyEntity { +/// fn enum_item(&self, w: &mut CodeWriter, e: &EnumPlan) { +/// w.line("#[non_exhaustive]"); +/// entity::enum_item(w, e); +/// } +/// } +/// +/// impl Generator for MyEntity { +/// fn name(&self) -> &str { +/// "entity" +/// } +/// fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { +/// self.render(ctx) +/// } +/// } +/// ``` +/// +/// An override can call the shipped piece, a public function of this module with the same +/// name, and add to it. These methods are not a stability contract: they may be renamed, split +/// or change signature in a minor release, and the CHANGELOG says when. Eject for a contract. +pub trait EntityParts { + /// Every file: the support crate, then one model crate per package the run selects. + fn render(&self, ctx: &GenContext<'_>) -> Result, GenError> { + render(self, ctx) + } + + /// The support crate's files. + fn support_crate(&self) -> Vec { + support_crate() + } + + /// A model crate's `Cargo.toml`. + fn manifest(&self, name: &str, c: &CratePlan) -> String { + cargo_toml(name, c) + } + + /// A model crate's `src/lib.rs`: each module and what it exports. + fn lib_file(&self, package: &str, items: &[(String, Vec)]) -> String { + lib_file(package, items) + } + + /// One object's file: its struct, its create and patch bodies with their `validate()` + /// (or, for a value object, its own `validate()`), and its enums. + fn struct_file( + &self, + plan: &Plan, + s: &StructPlan, + current: &str, + q: &Qualifier<'_>, + ) -> Result { + struct_file(self, plan, s, current, q) + } + + /// One of an object's structs: the read type, the create body or the patch body. + fn struct_item( + &self, + w: &mut CodeWriter, + plan: &Plan, + s: &StructPlan, + shape: Shape, + current: &str, + q: &Qualifier<'_>, + ) { + struct_item(w, plan, s, shape, current, q); + } + + /// The `validate()` of one of an object's structs. + fn validate_item( + &self, + w: &mut CodeWriter, + plan: &Plan, + s: &StructPlan, + shape: Shape, + q: &Qualifier<'_>, + ) { + validate_item(w, plan, s, shape, q); + } + + /// One enum. + fn enum_item(&self, w: &mut CodeWriter, e: &EnumPlan) { + enum_item(w, e); + } +} + +/// The shipped [`EntityParts::render`], through `parts`. +pub fn render( + parts: &P, + ctx: &GenContext<'_>, +) -> Result, GenError> { + let plan = Plan::of(ctx)?; + let selected = plan.selected_crates(ctx.entities)?; + let mut files = parts.support_crate(); + for (cname, c) in &plan.crates { + if selected.as_ref().is_some_and(|sel| !sel.contains(cname)) { + continue; } - Ok(files) + model_crate(parts, &plan, cname, c, &mut files)?; } + Ok(files) } // ---- crates ---------------------------------------------------------------------------- /// The crate of wire types and checks the model crates share. It is generated, so the /// output depends on nothing from MetaObjects. -fn support_crate() -> Vec { - let manifest = format!( - "{MANIFEST_BANNER}[package]\n\ - name = {}\n\ - version = \"0.1.0\"\n\ - edition = \"2021\"\n\ - publish = false\n\ - description = \"Wire types and validation checks for the generated MetaObjects model crates.\"\n\ - \n\ - [dependencies]\n\ - serde = \"1\"\n", - literal(SUPPORT_CRATE) - ); - let lib = format!( - "{BANNER}\n\ - \n\ - //! What every generated model crate uses: the exact `Decimal` and the ISO-8601\n\ - //! `Duration` of the wire form, and the checks `validate()` is written in.\n\ - \n\ - pub mod pattern;\n\ - pub mod validation;\n\ - pub mod wire;\n" +pub fn support_crate() -> Vec { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, SUPPORT_CRATE); + m.entry( + "description", + &toml_string( + "Wire types and validation checks for the generated MetaObjects model crates.", + ), ); + m.blank() + .table("dependencies") + .entry("serde", &toml_string("1")); + let manifest = m.finish(); + let mut w = CodeWriter::new(); + w.line(BANNER).blank(); + w.line("//! What every generated model crate uses: the exact `Decimal` and the ISO-8601"); + w.line("//! `Duration` of the wire form, and the checks `validate()` is written in."); + w.blank(); + for module in ["pattern", "validation", "wire"] { + w.line(format!("pub mod {module};")); + } + let lib = w + .finish() + .expect("the support crate's lib.rs opens no block"); let file = |name: &str, text: &str| { EmittedFile::new(format!("{SUPPORT_CRATE}/{name}"), text.to_string()) }; @@ -132,13 +235,14 @@ fn support_crate() -> Vec { file("Cargo.toml", &manifest), file("rustfmt.toml", RUSTFMT_TOML), file("src/lib.rs", &lib), - file("src/pattern.rs", &format!("{BANNER}\n\n{PATTERN_RS}")), - file("src/validation.rs", &format!("{BANNER}\n\n{VALIDATION_RS}")), - file("src/wire.rs", &format!("{BANNER}\n\n{WIRE_RS}")), + file("src/pattern.rs", &fixed(BANNER, PATTERN_RS)), + file("src/validation.rs", &fixed(BANNER, VALIDATION_RS)), + file("src/wire.rs", &fixed(BANNER, WIRE_RS)), ] } -fn model_crate( +fn model_crate( + parts: &P, plan: &Plan, cname: &str, c: &CratePlan, @@ -146,7 +250,7 @@ fn model_crate( ) -> Result<(), GenError> { files.push(EmittedFile::new( format!("{cname}/Cargo.toml"), - cargo_toml(cname, c), + parts.manifest(cname, c), )); files.push(EmittedFile::new( format!("{cname}/rustfmt.toml"), @@ -175,7 +279,7 @@ fn model_crate( } exports.extend(s.enums.iter().map(|e| e.type_name.clone())); lib_items.push((s.module(), exports)); - let text = struct_file(plan, s, cname, &q)?; + let text = parts.struct_file(plan, s, cname, &q)?; files.push(EmittedFile::new( format!("{cname}/src/{}.rs", s.module()), text, @@ -184,64 +288,60 @@ fn model_crate( for (_, e) in &c.shared_enums { let module = module_name(&e.type_name); lib_items.push((module.clone(), vec![e.type_name.clone()])); - let text = file(BANNER, &[item(|w| enum_item(w, e))?]); + let text = file(BANNER, &[item(|w| parts.enum_item(w, e))?]); files.push(EmittedFile::new(format!("{cname}/src/{module}.rs"), text)); } lib_items.sort(); files.push(EmittedFile::new( format!("{cname}/src/lib.rs"), - lib_file(&c.package, &lib_items), + parts.lib_file(&c.package, &lib_items), )); Ok(()) } -fn cargo_toml(name: &str, c: &CratePlan) -> String { - let mut out = String::from(MANIFEST_BANNER); - out.push_str("[package]\n"); - out.push_str(&format!("name = {}\n", literal(name))); - out.push_str("version = \"0.1.0\"\n"); - out.push_str("edition = \"2021\"\n"); - out.push_str("publish = false\n"); +/// The shipped [`EntityParts::manifest`]. +pub fn cargo_toml(name: &str, c: &CratePlan) -> String { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, name); if !c.package.is_empty() { - out.push_str(&format!( - "description = {}\n", - literal(&format!( + m.entry( + "description", + &toml_string(&format!( "Generated from the MetaObjects package {}.", c.package - )) - )); + )), + ); } - out.push_str("\n[dependencies]\n"); - out.push_str("serde = { version = \"1\", features = [\"derive\"] }\n"); - out.push_str(&format!( - "{SUPPORT_CRATE} = {{ path = \"../{SUPPORT_CRATE}\" }}\n" - )); + m.blank().table("dependencies"); + m.entry("serde", r#"{ version = "1", features = ["derive"] }"#); + m.entry(SUPPORT_CRATE, &sibling_dep(SUPPORT_CRATE)); for dep in &c.deps { - out.push_str(&format!("{dep} = {{ path = \"../{dep}\" }}\n")); + m.entry(dep, &sibling_dep(dep)); } - out + m.finish() } -fn lib_file(package: &str, items: &[(String, Vec)]) -> String { - let mut out = format!("{BANNER}\n\n"); +/// The shipped [`EntityParts::lib_file`]. +pub fn lib_file(package: &str, items: &[(String, Vec)]) -> String { + let mut w = CodeWriter::new(); + w.line(BANNER).blank(); if package.is_empty() { - out.push_str("//! Generated from the MetaObjects model that declares no package.\n"); + w.line("//! Generated from the MetaObjects model that declares no package."); } else { - out.push_str(&format!( - "//! Generated from the MetaObjects package `{package}`.\n" + w.line(format!( + "//! Generated from the MetaObjects package `{package}`." )); } - out.push('\n'); + w.blank(); for (module, _) in items { - out.push_str(&format!("mod {module};\n")); + w.line(format!("mod {module};")); } - out.push('\n'); + w.blank(); for (module, exports) in items { for e in exports { - out.push_str(&format!("pub use {module}::{e};\n")); + w.line(format!("pub use {module}::{e};")); } } - out + w.finish().expect("a lib.rs opens no block") } // ---- text ------------------------------------------------------------------------------ @@ -252,12 +352,13 @@ fn text(s: impl Into) -> Piece { /// Spells a std type by its short name, or by its full path in a crate that declares a type /// with the same name (an object called `Option` must not capture the field types). -struct Qualifier<'a> { +pub struct Qualifier<'a> { shadowed: HashSet<&'a str>, } impl Qualifier<'_> { - fn std(&self, short: &'static str, full: &'static str) -> &'static str { + /// `short`, or `full` when the crate declares a type named `short`. + pub fn std(&self, short: &'static str, full: &'static str) -> &'static str { if self.shadowed.contains(short) { full } else { @@ -265,11 +366,11 @@ impl Qualifier<'_> { } } - fn vec(&self) -> &'static str { + pub fn vec(&self) -> &'static str { self.std("Vec", "std::vec::Vec") } - fn option(&self) -> &'static str { + pub fn option(&self) -> &'static str { self.std("Option", "std::option::Option") } } @@ -292,8 +393,8 @@ fn render_ty(ty: &Ty, current: &str, q: &Qualifier<'_>) -> String { } /// Which of an object's three types a member belongs to. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Shape { +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Shape { Read, Create, Patch, @@ -345,7 +446,8 @@ fn member_type(f: &FieldPlan, shape: Shape, current: &str, q: &Qualifier<'_>) -> } } -fn enum_item(w: &mut CodeWriter, e: &EnumPlan) { +/// The shipped [`EntityParts::enum_item`]. +pub fn enum_item(w: &mut CodeWriter, e: &EnumPlan) { if let Some(doc) = &e.doc { w.doc(doc); } @@ -378,7 +480,8 @@ fn enum_item(w: &mut CodeWriter, e: &EnumPlan) { }); } -fn struct_item( +/// The shipped [`EntityParts::struct_item`]. +pub fn struct_item( w: &mut CodeWriter, plan: &Plan, s: &StructPlan, @@ -405,9 +508,10 @@ fn struct_item( } Shape::Patch => { w.doc(&format!( - "A change to one `{}`: a member left `None` is not touched. A member the model lets be\nnull is `Some(None)` to set it to null.", + "A change to one `{}`: a member left `None` is not touched. A member the model lets be", s.type_name )); + w.doc("null is `Some(None)` to set it to null."); } } let default = if derive_default { "Default, " } else { "" }; @@ -1014,7 +1118,14 @@ fn cross_check(s: &StructPlan, rule: &CrossRule, n: &mut usize, out: &mut Vec) { +/// The shipped [`EntityParts::validate_item`]. +pub fn validate_item( + w: &mut CodeWriter, + plan: &Plan, + s: &StructPlan, + shape: Shape, + q: &Qualifier<'_>, +) { let name = match shape { Shape::Read => s.type_name.clone(), Shape::Create => s.create_name(), @@ -1049,23 +1160,27 @@ fn validate_item(w: &mut CodeWriter, plan: &Plan, s: &StructPlan, shape: Shape, }); } -fn struct_file( +/// The shipped [`EntityParts::struct_file`], through `parts`. +pub fn struct_file( + parts: &P, plan: &Plan, s: &StructPlan, current: &str, q: &Qualifier<'_>, ) -> Result { - let mut items = vec![item(|w| struct_item(w, plan, s, Shape::Read, current, q))?]; + let mut items = vec![item(|w| { + parts.struct_item(w, plan, s, Shape::Read, current, q) + })?]; if s.is_entity { for shape in [Shape::Create, Shape::Patch] { - items.push(item(|w| struct_item(w, plan, s, shape, current, q))?); - items.push(item(|w| validate_item(w, plan, s, shape, q))?); + items.push(item(|w| parts.struct_item(w, plan, s, shape, current, q))?); + items.push(item(|w| parts.validate_item(w, plan, s, shape, q))?); } } else { - items.push(item(|w| validate_item(w, plan, s, Shape::Read, q))?); + items.push(item(|w| parts.validate_item(w, plan, s, Shape::Read, q))?); } for e in &s.enums { - items.push(item(|w| enum_item(w, e))?); + items.push(item(|w| parts.enum_item(w, e))?); } Ok(file(BANNER, &items)) } diff --git a/server/rust/metaobjects-codegen/src/generator.rs b/server/rust/metaobjects-codegen/src/generator.rs index 5f36c6e5e0..01b66cd0e7 100644 --- a/server/rust/metaobjects-codegen/src/generator.rs +++ b/server/rust/metaobjects-codegen/src/generator.rs @@ -81,6 +81,34 @@ pub const ERR_UNSUPPORTED: &str = "ERR_RUST_UNSUPPORTED"; pub const ERR_CRATE_CYCLE: &str = "ERR_CRATE_CYCLE"; /// The output directory is not inside the project. pub const ERR_OUT_DIR: &str = "ERR_OUT_DIR_OUTSIDE_PROJECT"; +/// A project gave a generator an option it does not take. +pub const ERR_UNKNOWN_OPTION: &str = "ERR_UNKNOWN_GENERATOR_OPTION"; + +/// The options a project wrote for one generator in `metaobjects.config.json`. +pub type Options = serde_json::Map; + +/// The refusal for options `generator` does not take, naming each one and what it takes +/// (`known`, empty for a generator that takes none). A generator's +/// [`Generator::configure`] returns it for any key outside `known`. +pub fn unknown_options(generator: &str, options: &Options, known: &[&str]) -> GenError { + let unknown: Vec = options + .keys() + .filter(|k| !known.contains(&k.as_str())) + .map(|k| format!("\"{k}\"")) + .collect(); + let takes = if known.is_empty() { + "it takes no options".to_string() + } else { + format!("it takes: {}", known.join(", ")) + }; + GenError::new( + ERR_UNKNOWN_OPTION, + format!( + "the generator {generator} has no option {}; {takes}", + unknown.join(", ") + ), + ) +} /// A code generator the run engine can drive. pub trait Generator { @@ -107,6 +135,18 @@ pub trait Generator { Vec::new() } + /// This generator built with the options a project wrote for it in + /// `metaobjects.config.json` (`{"name": "client", "options": {...}}`). Options go through a + /// generator's constructor: a generator that takes options overrides this to construct + /// itself from them, and refuses any key it does not know with [`unknown_options`]. The + /// default takes none and refuses every key, so a misspelt option fails the run instead + /// of being ignored. The engine calls it only for an entry that has options, and the + /// generator it returns runs in this one's place (its [`Generator::identity`] should + /// carry the options, since they can change what it emits). + fn configure(&self, options: &Options) -> Result, GenError> { + Err(unknown_options(self.name(), options, &[])) + } + /// Produce the generator's files for the loaded model. fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError>; } diff --git a/server/rust/metaobjects-codegen/src/generator_list.rs b/server/rust/metaobjects-codegen/src/generator_list.rs index 1bfe090efa..496077a8e8 100644 --- a/server/rust/metaobjects-codegen/src/generator_list.rs +++ b/server/rust/metaobjects-codegen/src/generator_list.rs @@ -5,11 +5,14 @@ //! the other ports, so changing the list never needs an eject: //! //! ```json -//! { "generators": ["entity", "client", "commands"] } +//! { "generators": ["entity", "client", "commands", "render-helper", "output-parser", "output-prompt"] } //! ``` //! -//! The list names generators; it takes no options and carries no layer or set settings, because -//! a layer is only a generator. A project with no such file runs every generator its host +//! An entry is a generator's name, or `{"name": "...", "options": {...}}` to construct it with +//! options: they reach the generator through [`crate::Generator::configure`], and a generator +//! refuses an option it does not take, so a misspelt one fails the run instead of being +//! ignored. The shipped generators take none yet. The list carries no layer or set settings, +//! because a layer is only a generator. A project with no such file runs every generator its host //! offers, which is what a project did before the file existed. A list may leave a generator //! out; generated files of a generator that left the list are swept like those of any //! generator that stops emitting them (an edited one is refused by name). @@ -20,16 +23,43 @@ use std::path::Path; use crate::eject; +use crate::generator::Options; /// The file that holds the list, from the project root. pub const GENERATOR_LIST_FILE: &str = "metaobjects.config.json"; /// The one key the file takes. const KEY: &str = "generators"; +/// The keys an entry written as an object takes. +const ENTRY_NAME: &str = "name"; +const ENTRY_OPTIONS: &str = "options"; + +/// One entry of the list: a generator, and the options the project constructs it with +/// (empty for an entry written as a bare name). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Entry { + pub name: String, + pub options: Options, +} + +impl Entry { + /// An entry with no options. + pub fn named(name: impl Into) -> Self { + Self { + name: name.into(), + options: Options::new(), + } + } +} + +/// The generator names of `entries`, in order. +pub fn names(entries: &[Entry]) -> Vec { + entries.iter().map(|e| e.name.clone()).collect() +} /// The list the project wrote, in the order it wrote it, or `None` when the project has no /// such file. Anything wrong with the file is an error naming the file and what to change. -pub fn read(project_root: &Path) -> Result>, String> { +pub fn read(project_root: &Path) -> Result>, String> { let path = project_root.join(GENERATOR_LIST_FILE); let text = match std::fs::read_to_string(&path) { Ok(text) => text, @@ -40,7 +70,7 @@ pub fn read(project_root: &Path) -> Result>, String> { } /// The list in `text`, the contents of [`GENERATOR_LIST_FILE`]. -pub fn parse(text: &str) -> Result, String> { +pub fn parse(text: &str) -> Result, String> { let value: serde_json::Value = serde_json::from_str(text) .map_err(|e| format!("{GENERATOR_LIST_FILE} is not valid JSON: {e}"))?; let Some(object) = value.as_object() else { @@ -51,7 +81,7 @@ pub fn parse(text: &str) -> Result, String> { if let Some(unknown) = object.keys().find(|k| k.as_str() != KEY) { return Err(format!( "{GENERATOR_LIST_FILE} has an unknown key \"{unknown}\". The only key is \"{KEY}\": \ - the generators to run, by name. Generators take no options here, and a layer is just a generator" + the generators to run, each a name or {{\"{ENTRY_NAME}\": ..., \"{ENTRY_OPTIONS}\": {{...}}}}. A layer is just a generator" )); } let Some(list) = object.get(KEY).and_then(|v| v.as_array()) else { @@ -61,21 +91,60 @@ pub fn parse(text: &str) -> Result, String> { example() )); }; - let mut names: Vec = Vec::with_capacity(list.len()); + let mut entries: Vec = Vec::with_capacity(list.len()); for item in list { - let Some(name) = item.as_str() else { + let entry = entry(item)?; + if entries.iter().any(|e| e.name == entry.name) { return Err(format!( - "{GENERATOR_LIST_FILE}: every entry of \"{KEY}\" is a generator name (a string), got {item}" + "{GENERATOR_LIST_FILE}: \"{}\" is listed twice; a generator runs once", + entry.name )); - }; - if names.iter().any(|n| n == name) { + } + entries.push(entry); + } + Ok(entries) +} + +/// One entry: a name, or an object with a `name` and optional `options`. +fn entry(item: &serde_json::Value) -> Result { + let shape = || { + format!( + "{GENERATOR_LIST_FILE}: every entry of \"{KEY}\" is a generator name (a string) or \ + {{\"{ENTRY_NAME}\": \"...\", \"{ENTRY_OPTIONS}\": {{...}}}}, got {item}" + ) + }; + if let Some(name) = item.as_str() { + return Ok(Entry::named(name)); + } + let Some(object) = item.as_object() else { + return Err(shape()); + }; + let Some(name) = object.get(ENTRY_NAME).and_then(|v| v.as_str()) else { + return Err(shape()); + }; + if let Some(unknown) = object + .keys() + .find(|k| k.as_str() != ENTRY_NAME && k.as_str() != ENTRY_OPTIONS) + { + return Err(format!( + "{GENERATOR_LIST_FILE}: the entry for \"{name}\" has an unknown key \"{unknown}\"; \ + an entry takes \"{ENTRY_NAME}\" and \"{ENTRY_OPTIONS}\" (the generator's own options)" + )); + } + let options = match object.get(ENTRY_OPTIONS) { + None => Options::new(), + Some(serde_json::Value::Object(o)) => o.clone(), + Some(other) => { return Err(format!( - "{GENERATOR_LIST_FILE}: \"{name}\" is listed twice; a generator runs once" + "{GENERATOR_LIST_FILE}: the \"{ENTRY_OPTIONS}\" of \"{name}\" must be an object of \ + option names to values, got {other}" )); } - names.push(name.to_string()); - } - Ok(names) + }; + Ok(Entry { + name: name.to_string(), + options, + }) } /// Check a list against the generators a host offers: each name is one of them, and a shipped @@ -145,10 +214,17 @@ mod tests { #[test] fn the_scaffold_parses_and_names_every_shipped_generator_in_run_order() { assert_eq!( - parse(&scaffold()).unwrap(), - s(&["entity", "client", "commands"]) + names(&parse(&scaffold()).unwrap()), + s(&[ + "entity", + "client", + "commands", + "render-helper", + "output-parser", + "output-prompt" + ]) ); - assert!(check(&parse(&scaffold()).unwrap(), &shipped_names()).is_ok()); + assert!(check(&names(&parse(&scaffold()).unwrap()), &shipped_names()).is_ok()); } #[test] @@ -162,6 +238,22 @@ mod tests { "needs a \"generators\" list", ), ("{\"generators\": [1]}", "generator name (a string)"), + ( + "{\"generators\": [{\"options\": {}}]}", + "generator name (a string)", + ), + ( + "{\"generators\": [{\"name\": \"entity\", \"packages\": []}]}", + "the entry for \"entity\" has an unknown key \"packages\"", + ), + ( + "{\"generators\": [{\"name\": \"entity\", \"options\": []}]}", + "must be an object of option names", + ), + ( + "{\"generators\": [\"entity\", {\"name\": \"entity\"}]}", + "listed twice", + ), ("{\"generators\": [\"entity\", \"entity\"]}", "listed twice"), ( "{\"generators\": [], \"layers\": {}}", @@ -172,7 +264,20 @@ mod tests { assert!(e.contains(wants), "{text}: {e}"); assert!(e.contains(GENERATOR_LIST_FILE), "{e}"); } - assert_eq!(parse("{\"generators\": []}").unwrap(), Vec::::new()); + assert_eq!(parse("{\"generators\": []}").unwrap(), Vec::::new()); + } + + #[test] + fn an_entry_is_a_name_or_a_name_with_its_options() { + let entries = + parse(r#"{"generators": ["entity", {"name": "client", "options": {"pageSize": 25}}, {"name": "commands"}]}"#) + .unwrap(); + assert_eq!(names(&entries), s(&["entity", "client", "commands"])); + assert!(entries[0].options.is_empty() && entries[2].options.is_empty()); + assert_eq!( + entries[1].options.get("pageSize"), + Some(&serde_json::json!(25)) + ); } #[test] @@ -180,7 +285,8 @@ mod tests { let available = shipped_names(); let e = check(&s(&["entity", "nope"]), &available).unwrap_err(); assert!( - e.contains("\"nope\"") && e.contains("available: entity, client, commands"), + e.contains("\"nope\"") + && e.contains("available: entity, client, commands, render-helper, output-parser, output-prompt"), "{e}" ); let e = check(&s(&["client"]), &available).unwrap_err(); diff --git a/server/rust/metaobjects-codegen/src/inbound.rs b/server/rust/metaobjects-codegen/src/inbound.rs new file mode 100644 index 0000000000..cdab72b247 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/inbound.rs @@ -0,0 +1,348 @@ +//! The inbound half of a prompt, read from the model once for every generator that needs it +//! (ADR-0052, ADR-0053). +//! +//! A template subtype's axis is direction: a `template.output` renders outbound and parses +//! nothing; a `template.prompt` that declares `@responseRef` names the value object its reply +//! is read into. [`inbound_templates`] is that rule, in one place, so no generator re-derives +//! "which templates have a response". The reply's syntax is `@responseFormat` (`json`, the +//! default, or `xml`), never `@format`, which is the syntax of the prompt's own body. +//! +//! [`extract_schema`] and [`output_format_spec`] derive, from the response value object, +//! the descriptors the reply parser and the output-format fragment run on, as the +//! `metaobjects-render` crate's own types: the derivation the other ports' runtime extract +//! makes, so a generated parser reads a reply as every port reads it. + +use std::collections::{HashMap, HashSet}; + +use metaobjects::node::{NodeId, Tree}; +use metaobjects::validate::util::ObjectIndex; +use metaobjects_render::extract::{ExtractSchema, FieldKind, FieldSpec, Format, normalize}; +use metaobjects_render::prompt::{OutputFormatSpec, PromptField, PromptStyle}; +use serde_json::Value; + +const TYPE_TEMPLATE: &str = "template"; +const TYPE_OBJECT: &str = "object"; +const TYPE_FIELD: &str = "field"; +const TYPE_VALIDATOR: &str = "validator"; +const TEMPLATE_PROMPT: &str = "prompt"; +const VALIDATOR_NUMERIC: &str = "numeric"; +const VALIDATOR_ARRAY: &str = "array"; +const ATTR_RESPONSE_REF: &str = "responseRef"; +const ATTR_RESPONSE_FORMAT: &str = "responseFormat"; +const ATTR_PROMPT_STYLE: &str = "promptStyle"; +const ATTR_OBJECT_REF: &str = "objectRef"; +const ATTR_REQUIRED: &str = "required"; +const ATTR_VALUES: &str = "values"; +const ATTR_ENUM_ALIAS: &str = "enumAlias"; +const ATTR_ENUM_DOC: &str = "enumDoc"; +const ATTR_COERCE_DEFAULT: &str = "coerceDefault"; +const ATTR_DEFAULT: &str = "default"; +const ATTR_NORMALIZE: &str = "normalize"; +const ATTR_XML_TEXT: &str = "xmlText"; +const ATTR_EXAMPLE: &str = "example"; +const ATTR_INSTRUCTION: &str = "instruction"; +const ATTR_MIN: &str = "min"; +const ATTR_MAX: &str = "max"; +const FORMAT_XML: &str = "xml"; + +/// How deep a reply's nested objects are read; past it a member is opaque text. Every port +/// stops at the same depth. +pub const MAX_NEST_DEPTH: usize = 8; + +/// Every concrete `template.prompt` at the root that declares a response shape, by name. +/// The gate is `@responseRef` being there (resolved through `extends`), never a format. +#[must_use] +pub fn inbound_templates(tree: &Tree, root: NodeId) -> Vec { + // ADR-0039 own: the root's top-level nodes are its declared children; a root extends + // nothing, so own and effective agree. + let mut out: Vec = tree + .own_children(root) + .iter() + .copied() + .filter(|&c| { + let n = tree.node(c); + n.type_name == TYPE_TEMPLATE + && n.sub_type == TEMPLATE_PROMPT + && !n.is_abstract + && str_attr(tree, c, ATTR_RESPONSE_REF).is_some() + }) + .collect(); + out.sort_by(|a, b| tree.node(*a).name.cmp(&tree.node(*b).name)); + out +} + +/// The object a prompt's reply is read into: its `@responseRef`, resolved on its exact +/// package-qualified name (ADR-0041). `None` when it names no object. +#[must_use] +pub fn response_object(tree: &Tree, index: &ObjectIndex, template: NodeId) -> Option { + index + .ref_target(tree, template, ATTR_RESPONSE_REF) + .filter(|&o| tree.node(o).type_name == TYPE_OBJECT) +} + +/// The reply's syntax (ADR-0053): `@responseFormat`, `json` unless it says `xml`. +#[must_use] +pub fn reply_format(tree: &Tree, template: NodeId) -> Format { + match str_attr(tree, template, ATTR_RESPONSE_FORMAT) { + Some(f) if f.eq_ignore_ascii_case(FORMAT_XML) => Format::Xml, + _ => Format::Json, + } +} + +/// The fragment's style: `@promptStyle`, `guide` unless it says otherwise. +#[must_use] +pub fn prompt_style(tree: &Tree, template: NodeId) -> PromptStyle { + PromptStyle::from_attr(str_attr(tree, template, ATTR_PROMPT_STYLE)) +} + +/// The extract descriptor of `object`: every effective field, nested value objects read +/// through their `@objectRef` to [`MAX_NEST_DEPTH`], a cycle or an unresolved reference +/// read as opaque text. +#[must_use] +pub fn extract_schema( + tree: &Tree, + index: &ObjectIndex, + object: NodeId, + format: Format, +) -> ExtractSchema { + schema_at(tree, index, object, format, &mut HashSet::new(), 0) +} + +fn schema_at( + tree: &Tree, + index: &ObjectIndex, + object: NodeId, + format: Format, + visited: &mut HashSet, + depth: usize, +) -> ExtractSchema { + visited.insert(object); + let fields = fields_of(tree, object) + .into_iter() + .map(|f| field_spec(tree, index, f, object, format, visited, depth)) + .collect(); + visited.remove(&object); + ExtractSchema { + format, + root_name: tree.node(object).name.clone(), + fields, + } +} + +fn field_spec( + tree: &Tree, + index: &ObjectIndex, + field: NodeId, + owner: NodeId, + format: Format, + visited: &mut HashSet, + depth: usize, +) -> FieldSpec { + let spec = field_shape(tree, index, field, owner, format, visited, depth); + if !spec.array { + return spec; + } + // Element-count bounds: the field's array validator is the one source of them. + match validator(tree, field, VALIDATOR_ARRAY) { + Some(v) => FieldSpec { + min_items: own_u64(tree, v, ATTR_MIN).and_then(|n| usize::try_from(n).ok()), + max_items: own_u64(tree, v, ATTR_MAX).and_then(|n| usize::try_from(n).ok()), + ..spec + }, + None => spec, + } +} + +fn field_shape( + tree: &Tree, + index: &ObjectIndex, + field: NodeId, + owner: NodeId, + format: Format, + visited: &mut HashSet, + depth: usize, +) -> FieldSpec { + let n = tree.node(field); + let name = n.name.as_str(); + let required = is_true(tree, field, ATTR_REQUIRED); + let array = tree.resolved_is_array(field); + let listed = |spec: FieldSpec| FieldSpec { array, ..spec }; + if n.sub_type == "enum" { + let mode = str_attr(tree, field, ATTR_NORMALIZE) + .or_else(|| str_attr(tree, owner, ATTR_NORMALIZE)) + .unwrap_or(normalize::DEFAULT); + return listed(FieldSpec { + enum_alias: string_map(tree, field, ATTR_ENUM_ALIAS), + coerce_default: str_attr(tree, field, ATTR_COERCE_DEFAULT).map(str::to_string), + default_value: str_attr(tree, field, ATTR_DEFAULT).map(str::to_string), + normalize: mode.to_string(), + ..FieldSpec::enumeration(name, required, strings(tree, field, ATTR_VALUES)) + }); + } + if n.sub_type == "object" || tree.attr(field, ATTR_OBJECT_REF).is_some() { + return match index.ref_target(tree, field, ATTR_OBJECT_REF) { + Some(target) + if tree.node(target).type_name == TYPE_OBJECT + && !visited.contains(&target) + && depth + 1 < MAX_NEST_DEPTH => + { + let nested = schema_at(tree, index, target, format, visited, depth + 1); + listed(FieldSpec::object(name, required, nested)) + } + // An unresolved reference, a cycle or the depth bound: an opaque leaf. + _ => FieldSpec::scalar(name, FieldKind::String, required), + }; + } + let kind = scalar_kind(&n.sub_type); + if array { + return FieldSpec::scalar(name, kind, required).array(); + } + if is_true(tree, field, ATTR_XML_TEXT) { + return FieldSpec::scalar(name, kind, required).text_content(); + } + let spec = FieldSpec::scalar(name, kind, required); + if matches!(kind, FieldKind::Int | FieldKind::Long | FieldKind::Double) + && let Some(v) = validator(tree, field, VALIDATOR_NUMERIC) + { + let (min, max) = (own_f64(tree, v, ATTR_MIN), own_f64(tree, v, ATTR_MAX)); + if min.is_some() || max.is_some() { + return spec.range(min, max); + } + } + spec.default_value(str_attr(tree, field, ATTR_DEFAULT).map(str::to_string)) +} + +/// The output-format fragment's descriptor for `object`, the reply's root. A nested object +/// is named with its kind and taught no deeper, as in every port. +#[must_use] +pub fn output_format_spec( + tree: &Tree, + object: NodeId, + format: Format, + style: PromptStyle, +) -> OutputFormatSpec { + let fields = fields_of(tree, object) + .into_iter() + .map(|f| prompt_field(tree, f)) + .collect(); + OutputFormatSpec { + format, + root_name: tree.node(object).name.clone(), + style, + fields, + } +} + +fn prompt_field(tree: &Tree, field: NodeId) -> PromptField { + let n = tree.node(field); + let required = is_true(tree, field, ATTR_REQUIRED); + let array = tree.resolved_is_array(field); + if n.sub_type == "object" { + return PromptField { + array, + ..PromptField::new(&n.name, FieldKind::Object, required) + }; + } + let example = str_attr(tree, field, ATTR_EXAMPLE).map(str::to_string); + let instruction = str_attr(tree, field, ATTR_INSTRUCTION).map(str::to_string); + if n.sub_type == "enum" { + let doc = string_map(tree, field, ATTR_ENUM_DOC); + return PromptField { + array, + enum_values: Some(strings(tree, field, ATTR_VALUES)), + enum_doc: (!doc.is_empty()).then(|| doc.into_iter().collect::>()), + example, + instruction, + ..PromptField::new(&n.name, FieldKind::Enum, required) + }; + } + PromptField { + array, + example, + instruction, + ..PromptField::new(&n.name, scalar_kind(&n.sub_type), required) + } +} + +/// The extract kind of a scalar field subtype; anything not numeric or boolean is text. +#[must_use] +pub fn scalar_kind(sub_type: &str) -> FieldKind { + match sub_type { + "int" => FieldKind::Int, + "long" | "currency" => FieldKind::Long, + "double" | "float" | "decimal" => FieldKind::Double, + "boolean" => FieldKind::Boolean, + _ => FieldKind::String, + } +} + +// ---- model reads ----------------------------------------------------------------------- + +/// The effective fields of `object`, inherited ones included, in declaration order. +fn fields_of(tree: &Tree, object: NodeId) -> Vec { + tree.children(object) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_FIELD) + .collect() +} + +fn validator(tree: &Tree, field: NodeId, sub_type: &str) -> Option { + tree.children(field).iter().copied().find(|&c| { + let n = tree.node(c); + n.type_name == TYPE_VALIDATOR && n.sub_type == sub_type + }) +} + +fn str_attr<'t>(tree: &'t Tree, id: NodeId, name: &str) -> Option<&'t str> { + tree.attr(id, name) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) +} + +fn is_true(tree: &Tree, id: NodeId, name: &str) -> bool { + match tree.attr(id, name) { + Some(Value::Bool(b)) => *b, + Some(Value::String(s)) => s.eq_ignore_ascii_case("true"), + _ => false, + } +} + +fn strings(tree: &Tree, id: NodeId, name: &str) -> Vec { + tree.attr(id, name) + .and_then(Value::as_array) + .map(|a| { + a.iter() + .map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_string)) + .collect() + }) + .unwrap_or_default() +} + +/// A string-to-string map attribute, in declaration order; a null value is dropped. +fn string_map(tree: &Tree, id: NodeId, name: &str) -> Vec<(String, String)> { + tree.attr(id, name) + .and_then(Value::as_object) + .map(|m| { + m.iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| { + let v = v.as_str().map_or_else(|| v.to_string(), str::to_string); + (k.clone(), v) + }) + .collect() + }) + .unwrap_or_default() +} + +// ADR-0039 own: a validator's `@min`/`@max` are its own declared bounds. +fn own_f64(tree: &Tree, id: NodeId, name: &str) -> Option { + tree.own_attr(id, name) + .filter(|a| !a.value.is_boolean()) + .and_then(|a| a.value.as_f64()) +} + +// ADR-0039 own: a validator's `@min`/`@max` are its own declared bounds. +fn own_u64(tree: &Tree, id: NodeId, name: &str) -> Option { + tree.own_attr(id, name).and_then(|a| a.value.as_u64()) +} diff --git a/server/rust/metaobjects-codegen/src/lib.rs b/server/rust/metaobjects-codegen/src/lib.rs index 9e37d4902e..edb1e6bb92 100644 --- a/server/rust/metaobjects-codegen/src/lib.rs +++ b/server/rust/metaobjects-codegen/src/lib.rs @@ -23,9 +23,13 @@ pub mod fingerprint; pub mod generator; pub mod generator_list; pub mod hashes; +pub mod inbound; pub mod names; +pub mod output_parser; +pub mod output_prompt; pub mod plan; pub mod project; +pub mod render_helper; pub mod sha256; pub mod writer; @@ -37,6 +41,12 @@ pub use engine::{ }; pub use entity::EntityGenerator; pub use generator::{EmittedFile, GenContext, GenError, Generator}; +/// The prompt render crate the `render-helper` generator checks templates with, so an owned +/// copy of it names `metaobjects_codegen::render` and needs no dependency of its own. +pub use metaobjects_render as render; +pub use output_parser::OutputParserGenerator; +pub use output_prompt::OutputPromptGenerator; +pub use render_helper::{RenderHelperGenerator, TemplateCheck, check_templates}; /// The generators `cargo meta gen` runs when the project owns none, in the order they run. pub fn shipped_generators() -> Vec> { @@ -44,5 +54,8 @@ pub fn shipped_generators() -> Vec> { Box::new(EntityGenerator), Box::new(ClientGenerator), Box::new(CommandsGenerator), + Box::new(RenderHelperGenerator), + Box::new(OutputParserGenerator), + Box::new(OutputPromptGenerator), ] } diff --git a/server/rust/metaobjects-codegen/src/names.rs b/server/rust/metaobjects-codegen/src/names.rs index 5e8ab68e28..ae86fa009d 100644 --- a/server/rust/metaobjects-codegen/src/names.rs +++ b/server/rust/metaobjects-codegen/src/names.rs @@ -184,24 +184,6 @@ pub fn literal(text: &str) -> String { out } -/// `/// ` doc-comment lines for `text` at `indent`, one per line of text, with no trailing -/// whitespace (an empty line is a bare `///`). -pub fn doc_comment(text: &str, indent: &str) -> String { - let mut out = String::new(); - for line in text.trim().lines() { - let line = line.trim_end(); - out.push_str(indent); - if line.is_empty() { - out.push_str("///\n"); - } else { - out.push_str("/// "); - out.push_str(line); - out.push('\n'); - } - } - out -} - #[cfg(test)] mod tests { use super::*; @@ -250,11 +232,7 @@ mod tests { } #[test] - fn literals_and_doc_comments_are_escaped_and_trimmed() { + fn literals_are_escaped() { assert_eq!(literal("a\"b\\c\nd"), "\"a\\\"b\\\\c\\nd\""); - assert_eq!( - doc_comment("One.\n\nTwo. ", " "), - " /// One.\n ///\n /// Two.\n" - ); } } diff --git a/server/rust/metaobjects-codegen/src/output_parser.rs b/server/rust/metaobjects-codegen/src/output_parser.rs new file mode 100644 index 0000000000..3e148cc7bd --- /dev/null +++ b/server/rust/metaobjects-codegen/src/output_parser.rs @@ -0,0 +1,536 @@ +//! The `output-parser` generator: a response parser per responding prompt, one crate per +//! package. +//! +//! A `template.prompt` that declares `@responseRef` names the value object its reply is read +//! into (ADR-0052). For the package `acme::ai` the generator writes: +//! +//! ```text +//! /acme_ai_parsers/Cargo.toml the crate (metaobjects-render, the response crates) +//! /acme_ai_parsers/src/lib.rs one `mod` per prompt and a `pub use` of its functions +//! /acme_ai_parsers/src/.rs one prompt: its parsers and its extract descriptor +//! ``` +//! +//! Each prompt gets two ways to read a reply into the response type, which is the value +//! object's own struct, written by the `entity` generator (ADR-0056): +//! +//! - `parse_(text) -> Result`, the strict parse: the reply must be +//! exactly the JSON of a `T`. A prompt whose `@responseFormat` is `xml` has none (ADR-0053): +//! all-or-nothing over a reader that repairs is not a contract anyone can reason about. +//! - `extract_(text, opts) -> Extracted`, the tolerant read of a raw model reply: +//! fences, prose, comments, trailing commas, cut-off values and synonyms are tolerated, every +//! field is classified in a report, and it never fails. The typed value is there when the +//! extracted fields make a complete `T`. +//! +//! `_schema()` returns the extract descriptor both rest on, derived from the response +//! object as every port derives it: nested value objects read to the shared depth, numeric +//! ranges and element counts from the field's validators, `@enumAlias`, `@coerceDefault`, +//! `@default`, `@normalize` and `@xmlText`. The parsers run on the `metaobjects-render` +//! crate, an ordinary Apache-2.0 library. + +use std::collections::{BTreeMap, BTreeSet}; + +use metaobjects::node::{NodeId, Tree}; +use metaobjects::validate::util::ObjectIndex; +use metaobjects_codegen::generator::{ + ERR_UNSUPPORTED, EmittedFile, GenContext, GenError, Generator, +}; +use metaobjects_codegen::inbound::{ + extract_schema, inbound_templates, reply_format, response_object, +}; +use metaobjects_codegen::names::{crate_name, field_ident, literal, snake}; +use metaobjects_codegen::plan::Plan; +use metaobjects_codegen::render::extract::{ExtractSchema, FieldSpec, Format, normalize}; +use metaobjects_codegen::writer::{ + CodeWriter, Manifest, Piece, RUSTFMT_TOML, file, item, list, padded, sibling_dep, toml_string, +}; + +/// Bump when the emitted text changes shape, so a stored skip key never survives it. +const FORMAT: u32 = 1; + +/// The line every generated Rust file starts with. +pub const BANNER: &str = "// @generated by the MetaObjects output-parser generator. Do not edit: change the model and run `cargo meta gen`."; + +const MANIFEST_BANNER: &str = "@generated by the MetaObjects output-parser generator. Do not edit: change the model and run `cargo meta gen`."; + +/// The suffix of the parser crate of a package: `shop`'s replies are read by `shop_parsers`. +pub const PARSERS_SUFFIX: &str = "_parsers"; + +const RENDER_CRATE: &str = "metaobjects-render"; +/// The version requirement the generated crate names `metaobjects-render` by. +const RENDER_VERSION: &str = metaobjects_codegen::render::REQUIREMENT; + +/// The output-parser generator. +#[derive(Debug, Clone, Copy, Default)] +pub struct OutputParserGenerator; + +impl Generator for OutputParserGenerator { + fn name(&self) -> &str { + "output-parser" + } + + fn identity(&self) -> String { + format!("output-parser:{FORMAT}") + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + self.render(ctx) + } +} + +impl OutputParserParts for OutputParserGenerator {} + +/// The pieces of the output-parser generator's output, one method each (ADR-0063 item 7). Each +/// default is the shipped piece: implement this for a generator of your own, override the +/// piece you want changed, and have its [`Generator::generate`] return `self.render(ctx)` +/// (the [`crate::entity::EntityParts`] example shows the shape). An override can call the +/// shipped piece, a public function of this module with the same name. Not a stability +/// contract: the methods may change in a minor release, and the CHANGELOG says when. +pub trait OutputParserParts { + /// Every file: one parsers crate per package with a responding prompt. + fn render(&self, ctx: &GenContext<'_>) -> Result, GenError> { + render(self, ctx) + } + + /// A parsers crate's `Cargo.toml`. + fn manifest(&self, name: &str, c: &ParsersCrate) -> String { + cargo_toml(name, c) + } + + /// A parsers crate's `src/lib.rs`: each module and the parsers it exports. + fn lib_file(&self, c: &ParsersCrate) -> String { + lib_file(c) + } + + /// One prompt's file: its imports, its parsers and its schemas. + fn parser_file(&self, p: &ParserPlan) -> Result { + parser_file(self, p) + } + + /// The strict `parse_*` of a prompt whose reply is exactly JSON. + fn strict_fn(&self, w: &mut CodeWriter, p: &ParserPlan) { + strict_fn(w, p); + } + + /// The tolerant `extract_*`. + fn extract_fn(&self, w: &mut CodeWriter, p: &ParserPlan) { + extract_fn(w, p); + } + + /// One schema function: the root's (`root`) or a nested object's. + fn schema_fn( + &self, + w: &mut CodeWriter, + p: &ParserPlan, + root: bool, + name: &str, + s: &ExtractSchema, + ) { + schema_fn(w, p, root, name, s); + } +} + +/// The shipped [`OutputParserParts::render`], through `parts`. +pub fn render( + parts: &P, + ctx: &GenContext<'_>, +) -> Result, GenError> { + let templates = inbound_templates(ctx.tree, ctx.root); + if templates.is_empty() { + return Ok(Vec::new()); + } + let plan = Plan::of(ctx)?; + let selected = plan.selected_crates(ctx.entities)?; + let index = ObjectIndex::build(ctx.tree, ctx.root); + let mut crates: BTreeMap = BTreeMap::new(); + for t in templates { + let parser = parser_of(ctx.tree, &plan, &index, t)?; + if selected + .as_ref() + .is_some_and(|sel| !sel.contains(&parser.response_crate)) + { + continue; + } + let package = ctx.tree.effective_package(t); + let c = crates + .entry(format!("{}{PARSERS_SUFFIX}", crate_name(&package))) + .or_default(); + c.package = package; + c.deps.insert(parser.response_crate.clone()); + c.parsers.push(parser); + } + let mut files = Vec::new(); + for (name, c) in &crates { + parsers_crate(parts, name, c, &mut files)?; + } + Ok(files) +} + +/// What one prompt's parser needs. +pub struct ParserPlan { + pub template: String, + pub module: String, + pub response_name: String, + pub response_crate: String, + pub response_type: String, + pub strict: bool, + pub schema: ExtractSchema, +} + +fn parser_of( + tree: &Tree, + plan: &Plan, + index: &ObjectIndex, + t: NodeId, +) -> Result { + let n = tree.node(t); + let unsupported = |message: String| GenError::new(ERR_UNSUPPORTED, message); + let response = response_object(tree, index, t).ok_or_else(|| { + unsupported(format!( + "template.prompt \"{}\": @responseRef resolves to no object", + n.name + )) + })?; + let s = plan + .structs + .iter() + .find(|s| s.node == response) + .ok_or_else(|| { + unsupported(format!( + "template.prompt \"{}\": the response \"{}\" is not a value object, and the \ + Rust port generates a type only for value objects and entities", + n.name, + tree.node(response).name + )) + })?; + let format = reply_format(tree, t); + Ok(ParserPlan { + template: n.name.clone(), + module: snake(&n.name), + response_name: tree.node(response).name.clone(), + response_crate: s.crate_name.clone(), + response_type: s.type_name.clone(), + strict: format == Format::Json, + schema: extract_schema(tree, index, response, format), + }) +} + +// ---- one parsers crate ----------------------------------------------------------------- + +#[derive(Default)] +pub struct ParsersCrate { + pub package: String, + pub deps: BTreeSet, + pub parsers: Vec, +} + +fn parsers_crate( + parts: &P, + name: &str, + c: &ParsersCrate, + files: &mut Vec, +) -> Result<(), GenError> { + for p in &c.parsers { + files.push(EmittedFile::new( + format!("{name}/src/{}.rs", p.module), + parts.parser_file(p)?, + )); + } + files.push(EmittedFile::new( + format!("{name}/Cargo.toml"), + parts.manifest(name, c), + )); + files.push(EmittedFile::new( + format!("{name}/rustfmt.toml"), + RUSTFMT_TOML.to_string(), + )); + files.push(EmittedFile::new( + format!("{name}/src/lib.rs"), + parts.lib_file(c), + )); + Ok(()) +} + +/// The shipped [`OutputParserParts::manifest`]. +pub fn cargo_toml(name: &str, c: &ParsersCrate) -> String { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, name); + let package = if c.package.is_empty() { + "the model's" + } else { + c.package.as_str() + }; + m.entry( + "description", + &toml_string(&format!( + "Response parsers for the prompts of the MetaObjects package {package}." + )), + ); + m.blank().table("dependencies"); + m.entry(RENDER_CRATE, &toml_string(RENDER_VERSION)); + if c.parsers.iter().any(|p| p.strict) { + m.entry("serde_json", &toml_string("1")); + } + for dep in &c.deps { + m.entry(dep, &sibling_dep(dep)); + } + m.finish() +} + +/// The shipped [`OutputParserParts::lib_file`]. +pub fn lib_file(c: &ParsersCrate) -> String { + let mut w = CodeWriter::new(); + w.line(BANNER).blank(); + if c.package.is_empty() { + w.line("//! Response parsers for the prompts of the MetaObjects model that declares no package."); + } else { + w.line(format!( + "//! Response parsers for the prompts of the MetaObjects package `{}`.", + c.package + )); + } + w.line("//!"); + w.line( + "//! Each prompt's reply is read into its response type: `parse_*` exactly, `extract_*`", + ); + w.line("//! tolerantly, with a report of every field."); + w.blank(); + let mut parsers: Vec<&ParserPlan> = c.parsers.iter().collect(); + parsers.sort_by(|a, b| a.module.cmp(&b.module)); + for p in &parsers { + w.line(format!("mod {};", p.module)); + } + w.blank(); + w.line("pub use metaobjects_render::extract::{ExtractOptions, Extracted, FieldExtraction, Tolerance};"); + for p in &parsers { + let m = &p.module; + let mut names = Vec::new(); + if p.strict { + names.push(format!("parse_{m}")); + } + names.push(format!("extract_{m}")); + names.push(format!("{m}_schema")); + w.line(format!("pub use {m}::{{{}}};", names.join(", "))); + } + w.finish().expect("a lib.rs opens no block") +} + +// ---- one parser ------------------------------------------------------------------------ + +/// The shipped [`OutputParserParts::parser_file`], through `parts`. +pub fn parser_file( + parts: &P, + p: &ParserPlan, +) -> Result { + // The schemas, root first, then each nested object's in the order it is reached. + let mut schemas = Vec::new(); + collect_schemas(&format!("{}_schema", p.module), &p.schema, &mut schemas); + let mut used = BTreeSet::from(["ExtractOptions", "ExtractSchema", "Extracted", "Format"]); + used.insert("extract_into"); + for (_, s) in &schemas { + if !s.fields.is_empty() { + used.insert("FieldKind"); + used.insert("FieldSpec"); + } + } + let mut imports: Vec<&str> = used.into_iter().collect(); + imports.sort_by_key(|s| (s.starts_with(char::is_lowercase), *s)); + let mut uses = CodeWriter::new(); + uses.use_list("metaobjects_render::extract", &imports); + uses.use_list(&p.response_crate, &[&p.response_type]); + let mut items = vec![uses.finish()?]; + if p.strict { + items.push(item(|w| parts.strict_fn(w, p))?); + } + items.push(item(|w| parts.extract_fn(w, p))?); + for (i, (name, schema)) in schemas.iter().enumerate() { + items.push(item(|w| parts.schema_fn(w, p, i == 0, name, schema))?); + } + Ok(file(BANNER, &items)) +} + +/// Each schema in the tree with the name of the function that builds it: `` for the +/// root, `_` for a nested one, and so on down. +fn collect_schemas<'s>( + name: &str, + schema: &'s ExtractSchema, + out: &mut Vec<(String, &'s ExtractSchema)>, +) { + out.push((name.to_string(), schema)); + for f in &schema.fields { + if let Some(nested) = &f.nested { + collect_schemas(&format!("{name}_{}", snake(&f.name)), nested, out); + } + } +} + +/// The shipped [`OutputParserParts::strict_fn`]. +pub fn strict_fn(w: &mut CodeWriter, p: &ParserPlan) { + w.prose(&format!( + "Parse a reply to the `{}` prompt that is exactly the JSON of a `{}`.", + p.template, p.response_name + )); + w.doc_break(); + w.prose("# Errors"); + w.prose(&format!( + "Anything that is not that JSON: prose around it, a fence, a member missing or of the \ + wrong type. Read a raw model reply with [`extract_{}`] instead.", + p.module + )); + w.open(vec![ + format!("pub fn parse_{}", p.module).into(), + list("(", ["text: &str"], ")"), + format!(" -> Result<{}, serde_json::Error> {{", p.response_type).into(), + ]); + w.line("serde_json::from_str(text)"); + w.close("}"); +} + +/// The shipped [`OutputParserParts::extract_fn`]. +pub fn extract_fn(w: &mut CodeWriter, p: &ParserPlan) { + w.prose(&format!( + "Read a raw model reply to the `{}` prompt into a `{}`, tolerantly: fences, prose, \ + comments, trailing commas, cut-off values and synonyms are read through. It never \ + fails: `value` is the answer when the extracted fields make a complete `{}`, and the \ + report classifies every field either way.", + p.template, p.response_name, p.response_name + )); + w.line("#[must_use]"); + w.open(vec![ + format!("pub fn extract_{}", p.module).into(), + list("(", ["text: &str", "opts: &ExtractOptions"], ")"), + format!(" -> Extracted<{}> {{", p.response_type).into(), + ]); + w.line(vec![ + "extract_into".into(), + list( + "(", + [ + "Some(text)".to_string(), + format!("&{}_schema()", p.module), + "opts".to_string(), + ], + ")", + ), + ]); + w.close("}"); +} + +/// The shipped [`OutputParserParts::schema_fn`]. +pub fn schema_fn(w: &mut CodeWriter, p: &ParserPlan, root: bool, name: &str, s: &ExtractSchema) { + if root { + w.prose(&format!( + "The extract descriptor of a reply to the `{}` prompt: the fields of `{}`, as \ + the model declares them.", + p.template, p.response_name + )); + w.line("#[must_use]"); + w.open(format!("pub fn {name}() -> ExtractSchema {{")); + } else { + w.open(format!("fn {name}() -> ExtractSchema {{")); + } + let mut locals = Vec::new(); + for f in &s.fields { + let local = field_ident(&f.name); + let sets = field_sets(name, f); + let binding = if sets.is_empty() { + format!("let {local} =") + } else { + format!("let mut {local} =") + }; + w.assign( + &binding, + vec![ + "FieldSpec::scalar".into(), + list( + "(", + [ + literal(&f.name), + format!("FieldKind::{:?}", f.kind), + f.required.to_string(), + ], + ");", + ), + ], + ); + for (member, value) in sets { + w.assign(&format!("{local}.{member} ="), value); + } + locals.push(local); + } + let format = match s.format { + Format::Json => "Format::Json", + Format::Xml => "Format::Xml", + }; + w.line(vec![ + "ExtractSchema ".into(), + padded( + "{", + vec![ + Piece::from(format!("format: {format}")), + format!("root_name: {}.into()", literal(&s.root_name)).into(), + vec!["fields: ".into(), list("vec![", locals, "]")].into(), + ], + "}", + ), + ]); + w.close("}"); +} + +/// The members of `f` that differ from `FieldSpec::scalar(name, kind, required)`, each with +/// the right-hand side that sets it. +fn field_sets(schema: &str, f: &FieldSpec) -> Vec<(&'static str, Piece)> { + let text = |s: &str| format!("{}.into()", literal(s)); + let some_text = |s: &Option| s.as_deref().map(|v| format!("Some({});", text(v)).into()); + let mut out = Vec::new(); + if f.array { + out.push(("array", "true;".into())); + } + if let Some(values) = &f.enum_values { + out.push(( + "enum_values", + list("Some(vec![", values.iter().map(|v| text(v)), "]);"), + )); + } + if !f.enum_alias.is_empty() { + out.push(( + "enum_alias", + list( + "vec![", + f.enum_alias + .iter() + .map(|(from, to)| format!("({}, {})", text(from), text(to))), + "];", + ), + )); + } + if let Some(min) = f.min { + out.push(("min", format!("Some({min:?});").into())); + } + if let Some(max) = f.max { + out.push(("max", format!("Some({max:?});").into())); + } + if f.nested.is_some() { + out.push(( + "nested", + format!("Some(Box::new({schema}_{}()));", snake(&f.name)).into(), + )); + } + if let Some(v) = some_text(&f.coerce_default) { + out.push(("coerce_default", v)); + } + if let Some(v) = some_text(&f.default_value) { + out.push(("default_value", v)); + } + if f.normalize != normalize::DEFAULT { + out.push(("normalize", format!("{};", text(&f.normalize)).into())); + } + if f.text_content { + out.push(("text_content", "true;".into())); + } + if let Some(n) = f.min_items { + out.push(("min_items", format!("Some({n});").into())); + } + if let Some(n) = f.max_items { + out.push(("max_items", format!("Some({n});").into())); + } + out +} diff --git a/server/rust/metaobjects-codegen/src/output_prompt.rs b/server/rust/metaobjects-codegen/src/output_prompt.rs new file mode 100644 index 0000000000..59c54ea993 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/output_prompt.rs @@ -0,0 +1,427 @@ +//! The `output-prompt` generator: the output-format fragment of each responding prompt, one +//! crate per package. +//! +//! A `template.prompt` that declares `@responseRef` asks for an answer shaped like that value +//! object (ADR-0052). The fragment is the part of the prompt that says so: "produce your +//! answer like this", as a field guide, an inline skeleton or a filled example +//! (`@promptStyle`: `guide`, `inline`, `exampleOnly`), in the reply's syntax +//! (`@responseFormat`: `json` or `xml`, ADR-0053). For the package `acme::ai` the generator +//! writes: +//! +//! ```text +//! /acme_ai_formats/Cargo.toml the crate (metaobjects-render) +//! /acme_ai_formats/src/lib.rs one `mod` per prompt and a `pub use` of its functions +//! /acme_ai_formats/src/.rs one prompt: its fragment and its descriptor +//! ``` +//! +//! Each prompt gets `render__format(overrides) -> String` and the descriptor it renders, +//! `_format_spec()`: every field of the response object with its kind, whether it is +//! required, enum members and their `@enumDoc`, `@example` and `@instruction`. A nested +//! object is named with its kind and taught no deeper, as in every port. The fragment's root +//! is the response object's name, the same root the generated parser looks for. + +use std::collections::{BTreeMap, BTreeSet}; + +use metaobjects::node::{NodeId, Tree}; +use metaobjects::validate::util::ObjectIndex; +use metaobjects_codegen::generator::{EmittedFile, GenContext, GenError, Generator}; +use metaobjects_codegen::inbound::{ + inbound_templates, output_format_spec, prompt_style, reply_format, response_object, +}; +use metaobjects_codegen::names::{crate_name, field_ident, literal, snake}; +use metaobjects_codegen::plan::Plan; +use metaobjects_codegen::render::extract::Format; +use metaobjects_codegen::render::prompt::{OutputFormatSpec, PromptField, PromptStyle}; +use metaobjects_codegen::writer::{ + CodeWriter, Manifest, Piece, RUSTFMT_TOML, file, item, list, padded, toml_string, +}; + +/// Bump when the emitted text changes shape, so a stored skip key never survives it. +const FORMAT: u32 = 1; + +/// The line every generated Rust file starts with. +pub const BANNER: &str = "// @generated by the MetaObjects output-prompt generator. Do not edit: change the model and run `cargo meta gen`."; + +const MANIFEST_BANNER: &str = "@generated by the MetaObjects output-prompt generator. Do not edit: change the model and run `cargo meta gen`."; + +/// The suffix of the fragment crate of a package: `shop`'s fragments are in `shop_formats`. +pub const FORMATS_SUFFIX: &str = "_formats"; + +const RENDER_CRATE: &str = "metaobjects-render"; +/// The version requirement the generated crate names `metaobjects-render` by. +const RENDER_VERSION: &str = metaobjects_codegen::render::REQUIREMENT; + +/// The output-prompt generator. +#[derive(Debug, Clone, Copy, Default)] +pub struct OutputPromptGenerator; + +impl Generator for OutputPromptGenerator { + fn name(&self) -> &str { + "output-prompt" + } + + fn identity(&self) -> String { + format!("output-prompt:{FORMAT}") + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + self.render(ctx) + } +} + +impl OutputPromptParts for OutputPromptGenerator {} + +/// The pieces of the output-prompt generator's output, one method each (ADR-0063 item 7). Each +/// default is the shipped piece: implement this for a generator of your own, override the +/// piece you want changed, and have its [`Generator::generate`] return `self.render(ctx)` +/// (the [`crate::entity::EntityParts`] example shows the shape). An override can call the +/// shipped piece, a public function of this module with the same name. Not a stability +/// contract: the methods may change in a minor release, and the CHANGELOG says when. +pub trait OutputPromptParts { + /// Every file: one formats crate per package with a responding prompt. + fn render(&self, ctx: &GenContext<'_>) -> Result, GenError> { + render(self, ctx) + } + + /// A formats crate's `Cargo.toml`. + fn manifest(&self, name: &str, c: &FormatsCrate) -> String { + cargo_toml(name, c) + } + + /// A formats crate's `src/lib.rs`: each module and the functions it exports. + fn lib_file(&self, c: &FormatsCrate) -> String { + lib_file(c) + } + + /// One prompt's file: its imports, its fragment function and its spec. + fn fragment_file(&self, f: &FragmentPlan) -> Result { + fragment_file(self, f) + } + + /// The function that renders the fragment. + fn render_fn(&self, w: &mut CodeWriter, f: &FragmentPlan) { + render_fn(w, f); + } + + /// The function that builds the fragment's spec. + fn spec_fn(&self, w: &mut CodeWriter, f: &FragmentPlan) { + spec_fn(w, f); + } +} + +/// The shipped [`OutputPromptParts::render`], through `parts`. +pub fn render( + parts: &P, + ctx: &GenContext<'_>, +) -> Result, GenError> { + let templates = inbound_templates(ctx.tree, ctx.root); + if templates.is_empty() { + return Ok(Vec::new()); + } + let plan = Plan::of(ctx)?; + let selected = plan.selected_crates(ctx.entities)?; + let index = ObjectIndex::build(ctx.tree, ctx.root); + let mut crates: BTreeMap = BTreeMap::new(); + for t in templates { + // A reply shape that names no object gets no fragment (the loader reports it). + let Some(fragment) = fragment_of(ctx.tree, &index, t) else { + continue; + }; + // A run limited to some entities writes the fragments of their crates only. + let response_crate = plan + .structs + .iter() + .find(|s| s.node == fragment.response) + .map(|s| &s.crate_name); + if let (Some(sel), Some(c)) = (selected.as_ref(), response_crate) + && !sel.contains(c) + { + continue; + } + let package = ctx.tree.effective_package(t); + let c = crates + .entry(format!("{}{FORMATS_SUFFIX}", crate_name(&package))) + .or_default(); + c.package = package; + c.fragments.push(fragment); + } + let mut files = Vec::new(); + for (name, c) in &crates { + formats_crate(parts, name, c, &mut files)?; + } + Ok(files) +} + +/// What one prompt's fragment needs. +pub struct FragmentPlan { + pub template: String, + pub module: String, + pub response: NodeId, + pub response_name: String, + pub spec: OutputFormatSpec, +} + +fn fragment_of(tree: &Tree, index: &ObjectIndex, t: NodeId) -> Option { + let response = response_object(tree, index, t)?; + let n = tree.node(t); + Some(FragmentPlan { + template: n.name.clone(), + module: snake(&n.name), + response, + response_name: tree.node(response).name.clone(), + spec: output_format_spec(tree, response, reply_format(tree, t), prompt_style(tree, t)), + }) +} + +// ---- one formats crate ----------------------------------------------------------------- + +#[derive(Default)] +pub struct FormatsCrate { + pub package: String, + pub fragments: Vec, +} + +fn formats_crate( + parts: &P, + name: &str, + c: &FormatsCrate, + files: &mut Vec, +) -> Result<(), GenError> { + for f in &c.fragments { + files.push(EmittedFile::new( + format!("{name}/src/{}.rs", f.module), + parts.fragment_file(f)?, + )); + } + files.push(EmittedFile::new( + format!("{name}/Cargo.toml"), + parts.manifest(name, c), + )); + files.push(EmittedFile::new( + format!("{name}/rustfmt.toml"), + RUSTFMT_TOML.to_string(), + )); + files.push(EmittedFile::new( + format!("{name}/src/lib.rs"), + parts.lib_file(c), + )); + Ok(()) +} + +/// The shipped [`OutputPromptParts::manifest`]. +pub fn cargo_toml(name: &str, c: &FormatsCrate) -> String { + let mut m = Manifest::generated_crate(MANIFEST_BANNER, name); + let package = if c.package.is_empty() { + "the model's" + } else { + c.package.as_str() + }; + m.entry( + "description", + &toml_string(&format!( + "Output-format prompt fragments for the prompts of the MetaObjects package {package}." + )), + ); + m.blank().table("dependencies"); + m.entry(RENDER_CRATE, &toml_string(RENDER_VERSION)); + m.finish() +} + +/// The shipped [`OutputPromptParts::lib_file`]. +pub fn lib_file(c: &FormatsCrate) -> String { + let mut w = CodeWriter::new(); + w.line(BANNER).blank(); + if c.package.is_empty() { + w.line("//! Output-format prompt fragments for the prompts of the MetaObjects model that declares no package."); + } else { + w.line(format!( + "//! Output-format prompt fragments for the prompts of the MetaObjects package `{}`.", + c.package + )); + } + w.line("//!"); + w.line("//! Each fragment tells a model how to shape its answer, in the shape the matching"); + w.line("//! response parser reads."); + w.blank(); + let mut fragments: Vec<&FragmentPlan> = c.fragments.iter().collect(); + fragments.sort_by(|a, b| a.module.cmp(&b.module)); + for f in &fragments { + w.line(format!("mod {};", f.module)); + } + w.blank(); + w.line("pub use metaobjects_render::prompt::{PromptOverrides, PromptStyle};"); + for f in &fragments { + let m = &f.module; + w.line(format!( + "pub use {m}::{{render_{m}_format, {m}_format_spec}};" + )); + } + w.finish().expect("a lib.rs opens no block") +} + +// ---- one fragment ---------------------------------------------------------------------- + +/// The shipped [`OutputPromptParts::fragment_file`], through `parts`. +pub fn fragment_file( + parts: &P, + f: &FragmentPlan, +) -> Result { + let s = &f.spec; + let mut prompt = BTreeSet::from(["OutputFormatSpec", "PromptOverrides", "PromptStyle"]); + prompt.insert("render_output_format"); + let mut extract = BTreeSet::from(["Format"]); + if !s.fields.is_empty() { + prompt.insert("PromptField"); + extract.insert("FieldKind"); + } + let has_doc = s.fields.iter().any(|p| p.enum_doc.is_some()); + let sorted = |set: BTreeSet<&'static str>| { + let mut v: Vec<&str> = set.into_iter().collect(); + v.sort_by_key(|s| (s.starts_with(char::is_lowercase), *s)); + v + }; + let mut uses = CodeWriter::new(); + if has_doc { + uses.use_list("std::collections", &["HashMap"]).blank(); + } + uses.use_list("metaobjects_render::extract", &sorted(extract)); + uses.use_list("metaobjects_render::prompt", &sorted(prompt)); + let items = vec![ + uses.finish()?, + item(|w| parts.render_fn(w, f))?, + item(|w| parts.spec_fn(w, f))?, + ]; + Ok(file(BANNER, &items)) +} + +/// The shipped [`OutputPromptParts::render_fn`]. +pub fn render_fn(w: &mut CodeWriter, f: &FragmentPlan) { + w.prose(&format!( + "The output-format fragment of the `{}` prompt: how to shape an answer as a `{}`. \ + Pass `PromptOverrides::default()` for the model's style, examples and instructions, \ + or override any of them at render time.", + f.template, f.response_name + )); + w.line("#[must_use]"); + w.open(vec![ + format!("pub fn render_{}_format", f.module).into(), + list("(", ["overrides: &PromptOverrides"], ")"), + " -> String {".into(), + ]); + w.line(vec![ + "render_output_format".into(), + list( + "(", + [ + format!("&{}_format_spec()", f.module), + "overrides".to_string(), + ], + ")", + ), + ]); + w.close("}"); +} + +/// The shipped [`OutputPromptParts::spec_fn`]. +pub fn spec_fn(w: &mut CodeWriter, f: &FragmentPlan) { + let s = &f.spec; + w.prose(&format!( + "The output-format descriptor of the `{}` prompt: the fields of `{}`, as the model \ + declares them.", + f.template, f.response_name + )); + w.line("#[must_use]"); + w.open(format!( + "pub fn {}_format_spec() -> OutputFormatSpec {{", + f.module + )); + let mut locals = Vec::new(); + for p in &s.fields { + let local = field_ident(&p.name); + let sets = field_sets(p); + let binding = if sets.is_empty() { + format!("let {local} =") + } else { + format!("let mut {local} =") + }; + w.assign( + &binding, + vec![ + "PromptField::new".into(), + list( + "(", + [ + literal(&p.name), + format!("FieldKind::{:?}", p.kind), + p.required.to_string(), + ], + ");", + ), + ], + ); + for (member, value) in sets { + w.assign(&format!("{local}.{member} ="), value); + } + locals.push(local); + } + let format = match s.format { + Format::Json => "Format::Json", + Format::Xml => "Format::Xml", + }; + let style = match s.style { + PromptStyle::Guide => "PromptStyle::Guide", + PromptStyle::Inline => "PromptStyle::Inline", + PromptStyle::ExampleOnly => "PromptStyle::ExampleOnly", + }; + w.line(vec![ + "OutputFormatSpec ".into(), + padded( + "{", + vec![ + Piece::from(format!("format: {format}")), + format!("root_name: {}.into()", literal(&s.root_name)).into(), + format!("style: {style}").into(), + vec!["fields: ".into(), list("vec![", locals, "]")].into(), + ], + "}", + ), + ]); + w.close("}"); +} + +/// The members of `p` that differ from `PromptField::new(name, kind, required)`, each with +/// the right-hand side that sets it. +fn field_sets(p: &PromptField) -> Vec<(&'static str, Piece)> { + let text = |s: &str| format!("{}.into()", literal(s)); + let mut out = Vec::new(); + if p.array { + out.push(("array", "true;".into())); + } + if let Some(values) = &p.enum_values { + out.push(( + "enum_values", + list("Some(vec![", values.iter().map(|v| text(v)), "]);"), + )); + } + if let Some(doc) = &p.enum_doc { + // A HashMap has no order of its own: the source lists it by member. + let sorted: BTreeMap<&String, &String> = doc.iter().collect(); + out.push(( + "enum_doc", + list( + "Some(HashMap::from([", + sorted + .into_iter() + .map(|(k, v)| format!("({}, {})", text(k), text(v))), + "]));", + ), + )); + } + if let Some(v) = &p.example { + out.push(("example", format!("Some({});", text(v)).into())); + } + if let Some(v) = &p.instruction { + out.push(("instruction", format!("Some({});", text(v)).into())); + } + out +} diff --git a/server/rust/metaobjects-codegen/src/render_helper.rs b/server/rust/metaobjects-codegen/src/render_helper.rs new file mode 100644 index 0000000000..c81844a8ce --- /dev/null +++ b/server/rust/metaobjects-codegen/src/render_helper.rs @@ -0,0 +1,787 @@ +//! The `render-helper` generator: a typed render function per renderable template, one crate +//! per package. +//! +//! A `template.output` or `template.prompt` names a payload value object (`@payloadRef`) and +//! the Mustache bodies it renders (`@textRef`, or the three parts of an email). For the +//! package `acme::ai` the generator writes: +//! +//! ```text +//! /acme_ai_prompts/Cargo.toml the crate (metaobjects-render, the payload crates) +//! /acme_ai_prompts/src/lib.rs one `mod` per template and a `pub use` of each helper +//! /acme_ai_prompts/src/