From 18ee7d9089be5de9f9e6c1798be797a06b047e18 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 23:33:33 -0500 Subject: [PATCH 01/13] feat(rust): add the run engine, `cargo meta gen` and the entity generator The Rust port can now generate code. Two new workspace crates: - metaobjects-codegen: the run engine (ADR-0064) and the `entity` generator. The engine writes a generated file only when its bytes changed, saves the hash manifest once per run and only when a record changed, and skips the whole run when the model hash tree, project config, engine build, generator identities and flags match the stored key and every recorded output is intact. `entity` writes one crate per metadata package: serde structs for entities and value objects, enums, Box only where a by-value cycle needs it, path dependencies for cross-package references, already rustfmt-clean. - metaobjects-cli: the `cargo-meta` binary, so `cargo meta gen` works. Rust differs from the other ports on purpose: no three-way merge (a hand-edited generated file is refused), outputs must be inside the project, and there is no verify, eject or template tier yet. Tests: golden text, `cargo check` + rustfmt + serde round trip on generated crates, run-engine, the shared skip-conformance corpus, CLI. gen_bench records time per stage with no thresholds; the rust lane prints it. --- CHANGELOG.md | 29 + scripts/ci-local.sh | 19 +- server/rust/Cargo.lock | 17 + server/rust/Cargo.toml | 11 +- server/rust/metaobjects-cli/Cargo.toml | 27 + server/rust/metaobjects-cli/src/lib.rs | 263 +++++ server/rust/metaobjects-cli/src/main.rs | 19 + server/rust/metaobjects-cli/tests/cli.rs | 124 +++ server/rust/metaobjects-codegen/Cargo.toml | 19 + server/rust/metaobjects-codegen/build.rs | 58 ++ .../metaobjects-codegen/examples/gen_bench.rs | 242 +++++ server/rust/metaobjects-codegen/src/engine.rs | 467 +++++++++ server/rust/metaobjects-codegen/src/entity.rs | 956 ++++++++++++++++++ .../metaobjects-codegen/src/fingerprint.rs | 253 +++++ .../rust/metaobjects-codegen/src/generator.rs | 99 ++ server/rust/metaobjects-codegen/src/hashes.rs | 231 +++++ server/rust/metaobjects-codegen/src/lib.rs | 20 + server/rust/metaobjects-codegen/src/names.rs | 260 +++++ .../rust/metaobjects-codegen/src/project.rs | 41 + server/rust/metaobjects-codegen/src/sha256.rs | 205 ++++ .../metaobjects-codegen/tests/common/mod.rs | 128 +++ .../rust/metaobjects-codegen/tests/compile.rs | 189 ++++ .../metaobjects-codegen/tests/entity_edges.rs | 167 +++ .../rust/metaobjects-codegen/tests/golden.rs | 87 ++ .../tests/golden/shop/shop/Cargo.toml | 10 + .../tests/golden/shop/shop/rustfmt.toml | 6 + .../tests/golden/shop/shop/src/address.rs | 9 + .../tests/golden/shop/shop/src/category.rs | 11 + .../tests/golden/shop/shop/src/currency.rs | 23 + .../tests/golden/shop/shop/src/lib.rs | 14 + .../tests/golden/shop/shop/src/order.rs | 47 + .../tests/golden/shop/shop_billing/Cargo.toml | 11 + .../golden/shop/shop_billing/rustfmt.toml | 6 + .../golden/shop/shop_billing/src/invoice.rs | 9 + .../tests/golden/shop/shop_billing/src/lib.rs | 7 + .../metaobjects-codegen/tests/run_engine.rs | 265 +++++ .../tests/skip_conformance.rs | 398 ++++++++ 37 files changed, 4737 insertions(+), 10 deletions(-) create mode 100644 server/rust/metaobjects-cli/Cargo.toml create mode 100644 server/rust/metaobjects-cli/src/lib.rs create mode 100644 server/rust/metaobjects-cli/src/main.rs create mode 100644 server/rust/metaobjects-cli/tests/cli.rs create mode 100644 server/rust/metaobjects-codegen/Cargo.toml create mode 100644 server/rust/metaobjects-codegen/build.rs create mode 100644 server/rust/metaobjects-codegen/examples/gen_bench.rs create mode 100644 server/rust/metaobjects-codegen/src/engine.rs create mode 100644 server/rust/metaobjects-codegen/src/entity.rs create mode 100644 server/rust/metaobjects-codegen/src/fingerprint.rs create mode 100644 server/rust/metaobjects-codegen/src/generator.rs create mode 100644 server/rust/metaobjects-codegen/src/hashes.rs create mode 100644 server/rust/metaobjects-codegen/src/lib.rs create mode 100644 server/rust/metaobjects-codegen/src/names.rs create mode 100644 server/rust/metaobjects-codegen/src/project.rs create mode 100644 server/rust/metaobjects-codegen/src/sha256.rs create mode 100644 server/rust/metaobjects-codegen/tests/common/mod.rs create mode 100644 server/rust/metaobjects-codegen/tests/compile.rs create mode 100644 server/rust/metaobjects-codegen/tests/entity_edges.rs create mode 100644 server/rust/metaobjects-codegen/tests/golden.rs create mode 100644 server/rust/metaobjects-codegen/tests/golden/shop/shop/Cargo.toml create mode 100644 server/rust/metaobjects-codegen/tests/golden/shop/shop/rustfmt.toml create mode 100644 server/rust/metaobjects-codegen/tests/golden/shop/shop/src/address.rs create mode 100644 server/rust/metaobjects-codegen/tests/golden/shop/shop/src/category.rs create mode 100644 server/rust/metaobjects-codegen/tests/golden/shop/shop/src/currency.rs create mode 100644 server/rust/metaobjects-codegen/tests/golden/shop/shop/src/lib.rs create mode 100644 server/rust/metaobjects-codegen/tests/golden/shop/shop/src/order.rs create mode 100644 server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/Cargo.toml create mode 100644 server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/rustfmt.toml create mode 100644 server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/src/invoice.rs create mode 100644 server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/src/lib.rs create mode 100644 server/rust/metaobjects-codegen/tests/run_engine.rs create mode 100644 server/rust/metaobjects-codegen/tests/skip_conformance.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e4b248920..822c3c37ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,35 @@ here.** `iam` and `ai` library sources embedded in the crate, and the naming strategies, pluralizers and collection-name collision check. It passes `yaml-conformance` 18 of 19, and the `source-resolution-conformance` and `naming-conformance` corpora in full. Nothing is published. +- **Rust port generates code, in preview: `cargo meta gen` and the `entity` generator.** Two new + workspace crates. `metaobjects-codegen` holds the run engine and the generator; + `metaobjects-cli` builds the binary `cargo-meta`, so cargo's external-subcommand rule makes + `cargo meta gen` work (`cargo-meta gen` too). The run engine follows ADR-0064 and keeps the + other ports' manifest format: it writes a generated file only when its bytes changed, saves + `.metaobjects/.gen-state/.hashes.json` once per run and only when a record changed, and skips + the whole run (nothing rendered, nothing written, not even the manifest) when the model hash + tree, the project config, the engine's built code, each generator's identity and the flags match + the stored key in `.fingerprint-rust.json` and every recorded output is still as the last run + left it. The shared `fixtures/codegen-skip-conformance` corpus runs against it: every case the port can meet runs, + and the ones it cannot (templates, ejected generators, `verify`, a kept hand edit) are named + with the reason. The `entity` generator writes one crate per metadata package: serde structs + for `object.entity` and `object.value` (inherited fields included, optional fields as `Option`, + arrays as `Vec`, a map as `BTreeMap`), enums for `field.enum` (shared enums once, in their + declaration's package) with the member symbols as the wire form, `Box` only where a by-value + cycle needs it, and a path dependency for each cross-package reference. The output is already + rustfmt-clean under the `rustfmt.toml` written beside it, so no formatter runs in the hot path. + Tests: a golden test of a two-package model's text, a test that generates that model and the + fitness model and runs `cargo check`, `rustfmt --check` and a serde round trip on the crates, + and the run-engine, skip-corpus and CLI suites. `gen_bench` prints time per stage (load, plan, + skip, render, write) for a first run, an unchanged run, a one-file change and a forced run on + the 20x fitness project, record only, and the `rust` lane prints it. Where Rust differs from the + other ports, on purpose: there is no three-way merge, so a generated file edited by hand (or an + existing file nobody recorded) is refused and the run exits 1 after finishing the other files, + as Python does; the output directory must be inside the project, so every manifest key is + project-relative; a named run (`cargo meta gen Order`) regenerates the whole files of the named + objects and their crate's manifest files rather than merging; and there is no `verify`, + `eject`, template or client generator yet. Relationships, projections and reports are not + emitted. Nothing is published. - **Cross-port stage benchmark and Rust port documentation.** `scripts/bench-load/stages.py` runs every port (TypeScript, Python, C#, Java, Kotlin, Rust) over the same model, stage by stage: load diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 61d80873cf..7d826b8961 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -72,8 +72,9 @@ # # rust → the Rust port (preview): cargo fmt # # --check, clippy -D warnings, and its # # tests, which run the registry and -# # metamodel corpora, then the load_bench -# # table (record only). No docker half. +# # metamodel corpora and the codegen suites, +# # then the load_bench and gen_bench tables +# # (record only). No docker half. # # cube → the cube-model live check: a real Cube # # (cubejs/cube, pinned) over a private # # Postgres, both in docker (FR-044). Its @@ -819,8 +820,9 @@ gate_conf_python() { if [ "$NO_INTEG" -eq 1 ] || ! docker info >/dev/null 2>&1; then skip_integ=""; fi ( cd server/python && uv run --extra integration pytest tests/ $skip_integ -q -n "${MO_CI_PY_WORKERS:-8}" ) } -# The Rust port (preview, ADR-0065). The whole crate suite, not a cherry-pick: it is the -# registry-conformance and metamodel corpora plus the unit tests, ~1s once built. --locked +# The Rust port (preview, ADR-0065). The whole workspace suite, not a cherry-pick: the +# registry-conformance and metamodel corpora, the unit tests, and the codegen tests (which run +# `cargo check` on generated crates), a few seconds once built. --locked # so a stale Cargo.lock fails here instead of being rewritten. The build goes to the # workspace's own target/ (gitignored); never a CARGO_TARGET_DIR shared between checkouts. gate_conf_rust() { @@ -828,7 +830,8 @@ gate_conf_rust() { && cargo fmt --all --check \ && cargo clippy --locked --all-targets -q -- -D warnings \ && cargo test --locked -q -- --nocapture \ - && gate_rust_load_bench ) + && gate_rust_load_bench \ + && gate_rust_gen_bench ) } # Load time per phase and per validation pass on the 20x fitness model. Record only: # it prints a table and never fails on a number, so a slowdown is read in the log and @@ -841,6 +844,12 @@ gate_conf_rust() { gate_rust_load_bench() { cargo run --release --locked -q --example load_bench -- 20 15 } +# Generation time per stage (load, plan, skip, render, write) on the 20x fitness project: +# a first run, an unchanged run (which skips), a one-file change and a forced run. Record +# only, like load_bench; it writes its project under $DEV_SCRATCH and removes it. +gate_rust_gen_bench() { + cargo run --release --locked -q -p metaobjects-codegen --example gen_bench -- 20 9 +} gate_conf_kotlin() { ( cd server/java \ && mvn -pl codegen-kotlin -am install -DskipTests -q \ diff --git a/server/rust/Cargo.lock b/server/rust/Cargo.lock index 1815dc38d9..37cd63e867 100644 --- a/server/rust/Cargo.lock +++ b/server/rust/Cargo.lock @@ -101,6 +101,23 @@ dependencies = [ "serde_json", ] +[[package]] +name = "metaobjects-cli" +version = "0.1.0" +dependencies = [ + "metaobjects", + "metaobjects-codegen", +] + +[[package]] +name = "metaobjects-codegen" +version = "0.1.0" +dependencies = [ + "indexmap", + "metaobjects", + "serde_json", +] + [[package]] name = "multiversion_no_op" version = "1.0.0" diff --git a/server/rust/Cargo.toml b/server/rust/Cargo.toml index 27a039904d..209d444e2b 100644 --- a/server/rust/Cargo.toml +++ b/server/rust/Cargo.toml @@ -1,13 +1,14 @@ # The Rust port of MetaObjects (preview). ADR-0065 records why it exists and how it # differs from the other five ports. # -# One crate today: `metaobjects` (metamodel registry, JSON loader, canonical -# serializer). The codegen engine (`metaobjects-codegen`) and the `cargo meta` -# command (`metaobjects-cli`) join this workspace in later steps; no placeholder -# crates are created for them ahead of time. +# Three crates: +# `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. [workspace] resolver = "3" -members = ["metaobjects"] +members = ["metaobjects", "metaobjects-codegen", "metaobjects-cli"] [workspace.package] version = "0.1.0" diff --git a/server/rust/metaobjects-cli/Cargo.toml b/server/rust/metaobjects-cli/Cargo.toml new file mode 100644 index 0000000000..71b6393d24 --- /dev/null +++ b/server/rust/metaobjects-cli/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "metaobjects-cli" +description = "The `cargo meta` command for MetaObjects on Rust (preview)." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +# Not published yet. The crates.io name `cargo-meta` belongs to an unrelated crate, so this +# package is `metaobjects-cli` and only its binary is called `cargo-meta`; that binary name +# is what makes cargo's external-subcommand rule run it for `cargo meta ...`. +publish = false + +[lib] +name = "metaobjects_cli" +path = "src/lib.rs" + +[[bin]] +name = "cargo-meta" +path = "src/main.rs" + +[dependencies] +metaobjects = { path = "../metaobjects" } +metaobjects-codegen = { path = "../metaobjects-codegen" } + +[lints] +workspace = true diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs new file mode 100644 index 0000000000..2754b6b9cf --- /dev/null +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -0,0 +1,263 @@ +//! The `cargo meta` command (preview). +//! +//! Cargo runs `cargo-` for `cargo ` and passes `` as the first argument, so +//! the binary accepts both `cargo-meta meta gen` (how cargo calls it) and `cargo-meta gen`. +//! The commands are written against `Write` handles so they run in tests without a process. + +use std::io::Write; +use std::path::{Path, PathBuf}; + +use metaobjects::timing::{LoadTimings, ms, render_table}; +use metaobjects_codegen::engine::{Outcome, RunError, RunOptions, RunReport}; +use metaobjects_codegen::{EntityGenerator, Generator, run}; + +const USAGE: &str = "\ +cargo meta: MetaObjects for Rust (preview) + +USAGE: + cargo meta gen [OPTIONS] [ENTITY...] + +COMMANDS: + gen Generate Rust crates (one per metadata package) from the project's model. + Skips the whole run when the model, the project config and the generators + are unchanged; writes only files whose bytes changed. + +OPTIONS: + --project The project root (the directory holding .metaobjects/config.json). + Default: the nearest one at or above the current directory. + --out Where the crates are written, relative to the project root and + inside it. Default: generated + --generators Run only these generators. Available: entity + --strict Load strictly: an attribute no provider declares is an error. + --force Render and compare even when nothing changed. + --timings Print the time spent in each stage (load, plan, skip, render, write). + -h, --help Print this help. + -V, --version Print the version. + +ENTITY names limit the run to the packages that contain them. Such a run never skips and +never stores the skip key. + +EXIT STATUS: 0 success; 1 the run failed; 2 usage error. +"; + +/// The generators `cargo meta gen` runs. +fn generators() -> Vec> { + vec![Box::new(EntityGenerator)] +} + +/// Parsed `gen` arguments. +#[derive(Debug, PartialEq)] +struct GenArgs { + options: RunOptions, + timings: bool, +} + +#[derive(Debug, PartialEq)] +enum Parsed { + Help, + Version, + Gen(Box), +} + +fn parse(args: &[String], cwd: &Path) -> Result { + let mut rest = args; + if rest.first().map(String::as_str) == Some("meta") { + rest = &rest[1..]; + } + let mut options = RunOptions::new(cwd); + let mut timings = false; + let mut command = None; + let mut it = rest.iter(); + while let Some(a) = it.next() { + let mut value = |flag: &str| { + it.next() + .cloned() + .ok_or_else(|| format!("{flag} needs a value")) + }; + match a.as_str() { + "-h" | "--help" | "help" => return Ok(Parsed::Help), + "-V" | "--version" => return Ok(Parsed::Version), + "--project" => options.project_dir = Some(PathBuf::from(value("--project")?)), + "--out" => options.out_dir = PathBuf::from(value("--out")?), + "--generators" => { + let v = value("--generators")?; + options.generators = Some( + v.split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect(), + ); + } + "--strict" => options.strict = true, + "--force" => options.force = true, + "--timings" => timings = true, + flag if flag.starts_with('-') => return Err(format!("unknown option {flag}")), + word if command.is_none() => command = Some(word.to_string()), + entity => options.entities.push(entity.to_string()), + } + } + match command.as_deref() { + Some("gen") => {} + Some(other) => return Err(format!("unknown command {other}")), + None => return Err("missing command: try `cargo meta gen`".to_string()), + } + if let Some(names) = &options.generators { + let known: Vec = generators().iter().map(|g| g.name().to_string()).collect(); + for n in names { + if !known.contains(n) { + return Err(format!( + "unknown generator {n}; available: {}", + known.join(", ") + )); + } + } + } + Ok(Parsed::Gen(Box::new(GenArgs { options, timings }))) +} + +fn stage_rows(t: &LoadTimings) -> Vec<(String, f64)> { + t.phases + .iter() + .map(|x| (x.name.to_string(), ms(x.duration))) + .collect() +} + +fn report_summary(r: &RunReport) -> String { + let total = ms(r.timings.total()); + match r.outcome { + Outcome::Skipped => { + format!("gen: skipped, nothing changed since the last run ({total:.1} ms)") + } + Outcome::Generated => { + let f = &r.files; + let mut parts = vec![ + format!("{} created", f.created), + format!("{} updated", f.overwritten), + format!("{} unchanged", f.unchanged), + ]; + if f.removed > 0 { + parts.push(format!("{} removed", f.removed)); + } + let total_files = f.created + f.overwritten + f.unchanged; + format!( + "gen: {total_files} files ({}) in {total:.1} ms{}", + parts.join(", "), + match r.no_skip_reason { + Some(why) => format!("; did not skip: {why}"), + None => String::new(), + } + ) + } + } +} + +/// Run the command line. Returns the process exit status. +pub fn main_with(args: &[String], cwd: &Path, out: &mut dyn Write, err: &mut dyn Write) -> i32 { + let parsed = match parse(args, cwd) { + Ok(p) => p, + Err(msg) => { + let _ = writeln!(err, "cargo meta: {msg}\n\n{USAGE}"); + return 2; + } + }; + let gen_args = match parsed { + Parsed::Help => { + let _ = write!(out, "{USAGE}"); + return 0; + } + Parsed::Version => { + let _ = writeln!(out, "cargo-meta {}", env!("CARGO_PKG_VERSION")); + return 0; + } + Parsed::Gen(a) => *a, + }; + match run(&gen_args.options, &generators()) { + Ok(report) => { + for w in &report.warnings { + let _ = writeln!(err, "warning: {w}"); + } + let _ = writeln!(out, "{}", report_summary(&report)); + if gen_args.timings { + let _ = writeln!(out); + let _ = write!( + out, + "{}", + render_table("stage", &stage_rows(&report.timings), None) + ); + } + 0 + } + Err(e) => { + let _ = writeln!(err, "cargo meta gen failed:\n{e}"); + if matches!(e, RunError::Load(_)) { + let _ = writeln!(err, "\nNothing was written."); + } + 1 + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(list: &[&str]) -> Vec { + list.iter().map(ToString::to_string).collect() + } + + fn gen_options(list: &[&str]) -> GenArgs { + match parse(&args(list), Path::new("/p")).expect("parses") { + Parsed::Gen(a) => *a, + other => panic!("not a gen command: {other:?}"), + } + } + + #[test] + fn cargo_passes_the_subcommand_name_first_and_both_spellings_parse() { + let a = gen_options(&["meta", "gen", "--force", "Order"]); + let b = gen_options(&["gen", "--force", "Order"]); + assert_eq!(a, b); + assert!(a.options.force); + assert_eq!(a.options.entities, vec!["Order".to_string()]); + } + + #[test] + fn flags_with_values_parse() { + let a = gen_options(&[ + "meta", + "gen", + "--out", + "crates", + "--project", + "app", + "--generators", + "entity", + "--timings", + "--strict", + ]); + assert_eq!(a.options.out_dir, PathBuf::from("crates")); + assert_eq!(a.options.project_dir, Some(PathBuf::from("app"))); + assert_eq!(a.options.generators, Some(vec!["entity".to_string()])); + assert!(a.timings && a.options.strict); + } + + #[test] + fn bad_input_is_a_usage_error() { + assert!(parse(&args(&["meta"]), Path::new("/p")).is_err()); + assert!(parse(&args(&["meta", "verify"]), Path::new("/p")).is_err()); + assert!(parse(&args(&["meta", "gen", "--bogus"]), Path::new("/p")).is_err()); + assert!(parse(&args(&["meta", "gen", "--out"]), Path::new("/p")).is_err()); + assert!( + parse( + &args(&["meta", "gen", "--generators", "nope"]), + Path::new("/p") + ) + .is_err() + ); + assert_eq!( + parse(&args(&["meta", "--help"]), Path::new("/p")), + Ok(Parsed::Help) + ); + } +} diff --git a/server/rust/metaobjects-cli/src/main.rs b/server/rust/metaobjects-cli/src/main.rs new file mode 100644 index 0000000000..bda106ff56 --- /dev/null +++ b/server/rust/metaobjects-cli/src/main.rs @@ -0,0 +1,19 @@ +//! `cargo-meta`: the binary behind `cargo meta`. + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let cwd = match std::env::current_dir() { + Ok(dir) => dir, + Err(e) => { + eprintln!("cargo meta: cannot read the current directory: {e}"); + std::process::exit(1); + } + }; + let code = metaobjects_cli::main_with( + &args, + &cwd, + &mut std::io::stdout().lock(), + &mut std::io::stderr().lock(), + ); + std::process::exit(code); +} diff --git a/server/rust/metaobjects-cli/tests/cli.rs b/server/rust/metaobjects-cli/tests/cli.rs new file mode 100644 index 0000000000..86fb4477fe --- /dev/null +++ b/server/rust/metaobjects-cli/tests/cli.rs @@ -0,0 +1,124 @@ +//! `cargo meta gen` as cargo runs it: the real `cargo-meta` binary, started the way cargo +//! starts an external subcommand (`cargo-meta meta gen ...`) and the way a person might +//! (`cargo-meta gen ...`). + +use std::path::PathBuf; +use std::process::{Command, Output}; + +const MODEL: &str = r#"{ "metadata.root": { "package": "shop", "children": [ + { "object.entity": { "name": "Order", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.string": { "name": "note" } } + ] } } +] } }"#; + +struct Project(PathBuf); + +impl Project { + fn new(tag: &str) -> Self { + let base = std::env::var_os("DEV_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let dir = base.join(format!("mo-cli-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join(".metaobjects")).unwrap(); + std::fs::create_dir_all(dir.join("metaobjects")).unwrap(); + std::fs::write( + dir.join(".metaobjects/config.json"), + r#"{ "schema_version": 1 }"#, + ) + .unwrap(); + std::fs::write(dir.join("metaobjects/meta.shop.json"), MODEL).unwrap(); + Project(dir) + } + + fn run(&self, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_cargo-meta")) + .args(args) + .current_dir(&self.0) + .output() + .expect("cargo-meta starts") + } +} + +impl Drop for Project { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn text(b: &[u8]) -> String { + String::from_utf8_lossy(b).into_owned() +} + +#[test] +fn cargo_meta_gen_writes_the_crate_then_skips() { + let p = Project::new("gen"); + let first = p.run(&["meta", "gen", "--timings"]); + assert!(first.status.success(), "{}", text(&first.stderr)); + let out = text(&first.stdout); + assert!(out.contains("gen: 4 files (4 created"), "{out}"); + assert!(out.contains("render") && out.contains("write"), "{out}"); + let order = std::fs::read_to_string(p.0.join("generated/shop/src/order.rs")).unwrap(); + assert!(order.contains("pub struct Order"), "{order}"); + assert!(order.contains("pub note: Option"), "{order}"); + + let second = p.run(&["meta", "gen", "--timings"]); + assert!(second.status.success()); + let out = text(&second.stdout); + assert!(out.contains("skipped, nothing changed"), "{out}"); + assert!( + !out.contains("render"), + "a skipped run has no render stage: {out}" + ); +} + +#[test] +fn the_direct_spelling_works_and_out_moves_the_output() { + let p = Project::new("direct"); + let r = p.run(&["gen", "--out", "crates"]); + assert!(r.status.success(), "{}", text(&r.stderr)); + assert!(p.0.join("crates/shop/Cargo.toml").exists()); + assert!(!p.0.join("generated").exists()); +} + +#[test] +fn a_hand_edit_makes_the_run_fail_and_name_the_file() { + let p = Project::new("edit"); + assert!(p.run(&["meta", "gen"]).status.success()); + let file = p.0.join("generated/shop/src/order.rs"); + std::fs::write(&file, "// mine\n").unwrap(); + let r = p.run(&["meta", "gen"]); + assert_eq!(r.status.code(), Some(1)); + assert!( + text(&r.stderr).contains("generated/shop/src/order.rs"), + "{}", + text(&r.stderr) + ); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "// mine\n"); +} + +#[test] +fn a_model_that_does_not_load_exits_1_and_writes_nothing() { + let p = Project::new("bad"); + std::fs::write(p.0.join("metaobjects/meta.shop.json"), "{ nope").unwrap(); + let r = p.run(&["meta", "gen"]); + assert_eq!(r.status.code(), Some(1)); + assert!( + text(&r.stderr).contains("Nothing was written"), + "{}", + text(&r.stderr) + ); + assert!(!p.0.join("generated").exists()); +} + +#[test] +fn usage_errors_exit_2_and_help_exits_0() { + let p = Project::new("usage"); + assert_eq!(p.run(&["meta", "verify"]).status.code(), Some(2)); + assert_eq!(p.run(&["meta", "gen", "--nope"]).status.code(), Some(2)); + let h = p.run(&["meta", "--help"]); + assert!(h.status.success()); + assert!(text(&h.stdout).contains("cargo meta gen")); +} diff --git a/server/rust/metaobjects-codegen/Cargo.toml b/server/rust/metaobjects-codegen/Cargo.toml new file mode 100644 index 0000000000..1763822309 --- /dev/null +++ b/server/rust/metaobjects-codegen/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "metaobjects-codegen" +description = "MetaObjects code generation for Rust (preview): the run engine and the entity generator." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +# Not published yet: the first crates.io release is a separate, approved step. +publish = false +build = "build.rs" + +[dependencies] +metaobjects = { path = "../metaobjects" } +serde_json.workspace = true +indexmap.workspace = true + +[lints] +workspace = true diff --git a/server/rust/metaobjects-codegen/build.rs b/server/rust/metaobjects-codegen/build.rs new file mode 100644 index 0000000000..6a5171bb6a --- /dev/null +++ b/server/rust/metaobjects-codegen/build.rs @@ -0,0 +1,58 @@ +//! Hashes the sources of the engine and of the loader it is built on, and hands the digest +//! to the crate as `METAOBJECTS_ENGINE_SOURCE_HASH`. +//! +//! The skip key (ADR-0064 section 3) names a generator by the hash of its built code, not +//! only by a release number, so a locally built engine with different content never reuses +//! a key a different build stored. For Rust the built code is a function of these sources. + +#[path = "src/sha256.rs"] +#[allow(dead_code)] +mod sha256; + +use std::path::{Path, PathBuf}; + +fn collect(dir: &Path, out: &mut Vec) { + let Ok(read) = std::fs::read_dir(dir) else { + return; + }; + let mut entries: Vec<_> = read.filter_map(Result::ok).map(|e| e.path()).collect(); + entries.sort(); + for p in entries { + if p.is_dir() { + collect(&p, out); + } else if p.extension().is_some_and(|e| e == "rs" || e == "toml") { + out.push(p); + } + } +} + +fn main() { + let manifest = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("manifest dir")); + let roots = [ + manifest.join("src"), + manifest.join("Cargo.toml"), + manifest.join("../metaobjects/src"), + manifest.join("../metaobjects/Cargo.toml"), + ]; + let mut hasher = sha256::Sha256::new(); + for root in &roots { + println!("cargo:rerun-if-changed={}", root.display()); + let mut files = Vec::new(); + if root.is_dir() { + collect(root, &mut files); + } else if root.is_file() { + files.push(root.clone()); + } + for f in files { + let rel = f.strip_prefix(&manifest).unwrap_or(&f); + hasher.update(rel.to_string_lossy().replace('\\', "/").as_bytes()); + hasher.update(&[0]); + hasher.update(&std::fs::read(&f).unwrap_or_default()); + hasher.update(&[0]); + } + } + println!( + "cargo:rustc-env=METAOBJECTS_ENGINE_SOURCE_HASH={}", + sha256::hex(&hasher.finish()) + ); +} diff --git a/server/rust/metaobjects-codegen/examples/gen_bench.rs b/server/rust/metaobjects-codegen/examples/gen_bench.rs new file mode 100644 index 0000000000..e5a1c5e412 --- /dev/null +++ b/server/rust/metaobjects-codegen/examples/gen_bench.rs @@ -0,0 +1,242 @@ +//! Code-generation time per stage on a 20-times project written to disk, built from the +//! public conformance fitness model +//! (`fixtures/persistence-conformance/canonical/meta.fitness.json`). +//! +//! Each copy keeps every name and gets its own root package (`fitness_x00` ... `fitness_x19`), +//! so each becomes its own crate. The project lives under `$DEV_SCRATCH` (a RAM disk when set) +//! and is removed when the run ends. +//! +//! ```text +//! cargo run --release --example gen_bench [-- +//! [--baseline ] [--write-baseline ]] +//! ``` +//! +//! Four scenarios, each the median over the iterations, each as a table of time per stage +//! (load, plan, skip, render, write): +//! +//! - `first run`: no outputs and no state on disk; every file is created. +//! - `no change`: the run after it; the skip key matches, so nothing renders or writes. +//! - `one file changed`: one object in one copy gained a description; one file is rewritten, and the +//! manifest is saved once. +//! - `forced, nothing changed`: `--force`; every file is rendered and compared and none is +//! written, which is what the write path costs when bytes are identical. +//! +//! With `--baseline` each row also shows the baseline's figure and the change; with +//! `--write-baseline` the run is saved in that file's format. A baseline is a record to read: +//! the comparison never fails the run. + +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use metaobjects::timing::{ms, render_table}; +use metaobjects_codegen::engine::{STAGE_LOAD, STAGE_PLAN, STAGE_RENDER, STAGE_SKIP, STAGE_WRITE}; +use metaobjects_codegen::{EntityGenerator, Generator, Outcome, RunOptions, RunReport, run}; +use serde_json::{Map, Value, json}; + +const FITNESS: &str = + include_str!("../../../../fixtures/persistence-conformance/canonical/meta.fitness.json"); +const ROOT_PACKAGE: &str = "\"package\": \"fitness\""; +/// An object that exists in every copy; the change scenario gives it a description. +const CHANGE_AT: &str = "\"name\": \"AllTypes\""; + +const STAGES: [&str; 5] = [ + STAGE_LOAD, + STAGE_PLAN, + STAGE_SKIP, + STAGE_RENDER, + STAGE_WRITE, +]; + +fn scratch_base() -> PathBuf { + std::env::var_os("DEV_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir) +} + +fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().expect("a file has a parent")).expect("mkdir"); + std::fs::write(path, text).expect("write"); +} + +fn copy_text(i: usize) -> String { + FITNESS.replacen( + ROOT_PACKAGE, + &format!("\"package\": \"fitness_x{i:02}\""), + 1, + ) +} + +fn gen_run(project: &Path, force: bool) -> RunReport { + let mut opts = RunOptions::new(project); + opts.force = force; + let generators: Vec> = vec![Box::new(EntityGenerator)]; + run(&opts, &generators).unwrap_or_else(|e| panic!("gen failed: {e}")) +} + +/// Time per stage in milliseconds, every stage present (zero when the run skipped it), plus +/// the run's total. +fn stage_rows(r: &RunReport) -> Vec<(String, f64)> { + let mut rows: Vec<(String, f64)> = STAGES + .iter() + .map(|s| (s.to_string(), ms(r.timings.phase_time(s)))) + .collect(); + rows.push(("total".to_string(), ms(r.timings.total()))); + rows +} + +fn median_rows(runs: &[Vec<(String, f64)>]) -> Vec<(String, f64)> { + let names: Vec = runs[0].iter().map(|(n, _)| n.clone()).collect(); + names + .into_iter() + .map(|n| { + let mut v: Vec = runs + .iter() + .map(|r| r.iter().find(|(m, _)| *m == n).map_or(0.0, |(_, t)| *t)) + .collect(); + v.sort_by(f64::total_cmp); + let mid = v[v.len() / 2]; + (n, mid) + }) + .collect() +} + +fn to_json_rows(rows: &[(String, f64)]) -> Value { + Value::Object( + rows.iter() + .map(|(n, t)| (n.clone(), json!((t * 1000.0).round() / 1000.0))) + .collect::>(), + ) +} + +fn from_json_rows(v: &Value) -> Vec<(String, f64)> { + v.as_object() + .map(|m| { + m.iter() + .filter_map(|(k, v)| Some((k.clone(), v.as_f64()?))) + .collect() + }) + .unwrap_or_default() +} + +fn main() { + let mut baseline_path = None; + let mut write_path = None; + let mut positional = Vec::new(); + let mut raw = std::env::args().skip(1); + while let Some(a) = raw.next() { + match a.as_str() { + "--baseline" => baseline_path = Some(raw.next().expect("--baseline takes a file")), + "--write-baseline" => { + write_path = Some(raw.next().expect("--write-baseline takes a file")); + } + _ => positional.push(a), + } + } + let mut args = positional.into_iter(); + let copies: usize = args + .next() + .map_or(20, |a| a.parse().expect("copies is a number")); + let iterations: usize = args + .next() + .map_or(9, |a| a.parse().expect("iterations is a number")); + assert!(FITNESS.contains(ROOT_PACKAGE) && FITNESS.contains(CHANGE_AT)); + + let project = scratch_base().join(format!("mo-gen-bench-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&project); + write( + &project.join(".metaobjects/config.json"), + r#"{ "schema_version": 1 }"#, + ); + let model_file = |i: usize| project.join(format!("metaobjects/meta.fitness_x{i:02}.json")); + for i in 0..copies { + write(&model_file(i), ©_text(i)); + } + let bytes: usize = (0..copies).map(|i| copy_text(i).len()).sum(); + + let mut firsts = Vec::new(); + let mut skips = Vec::new(); + let mut changes = Vec::new(); + let mut forced = Vec::new(); + let mut files = 0; + let started = Instant::now(); + for n in 0..iterations { + // A cold start: no outputs, no manifest, no stored key. + let _ = std::fs::remove_dir_all(project.join("generated")); + let _ = std::fs::remove_dir_all(project.join(".metaobjects/.gen-state")); + write(&model_file(0), ©_text(0)); + + let r = gen_run(&project, false); + assert_eq!(r.outcome, Outcome::Generated); + files = r.files.created; + firsts.push(stage_rows(&r)); + + let r = gen_run(&project, false); + assert_eq!(r.outcome, Outcome::Skipped, "an unchanged project skips"); + skips.push(stage_rows(&r)); + + // A new description on AllTypes in copy 0; different each iteration. + let edited = copy_text(0).replacen( + CHANGE_AT, + &format!("\"name\": \"AllTypes\", \"@description\": \"edit {n}\""), + 1, + ); + write(&model_file(0), &edited); + let r = gen_run(&project, false); + assert_eq!(r.outcome, Outcome::Generated); + assert_eq!( + r.files.overwritten, 1, + "one object changed, one file rewrites" + ); + changes.push(stage_rows(&r)); + + let r = gen_run(&project, true); + assert_eq!(r.outcome, Outcome::Generated); + assert_eq!(r.files.created + r.files.overwritten, 0); + forced.push(stage_rows(&r)); + } + let elapsed = started.elapsed(); + let _ = std::fs::remove_dir_all(&project); + + println!( + "project: {copies} copies of the fitness model, {} KiB of JSON, {files} generated files in {copies} crates", + bytes / 1024 + ); + println!("median of {iterations} iterations; whole benchmark {elapsed:.1?}"); + + let scenarios = [ + ("first run", median_rows(&firsts)), + ("no change", median_rows(&skips)), + ("one file changed", median_rows(&changes)), + ("forced, nothing changed", median_rows(&forced)), + ]; + let baseline: Option = baseline_path.as_ref().map(|p| { + serde_json::from_str(&std::fs::read_to_string(p).expect("baseline file is readable")) + .expect("baseline file is JSON") + }); + for (name, rows) in &scenarios { + println!(); + print!( + "{}", + render_table( + name, + rows, + baseline + .as_ref() + .map(|b| from_json_rows(&b[name])) + .as_deref() + ) + ); + } + if let Some(p) = write_path { + let doc: Map = scenarios + .iter() + .map(|(n, rows)| (n.to_string(), to_json_rows(rows))) + .collect(); + std::fs::write( + &p, + serde_json::to_string_pretty(&Value::Object(doc)).unwrap() + "\n", + ) + .expect("write baseline"); + println!("\nbaseline written to {p}"); + } +} diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs new file mode 100644 index 0000000000..334ec68f95 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -0,0 +1,467 @@ +//! The run engine: load, plan, skip, render, write. +//! +//! One run is five stages, each timed the way a load is (`LoadTimings`, no thresholds): +//! +//! | stage | what it does | +//! |----------|--------------| +//! | `load` | resolve the project, read its files, load and validate the model | +//! | `plan` | hash the model and every input into the skip key; read the manifest | +//! | `skip` | when the key matches the stored one, check every recorded file still has the bytes the last run left | +//! | `render` | run the generators (in memory) | +//! | `write` | write only files whose bytes changed; save the manifest once; store the key | +//! +//! A run that skips records `load`, `plan` and `skip` only: it renders nothing and writes +//! nothing, not even the manifest or the stored key (ADR-0064). + +use std::collections::{BTreeMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use metaobjects::errors::MetaError; +use metaobjects::sources::{CONFIG_FILE, DEFAULT_METAOBJECTS_DIR}; +use metaobjects::timing::LoadTimings; + +use crate::fingerprint::{ + self, ABSENT, InputEntry, KIND_CONFIG, KIND_ENGINE, KIND_EXTRA, KIND_FLAG, KIND_GENERATOR, + KIND_MODEL, KIND_TOOL, build_model_tree, fold, hash_file, hash_tree, +}; +use crate::generator::{ + ERR_OUT_DIR, ERR_PATH_COLLISION, EmittedFile, GenContext, GenError, Generator, +}; +use crate::hashes::{HashManifest, content_hash}; +use crate::project::load_project; +use crate::sha256::sha256_hex; + +pub const STAGE_LOAD: &str = "load"; +pub const STAGE_PLAN: &str = "plan"; +pub const STAGE_SKIP: &str = "skip"; +pub const STAGE_RENDER: &str = "render"; +pub const STAGE_WRITE: &str = "write"; + +/// The gen-state directory beneath a project's `.metaobjects`. +pub const GEN_STATE_DIR: &str = ".gen-state"; + +/// The hash of this engine's own sources and the loader's, taken when it was built. +pub const ENGINE_SOURCE_HASH: &str = env!("METAOBJECTS_ENGINE_SOURCE_HASH"); + +/// What one run was asked to do. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RunOptions { + /// Where project discovery starts (the nearest `.metaobjects/config.json` upward). + pub start_dir: PathBuf, + /// A project root named outright (`--project`), skipping discovery. + pub project_dir: Option, + /// The output directory, relative to the project root unless absolute; it must lie + /// inside the project. + pub out_dir: PathBuf, + /// Render even when the skip key matches (`--force`). + pub force: bool, + /// Load strictly (ADR-0023). + pub strict: bool, + /// Object names the run is limited to. Such a run never skips and never stores a key. + pub entities: Vec, + /// Generator names to run; `None` runs them all. + pub generators: Option>, +} + +impl RunOptions { + pub fn new(start_dir: impl Into) -> Self { + Self { + start_dir: start_dir.into(), + project_dir: None, + out_dir: PathBuf::from("generated"), + force: false, + strict: false, + entities: Vec::new(), + generators: None, + } + } +} + +/// How the run ended, when it did not fail. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Outcome { + /// The skip key matched: nothing was rendered or written. + Skipped, + /// The generators ran and the files were reconciled with disk. + Generated, +} + +/// What a run did to each file. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct FileCounts { + /// Files that did not exist before. + pub created: usize, + /// Files whose bytes changed. + pub overwritten: usize, + /// Files whose fresh bytes equal what is on disk, left untouched. + pub unchanged: usize, + /// Generated files no longer emitted, removed. + pub removed: usize, +} + +/// The result of a run that did not fail. +#[derive(Debug, Clone)] +pub struct RunReport { + pub outcome: Outcome, + /// `load`, `plan`, `skip`, `render`, `write`, in the order they ran. + pub timings: LoadTimings, + /// The load's own phases and validation passes. + pub load_timings: LoadTimings, + pub files: FileCounts, + /// Whether the manifest was rewritten. + pub manifest_written: bool, + /// Why the run did not skip, when it did not. + pub no_skip_reason: Option<&'static str>, + /// Warnings from the load, the config and the run. + pub warnings: Vec, + /// The project root the run used. + pub project_root: PathBuf, +} + +/// Why a run failed. +#[derive(Debug)] +pub enum RunError { + /// The project did not resolve or the model did not load. + Load(Vec), + /// A generator failed. + Generator(GenError), + /// Existing files are not what a previous run left (hand-edited, or unrecorded), so + /// they were left alone. The rest of the run completed. + Refused(Vec), + /// A file could not be read or written. + Io(String), +} + +impl std::fmt::Display for RunError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + RunError::Load(errors) => { + for (i, e) in errors.iter().enumerate() { + if i > 0 { + writeln!(f)?; + } + write!(f, "{e}")?; + } + Ok(()) + } + RunError::Generator(e) => write!(f, "{e}"), + RunError::Refused(paths) => write!( + f, + "refused to overwrite {} file(s) that differ from what the last run wrote \ + (edited by hand, or not recorded in {DEFAULT_METAOBJECTS_DIR}/{GEN_STATE_DIR}/.hashes.json): {}. \ + Restore them, or delete them to generate them afresh.", + paths.len(), + paths.join(", ") + ), + RunError::Io(m) => write!(f, "{m}"), + } + } +} + +impl std::error::Error for RunError {} + +fn rel_key(root: &Path, path: &Path) -> Option { + let rel = path.strip_prefix(root).ok()?; + Some( + rel.components() + .map(|c| c.as_os_str().to_string_lossy()) + .collect::>() + .join("/"), + ) +} + +/// Collapse `.` and `..` lexically (the out dir need not exist yet). +fn normalize(path: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for c in path.components() { + match c { + std::path::Component::ParentDir => { + out.pop(); + } + std::path::Component::CurDir => {} + other => out.push(other), + } + } + out +} + +fn io_error(what: &str, path: &Path, e: &std::io::Error) -> RunError { + RunError::Io(format!("{what} {}: {e}", path.display())) +} + +/// Run `generators` over the project: the whole pipeline. +pub fn run(opts: &RunOptions, generators: &[Box]) -> Result { + let mut timings = LoadTimings::default(); + + // load + let start = Instant::now(); + let loaded = load_project(&opts.start_dir, opts.project_dir.as_deref(), opts.strict) + .map_err(RunError::Load)?; + timings.add_phase(STAGE_LOAD, start.elapsed()); + let project_root = loaded.collection.config_dir.clone(); + let mut warnings = loaded.collection.warnings.clone(); + warnings.extend(loaded.result.warnings.iter().map(ToString::to_string)); + let load_timings = loaded.result.timings.clone(); + + // plan + let start = Instant::now(); + let selected: Vec<&dyn Generator> = match &opts.generators { + None => generators.iter().map(AsRef::as_ref).collect(), + Some(names) => generators + .iter() + .map(AsRef::as_ref) + .filter(|g| names.iter().any(|n| n == g.name())) + .collect(), + }; + let out_dir = normalize(&if opts.out_dir.is_absolute() { + opts.out_dir.clone() + } else { + project_root.join(&opts.out_dir) + }); + let out_rel = rel_key(&normalize(&project_root), &out_dir).ok_or_else(|| { + RunError::Generator(GenError::new( + ERR_OUT_DIR, + format!( + "the output directory {} is outside the project {}; the hash manifest keys every file by its path from the project root", + out_dir.display(), + project_root.display() + ), + )) + })?; + let gen_state = project_root + .join(DEFAULT_METAOBJECTS_DIR) + .join(GEN_STATE_DIR); + let mut manifest = HashManifest::load(&gen_state); + let model = build_model_tree(&loaded.result.tree, loaded.result.root); + let cacheable = selected.iter().all(|g| g.cacheable()); + let mut entries = vec![ + InputEntry::new( + KIND_TOOL, + "fingerprint-format", + fingerprint::FINGERPRINT_FORMAT.to_string(), + ), + InputEntry::new(KIND_TOOL, "engine-version", env!("CARGO_PKG_VERSION")), + InputEntry::new(KIND_ENGINE, "metaobjects-codegen", ENGINE_SOURCE_HASH), + InputEntry::new( + KIND_CONFIG, + "project-config", + hash_file(&project_root.join(DEFAULT_METAOBJECTS_DIR).join(CONFIG_FILE)), + ), + InputEntry::new(KIND_MODEL, "model", model.model.clone()), + InputEntry::new(KIND_FLAG, "out", out_rel.clone()), + InputEntry::new(KIND_FLAG, "strict", opts.strict.to_string()), + ]; + let mut names: Vec<&str> = selected.iter().map(|g| g.name()).collect(); + names.sort_unstable(); + entries.push(InputEntry::new(KIND_FLAG, "generators", names.join(","))); + for g in &selected { + entries.push(InputEntry::new( + KIND_GENERATOR, + g.name(), + sha256_hex(g.identity().as_bytes()), + )); + for extra in g.extra_inputs() { + let digest = hash_tree(&project_root.join(&extra)); + entries.push(InputEntry::new(KIND_EXTRA, extra, digest)); + } + } + let key = fold(&entries); + let stored = fingerprint::read_stored(&gen_state); + timings.add_phase(STAGE_PLAN, start.elapsed()); + + // skip + let named = !opts.entities.is_empty(); + let no_skip_reason = if opts.force { + Some("--force") + } else if named { + Some("entities were named") + } else if !cacheable { + Some("a generator is not cacheable") + } else { + match &stored { + None => Some("no stored key"), + Some(s) if s.key != key => Some("an input changed"), + Some(_) => None, + } + }; + let mut no_skip_reason = no_skip_reason; + if no_skip_reason.is_none() { + let start = Instant::now(); + let unchanged = stored.as_ref().is_some_and(|s| { + fingerprint::output_hashes(&manifest, &project_root).as_ref() == Some(&s.outputs) + }); + timings.add_phase(STAGE_SKIP, start.elapsed()); + if unchanged { + return Ok(RunReport { + outcome: Outcome::Skipped, + timings, + load_timings, + files: FileCounts::default(), + manifest_written: false, + no_skip_reason: None, + warnings, + project_root, + }); + } + no_skip_reason = Some("a generated file changed or is missing"); + } + + // A run that goes on to write deletes the stored key first, so a failed or half-written + // run is never mistaken for a current one. A named run leaves the full-run key alone. + if !named { + fingerprint::delete_stored(&gen_state); + } + + // render + let start = Instant::now(); + let ctx = GenContext { + tree: &loaded.result.tree, + root: loaded.result.root, + entities: &opts.entities, + }; + let mut emitted: Vec = Vec::new(); + for g in &selected { + emitted.extend(g.generate(&ctx).map_err(RunError::Generator)?); + } + timings.add_phase(STAGE_RENDER, start.elapsed()); + + // write + let start = Instant::now(); + let mut seen: HashSet<&str> = HashSet::with_capacity(emitted.len()); + for f in &emitted { + if !seen.insert(f.path.as_str()) { + return Err(RunError::Generator(GenError::new( + ERR_PATH_COLLISION, + format!("two generated files claim the path {}", f.path), + ))); + } + } + let mut files = FileCounts::default(); + let mut refused: Vec = Vec::new(); + let mut known_dirs: HashSet = HashSet::new(); + let mut written_hashes: BTreeMap = BTreeMap::new(); + for f in &emitted { + let key = if out_rel.is_empty() { + f.path.clone() + } else { + format!("{out_rel}/{}", f.path) + }; + let path = project_root.join(&key); + let fresh_hash = content_hash(&f.content); + match std::fs::read(&path) { + Ok(disk) if disk == f.content.as_bytes() => { + files.unchanged += 1; + manifest.record(&key, &fresh_hash); + } + Ok(disk) => { + let disk_hash = sha256_hex(&disk); + if manifest.hash_of(&key) == Some(disk_hash.as_str()) { + std::fs::write(&path, &f.content) + .map_err(|e| io_error("writing", &path, &e))?; + files.overwritten += 1; + manifest.record(&key, &fresh_hash); + } else { + refused.push(key.clone()); + continue; + } + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + if let Some(dir) = path.parent() + && known_dirs.insert(dir.to_path_buf()) + { + std::fs::create_dir_all(dir).map_err(|e| io_error("creating", dir, &e))?; + } + std::fs::write(&path, &f.content).map_err(|e| io_error("writing", &path, &e))?; + files.created += 1; + manifest.record(&key, &fresh_hash); + } + Err(e) => return Err(io_error("reading", &path, &e)), + } + written_hashes.insert(key, fresh_hash); + } + + // Generated files this run no longer emits (a package that went away) are removed when + // they are still exactly what a run wrote; one with an edit is kept and reported. A run + // limited to some generators (or some objects) cannot tell a file nobody emits any more + // from a file another generator emits, so it sweeps nothing. + if !named && opts.generators.is_none() { + let prefix = if out_rel.is_empty() { + String::new() + } else { + format!("{out_rel}/") + }; + let stale: Vec<(String, String)> = manifest + .records() + .filter(|(k, _)| k.starts_with(&prefix) && !written_hashes.contains_key(*k)) + .map(|(k, h)| (k.to_string(), h.to_string())) + .collect(); + for (key, recorded) in stale { + let path = project_root.join(&key); + match std::fs::read(&path) { + Ok(disk) if sha256_hex(&disk) == recorded => { + std::fs::remove_file(&path).map_err(|e| io_error("removing", &path, &e))?; + remove_empty_parents(&path, &out_dir); + manifest.remove(&key); + files.removed += 1; + } + Ok(_) => warnings.push(format!( + "{key} is no longer generated but differs from what the last run wrote, so it was kept" + )), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => manifest.remove(&key), + Err(e) => return Err(io_error("reading", &path, &e)), + } + } + } + + // The manifest is written once, and only when a record changed. It is written even when a + // file was refused: every record in it is on disk. + let manifest_written = manifest + .save() + .map_err(|e| io_error("writing", &gen_state.join(".hashes.json"), &e))?; + if !refused.is_empty() { + return Err(RunError::Refused(refused)); + } + + // Store the key only for a full run, with every generator cacheable. + if !named && cacheable { + let mut outputs: BTreeMap = BTreeMap::new(); + for (key, _) in manifest.records() { + let digest = match written_hashes.get(key) { + Some(h) => h.clone(), + None => std::fs::read(project_root.join(key)) + .map(|b| sha256_hex(&b)) + .unwrap_or_else(|_| ABSENT.to_string()), + }; + outputs.insert(key.to_string(), digest); + } + fingerprint::write_stored(&gen_state, &key, &outputs) + .map_err(|e| io_error("writing", &gen_state, &e))?; + } + timings.add_phase(STAGE_WRITE, start.elapsed()); + + Ok(RunReport { + outcome: Outcome::Generated, + timings, + load_timings, + files, + manifest_written, + no_skip_reason, + warnings, + project_root, + }) +} + +/// Remove the now-empty directories above `path`, stopping at (and keeping) `stop`. +fn remove_empty_parents(path: &Path, stop: &Path) { + let mut cur = path.parent(); + while let Some(dir) = cur { + if dir == stop || !dir.starts_with(stop) { + break; + } + if std::fs::remove_dir(dir).is_err() { + break; + } + cur = dir.parent(); + } +} diff --git a/server/rust/metaobjects-codegen/src/entity.rs b/server/rust/metaobjects-codegen/src/entity.rs new file mode 100644 index 0000000000..3688c53200 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/entity.rs @@ -0,0 +1,956 @@ +//! The `entity` generator: serde structs, enums and value objects, one crate per package. +//! +//! ADR-0065 maps a metadata package to a Cargo crate, because a crate is Rust's unit of +//! compilation and visibility. For the package `acme::billing` the generator writes: +//! +//! ```text +//! /acme_billing/Cargo.toml the crate (serde, plus one path dependency per package it refers to) +//! /acme_billing/rustfmt.toml pins the formatting the files are written in +//! /acme_billing/src/lib.rs one `mod` per type and a `pub use` of each type +//! /acme_billing/src/.rs one struct (and the enums its fields declare) per file +//! ``` +//! +//! What becomes what: +//! +//! - a concrete `object.entity` or `object.value` becomes a `pub struct` with every +//! EFFECTIVE field, so a field inherited through `extends` is a field of the struct; +//! - a `field.enum` becomes a `pub enum` whose variants serialize as the member symbols +//! (the wire form stays the symbol, as in every port). An enum declared on a field is +//! named ``; a shared enum (a root-level abstract `field.enum` that fields +//! reach through `extends`) is one enum in its own file, named after the declaration; +//! - a field that is not `@required` (and is not part of the primary identity) is an +//! `Option`; an array is a `Vec`; a `field.map` is a `BTreeMap`; +//! - a `field.object` is the struct its `@objectRef` names, `Box`ed when the reference +//! closes a cycle of by-value containment, and a reference into another package is a path +//! dependency on that package's crate. +//! +//! Types the standard library has no counterpart for stay textual, as they are on the wire: +//! `decimal`, `date`, `time`, `timestamp`, `uuid`, `uri` and `duration` are `String` (a +//! decimal is a string precisely so it never passes through a float), `currency` is `i64` +//! minor units, and `inet` is `std::net::IpAddr`. Navigation across relationships is not +//! generated: a relationship is not a field, and the foreign-key fields it is built on are. +//! +//! The output is already formatted (ADR-0063: no formatter runs in the generation path), and +//! each crate carries the `rustfmt.toml` its text was written under, so `cargo fmt` over the +//! output changes nothing and never makes a later run refuse a file. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; + +use metaobjects::node::{NodeId, PACKAGE_SEP, Tree}; +use serde_json::Value; + +use crate::generator::{ + ERR_CRATE_CYCLE, ERR_NAME_COLLISION, ERR_UNSUPPORTED, EmittedFile, GenContext, GenError, + Generator, +}; +use crate::names::{ + PRELUDE_TYPES, crate_name, doc_comment, field_ident, literal, module_name, pascal, type_ident, +}; + +/// 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 entity generator. Do not edit: change the model and run `cargo meta gen`.\n"; + +const MAX_WIDTH: usize = 100; + +const RUSTFMT_TOML: &str = "# @generated by the MetaObjects entity generator.\n\ +# The generated files are written in rustfmt's output form under these settings; they pin\n\ +# that form, so `cargo fmt` over the output changes nothing.\n\ +max_width = 100\n\ +reorder_imports = false\n\ +reorder_modules = false\n"; + +/// The entity generator. +#[derive(Debug, Clone, Copy, Default)] +pub struct EntityGenerator; + +impl Generator for EntityGenerator { + fn name(&self) -> &str { + "entity" + } + + fn identity(&self) -> String { + format!("entity:{FORMAT}") + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + let plan = Plan::build(ctx.tree, ctx.root)?; + plan.emit(ctx.entities) + } +} + +// ---- the plan -------------------------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Eq)] +struct TypeRef { + crate_name: String, + type_name: String, +} + +#[derive(Debug, Clone)] +enum Ty { + Str, + Prim(&'static str), + Ip, + Ref(TypeRef), + Map(Box), +} + +#[derive(Debug)] +struct Member { + variant: String, + wire: String, +} + +#[derive(Debug)] +struct EnumPlan { + type_name: String, + doc: Option, + members: Vec, +} + +#[derive(Debug)] +struct FieldPlan { + wire: String, + ident: String, + ty: Ty, + array: bool, + optional: bool, + boxed: bool, + doc: Option, +} + +#[derive(Debug)] +struct StructPlan { + node: NodeId, + key: String, + crate_name: String, + type_name: String, + doc: Option, + fields: Vec, + enums: Vec, +} + +#[derive(Debug, Default)] +struct CratePlan { + package: String, + structs: Vec, + shared_enums: Vec<(NodeId, EnumPlan)>, + deps: BTreeSet, +} + +struct Plan { + structs: Vec, + crates: BTreeMap, +} + +fn unsupported(msg: String) -> GenError { + GenError::new(ERR_UNSUPPORTED, msg) +} + +fn str_attr<'t>(tree: &'t Tree, id: NodeId, name: &str) -> Option<&'t str> { + tree.attr(id, name).and_then(Value::as_str) +} + +fn bool_attr(tree: &Tree, id: NodeId, name: &str) -> bool { + tree.attr(id, name).and_then(Value::as_bool) == Some(true) +} + +fn enum_members(tree: &Tree, field: NodeId, what: &str) -> Result, GenError> { + let values = tree + .attr(field, "values") + .and_then(Value::as_array) + .ok_or_else(|| unsupported(format!("{what} is a field.enum with no @values")))?; + Ok(values + .iter() + .map(|v| v.as_str().map_or_else(|| v.to_string(), str::to_string)) + .collect()) +} + +fn plan_enum( + type_name: &str, + symbols: &[String], + doc: Option, +) -> Result { + let mut seen: HashMap = HashMap::new(); + let mut members = Vec::with_capacity(symbols.len()); + for s in symbols { + let variant = type_ident(s); + if let Some(other) = seen.insert(variant.clone(), s) { + return Err(GenError::new( + ERR_NAME_COLLISION, + format!( + "enum {type_name}: the members '{other}' and '{s}' both become the Rust variant {variant}" + ), + )); + } + members.push(Member { + variant, + wire: s.clone(), + }); + } + Ok(EnumPlan { + type_name: type_name.to_string(), + doc, + members, + }) +} + +/// The root-level abstract `field.enum` a field resolves to through `extends`, if any +/// (ADR-0026 Amendment 1; the walk the TypeScript `resolveSharedEnumDeclaration` makes). +fn shared_enum_declaration(tree: &Tree, root: NodeId, field: NodeId) -> Option { + let mut seen = HashSet::new(); + let mut cur = Some(field); + while let Some(n) = cur { + let node = tree.node(n); + if node.type_name != "field" || node.sub_type != "enum" || !seen.insert(n) { + return None; + } + if node.is_abstract && node.parent == Some(root) { + return Some(n); + } + // ADR-0039 sanctioned own: the question is whether THIS node redeclares the + // vocabulary; a resolving read would see the inherited @values on every hop. + if tree.own_attr(n, "values").is_some() || tree.own_attr(n, "intValueMap").is_some() { + return None; + } + cur = node.super_node; + } + None +} + +fn scalar(sub_type: &str) -> Option { + Some(match sub_type { + "string" | "decimal" | "date" | "time" | "timestamp" | "uuid" | "uri" | "duration" => { + Ty::Str + } + "int" => Ty::Prim("i32"), + "long" | "currency" => Ty::Prim("i64"), + "double" => Ty::Prim("f64"), + "float" => Ty::Prim("f32"), + "boolean" => Ty::Prim("bool"), + "inet" => Ty::Ip, + _ => return None, + }) +} + +impl Plan { + fn build(tree: &Tree, root: NodeId) -> Result { + // Every concrete entity and value object, in model order. + let mut structs: Vec = Vec::new(); + let mut by_key: HashMap = HashMap::new(); + for &id in tree.own_children(root) { + let n = tree.node(id); + if n.type_name != "object" + || !matches!(n.sub_type.as_str(), "entity" | "value") + || n.is_abstract + { + continue; + } + let pkg = tree.effective_package(id); + by_key.insert(tree.resolution_key(id), structs.len()); + structs.push(StructPlan { + node: id, + key: tree.resolution_key(id), + crate_name: crate_name(&pkg), + type_name: type_ident(&n.name), + doc: str_attr(tree, id, "description").map(str::to_string), + fields: Vec::new(), + enums: Vec::new(), + }); + } + + let mut crates: BTreeMap = BTreeMap::new(); + for (i, s) in structs.iter().enumerate() { + let pkg = tree.effective_package(s.node); + let c = crates.entry(s.crate_name.clone()).or_default(); + if c.structs.is_empty() { + c.package = pkg.clone(); + } else if c.package != pkg { + return Err(GenError::new( + ERR_NAME_COLLISION, + format!( + "the packages '{}' and '{}' both become the crate {}", + c.package, pkg, s.crate_name + ), + )); + } + c.structs.push(i); + } + + // Fields. + let mut shared: BTreeMap = BTreeMap::new(); + for i in 0..structs.len() { + let (node, owner_crate, owner_type, owner_key) = { + let s = &structs[i]; + ( + s.node, + s.crate_name.clone(), + s.type_name.clone(), + s.key.clone(), + ) + }; + let primary: HashSet = tree + .children(node) + .iter() + .filter(|&&c| { + let n = tree.node(c); + n.type_name == "identity" && n.sub_type == "primary" + }) + .filter_map(|&c| tree.attr(c, "fields").and_then(Value::as_array)) + .flat_map(|a| a.iter().filter_map(Value::as_str).map(str::to_string)) + .collect(); + let owner_pkg = tree.effective_package(node); + let mut fields: Vec = Vec::new(); + let mut enums: Vec = Vec::new(); + for &f in tree.children(node).iter() { + let fnode = tree.node(f); + if fnode.type_name != "field" { + continue; + } + let what = format!("{owner_key}.{}", fnode.name); + let array = tree.resolved_is_array(f); + let mut boxed = false; + let ty = match fnode.sub_type.as_str() { + "enum" => { + if let Some(decl) = shared_enum_declaration(tree, root, f) { + if str_attr_own_true(tree, decl, "provided") { + return Err(unsupported(format!( + "{what} uses the @provided enum {}: the Rust generator has no setting for where a hand-written enum lives yet", + tree.node(decl).name + ))); + } + let target = shared.entry(decl).or_insert_with(|| TypeRef { + crate_name: crate_name(&tree.effective_package(decl)), + type_name: type_ident(&tree.node(decl).name), + }); + Ty::Ref(target.clone()) + } else { + let symbols = enum_members(tree, f, &what)?; + let name = format!("{owner_type}{}", pascal(&fnode.name)); + let doc = str_attr(tree, f, "description").map(str::to_string); + enums.push(plan_enum(&name, &symbols, doc)?); + Ty::Ref(TypeRef { + crate_name: owner_crate.clone(), + type_name: name, + }) + } + } + "object" => match str_attr(tree, f, "objectRef") { + // The loader refuses a field.object without an @objectRef + // (ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF), so none reaches here. + None => { + return Err(unsupported(format!( + "{what} is a field.object with no @objectRef" + ))); + } + Some(r) => { + let target = resolve_object_ref(&structs, &by_key, r, &owner_pkg) + .ok_or_else(|| { + unsupported(format!( + "{what} refers to {r}, which is not a concrete entity or value object the entity generator emits" + )) + })?; + boxed = !array; + Ty::Ref(TypeRef { + crate_name: structs[target].crate_name.clone(), + type_name: structs[target].type_name.clone(), + }) + } + }, + "map" => { + let value = if let Some(r) = str_attr(tree, f, "objectRef") { + let target = resolve_object_ref(&structs, &by_key, r, &owner_pkg) + .ok_or_else(|| { + unsupported(format!( + "{what} is a map of {r}, which is not a concrete entity or value object the entity generator emits" + )) + })?; + Ty::Ref(TypeRef { + crate_name: structs[target].crate_name.clone(), + type_name: structs[target].type_name.clone(), + }) + } else { + let vt = str_attr(tree, f, "valueType").unwrap_or("string"); + scalar(vt).ok_or_else(|| { + unsupported(format!( + "{what} is a map with the unsupported @valueType {vt}" + )) + })? + }; + Ty::Map(Box::new(value)) + } + other => scalar(other).ok_or_else(|| { + unsupported(format!( + "{what} has the field subtype {other}, which has no Rust mapping" + )) + })?, + }; + // A map is one value, never wrapped in a Vec. + let array = array && !matches!(ty, Ty::Map(_)); + let optional = !(bool_attr(tree, f, "required") || primary.contains(&fnode.name)); + fields.push(FieldPlan { + wire: fnode.name.clone(), + ident: field_ident(&fnode.name), + ty, + array, + optional, + boxed, + doc: str_attr(tree, f, "description").map(str::to_string), + }); + } + check_fields(&owner_key, &fields)?; + structs[i].fields = fields; + structs[i].enums = enums; + } + + // Shared enums are materialized once, in their declaration's package, and only when a + // field consumes them. + for (&decl, target) in &shared { + let symbols = enum_members(tree, decl, &tree.resolution_key(decl))?; + let plan = plan_enum( + &target.type_name, + &symbols, + str_attr(tree, decl, "description").map(str::to_string), + )?; + let pkg = tree.effective_package(decl); + let c = crates.entry(target.crate_name.clone()).or_default(); + if c.package.is_empty() && c.structs.is_empty() && c.shared_enums.is_empty() { + c.package = pkg; + } + c.shared_enums.push((decl, plan)); + } + + let mut plan = Plan { structs, crates }; + plan.link_dependencies(); + plan.check_names()?; + plan.check_cycles()?; + plan.box_cycles(); + Ok(plan) + } + + /// Every reference into another crate is a path dependency on it. + fn link_dependencies(&mut self) { + let mut edges: Vec<(String, String)> = Vec::new(); + for s in &self.structs { + for f in &s.fields { + if let Some(t) = ty_ref(&f.ty) + && t.crate_name != s.crate_name + { + edges.push((s.crate_name.clone(), t.crate_name.clone())); + } + } + } + for (from, to) in edges { + self.crates.get_mut(&from).expect("crate").deps.insert(to); + } + } + + /// Two types of one crate must not share a Rust name or a module name. + fn check_names(&self) -> Result<(), GenError> { + for (cname, c) in &self.crates { + let mut types: BTreeMap = BTreeMap::new(); + let mut modules: BTreeMap = BTreeMap::new(); + let mut claim = |ty: &str, origin: String, module: Option| { + if let Some(prev) = types.insert(ty.to_string(), origin.clone()) { + return Err(GenError::new( + ERR_NAME_COLLISION, + format!("crate {cname}: {origin} and {prev} are both named {ty}"), + )); + } + if let Some(m) = module + && let Some(prev) = modules.insert(m.clone(), origin.clone()) + { + return Err(GenError::new( + ERR_NAME_COLLISION, + format!("crate {cname}: {origin} and {prev} both become the module {m}"), + )); + } + Ok(()) + }; + for &i in &c.structs { + let s = &self.structs[i]; + claim(&s.type_name, s.key.clone(), Some(module_name(&s.type_name)))?; + for e in &s.enums { + claim(&e.type_name, format!("the enum {}", e.type_name), None)?; + } + } + for (decl, e) in &c.shared_enums { + claim( + &e.type_name, + format!("the shared enum declaration #{}", decl.index()), + Some(module_name(&e.type_name)), + )?; + } + } + Ok(()) + } + + /// Cargo refuses cyclic path dependencies, so two packages that refer to each other + /// cannot become two crates. + fn check_cycles(&self) -> Result<(), GenError> { + #[derive(Clone, Copy, PartialEq)] + enum Mark { + Open, + Done, + } + fn visit<'a>( + name: &'a str, + crates: &'a BTreeMap, + marks: &mut HashMap<&'a str, Mark>, + path: &mut Vec<&'a str>, + ) -> Option> { + match marks.get(name) { + Some(Mark::Done) => return None, + Some(Mark::Open) => { + let start = path.iter().position(|p| *p == name).unwrap_or(0); + let mut cycle: Vec = + path[start..].iter().map(|s| s.to_string()).collect(); + cycle.push(name.to_string()); + return Some(cycle); + } + None => {} + } + marks.insert(name, Mark::Open); + path.push(name); + if let Some(c) = crates.get(name) { + for dep in &c.deps { + if let Some(cycle) = visit(dep, crates, marks, path) { + return Some(cycle); + } + } + } + path.pop(); + marks.insert(name, Mark::Done); + None + } + let mut marks = HashMap::new(); + for name in self.crates.keys() { + if let Some(cycle) = visit(name, &self.crates, &mut marks, &mut Vec::new()) { + return Err(GenError::new( + ERR_CRATE_CYCLE, + format!( + "these packages refer to each other, so their crates would depend on each other, which Cargo refuses: {}", + cycle.join(" -> ") + ), + )); + } + } + Ok(()) + } + + /// A struct that contains itself by value, directly or through others, has no size. + /// Every by-value containment edge that lies inside a cycle goes through a `Box`. + fn box_cycles(&mut self) { + let index: HashMap<(&str, &str), usize> = self + .structs + .iter() + .enumerate() + .map(|(i, s)| ((s.crate_name.as_str(), s.type_name.as_str()), i)) + .collect(); + let edges: Vec> = self + .structs + .iter() + .map(|s| { + s.fields + .iter() + .enumerate() + .filter(|(_, f)| f.boxed) + .filter_map(|(fi, f)| { + let t = ty_ref(&f.ty)?; + let target = *index.get(&(t.crate_name.as_str(), t.type_name.as_str()))?; + Some((fi, target)) + }) + .collect() + }) + .collect(); + let adjacency: Vec> = edges + .iter() + .map(|e| e.iter().map(|&(_, t)| t).collect()) + .collect(); + let component = strongly_connected(&adjacency); + let mut cyclic: Vec<(usize, usize)> = Vec::new(); + for (si, list) in edges.iter().enumerate() { + for &(fi, target) in list { + if component[si] == component[target] { + cyclic.push((si, fi)); + } + } + } + for s in &mut self.structs { + for f in &mut s.fields { + f.boxed = false; + } + } + for (si, fi) in cyclic { + self.structs[si].fields[fi].boxed = true; + } + } + + fn emit(&self, entities: &[String]) -> Result, GenError> { + let selected: Option> = if entities.is_empty() { + None + } else { + let mut picked = HashSet::new(); + for name in entities { + let hit = self.structs.iter().position(|s| { + s.key == *name || s.key.rsplit(PACKAGE_SEP).next() == Some(name.as_str()) + }); + match hit { + Some(i) => { + picked.insert(i); + } + None => { + return Err(GenError::new( + ERR_UNSUPPORTED, + format!("no entity or value object named {name}"), + )); + } + } + } + Some(picked) + }; + let mut files = Vec::new(); + for (cname, c) in &self.crates { + let crate_selected = selected + .as_ref() + .is_none_or(|sel| c.structs.iter().any(|i| sel.contains(i))); + if !crate_selected { + continue; + } + files.push(EmittedFile::new( + format!("{cname}/Cargo.toml"), + cargo_toml(cname, c), + )); + files.push(EmittedFile::new( + format!("{cname}/rustfmt.toml"), + RUSTFMT_TOML.to_string(), + )); + let shadowed: HashSet<&str> = c + .structs + .iter() + .map(|&i| self.structs[i].type_name.as_str()) + .chain( + c.structs + .iter() + .flat_map(|&i| self.structs[i].enums.iter().map(|e| e.type_name.as_str())), + ) + .chain(c.shared_enums.iter().map(|(_, e)| e.type_name.as_str())) + .filter(|n| PRELUDE_TYPES.contains(n)) + .collect(); + let q = Qualifier { shadowed }; + + let mut lib_items: Vec<(String, Vec)> = Vec::new(); + for &i in &c.structs { + let s = &self.structs[i]; + let module = module_name(&s.type_name); + let mut exports = vec![s.type_name.clone()]; + exports.extend(s.enums.iter().map(|e| e.type_name.clone())); + lib_items.push((module.clone(), exports)); + if selected.as_ref().is_none_or(|sel| sel.contains(&i)) { + files.push(EmittedFile::new( + format!("{cname}/src/{module}.rs"), + struct_file(s, cname, &q), + )); + } + } + for (_, e) in &c.shared_enums { + let module = module_name(&e.type_name); + lib_items.push((module.clone(), vec![e.type_name.clone()])); + if selected.is_none() { + files.push(EmittedFile::new( + format!("{cname}/src/{module}.rs"), + enum_file(e), + )); + } + } + lib_items.sort(); + files.push(EmittedFile::new( + format!("{cname}/src/lib.rs"), + lib_file(&c.package, &lib_items), + )); + } + Ok(files) + } +} + +fn str_attr_own_true(tree: &Tree, id: NodeId, name: &str) -> bool { + // ADR-0039 sanctioned own: `@provided` marks THIS declaration as supplied by hand-written + // code, like `abstract`; it does not flow down an extends chain. + tree.own_attr(id, name).and_then(|a| a.value.as_bool()) == Some(true) +} + +fn ty_ref(ty: &Ty) -> Option<&TypeRef> { + match ty { + Ty::Ref(r) => Some(r), + Ty::Map(inner) => ty_ref(inner), + _ => None, + } +} + +/// The struct an `@objectRef` names: the canonical spelling is `pkg::Name`, or `::Name` for a +/// package-less target; a bare name is also tried in the referrer's own package. +fn resolve_object_ref( + structs: &[StructPlan], + by_key: &HashMap, + r: &str, + owner_pkg: &str, +) -> Option { + let _ = structs; + let bare = r.strip_prefix(PACKAGE_SEP).unwrap_or(r); + if let Some(&i) = by_key.get(bare) { + return Some(i); + } + if !owner_pkg.is_empty() + && let Some(&i) = by_key.get(&format!("{owner_pkg}{PACKAGE_SEP}{bare}")) + { + return Some(i); + } + None +} + +/// Two fields of one struct must not become one Rust field. +fn check_fields(owner: &str, fields: &[FieldPlan]) -> Result<(), GenError> { + let mut seen: HashMap<&str, &str> = HashMap::new(); + for f in fields { + let bare = f.ident.strip_prefix("r#").unwrap_or(&f.ident); + if let Some(prev) = seen.insert(bare, &f.wire) { + return Err(GenError::new( + ERR_NAME_COLLISION, + format!( + "{owner}: the fields '{prev}' and '{}' both become the Rust field {bare}", + f.wire + ), + )); + } + } + Ok(()) +} + +/// Tarjan's algorithm: the component number of every node. +fn strongly_connected(adjacency: &[Vec]) -> Vec { + struct State<'a> { + adjacency: &'a [Vec], + index: Vec>, + low: Vec, + on_stack: Vec, + stack: Vec, + next: usize, + component: Vec, + components: usize, + } + fn connect(s: &mut State<'_>, v: usize) { + s.index[v] = Some(s.next); + s.low[v] = s.next; + s.next += 1; + s.stack.push(v); + s.on_stack[v] = true; + for k in 0..s.adjacency[v].len() { + let w = s.adjacency[v][k]; + match s.index[w] { + None => { + connect(s, w); + s.low[v] = s.low[v].min(s.low[w]); + } + Some(wi) if s.on_stack[w] => s.low[v] = s.low[v].min(wi), + Some(_) => {} + } + } + if Some(s.low[v]) == s.index[v] { + while let Some(w) = s.stack.pop() { + s.on_stack[w] = false; + s.component[w] = s.components; + if w == v { + break; + } + } + s.components += 1; + } + } + let n = adjacency.len(); + let mut s = State { + adjacency, + index: vec![None; n], + low: vec![0; n], + on_stack: vec![false; n], + stack: Vec::new(), + next: 0, + component: vec![0; n], + components: 0, + }; + for v in 0..n { + if s.index[v].is_none() { + connect(&mut s, v); + } + } + s.component +} + +// ---- the text -------------------------------------------------------------------------- + +/// 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> { + shadowed: HashSet<&'a str>, +} + +impl Qualifier<'_> { + fn std(&self, short: &'static str, full: &'static str) -> &'static str { + if self.shadowed.contains(short) { + full + } else { + short + } + } +} + +fn render_ty(ty: &Ty, current: &str, q: &Qualifier<'_>) -> String { + match ty { + Ty::Str => q.std("String", "std::string::String").to_string(), + Ty::Prim(p) => (*p).to_string(), + Ty::Ip => "std::net::IpAddr".to_string(), + Ty::Ref(r) if r.crate_name == current => format!("crate::{}", r.type_name), + Ty::Ref(r) => format!("{}::{}", r.crate_name, r.type_name), + Ty::Map(v) => format!( + "std::collections::BTreeMap<{}, {}>", + q.std("String", "std::string::String"), + render_ty(v, current, q) + ), + } +} + +fn field_type_text(f: &FieldPlan, current: &str, q: &Qualifier<'_>) -> String { + let mut text = render_ty(&f.ty, current, q); + if f.boxed { + text = format!("{}<{text}>", q.std("Box", "std::boxed::Box")); + } + if f.array { + text = format!("{}<{text}>", q.std("Vec", "std::vec::Vec")); + } + if f.optional { + text = format!("{}<{text}>", q.std("Option", "std::option::Option")); + } + text +} + +fn cargo_toml(name: &str, c: &CratePlan) -> String { + let mut out = String::new(); + out.push_str("# @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`.\n"); + 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"); + if !c.package.is_empty() { + out.push_str(&format!( + "description = {}\n", + literal(&format!( + "Generated from the MetaObjects package {}.", + c.package + )) + )); + } + out.push_str("\n[dependencies]\n"); + out.push_str("serde = { version = \"1\", features = [\"derive\"] }\n"); + for dep in &c.deps { + out.push_str(&format!("{dep} = {{ path = \"../{dep}\" }}\n")); + } + out +} + +fn lib_file(package: &str, items: &[(String, Vec)]) -> String { + let mut out = String::from(BANNER); + out.push('\n'); + if package.is_empty() { + out.push_str("//! Generated from the MetaObjects model that declares no package.\n"); + } else { + out.push_str(&format!( + "//! Generated from the MetaObjects package `{package}`.\n" + )); + } + out.push('\n'); + for (module, _) in items { + out.push_str(&format!("mod {module};\n")); + } + out.push('\n'); + for (module, exports) in items { + for e in exports { + out.push_str(&format!("pub use {module}::{e};\n")); + } + } + out +} + +fn enum_text(e: &EnumPlan) -> String { + let mut out = String::new(); + if let Some(doc) = &e.doc { + out.push_str(&doc_comment(doc, "")); + } + out.push_str("#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]\n"); + out.push_str(&format!("pub enum {} {{\n", e.type_name)); + for m in &e.members { + if m.variant != m.wire { + out.push_str(&format!(" #[serde(rename = {})]\n", literal(&m.wire))); + } + out.push_str(&format!(" {},\n", m.variant)); + } + out.push_str("}\n\n"); + out.push_str(&format!("impl {} {{\n", e.type_name)); + out.push_str(" /// The wire spelling of the member.\n"); + out.push_str(" pub const fn as_str(self) -> &'static str {\n"); + out.push_str(" match self {\n"); + for m in &e.members { + out.push_str(&format!( + " {}::{} => {},\n", + e.type_name, + m.variant, + literal(&m.wire) + )); + } + out.push_str(" }\n }\n}\n"); + out +} + +fn enum_file(e: &EnumPlan) -> String { + format!("{BANNER}\n{}", enum_text(e)) +} + +fn struct_file(s: &StructPlan, current: &str, q: &Qualifier<'_>) -> String { + let mut out = String::from(BANNER); + out.push('\n'); + if let Some(doc) = &s.doc { + out.push_str(&doc_comment(doc, "")); + } + let mut body = String::new(); + let mut too_wide = false; + for f in &s.fields { + if let Some(doc) = &f.doc { + body.push_str(&doc_comment(doc, " ")); + } + let bare = f.ident.strip_prefix("r#").unwrap_or(&f.ident); + if bare != f.wire { + body.push_str(&format!(" #[serde(rename = {})]\n", literal(&f.wire))); + } + let line = format!(" pub {}: {},\n", f.ident, field_type_text(f, current, q)); + too_wide |= line.trim_end().chars().count() > MAX_WIDTH; + body.push_str(&line); + } + // A field line past the width is one rustfmt would break in a form this emitter does not + // reproduce, so such a struct is left as written. + if too_wide { + out.push_str("#[rustfmt::skip]\n"); + } + out.push_str("#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]\n"); + if s.fields.is_empty() { + out.push_str(&format!("pub struct {} {{}}\n", s.type_name)); + } else { + out.push_str(&format!("pub struct {} {{\n{body}}}\n", s.type_name)); + } + for e in &s.enums { + out.push('\n'); + out.push_str(&enum_text(e)); + } + out +} diff --git a/server/rust/metaobjects-codegen/src/fingerprint.rs b/server/rust/metaobjects-codegen/src/fingerprint.rs new file mode 100644 index 0000000000..463942f055 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/fingerprint.rs @@ -0,0 +1,253 @@ +//! The whole-run skip key (ADR-0064 section 3). +//! +//! `gen` loads the metadata, then computes ONE key from every input that can change what it +//! writes, and compares it with the one the last successful run stored in +//! `.metaobjects/.gen-state/.fingerprint-rust.json`. A match, with every file the manifest +//! records still on disk with the bytes that run left, skips the run: nothing renders and +//! nothing is written, the manifest and the stored key included. +//! +//! The key may be wrong only in the safe direction: an input it over-counts causes an extra +//! render; an input it misses would cause a wrong skip, so anything in doubt is counted. +//! Timestamps are never an input. +//! +//! The key is built from small named entries ([`InputEntry`]: a kind, a name and a content +//! hash) folded into one digest by [`fold`], so a later per-object key can reuse the same +//! entries for a subset of the inputs. Its bytes are internal to this port and are never +//! compared with another port's. + +use std::collections::BTreeMap; +use std::path::Path; + +use metaobjects::node::{NodeId, Tree}; +use metaobjects::serializer::to_canonical_value; +use serde_json::{Map, Value}; + +use crate::hashes::HashManifest; +use crate::sha256::{Sha256, hex, sha256_hex}; + +/// Bump when the key's own recipe changes: every stored key then misses. +pub const FINGERPRINT_FORMAT: u64 = 1; + +/// Where this port keeps its key, beside the (committed) manifest and never committed +/// itself (`.gen-state/*` is ignored except `.hashes.json`). +pub const FINGERPRINT_FILE: &str = ".fingerprint-rust.json"; + +/// The hash of an input that does not exist. A file that appears or disappears changes it. +pub const ABSENT: &str = "absent"; + +pub const KIND_TOOL: &str = "tool"; +pub const KIND_ENGINE: &str = "engine"; +pub const KIND_CONFIG: &str = "config"; +pub const KIND_MODEL: &str = "model"; +pub const KIND_FLAG: &str = "flag"; +pub const KIND_GENERATOR: &str = "generator"; +pub const KIND_EXTRA: &str = "extra"; + +/// One named input of the run: what kind it is, its name, and its content hash. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InputEntry { + pub kind: &'static str, + pub name: String, + pub sha256: String, +} + +impl InputEntry { + pub fn new(kind: &'static str, name: impl Into, sha256: impl Into) -> Self { + Self { + kind, + name: name.into(), + sha256: sha256.into(), + } + } +} + +/// The one key: a SHA-256 over the sorted entries. Order of arrival is irrelevant. +pub fn fold(entries: &[InputEntry]) -> String { + let mut lines: Vec = entries + .iter() + .map(|e| format!("{}\0{}\0{}", e.kind, e.name, e.sha256)) + .collect(); + lines.sort(); + sha256_hex(lines.join("\n").as_bytes()) +} + +/// The SHA-256 of a file's bytes, or [`ABSENT`]. Timestamps are never read. +pub fn hash_file(path: &Path) -> String { + match std::fs::read(path) { + Ok(bytes) => sha256_hex(&bytes), + Err(_) => ABSENT.to_string(), + } +} + +/// One hash over every file under `root` (relative path and content), or over the file +/// itself, or [`ABSENT`]. Adding, removing, renaming or editing any file changes it. +pub fn hash_tree(root: &Path) -> String { + if !root.exists() { + return ABSENT.to_string(); + } + if root.is_file() { + return hash_file(root); + } + fn walk(dir: &Path, out: &mut Vec) { + let Ok(read) = std::fs::read_dir(dir) else { + return; + }; + let mut entries: Vec<_> = read.filter_map(Result::ok).map(|e| e.path()).collect(); + entries.sort(); + for p in entries { + if p.is_dir() { + walk(&p, out); + } else { + out.push(p); + } + } + } + let mut files = Vec::new(); + walk(root, &mut files); + let mut h = Sha256::new(); + for f in files { + let rel = f.strip_prefix(root).unwrap_or(&f); + h.update(rel.to_string_lossy().replace('\\', "/").as_bytes()); + h.update(&[0]); + h.update(hash_file(&f).as_bytes()); + h.update(b"\n"); + } + hex(&h.finish()) +} + +/// The model half of the key: a hash tree over the LOADED root. +/// +/// Each root-level node (an object, a shared field, a template node) is hashed in its +/// canonical EFFECTIVE form (`extends` and overlays applied, attributes in fixed order, no +/// source positions). Node hashes roll up into one hash per package and one for the model. +/// Nothing here reads a metadata source file, so a file that is reformatted, reordered or +/// split in two without changing what loads does not change the key, and an edit to an +/// abstract parent changes the key of every node that inherits from it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ModelTree { + /// Resolution key to the hash of the node's canonical effective form. + pub nodes: BTreeMap, + /// Package to the hash over its sorted `resolution-key:node-hash` lines. + pub packages: BTreeMap, + /// The hash over the sorted `package:package-hash` lines. + pub model: String, +} + +fn node_hash(tree: &Tree, id: NodeId) -> String { + let mut value = to_canonical_value(tree, id, true); + // The RESOLVED package is part of the node's resolution key, so the node's own + // `package` attribute is dropped: moving a node to another file of the same package + // (which may or may not restate it) does not change the hash. + if let Value::Object(top) = &mut value { + for body in top.values_mut() { + if let Value::Object(b) = body { + b.shift_remove("package"); + } + } + } + sha256_hex(value.to_string().as_bytes()) +} + +/// Build the hash tree of the loaded root. +pub fn build_model_tree(tree: &Tree, root: NodeId) -> ModelTree { + // ADR-0039 sanctioned own: a top-level scan of the loader ROOT (`metadata.root` is never + // extended, so own == effective). + let mut nodes = BTreeMap::new(); + let mut by_package: BTreeMap> = BTreeMap::new(); + for &child in tree.own_children(root) { + let key = tree.resolution_key(child); + let digest = node_hash(tree, child); + by_package + .entry(tree.effective_package(child)) + .or_default() + .push(format!("{key}:{digest}")); + nodes.insert(key, digest); + } + let mut packages = BTreeMap::new(); + for (pkg, mut lines) in by_package { + lines.sort(); + packages.insert(pkg, sha256_hex(lines.join("\n").as_bytes())); + } + let model_lines: Vec = packages.iter().map(|(p, h)| format!("{p}:{h}")).collect(); + let model = sha256_hex(model_lines.join("\n").as_bytes()); + ModelTree { + nodes, + packages, + model, + } +} + +/// The key a previous successful run stored. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StoredFingerprint { + pub key: String, + /// Every manifest-recorded path (project-relative, as the manifest keys it) mapped to + /// the SHA-256 of the bytes on disk when the run finished. + pub outputs: BTreeMap, +} + +pub fn fingerprint_path(gen_state_dir: &Path) -> std::path::PathBuf { + gen_state_dir.join(FINGERPRINT_FILE) +} + +/// Read the stored key; anything unreadable or of another format is no key. +pub fn read_stored(gen_state_dir: &Path) -> Option { + let text = std::fs::read_to_string(fingerprint_path(gen_state_dir)).ok()?; + let raw: Value = serde_json::from_str(&text).ok()?; + let obj = raw.as_object()?; + if obj.get("format")?.as_u64()? != FINGERPRINT_FORMAT { + return None; + } + let key = obj.get("fingerprint")?.as_str()?.to_string(); + let mut outputs = BTreeMap::new(); + for (k, v) in obj.get("outputs")?.as_object()? { + outputs.insert(k.clone(), v.as_str()?.to_string()); + } + Some(StoredFingerprint { key, outputs }) +} + +/// Store the key of a run that succeeded with every generator cacheable. +pub fn write_stored( + gen_state_dir: &Path, + key: &str, + outputs: &BTreeMap, +) -> std::io::Result<()> { + std::fs::create_dir_all(gen_state_dir)?; + let mut out = Map::new(); + out.insert("format".into(), Value::from(FINGERPRINT_FORMAT)); + out.insert("fingerprint".into(), Value::from(key)); + out.insert("extras".into(), Value::Array(Vec::new())); + out.insert( + "outputs".into(), + Value::Object( + outputs + .iter() + .map(|(k, v)| (k.clone(), Value::from(v.clone()))) + .collect(), + ), + ); + out.insert("untracked".into(), Value::Array(Vec::new())); + let mut text = + serde_json::to_string_pretty(&Value::Object(out)).expect("a plain map serializes"); + text.push('\n'); + std::fs::write(fingerprint_path(gen_state_dir), text) +} + +/// Delete the stored key (a run does this before it writes anything). +pub fn delete_stored(gen_state_dir: &Path) { + let _ = std::fs::remove_file(fingerprint_path(gen_state_dir)); +} + +/// Every manifest-recorded path mapped to the SHA-256 of the bytes on disk now, or `None` +/// when any recorded file is missing (a skip then never matches). +pub fn output_hashes( + manifest: &HashManifest, + project_root: &Path, +) -> Option> { + let mut hashes = BTreeMap::new(); + for (key, _) in manifest.records() { + let bytes = std::fs::read(project_root.join(key)).ok()?; + hashes.insert(key.to_string(), sha256_hex(&bytes)); + } + Some(hashes) +} diff --git a/server/rust/metaobjects-codegen/src/generator.rs b/server/rust/metaobjects-codegen/src/generator.rs new file mode 100644 index 0000000000..18a3a33542 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/generator.rs @@ -0,0 +1,99 @@ +//! The generator contract: what a generator is handed, what it returns, and how it fails. +//! +//! A generator is a pure function of the loaded model: it returns the files it wants on +//! disk and writes nothing itself. The run engine owns reading and writing, so a file whose +//! bytes did not change is never rewritten and the manifest is saved once per run. + +use std::fmt; + +use metaobjects::node::{NodeId, Tree}; + +/// One generated file: its path relative to the output directory (always `/`-separated) +/// and its text. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EmittedFile { + pub path: String, + pub content: String, +} + +impl EmittedFile { + pub fn new(path: impl Into, content: impl Into) -> Self { + Self { + path: path.into(), + content: content.into(), + } + } +} + +/// What a generator reads: the loaded model and the run's entity selection. +#[derive(Debug, Clone, Copy)] +pub struct GenContext<'a> { + pub tree: &'a Tree, + pub root: NodeId, + /// Object names the run was limited to (`cargo meta gen A B`); empty means every object. + pub entities: &'a [String], +} + +/// A generator failed: a shared-style error code and a message for people. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GenError { + pub code: &'static str, + pub message: String, +} + +impl GenError { + pub fn new(code: &'static str, message: impl Into) -> Self { + Self { + code, + message: message.into(), + } + } +} + +impl fmt::Display for GenError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}: {}", self.code, self.message) + } +} + +impl std::error::Error for GenError {} + +/// Two types in one crate would take the same Rust name (or module name). +pub const ERR_NAME_COLLISION: &str = "ERR_NAME_COLLISION"; +/// Two generators (or two objects) claim one output path. +pub const ERR_PATH_COLLISION: &str = "ERR_PATH_COLLISION"; +/// A field or reference the generator cannot turn into Rust. +pub const ERR_UNSUPPORTED: &str = "ERR_RUST_UNSUPPORTED"; +/// Crate dependencies between packages form a cycle, which Cargo refuses. +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 code generator the run engine can drive. +pub trait Generator { + /// The name `--generators` selects it by. + fn name(&self) -> &str; + + /// Everything about this generator's own code and options that can change what it + /// emits. The engine already hashes its own built sources; a generator adds the options + /// it was constructed with. + fn identity(&self) -> String { + self.name().to_string() + } + + /// Whether a run that includes this generator may be skipped. A generator that reads + /// anything it cannot declare in [`Generator::extra_inputs`] returns `false`, and a run + /// that includes it never skips (ADR-0064 section 3). + fn cacheable(&self) -> bool { + true + } + + /// Project-relative paths of files this generator reads besides the model (a directory + /// is hashed whole). Their content is part of the skip key. + fn extra_inputs(&self) -> Vec { + Vec::new() + } + + /// Produce the generator's files for the loaded model. + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError>; +} diff --git a/server/rust/metaobjects-codegen/src/hashes.rs b/server/rust/metaobjects-codegen/src/hashes.rs new file mode 100644 index 0000000000..64ee6b3142 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/hashes.rs @@ -0,0 +1,231 @@ +//! The hash manifest: `.metaobjects/.gen-state/.hashes.json`, one SHA-256 per generated +//! path (ADR-0064 decision 1). +//! +//! The file is committed. It is the only thing that lets a machine that did not generate +//! the output tell "this is exactly what I wrote" from "somebody edited this". Every port +//! writes the same shape: keys are paths relative to the project root, sorted, two-space +//! indentation, a trailing newline; a value is the hex digest, or an object carrying a +//! `hash` field (owner fields other tools keep there are preserved). +//! +//! The manifest is read once at the start of a run, updated in memory, and saved once at +//! the end, and only when an entry was added, changed or removed. A run that changes nothing +//! leaves the file, and its timestamp, alone. + +use std::path::{Path, PathBuf}; + +use serde_json::{Map, Value}; + +use crate::sha256::sha256_hex; + +/// The manifest's file name inside the gen-state directory. +pub const HASHES_FILE: &str = ".hashes.json"; + +/// The hex SHA-256 of generated text: the function that produces every manifest value. +pub fn content_hash(content: &str) -> String { + sha256_hex(content.as_bytes()) +} + +fn entry_hash(value: &Value) -> Option<&str> { + match value { + Value::String(s) => Some(s), + Value::Object(o) => o.get("hash").and_then(Value::as_str), + _ => None, + } +} + +/// The manifest as one in-memory session. +#[derive(Debug)] +pub struct HashManifest { + path: PathBuf, + entries: Map, + existed: bool, + dirty: bool, +} + +impl HashManifest { + /// Read the manifest in `gen_state_dir`. A missing file is an empty manifest; an + /// unreadable or corrupt one reads as empty too, which fails closed: every existing + /// generated file is then refused rather than assumed ours. + pub fn load(gen_state_dir: &Path) -> Self { + let path = gen_state_dir.join(HASHES_FILE); + let text = std::fs::read_to_string(&path).ok(); + let parsed = text + .as_deref() + .and_then(|t| serde_json::from_str::(t).ok()); + let corrupt = text.is_some() && !matches!(parsed, Some(Value::Object(_))); + let entries = match parsed { + Some(Value::Object(map)) => map, + _ => Map::new(), + }; + // A corrupt file is present but unusable: the next save replaces it. + let existed = text.is_some(); + let dirty = corrupt; + Self { + path, + entries, + existed, + dirty, + } + } + + /// Whether the project had a manifest file at all. + pub fn existed(&self) -> bool { + self.existed + } + + /// The recorded hash for `key` (a project-relative path), if any. + pub fn hash_of(&self, key: &str) -> Option<&str> { + self.entries.get(key).and_then(entry_hash) + } + + /// Every recorded key with its hash, in key order. + pub fn records(&self) -> impl Iterator { + self.entries + .iter() + .filter_map(|(k, v)| Some((k.as_str(), entry_hash(v)?))) + } + + /// Record `hash` for `key`. A no-op, leaving the manifest clean, when it is already + /// recorded. + pub fn record(&mut self, key: &str, hash: &str) { + if self.hash_of(key) == Some(hash) { + return; + } + match self.entries.get_mut(key) { + Some(Value::Object(o)) => { + o.insert("hash".into(), Value::String(hash.into())); + } + _ => { + self.entries.insert(key.into(), Value::String(hash.into())); + } + } + self.dirty = true; + } + + /// Drop the record for `key`. + pub fn remove(&mut self, key: &str) { + if self.entries.shift_remove(key).is_some() { + self.dirty = true; + } + } + + /// Whether the in-memory manifest differs from what was loaded. + pub fn is_dirty(&self) -> bool { + self.dirty + } + + /// The manifest's text: keys sorted, two-space indent, trailing newline. + pub fn to_text(&self) -> String { + let mut keys: Vec<&String> = self.entries.keys().collect(); + keys.sort(); + let mut sorted = Map::new(); + for k in keys { + sorted.insert(k.clone(), self.entries[k].clone()); + } + let mut text = serde_json::to_string_pretty(&Value::Object(sorted)) + .expect("a map of strings serializes"); + text.push('\n'); + text + } + + /// Write the manifest once, and only when an entry changed. Returns whether it wrote. + pub fn save(&mut self) -> std::io::Result { + if !self.dirty { + return Ok(false); + } + if let Some(dir) = self.path.parent() { + std::fs::create_dir_all(dir)?; + } + std::fs::write(&self.path, self.to_text())?; + self.dirty = false; + self.existed = true; + Ok(true) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let base = std::env::var_os("DEV_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let dir = base.join(format!("mo-hashes-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn saves_sorted_with_a_trailing_newline_and_only_when_dirty() { + let dir = scratch("save"); + let mut m = HashManifest::load(&dir); + assert!(!m.existed()); + m.record("b/two.rs", "22"); + m.record("a/one.rs", "11"); + assert!(m.save().unwrap()); + let text = std::fs::read_to_string(dir.join(HASHES_FILE)).unwrap(); + assert_eq!( + text, + "{\n \"a/one.rs\": \"11\",\n \"b/two.rs\": \"22\"\n}\n" + ); + + let mut again = HashManifest::load(&dir); + again.record("a/one.rs", "11"); + assert!(!again.is_dirty()); + assert!( + !again.save().unwrap(), + "an unchanged manifest is not rewritten" + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn keeps_owner_fields_of_object_entries() { + let dir = scratch("owner"); + std::fs::write( + dir.join(HASHES_FILE), + "{\n \"x.rs\": { \"hash\": \"old\", \"generator\": \"entity\" }\n}\n", + ) + .unwrap(); + let mut m = HashManifest::load(&dir); + assert_eq!(m.hash_of("x.rs"), Some("old")); + m.record("x.rs", "new"); + m.save().unwrap(); + let text = std::fs::read_to_string(dir.join(HASHES_FILE)).unwrap(); + assert!(text.contains("\"generator\": \"entity\""), "{text}"); + assert!(text.contains("\"hash\": \"new\""), "{text}"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_corrupt_manifest_reads_empty_and_is_replaced_on_save() { + let dir = scratch("corrupt"); + std::fs::write(dir.join(HASHES_FILE), "not json").unwrap(); + let mut m = HashManifest::load(&dir); + assert!(m.existed()); + assert_eq!(m.records().count(), 0); + assert!(m.is_dirty()); + assert!(m.save().unwrap()); + assert_eq!( + std::fs::read_to_string(dir.join(HASHES_FILE)).unwrap(), + "{}\n" + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn removing_a_record_marks_the_manifest_dirty() { + let dir = scratch("remove"); + let mut m = HashManifest::load(&dir); + m.record("x.rs", "1"); + m.save().unwrap(); + let mut m = HashManifest::load(&dir); + m.remove("missing"); + assert!(!m.is_dirty()); + m.remove("x.rs"); + assert!(m.is_dirty()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/server/rust/metaobjects-codegen/src/lib.rs b/server/rust/metaobjects-codegen/src/lib.rs new file mode 100644 index 0000000000..96220729bc --- /dev/null +++ b/server/rust/metaobjects-codegen/src/lib.rs @@ -0,0 +1,20 @@ +//! MetaObjects code generation for Rust (preview). +//! +//! The run engine ([`engine`]) loads a project, decides whether anything changed +//! ([`fingerprint`], ADR-0064), renders through [`generator::Generator`]s, and writes only the +//! files whose bytes changed, keeping one hash manifest ([`hashes`]) that it saves once per +//! run. [`entity`] is the first generator: serde structs, enums and value objects, one crate +//! per metadata package (ADR-0065). + +pub mod engine; +pub mod entity; +pub mod fingerprint; +pub mod generator; +pub mod hashes; +pub mod names; +pub mod project; +pub mod sha256; + +pub use engine::{FileCounts, Outcome, RunError, RunOptions, RunReport, run}; +pub use entity::EntityGenerator; +pub use generator::{EmittedFile, GenContext, GenError, Generator}; diff --git a/server/rust/metaobjects-codegen/src/names.rs b/server/rust/metaobjects-codegen/src/names.rs new file mode 100644 index 0000000000..5e8ab68e28 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/names.rs @@ -0,0 +1,260 @@ +//! Rust spellings of metadata names: types, fields, crates, modules and literals. +//! +//! Pure functions; nothing here reads a model. + +/// Words that cannot be a plain identifier in edition 2021 or 2024 (strict, reserved and +/// the `gen` keyword the 2024 edition adds). `self`, `Self`, `super` and `crate` cannot be +/// raw identifiers either; [`field_ident`] and [`type_ident`] handle them separately. +const KEYWORDS: &[&str] = &[ + "abstract", "as", "async", "await", "become", "box", "break", "const", "continue", "do", "dyn", + "else", "enum", "extern", "false", "final", "fn", "for", "gen", "if", "impl", "in", "let", + "loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub", "ref", "return", + "static", "struct", "trait", "true", "try", "type", "typeof", "unsafe", "unsized", "use", + "virtual", "where", "while", "yield", +]; + +/// Keywords no `r#` prefix rescues. +const NO_RAW: &[&str] = &["self", "Self", "super", "crate"]; + +/// Std types a generated file names unqualified; an object with one of these names makes the +/// crate spell the std type by its full path instead (see `entity::Types`). +pub const PRELUDE_TYPES: &[&str] = &["String", "Vec", "Option", "Box"]; + +/// `user_profile`, `USER_PROFILE`, `userProfile`, `user-profile` become `UserProfile`; +/// `User` stays `User`; `ID` becomes `Id`. Splits on `_`, `-` and spaces only, so an +/// already-capitalised word such as `HTTPServer` keeps its spelling. +pub fn pascal(symbol: &str) -> String { + let all_upper = symbol == symbol.to_uppercase() && symbol.chars().any(char::is_alphabetic); + let mut out = String::with_capacity(symbol.len()); + for part in symbol.split(['_', '-', ' ']).filter(|p| !p.is_empty()) { + let part = if all_upper { + part.to_lowercase() + } else { + part.to_string() + }; + let mut chars = part.chars(); + if let Some(first) = chars.next() { + out.extend(first.to_uppercase()); + out.push_str(chars.as_str()); + } + } + out +} + +/// `userId` becomes `user_id`, `HTTPServer` becomes `http_server`, `address2Line` becomes +/// `address2_line`, `in-flight` becomes `in_flight`. +pub fn snake(name: &str) -> String { + let chars: Vec = name.chars().collect(); + let mut out = String::with_capacity(name.len() + 4); + for (i, &c) in chars.iter().enumerate() { + if c == '-' || c == ' ' { + out.push('_'); + continue; + } + if c.is_uppercase() && i > 0 { + let prev = chars[i - 1]; + let next_is_lower = chars.get(i + 1).is_some_and(|n| n.is_lowercase()); + let boundary = prev.is_lowercase() + || prev.is_ascii_digit() + || (prev.is_uppercase() && next_is_lower); + if boundary && !out.ends_with('_') { + out.push('_'); + } + } + out.extend(c.to_lowercase()); + } + out +} + +fn is_ident_text(s: &str) -> bool { + let mut chars = s.chars(); + chars.next().is_some_and(|c| c == '_' || c.is_alphabetic()) + && chars.all(|c| c == '_' || c.is_alphanumeric()) +} + +/// A field or module identifier for `name`: snake case, `r#`-escaped when it is a keyword, +/// suffixed with `_` when no escape exists, prefixed with `_` when it would start with a digit. +pub fn field_ident(name: &str) -> String { + let mut s = snake(name); + if !is_ident_text(&s) { + s = s + .chars() + .map(|c| { + if c == '_' || c.is_alphanumeric() { + c + } else { + '_' + } + }) + .collect(); + if s.chars().next().is_none_or(|c| c.is_ascii_digit()) { + s.insert(0, '_'); + } + } + if NO_RAW.contains(&s.as_str()) { + s.push('_'); + } else if KEYWORDS.contains(&s.as_str()) { + s.insert_str(0, "r#"); + } + s +} + +/// The identifier of a generated type or enum variant: [`pascal`], with `Self` made +/// distinct and a leading digit guarded. +pub fn type_ident(name: &str) -> String { + let mut s = pascal(name); + if !is_ident_text(&s) { + s = s + .chars() + .map(|c| { + if c == '_' || c.is_alphanumeric() { + c + } else { + '_' + } + }) + .collect(); + } + if s.chars().next().is_none_or(|c| c.is_ascii_digit()) { + s.insert(0, '_'); + } + if s == "Self" { + s.push('_'); + } + s +} + +/// The module (file) name of a generated type: its snake-case spelling, never raw. +pub fn module_name(type_name: &str) -> String { + let m = snake(type_name); + let m = field_ident(&m); + match m.strip_prefix("r#") { + Some(rest) => format!("{rest}_"), + None => m, + } +} + +/// The crate (and directory) name of a metadata package: each `::` segment in snake case, +/// joined with `_`. `acme::billing::v2` becomes `acme_billing_v2`; the empty package becomes +/// `model`. A name that starts with a digit gets a `p_` prefix. +pub fn crate_name(package: &str) -> String { + if package.is_empty() { + return "model".to_string(); + } + let mut out = String::new(); + for seg in package.split("::").filter(|s| !s.is_empty()) { + if !out.is_empty() { + out.push('_'); + } + for c in snake(seg).chars() { + out.push(if c == '_' || c.is_ascii_alphanumeric() { + c + } else { + '_' + }); + } + } + if out.is_empty() { + return "model".to_string(); + } + if out.starts_with(|c: char| c.is_ascii_digit()) { + out.insert_str(0, "p_"); + } + out +} + +/// A Rust string literal for `text`. +pub fn literal(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 2); + out.push('"'); + for ch in text.chars() { + match ch { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 || c as u32 == 0x7f => { + out.push_str(&format!("\\u{{{:x}}}", c as u32)); + } + c => out.push(c), + } + } + out.push('"'); + 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::*; + + #[test] + fn pascal_keeps_capitalised_words_and_lowers_all_caps() { + assert_eq!(pascal("User"), "User"); + assert_eq!(pascal("user_profile"), "UserProfile"); + assert_eq!(pascal("IN_FLIGHT"), "InFlight"); + assert_eq!(pascal("ID"), "Id"); + assert_eq!(pascal("HTTPServer"), "HTTPServer"); + assert_eq!(pascal("userProfile"), "UserProfile"); + } + + #[test] + fn snake_splits_camel_acronyms_and_digits() { + assert_eq!(snake("userId"), "user_id"); + assert_eq!(snake("HTTPServer"), "http_server"); + assert_eq!(snake("address2Line"), "address2_line"); + assert_eq!(snake("in-flight"), "in_flight"); + assert_eq!(snake("id"), "id"); + assert_eq!(snake("user_id"), "user_id"); + } + + #[test] + fn identifiers_escape_keywords_and_unescapable_words() { + assert_eq!(field_ident("type"), "r#type"); + assert_eq!(field_ident("gen"), "r#gen"); + assert_eq!(field_ident("self"), "self_"); + assert_eq!(field_ident("crate"), "crate_"); + assert_eq!(field_ident("userName"), "user_name"); + assert_eq!(field_ident("9lives"), "_9lives"); + assert_eq!(type_ident("self"), "Self_"); + assert_eq!(type_ident("order"), "Order"); + assert_eq!(module_name("Type"), "type_"); + assert_eq!(module_name("OrderLine"), "order_line"); + } + + #[test] + fn crate_names_join_package_segments() { + assert_eq!(crate_name("acme::billing::v2"), "acme_billing_v2"); + assert_eq!(crate_name("fitness"), "fitness"); + assert_eq!(crate_name(""), "model"); + assert_eq!(crate_name("2fa"), "p_2fa"); + assert_eq!(crate_name("AcmeShop"), "acme_shop"); + } + + #[test] + fn literals_and_doc_comments_are_escaped_and_trimmed() { + 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/project.rs b/server/rust/metaobjects-codegen/src/project.rs new file mode 100644 index 0000000000..9cd8622363 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/project.rs @@ -0,0 +1,41 @@ +//! Reading a project the way the other ports read it: find its collection, read its +//! config, gather its files (YAML and JSON, plus the opted-in libraries), and load them. + +use std::path::Path; + +use metaobjects::collection::{Collection, resolve_collection}; +use metaobjects::errors::MetaError; +use metaobjects::loader::{LoadResult, Loader}; +use metaobjects::naming::NamingRegistry; +use metaobjects::providers::default_registry; + +/// A loaded project: the resolved collection and the model it loaded. +#[derive(Debug)] +pub struct LoadedProject { + pub collection: Collection, + pub result: LoadResult, +} + +/// Resolve and load the project that `start_dir` belongs to (or `explicit_dir`, when given). +/// Every load error (and every unreadable file) comes back together; the model is only +/// returned when there are none. +pub fn load_project( + start_dir: &Path, + explicit_dir: Option<&Path>, + strict: bool, +) -> Result> { + let naming = NamingRegistry::builtin(); + let collection = resolve_collection(start_dir, explicit_dir, &naming).map_err(|e| vec![e])?; + let (sources, mut read_errors) = collection.read_sources(); + let mut registry = default_registry().map_err(|e| vec![e])?; + registry.seal(); + let mut result = Loader::new(®istry) + .naming(naming, collection.physical_naming.clone()) + .strict(strict) + .load_sources(&sources); + read_errors.append(&mut result.errors); + if !read_errors.is_empty() { + return Err(read_errors); + } + Ok(LoadedProject { collection, result }) +} diff --git a/server/rust/metaobjects-codegen/src/sha256.rs b/server/rust/metaobjects-codegen/src/sha256.rs new file mode 100644 index 0000000000..0f33ade2fe --- /dev/null +++ b/server/rust/metaobjects-codegen/src/sha256.rs @@ -0,0 +1,205 @@ +//! SHA-256 (FIPS 180-4), std only. +//! +//! The hash manifest (`.metaobjects/.gen-state/.hashes.json`) records the SHA-256 of +//! every generated file, the same digest every port writes, so the Rust port needs +//! the algorithm. It is a few dozen lines, so it lives here rather than as a +//! dependency of a code generator. This file is also compiled into `build.rs` +//! (`#[path]`), which hashes the engine's own sources into the skip key. + +const K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; + +const H0: [u32; 8] = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, +]; + +fn compress(state: &mut [u32; 8], block: &[u8]) { + let mut w = [0u32; 64]; + for (i, chunk) in block.chunks_exact(4).enumerate() { + w[i] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); + } + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + .wrapping_add(s0) + .wrapping_add(w[i - 7]) + .wrapping_add(s1); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *state; + for i in 0..64 { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let ch = (e & f) ^ (!e & g); + let t1 = h + .wrapping_add(s1) + .wrapping_add(ch) + .wrapping_add(K[i]) + .wrapping_add(w[i]); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let maj = (a & b) ^ (a & c) ^ (b & c); + let t2 = s0.wrapping_add(maj); + h = g; + g = f; + f = e; + e = d.wrapping_add(t1); + d = c; + c = b; + b = a; + a = t1.wrapping_add(t2); + } + for (s, v) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) { + *s = s.wrapping_add(v); + } +} + +/// An incremental SHA-256. +#[derive(Clone)] +pub struct Sha256 { + state: [u32; 8], + buffer: [u8; 64], + filled: usize, + length: u64, +} + +impl Default for Sha256 { + fn default() -> Self { + Self::new() + } +} + +impl Sha256 { + pub fn new() -> Self { + Self { + state: H0, + buffer: [0; 64], + filled: 0, + length: 0, + } + } + + pub fn update(&mut self, mut data: &[u8]) { + self.length += data.len() as u64; + if self.filled > 0 { + let take = (64 - self.filled).min(data.len()); + self.buffer[self.filled..self.filled + take].copy_from_slice(&data[..take]); + self.filled += take; + data = &data[take..]; + if self.filled < 64 { + return; + } + let block = self.buffer; + compress(&mut self.state, &block); + self.filled = 0; + } + let mut blocks = data.chunks_exact(64); + for block in &mut blocks { + compress(&mut self.state, block); + } + let rest = blocks.remainder(); + self.buffer[..rest.len()].copy_from_slice(rest); + self.filled = rest.len(); + } + + pub fn finish(mut self) -> [u8; 32] { + let bit_length = self.length.wrapping_mul(8); + let mut tail = [0u8; 72]; + tail[0] = 0x80; + // Pad to 56 mod 64, then the 64-bit big-endian bit length. + let pad = if self.filled < 56 { + 56 - self.filled + } else { + 120 - self.filled + }; + tail[pad..pad + 8].copy_from_slice(&bit_length.to_be_bytes()); + let total_length = self.length; + self.update(&tail[..pad + 8]); + self.length = total_length; + debug_assert_eq!(self.filled, 0); + let mut out = [0u8; 32]; + for (chunk, word) in out.chunks_exact_mut(4).zip(self.state) { + chunk.copy_from_slice(&word.to_be_bytes()); + } + out + } +} + +/// The lowercase hex SHA-256 of `data`. +pub fn sha256_hex(data: &[u8]) -> String { + let mut h = Sha256::new(); + h.update(data); + hex(&h.finish()) +} + +/// Lowercase hex of `bytes`. +pub fn hex(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for b in bytes { + out.push(DIGITS[(b >> 4) as usize] as char); + out.push(DIGITS[(b & 15) as usize] as char); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_the_fips_180_4_vectors() { + assert_eq!( + sha256_hex(b""), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + assert_eq!( + sha256_hex(b"abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!( + sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" + ); + let million_a = vec![b'a'; 1_000_000]; + assert_eq!( + sha256_hex(&million_a), + "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0" + ); + } + + #[test] + fn chunked_updates_equal_one_shot_at_every_boundary() { + let data: Vec = (0..300u32).map(|i| (i * 7 + 3) as u8).collect(); + let whole = sha256_hex(&data); + for split in 0..data.len() { + let mut h = Sha256::new(); + h.update(&data[..split]); + h.update(&data[split..]); + assert_eq!(hex(&h.finish()), whole, "split at {split}"); + } + } + + #[test] + fn padding_edges_55_56_63_64_bytes_agree_with_known_digests() { + // 55 bytes fits the length in the same block; 56 spills into a second one. + assert_eq!( + sha256_hex(&[b'a'; 55]), + "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318" + ); + assert_eq!( + sha256_hex(&[b'a'; 56]), + "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a" + ); + assert_eq!( + sha256_hex(&[b'a'; 64]), + "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb" + ); + } +} diff --git a/server/rust/metaobjects-codegen/tests/common/mod.rs b/server/rust/metaobjects-codegen/tests/common/mod.rs new file mode 100644 index 0000000000..8244a75a52 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/common/mod.rs @@ -0,0 +1,128 @@ +//! Shared scaffolding for the integration tests: scratch projects and the small model the +//! golden and compile tests both use. +#![allow(dead_code)] + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU32, Ordering}; + +/// A throwaway project directory under `$DEV_SCRATCH` (a RAM disk), removed on drop. +pub struct Scratch(pub PathBuf); + +impl Scratch { + pub fn new(tag: &str) -> Self { + static N: AtomicU32 = AtomicU32::new(0); + let base = std::env::var_os("DEV_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let dir = base.join(format!( + "mo-codegen-{tag}-{}-{}", + std::process::id(), + N.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } + + /// A project holding the given `(path, text)` files, with an empty `.metaobjects/config.json` + /// when the files do not bring their own. + pub fn project(tag: &str, files: &[(&str, &str)]) -> Self { + let s = Self::new(tag); + if !files.iter().any(|(p, _)| *p == ".metaobjects/config.json") { + s.write(".metaobjects/config.json", r#"{ "schema_version": 1 }"#); + } + for (path, text) in files { + s.write(path, text); + } + s + } + + pub fn path(&self) -> &Path { + &self.0 + } + + pub fn write(&self, rel: &str, text: &str) { + let p = self.0.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, text).unwrap(); + } + + pub fn read(&self, rel: &str) -> String { + std::fs::read_to_string(self.0.join(rel)).unwrap() + } + + pub fn exists(&self, rel: &str) -> bool { + self.0.join(rel).exists() + } + + pub fn mtime(&self, rel: &str) -> std::time::SystemTime { + std::fs::metadata(self.0.join(rel)) + .unwrap() + .modified() + .unwrap() + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The `shop` package: an abstract base, a shared enum, a value object, an entity that +/// uses all of them (inherited fields, inline and shared enums, optional and array fields, +/// a map, a keyword field name), and a self-referencing entity (which must be boxed). +pub const SHOP: &str = r#"{ "metadata.root": { "package": "shop", "children": [ + { "field.enum": { "name": "Currency", "abstract": true, + "@description": "A currency the shop trades in.", + "@values": ["usd", "EUR", "gbp_pound"] } }, + { "object.value": { "name": "Address", "@description": "Where a parcel goes.", "children": [ + { "field.string": { "name": "street", "@required": true } }, + { "field.string": { "name": "zipCode" } } + ] } }, + { "object.entity": { "name": "Base", "abstract": true, "children": [ + { "field.long": { "name": "id" } }, + { "field.timestamp": { "name": "createdAt", "@required": true } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } + ] } }, + { "object.entity": { "name": "Order", "extends": "Base", "@description": "One purchase.\nSecond line.", "children": [ + { "field.enum": { "name": "status", "@required": true, "@description": "Where the order is.", + "@values": ["NEW", "IN_FLIGHT", "done"] } }, + { "field.enum": { "name": "currency", "extends": "Currency", "@required": true } }, + { "field.currency": { "name": "total", "@required": true, "@currency": "USD" } }, + { "field.decimal": { "name": "taxRate" } }, + { "field.string": { "name": "type" } }, + { "field.string": { "name": "tags", "isArray": true } }, + { "field.map": { "name": "attributes", "@valueType": "string" } }, + { "field.object": { "name": "shipTo", "@required": true, "@objectRef": "Address" } }, + { "field.object": { "name": "billTo", "@objectRef": "Address" } }, + { "field.object": { "name": "history", "isArray": true, "@objectRef": "Address" } } + ] } }, + { "object.entity": { "name": "Category", "extends": "Base", "children": [ + { "field.string": { "name": "title", "@required": true } }, + { "field.object": { "name": "parent", "@objectRef": "Category" } }, + { "field.object": { "name": "subcategories", "isArray": true, "@objectRef": "Category" } } + ] } } +] } }"#; + +/// A second package whose entity refers to `shop`, so its crate depends on the `shop` crate. +pub const BILLING: &str = r#"{ "metadata.root": { "package": "shop::billing", "children": [ + { "object.entity": { "name": "Invoice", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.object": { "name": "order", "@required": true, "@objectRef": "shop::Order" } }, + { "field.enum": { "name": "currency", "extends": "shop::Currency" } } + ] } } +] } }"#; + +/// The two-package model as project files. +pub fn shop_files() -> Vec<(&'static str, &'static str)> { + vec![ + ("metaobjects/meta.shop.json", SHOP), + ("metaobjects/meta.billing.json", BILLING), + ] +} + +/// The shared public fitness model every port's conformance corpora use. +pub const FITNESS: &str = + include_str!("../../../../../fixtures/persistence-conformance/canonical/meta.fitness.json"); diff --git a/server/rust/metaobjects-codegen/tests/compile.rs b/server/rust/metaobjects-codegen/tests/compile.rs new file mode 100644 index 0000000000..4f26568fed --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/compile.rs @@ -0,0 +1,189 @@ +//! The generated crates build, are rustfmt-clean, and speak the wire form the model says. +//! +//! The small two-package model and the public fitness model are generated through the real +//! run engine into one scratch Cargo workspace, which `cargo check` builds with the real +//! compiler. A probe crate (hand-written here) then uses the generated types: it serializes +//! an order to JSON, parses it back, and walks a recursive structure and a cross-crate +//! reference, so a wrong `serde` attribute or a missing `Box` fails here and not in an +//! adopter's build. + +mod common; + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use common::{FITNESS, Scratch, shop_files}; +use metaobjects_codegen::{EntityGenerator, Generator, RunOptions, run}; + +fn target_dir() -> PathBuf { + // The workspace's own target directory, so serde and its derive build once and later runs + // reuse them. A separate sub-directory keeps this off the outer `cargo test`'s lock. + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../target/gen-check") +} + +fn cargo(dir: &Path, args: &[&str]) -> std::process::Output { + Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())) + .args(args) + .current_dir(dir) + .env("CARGO_TARGET_DIR", target_dir()) + .env_remove("CARGO_ENCODED_RUSTFLAGS") + .output() + .expect("cargo runs") +} + +fn generate(project: &Scratch) { + let generators: Vec> = vec![Box::new(EntityGenerator)]; + let mut opts = RunOptions::new(project.path()); + opts.out_dir = PathBuf::from("generated"); + run(&opts, &generators).unwrap_or_else(|e| panic!("gen failed: {e}")); +} + +const PROBE_MAIN: &str = r#" +use shop::{Address, Category, Currency, Order, OrderStatus}; +use shop_billing::Invoice; + +fn main() { + let order = Order { + id: 7, + created_at: "2026-01-02T03:04:05Z".to_string(), + status: OrderStatus::InFlight, + currency: Currency::GbpPound, + total: 1999, + tax_rate: None, + r#type: Some("rush".to_string()), + tags: Some(vec!["a".to_string(), "b".to_string()]), + attributes: None, + ship_to: Address { street: "1 Main".to_string(), zip_code: Some("90210".to_string()) }, + bill_to: None, + history: None, + }; + let json = serde_json::to_string(&order).unwrap(); + println!("{json}"); + let back: Order = serde_json::from_str(&json).unwrap(); + assert_eq!(back, order); + + let parent = Category { + id: 1, + created_at: "t".to_string(), + title: "root".to_string(), + parent: None, + subcategories: None, + }; + let child = Category { + id: 2, + created_at: "t".to_string(), + title: "leaf".to_string(), + parent: Some(Box::new(parent)), + subcategories: Some(Vec::new()), + }; + let child_json = serde_json::to_string(&child).unwrap(); + assert_eq!(serde_json::from_str::(&child_json).unwrap(), child); + + let invoice = Invoice { id: 9, order, currency: Some(Currency::Eur) }; + println!("{}", serde_json::to_string(&invoice).unwrap()); + assert_eq!(OrderStatus::Done.as_str(), "done"); + assert!(serde_json::from_str::("\"IN-FLIGHT\"").is_err()); +} +"#; + +#[test] +fn generated_crates_compile_are_formatted_and_round_trip_through_serde() { + let shop = Scratch::project("compile-shop", &shop_files()); + generate(&shop); + let fitness = Scratch::project( + "compile-fitness", + &[("metaobjects/meta.fitness.json", FITNESS)], + ); + generate(&fitness); + + let ws = Scratch::new("compile-ws"); + let copy = |from: &Path, to: &Path| { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + copy_tree(&entry.path(), &to.join(entry.file_name())); + } + }; + fn copy_tree(from: &Path, to: &Path) { + if from.is_dir() { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + copy_tree(&entry.path(), &to.join(entry.file_name())); + } + } else { + std::fs::copy(from, to).unwrap(); + } + } + copy(&shop.path().join("generated"), &ws.path().join("shop-out")); + copy( + &fitness.path().join("generated"), + &ws.path().join("fitness-out"), + ); + ws.write( + "Cargo.toml", + "[workspace]\nresolver = \"2\"\nmembers = [\"shop-out/*\", \"fitness-out/*\", \"probe\"]\n", + ); + // The scratch workspace resolves the same serde the repository does. + std::fs::copy( + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../Cargo.lock"), + ws.path().join("Cargo.lock"), + ) + .unwrap(); + ws.write( + "probe/Cargo.toml", + "[package]\nname = \"probe\"\nversion = \"0.0.0\"\nedition = \"2021\"\npublish = false\n\n\ + [dependencies]\nshop = { path = \"../shop-out/shop\" }\n\ + shop_billing = { path = \"../shop-out/shop_billing\" }\n\ + fitness = { path = \"../fitness-out/fitness\" }\nserde_json = \"1\"\n", + ); + ws.write("probe/src/main.rs", PROBE_MAIN); + + // rustfmt: the generated files must already be in their formatted form. + for lib in [ + "shop-out/shop", + "shop-out/shop_billing", + "fitness-out/fitness", + ] { + let out = Command::new("rustfmt") + .args(["--check", "--edition", "2021", "src/lib.rs"]) + .current_dir(ws.path().join(lib)) + .output() + .expect("rustfmt runs"); + assert!( + out.status.success(), + "{lib} is not rustfmt-clean:\n{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + } + + let check = cargo( + ws.path(), + &["check", "--offline", "--workspace", "--all-targets", "-q"], + ); + assert!( + check.status.success(), + "cargo check failed:\n{}", + String::from_utf8_lossy(&check.stderr) + ); + + let probe = cargo(ws.path(), &["run", "--offline", "-q", "-p", "probe"]); + assert!( + probe.status.success(), + "the probe failed:\n{}", + String::from_utf8_lossy(&probe.stderr) + ); + let stdout = String::from_utf8_lossy(&probe.stdout); + let mut lines = stdout.lines(); + assert_eq!( + lines.next().unwrap(), + r#"{"id":7,"createdAt":"2026-01-02T03:04:05Z","status":"IN_FLIGHT","currency":"gbp_pound","total":1999,"taxRate":null,"type":"rush","tags":["a","b"],"attributes":null,"shipTo":{"street":"1 Main","zipCode":"90210"},"billTo":null,"history":null}"# + ); + assert!( + lines + .next() + .unwrap() + .starts_with(r#"{"id":9,"order":{"id":7,"#) + ); +} diff --git a/server/rust/metaobjects-codegen/tests/entity_edges.rs b/server/rust/metaobjects-codegen/tests/entity_edges.rs new file mode 100644 index 0000000000..c120a494d3 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/entity_edges.rs @@ -0,0 +1,167 @@ +//! Edge cases of the entity generator: names Rust reserves, names the prelude owns, models +//! with no package, and references the generator refuses to guess at. + +mod common; + +use std::collections::BTreeMap; + +use common::Scratch; +use metaobjects_codegen::generator::{GenContext, GenError}; +use metaobjects_codegen::project::load_project; +use metaobjects_codegen::{EntityGenerator, Generator}; + +fn generate(files: &[(&str, &str)]) -> Result, GenError> { + let project = Scratch::project("edges", files); + let loaded = load_project(project.path(), None, false).expect("the model loads clean"); + let ctx = GenContext { + tree: &loaded.result.tree, + root: loaded.result.root, + entities: &[], + }; + EntityGenerator + .generate(&ctx) + .map(|f| f.into_iter().map(|f| (f.path, f.content)).collect()) +} + +fn model(package: &str, body: &str) -> String { + let pkg = if package.is_empty() { + String::new() + } else { + format!("\"package\": \"{package}\", ") + }; + format!(r#"{{ "metadata.root": {{ {pkg}"children": [ {body} ] }} }}"#) +} + +#[test] +fn reserved_words_become_raw_identifiers_and_self_gets_a_suffix() { + let m = model( + "kw", + r#"{ "object.entity": { "name": "Thing", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.string": { "name": "type" } }, + { "field.string": { "name": "gen" } }, + { "field.string": { "name": "self" } }, + { "field.string": { "name": "match_" } } + ] } }"#, + ); + let out = generate(&[("metaobjects/meta.kw.json", &m)]).unwrap(); + let text = &out["kw/src/thing.rs"]; + assert!(text.contains("pub r#type: Option"), "{text}"); + assert!(text.contains("pub r#gen: Option"), "{text}"); + assert!( + text.contains("#[serde(rename = \"self\")]\n pub self_: Option"), + "{text}" + ); +} + +#[test] +fn an_object_named_like_a_prelude_type_makes_the_crate_spell_std_paths_in_full() { + let m = model( + "pre", + r#"{ "object.entity": { "name": "Option", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.string": { "name": "label" } }, + { "field.string": { "name": "tags", "isArray": true } } + ] } }, + { "object.value": { "name": "Vec", "children": [ { "field.string": { "name": "x" } } ] } }, + { "object.value": { "name": "String", "children": [ { "field.string": { "name": "y" } } ] } }"#, + ); + let out = generate(&[("metaobjects/meta.pre.json", &m)]).unwrap(); + let text = &out["pre/src/option.rs"]; + assert!( + text.contains("pub label: std::option::Option"), + "{text}" + ); + assert!( + text.contains("pub tags: std::option::Option>"), + "{text}" + ); +} + +#[test] +fn a_model_with_no_package_becomes_the_model_crate() { + let m = model( + "", + r#"{ "object.entity": { "name": "Solo", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } + ] } }"#, + ); + let out = generate(&[("metaobjects/meta.solo.json", &m)]).unwrap(); + assert!(out.contains_key("model/Cargo.toml"), "{:?}", out.keys()); + assert!(out["model/src/lib.rs"].contains("pub use solo::Solo;")); +} + +#[test] +fn a_packaged_object_may_refer_to_a_package_less_one() { + let root = model( + "", + r#"{ "object.value": { "name": "Money", "children": [ { "field.long": { "name": "cents" } } ] } }"#, + ); + let app = model( + "app", + r#"{ "object.entity": { "name": "Bill", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.object": { "name": "due", "@objectRef": "Money" } } + ] } }"#, + ); + let out = generate(&[ + ("metaobjects/meta.root.json", &root), + ("metaobjects/meta.app.json", &app), + ]) + .unwrap(); + assert!( + out["app/src/bill.rs"].contains("pub due: Option"), + "{}", + out["app/src/bill.rs"] + ); + assert!(out["app/Cargo.toml"].contains("model = { path = \"../model\" }")); +} + +#[test] +fn two_enum_members_that_become_one_variant_are_an_error() { + let m = model( + "en", + r#"{ "object.entity": { "name": "Thing", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.enum": { "name": "kind", "@normalize": "none", "@values": ["in_flight", "IN_FLIGHT"] } } + ] } }"#, + ); + let e = generate(&[("metaobjects/meta.en.json", &m)]).unwrap_err(); + assert_eq!(e.code, "ERR_NAME_COLLISION"); +} + +#[test] +fn a_reference_to_something_that_is_not_a_struct_is_refused_by_name() { + let m = model( + "pr", + r#"{ "object.entity": { "name": "Base", "abstract": true, "children": [ + { "field.string": { "name": "x" } } ] } }, + { "object.entity": { "name": "Thing", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.object": { "name": "view", "@objectRef": "Base" } } + ] } }"#, + ); + let e = generate(&[("metaobjects/meta.pr.json", &m)]).unwrap_err(); + assert_eq!(e.code, "ERR_RUST_UNSUPPORTED"); + assert!(e.message.contains("pr::Thing.view"), "{}", e.message); +} + +#[test] +fn a_long_field_line_keeps_rustfmt_from_reflowing_the_struct() { + let m = model( + "wide", + r#"{ "object.entity": { "name": "Thing", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.map": { "name": "aVeryLongFieldNameThatKeepsGoingAndGoingForNoGoodReasonAtAll", "@valueType": "string" } } + ] } }"#, + ); + let out = generate(&[("metaobjects/meta.wide.json", &m)]).unwrap(); + assert!(out["wide/src/thing.rs"].contains("#[rustfmt::skip]")); +} diff --git a/server/rust/metaobjects-codegen/tests/golden.rs b/server/rust/metaobjects-codegen/tests/golden.rs new file mode 100644 index 0000000000..be381c636e --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/golden.rs @@ -0,0 +1,87 @@ +//! The generated text of a small two-package model, pinned file by file. +//! +//! The goldens under `tests/golden/shop/` are the specification of the entity generator's +//! output. A change to the emitted text fails here with the file named; regenerate them +//! deliberately with `UPDATE_GOLDEN=1 cargo test -p metaobjects-codegen --test golden`. + +mod common; + +use std::collections::BTreeMap; +use std::path::PathBuf; + +use common::{Scratch, shop_files}; +use metaobjects_codegen::EntityGenerator; +use metaobjects_codegen::generator::{GenContext, Generator}; +use metaobjects_codegen::project::load_project; + +fn golden_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/golden/shop") +} + +fn generate(files: &[(&str, &str)]) -> BTreeMap { + let project = Scratch::project("golden", files); + let loaded = load_project(project.path(), None, false).expect("the model loads clean"); + let ctx = GenContext { + tree: &loaded.result.tree, + root: loaded.result.root, + entities: &[], + }; + EntityGenerator + .generate(&ctx) + .expect("the entity generator succeeds") + .into_iter() + .map(|f| (f.path, f.content)) + .collect() +} + +fn read_goldens() -> BTreeMap { + fn walk(dir: &std::path::Path, base: &std::path::Path, out: &mut BTreeMap) { + let Ok(read) = std::fs::read_dir(dir) else { + return; + }; + for e in read.filter_map(Result::ok) { + let p = e.path(); + if p.is_dir() { + walk(&p, base, out); + } else { + let rel = p + .strip_prefix(base) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + out.insert(rel, std::fs::read_to_string(&p).unwrap()); + } + } + } + let mut out = BTreeMap::new(); + walk(&golden_dir(), &golden_dir(), &mut out); + out +} + +#[test] +fn the_shop_model_generates_exactly_the_golden_files() { + let got = generate(&shop_files()); + if std::env::var_os("UPDATE_GOLDEN").is_some() { + let _ = std::fs::remove_dir_all(golden_dir()); + for (path, text) in &got { + let p = golden_dir().join(path); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, text).unwrap(); + } + return; + } + let want = read_goldens(); + assert_eq!( + got.keys().collect::>(), + want.keys().collect::>(), + "the set of generated files changed" + ); + for (path, text) in &got { + assert_eq!(text, &want[path], "{path} differs from its golden"); + } +} + +#[test] +fn generation_is_deterministic() { + assert_eq!(generate(&shop_files()), generate(&shop_files())); +} diff --git a/server/rust/metaobjects-codegen/tests/golden/shop/shop/Cargo.toml b/server/rust/metaobjects-codegen/tests/golden/shop/shop/Cargo.toml new file mode 100644 index 0000000000..456a42d299 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/golden/shop/shop/Cargo.toml @@ -0,0 +1,10 @@ +# @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. +[package] +name = "shop" +version = "0.1.0" +edition = "2021" +publish = false +description = "Generated from the MetaObjects package shop." + +[dependencies] +serde = { version = "1", features = ["derive"] } diff --git a/server/rust/metaobjects-codegen/tests/golden/shop/shop/rustfmt.toml b/server/rust/metaobjects-codegen/tests/golden/shop/shop/rustfmt.toml new file mode 100644 index 0000000000..b653465db7 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/golden/shop/shop/rustfmt.toml @@ -0,0 +1,6 @@ +# @generated by the MetaObjects entity generator. +# The generated files are written in rustfmt's output form under these settings; they pin +# that form, so `cargo fmt` over the output changes nothing. +max_width = 100 +reorder_imports = false +reorder_modules = false diff --git a/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/address.rs b/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/address.rs new file mode 100644 index 0000000000..21ba41e481 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/address.rs @@ -0,0 +1,9 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +/// Where a parcel goes. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Address { + pub street: String, + #[serde(rename = "zipCode")] + pub zip_code: Option, +} diff --git a/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/category.rs b/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/category.rs new file mode 100644 index 0000000000..8c5d9b4000 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/category.rs @@ -0,0 +1,11 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Category { + pub id: i64, + #[serde(rename = "createdAt")] + pub created_at: String, + pub title: String, + pub parent: Option>, + pub subcategories: Option>, +} diff --git a/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/currency.rs b/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/currency.rs new file mode 100644 index 0000000000..ff482f2ccd --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/currency.rs @@ -0,0 +1,23 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +/// A currency the shop trades in. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum Currency { + #[serde(rename = "usd")] + Usd, + #[serde(rename = "EUR")] + Eur, + #[serde(rename = "gbp_pound")] + GbpPound, +} + +impl Currency { + /// The wire spelling of the member. + pub const fn as_str(self) -> &'static str { + match self { + Currency::Usd => "usd", + Currency::Eur => "EUR", + Currency::GbpPound => "gbp_pound", + } + } +} diff --git a/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/lib.rs b/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/lib.rs new file mode 100644 index 0000000000..89306c07e4 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/lib.rs @@ -0,0 +1,14 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +//! Generated from the MetaObjects package `shop`. + +mod address; +mod category; +mod currency; +mod order; + +pub use address::Address; +pub use category::Category; +pub use currency::Currency; +pub use order::Order; +pub use order::OrderStatus; diff --git a/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/order.rs b/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/order.rs new file mode 100644 index 0000000000..a75054e728 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/golden/shop/shop/src/order.rs @@ -0,0 +1,47 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +/// One purchase. +/// Second line. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Order { + pub id: i64, + #[serde(rename = "createdAt")] + pub created_at: String, + /// Where the order is. + pub status: crate::OrderStatus, + /// A currency the shop trades in. + pub currency: crate::Currency, + pub total: i64, + #[serde(rename = "taxRate")] + pub tax_rate: Option, + pub r#type: Option, + pub tags: Option>, + pub attributes: Option>, + #[serde(rename = "shipTo")] + pub ship_to: crate::Address, + #[serde(rename = "billTo")] + pub bill_to: Option, + pub history: Option>, +} + +/// Where the order is. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub enum OrderStatus { + #[serde(rename = "NEW")] + New, + #[serde(rename = "IN_FLIGHT")] + InFlight, + #[serde(rename = "done")] + Done, +} + +impl OrderStatus { + /// The wire spelling of the member. + pub const fn as_str(self) -> &'static str { + match self { + OrderStatus::New => "NEW", + OrderStatus::InFlight => "IN_FLIGHT", + OrderStatus::Done => "done", + } + } +} diff --git a/server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/Cargo.toml b/server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/Cargo.toml new file mode 100644 index 0000000000..baa170136b --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/Cargo.toml @@ -0,0 +1,11 @@ +# @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. +[package] +name = "shop_billing" +version = "0.1.0" +edition = "2021" +publish = false +description = "Generated from the MetaObjects package shop::billing." + +[dependencies] +serde = { version = "1", features = ["derive"] } +shop = { path = "../shop" } diff --git a/server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/rustfmt.toml b/server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/rustfmt.toml new file mode 100644 index 0000000000..b653465db7 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/rustfmt.toml @@ -0,0 +1,6 @@ +# @generated by the MetaObjects entity generator. +# The generated files are written in rustfmt's output form under these settings; they pin +# that form, so `cargo fmt` over the output changes nothing. +max_width = 100 +reorder_imports = false +reorder_modules = false diff --git a/server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/src/invoice.rs b/server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/src/invoice.rs new file mode 100644 index 0000000000..2607730871 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/src/invoice.rs @@ -0,0 +1,9 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Invoice { + pub id: i64, + pub order: shop::Order, + /// A currency the shop trades in. + pub currency: Option, +} diff --git a/server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/src/lib.rs b/server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/src/lib.rs new file mode 100644 index 0000000000..8f4d286a4a --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/golden/shop/shop_billing/src/lib.rs @@ -0,0 +1,7 @@ +// @generated by the MetaObjects entity generator. Do not edit: change the model and run `cargo meta gen`. + +//! Generated from the MetaObjects package `shop::billing`. + +mod invoice; + +pub use invoice::Invoice; diff --git a/server/rust/metaobjects-codegen/tests/run_engine.rs b/server/rust/metaobjects-codegen/tests/run_engine.rs new file mode 100644 index 0000000000..f1ac756f9a --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/run_engine.rs @@ -0,0 +1,265 @@ +//! The run engine's contract (ADR-0064): identical bytes are never rewritten, the manifest is +//! written only when a record changed, an unchanged project skips without touching disk, and a +//! hand-edited generated file is refused rather than overwritten. + +mod common; + +use std::path::PathBuf; +use std::thread::sleep; +use std::time::Duration; + +use common::{Scratch, shop_files}; +use metaobjects_codegen::engine::{ + Outcome, STAGE_LOAD, STAGE_PLAN, STAGE_RENDER, STAGE_SKIP, STAGE_WRITE, +}; +use metaobjects_codegen::fingerprint::FINGERPRINT_FILE; +use metaobjects_codegen::{EntityGenerator, Generator, RunError, RunOptions, RunReport, run}; + +const MANIFEST: &str = ".metaobjects/.gen-state/.hashes.json"; + +fn generators() -> Vec> { + vec![Box::new(EntityGenerator)] +} + +fn gen_with(project: &Scratch, tweak: impl FnOnce(&mut RunOptions)) -> Result { + let mut opts = RunOptions::new(project.path()); + tweak(&mut opts); + run(&opts, &generators()) +} + +fn gen_ok(project: &Scratch) -> RunReport { + gen_with(project, |_| {}).unwrap_or_else(|e| panic!("gen failed: {e}")) +} + +/// A pause longer than the filesystem's timestamp granularity, so "untouched" is observable. +fn tick() { + sleep(Duration::from_millis(30)); +} + +#[test] +fn a_first_run_writes_every_file_and_records_them_all() { + let p = Scratch::project("first", &shop_files()); + let r = gen_ok(&p); + assert_eq!(r.outcome, Outcome::Generated); + assert_eq!(r.files.overwritten + r.files.unchanged, 0); + assert!(r.files.created > 0); + assert!(r.manifest_written); + assert!(p.exists("generated/shop/src/order.rs")); + assert!(p.exists("generated/shop_billing/Cargo.toml")); + let manifest = p.read(MANIFEST); + assert!( + manifest.contains("\"generated/shop/src/order.rs\""), + "{manifest}" + ); + assert!(manifest.ends_with("}\n")); + assert!(p.exists(&format!(".metaobjects/.gen-state/{FINGERPRINT_FILE}"))); + let names: Vec<&str> = r.timings.phases.iter().map(|t| t.name).collect(); + assert_eq!(names, [STAGE_LOAD, STAGE_PLAN, STAGE_RENDER, STAGE_WRITE]); +} + +#[test] +fn an_unchanged_project_skips_without_touching_any_file() { + let p = Scratch::project("skip", &shop_files()); + gen_ok(&p); + let files = [ + "generated/shop/src/order.rs", + MANIFEST, + ".metaobjects/.gen-state/.fingerprint-rust.json", + ]; + let before: Vec<_> = files.iter().map(|f| p.mtime(f)).collect(); + tick(); + let r = gen_ok(&p); + assert_eq!(r.outcome, Outcome::Skipped); + assert!(!r.manifest_written); + assert_eq!(r.files, Default::default()); + let names: Vec<&str> = r.timings.phases.iter().map(|t| t.name).collect(); + assert_eq!( + names, + [STAGE_LOAD, STAGE_PLAN, STAGE_SKIP], + "a skip renders and writes nothing" + ); + let after: Vec<_> = files.iter().map(|f| p.mtime(f)).collect(); + assert_eq!(before, after, "a skipped run moves no timestamp"); +} + +#[test] +fn identical_bytes_are_never_rewritten_and_an_unchanged_manifest_is_never_saved() { + let p = Scratch::project("noop", &shop_files()); + gen_ok(&p); + let order = p.mtime("generated/shop/src/order.rs"); + let manifest = p.mtime(MANIFEST); + tick(); + // --force renders everything, so every file is compared; none may be written. + let r = gen_with(&p, |o| o.force = true).unwrap(); + assert_eq!(r.outcome, Outcome::Generated); + assert_eq!(r.files.created + r.files.overwritten, 0); + assert!(r.files.unchanged > 0); + assert!(!r.manifest_written); + assert_eq!(p.mtime("generated/shop/src/order.rs"), order); + assert_eq!(p.mtime(MANIFEST), manifest); +} + +#[test] +fn a_changed_model_rewrites_only_the_file_that_changed_and_saves_the_manifest_once() { + let p = Scratch::project("delta", &shop_files()); + gen_ok(&p); + let order = p.mtime("generated/shop/src/order.rs"); + let address = p.mtime("generated/shop/src/address.rs"); + tick(); + let edited = common::SHOP.replace( + r#"{ "field.string": { "name": "type" } },"#, + r#"{ "field.string": { "name": "type" } }, + { "field.string": { "name": "channel" } },"#, + ); + p.write("metaobjects/meta.shop.json", &edited); + let r = gen_ok(&p); + assert_eq!(r.outcome, Outcome::Generated); + assert_eq!(r.files.overwritten, 1, "{:?}", r.files); + assert_eq!(r.files.created, 0); + assert!(r.manifest_written, "one changed hash is one manifest save"); + assert!( + p.read("generated/shop/src/order.rs") + .contains("pub channel: Option") + ); + assert!(p.mtime("generated/shop/src/order.rs") > order); + assert_eq!(p.mtime("generated/shop/src/address.rs"), address); +} + +#[test] +fn a_hand_edited_generated_file_is_refused_and_the_run_stores_no_key() { + let p = Scratch::project("edited", &shop_files()); + gen_ok(&p); + let path = "generated/shop/src/address.rs"; + let edited = format!("{}\n// my edit\n", p.read(path)); + p.write(path, &edited); + let e = gen_ok_err(&p); + match e { + RunError::Refused(paths) => assert_eq!(paths, vec![path.to_string()]), + other => panic!("expected a refusal, got {other}"), + } + assert_eq!(p.read(path), edited, "the edit is left in place"); + assert!( + !p.exists(&format!(".metaobjects/.gen-state/{FINGERPRINT_FILE}")), + "a refused run is not a current one" + ); +} + +fn gen_ok_err(p: &Scratch) -> RunError { + gen_with(p, |_| {}).expect_err("the run fails") +} + +#[test] +fn an_existing_file_nobody_recorded_is_refused_not_adopted() { + let p = Scratch::project("unrecorded", &shop_files()); + p.write("generated/shop/Cargo.toml", "# somebody else's\n"); + match gen_ok_err(&p) { + RunError::Refused(paths) => { + assert_eq!(paths, vec!["generated/shop/Cargo.toml".to_string()]) + } + other => panic!("expected a refusal, got {other}"), + } +} + +#[test] +fn a_package_that_goes_away_has_its_generated_files_removed() { + let p = Scratch::project("orphan", &shop_files()); + gen_ok(&p); + assert!(p.exists("generated/shop_billing/src/invoice.rs")); + std::fs::remove_file(p.path().join("metaobjects/meta.billing.json")).unwrap(); + let r = gen_ok(&p); + assert!(r.files.removed >= 4, "{:?}", r.files); + assert!( + !p.exists("generated/shop_billing"), + "the emptied crate directory is gone too" + ); + assert!(p.exists("generated/shop/src/order.rs")); + assert!(!p.read(MANIFEST).contains("shop_billing")); +} + +#[test] +fn an_orphan_with_a_hand_edit_is_kept_with_a_warning() { + let p = Scratch::project("orphan-edited", &shop_files()); + gen_ok(&p); + p.write("generated/shop_billing/src/invoice.rs", "// mine\n"); + std::fs::remove_file(p.path().join("metaobjects/meta.billing.json")).unwrap(); + let r = gen_ok(&p); + assert!(p.exists("generated/shop_billing/src/invoice.rs")); + assert!( + r.warnings.iter().any(|w| w.contains("invoice.rs")), + "{:?}", + r.warnings + ); +} + +#[test] +fn naming_an_entity_limits_the_run_and_never_skips_or_stores_a_key() { + let p = Scratch::project("named", &shop_files()); + gen_ok(&p); + let key = p.read(&format!(".metaobjects/.gen-state/{FINGERPRINT_FILE}")); + let address = p.mtime("generated/shop/src/address.rs"); + tick(); + let r = gen_with(&p, |o| o.entities = vec!["Order".to_string()]).unwrap(); + assert_eq!(r.outcome, Outcome::Generated, "a named run never skips"); + assert_eq!(r.files.created + r.files.overwritten, 0); + assert_eq!(r.files.removed, 0, "a named run sweeps nothing"); + assert_eq!(p.mtime("generated/shop/src/address.rs"), address); + assert_eq!( + p.read(&format!(".metaobjects/.gen-state/{FINGERPRINT_FILE}")), + key, + "the full-run key is left as it was found" + ); + let e = gen_with(&p, |o| o.entities = vec!["Nope".to_string()]).expect_err("unknown entity"); + assert!( + e.to_string() + .contains("no entity or value object named Nope"), + "{e}" + ); +} + +#[test] +fn a_load_error_stops_the_run_before_anything_is_written() { + let p = Scratch::project("bad", &[("metaobjects/meta.bad.json", "{ not json")]); + let e = gen_with(&p, |_| {}).expect_err("the model does not load"); + assert!(matches!(e, RunError::Load(_)), "{e}"); + assert!(!p.exists("generated")); + assert!(!p.exists(".metaobjects/.gen-state")); +} + +#[test] +fn the_output_directory_must_be_inside_the_project() { + let p = Scratch::project("outside", &shop_files()); + let e = gen_with(&p, |o| o.out_dir = PathBuf::from("../elsewhere")).expect_err("outside"); + assert!(e.to_string().contains("ERR_OUT_DIR_OUTSIDE_PROJECT"), "{e}"); +} + +#[test] +fn two_name_collisions_and_a_crate_cycle_are_reported_not_emitted() { + // Two objects that become one Rust type. + let dup = r#"{ "metadata.root": { "package": "dup", "children": [ + { "object.entity": { "name": "order_line", "children": [{ "field.long": { "name": "id" } }] } }, + { "object.entity": { "name": "OrderLine", "children": [{ "field.long": { "name": "id" } }] } } + ] } }"#; + let p = Scratch::project("dup", &[("metaobjects/meta.dup.json", dup)]); + let e = gen_with(&p, |_| {}).expect_err("collision"); + assert!(e.to_string().contains("ERR_NAME_COLLISION"), "{e}"); + + // Two packages that refer to each other cannot be two crates. + let a = r#"{ "metadata.root": { "package": "ca", "children": [ + { "object.entity": { "name": "A", "children": [ + { "field.long": { "name": "id" } }, + { "field.object": { "name": "b", "@objectRef": "cb::B" } } ] } } ] } }"#; + let b = r#"{ "metadata.root": { "package": "cb", "children": [ + { "object.entity": { "name": "B", "children": [ + { "field.long": { "name": "id" } }, + { "field.object": { "name": "a", "@objectRef": "ca::A" } } ] } } ] } }"#; + let p = Scratch::project( + "cycle", + &[ + ("metaobjects/meta.a.json", a), + ("metaobjects/meta.b.json", b), + ], + ); + let e = gen_with(&p, |_| {}).expect_err("cycle"); + assert!(e.to_string().contains("ERR_CRATE_CYCLE"), "{e}"); + assert!(!p.exists("generated")); +} diff --git a/server/rust/metaobjects-codegen/tests/skip_conformance.rs b/server/rust/metaobjects-codegen/tests/skip_conformance.rs new file mode 100644 index 0000000000..354856d383 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/skip_conformance.rs @@ -0,0 +1,398 @@ +//! The shared generation-skip corpus (ADR-0064), run against the Rust engine. +//! +//! `fixtures/codegen-skip-conformance/cases.json` lists what each port's next `gen` must do after +//! each kind of change: skip (render and write nothing) or regenerate. Every port runs every +//! case against its own project shape. A case id this runner does not know FAILS, so a case +//! added for the other ports reaches this one. +//! +//! Where Rust differs it says so below, in the one table of `Fit` values: +//! - `Applies` runs the case and checks the corpus's `gen` column. +//! - `NotApplicable` names why the case cannot arise (there are no templates, no ejected +//! generators, no merge engine and no `verify` in the Rust port yet). +//! - `generated-file-edited` runs, and "regenerate" means the run is attempted and the edited file +//! is REFUSED (the run fails and names it): Rust has no three-way merge, as Python has none. + +mod common; + +use std::thread::sleep; +use std::time::Duration; + +use common::{Scratch, shop_files}; +use metaobjects_codegen::generator::{EmittedFile, GenContext, GenError}; +use metaobjects_codegen::{EntityGenerator, Generator, Outcome, RunError, RunOptions, run}; +use serde_json::{Value, json}; + +const CASES: &str = include_str!("../../../../fixtures/codegen-skip-conformance/cases.json"); + +enum Fit { + Applies, + NotApplicable(&'static str), +} + +fn fit(id: &str) -> Fit { + match id { + "template-edited" | "template-added" => { + Fit::NotApplicable("the Rust port has no templates (out of scope for ADR-0065 phase 1)") + } + "owned-generator-edited" => { + Fit::NotApplicable("there is no `eject` in the Rust port yet, so no owned generator") + } + "hand-edit-kept" => Fit::NotApplicable( + "a hand edit is never kept: with no merge engine, the run refuses the file instead", + ), + "ci" => { + Fit::NotApplicable("the case is about `verify`, which the Rust port does not have yet") + } + _ => Fit::Applies, + } +} + +/// The entity generator with the knobs the corpus needs to turn. +struct Probe { + identity: &'static str, + cacheable: bool, + extras: Vec, + fail: bool, +} + +impl Default for Probe { + fn default() -> Self { + Probe { + identity: "entity", + cacheable: true, + extras: Vec::new(), + fail: false, + } + } +} + +impl Generator for Probe { + fn name(&self) -> &str { + "entity" + } + fn identity(&self) -> String { + format!("{}:{}", EntityGenerator.identity(), self.identity) + } + fn cacheable(&self) -> bool { + self.cacheable + } + fn extra_inputs(&self) -> Vec { + self.extras.clone() + } + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + if self.fail { + return Err(GenError::new( + "ERR_PROBE", + "the probe generator was told to fail", + )); + } + EntityGenerator.generate(ctx) + } +} + +type RunResult = Result; + +fn go(p: &Scratch, probe: Probe, tweak: impl FnOnce(&mut RunOptions)) -> RunResult { + let mut opts = RunOptions::new(p.path()); + tweak(&mut opts); + run(&opts, &[Box::new(probe) as Box]) +} + +fn tick() { + sleep(Duration::from_millis(30)); +} + +fn shop_json() -> Value { + serde_json::from_str(common::SHOP).unwrap() +} + +fn children_mut(doc: &mut Value) -> &mut Vec { + doc["metadata.root"]["children"].as_array_mut().unwrap() +} + +fn object_named<'a>(doc: &'a mut Value, name: &str) -> &'a mut Value { + children_mut(doc) + .iter_mut() + .find(|c| { + c.as_object() + .is_some_and(|o| o.values().any(|b| b["name"] == name)) + }) + .unwrap_or_else(|| panic!("no object {name}")) + .as_object_mut() + .unwrap() + .values_mut() + .next() + .unwrap() +} + +fn add_field(doc: &mut Value, object: &str, field: Value) { + object_named(doc, object)["children"] + .as_array_mut() + .unwrap() + .push(field); +} + +fn write_json(p: &Scratch, rel: &str, doc: &Value) { + p.write(rel, &serde_json::to_string_pretty(doc).unwrap()); +} + +const SHOP_FILE: &str = "metaobjects/meta.shop.json"; +const BILLING_FILE: &str = "metaobjects/meta.billing.json"; +const KEY_FILE: &str = ".metaobjects/.gen-state/.fingerprint-rust.json"; + +/// Apply the case's change and run the next `gen`. +fn next_run(id: &str, p: &Scratch) -> RunResult { + match id { + "no-change" => go(p, Probe::default(), |_| {}), + "metadata-touched" => { + tick(); + p.write(SHOP_FILE, &p.read(SHOP_FILE)); + go(p, Probe::default(), |_| {}) + } + "unrelated-file-edited" => { + p.write("README.md", "# notes\nedited\n"); + go(p, Probe::default(), |_| {}) + } + "metadata-reformatted" => { + // serde_json sorts keys and re-indents: other whitespace, other key order. + let doc = shop_json(); + write_json(p, SHOP_FILE, &doc); + assert_ne!(p.read(SHOP_FILE), common::SHOP); + go(p, Probe::default(), |_| {}) + } + "metadata-moved" => { + let mut doc = shop_json(); + let moved = { + let kids = children_mut(&mut doc); + let at = kids + .iter() + .position(|c| { + c.as_object() + .is_some_and(|o| o.values().any(|b| b["name"] == "Category")) + }) + .unwrap(); + kids.remove(at) + }; + write_json(p, SHOP_FILE, &doc); + p.write( + "metaobjects/meta.category.json", + &serde_json::to_string_pretty(&json!({ + "metadata.root": { "package": "shop", "children": [moved] } + })) + .unwrap(), + ); + go(p, Probe::default(), |_| {}) + } + "metadata-edited" => { + let mut doc = shop_json(); + add_field( + &mut doc, + "Address", + json!({ "field.string": { "name": "country" } }), + ); + write_json(p, SHOP_FILE, &doc); + go(p, Probe::default(), |_| {}) + } + "metadata-added" => { + p.write( + "metaobjects/meta.extra.json", + r#"{ "metadata.root": { "package": "shop", "children": [ + { "object.value": { "name": "Note", "children": [ { "field.string": { "name": "text" } } ] } } ] } }"#, + ); + go(p, Probe::default(), |_| {}) + } + "metadata-removed" => { + std::fs::remove_file(p.path().join(BILLING_FILE)).unwrap(); + go(p, Probe::default(), |_| {}) + } + "parent-edited" => { + let mut doc = shop_json(); + add_field( + &mut doc, + "Base", + json!({ "field.string": { "name": "owner" } }), + ); + write_json(p, SHOP_FILE, &doc); + go(p, Probe::default(), |_| {}) + } + // Rust has no codegen config file: the generator set and each generator's identity + // (its options) are the config, and a changed identity is a changed config. + "config-edited" => go( + p, + Probe { + identity: "options-changed", + ..Probe::default() + }, + |_| {}, + ), + "project-config-edited" => { + p.write( + ".metaobjects/config.json", + r#"{ "schema_version": 1, "sources": [{ "path": "metaobjects" }] }"#, + ); + go(p, Probe::default(), |_| {}) + } + "engine-changed" => { + // The engine's identity is its built source hash, a compile-time constant a test + // cannot change; what can be shown is that a stored key from a different engine + // build no longer matches. + let mut key: Value = serde_json::from_str(&p.read(KEY_FILE)).unwrap(); + key["fingerprint"] = json!("0".repeat(64)); + p.write(KEY_FILE, &serde_json::to_string_pretty(&key).unwrap()); + go(p, Probe::default(), |_| {}) + } + "selection-changed" => go(p, Probe::default(), |o| o.strict = true), + "declared-extra-edited" => { + // The stored run must have declared the extra; rerun once with it, then edit it. + p.write("seed.txt", "one"); + let first = go( + p, + Probe { + extras: vec!["seed.txt".into()], + ..Probe::default() + }, + |_| {}, + ); + assert_eq!(first.unwrap().outcome, Outcome::Generated); + p.write("seed.txt", "two"); + go( + p, + Probe { + extras: vec!["seed.txt".into()], + ..Probe::default() + }, + |_| {}, + ) + } + "uncacheable-generator" => go( + p, + Probe { + cacheable: false, + ..Probe::default() + }, + |_| {}, + ), + "generated-file-deleted" => { + std::fs::remove_file(p.path().join("generated/shop/src/order.rs")).unwrap(); + go(p, Probe::default(), |_| {}) + } + "generated-file-edited" => { + let path = "generated/shop/src/order.rs"; + p.write(path, &format!("{}// by hand\n", p.read(path))); + go(p, Probe::default(), |_| {}) + } + "fingerprint-missing" => { + std::fs::remove_file(p.path().join(KEY_FILE)).unwrap(); + go(p, Probe::default(), |_| {}) + } + "force" => go(p, Probe::default(), |o| o.force = true), + "failed-run" => { + let original = p.read(SHOP_FILE); + let mut doc = shop_json(); + add_field( + &mut doc, + "Address", + json!({ "field.string": { "name": "country" } }), + ); + write_json(p, SHOP_FILE, &doc); + let failed = go( + p, + Probe { + fail: true, + ..Probe::default() + }, + |_| {}, + ); + assert!( + matches!(failed, Err(RunError::Generator(_))), + "the probe run must fail" + ); + p.write(SHOP_FILE, &original); + go(p, Probe::default(), |_| {}) + } + other => panic!( + "the skip-conformance corpus has a case this port does not know: {other}. \ + Add it to `fit` (and `next_run`) so it reaches the Rust port." + ), + } +} + +#[test] +fn every_case_in_the_shared_corpus_behaves_as_it_says() { + let corpus: Value = serde_json::from_str(CASES).unwrap(); + assert_eq!(corpus["version"], 1, "the corpus changed shape"); + let cases = corpus["cases"].as_array().unwrap(); + assert!(cases.len() >= 25); + let mut ran = 0; + for case in cases { + let id = case["id"].as_str().unwrap(); + match fit(id) { + Fit::NotApplicable(why) => { + assert!(!why.is_empty()); + continue; + } + Fit::Applies => {} + } + let p = Scratch::project(&format!("skip-{id}"), &shop_files()); + let first = go(&p, Probe::default(), |_| {}) + .unwrap_or_else(|e| panic!("{id}: first run failed: {e}")); + assert_eq!(first.outcome, Outcome::Generated, "{id}"); + assert!(p.exists(KEY_FILE), "{id}: the first run must store a key"); + tick(); + + let result = next_run(id, &p); + match case["gen"].as_str().unwrap() { + "skip" => { + let r = + result.unwrap_or_else(|e| panic!("{id}: expected a skip, the run failed: {e}")); + assert_eq!(r.outcome, Outcome::Skipped, "{id}: {}", case["change"]); + assert_eq!(r.files, Default::default(), "{id}: a skip writes nothing"); + assert!(!r.manifest_written, "{id}: a skip saves no manifest"); + } + "regenerate" if id == "generated-file-edited" => match result { + Err(RunError::Refused(paths)) => { + assert_eq!(paths, vec!["generated/shop/src/order.rs".to_string()]) + } + other => panic!("{id}: expected the edited file to be refused, got {other:?}"), + }, + "regenerate" => { + let r = result.unwrap_or_else(|e| panic!("{id}: the run failed: {e}")); + assert_eq!(r.outcome, Outcome::Generated, "{id}: {}", case["change"]); + } + other => panic!("{id}: unknown gen expectation {other}"), + } + ran += 1; + } + assert!( + ran >= 20, + "only {ran} cases ran; the table of not-applicable cases has grown too far" + ); +} + +#[test] +fn a_run_that_regenerates_stores_a_key_that_the_next_run_skips_on() { + let p = Scratch::project("skip-after-regen", &shop_files()); + go(&p, Probe::default(), |_| {}).unwrap(); + let mut doc = shop_json(); + add_field( + &mut doc, + "Address", + json!({ "field.string": { "name": "country" } }), + ); + write_json(&p, SHOP_FILE, &doc); + assert_eq!( + go(&p, Probe::default(), |_| {}).unwrap().outcome, + Outcome::Generated + ); + assert_eq!( + go(&p, Probe::default(), |_| {}).unwrap().outcome, + Outcome::Skipped + ); +} + +#[test] +fn the_engine_identity_is_a_content_hash() { + let h = metaobjects_codegen::engine::ENGINE_SOURCE_HASH; + assert_eq!(h.len(), 64); + assert!(h.bytes().all(|b| b.is_ascii_hexdigit())); +} From 6f7a4d639387fcb9fbad361c791e6a768ec26455 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 23:51:51 -0500 Subject: [PATCH 02/13] no-mistakes(review): align ref resolution, named-run crates, fingerprint --- CHANGELOG.md | 4 +- server/rust/metaobjects-codegen/src/entity.rs | 90 +++++++++-------- .../metaobjects-codegen/src/fingerprint.rs | 2 - .../rust/metaobjects-codegen/tests/compile.rs | 78 +++++++++++---- .../metaobjects-codegen/tests/entity_edges.rs | 99 ++++++++++++++++++- .../metaobjects-codegen/tests/run_engine.rs | 14 +++ 6 files changed, 219 insertions(+), 68 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 822c3c37ec..27622f7ec5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,8 +66,8 @@ here.** other ports, on purpose: there is no three-way merge, so a generated file edited by hand (or an existing file nobody recorded) is refused and the run exits 1 after finishing the other files, as Python does; the output directory must be inside the project, so every manifest key is - project-relative; a named run (`cargo meta gen Order`) regenerates the whole files of the named - objects and their crate's manifest files rather than merging; and there is no `verify`, + project-relative; a named run (`cargo meta gen Order`) regenerates every file of the crates + that contain the named objects rather than merging; and there is no `verify`, `eject`, template or client generator yet. Relationships, projections and reports are not emitted. Nothing is published. diff --git a/server/rust/metaobjects-codegen/src/entity.rs b/server/rust/metaobjects-codegen/src/entity.rs index 3688c53200..1c8c089a16 100644 --- a/server/rust/metaobjects-codegen/src/entity.rs +++ b/server/rust/metaobjects-codegen/src/entity.rs @@ -36,6 +36,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use metaobjects::loader::owner_candidate_keys; use metaobjects::node::{NodeId, PACKAGE_SEP, Tree}; use serde_json::Value; @@ -347,8 +348,8 @@ impl Plan { ))); } Some(r) => { - let target = resolve_object_ref(&structs, &by_key, r, &owner_pkg) - .ok_or_else(|| { + let target = + resolve_object_ref(&by_key, r, &owner_pkg).ok_or_else(|| { unsupported(format!( "{what} refers to {r}, which is not a concrete entity or value object the entity generator emits" )) @@ -362,8 +363,8 @@ impl Plan { }, "map" => { let value = if let Some(r) = str_attr(tree, f, "objectRef") { - let target = resolve_object_ref(&structs, &by_key, r, &owner_pkg) - .ok_or_else(|| { + let target = + resolve_object_ref(&by_key, r, &owner_pkg).ok_or_else(|| { unsupported(format!( "{what} is a map of {r}, which is not a concrete entity or value object the entity generator emits" )) @@ -595,19 +596,36 @@ impl Plan { } else { let mut picked = HashSet::new(); for name in entities { - let hit = self.structs.iter().position(|s| { - s.key == *name || s.key.rsplit(PACKAGE_SEP).next() == Some(name.as_str()) - }); - match hit { - Some(i) => { - picked.insert(i); - } - None => { + let hits: Vec = self + .structs + .iter() + .enumerate() + .filter(|(_, s)| { + s.key == *name || s.key.rsplit(PACKAGE_SEP).next() == Some(name.as_str()) + }) + .map(|(i, _)| i) + .collect(); + match hits.as_slice() { + [] => { return Err(GenError::new( ERR_UNSUPPORTED, format!("no entity or value object named {name}"), )); } + [only] => { + picked.insert(*only); + } + many => { + let keys: Vec<&str> = + many.iter().map(|&i| self.structs[i].key.as_str()).collect(); + return Err(GenError::new( + ERR_NAME_COLLISION, + format!( + "{name} names more than one entity or value object ({}); name one by its full package-qualified key", + keys.join(", ") + ), + )); + } } } Some(picked) @@ -649,22 +667,18 @@ impl Plan { let mut exports = vec![s.type_name.clone()]; exports.extend(s.enums.iter().map(|e| e.type_name.clone())); lib_items.push((module.clone(), exports)); - if selected.as_ref().is_none_or(|sel| sel.contains(&i)) { - files.push(EmittedFile::new( - format!("{cname}/src/{module}.rs"), - struct_file(s, cname, &q), - )); - } + files.push(EmittedFile::new( + format!("{cname}/src/{module}.rs"), + struct_file(s, cname, &q), + )); } for (_, e) in &c.shared_enums { let module = module_name(&e.type_name); lib_items.push((module.clone(), vec![e.type_name.clone()])); - if selected.is_none() { - files.push(EmittedFile::new( - format!("{cname}/src/{module}.rs"), - enum_file(e), - )); - } + files.push(EmittedFile::new( + format!("{cname}/src/{module}.rs"), + enum_file(e), + )); } lib_items.sort(); files.push(EmittedFile::new( @@ -690,25 +704,15 @@ fn ty_ref(ty: &Ty) -> Option<&TypeRef> { } } -/// The struct an `@objectRef` names: the canonical spelling is `pkg::Name`, or `::Name` for a -/// package-less target; a bare name is also tried in the referrer's own package. -fn resolve_object_ref( - structs: &[StructPlan], - by_key: &HashMap, - r: &str, - owner_pkg: &str, -) -> Option { - let _ = structs; - let bare = r.strip_prefix(PACKAGE_SEP).unwrap_or(r); - if let Some(&i) = by_key.get(bare) { - return Some(i); - } - if !owner_pkg.is_empty() - && let Some(&i) = by_key.get(&format!("{owner_pkg}{PACKAGE_SEP}{bare}")) - { - return Some(i); - } - None +/// The struct an `@objectRef` names, bound by the same candidates in the same order as the +/// loader binds it (`ObjectIndex::resolve` over [`owner_candidate_keys`]): `::Name` +/// package-less, `..::Name` parent-relative, `pkg::Name` exact, and a bare `Name` the +/// referrer's own package first and the root level second. +fn resolve_object_ref(by_key: &HashMap, r: &str, owner_pkg: &str) -> Option { + owner_candidate_keys(r, owner_pkg) + .ok()? + .iter() + .find_map(|k| by_key.get(k).copied()) } /// Two fields of one struct must not become one Rust field. diff --git a/server/rust/metaobjects-codegen/src/fingerprint.rs b/server/rust/metaobjects-codegen/src/fingerprint.rs index 463942f055..c3c6da4d8b 100644 --- a/server/rust/metaobjects-codegen/src/fingerprint.rs +++ b/server/rust/metaobjects-codegen/src/fingerprint.rs @@ -216,7 +216,6 @@ pub fn write_stored( let mut out = Map::new(); out.insert("format".into(), Value::from(FINGERPRINT_FORMAT)); out.insert("fingerprint".into(), Value::from(key)); - out.insert("extras".into(), Value::Array(Vec::new())); out.insert( "outputs".into(), Value::Object( @@ -226,7 +225,6 @@ pub fn write_stored( .collect(), ), ); - out.insert("untracked".into(), Value::Array(Vec::new())); let mut text = serde_json::to_string_pretty(&Value::Object(out)).expect("a plain map serializes"); text.push('\n'); diff --git a/server/rust/metaobjects-codegen/tests/compile.rs b/server/rust/metaobjects-codegen/tests/compile.rs index 4f26568fed..9c33f9adcf 100644 --- a/server/rust/metaobjects-codegen/tests/compile.rs +++ b/server/rust/metaobjects-codegen/tests/compile.rs @@ -38,6 +38,35 @@ fn generate(project: &Scratch) { run(&opts, &generators).unwrap_or_else(|e| panic!("gen failed: {e}")); } +fn copy_tree(from: &Path, to: &Path) { + if from.is_dir() { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + copy_tree(&entry.path(), &to.join(entry.file_name())); + } + } else { + std::fs::copy(from, to).unwrap(); + } +} + +/// A scratch workspace holding a copy of `from`'s `generated` tree, pinned to the +/// repository's lockfile so `--offline` resolves the same serde. +fn locked_ws(tag: &str, from: &Path) -> Scratch { + let ws = Scratch::new(tag); + copy_tree(&from.join("generated"), &ws.path().join("out")); + ws.write( + "Cargo.toml", + "[workspace]\nresolver = \"2\"\nmembers = [\"out/*\"]\n", + ); + std::fs::copy( + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../Cargo.lock"), + ws.path().join("Cargo.lock"), + ) + .unwrap(); + ws +} + const PROBE_MAIN: &str = r#" use shop::{Address, Category, Currency, Order, OrderStatus}; use shop_billing::Invoice; @@ -97,26 +126,8 @@ fn generated_crates_compile_are_formatted_and_round_trip_through_serde() { generate(&fitness); let ws = Scratch::new("compile-ws"); - let copy = |from: &Path, to: &Path| { - std::fs::create_dir_all(to).unwrap(); - for entry in std::fs::read_dir(from).unwrap() { - let entry = entry.unwrap(); - copy_tree(&entry.path(), &to.join(entry.file_name())); - } - }; - fn copy_tree(from: &Path, to: &Path) { - if from.is_dir() { - std::fs::create_dir_all(to).unwrap(); - for entry in std::fs::read_dir(from).unwrap() { - let entry = entry.unwrap(); - copy_tree(&entry.path(), &to.join(entry.file_name())); - } - } else { - std::fs::copy(from, to).unwrap(); - } - } - copy(&shop.path().join("generated"), &ws.path().join("shop-out")); - copy( + copy_tree(&shop.path().join("generated"), &ws.path().join("shop-out")); + copy_tree( &fitness.path().join("generated"), &ws.path().join("fitness-out"), ); @@ -187,3 +198,30 @@ fn generated_crates_compile_are_formatted_and_round_trip_through_serde() { .starts_with(r#"{"id":9,"order":{"id":7,"#) ); } + +#[test] +fn a_named_first_run_leaves_a_crate_the_real_compiler_accepts() { + // The regression: a named run on a never-generated project used to write lib.rs + // declaring every module of the crate while emitting only the named struct's file, + // so the crate could not build. The oracle is `cargo check` itself: the crate the + // run leaves behind must compile. + let p = Scratch::project("compile-named", &shop_files()); + let generators: Vec> = vec![Box::new(EntityGenerator)]; + let mut opts = RunOptions::new(p.path()); + opts.out_dir = PathBuf::from("generated"); + opts.entities = vec!["Order".to_string()]; + run(&opts, &generators).unwrap_or_else(|e| panic!("named gen failed: {e}")); + // The whole crate came out: the shared enum beside the named struct, and nothing + // of the crate that holds no named object. + assert!(p.exists("generated/shop/src/currency.rs")); + assert!(p.exists("generated/shop/src/order.rs")); + assert!(!p.exists("generated/shop_billing")); + + let ws = locked_ws("compile-named-ws", p.path()); + let check = cargo(ws.path(), &["check", "--offline", "--workspace", "-q"]); + assert!( + check.status.success(), + "cargo check failed on a named first run's crate:\n{}", + String::from_utf8_lossy(&check.stderr) + ); +} diff --git a/server/rust/metaobjects-codegen/tests/entity_edges.rs b/server/rust/metaobjects-codegen/tests/entity_edges.rs index c120a494d3..752e90e3b9 100644 --- a/server/rust/metaobjects-codegen/tests/entity_edges.rs +++ b/server/rust/metaobjects-codegen/tests/entity_edges.rs @@ -11,12 +11,20 @@ use metaobjects_codegen::project::load_project; use metaobjects_codegen::{EntityGenerator, Generator}; fn generate(files: &[(&str, &str)]) -> Result, GenError> { + generate_named(files, &[]) +} + +fn generate_named( + files: &[(&str, &str)], + entities: &[&str], +) -> Result, GenError> { let project = Scratch::project("edges", files); let loaded = load_project(project.path(), None, false).expect("the model loads clean"); + let names: Vec = entities.iter().map(|e| e.to_string()).collect(); let ctx = GenContext { tree: &loaded.result.tree, root: loaded.result.root, - entities: &[], + entities: &names, }; EntityGenerator .generate(&ctx) @@ -121,6 +129,95 @@ fn a_packaged_object_may_refer_to_a_package_less_one() { assert!(out["app/Cargo.toml"].contains("model = { path = \"../model\" }")); } +#[test] +fn a_bare_object_ref_binds_the_own_package_first_like_the_loader() { + // The loader's candidate order (ADR-0059 R2): from `app`, a bare `Foo` is `app::Foo` + // first and the package-less `Foo` second. The oracle is the loader itself: it + // validates the ref against `app::Foo`, so the generator must emit the same struct. + let root = model( + "", + r#"{ "object.value": { "name": "Foo", "children": [ { "field.long": { "name": "cents" } } ] } }"#, + ); + let app = model( + "app", + r#"{ "object.value": { "name": "Foo", "children": [ { "field.string": { "name": "label" } } ] } }, + { "object.entity": { "name": "Bill", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.object": { "name": "due", "@objectRef": "Foo" } } + ] } }"#, + ); + let out = generate(&[ + ("metaobjects/meta.root.json", &root), + ("metaobjects/meta.app.json", &app), + ]) + .unwrap(); + assert!( + out["app/src/bill.rs"].contains("pub due: Option"), + "{}", + out["app/src/bill.rs"] + ); + assert!( + !out["app/Cargo.toml"].contains("model = { path"), + "the ref stays in the app crate: {}", + out["app/Cargo.toml"] + ); + assert!( + out["app/src/foo.rs"].contains("pub label"), + "the app crate's Foo is app::Foo, not the package-less one: {}", + out["app/src/foo.rs"] + ); +} + +#[test] +fn a_parent_relative_object_ref_resolves_like_the_loader() { + // `..::Foo` from `a::b` is `a::Foo` in the loader (`ObjectIndex::resolve`); the + // generator must accept the same spelling, not refuse it. + let a = model( + "a", + r#"{ "object.value": { "name": "Foo", "children": [ { "field.string": { "name": "label" } } ] } }"#, + ); + let b = model( + "a::b", + r#"{ "object.entity": { "name": "Bill", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.object": { "name": "due", "@objectRef": "..::Foo" } } + ] } }"#, + ); + let out = generate(&[ + ("metaobjects/meta.a.json", &a), + ("metaobjects/meta.b.json", &b), + ]) + .unwrap(); + assert!( + out["a_b/src/bill.rs"].contains("pub due: Option"), + "{}", + out["a_b/src/bill.rs"] + ); + assert!(out["a_b/Cargo.toml"].contains("a = { path = \"../a\" }")); +} + +#[test] +fn a_bare_entity_name_that_matches_two_objects_is_an_error_not_a_guess() { + let root = model( + "", + r#"{ "object.value": { "name": "Foo", "children": [ { "field.long": { "name": "cents" } } ] } }"#, + ); + let app = model( + "app", + r#"{ "object.value": { "name": "Foo", "children": [ { "field.string": { "name": "label" } } ] } }"#, + ); + let files: &[(&str, &str)] = &[ + ("metaobjects/meta.root.json", &root), + ("metaobjects/meta.app.json", &app), + ]; + let e = generate_named(files, &["Foo"]).unwrap_err(); + assert_eq!(e.code, "ERR_NAME_COLLISION"); + assert!(e.message.contains("app::Foo"), "{}", e.message); + assert!(e.message.contains("more than one"), "{}", e.message); +} + #[test] fn two_enum_members_that_become_one_variant_are_an_error() { let m = model( diff --git a/server/rust/metaobjects-codegen/tests/run_engine.rs b/server/rust/metaobjects-codegen/tests/run_engine.rs index f1ac756f9a..016b433d5f 100644 --- a/server/rust/metaobjects-codegen/tests/run_engine.rs +++ b/server/rust/metaobjects-codegen/tests/run_engine.rs @@ -216,6 +216,20 @@ fn naming_an_entity_limits_the_run_and_never_skips_or_stores_a_key() { ); } +#[test] +fn a_named_run_emits_every_file_of_the_selected_crate_and_nothing_of_the_others() { + let p = Scratch::project("named-crate", &shop_files()); + gen_ok(&p); + std::fs::remove_file(p.path().join("generated/shop/src/currency.rs")).unwrap(); + std::fs::remove_file(p.path().join("generated/shop_billing/src/invoice.rs")).unwrap(); + let r = gen_with(&p, |o| o.entities = vec!["Order".to_string()]).unwrap(); + // `Order`'s crate is the unit: its shared enum file comes back, the untouched + // `shop_billing` crate does not. + assert!(p.exists("generated/shop/src/currency.rs")); + assert!(!p.exists("generated/shop_billing/src/invoice.rs")); + assert_eq!(r.files.created, 1, "{:?}", r.files); +} + #[test] fn a_load_error_stops_the_run_before_anything_is_written() { let p = Scratch::project("bad", &[("metaobjects/meta.bad.json", "{ not json")]); From d07b83871fe3ce9dfd61d0d42366fa862cdfccb4 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 19 Nov 2026 00:01:10 -0500 Subject: [PATCH 03/13] no-mistakes(review): named-run crate selection includes transitive dep crates --- CHANGELOG.md | 3 +- server/rust/metaobjects-codegen/src/entity.rs | 30 ++++++- .../rust/metaobjects-codegen/tests/compile.rs | 78 +++++++++++++++++++ .../metaobjects-codegen/tests/run_engine.rs | 14 ++++ 4 files changed, 121 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 27622f7ec5..515246436e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,7 +67,8 @@ here.** existing file nobody recorded) is refused and the run exits 1 after finishing the other files, as Python does; the output directory must be inside the project, so every manifest key is project-relative; a named run (`cargo meta gen Order`) regenerates every file of the crates - that contain the named objects rather than merging; and there is no `verify`, + that contain the named objects, plus the transitive closure of the crates those depend on, + rather than merging; and there is no `verify`, `eject`, template or client generator yet. Relationships, projections and reports are not emitted. Nothing is published. diff --git a/server/rust/metaobjects-codegen/src/entity.rs b/server/rust/metaobjects-codegen/src/entity.rs index 1c8c089a16..668b3fa2c1 100644 --- a/server/rust/metaobjects-codegen/src/entity.rs +++ b/server/rust/metaobjects-codegen/src/entity.rs @@ -630,12 +630,36 @@ impl Plan { } Some(picked) }; + // A named run emits every file of every crate that contains a selected object, plus + // the transitive closure of the crates those depend on: a selected crate's manifest + // declares a path dependency on every crate its fields reference, so a dependency + // crate left out would leave output `cargo check` cannot build. Unchanged bytes are + // never rewritten, so re-emitting a dependency crate costs nothing. + let selected_crates: Option> = selected.as_ref().map(|sel| { + let mut chosen: HashSet<&str> = self + .crates + .iter() + .filter(|(_, c)| c.structs.iter().any(|i| sel.contains(i))) + .map(|(name, _)| name.as_str()) + .collect(); + let mut queue: Vec<&str> = chosen.iter().copied().collect(); + while let Some(name) = queue.pop() { + if let Some(c) = self.crates.get(name) { + for dep in &c.deps { + if chosen.insert(dep.as_str()) { + queue.push(dep.as_str()); + } + } + } + } + chosen + }); let mut files = Vec::new(); for (cname, c) in &self.crates { - let crate_selected = selected + if !selected_crates .as_ref() - .is_none_or(|sel| c.structs.iter().any(|i| sel.contains(i))); - if !crate_selected { + .is_none_or(|sel| sel.contains(cname.as_str())) + { continue; } files.push(EmittedFile::new( diff --git a/server/rust/metaobjects-codegen/tests/compile.rs b/server/rust/metaobjects-codegen/tests/compile.rs index 9c33f9adcf..57e58930fa 100644 --- a/server/rust/metaobjects-codegen/tests/compile.rs +++ b/server/rust/metaobjects-codegen/tests/compile.rs @@ -225,3 +225,81 @@ fn a_named_first_run_leaves_a_crate_the_real_compiler_accepts() { String::from_utf8_lossy(&check.stderr) ); } + +#[test] +fn a_named_first_run_across_a_crate_dependency_leaves_a_buildable_workspace() { + // `Invoice` lives in `shop_billing`, whose manifest declares a path dependency on the + // `shop` crate (Invoice.order and Invoice.currency both reach into `shop`), so the run + // must emit that dependency crate too or its own output cannot build. The oracle is + // `cargo check` itself. + let p = Scratch::project("compile-named-dep", &shop_files()); + let generators: Vec> = vec![Box::new(EntityGenerator)]; + let mut opts = RunOptions::new(p.path()); + opts.out_dir = PathBuf::from("generated"); + opts.entities = vec!["Invoice".to_string()]; + run(&opts, &generators).unwrap_or_else(|e| panic!("named gen failed: {e}")); + assert!(p.exists("generated/shop_billing/src/invoice.rs")); + assert!( + p.exists("generated/shop/src/order.rs"), + "the dependency crate came out too" + ); + + let ws = locked_ws("compile-named-dep-ws", p.path()); + let check = cargo(ws.path(), &["check", "--offline", "--workspace", "-q"]); + assert!( + check.status.success(), + "cargo check failed on a named first run across a crate dependency:\n{}", + String::from_utf8_lossy(&check.stderr) + ); +} + +#[test] +fn a_named_first_run_follows_a_three_deep_crate_dependency_chain() { + // A depends on B depends on C, one crate each; naming an object of A must bring out + // all three crates, or the chain's middle manifest points at a crate that is not there. + let a = r#"{ "metadata.root": { "package": "chain::a", "children": [ + { "object.entity": { "name": "A", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.object": { "name": "b", "@required": true, "@objectRef": "chain::b::B" } } + ] } } ] } }"#; + let b = r#"{ "metadata.root": { "package": "chain::b", "children": [ + { "object.entity": { "name": "B", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "field.object": { "name": "c", "@required": true, "@objectRef": "chain::c::C" } } + ] } } ] } }"#; + let c = r#"{ "metadata.root": { "package": "chain::c", "children": [ + { "object.entity": { "name": "C", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } + ] } } ] } }"#; + let p = Scratch::project( + "compile-chain", + &[ + ("metaobjects/meta.chain-a.json", a), + ("metaobjects/meta.chain-b.json", b), + ("metaobjects/meta.chain-c.json", c), + ], + ); + let generators: Vec> = vec![Box::new(EntityGenerator)]; + let mut opts = RunOptions::new(p.path()); + opts.out_dir = PathBuf::from("generated"); + opts.entities = vec!["A".to_string()]; + run(&opts, &generators).unwrap_or_else(|e| panic!("named gen failed: {e}")); + for crate_file in [ + "generated/chain_a/src/a.rs", + "generated/chain_b/src/b.rs", + "generated/chain_c/src/c.rs", + ] { + assert!(p.exists(crate_file), "{crate_file} is missing"); + } + + let ws = locked_ws("compile-chain-ws", p.path()); + let check = cargo(ws.path(), &["check", "--offline", "--workspace", "-q"]); + assert!( + check.status.success(), + "cargo check failed on a named first run's dependency chain:\n{}", + String::from_utf8_lossy(&check.stderr) + ); +} diff --git a/server/rust/metaobjects-codegen/tests/run_engine.rs b/server/rust/metaobjects-codegen/tests/run_engine.rs index 016b433d5f..781c3432a8 100644 --- a/server/rust/metaobjects-codegen/tests/run_engine.rs +++ b/server/rust/metaobjects-codegen/tests/run_engine.rs @@ -230,6 +230,20 @@ fn a_named_run_emits_every_file_of_the_selected_crate_and_nothing_of_the_others( assert_eq!(r.files.created, 1, "{:?}", r.files); } +#[test] +fn a_named_run_restores_a_deleted_file_of_a_dependency_crate() { + // `Invoice` sits in `shop_billing`, whose manifest depends on the `shop` crate; the + // shared enum the emitted crate imports lives there, so a named run of `Invoice` + // must bring that dependency crate's deleted file back. + let p = Scratch::project("named-dep", &shop_files()); + gen_ok(&p); + std::fs::remove_file(p.path().join("generated/shop/src/currency.rs")).unwrap(); + tick(); + let r = gen_with(&p, |o| o.entities = vec!["Invoice".to_string()]).unwrap(); + assert!(p.exists("generated/shop/src/currency.rs")); + assert_eq!(r.files.created, 1, "{:?}", r.files); +} + #[test] fn a_load_error_stops_the_run_before_anything_is_written() { let p = Scratch::project("bad", &[("metaobjects/meta.bad.json", "{ not json")]); From 6b1944596c4d975610d73c375be88b38966055d7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 19 Nov 2026 00:06:44 -0500 Subject: [PATCH 04/13] no-mistakes(review): accept ::Name to select package-less objects in named runs --- server/rust/metaobjects-codegen/src/entity.rs | 11 ++++++++--- server/rust/metaobjects-codegen/tests/entity_edges.rs | 9 +++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/server/rust/metaobjects-codegen/src/entity.rs b/server/rust/metaobjects-codegen/src/entity.rs index 668b3fa2c1..7bee7eb7db 100644 --- a/server/rust/metaobjects-codegen/src/entity.rs +++ b/server/rust/metaobjects-codegen/src/entity.rs @@ -596,12 +596,17 @@ impl Plan { } else { let mut picked = HashSet::new(); for name in entities { + let exact = name.strip_prefix(PACKAGE_SEP); let hits: Vec = self .structs .iter() .enumerate() - .filter(|(_, s)| { - s.key == *name || s.key.rsplit(PACKAGE_SEP).next() == Some(name.as_str()) + .filter(|(_, s)| match exact { + Some(key) => s.key == key, + None => { + s.key == *name + || s.key.rsplit(PACKAGE_SEP).next() == Some(name.as_str()) + } }) .map(|(i, _)| i) .collect(); @@ -621,7 +626,7 @@ impl Plan { return Err(GenError::new( ERR_NAME_COLLISION, format!( - "{name} names more than one entity or value object ({}); name one by its full package-qualified key", + "{name} names more than one entity or value object ({}); name one by its full key, `::Name` for a package-less object or `pkg::Name`", keys.join(", ") ), )); diff --git a/server/rust/metaobjects-codegen/tests/entity_edges.rs b/server/rust/metaobjects-codegen/tests/entity_edges.rs index 752e90e3b9..6cf5f09ecd 100644 --- a/server/rust/metaobjects-codegen/tests/entity_edges.rs +++ b/server/rust/metaobjects-codegen/tests/entity_edges.rs @@ -216,6 +216,15 @@ fn a_bare_entity_name_that_matches_two_objects_is_an_error_not_a_guess() { assert_eq!(e.code, "ERR_NAME_COLLISION"); assert!(e.message.contains("app::Foo"), "{}", e.message); assert!(e.message.contains("more than one"), "{}", e.message); + assert!(e.message.contains("::Name"), "{}", e.message); + + let package_less = + generate_named(files, &["::Foo"]).expect("::Foo selects the package-less Foo"); + let packaged = generate_named(files, &["app::Foo"]).expect("app::Foo selects the packaged Foo"); + assert!(package_less.values().any(|c| c.contains("pub cents:"))); + assert!(!package_less.values().any(|c| c.contains("pub label:"))); + assert!(packaged.values().any(|c| c.contains("pub label:"))); + assert!(!packaged.values().any(|c| c.contains("pub cents:"))); } #[test] From 03d44f475ccb40a1a17ed0c99169d8424ec431f2 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 19 Nov 2026 00:08:55 -0500 Subject: [PATCH 05/13] no-mistakes(review): reject project-root out dir; skip refused stale warning --- server/rust/metaobjects-codegen/src/engine.rs | 22 ++++++++++--------- .../metaobjects-codegen/tests/run_engine.rs | 13 +++++++++++ 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index 334ec68f95..1e9b6b359f 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -229,6 +229,15 @@ pub fn run(opts: &RunOptions, generators: &[Box]) -> Result]) -> Result = HashSet::new(); let mut written_hashes: BTreeMap = BTreeMap::new(); for f in &emitted { - let key = if out_rel.is_empty() { - f.path.clone() - } else { - format!("{out_rel}/{}", f.path) - }; + let key = format!("{out_rel}/{}", f.path); let path = project_root.join(&key); let fresh_hash = content_hash(&f.content); match std::fs::read(&path) { @@ -386,11 +391,7 @@ pub fn run(opts: &RunOptions, generators: &[Box]) -> Result = manifest .records() .filter(|(k, _)| k.starts_with(&prefix) && !written_hashes.contains_key(*k)) @@ -405,6 +406,7 @@ pub fn run(opts: &RunOptions, generators: &[Box]) -> Result {} Ok(_) => warnings.push(format!( "{key} is no longer generated but differs from what the last run wrote, so it was kept" )), diff --git a/server/rust/metaobjects-codegen/tests/run_engine.rs b/server/rust/metaobjects-codegen/tests/run_engine.rs index 781c3432a8..6679095a55 100644 --- a/server/rust/metaobjects-codegen/tests/run_engine.rs +++ b/server/rust/metaobjects-codegen/tests/run_engine.rs @@ -260,6 +260,19 @@ fn the_output_directory_must_be_inside_the_project() { assert!(e.to_string().contains("ERR_OUT_DIR_OUTSIDE_PROJECT"), "{e}"); } +#[test] +fn the_project_root_is_not_an_output_directory_and_nothing_is_written() { + let p = Scratch::project("root-out", &shop_files()); + for out in [".", ""] { + let e = gen_with(&p, |o| o.out_dir = PathBuf::from(out)).expect_err("the project root"); + assert!(e.to_string().contains("ERR_OUT_DIR_OUTSIDE_PROJECT"), "{e}"); + assert!(e.to_string().contains("sub-directory"), "{e}"); + } + assert!(!p.exists(".metaobjects/.gen-state")); + assert!(!p.exists("shop")); + assert!(!p.exists("Cargo.toml")); +} + #[test] fn two_name_collisions_and_a_crate_cycle_are_reported_not_emitted() { // Two objects that become one Rust type. From 78526631f5155530f6c5cceb8caf9c621defb833 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 19 Nov 2026 00:13:30 -0500 Subject: [PATCH 06/13] no-mistakes(review): bind @objectRef via the loader's resolver; fix help --- server/rust/metaobjects-cli/src/lib.rs | 6 +- server/rust/metaobjects-codegen/src/engine.rs | 1 - server/rust/metaobjects-codegen/src/entity.rs | 35 ++++++------ .../metaobjects-codegen/tests/entity_edges.rs | 56 +++++++++++++++++++ 4 files changed, 77 insertions(+), 21 deletions(-) diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index 2754b6b9cf..5c995d64a7 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -26,7 +26,7 @@ OPTIONS: --project The project root (the directory holding .metaobjects/config.json). Default: the nearest one at or above the current directory. --out Where the crates are written, relative to the project root and - inside it. Default: generated + a sub-directory of it. Default: generated --generators Run only these generators. Available: entity --strict Load strictly: an attribute no provider declares is an error. --force Render and compare even when nothing changed. @@ -34,8 +34,8 @@ OPTIONS: -h, --help Print this help. -V, --version Print the version. -ENTITY names limit the run to the packages that contain them. Such a run never skips and -never stores the skip key. +ENTITY names limit the run to the crates that contain them plus the crates those depend on. +Such a run never skips and never stores the skip key. EXIT STATUS: 0 success; 1 the run failed; 2 usage error. "; diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index 1e9b6b359f..39fdcbbf06 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -406,7 +406,6 @@ pub fn run(opts: &RunOptions, generators: &[Box]) -> Result {} Ok(_) => warnings.push(format!( "{key} is no longer generated but differs from what the last run wrote, so it was kept" )), diff --git a/server/rust/metaobjects-codegen/src/entity.rs b/server/rust/metaobjects-codegen/src/entity.rs index 7bee7eb7db..c12bdf614d 100644 --- a/server/rust/metaobjects-codegen/src/entity.rs +++ b/server/rust/metaobjects-codegen/src/entity.rs @@ -36,8 +36,8 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; -use metaobjects::loader::owner_candidate_keys; use metaobjects::node::{NodeId, PACKAGE_SEP, Tree}; +use metaobjects::validate::util::ObjectIndex; use serde_json::Value; use crate::generator::{ @@ -241,7 +241,8 @@ impl Plan { fn build(tree: &Tree, root: NodeId) -> Result { // Every concrete entity and value object, in model order. let mut structs: Vec = Vec::new(); - let mut by_key: HashMap = HashMap::new(); + let mut by_node: HashMap = HashMap::new(); + let index = ObjectIndex::build(tree, root); for &id in tree.own_children(root) { let n = tree.node(id); if n.type_name != "object" @@ -251,7 +252,7 @@ impl Plan { continue; } let pkg = tree.effective_package(id); - by_key.insert(tree.resolution_key(id), structs.len()); + by_node.insert(id, structs.len()); structs.push(StructPlan { node: id, key: tree.resolution_key(id), @@ -303,7 +304,6 @@ impl Plan { .filter_map(|&c| tree.attr(c, "fields").and_then(Value::as_array)) .flat_map(|a| a.iter().filter_map(Value::as_str).map(str::to_string)) .collect(); - let owner_pkg = tree.effective_package(node); let mut fields: Vec = Vec::new(); let mut enums: Vec = Vec::new(); for &f in tree.children(node).iter() { @@ -348,8 +348,7 @@ impl Plan { ))); } Some(r) => { - let target = - resolve_object_ref(&by_key, r, &owner_pkg).ok_or_else(|| { + let target = bound_struct(&index, &by_node, tree, f).ok_or_else(|| { unsupported(format!( "{what} refers to {r}, which is not a concrete entity or value object the entity generator emits" )) @@ -363,8 +362,7 @@ impl Plan { }, "map" => { let value = if let Some(r) = str_attr(tree, f, "objectRef") { - let target = - resolve_object_ref(&by_key, r, &owner_pkg).ok_or_else(|| { + let target = bound_struct(&index, &by_node, tree, f).ok_or_else(|| { unsupported(format!( "{what} is a map of {r}, which is not a concrete entity or value object the entity generator emits" )) @@ -733,15 +731,18 @@ fn ty_ref(ty: &Ty) -> Option<&TypeRef> { } } -/// The struct an `@objectRef` names, bound by the same candidates in the same order as the -/// loader binds it (`ObjectIndex::resolve` over [`owner_candidate_keys`]): `::Name` -/// package-less, `..::Name` parent-relative, `pkg::Name` exact, and a bare `Name` the -/// referrer's own package first and the root level second. -fn resolve_object_ref(by_key: &HashMap, r: &str, owner_pkg: &str) -> Option { - owner_candidate_keys(r, owner_pkg) - .ok()? - .iter() - .find_map(|k| by_key.get(k).copied()) +/// The struct an `@objectRef` binds to, resolved by the loader's own resolver: the package +/// that declared the attribute (up the `extends` chain) decides, and the first top-level +/// object it names wins, emitted or not. +fn bound_struct( + index: &ObjectIndex, + by_node: &HashMap, + tree: &Tree, + field: NodeId, +) -> Option { + index + .ref_target(tree, field, "objectRef") + .and_then(|t| by_node.get(&t).copied()) } /// Two fields of one struct must not become one Rust field. diff --git a/server/rust/metaobjects-codegen/tests/entity_edges.rs b/server/rust/metaobjects-codegen/tests/entity_edges.rs index 6cf5f09ecd..e3e6ee2ac7 100644 --- a/server/rust/metaobjects-codegen/tests/entity_edges.rs +++ b/server/rust/metaobjects-codegen/tests/entity_edges.rs @@ -169,6 +169,62 @@ fn a_bare_object_ref_binds_the_own_package_first_like_the_loader() { ); } +#[test] +fn an_inherited_object_ref_binds_from_the_package_that_declared_it() { + // ADR-0059 R3: `Base.addr` was declared in `base`, so its bare `Address` is `base::Address` + // for every struct that inherits the field, whatever package that struct lives in. + let base = model( + "base", + r#"{ "object.value": { "name": "Address", "children": [ { "field.string": { "name": "street" } } ] } }, + { "object.value": { "name": "Base", "abstract": true, "children": [ + { "field.object": { "name": "addr", "@objectRef": "Address" } } ] } }"#, + ); + let app = model( + "app", + r#"{ "object.value": { "name": "Address", "children": [ { "field.string": { "name": "label" } } ] } }, + { "object.value": { "name": "Thing", "extends": "base::Base" } }"#, + ); + let out = generate(&[ + ("metaobjects/meta.base.json", &base), + ("metaobjects/meta.app.json", &app), + ]) + .unwrap(); + assert!( + out["app/src/thing.rs"].contains("base::Address"), + "{}", + out["app/src/thing.rs"] + ); + assert!( + out["app/Cargo.toml"].contains("base = { path"), + "{}", + out["app/Cargo.toml"] + ); +} + +#[test] +fn an_object_ref_the_loader_binds_to_an_abstract_object_is_refused_not_redirected() { + // From `app`, a bare `Foo` is `app::Foo` first. That one is abstract, so nothing is + // emitted for it, and the generator must say so instead of falling through to the + // package-less `Foo` the loader did not choose. + let root = model( + "", + r#"{ "object.value": { "name": "Foo", "children": [ { "field.long": { "name": "cents" } } ] } }"#, + ); + let app = model( + "app", + r#"{ "object.value": { "name": "Foo", "abstract": true, "children": [ { "field.string": { "name": "label" } } ] } }, + { "object.value": { "name": "Bill", "children": [ + { "field.object": { "name": "due", "@objectRef": "Foo" } } ] } }"#, + ); + let e = generate(&[ + ("metaobjects/meta.root.json", &root), + ("metaobjects/meta.app.json", &app), + ]) + .unwrap_err(); + assert!(e.message.contains("app::Bill.due"), "{}", e.message); + assert!(e.message.contains("not a concrete"), "{}", e.message); +} + #[test] fn a_parent_relative_object_ref_resolves_like_the_loader() { // `..::Foo` from `a::b` is `a::Foo` in the loader (`ObjectIndex::resolve`); the From 62a46f33f7c6b1ac741b5f60fcc5f74cbc2b6c91 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Thu, 19 Nov 2026 00:24:40 -0500 Subject: [PATCH 07/13] no-mistakes(document): update Rust port docs for codegen --- CHANGELOG.md | 15 +++++++-------- README.md | 2 +- docs/CONFORMANCE.md | 9 +++++---- docs/features/cli.md | 1 + fixtures/codegen-skip-conformance/README.md | 1 + spec/decisions/ADR-0065-rust-is-the-sixth-port.md | 15 +++++++++------ 6 files changed, 24 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 515246436e..518106dc95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,9 +23,8 @@ here.** (the conformance ledger is empty and may only shrink). While the port is in preview, a new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; a fixture that passed and regresses still fails it, because - the ledger records how many fixtures must pass. Nothing is published and there is no codegen - or `cargo meta` command yet. Every load records how long each phase and each validation pass - took (`LoadResult::timings`; the `validate` module's ordered pass list holds the ported passes in + the ledger records how many fixtures must pass. Nothing is published. Every load records how + long each phase and each validation pass took (`LoadResult::timings`; the `validate` module's ordered pass list holds the ported passes in reference order), and `load_bench` prints the per-phase and per-pass medians, with `--write-baseline` / `--baseline` to record and compare a run — a baseline is a record to read, never a threshold, and the committed 20x baseline is a machine-local reference. A @@ -65,11 +64,11 @@ here.** the 20x fitness project, record only, and the `rust` lane prints it. Where Rust differs from the other ports, on purpose: there is no three-way merge, so a generated file edited by hand (or an existing file nobody recorded) is refused and the run exits 1 after finishing the other files, - as Python does; the output directory must be inside the project, so every manifest key is - project-relative; a named run (`cargo meta gen Order`) regenerates every file of the crates - that contain the named objects, plus the transitive closure of the crates those depend on, - rather than merging; and there is no `verify`, - `eject`, template or client generator yet. Relationships, projections and reports are not + as Python does; the output directory must be a sub-directory of the project (the project root + itself is refused), so every manifest key is project-relative; a named run (`cargo meta gen + Order`) regenerates every file of the crates that contain the named objects, plus the + transitive closure of the crates those depend on, rather than merging; and there is no + `verify`, `eject`, template or client generator yet. Relationships, projections and reports are not emitted. Nothing is published. - **Cross-port stage benchmark and Rust port documentation.** `scripts/bench-load/stages.py` runs diff --git a/README.md b/README.md index 66574809bc..587fbc3fc5 100644 --- a/README.md +++ b/README.md @@ -331,7 +331,7 @@ metaobjects/ │ ├── java/ # Java port (incl. codegen-kotlin + metadata-ktx) │ ├── csharp/ # C# port │ ├── python/ # Python port -│ └── rust/ # Rust port (preview, ADR-0065 — unpublished; no codegen yet) +│ └── rust/ # Rust port (preview, ADR-0065 — unpublished; entity generator only) │ └── client/ └── web/ # universal browser packages (React, TanStack, Angular, framework-agnostic) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 6ddbaa02f8..047c419f7c 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -69,15 +69,16 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 19 cases (14 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the `explorer.json` data spine: `meta export --effective` + `meta verify --format json` + the generated-file manifest in, one explorer document out) | 1 case (`shop`) | ✓ (the builder is TypeScript, and reads only port-neutral inputs) | — | — | — | — | -**Rust (preview, ADR-0065) is not a column yet.** The sixth port runs five corpora +**Rust (preview, ADR-0065) is not a column yet.** The sixth port runs six corpora today: `registry-conformance` (byte-identical manifest); the metamodel corpus, all 526 green, with every validation pass the TypeScript loader runs, in the same order, so `server/rust/metaobjects/tests/conformance-expected-failures.json` is empty; `yaml-conformance`, 18 of 19 (the one on `yaml-conformance-expected-failures.json`, `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); and `naming-conformance` (all of it). Those ledgers may only shrink. While the -port is in preview, a new fixture that fails in Rust and is not on the ledger prints a +cases); `naming-conformance` (all of it); and `codegen-skip-conformance` (ADR-0064), for the +cases its `gen` can meet (the rest are named with their reason in its runner). Those ledgers +may only shrink. While the port is in preview, a new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; it becomes a hard failure when the port leaves preview. A regression still fails: the ledger's `minPassing` (526) is the number of fixtures known to pass, and the run fails when fewer do. The column joins this table when @@ -397,7 +398,7 @@ Per-port runners + commands: | Kotlin | `cd server/java && mvn -pl codegen-kotlin test` (snapshot suite) | `mvn -f server/java/integration-tests-kotlin/pom.xml test` (needs Docker) | `mvn -f server/java/integration-tests-kotlin/pom.xml test -Dtest=ApiContractConformanceTest` (needs Docker) | | C# | `dotnet test` (per project) | `scripts/integration-test.sh csharp` (needs Docker) | `dotnet test server/csharp/MetaObjects.IntegrationTests/MetaObjects.IntegrationTests.csproj --filter "FullyQualifiedName~ApiContractConformanceTest"` (needs Docker) | | Python | `pytest` (per package) | `scripts/integration-test.sh python` (needs Docker) | `cd server/python && uv run --extra integration pytest tests/integration/test_api_contract.py` (needs Docker) | -| Rust (preview) | `cd server/rust && cargo test` (registry, metamodel, YAML, source-resolution and naming corpora) | — | — | +| Rust (preview) | `cd server/rust && cargo test` (registry, metamodel, YAML, source-resolution and naming corpora; the codegen suites, which run `cargo check` on generated crates) | — | — | 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/features/cli.md b/docs/features/cli.md index 35f4a755d4..cfa166fbe4 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -41,6 +41,7 @@ command surface splits in two: | Java/Kotlin codegen | Maven plugin | `mvn metaobjects:generate` (`metaobjects:generate`) | Kotlin generators run through the same goal — see below. **No `--template-spec` flag, deliberately** — `` already loads a consumer class from the project classpath, so the declarative surface is `com.metaobjects.generator.template.TemplateScopeGenerator` wired as an ordinary `` with `