Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions changelog.d/rust-reference-facet.md
Original file line number Diff line number Diff line change
@@ -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`).
2 changes: 1 addition & 1 deletion docs/CONFORMANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ regenerate with `ls -d fixtures/<corpus>/*/ | 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 | ✓ | ✓ | ✓ |
Expand Down
2 changes: 1 addition & 1 deletion docs/ports/rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
60 changes: 59 additions & 1 deletion server/rust/metaobjects/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//! to the fixture.

use std::fmt;
use std::sync::OnceLock;

use crate::source::ErrorSource;

Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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,
];

Expand All @@ -93,6 +102,10 @@ pub struct MetaError {
pub message: String,
/// Boxed so a `Result<_, MetaError>` stays small on the happy path.
pub source: Box<ErrorSource>,
/// 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<String>,
}

impl MetaError {
Expand All @@ -102,6 +115,7 @@ impl MetaError {
code,
message: message.into(),
source: Box::new(ErrorSource::Code),
provider_code: None,
}
}

Expand All @@ -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<String>, 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<Vec<&'static str>> = 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)
}
}

Expand Down
98 changes: 91 additions & 7 deletions server/rust/metaobjects/src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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 {
Expand All @@ -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<SymbolTable<'_>> = 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<String> {
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,
Expand Down Expand Up @@ -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
Expand Down
32 changes: 31 additions & 1 deletion server/rust/metaobjects/src/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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),
Expand All @@ -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(),
Expand Down
14 changes: 12 additions & 2 deletions server/rust/metaobjects/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading