diff --git a/changelog.d/rust-reference-facet.md b/changelog.d/rust-reference-facet.md new file mode 100644 index 000000000..beb13f17c --- /dev/null +++ b/changelog.d/rust-reference-facet.md @@ -0,0 +1,26 @@ +- **The Rust loader reads and enforces the reference facet** (`ref` on a `type: "attr"` entry of + a provider definition, `spec/metamodel-definitions.md`), matching the TypeScript, C# and Java + loaders. The spec reader in `providers.rs` validates the facet (refusing a bad facet, or one on + a structural child) and carries it to `AttrSchema::reference`. The registered walk enforces it + through a kind-typed symbol table: a dotted value resolves `System.child` and + `pkg::System.child`, a bare value is looked for in the referrer's own containers first, and a + value that names nothing (`ERR_REF_UNRESOLVED`), the wrong kind of node (`ERR_REF_WRONG_KIND`) + or a node of another system (the facet's own code) is refused, with `sameSystem` judged on the + path the lookup walked. The reference pass writes a canonical value as that walked path, and + keeps a value as written when its canonical spelling would not look up the same target. The + registry manifest writes `ref` only on an attribute that has one. No definition file uses the + facet yet, so no registry, manifest or generated output changes. A provider's own code that is + not in the shared catalogue keeps its spelling in `MetaError::provider_code` (`code` stays + `ERR_UNKNOWN`; `MetaError::code_name()` gives either, and the error prints under it). A + parent-relative `@references` value (`..::Address.id`) now resolves its owner instead of + reading the `..` as one. A root-level node and a same-named node in a package, declared in one + document, are now two nodes rather than one merged node, as in every other port and the + loader's cross-file merge; this closes the last ledgered `yaml-conformance` fixture + (`yaml-ref-root-escape`), so Rust passes 19 of 19. + + Upgrading: Rust `ReferenceDescriptor` is now `{ attr, facet }`. A provider that sets + `TypeDefinition::references` in code builds `ReferenceDescriptor { attr, facet: ReferenceFacet { .. } }`, + or `ReferenceFacet::of(target_type, error_code)`. `target_type` and `error_code` move onto + `ReferenceFacet` (where `error_code` is optional), and `dotted_field_path` becomes + `ReferenceFacet::field_path`. `AttrSchema` gains the field `reference` and `MetaError` the field + `provider_code`, so code that builds either with a struct literal sets them (`None`). diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 1002bfd0f..e620400f8 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -27,7 +27,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | Rust | |---|---|---|---|---|---|---|---| | [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 584 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | ✓ (584 / 584, empty ledger) | -| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | 18 / 19 (1 ledgered: `yaml-ref-root-escape`, the ADR-0059 root-level `::` rules) | +| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 19 | 19 / 19 | 19 / 19 | inherits via Java | 18 / 19 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 19 / 19 | 19 / 19 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | — | | [`fixtures/render-conformance/`](../fixtures/render-conformance/) | 26 | ✓ | ✓ | inherits via Java | ✓ | ✓ | ✓ | diff --git a/docs/ports/rust.md b/docs/ports/rust.md index a313f949a..71ae4b32d 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -618,7 +618,7 @@ outright. |---|---| | `registry-conformance` | byte-identical manifest | | `conformance` (the metamodel corpus) | **584 of 584**, and the ledger is empty | -| `yaml-conformance` | 18 of 19. The one on the ledger, `yaml-ref-root-escape`, waits for the root-level `::` reference rules of [ADR-0059](../../spec/decisions/ADR-0059-references-resolve-once-after-the-tree.md), which are reference resolution, not a validation pass. | +| `yaml-conformance` | all 19, and the ledger is empty | | `source-resolution-conformance` | all 30 cases | | `reference-source-conformance` | all 6 cases: a `reference: true` source loads so references resolve against it, a node declared only in reference files is a reference node no generator emits, and a `template.*` declared only there is refused (`ERR_REFERENCE_SOURCE_TEMPLATE`) | | `naming-conformance` | all of it | diff --git a/server/rust/metaobjects/src/errors.rs b/server/rust/metaobjects/src/errors.rs index 5601f22ec..fa6421a28 100644 --- a/server/rust/metaobjects/src/errors.rs +++ b/server/rust/metaobjects/src/errors.rs @@ -6,6 +6,7 @@ //! to the fixture. use std::fmt; +use std::sync::OnceLock; use crate::source::ErrorSource; @@ -46,6 +47,12 @@ pub const ERR_COLLECTION_NAME_COLLISION: &str = "ERR_COLLECTION_NAME_COLLISION"; pub const ERR_UNKNOWN_LIBRARY: &str = "ERR_UNKNOWN_LIBRARY"; /// A `template.*` declared only in reference sources. pub const ERR_REFERENCE_SOURCE_TEMPLATE: &str = "ERR_REFERENCE_SOURCE_TEMPLATE"; +/// The reference facet's default code for a value that names no node +/// (`spec/metamodel-definitions.md`). +pub const ERR_REF_UNRESOLVED: &str = "ERR_REF_UNRESOLVED"; +/// The reference facet's default code for a value that names a node of the wrong type +/// or subtype. +pub const ERR_REF_WRONG_KIND: &str = "ERR_REF_WRONG_KIND"; /// The code reported for a failure that carries none (a programming error in a /// provider definition, say). @@ -83,6 +90,8 @@ pub const ALL_CODES: &[&str] = &[ ERR_COLLECTION_NAME_COLLISION, ERR_UNKNOWN_LIBRARY, ERR_REFERENCE_SOURCE_TEMPLATE, + ERR_REF_UNRESOLVED, + ERR_REF_WRONG_KIND, ERR_UNKNOWN, ]; @@ -93,6 +102,10 @@ pub struct MetaError { pub message: String, /// Boxed so a `Result<_, MetaError>` stays small on the happy path. pub source: Box, + /// A loader code a provider named that this crate does not know (a reference facet's + /// `errorCode` or `wrongSystemCode`, such as `ERR_GRANT_CROSSES_SYSTEM`). `code` is then + /// [`ERR_UNKNOWN`]. `None` for a code this crate knows. + pub provider_code: Option, } impl MetaError { @@ -102,6 +115,7 @@ impl MetaError { code, message: message.into(), source: Box::new(ErrorSource::Code), + provider_code: None, } } @@ -116,13 +130,57 @@ impl MetaError { code, message: message.into(), source: Box::new(source), + provider_code: None, } } + + /// An error located in a document, under a code a provider named: a code in the shared + /// catalogue (`ERROR-CODES.json`) is used as is; any other keeps its spelling in + /// [`MetaError::provider_code`] and reports [`ERR_UNKNOWN`]. + pub fn at_provider_code(code: &str, message: impl Into, source: ErrorSource) -> Self { + let known = catalogue_code(code); + let mut e = Self::at(known.unwrap_or(ERR_UNKNOWN), message, source); + if known.is_none() { + e.provider_code = Some(code.to_string()); + } + e + } + + /// The code as its provider spelled it: [`MetaError::provider_code`] when set, else + /// [`MetaError::code`]. + pub fn code_name(&self) -> &str { + self.provider_code.as_deref().unwrap_or(self.code) + } +} + +/// `code` as the `&'static str` the shared catalogue spells it, or `None` when the +/// catalogue does not list it. The catalogue is the embedded `data/ERROR-CODES.json`. +fn catalogue_code(code: &str) -> Option<&'static str> { + static CODES: OnceLock> = OnceLock::new(); + CODES + .get_or_init(|| { + let doc: serde_json::Value = + serde_json::from_str(include_str!("../data/ERROR-CODES.json")) + .expect("data/ERROR-CODES.json is valid JSON"); + doc["codes"] + .as_object() + .map(|codes| { + codes + .keys() + // Built once per process: the catalogue's keys live as long as it. + .map(|k| &*Box::leak(k.clone().into_boxed_str())) + .collect() + }) + .unwrap_or_default() + }) + .iter() + .copied() + .find(|c| *c == code) } impl fmt::Display for MetaError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}: {}", self.code, self.message) + write!(f, "{}: {}", self.code_name(), self.message) } } diff --git a/server/rust/metaobjects/src/loader.rs b/server/rust/metaobjects/src/loader.rs index 8d5943aa9..126da5b2e 100644 --- a/server/rust/metaobjects/src/loader.rs +++ b/server/rust/metaobjects/src/loader.rs @@ -32,6 +32,8 @@ use crate::timing::{ LoadTimings, PHASE_FREEZE, PHASE_JSON, PHASE_MERGE, PHASE_READ, PHASE_REFS, PHASE_SUPERS, PHASE_TREE, PHASE_YAML, }; +use crate::validate::refs::{RefMatch, SymbolTable, facet_of}; +use crate::validate::structure::preorder; use crate::validate::util::{ObjectIndex, find_hop}; use crate::validate::{self, Ctx, Findings}; use crate::yaml::parse_yaml; @@ -290,7 +292,9 @@ impl<'r> Loader<'r> { validate::run(&ctx, &mut findings, &mut timings); errors.append(&mut findings.errors); warnings.append(&mut findings.warnings); - timings.phase(PHASE_REFS, || resolve_references(&mut tree, root, &top)); + timings.phase(PHASE_REFS, || { + resolve_references(&mut tree, root, &top, self.registry); + }); root }; // The terminal phase: the tree is complete, so it becomes read-only and its @@ -317,7 +321,7 @@ struct MergeOut { /// The package-qualified identity of a root-level node for merge matching: its own /// package, else its file's (never the merged root's). -fn root_child_key(tree: &Tree, id: NodeId) -> String { +pub(crate) fn root_child_key(tree: &Tree, id: NodeId) -> String { let n = tree.node(id); let pkg = n .package @@ -954,8 +958,12 @@ impl TopLevel { /// ADR-0059 R5: rewrite every resolved `extends` and reference attribute to its /// canonical spelling, keeping the authored value beside it. A reference that does -/// not resolve is left as written. -fn resolve_references(tree: &mut Tree, root: NodeId, top: &TopLevel) { +/// not resolve is left as written. An attribute whose schema carries the reference +/// facet is resolved by the facet's typed lookup ([`facet_rewrites`]). +fn resolve_references(tree: &mut Tree, root: NodeId, top: &TopLevel, registry: &TypeRegistry) { + for (id, name, value) in facet_rewrites(tree, root, registry) { + set_canonical_attr(tree, id, &name, value); + } let mut stack = vec![root]; while let Some(id) = stack.pop() { if id != root { @@ -966,6 +974,10 @@ fn resolve_references(tree: &mut Tree, root: NodeId, top: &TopLevel) { // ADR-0039: own — reference resolution rewrites the value this node declares, not an inherited one. .own_attrs(id) .filter(|(k, _)| is_ref_bearing_attr(type_name, k)) + .filter(|(k, _)| { + let n = tree.node(id); + facet_of(registry, &n.type_name, &n.sub_type, k).is_none() + }) .map(|(k, _)| k.clone()) .collect(); for name in names { @@ -978,6 +990,74 @@ fn resolve_references(tree: &mut Tree, root: NodeId, top: &TopLevel) { } } +/// The canonical value of every facet reference attribute a node declares itself +/// (`spec/metamodel-definitions.md`, rule 7): the target the typed lookup finds, spelled +/// as the top-level owner it was reached through plus the child names walked; a +/// `fieldPath` value keeps its field segment. A spelling that would not look up the +/// same target again keeps the value as written. Only values that change are returned. +fn facet_rewrites( + tree: &Tree, + root: NodeId, + registry: &TypeRegistry, +) -> Vec<(NodeId, String, Value)> { + let mut out = Vec::new(); + let mut symbols: Option> = None; + for id in preorder(tree, root) { + if id == root { + continue; + } + let n = tree.node(id); + // ADR-0039: own — reference resolution rewrites the value this node declares, not an inherited one. + for (name, attr) in tree.own_attrs(id) { + let Some(facet) = facet_of(registry, &n.type_name, &n.sub_type, name) else { + continue; + }; + let symbols = symbols.get_or_insert_with(|| SymbolTable::build(tree, root)); + let decl_pkg = tree.effective_package(tree.top_level_of(id)); + let canonical = |value: &str| -> Option { + let RefMatch::Found(path) = symbols.lookup(id, value, facet, &decl_pkg) else { + return None; + }; + let target = path[path.len() - 1]; + let tail: String = if facet.field_path { + split_child_tail(value).1.to_string() + } else { + path[1..] + .iter() + .map(|&p| format!("{CHILD_REF_SEP}{}", tree.node(p).name)) + .collect() + }; + let spelled = spell_ref(tree, path[0], &decl_pkg, &tail); + let again = symbols.lookup(id, &spelled, facet, &decl_pkg); + Some(match again { + RefMatch::Found(p) if p[p.len() - 1] == target => spelled, + _ => value.to_string(), + }) + }; + let new_value = match &attr.value { + Value::String(s) if !s.is_empty() => canonical(s).map(Value::String), + Value::Array(items) if items.iter().all(Value::is_string) => Some(Value::Array( + items + .iter() + .map(|v| { + let s = v.as_str().unwrap_or_default(); + (!s.is_empty()) + .then(|| canonical(s)) + .flatten() + .map_or_else(|| v.clone(), Value::String) + }) + .collect(), + )), + _ => None, + }; + if let Some(v) = new_value.filter(|v| *v != attr.value) { + out.push((id, name.clone(), v)); + } + } + } + out +} + fn resolve_one( tree: &Tree, top: &TopLevel, @@ -1121,9 +1201,13 @@ fn resolve_attr( } _ => None, }; - let Some(new_value) = new_value else { - return; - }; + if let Some(new_value) = new_value { + set_canonical_attr(tree, id, name, new_value); + } +} + +/// Rewrite an own reference attribute to its canonical value, keeping the authored one. +fn set_canonical_attr(tree: &mut Tree, id: NodeId, name: &str, new_value: Value) { // ADR-0039: own — reference resolution rewrites the value this node declares, not an inherited one. if let Some(attr) = tree.own_attr_mut(id, name) && attr.value != new_value diff --git a/server/rust/metaobjects/src/manifest.rs b/server/rust/metaobjects/src/manifest.rs index 46609c4ba..93dfa169f 100644 --- a/server/rust/metaobjects/src/manifest.rs +++ b/server/rust/metaobjects/src/manifest.rs @@ -4,7 +4,9 @@ use serde_json::{Map, Value, json}; use crate::json::{js_display, to_js_pretty}; -use crate::registry::{AttrSchema, ChildRule, ChildSubType, TypeDefinition, TypeRegistry}; +use crate::registry::{ + AttrSchema, ChildRule, ChildSubType, ReferenceFacet, TypeDefinition, TypeRegistry, +}; /// The metamodel version this build implements. pub const METAMODEL_VERSION: &str = "1.3"; @@ -53,6 +55,10 @@ fn manifest_attr(attr: &AttrSchema) -> Value { if let Some(list) = attr.ports.as_ref().filter(|v| !v.is_empty()) { m.insert("ports".into(), sorted(list)); } + // The reference facet (spec/metamodel-definitions.md), only when the attr has one. + if let Some(r) = &attr.reference { + m.insert("ref".into(), manifest_ref(r)); + } m.insert("description".into(), json!(attr.description)); for (key, val) in [ ("rules", &attr.rules), @@ -66,6 +72,30 @@ fn manifest_attr(attr: &AttrSchema) -> Value { Value::Object(m) } +/// An attr's reference facet, keys in the format's order: `targetType`, `targetSubTypes` +/// (sorted), `fieldPath` and `sameSystem` (each only when true), `errorCode` and +/// `wrongSystemCode` (each only when present). +fn manifest_ref(r: &ReferenceFacet) -> Value { + let mut m = Map::new(); + m.insert("targetType".into(), json!(r.target_type)); + if let Some(list) = &r.target_sub_types { + m.insert("targetSubTypes".into(), sorted(list)); + } + if r.field_path { + m.insert("fieldPath".into(), json!(true)); + } + if r.same_system { + m.insert("sameSystem".into(), json!(true)); + } + if let Some(c) = &r.error_code { + m.insert("errorCode".into(), json!(c)); + } + if let Some(c) = &r.wrong_system_code { + m.insert("wrongSystemCode".into(), json!(c)); + } + Value::Object(m) +} + fn sub_type_key(sub: &ChildSubType) -> String { match sub { ChildSubType::One(s) => s.clone(), diff --git a/server/rust/metaobjects/src/parser.rs b/server/rust/metaobjects/src/parser.rs index 138be1019..a78d66698 100644 --- a/server/rust/metaobjects/src/parser.rs +++ b/server/rust/metaobjects/src/parser.rs @@ -14,6 +14,7 @@ use crate::errors::{ ERR_UNKNOWN_SUBTYPE, ERR_UNKNOWN_TYPE, ERR_UNRESOLVED_SUPER, MetaError, }; use crate::json::{js_display, safe_whole_i64}; +use crate::loader::root_child_key; use crate::node::{Attr, Node, NodeId, PACKAGE_SEP, Tree}; use crate::registry::{SUBTYPE_BASE, TypeRegistry}; use crate::source::{ErrorSource, JsonPath, YamlPosition}; @@ -552,17 +553,26 @@ fn structural_bool( /// Add `child` under `parent`, or fold it into a same-type, same-name sibling the /// same document already declared (every port merges those during the parse). /// Unnamed nodes are always distinct, and overlays stay as written for the -/// loader's deferred pass (ADR-0055). +/// loader's deferred pass (ADR-0055). At the root the match is package-qualified, as +/// in the loader's merge: a root-level `Apple` and `acme::Apple` are two nodes. fn add_or_merge_child(tree: &mut Tree, parent: NodeId, child: NodeId) { let c = tree.node(child); if c.name.is_empty() || c.is_overlay { tree.add_child(parent, child); return; } + let key = tree + .node(parent) + .parent + .is_none() + .then(|| root_child_key(tree, child)); // ADR-0039: own — the merge works on the authored layer, before super resolution. let existing = tree.own_children(parent).iter().copied().find(|&s| { let n = tree.node(s); - !n.is_overlay && n.type_name == c.type_name && n.name == c.name + !n.is_overlay + && n.type_name == c.type_name + && n.name == c.name + && key.as_ref().is_none_or(|k| root_child_key(tree, s) == *k) }); let Some(existing) = existing else { tree.add_child(parent, child); diff --git a/server/rust/metaobjects/src/providers.rs b/server/rust/metaobjects/src/providers.rs index 08444c8e9..d01239908 100644 --- a/server/rust/metaobjects/src/providers.rs +++ b/server/rust/metaobjects/src/providers.rs @@ -6,6 +6,10 @@ //! compile time (`tests/vendored_data_parity.rs` holds them to the source) and //! lowers them exactly as the TypeScript reference does (`provider-data.ts`, //! `core-types.ts`). +//! +//! An attr entry may carry the reference facet (`ref`, `spec/metamodel-definitions.md`). +//! The reader refuses a facet the format does not allow, or one on a structural child, +//! and lowers a valid one onto [`AttrSchema::reference`] for the loader to enforce. use std::collections::HashSet; use std::sync::OnceLock; @@ -17,8 +21,8 @@ use crate::errors::{ MetaError, }; use crate::registry::{ - AttrSchema, ChildRule, ChildSubType, ReferenceDescriptor, SUBTYPE_BASE, TypeDefinition, - TypeRegistry, WILDCARD, + AttrSchema, ChildRule, ChildSubType, ReferenceDescriptor, ReferenceFacet, SUBTYPE_BASE, + TypeDefinition, TypeRegistry, WILDCARD, }; pub const CORE_TYPES_ID: &str = "metaobjects-core-types"; @@ -149,6 +153,8 @@ struct ChildDef { is_array: Option, ports: Option>, implemented_in: Option>, + /// The raw `ref` facet, checked when the child is lowered. + reference: Option, } #[derive(Debug, Clone)] @@ -226,6 +232,7 @@ fn parse_child(v: &Value) -> ChildDef { is_array: v.get("isArray").and_then(Value::as_bool), ports: strings(v, "ports"), implemented_in: strings(v, "implementedIn"), + reference: v.get(REF_KEY).cloned(), } } @@ -325,6 +332,141 @@ fn definitions() -> &'static Definitions { const ATTR_CHILD_TYPE: &str = "attr"; +/// The child-entry key that carries the reference facet. +const REF_KEY: &str = "ref"; +/// The only attr value type a reference may have. +const STRING_VALUE_TYPE: &str = "string"; +/// The facet's keys, in the format's order. +const FACET_KEYS: &[&str] = &[ + "targetType", + "targetSubTypes", + "fieldPath", + "sameSystem", + "errorCode", + "wrongSystemCode", +]; +const SUB_TYPES_RULE: &str = + "targetSubTypes must be a non-empty list of distinct subtype names, never \"*\""; + +fn facet_error(provider: &str, kind: &str, name: &str, key: &str, why: &str) -> MetaError { + MetaError::unknown(format!( + "provider definition ({provider}): {kind} \"{name}\" on \"{key}\" has an invalid reference facet: {why}." + )) +} + +/// A loader error code, as a facet names one: `ERR_` then upper case, digits and `_`. +fn is_loader_code(code: &str) -> bool { + code.strip_prefix("ERR_").is_some_and(|rest| { + !rest.is_empty() + && rest + .bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') + }) +} + +/// Read an attr entry's reference facet, refusing a facet the format does not allow +/// (`spec/metamodel-definitions.md`, "The reference facet"; the JSON schema states the +/// same rules). Mirrors the TypeScript `toReferenceFacet`. +fn to_reference_facet( + provider: &str, + key: &str, + child: &ChildDef, + raw: &Value, +) -> Result { + let fail = |why: &str| facet_error(provider, ATTR_CHILD_TYPE, &child.name, key, why); + let Value::Object(r) = raw else { + return Err(fail("ref must be an object")); + }; + if let Some(unknown) = r.keys().find(|k| !FACET_KEYS.contains(&k.as_str())) { + return Err(fail(&format!("unknown key \"{unknown}\""))); + } + let value_type = match &child.sub_type { + Some(ChildSubType::One(t)) => Some(t.as_str()), + _ => None, + }; + if value_type != Some(STRING_VALUE_TYPE) { + return Err(fail(&format!( + "only a string attr may be a reference (this one is \"{}\")", + value_type.unwrap_or("") + ))); + } + let target_type = match r.get("targetType").and_then(Value::as_str) { + Some(t) if !t.is_empty() && t != WILDCARD => t.to_string(), + _ => return Err(fail("targetType must name one type, never \"*\"")), + }; + let target_sub_types = match r.get("targetSubTypes") { + None => None, + Some(Value::Array(items)) => { + let mut list: Vec = Vec::new(); + for item in items { + match item.as_str() { + Some(sub) + if !sub.is_empty() && sub != WILDCARD && !list.iter().any(|l| l == sub) => + { + list.push(sub.to_string()); + } + _ => return Err(fail(SUB_TYPES_RULE)), + } + } + if list.is_empty() { + return Err(fail(SUB_TYPES_RULE)); + } + Some(list) + } + Some(_) => return Err(fail(SUB_TYPES_RULE)), + }; + let opt_bool = |k: &str| -> Result { + match r.get(k) { + None => Ok(false), + Some(Value::Bool(b)) => Ok(*b), + Some(_) => Err(fail(&format!("{k} must be a boolean"))), + } + }; + let field_path = opt_bool("fieldPath")?; + let same_system = opt_bool("sameSystem")?; + if field_path && same_system { + return Err(fail("fieldPath and sameSystem cannot both be true")); + } + let opt_code = |k: &str| -> Result, MetaError> { + match r.get(k) { + None => Ok(None), + Some(Value::String(c)) if is_loader_code(c) => Ok(Some(c.clone())), + Some(_) => Err(fail(&format!( + "{k} must be a loader code (ERR_ and upper case)" + ))), + } + }; + let error_code = opt_code("errorCode")?; + let wrong_system_code = opt_code("wrongSystemCode")?; + if same_system != wrong_system_code.is_some() { + return Err(fail( + "wrongSystemCode is present exactly when sameSystem is true", + )); + } + Ok(ReferenceFacet { + target_type, + target_sub_types, + field_path, + same_system, + error_code, + wrong_system_code, + }) +} + +/// Refuse a structural child that carries `ref`: only an attr may be a reference. +fn refuse_structural_ref(provider: &str, key: &str, child: &ChildDef) -> Result<(), MetaError> { + if child.reference.is_some() { + return Err(facet_error( + provider, + "child", + &child.name, + key, + "only an attr may be a reference", + )); + } + Ok(()) +} + fn is_universal(t: &TypeDef) -> bool { t.type_name == WILDCARD && t.sub_type == WILDCARD } @@ -364,6 +506,11 @@ fn to_attr_schema(provider: &str, key: &str, child: &ChildDef) -> Result Result Result<(), MetaError> { registry.register(def)?; } } - let reference = |attr: &str, dotted: bool, code: &str| ReferenceDescriptor { + let reference = |attr: &str, field_path: bool, code: &str| ReferenceDescriptor { attr: attr.to_string(), - target_type: "object".to_string(), - dotted_field_path: dotted, - error_code: code.to_string(), + facet: ReferenceFacet { + field_path, + ..ReferenceFacet::of("object", code) + }, }; for sub in registry.all_sub_types_of("relationship") { if let Some(def) = registry.find_mut("relationship", &sub) { diff --git a/server/rust/metaobjects/src/registry.rs b/server/rust/metaobjects/src/registry.rs index 3c94ff63b..6bb12877e 100644 --- a/server/rust/metaobjects/src/registry.rs +++ b/server/rust/metaobjects/src/registry.rs @@ -35,6 +35,9 @@ pub struct AttrSchema { pub rules: Option, pub example: Option, pub when_to_use: Option, + /// The reference facet (`ref`, `spec/metamodel-definitions.md`): what node the + /// attribute's value must name. `None` for an attribute that is not a reference. + pub reference: Option, } impl AttrSchema { @@ -53,6 +56,41 @@ impl AttrSchema { rules: None, example: None, when_to_use: None, + reference: None, + } + } +} + +/// The reference facet (`spec/metamodel-definitions.md`, "The reference facet"): what a +/// reference attribute may point at. A provider definition carries it as `ref` on a +/// `type: "attr"` child, and the loader enforces it with no code per provider. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReferenceFacet { + /// The type the value must resolve to. Never `*`. + pub target_type: String, + /// The subtypes of `target_type` the value may resolve to. `None`: any. Never empty. + pub target_sub_types: Option>, + /// The value is `Target.field`: only the top-level `Target` is resolved. + pub field_path: bool, + /// The target must be in the same system as the node that declares the attribute. + pub same_system: bool, + /// Raised when the value does not resolve or resolves to the wrong kind. `None`: + /// `ERR_REF_UNRESOLVED` and `ERR_REF_WRONG_KIND`. + pub error_code: Option, + /// Raised when `same_system` fails. Present exactly when `same_system` is true. + pub wrong_system_code: Option, +} + +impl ReferenceFacet { + /// A facet that targets `target_type` and reports `error_code` for every failure. + pub fn of(target_type: &str, error_code: &str) -> Self { + Self { + target_type: target_type.to_string(), + target_sub_types: None, + field_path: false, + same_system: false, + error_code: Some(error_code.to_string()), + wrong_system_code: None, } } } @@ -105,14 +143,13 @@ impl ChildRule { } } -/// An attribute whose value names another node, and the code reported when it -/// does not resolve. Recorded now; the reference pass that reads it is later work. +/// An attribute whose value names another node, and its reference facet. A provider +/// attaches these to a type definition in code; an attribute whose schema carries +/// [`AttrSchema::reference`] is enforced the same way without one. #[derive(Debug, Clone, PartialEq)] pub struct ReferenceDescriptor { pub attr: String, - pub target_type: String, - pub dotted_field_path: bool, - pub error_code: String, + pub facet: ReferenceFacet, } /// Everything the registry knows about one `type.subType`. diff --git a/server/rust/metaobjects/src/validate/refs.rs b/server/rust/metaobjects/src/validate/refs.rs index 7aa8a856e..d9c73cbe9 100644 --- a/server/rust/metaobjects/src/validate/refs.rs +++ b/server/rust/metaobjects/src/validate/refs.rs @@ -1,17 +1,27 @@ //! `runRegisteredValidation`: validation derived from the type registry. //! -//! Each node's `TypeDefinition` carries reference descriptors (an attribute that -//! names another node, and the code to report when it does not resolve). One walk -//! over a symbol table built once. The reference's per-type imperative `validate` -//! hook is unused by core (an extension point for downstream providers), so the -//! Rust registry has no equivalent; only descriptors are honoured. +//! A reference attribute names another node. A provider declares one either in code +//! (a [`ReferenceDescriptor`] on its type definition: the four core `object` +//! references) or as data (the `ref` facet on the attribute in its definition file, +//! `spec/metamodel-definitions.md`). Both are enforced here, in one walk over a symbol +//! table built once. The reference's per-type imperative `validate` hook is unused by +//! core (an extension point for downstream providers), so the Rust registry has no +//! equivalent; only descriptors and facets are honoured. +//! +//! The symbol table's lookup is the facet's ("How a reference is looked up"): the final +//! segment is typed by the facet, a dotted value walks `System.child` (or +//! `pkg::System.child`) through children by name, and a bare value is looked for in the +//! referrer's own containers, nearest first, before the top level. When the typed +//! lookup finds nothing, an untyped one along the same order tells a value that names +//! the wrong kind of node from one that names nothing. Mirrors the TypeScript +//! `symbol-table.ts` and the C# and Java `SymbolTable`. use std::collections::HashMap; -use crate::errors::{ERR_BAD_ATTR_VALUE, ERR_UNKNOWN}; -use crate::loader::owner_candidate_keys; -use crate::node::{NodeId, Tree}; -use crate::registry::{ReferenceDescriptor, TypeDefinition}; +use crate::errors::{ERR_BAD_ATTR_VALUE, ERR_REF_UNRESOLVED, ERR_REF_WRONG_KIND, MetaError}; +use crate::loader::{owner_candidate_keys, split_child_tail}; +use crate::node::{NodeId, PACKAGE_SEP, Tree}; +use crate::registry::{ReferenceDescriptor, ReferenceFacet, TypeDefinition, TypeRegistry}; use crate::validate::structure::preorder; use crate::validate::util::error_at; use crate::validate::{Ctx, Findings}; @@ -21,18 +31,10 @@ pub const ERR_INVALID_REFERENCE: &str = "ERR_INVALID_REFERENCE"; pub const ERR_UNRESOLVED_OBJECT_REF: &str = "ERR_UNRESOLVED_OBJECT_REF"; const TYPE_OBJECT: &str = "object"; - -/// The shared code a descriptor names. Codes are `&'static str`; a descriptor that -/// names one this port does not know reports `ERR_UNKNOWN` rather than guess. -fn descriptor_code(code: &str) -> &'static str { - match code { - ERR_INVALID_RELATIONSHIP => ERR_INVALID_RELATIONSHIP, - ERR_INVALID_REFERENCE => ERR_INVALID_REFERENCE, - ERR_UNRESOLVED_OBJECT_REF => ERR_UNRESOLVED_OBJECT_REF, - ERR_BAD_ATTR_VALUE => ERR_BAD_ATTR_VALUE, - _ => ERR_UNKNOWN, - } -} +/// ADR-0070's `system` type. Core registers it in 1.4.0; the facet's `sameSystem` check +/// reads it now to find a node's system, its nearest ancestor of this type. +const TYPE_SYSTEM: &str = "system"; +const CHILD_REF_SEP: char = '.'; /// A node's package as the reference resolver sees it: its own, else its file's. fn effective_package_of(tree: &Tree, id: NodeId) -> &str { @@ -43,9 +45,9 @@ fn effective_package_of(tree: &Tree, id: NodeId) -> &str { .unwrap_or("") } -/// ADR-0059 R3: a reference resolves in the package of the top-level node that -/// physically declares the attribute, which for an inherited one is the ancestor. -fn referrer_package_for<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> &'a str { +/// The node that physically declares `attr` for `node`: `node` itself, or the ancestor +/// along its `extends` chain that wrote it (`node` when none does). +fn declaring_node_for(tree: &Tree, node: NodeId, attr: &str) -> NodeId { let mut declarer = Some(node); let mut hops = 0; // ADR-0039: own: locating the layer that physically declares the attribute. @@ -56,36 +58,219 @@ fn referrer_package_for<'a>(tree: &'a Tree, node: NodeId, attr: &str) -> &'a str hops += 1; declarer = tree.node(d).super_node; } - effective_package_of(tree, tree.top_level_of(declarer.unwrap_or(node))) + declarer.unwrap_or(node) +} + +/// The reference facet of `attr` on a node of `type_name.sub_type`: the type's own +/// attribute schema, else the common attribute's. +pub(crate) fn facet_of<'r>( + registry: &'r TypeRegistry, + type_name: &str, + sub_type: &str, + attr: &str, +) -> Option<&'r ReferenceFacet> { + match registry + .find(type_name, sub_type) + .and_then(|d| d.attr(attr)) + { + Some(schema) => schema.reference.as_ref(), + None => registry.common_attr(attr)?.reference.as_ref(), + } } -/// Every top-level node, by type then resolution key (ADR-0042: no short-name fallback). -struct Symbols { - by_type: HashMap>, +/// What one reference value names. +pub(crate) enum RefMatch { + /// The nodes the lookup walked, from the top-level owner to the target (the last + /// entry). A child inherited through `extends` is reached through the node it was + /// looked up in, so the path is the address the value used, not the target's + /// physical parents. + Found(Vec), + /// The untyped lookup found this node: the value names the wrong kind of node. + WrongKind(NodeId), + /// Nothing of that name. + Unresolved, + /// A `..::` that climbs above the root package. + OverDrop, } -impl Symbols { - fn build(tree: &Tree, root: NodeId) -> Self { - let mut by_type: HashMap> = HashMap::new(); +/// Every top-level node by type then resolution key, and by key alone, built once per +/// load (ADR-0042: no short-name fallback). +pub(crate) struct SymbolTable<'t> { + tree: &'t Tree, + root: NodeId, + /// Indexed per type, so a template and an object sharing `pkg::Name` never collide. + by_type: HashMap<&'t str, HashMap>, + /// Every top-level node of any type: the owner of a dotted path matches by name of + /// any type, and two of different types under one key are ambiguous. + by_key: HashMap>, +} + +impl<'t> SymbolTable<'t> { + pub(crate) fn build(tree: &'t Tree, root: NodeId) -> Self { + let mut by_type: HashMap<&'t str, HashMap> = HashMap::new(); + let mut by_key: HashMap> = HashMap::new(); for &c in tree.children(root).iter() { + let key = tree.resolution_key(c); by_type - .entry(tree.node(c).type_name.clone()) + .entry(tree.node(c).type_name.as_str()) .or_default() - .insert(tree.resolution_key(c), c); + .insert(key.clone(), c); + by_key.entry(key).or_default().push(c); + } + Self { + tree, + root, + by_type, + by_key, } - Self { by_type } } - fn resolve(&self, type_name: &str, keys: &[String]) -> Option { + /// A top-level node of `type_name` by ADR-0059 R2 form: `::Rest` root-absolute, + /// `..::Rest` parent-relative, `pkg::Name` exact, bare `Name` in the referrer's + /// package then root-level. + fn resolve(&self, type_name: &str, reference: &str, pkg: &str) -> Option { let bucket = self.by_type.get(type_name)?; - keys.iter().find_map(|k| bucket.get(k).copied()) + owner_candidate_keys(reference, pkg) + .ok()? + .iter() + .find_map(|k| bucket.get(k).copied()) + } + + /// The top-level nodes of any type under the first candidate key that has any. + fn top_level_named(&self, owner: &str, pkg: &str) -> &[NodeId] { + owner_candidate_keys(owner, pkg) + .ok() + .and_then(|keys| keys.iter().find_map(|k| self.by_key.get(k))) + .map_or(&[], Vec::as_slice) + } + + /// The children of `parent` named `name`, inherited ones included. + fn children_named(&self, parent: NodeId, name: &str) -> Vec { + // ADR-0039: resolving: a child inherited through `extends` is addressable too. + self.tree + .children(parent) + .iter() + .copied() + .filter(|&c| self.tree.node(c).name == name) + .collect() + } + + /// The first child of `parent` named `name`, of `type_name` when given. + fn child_named(&self, parent: NodeId, name: &str, type_name: Option<&str>) -> Option { + self.children_named(parent, name) + .into_iter() + .find(|&c| type_name.is_none_or(|t| self.tree.node(c).type_name == t)) + } + + /// The physical containers from the top-level node down to `container`, inclusive. + fn containers_to(&self, container: NodeId) -> Vec { + let mut path = Vec::new(); + let mut cur = Some(container); + while let Some(c) = cur.filter(|&c| c != self.root) { + path.push(c); + cur = self.tree.node(c).parent; + } + path.reverse(); + path + } + + /// Look up one reference value under a facet. `referrer` is the node that declares + /// the attribute and `pkg` its ADR-0059 R3 package. + pub(crate) fn lookup( + &self, + referrer: NodeId, + value: &str, + facet: &ReferenceFacet, + pkg: &str, + ) -> RefMatch { + // A `fieldPath` value is `Target.field`: only the top-level `Target` is resolved. + let reference = if facet.field_path { + split_child_tail(value).0 + } else { + value + }; + if owner_candidate_keys(split_child_tail(reference).0, pkg).is_err() { + return RefMatch::OverDrop; + } + // A `fieldPath` target is top-level: the referrer's containers are not searched. + let from = (!facet.field_path).then_some(referrer); + if let Some(path) = self.find(from, reference, Some(&facet.target_type), pkg) { + return RefMatch::Found(path); + } + // Rule 6: the untyped lookup, along the same order, only picks the error code. + match self.find(from, reference, None, pkg) { + Some(path) => RefMatch::WrongKind(path[path.len() - 1]), + None => RefMatch::Unresolved, + } + } + + /// The path, top-level owner first, to the node `reference` names whose final segment + /// is of `type_name` (any type when `None`). With no `referrer`, no container is + /// searched. + fn find( + &self, + referrer: Option, + reference: &str, + type_name: Option<&str>, + pkg: &str, + ) -> Option> { + let (owner, tail) = split_child_tail(reference); + if tail.is_empty() { + // Rule 4: a bare value is looked for among the children of each container of + // the referrer, nearest first, up to and including its top-level node. + if let Some(referrer) = referrer + && !owner.contains(PACKAGE_SEP) + { + let mut cur = self.tree.node(referrer).parent; + while let Some(c) = cur.filter(|&c| c != self.root) { + if let Some(hit) = self.child_named(c, owner, type_name) { + let mut path = self.containers_to(c); + path.push(hit); + return Some(path); + } + cur = self.tree.node(c).parent; + } + } + let top = match type_name { + Some(t) => self.resolve(t, owner, pkg), + None => self.top_level_named(owner, pkg).first().copied(), + }; + return top.map(|t| vec![t]); + } + // Rule 3: `Owner.child[.grand]`: the owner by its form, then each segment by name. + let segments: Vec<&str> = tail[CHILD_REF_SEP.len_utf8()..] + .split(CHILD_REF_SEP) + .collect(); + if segments.iter().any(|s| s.is_empty()) { + return None; + } + let [owner_node] = self.top_level_named(owner, pkg) else { + return None; + }; + let mut walked = vec![*owner_node]; + // Rule 2: an intermediate segment matches a child by name, of any type; two + // children sharing the name make the step ambiguous. + for seg in &segments[..segments.len() - 1] { + let [next] = self.children_named(walked[walked.len() - 1], seg)[..] else { + return None; + }; + walked.push(next); + } + // Rule 1: the final segment is typed. + let last = self.child_named( + walked[walked.len() - 1], + segments[segments.len() - 1], + type_name, + )?; + walked.push(last); + Some(walked) } } /// Same-short-name objects in other packages, to append to an unresolved-object message. pub(super) fn did_you_mean_hint(tree: &Tree, root: NodeId, r: &str) -> String { - let (owner, _) = crate::loader::split_child_tail(r); - let short = owner.rsplit("::").next().unwrap_or(owner); + let (owner, _) = split_child_tail(r); + let short = owner.rsplit(PACKAGE_SEP).next().unwrap_or(owner); let candidates: Vec = tree .children(root) .iter() @@ -105,105 +290,210 @@ pub(super) fn did_you_mean_hint(tree: &Tree, root: NodeId, r: &str) -> String { ) } -fn check_descriptor( +/// The system of a node: its nearest physical ancestor, or itself, of type `system`. +fn system_of(tree: &Tree, node: NodeId) -> Option { + let mut cur = Some(node); + while let Some(n) = cur { + if tree.node(n).type_name == TYPE_SYSTEM { + return Some(n); + } + cur = tree.node(n).parent; + } + None +} + +/// An error on `node` under a code a facet names (a provider's own code keeps its +/// spelling in [`MetaError::provider_code`]). +fn facet_error(tree: &Tree, node: NodeId, code: &str, message: String) -> MetaError { + MetaError::at_provider_code(code, message, tree.node(node).source.clone()) +} + +/// Enforce one reference attribute on `node`, every value of it when it is a list +/// (`spec/metamodel-definitions.md`, "What the loader checks, in order"). +fn check_reference( ctx: &Ctx<'_>, - symbols: &Symbols, + symbols: &SymbolTable<'_>, node: NodeId, desc: &ReferenceDescriptor, out: &mut Findings, ) { let tree = ctx.tree; + let facet = &desc.facet; // ADR-0039: resolving: a reference attribute may be inherited through extends. - let Some(raw) = tree - .attr(node, &desc.attr) - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - else { - return; // absence is the required-attribute pass's job - }; - let entity_ref = if desc.dotted_field_path { - raw.split('.').next().unwrap_or(raw) - } else { - raw + let values: Vec<&str> = match tree.attr(node, &desc.attr) { + Some(serde_json::Value::String(s)) => vec![s.as_str()], + Some(serde_json::Value::Array(items)) => { + items.iter().filter_map(serde_json::Value::as_str).collect() + } + _ => return, }; - let ref_pkg = referrer_package_for(tree, node, &desc.attr); + // ADR-0059 R3 and rule 5: an inherited reference is looked up from the node that + // physically declares it, in that node's package, not from the inheritor. + let declarer = declaring_node_for(tree, node, &desc.attr); + let pkg = effective_package_of(tree, tree.top_level_of(declarer)); let n = tree.node(node); - let Ok(keys) = owner_candidate_keys(entity_ref, ref_pkg) else { - out.errors.push(error_at( - tree, - node, - ERR_BAD_ATTR_VALUE, - format!( - "{}.{} \"{}\" @{} \"{raw}\" climbs above the root package — each '..::' drops one segment of the declaring package.", - n.type_name, n.sub_type, n.name, desc.attr - ), - )); - return; - }; - if symbols.resolve(&desc.target_type, &keys).is_some() { - return; - } + // Qualify the node name with its owning node ("Order.items") so the error is + // locatable from the message alone. let qname = match n.parent.map(|p| tree.node(p).name.as_str()) { Some(p) if !p.is_empty() => format!("{p}.{}", n.name), _ => n.name.clone(), }; - let is_object = desc.target_type == TYPE_OBJECT; - let want = if is_object { - "an object".to_string() - } else { - format!("a {}", desc.target_type) - }; - let hint = if is_object { - did_you_mean_hint(tree, ctx.root, entity_ref) - } else { - String::new() - }; - out.errors.push(error_at( - tree, - node, - descriptor_code(&desc.error_code), + let label = |value: &str| { format!( - "{}.{} \"{qname}\" @{} \"{raw}\" does not resolve to {want}.{hint}", + "{}.{} \"{qname}\" @{} \"{value}\"", n.type_name, n.sub_type, desc.attr - ), - )); + ) + }; + let want = match &facet.target_sub_types { + None if facet.target_type == TYPE_OBJECT => "an object".to_string(), + None => format!("a {}", facet.target_type), + Some(subs) => subs + .iter() + .map(|s| format!("{}.{s}", facet.target_type)) + .collect::>() + .join(" or "), + }; + let kind_code = |default: &'static str| facet.error_code.as_deref().unwrap_or(default); + for value in values.into_iter().filter(|v| !v.is_empty()) { + // An absent or empty value is the required-attribute pass's job. + let path = match symbols.lookup(declarer, value, facet, pkg) { + RefMatch::Found(path) => path, + RefMatch::OverDrop => { + out.errors.push(error_at( + tree, + node, + ERR_BAD_ATTR_VALUE, + format!( + "{} climbs above the root package — each '..::' drops one segment of the declaring package.", + label(value) + ), + )); + continue; + } + miss => { + // ADR-0042 §5: the did-you-mean hint is object-scoped. + let hint = if facet.target_type == TYPE_OBJECT { + did_you_mean_hint(tree, ctx.root, value) + } else { + String::new() + }; + let (code, message) = match miss { + RefMatch::WrongKind(w) => { + let w = tree.node(w); + ( + kind_code(ERR_REF_WRONG_KIND), + format!( + "{} names {}.{} \"{}\", not {want}.{hint}", + label(value), + w.type_name, + w.sub_type, + w.name + ), + ) + } + _ => ( + kind_code(ERR_REF_UNRESOLVED), + format!("{} does not resolve to {want}.{hint}", label(value)), + ), + }; + out.errors.push(facet_error(tree, node, code, message)); + continue; + } + }; + let target = tree.node(path[path.len() - 1]); + // The system the path went through: an inherited child is in the system it was + // reached through, not the one that physically holds it. + let theirs = path + .iter() + .rev() + .copied() + .find(|&p| tree.node(p).type_name == TYPE_SYSTEM); + let place = theirs.map_or("no system".to_string(), |s| { + format!("system \"{}\"", tree.resolution_key(s)) + }); + let resolved = format!( + "{} resolves to {}.{} \"{}\" in {place}", + label(value), + target.type_name, + target.sub_type, + target.name + ); + // The typed lookup guarantees the type; only the subtype can still mismatch. + if let Some(subs) = &facet.target_sub_types + && !subs.contains(&target.sub_type) + { + out.errors.push(facet_error( + tree, + node, + kind_code(ERR_REF_WRONG_KIND), + format!("{resolved}, not {want}."), + )); + continue; + } + if facet.same_system { + let mine = system_of(tree, declarer); + if mine.is_none() || mine != theirs { + let from = mine.map_or("a node outside any system".to_string(), |s| { + format!("system \"{}\"", tree.resolution_key(s)) + }); + let code = facet + .wrong_system_code + .as_deref() + .unwrap_or(ERR_REF_WRONG_KIND); + out.errors.push(facet_error( + tree, + node, + code, + format!( + "{resolved}, but it must be in the same system as the node that declares it, which is in {from}." + ), + )); + } + } + } +} + +/// The reference descriptors of `def`: those a provider attached in code, then one for +/// every attribute of the type (and every common attribute) whose schema carries the +/// reference facet. +fn descriptors_of(def: &TypeDefinition, registry: &TypeRegistry) -> Vec { + let mut out = def.references.clone(); + let mut seen: Vec<&str> = Vec::new(); + for attr in def.attributes.iter().chain(registry.common_attrs()) { + if seen.contains(&attr.name.as_str()) { + continue; + } + seen.push(&attr.name); + if let Some(facet) = &attr.reference { + out.push(ReferenceDescriptor { + attr: attr.name.clone(), + facet: facet.clone(), + }); + } + } + out } -/// Run every registered reference descriptor over the tree. +/// Run every registered reference descriptor and facet over the tree. pub fn registered_validation(ctx: &Ctx<'_>, out: &mut Findings) { let tree = ctx.tree; - let symbols = Symbols::build(tree, ctx.root); - let mut defs: HashMap<(&str, &str), Option<&TypeDefinition>> = HashMap::new(); + let symbols = SymbolTable::build(tree, ctx.root); + let mut defs: HashMap<(&str, &str), Option>> = HashMap::new(); for id in preorder(tree, ctx.root) { let n = tree.node(id); - let def = *defs + let descriptors = defs .entry((n.type_name.as_str(), n.sub_type.as_str())) - .or_insert_with(|| ctx.registry.find(&n.type_name, &n.sub_type)); - let Some(def) = def else { continue }; - for desc in &def.references { - check_descriptor(ctx, &symbols, id, desc, out); + .or_insert_with(|| { + ctx.registry + .find(&n.type_name, &n.sub_type) + .map(|def| descriptors_of(def, ctx.registry)) + }); + for desc in descriptors.iter().flatten() { + check_reference(ctx, &symbols, id, desc, out); } } } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn every_code_is_in_the_shared_catalogue() { - let raw = include_str!("../../data/ERROR-CODES.json"); - let doc: serde_json::Value = serde_json::from_str(raw).unwrap(); - let codes = doc["codes"].as_object().unwrap(); - for code in [ - ERR_INVALID_RELATIONSHIP, - ERR_INVALID_REFERENCE, - ERR_UNRESOLVED_OBJECT_REF, - ] { - assert!( - codes.contains_key(code), - "{code} is not in ERROR-CODES.json" - ); - } - } -} +#[path = "refs_tests.rs"] +mod tests; diff --git a/server/rust/metaobjects/src/validate/refs_tests.rs b/server/rust/metaobjects/src/validate/refs_tests.rs new file mode 100644 index 000000000..55b3c0af0 --- /dev/null +++ b/server/rust/metaobjects/src/validate/refs_tests.rs @@ -0,0 +1,922 @@ +//! The reference facet (`spec/metamodel-definitions.md`): the spec reader carries `ref` on +//! an attr entry, the registered walk enforces it, the symbol table resolves `System.child` +//! and `pkg::System.child`, the lookup is kind-typed, the reference pass writes the walked +//! path, and the registry manifest writes the facet only when an attr has one. +//! +//! No shipped definition file uses the facet yet, so these tests compose a test provider +//! with a small system vocabulary of its own: the types are registered in code, and the +//! reference attributes come from a provider definition read by the spec reader. Mirrors +//! the TypeScript `reference-facet.test.ts` and the C# `ReferenceFacetTests` case for case. + +use serde_json::{Value, json}; + +use super::*; +use crate::errors::ERR_UNKNOWN; +use crate::loader::{LoadResult, Loader}; +use crate::manifest::{build_manifest, emit_manifest}; +use crate::providers::{Provider, apply_provider_definition, compose_registry, core_providers}; +use crate::registry::{ChildRule, TypeDefinition}; +use crate::serializer::canonical_serialize; + +const PROVIDER_ID: &str = "test-reference-facet"; + +/// The reference attributes, as a provider definition: an `extends` entry per type. +fn definition() -> Value { + json!({ + "provider": PROVIDER_ID, + "extends": [ + { "type": "app", "subType": "service", "children": [ + { "type": "attr", "subType": "string", "name": "runsAs", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "role", "sameSystem": true, "wrongSystemCode": "ERR_RUNSAS_OTHER_SYSTEM" } }, + { "type": "attr", "subType": "string", "name": "calls", "isArray": true, "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "app" } }, + { "type": "attr", "subType": "string", "name": "reads", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "resource", "fieldPath": true } } + ] }, + { "type": "grant", "subType": "rdb", "children": [ + { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "resource", "targetSubTypes": ["rdb"], "sameSystem": true, + "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } } + ] }, + { "type": "deployment", "subType": "test", "children": [ + { "type": "attr", "subType": "string", "name": "app", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "app" } }, + { "type": "attr", "subType": "string", "name": "anyRole", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "role", "errorCode": "ERR_TEST_ROLE" } }, + { "type": "attr", "subType": "string", "name": "pinnedRole", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "role", "sameSystem": true, "wrongSystemCode": "ERR_TEST_OUTSIDE" } }, + { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "role" } } + ] } + ] + }) +} + +fn register_test_types(r: &mut TypeRegistry) -> Result<(), MetaError> { + let types: &[(&str, &str, &[&str])] = &[ + ("system", "software", &["app", "role", "resource"]), + ("app", "service", &[]), + ("role", "service", &["grant", "resource"]), + ("grant", "rdb", &[]), + ("resource", "rdb", &[]), + ("resource", "queue", &[]), + ("deployment", "test", &[]), + ]; + for (type_name, sub_type, children) in types { + let mut def = TypeDefinition::new(type_name, sub_type, &format!("A test {type_name}.")); + def.child_rules = std::iter::once("attr") + .chain(children.iter().copied()) + .map(ChildRule::wildcard) + .collect(); + r.register(def)?; + } + r.extend( + "metadata", + "root", + Vec::new(), + ["system", "deployment", "app", "resource"] + .into_iter() + .map(ChildRule::wildcard) + .collect(), + )?; + apply_provider_definition(r, &definition()) +} + +fn registry() -> TypeRegistry { + let mut providers = core_providers(); + providers.push(Provider::new( + PROVIDER_ID, + &[crate::providers::CORE_TYPES_ID], + "Test systems vocabulary.", + register_test_types, + )); + let mut r = compose_registry(&providers).expect("the test registry composes"); + r.seal(); + r +} + +fn load_as(registry: &TypeRegistry, id: &str, text: &str) -> LoadResult { + Loader::new(registry) + .strict(true) + .load_sources(&[(id.to_string(), text.to_string())]) +} + +fn load(text: &str) -> (TypeRegistry, LoadResult) { + let r = registry(); + let result = load_as(&r, "systems.yaml", text); + (r, result) +} + +fn codes(r: &LoadResult) -> Vec { + r.errors.iter().map(|e| e.code_name().to_string()).collect() +} + +fn clean(r: &LoadResult) { + let errors: Vec = r.errors.iter().map(ToString::to_string).collect(); + assert!(errors.is_empty(), "unexpected errors: {errors:#?}"); +} + +/// Two systems in package `acme`: Parcels (an app and a role both named `api`) and Ledger. +fn model(parcels_extra: &str, outside: &str) -> String { + format!( + "metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - resource.rdb: {{ name: db }} + - resource.queue: {{ name: jobs }} + - role.service: + name: api + children: + - grant.rdb: {{ name: g1, resource: db }} + - app.service: + name: api + runsAs: api +{parcels_extra} + - system.software: + name: Ledger + children: + - resource.rdb: {{ name: books }} + - role.service: {{ name: clerk }} + - app.service: {{ name: web, runsAs: clerk }} +{outside} +" + ) +} + +/// A node by its path from the root; a step is `name` or `type:name`. +fn at(r: &LoadResult, steps: &[&str]) -> NodeId { + steps.iter().fold(r.root, |n, step| { + let (type_name, name) = match step.split_once(':') { + Some((t, n)) => (Some(t), n), + None => (None, *step), + }; + // ADR-0039: own: the test addresses the declared layer. + r.tree + .own_children(n) + .iter() + .copied() + .find(|&c| { + let node = r.tree.node(c); + node.name == name && type_name.is_none_or(|t| node.type_name == t) + }) + .unwrap_or_else(|| panic!("no node at {steps:?}")) + }) +} + +/// The string value of `attr` on `node` (the first, for a list). +fn value_of(r: &LoadResult, node: NodeId, attr: &str) -> String { + match r.tree.attr(node, attr) { + Some(Value::String(s)) => s.clone(), + Some(Value::Array(items)) => items[0].as_str().unwrap().to_string(), + other => panic!("@{attr} is {other:?}"), + } +} + +/// The node `attr`'s value on `node` (the first, for a list) names under its facet. +fn bound_to(registry: &TypeRegistry, r: &LoadResult, node: NodeId, attr: &str) -> Option { + let n = r.tree.node(node); + let facet = facet_of(registry, &n.type_name, &n.sub_type, attr).expect("a facet attribute"); + let declarer = declaring_node_for(&r.tree, node, attr); + let pkg = effective_package_of(&r.tree, r.tree.top_level_of(declarer)).to_string(); + let symbols = SymbolTable::build(&r.tree, r.root); + match symbols.lookup(declarer, &value_of(r, node, attr), facet, &pkg) { + RefMatch::Found(path) => path.last().copied(), + _ => None, + } +} + +fn type_of(r: &LoadResult, id: Option) -> Option { + id.map(|i| r.tree.node(i).type_name.clone()) +} + +// ---- the spec reader --------------------------------------------------------------- + +#[test] +fn the_reader_lowers_ref_onto_the_attribute_schema() { + let r = registry(); + let facet = facet_of(&r, "grant", "rdb", "resource").expect("a facet"); + assert_eq!(facet.target_type, "resource"); + assert_eq!(facet.target_sub_types, Some(vec!["rdb".to_string()])); + assert!(facet.same_system); + assert!(!facet.field_path); + assert_eq!(facet.error_code, None); + assert_eq!( + facet.wrong_system_code.as_deref(), + Some("ERR_GRANT_CROSSES_SYSTEM") + ); +} + +fn with_ref(reference: Value, sub_type: &str) -> Value { + json!({ "provider": "bad", "types": [ { "type": "widget", "subType": "x", "description": "x", "children": [ + { "type": "attr", "subType": sub_type, "name": "to", "min": 0, "max": 1, "description": "x", "ref": reference } + ] } ] }) +} + +fn apply_err(definition: &Value) -> String { + let mut r = TypeRegistry::new(); + match r.run_as_provider("bad", |r| apply_provider_definition(r, definition)) { + Ok(()) => panic!("the definition was accepted"), + Err(e) => e.message, + } +} + +#[test] +fn the_reader_refuses_a_facet_the_format_does_not_allow() { + let cases: &[(Value, &str, &str)] = &[ + (json!({ "targetType": "role" }), "int", "only a string attr"), + (json!({ "targetType": "*" }), "string", "targetType"), + ( + json!({ "targetType": "role", "targetSubTypes": [] }), + "string", + "targetSubTypes", + ), + ( + json!({ "targetType": "role", "targetSubTypes": ["*"] }), + "string", + "targetSubTypes", + ), + ( + json!({ "targetType": "role", "targetSubTypes": ["a", "a"] }), + "string", + "targetSubTypes", + ), + ( + json!({ "targetType": "role", "sameSystem": true }), + "string", + "wrongSystemCode", + ), + ( + json!({ "targetType": "role", "wrongSystemCode": "ERR_X" }), + "string", + "wrongSystemCode", + ), + ( + json!({ "targetType": "role", "fieldPath": true, "sameSystem": true, "wrongSystemCode": "ERR_X" }), + "string", + "fieldPath and sameSystem", + ), + ( + json!({ "targetType": "role", "errorCode": "bad" }), + "string", + "loader code", + ), + ( + json!({ "targetType": "role", "errorCode": "ERR_lower" }), + "string", + "loader code", + ), + ( + json!({ "targetType": "role", "targetSubType": "rdb" }), + "string", + "unknown key \"targetSubType\"", + ), + ( + json!({ "targetType": "role", "fieldPath": "yes" }), + "string", + "fieldPath must be a boolean", + ), + (json!(["role"]), "string", "ref must be an object"), + ]; + for (reference, sub_type, why) in cases { + let message = apply_err(&with_ref(reference.clone(), sub_type)); + assert!(message.contains(why), "{reference}: {message}"); + assert!( + message.contains("attr \"to\" on \"widget.x\""), + "{reference}: {message}" + ); + } +} + +#[test] +fn the_reader_refuses_a_facet_on_a_structural_child() { + let message = apply_err( + &json!({ "provider": "bad", "types": [ { "type": "widget", "subType": "x", "description": "x", "children": [ + { "type": "role", "subType": "*", "name": "*", "min": 0, "max": null, "ref": { "targetType": "role" } } + ] } ] }), + ); + assert!( + message.contains("only an attr may be a reference"), + "{message}" + ); +} + +#[test] +fn the_reader_carries_a_facet_on_a_types_entry_attr() { + let mut r = TypeRegistry::new(); + r.run_as_provider("good", |r| { + apply_provider_definition( + r, + &with_ref( + json!({ "targetType": "role", "targetSubTypes": ["b", "a"] }), + "string", + ), + ) + }) + .expect("a valid facet"); + let facet = facet_of(&r, "widget", "x", "to").expect("a facet"); + assert_eq!( + facet.target_sub_types, + Some(vec!["b".to_string(), "a".to_string()]) + ); +} + +#[test] +fn no_shipped_definition_file_uses_the_facet_yet() { + let r = crate::providers::default_registry().unwrap(); + for def in r.all() { + for a in &def.attributes { + assert!( + a.reference.is_none(), + "{}.{} @{}", + def.type_name, + def.sub_type, + a.name + ); + } + } + assert!(r.common_attrs().iter().all(|a| a.reference.is_none())); +} + +// ---- the loader ---------------------------------------------------------------------- + +#[test] +fn a_valid_model_loads_clean() { + clean(&load(&model("", "")).1); +} + +#[test] +fn a_role_and_an_app_both_named_api_the_lookup_is_kind_typed() { + let (reg, r) = load(&model( + " - app.service: { name: worker, runsAs: api, calls: [api, Parcels.api] }", + "", + )); + clean(&r); + let worker = at(&r, &["Parcels", "worker"]); + // runsAs targets a role: the role `api`, not the app `api`. + assert_eq!( + type_of(&r, bound_to(®, &r, worker, "runsAs")).as_deref(), + Some("role") + ); + assert_eq!(value_of(&r, worker, "runsAs"), "acme::Parcels.api"); + // calls targets an app: both spellings bind the app `api`. + assert_eq!( + r.tree.attr(worker, "calls"), + Some(&json!(["acme::Parcels.api", "acme::Parcels.api"])) + ); + assert_eq!( + bound_to(®, &r, worker, "calls"), + Some(at(&r, &["Parcels", "app:api"])) + ); +} + +#[test] +fn unresolved_a_value_naming_no_node() { + let (_, r) = load(&model( + " - app.service: { name: worker, calls: [nobody] }", + "", + )); + assert_eq!(codes(&r), ["ERR_REF_UNRESOLVED"]); + assert_eq!(r.errors[0].code, ERR_REF_UNRESOLVED); + assert!( + r.errors[0].message.contains("@calls \"nobody\""), + "{}", + r.errors[0].message + ); +} + +#[test] +fn wrong_kind_normative_case_a() { + let (_, r) = load(&model( + " - app.service: { name: worker, runsAs: db }", + "", + )); + assert_eq!(codes(&r), ["ERR_REF_WRONG_KIND"]); + assert_eq!(r.errors[0].code, ERR_REF_WRONG_KIND); + assert!( + r.errors[0].message.contains("resource.rdb"), + "{}", + r.errors[0].message + ); +} + +#[test] +fn unresolved_normative_case_b() { + let (_, r) = load(&model( + " - app.service: { name: worker, runsAs: nobody }", + "", + )); + assert_eq!(codes(&r), ["ERR_REF_UNRESOLVED"]); +} + +#[test] +fn wrong_kind_when_two_top_level_nodes_of_other_types_share_the_name() { + let outside = + " - system.software: { name: Shared }\n - deployment.test: { name: Shared }"; + let (_, r) = load(&model( + " - app.service: { name: worker, runsAs: Shared }", + outside, + )); + assert_eq!(codes(&r), ["ERR_REF_WRONG_KIND"]); +} + +const MOVER: &str = " - role.service: + name: mover + children: + - grant.rdb: { name: g2, resource: jobs }"; + +const AUDITOR: &str = " - role.service: + name: auditor + children: + - grant.rdb: { name: g3, resource: Ledger.books }"; + +#[test] +fn wrong_subtype_a_grant_rdb_naming_a_resource_queue() { + let (_, r) = load(&model(MOVER, "")); + assert_eq!(codes(&r), ["ERR_REF_WRONG_KIND"]); + let m = &r.errors[0].message; + assert!(m.contains("resource.queue"), "{m}"); + assert!(m.contains("system \"acme::Parcels\""), "{m}"); +} + +#[test] +fn crosses_system_raises_the_facet_wrong_system_code() { + let (_, r) = load(&model(AUDITOR, "")); + assert_eq!(codes(&r), ["ERR_GRANT_CROSSES_SYSTEM"]); + // A provider's own code is not one this crate knows: `code` is ERR_UNKNOWN, the + // spelling is kept, and the error prints under it. + let e = &r.errors[0]; + assert_eq!(e.code, ERR_UNKNOWN); + assert_eq!(e.provider_code.as_deref(), Some("ERR_GRANT_CROSSES_SYSTEM")); + assert!( + e.to_string().starts_with("ERR_GRANT_CROSSES_SYSTEM: "), + "{e}" + ); + assert!( + e.message.contains("system \"acme::Ledger\""), + "{}", + e.message + ); +} + +#[test] +fn a_facet_error_code_replaces_both_default_codes() { + let outside = " - deployment.test: { name: d1, anyRole: Parcels.nobody } + - deployment.test: { name: d2, anyRole: Parcels.db }"; + assert_eq!( + codes(&load(&model("", outside)).1), + ["ERR_TEST_ROLE", "ERR_TEST_ROLE"] + ); +} + +#[test] +fn a_facet_error_code_in_the_shared_catalogue_keeps_its_code() { + let mut e = facet_error_for("ERR_INVALID_RELATIONSHIP"); + assert_eq!(e.code, "ERR_INVALID_RELATIONSHIP"); + assert_eq!(e.provider_code, None); + e = facet_error_for("ERR_NOT_A_SHARED_CODE"); + assert_eq!(e.code, ERR_UNKNOWN); + assert_eq!(e.code_name(), "ERR_NOT_A_SHARED_CODE"); +} + +fn facet_error_for(code: &str) -> MetaError { + MetaError::at_provider_code(code, "m", crate::source::ErrorSource::Code) +} + +#[test] +fn system_child_and_pkg_system_child_resolve_from_outside_any_system() { + let (reg, r) = load(&model( + "", + " - deployment.test: { name: d1, app: Parcels.api, anyRole: acme::Ledger.clerk }", + )); + clean(&r); + let d1 = at(&r, &["d1"]); + assert_eq!( + type_of(&r, bound_to(®, &r, d1, "app")).as_deref(), + Some("app") + ); + assert_eq!(value_of(&r, d1, "app"), "acme::Parcels.api"); + assert_eq!(value_of(&r, d1, "anyRole"), "acme::Ledger.clerk"); + assert_eq!( + bound_to(®, &r, d1, "anyRole"), + Some(at(&r, &["Ledger", "clerk"])) + ); +} + +#[test] +fn a_bare_value_from_outside_a_system_does_not_see_inside_one() { + let (_, r) = load(&model("", " - deployment.test: { name: d1, app: web }")); + assert_eq!(codes(&r), ["ERR_REF_UNRESOLVED"]); +} + +#[test] +fn same_system_from_a_node_outside_any_system_fails_with_wrong_system_code() { + let (_, r) = load(&model( + "", + " - deployment.test: { name: d1, pinnedRole: Parcels.api }", + )); + assert_eq!(codes(&r), ["ERR_TEST_OUTSIDE"]); +} + +#[test] +fn an_intermediate_segment_shared_by_two_children_is_ambiguous() { + // `Parcels.api.g1`: `api` names both a role and an app under Parcels. + let (_, r) = load(&model( + "", + " - deployment.test: { name: d1, app: Parcels.api.g1 }", + )); + assert_eq!(codes(&r), ["ERR_REF_UNRESOLVED"]); +} + +#[test] +fn an_over_dropping_parent_relative_value_is_a_bad_attr_value() { + let (_, r) = load(&model( + "", + " - deployment.test: { name: d1, app: \"..::..::Parcels.api\" }", + )); + assert_eq!(codes(&r), ["ERR_BAD_ATTR_VALUE"]); + assert!( + r.errors[0] + .message + .contains("climbs above the root package") + ); +} + +#[test] +fn a_parent_relative_dotted_value_resolves_its_owner() { + // ADR-0059 §2: from package `acme::ops`, `..::Parcels.api` names `acme::Parcels.api`. + let text = model("", "") + + " - deployment.test: { name: d1, package: \"acme::ops\", app: \"..::Parcels.api\" }\n"; + let (reg, r) = load(&text); + clean(&r); + let d1 = at(&r, &["d1"]); + assert_eq!(value_of(&r, d1, "app"), "acme::Parcels.api"); + assert_eq!( + bound_to(®, &r, d1, "app"), + Some(at(&r, &["Parcels", "app:api"])) + ); +} + +// ---- inheritance and canonical spelling ---------------------------------------------- + +/// Load, serialize canonically, reload: the reloaded model loads clean and `attr` on the +/// node at `referrer` names the node at `target` in both trees. Returns the value written. +fn round_trip(yaml: &str, referrer: &[&str], attr: &str, target: &[&str]) -> Value { + let (reg, first) = load(yaml); + clean(&first); + assert_eq!( + bound_to(®, &first, at(&first, referrer), attr), + Some(at(&first, target)) + ); + let second = load_as( + ®, + "systems.json", + &canonical_serialize(&first.tree, first.root), + ); + clean(&second); + assert_eq!( + bound_to(®, &second, at(&second, referrer), attr), + Some(at(&second, target)) + ); + second + .tree + .attr(at(&second, referrer), attr) + .cloned() + .unwrap() +} + +#[test] +fn an_inherited_reference_is_looked_up_where_it_was_written() { + // Ledger has no role `api`: `web` inherits `runsAs: api` from Parcels' `base`. + let (reg, r) = load( + "metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - role.service: { name: api } + - app.service: { name: base, runsAs: api } + - system.software: + name: Ledger + children: + - app.service: { name: web, extends: acme::Parcels.base } +", + ); + clean(&r); + assert_eq!( + bound_to(®, &r, at(&r, &["Ledger", "web"]), "runsAs"), + Some(at(&r, &["Parcels", "api"])) + ); +} + +#[test] +fn an_inherited_same_system_reference_is_judged_where_it_was_written() { + // Ledger has its own role `api`, but `web`'s `runsAs: api` was written in Parcels. + let (reg, r) = load( + "metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - role.service: { name: api } + - app.service: { name: base, runsAs: api } + - system.software: + name: Ledger + children: + - role.service: { name: api } + - app.service: { name: web, extends: acme::Parcels.base } +", + ); + clean(&r); + assert_eq!( + bound_to(®, &r, at(&r, &["Ledger", "web"]), "runsAs"), + Some(at(&r, &["Parcels", "role:api"])) + ); +} + +fn inheriting(extra: &str) -> String { + format!( + "metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - role.service: {{ name: clerk }} + - system.software: + name: Ledger + extends: Parcels + children: + - app.service: {{ name: web, runsAs: clerk }} +{extra} +" + ) +} + +#[test] +fn an_inherited_child_keeps_the_path_it_was_addressed_by_and_is_in_that_system() { + let written = round_trip( + &inheriting(" - deployment.test: { name: d1, anyRole: Ledger.clerk }"), + &["d1"], + "anyRole", + &["Parcels", "clerk"], + ); + assert_eq!(written, json!("acme::Ledger.clerk")); + // `web` reaches the inherited `clerk` through its own system, so sameSystem holds. + let (_, r) = load(&inheriting("")); + clean(&r); + assert_eq!( + value_of(&r, at(&r, &["Ledger", "web"]), "runsAs"), + "acme::Ledger.clerk" + ); +} + +#[test] +fn a_path_through_a_shared_intermediate_name_keeps_the_value_as_written() { + let written = round_trip( + "metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - app.service: { name: api } + - role.service: + name: api + children: + - resource.rdb: { name: local } + - grant.rdb: { name: g1, resource: local } +", + &["Parcels", "role:api", "g1"], + "resource", + &["Parcels", "role:api", "local"], + ); + assert_eq!(written, json!("local")); +} + +#[test] +fn a_top_level_key_shared_by_two_types_keeps_the_value_as_written() { + let written = round_trip( + "metadata.root: + package: acme + children: + - deployment.test: { name: Shared } + - system.software: + name: Shared + children: + - role.service: { name: r } + - app.service: { name: a, runsAs: r } +", + &["system:Shared", "a"], + "runsAs", + &["system:Shared", "r"], + ); + assert_eq!(written, json!("r")); +} + +#[test] +fn a_root_absolute_value_a_container_child_would_shadow_keeps_its_root_prefix() { + let written = round_trip( + "metadata.root: + children: + - app.service: { name: api } + - system.software: + name: S + children: + - app.service: { name: api } + - app.service: { name: worker, calls: [\"::api\"] } +", + &["S", "worker"], + "calls", + &["app:api"], + ); + assert_eq!(written, json!(["::api"])); +} + +#[test] +fn a_field_path_value_names_a_top_level_target_never_a_container_child() { + let (reg, r) = load(&model( + " - app.service: { name: worker, reads: db.name }", + " - resource.rdb: { name: db }", + )); + clean(&r); + let worker = at(&r, &["Parcels", "worker"]); + assert_eq!( + bound_to(®, &r, worker, "reads"), + Some(at(&r, &["resource:db"])) + ); + assert_eq!(value_of(&r, worker, "reads"), "acme::db.name"); +} + +#[test] +fn a_facet_attribute_named_like_a_core_reference_is_bound_by_its_facet() { + let (reg, r) = load(&model( + "", + " - deployment.test: { name: d1, via: Parcels.api }", + )); + clean(&r); + let d1 = at(&r, &["d1"]); + assert_eq!( + type_of(&r, bound_to(®, &r, d1, "via")).as_deref(), + Some("role") + ); + assert_eq!(value_of(&r, d1, "via"), "acme::Parcels.api"); +} + +// ---- the core object references keep their codes and hints ---------------------------- + +#[test] +fn a_wrong_kind_object_reference_still_suggests_the_object_in_another_package() { + // `@objectRef: Address` finds the field itself among its containers (wrong kind); the + // object `Address` exists only in package `common`. + let (_, r) = load( + "metadata.root: + children: + - object.value: { name: Address, package: common, children: [ { field.string: { name: street } } ] } + - object.value: + name: Order + package: shop + children: + - field.object: { name: Address, objectRef: Address } +", + ); + assert_eq!(codes(&r), ["ERR_UNRESOLVED_OBJECT_REF"]); + let m = &r.errors[0].message; + assert!( + m.contains("An object named \"Address\" exists in: common::Address."), + "{m}" + ); +} + +#[test] +fn a_parent_relative_references_value_still_suggests_the_object_in_another_package() { + // ADR-0059 §2: `..::Address.id` from `acme::shop` names `acme::Address`; only + // `common::Address` exists. + let (_, r) = load( + "metadata.root: + children: + - object.value: { name: Address, package: common, children: [ { field.string: { name: id } } ] } + - object.entity: + name: Order + package: acme::shop + children: + - field.long: { name: id } + - field.string: { name: addressId } + - identity.primary: { name: pk, fields: [id] } + - identity.reference: { name: address, fields: [addressId], references: \"..::Address.id\" } +", + ); + assert_eq!(codes(&r), ["ERR_INVALID_REFERENCE"]); + let m = &r.errors[0].message; + assert!( + m.contains("An object named \"Address\" exists in: common::Address."), + "{m}" + ); +} + +#[test] +fn a_parent_relative_references_value_resolves_its_owner() { + let (_, r) = load( + "metadata.root: + children: + - object.entity: + name: Address + package: acme + children: + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + - object.entity: + name: Order + package: acme::shop + children: + - field.long: { name: id } + - field.long: { name: addressId } + - identity.primary: { name: pk, fields: [id] } + - identity.reference: { name: address, fields: [addressId], references: \"..::Address.id\" } +", + ); + clean(&r); + let reference = at(&r, &["Order", "address"]); + assert_eq!(value_of(&r, reference, "references"), "acme::Address.id"); +} + +// ---- the registry manifest ------------------------------------------------------------ + +fn manifest_attr(manifest: &Value, type_name: &str, sub_type: &str, name: &str) -> Value { + manifest["types"] + .as_array() + .unwrap() + .iter() + .find(|t| t["type"] == type_name && t["subType"] == sub_type) + .unwrap()["attrs"] + .as_array() + .unwrap() + .iter() + .find(|a| a["name"] == name) + .unwrap() + .clone() +} + +#[test] +fn the_manifest_writes_ref_only_on_an_attribute_that_has_one_in_the_fixed_key_order() { + let manifest = build_manifest(®istry()); + let resource = manifest_attr(&manifest, "grant", "rdb", "resource"); + let keys: Vec<&str> = resource + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect(); + assert_eq!( + keys, + [ + "name", + "valueType", + "isArray", + "required", + "ref", + "description" + ] + ); + assert_eq!( + resource["ref"].to_string(), + r#"{"targetType":"resource","targetSubTypes":["rdb"],"sameSystem":true,"wrongSystemCode":"ERR_GRANT_CROSSES_SYSTEM"}"# + ); + assert_eq!( + manifest_attr(&manifest, "deployment", "test", "anyRole")["ref"].to_string(), + r#"{"targetType":"role","errorCode":"ERR_TEST_ROLE"}"# + ); + assert_eq!( + manifest_attr(&manifest, "app", "service", "reads")["ref"].to_string(), + r#"{"targetType":"resource","fieldPath":true}"# + ); +} + +#[test] +fn a_registry_with_no_facet_writes_no_ref_key() { + let manifest = emit_manifest(&crate::providers::default_registry().unwrap()); + assert!(!manifest.contains("\"ref\"")); +} + +#[test] +fn every_code_is_in_the_shared_catalogue() { + let raw = include_str!("../../data/ERROR-CODES.json"); + let doc: Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for code in [ + ERR_INVALID_RELATIONSHIP, + ERR_INVALID_REFERENCE, + ERR_UNRESOLVED_OBJECT_REF, + ERR_REF_UNRESOLVED, + ERR_REF_WRONG_KIND, + ] { + assert!( + codes.contains_key(code), + "{code} is not in ERROR-CODES.json" + ); + } +} diff --git a/server/rust/metaobjects/src/validate/structure.rs b/server/rust/metaobjects/src/validate/structure.rs index 8cecfb590..68ce6d7cc 100644 --- a/server/rust/metaobjects/src/validate/structure.rs +++ b/server/rust/metaobjects/src/validate/structure.rs @@ -55,7 +55,7 @@ const SEQUENCE_INT_MAX: f64 = 2_147_483_647.0; /// Every node under `root` (the root included), each once where it is declared, /// parents before children: the shape of the reference's structural walks. -pub(super) fn preorder(tree: &Tree, root: NodeId) -> Vec { +pub(crate) fn preorder(tree: &Tree, root: NodeId) -> Vec { let mut out = Vec::with_capacity(tree.len()); let mut stack = vec![root]; while let Some(id) = stack.pop() { diff --git a/server/rust/metaobjects/tests/yaml-conformance-expected-failures.json b/server/rust/metaobjects/tests/yaml-conformance-expected-failures.json index 431b43e56..731a3945c 100644 --- a/server/rust/metaobjects/tests/yaml-conformance-expected-failures.json +++ b/server/rust/metaobjects/tests/yaml-conformance-expected-failures.json @@ -1,9 +1,7 @@ { "language": "rust", "corpus": "fixtures/yaml-conformance", - "notes": "Every YAML-specific behaviour passes: the desugar, the coercion guard, positions, anchors, block scalars, and the attribute-schema errors that follow a coercion. The one fixture below, yaml-ref-root-escape, needs ADR-0059 R2 root-level `::` references and package-aware merging, which are reference-resolution features of this port and not validation passes; it leaves the ledger when they land. The ledger may only shrink and minPassing may only rise.", - "minPassing": 18, - "fixtures": [ - "yaml-ref-root-escape" - ] + "notes": "Every fixture passes: the desugar, the coercion guard, positions, anchors, block scalars, the attribute-schema errors that follow a coercion, and root-level `::` references against a package-qualified same-document merge (yaml-ref-root-escape). The ledger may only shrink and minPassing may only rise.", + "minPassing": 19, + "fixtures": [] } diff --git a/spec/metamodel-definitions.md b/spec/metamodel-definitions.md index 2cad4150b..32950a0f7 100644 --- a/spec/metamodel-definitions.md +++ b/spec/metamodel-definitions.md @@ -194,7 +194,7 @@ facet that sets `sameSystem` before then can never pass and no definition file s The format and the schema are specified here. No definition file uses `ref` yet. -Ports whose spec reader reads and enforces `ref`: TypeScript, C#, Java, Kotlin. +Ports whose spec reader reads and enforces `ref`: TypeScript, C#, Java, Kotlin, Rust. A port joins that line in its own change, while no definition file uses the facet, so no registry output changes. A port on the line writes the facet in its registry manifest as