diff --git a/CHANGELOG.md b/CHANGELOG.md index 6335cff10d..edc9b5849e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,16 +18,15 @@ here.** that reads packages, children, subtypes, attributes, `extends` and references, with the canonical serializer. The loader freezes the tree when it finishes, and a frozen tree memoizes its resolved reads (effective children, attrs and array-ness) for many concurrent readers, as - the other ports do. It passes `registry-conformance` byte for byte and 261 of the 526 - metamodel fixtures; 254 of the rest are on a ledger that may only shrink (the validation passes, - merge warnings, the reporting short-name rule and `script.json` fixtures it does not run yet), - and 11 newer fixtures fail unlisted until those passes land. + the other ports do. It passes `registry-conformance` byte for byte and all 526 of the + metamodel fixtures, and runs every validation pass the TypeScript loader runs, in the same order + (the conformance ledger is empty and may only shrink). While the port is in preview, a new fixture that fails in Rust and is not on the ledger prints a warning and does not fail the lane; a fixture that passed and regresses still fails it, because the ledger records how many fixtures must pass. Nothing is published and there is no codegen or `cargo meta` command yet. Every load records how long each phase and each validation pass - took (`LoadResult::timings`; the `validate` module's ordered pass list is empty on purpose - until those passes land), and `load_bench` prints the per-phase and per-pass medians, with + took (`LoadResult::timings`; the `validate` module's ordered pass list holds the ported passes in + reference order), and `load_bench` prints the per-phase and per-pass medians, with `--write-baseline` / `--baseline` to record and compare a run — a baseline is a record to read, never a threshold, and the committed 20x baseline is a machine-local reference. A `rust` lane runs `cargo fmt --check`, clippy, the tests and the `load_bench` table (record diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 97d21cc83a..6ddbaa02f8 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -70,19 +70,18 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the `explorer.json` data spine: `meta export --effective` + `meta verify --format json` + the generated-file manifest in, one explorer document out) | 1 case (`shop`) | ✓ (the builder is TypeScript, and reads only port-neutral inputs) | — | — | — | — | **Rust (preview, ADR-0065) is not a column yet.** The sixth port runs five corpora -today: `registry-conformance` (byte-identical manifest); the metamodel corpus, 261 -of 526 green, 254 of the rest on `server/rust/metaobjects/tests/conformance-expected-failures.json` -(validation passes, merge warnings, the reporting short-name rule and the `script.json` -fixtures, none of them built yet) and 11 fixtures from the newer corpus failing unlisted -until those same validation passes land; `yaml-conformance`, 15 of 19 (the four on -`yaml-conformance-expected-failures.json` wait for the attribute-schema pass and the -ADR-0059 reference rules); `source-resolution-conformance` (all 28 cases); and -`naming-conformance` (all of it). Those ledgers may only shrink. While the port is in -preview, a new fixture that fails in Rust and is not on the ledger prints a warning and does -not fail the lane; it becomes a hard failure when the port leaves preview. A regression still -fails: the ledger's `minPassing` (261) is the number of fixtures known to pass, and the run -fails when fewer do. The column joins this table when the port leaves -preview. +today: `registry-conformance` (byte-identical manifest); the metamodel corpus, all 526 +green, with every validation pass the TypeScript loader runs, in the same order, so +`server/rust/metaobjects/tests/conformance-expected-failures.json` is empty; +`yaml-conformance`, 18 of 19 (the one on `yaml-conformance-expected-failures.json`, +`yaml-ref-root-escape`, waits for the ADR-0059 root-level `::` reference rules, which are +reference resolution, not a validation pass); `source-resolution-conformance` (all 28 +cases); and `naming-conformance` (all of it). Those ledgers may only shrink. While the +port is in preview, a new fixture that fails in Rust and is not on the ledger prints a +warning and does not fail the lane; it becomes a hard failure when the port leaves +preview. A regression still fails: the ledger's `minPassing` (526) is the number of +fixtures known to pass, and the run fails when fewer do. The column joins this table when +the port leaves preview. A ✓ means the port runs the corpus green; an explicit `n / m` is used where a port carries a ledgered divergence. The two ledgered YAML fixtures are documented diff --git a/server/rust/metaobjects/src/errors.rs b/server/rust/metaobjects/src/errors.rs index ed4a15e713..3799d62aa3 100644 --- a/server/rust/metaobjects/src/errors.rs +++ b/server/rust/metaobjects/src/errors.rs @@ -29,6 +29,11 @@ pub const ERR_PROVIDER_DUPLICATE_ID: &str = "ERR_PROVIDER_DUPLICATE_ID"; pub const ERR_PROVIDER_MISSING_DEPENDENCY: &str = "ERR_PROVIDER_MISSING_DEPENDENCY"; pub const ERR_PROVIDER_DEPENDENCY_CYCLE: &str = "ERR_PROVIDER_DEPENDENCY_CYCLE"; pub const ERR_OVERLAY_NO_TARGET: &str = "ERR_OVERLAY_NO_TARGET"; +pub const ERR_MERGE_CONFLICT: &str = "ERR_MERGE_CONFLICT"; +pub const WARN_DUPLICATE_DECLARATION: &str = "WARN_DUPLICATE_DECLARATION"; +/// The code of a warning that carries only a message: the string-list channel every +/// port's loader wraps at its boundary. +pub const WARN_LEGACY: &str = "WARN_LEGACY"; pub const ERR_MALFORMED_YAML: &str = "ERR_MALFORMED_YAML"; pub const ERR_YAML_COERCION: &str = "ERR_YAML_COERCION"; diff --git a/server/rust/metaobjects/src/loader.rs b/server/rust/metaobjects/src/loader.rs index d00e715738..dac642895f 100644 --- a/server/rust/metaobjects/src/loader.rs +++ b/server/rust/metaobjects/src/loader.rs @@ -15,17 +15,24 @@ use std::path::{Path, PathBuf}; use serde_json::Value; use crate::errors::{ - ERR_BAD_ATTR_VALUE, ERR_EXTENDS_TARGET_MISMATCH, ERR_MALFORMED_JSON, ERR_OVERLAY_NO_TARGET, - ERR_UNKNOWN, ERR_UNKNOWN_SUBTYPE, ERR_UNKNOWN_TYPE, ERR_UNRESOLVED_SUPER, MetaError, + ERR_BAD_ATTR_VALUE, ERR_EXTENDS_TARGET_MISMATCH, ERR_MALFORMED_JSON, ERR_MERGE_CONFLICT, + ERR_OVERLAY_NO_TARGET, ERR_UNKNOWN, ERR_UNKNOWN_SUBTYPE, ERR_UNKNOWN_TYPE, + ERR_UNRESOLVED_SUPER, MetaError, WARN_DUPLICATE_DECLARATION, }; +use crate::naming::{NamingCtx, NamingRegistry, PhysicalNaming}; use crate::node::{Node, NodeId, PACKAGE_SEP, Tree}; use crate::parser::{SUBTYPE_ROOT, TYPE_METADATA, TYPE_OBJECT, parse_document_with}; use crate::registry::TypeRegistry; +use crate::serializer::{normalize, to_canonical_value}; + +const TYPE_SOURCE: &str = "source"; +const SOURCE_SUBTYPE_RDB: &str = "rdb"; use crate::source::ErrorSource; use crate::timing::{ LoadTimings, PHASE_FREEZE, PHASE_JSON, PHASE_MERGE, PHASE_READ, PHASE_REFS, PHASE_SUPERS, PHASE_TREE, PHASE_YAML, }; +use crate::validate::util::{ObjectIndex, find_hop}; use crate::validate::{self, Ctx, Findings}; use crate::yaml::parse_yaml; @@ -66,6 +73,9 @@ pub struct LoadResult { /// Loads metadata against one registry. pub struct Loader<'r> { registry: &'r TypeRegistry, + strict: bool, + naming_registry: NamingRegistry, + naming: PhysicalNaming, } /// Every metadata file under `dir`, recursively, sorted by file name as every @@ -113,7 +123,33 @@ pub fn metadata_files(dir: &Path, exclude_pending: bool) -> std::io::Result Loader<'r> { pub fn new(registry: &'r TypeRegistry) -> Self { - Self { registry } + Self { + registry, + strict: false, + naming_registry: NamingRegistry::builtin(), + naming: PhysicalNaming::default(), + } + } + + /// The project's physical naming (`naming` in `.metaobjects/config.json`) and the + /// registry its strategy names resolve in; column-collision and `@via` reverse-hop + /// validation resolve names through both. Defaults to the built-in registry and + /// [`PhysicalNaming::default`]. A name the registry does not answer is one load + /// error, and validation then runs under the defaults. + #[must_use] + pub fn naming(mut self, registry: NamingRegistry, naming: PhysicalNaming) -> Self { + self.naming_registry = registry; + self.naming = naming; + self + } + + /// Load strictly (ADR-0023): an authored attribute the registry does not declare + /// is `ERR_UNKNOWN_ATTR`, and a child no child rule admits is `ERR_CHILD_NOT_ALLOWED`. + /// Off by default, as in the TypeScript reference. + #[must_use] + pub fn strict(mut self, strict: bool) -> Self { + self.strict = strict; + self } /// Load every metadata file under `dir`. A directory that cannot be walked is @@ -197,10 +233,32 @@ impl<'r> Loader<'r> { } } let mut warnings = Vec::new(); + let mut merged = MergeOut::default(); + let naming_errors: Vec = [ + self.naming_registry + .column_strategy(&self.naming.columns) + .err(), + self.naming + .collections + .as_deref() + .and_then(|p| self.naming_registry.pluralizer(p).err()), + ] + .into_iter() + .flatten() + .collect(); + let default_naming = (NamingRegistry::builtin(), PhysicalNaming::default()); + let (naming_registry, naming) = if naming_errors.is_empty() { + (&self.naming_registry, &self.naming) + } else { + (&default_naming.0, &default_naming.1) + }; + errors.extend(naming_errors); let root = if roots.is_empty() { tree.add(Node::new(TYPE_METADATA, SUBTYPE_ROOT, "")) } else { - let root = timings.phase(PHASE_MERGE, || merge_roots(&mut tree, &roots, &mut errors)); + let root = timings.phase(PHASE_MERGE, || merge_roots(&mut tree, &roots, &mut merged)); + errors.append(&mut merged.errors); + warnings.append(&mut merged.warnings); // Neither pass adds, removes or renames a top-level node, so one index serves both. let top = TopLevel::build(&tree, root); timings.phase(PHASE_SUPERS, || { @@ -211,7 +269,9 @@ impl<'r> Loader<'r> { tree: &tree, root, registry: self.registry, - strict: false, + strict: self.strict, + objects: &top.objects, + naming: NamingCtx::new(naming_registry, naming), }; validate::run(&ctx, &mut findings, &mut timings); errors.append(&mut findings.errors); @@ -232,6 +292,13 @@ impl<'r> Loader<'r> { } } +/// What the merge stage reports. +#[derive(Debug, Default)] +struct MergeOut { + errors: Vec, + warnings: Vec, +} + // ---- merge ----------------------------------------------------------------- /// The package-qualified identity of a root-level node for merge matching: its own @@ -270,7 +337,7 @@ fn find_merge_match(tree: &Tree, target: NodeId, sc: NodeId) -> Option { /// Fold every root into the first (ADR-0055's two-pass fold): plain declarations /// merge by type and name, last writer wins; `overlay: true` nodes are applied once /// every plain declaration is present. -fn merge_roots(tree: &mut Tree, roots: &[NodeId], errors: &mut Vec) -> NodeId { +fn merge_roots(tree: &mut Tree, roots: &[NodeId], out: &mut MergeOut) -> NodeId { let target = roots[0]; let contributions: Vec> = roots .iter() @@ -301,22 +368,24 @@ fn merge_roots(tree: &mut Tree, roots: &[NodeId], errors: &mut Vec) - if tree.node(sc).name.is_empty() { // Unnamed nodes are always distinct. tree.add_child(target, sc); - defer_nested_overlays(tree, sc, errors, Some(&mut pending)); + defer_nested_overlays(tree, sc, out, Some(&mut pending)); continue; } let key = (tree.node(sc).type_name.clone(), root_child_key(tree, sc)); match index.get(&key) { - Some(&tc) => merge_into(tree, tc, sc, errors, Some(&mut pending)), + Some(&tc) => { + merge_into(tree, tc, sc, out, Some(&mut pending)); + } None => { index.insert(key, sc); tree.add_child(target, sc); - defer_nested_overlays(tree, sc, errors, Some(&mut pending)); + defer_nested_overlays(tree, sc, out, Some(&mut pending)); } } } } for (parent, node) in pending { - apply_overlay(tree, parent, node, errors); + apply_overlay(tree, parent, node, out); } target } @@ -325,21 +394,24 @@ fn merge_child_into( tree: &mut Tree, target: NodeId, sc: NodeId, - errors: &mut Vec, + out: &mut MergeOut, pending: Option<&mut Vec<(NodeId, NodeId)>>, -) { +) -> bool { if tree.node(sc).is_overlay { - match pending { - Some(p) => p.push((target, sc)), - None => apply_overlay(tree, target, sc, errors), - } - return; + return match pending { + Some(p) => { + p.push((target, sc)); + false + } + None => apply_overlay(tree, target, sc, out), + }; } match find_merge_match(tree, target, sc) { - Some(tc) => merge_into(tree, tc, sc, errors, pending), + Some(tc) => merge_into(tree, tc, sc, out, pending), None => { tree.add_child(target, sc); - defer_nested_overlays(tree, sc, errors, pending); + defer_nested_overlays(tree, sc, out, pending); + true } } } @@ -347,7 +419,7 @@ fn merge_child_into( fn defer_nested_overlays( tree: &mut Tree, node: NodeId, - errors: &mut Vec, + out: &mut MergeOut, mut pending: Option<&mut Vec<(NodeId, NodeId)>>, ) { // ADR-0039: own — the merge works on the authored layer, before super resolution. @@ -368,10 +440,12 @@ fn defer_nested_overlays( if tree.node(c).is_overlay { match pending.as_deref_mut() { Some(p) => p.push((node, c)), - None => apply_overlay(tree, node, c, errors), + None => { + apply_overlay(tree, node, c, out); + } } } else { - defer_nested_overlays(tree, c, errors, pending.as_deref_mut()); + defer_nested_overlays(tree, c, out, pending.as_deref_mut()); } } } @@ -385,9 +459,9 @@ fn subtree_has_overlay(tree: &Tree, id: NodeId) -> bool { .any(|&c| subtree_has_overlay(tree, c)) } -fn apply_overlay(tree: &mut Tree, parent: NodeId, node: NodeId, errors: &mut Vec) { +fn apply_overlay(tree: &mut Tree, parent: NodeId, node: NodeId, out: &mut MergeOut) -> bool { match find_merge_match(tree, parent, node) { - Some(tc) => merge_into(tree, tc, node, errors, None), + Some(tc) => merge_into(tree, tc, node, out, None), None => { let n = tree.node(node); let p = tree.node(parent); @@ -397,11 +471,12 @@ fn apply_overlay(tree: &mut Tree, parent: NodeId, node: NodeId, errors: &mut Vec format!("{}.{}", p.name, n.name) }; let target = format!("{}:{}", n.type_name, n.name); - errors.push(MetaError::at( + out.errors.push(MetaError::at( ERR_OVERLAY_NO_TARGET, format!("overlay node '{}' has no merge target", n.fqn()), resolved_source(&n.source, referrer, target), )); + false } } } @@ -410,25 +485,143 @@ fn merge_into( tree: &mut Tree, target: NodeId, src: NodeId, - errors: &mut Vec, + out: &mut MergeOut, mut pending: Option<&mut Vec<(NodeId, NodeId)>>, -) { +) -> bool { + // The root is a synthetic accumulator, not an authored node: no merge + // attribution applies to it (this fold only reaches named nodes anyway). + let tracked = !tree.node(target).name.is_empty(); + // Change is tracked as the merge goes (an attr value that differs once normalized as + // the serializer does, or a child added or changed). The one shape the serializer + // rewrites across attr names, a `source.rdb`, is still compared canonically. + let canonical_check = tracked + && tree.node(target).type_name == TYPE_SOURCE + && tree.node(target).sub_type == SOURCE_SUBTYPE_RDB; + let pre_shape = canonical_check.then(|| to_canonical_value(tree, target, false)); + let mut changed = false; + let contributor = tree.node(src).source.files().first().cloned(); + if tracked && !tree.node(src).is_overlay { + detect_attr_conflicts(tree, target, src, contributor.as_deref(), out); + } let attrs: Vec<_> = tree // ADR-0039: own — the merge works on the authored layer, before super resolution. .own_attrs(src) .map(|(k, a)| (k.clone(), a.clone())) .collect(); for (k, a) in attrs { + changed |= tree + .own_attr(target, &k) + .is_none_or(|old| attr_value_differs(&old.value, &a.value)); tree.set_attr(target, &k, a); } // ADR-0039: own — the merge works on the authored layer, before super resolution. for sc in tree.own_children(src).to_vec() { - merge_child_into(tree, target, sc, errors, pending.as_deref_mut()); + changed |= merge_child_into(tree, target, sc, out, pending.as_deref_mut()); + } + if let Some(pre) = pre_shape { + changed = to_canonical_value(tree, target, false) != pre; + } + let (true, Some(contributor)) = (tracked, contributor) else { + return changed; + }; + // A real overlay upgrades the node's source to `merged`; an identical + // re-declaration from another file only warns (FR5c, ADR-0009). + let existing = tree.node(target).source.clone(); + let mut files: Vec = existing.files().to_vec(); + if !changed && (files.is_empty() || files.contains(&contributor)) { + return changed; + } + if !files.contains(&contributor) { + files.push(contributor); + } + files.sort(); + let merged = ErrorSource::Merged { + files, + json_path: existing.json_path().unwrap_or("$").to_string(), + }; + if changed { + tree.node_mut(target).source = merged; + } else { + out.warnings.push(MetaError::at( + WARN_DUPLICATE_DECLARATION, + format!( + "duplicate declaration of {} with no semantic change", + tree.node(target).fqn() + ), + merged, + )); + } + changed +} + +/// Whether two attr values serialize differently (the serializer normalizes numbers). +fn attr_value_differs(old: &Value, new: &Value) -> bool { + old != new && normalize(old.clone()) != normalize(new.clone()) +} + +/// Attrs whose empty string is a value rather than "not set" (FR5c). +const EMPTY_STRING_IS_A_VALUE: &[&str] = &["flattenedColumnPrefix"]; + +fn is_empty_attr_value(v: &Value, name: &str) -> bool { + match v { + Value::Null => true, + Value::String(s) => s.is_empty() && !EMPTY_STRING_IS_A_VALUE.contains(&name), + Value::Array(a) => a.is_empty(), + _ => false, + } +} + +/// FR5c: an attr `src` sets to a different non-empty value than `target` already +/// declares is a conflict; the merge itself still proceeds last-writer-wins. +fn detect_attr_conflicts( + tree: &Tree, + target: NodeId, + src: NodeId, + contributor: Option<&str>, + out: &mut MergeOut, +) { + let existing = &tree.node(target).source; + let mut files: Vec = existing.files().to_vec(); + // ADR-0039: own — merge machinery on the authored declaration layer. + for (name, new) in tree.own_attrs(src) { + let Some(old) = tree.own_attr(target, name) else { + continue; + }; + if is_empty_attr_value(&new.value, name) + || is_empty_attr_value(&old.value, name) + || new.value == old.value + { + continue; + } + if let Some(c) = contributor + && !files.iter().any(|f| f == c) + { + files.push(c.to_string()); + } + files.sort(); + let base = tree.node(src).source.json_path().unwrap_or("$"); + out.errors.push(MetaError::at( + ERR_MERGE_CONFLICT, + format!( + "attr '@{name}' conflicts: existing value {} differs from new value {} on {}", + old.value, + new.value, + tree.node(target).fqn() + ), + ErrorSource::Merged { + files: files.clone(), + json_path: format!("{base}.@{name}"), + }, + )); } } /// A `resolved` envelope at `source`'s location. -fn resolved_source(source: &ErrorSource, referrer: String, target: String) -> ErrorSource { +pub(crate) fn resolved_source( + source: &ErrorSource, + referrer: String, + target: String, +) -> ErrorSource { ErrorSource::Resolved { files: source.files().to_vec(), json_path: source.json_path().unwrap_or("$").to_string(), @@ -718,24 +911,23 @@ fn resolve_supers(tree: &mut Tree, root: NodeId, top: &TopLevel, errors: &mut Ve /// once per pass so each reference is one hash lookup. struct TopLevel { named: HashMap, - objects: HashMap, + objects: ObjectIndex, } impl TopLevel { fn build(tree: &Tree, root: NodeId) -> Self { let mut named = HashMap::new(); - let mut objects = HashMap::new(); // ADR-0039: own — the root's top-level nodes are its declared children; a root extends nothing. for &c in tree.own_children(root) { let key = tree.resolution_key(c); - if tree.node(c).type_name == TYPE_OBJECT { - objects.entry(key.clone()).or_insert(c); - } if !tree.node(c).name.is_empty() { named.entry(key).or_insert(c); } } - Self { named, objects } + Self { + named, + objects: ObjectIndex::build(tree, root), + } } fn bind(map: &HashMap, owner: &str, pkg: &str) -> Option { @@ -762,7 +954,8 @@ fn resolve_references(tree: &mut Tree, root: NodeId, top: &TopLevel) { .map(|(k, _)| k.clone()) .collect(); for name in names { - resolve_attr(tree, top, id, &name, &decl_pkg); + let ref_pkg = referrer_package(tree, top, id, &name, &decl_pkg); + resolve_attr(tree, top, id, &name, &ref_pkg, &decl_pkg); } } // ADR-0039: own — a whole-tree walk visits each physical node once; inherited children are visited where they are declared. @@ -770,19 +963,86 @@ fn resolve_references(tree: &mut Tree, root: NodeId, top: &TopLevel) { } } -fn resolve_one(tree: &Tree, top: &TopLevel, value: &str, pkg: &str) -> Option { +fn resolve_one( + tree: &Tree, + top: &TopLevel, + value: &str, + pkg: &str, + decl_pkg: &str, +) -> Option { let (owner, tail) = split_child_tail(value); - let target = TopLevel::bind(&top.objects, owner, pkg)?; - Some(spell_ref(tree, target, pkg, tail)) + let target = top.objects.resolve(owner, pkg)?; + // Root-level targets are spelled `::Name` unless both packages are root-level. + let spell_from = if pkg.is_empty() { decl_pkg } else { pkg }; + Some(spell_ref(tree, target, spell_from, tail)) } -fn resolve_attr(tree: &mut Tree, top: &TopLevel, id: NodeId, name: &str, pkg: &str) { +/// ADR-0059 R3: the package an own reference attribute of `id` resolves in. A +/// dimension's `@of` resolves in the package of the entity its `@via` walk reaches; +/// a report's `@spine` in the package of its `@from`; everything else in the package +/// of the top-level node that declares it. +fn referrer_package(tree: &Tree, top: &TopLevel, id: NodeId, attr: &str, decl_pkg: &str) -> String { + let node = tree.node(id); + if node.type_name == "dimension" && attr == "of" { + // ADR-0039: resolving: the @via that governs this @of may be inherited. + if let (Some(Value::String(via)), Some(declaring)) = (tree.attr(id, "via"), node.parent) + && !via.is_empty() + { + return match dimension_via_terminal(tree, top, declaring, via) { + Some(t) => tree.effective_package(t), + None => decl_pkg.to_string(), + }; + } + } + if node.type_name == TYPE_OBJECT && node.sub_type == "report" && attr == "spine" { + // ADR-0039: resolving: @from may be inherited. + if let Some(Value::String(from)) = tree.attr(id, "from") + && !from.is_empty() + && let Some(from_node) = top.objects.resolve(from, decl_pkg) + { + return tree.effective_package(from_node); + } + } + decl_pkg.to_string() +} + +/// The entity a dimension's `@via` (`Owner.hop[.hop...]`) reaches, walked from its +/// declaring entity over to-one hops (`relationship` or `identity.reference`), or `None` +/// when the walk fails (the reporting pass reports why). +fn dimension_via_terminal( + tree: &Tree, + top: &TopLevel, + declaring: NodeId, + via: &str, +) -> Option { + let mut parts = via.split(CHILD_REF_SEP); + parts.next().filter(|o| !o.is_empty())?; + let mut current = declaring; + let mut any = false; + for hop_name in parts { + any = true; + let (hop, is_ref) = find_hop(tree, current, hop_name)?; + current = top.objects.hop_target(tree, hop, is_ref)?; + } + any.then_some(current) +} + +fn resolve_attr( + tree: &mut Tree, + top: &TopLevel, + id: NodeId, + name: &str, + pkg: &str, + decl_pkg: &str, +) { // ADR-0039: own — reference resolution rewrites the value this node declares, not an inherited one. let Some(attr) = tree.own_attr(id, name) else { return; }; let new_value = match &attr.value { - Value::String(s) if !s.is_empty() => resolve_one(tree, top, s, pkg).map(Value::String), + Value::String(s) if !s.is_empty() => { + resolve_one(tree, top, s, pkg, decl_pkg).map(Value::String) + } Value::Array(items) if items.iter().all(Value::is_string) => { let mut any = false; let out: Vec = items @@ -790,7 +1050,7 @@ fn resolve_attr(tree: &mut Tree, top: &TopLevel, id: NodeId, name: &str, pkg: &s .map(|v| { let s = v.as_str().unwrap_or_default(); match (!s.is_empty()) - .then(|| resolve_one(tree, top, s, pkg)) + .then(|| resolve_one(tree, top, s, pkg, decl_pkg)) .flatten() { Some(c) => { diff --git a/server/rust/metaobjects/src/node.rs b/server/rust/metaobjects/src/node.rs index c71200db2f..78b9bd9c49 100644 --- a/server/rust/metaobjects/src/node.rs +++ b/server/rust/metaobjects/src/node.rs @@ -26,6 +26,7 @@ //! already borrow the node's own storage, so there is nothing to save. use std::borrow::Cow; +use std::collections::HashMap; use std::sync::OnceLock; use indexmap::IndexMap; @@ -238,22 +239,36 @@ impl Tree { }; visited.push(sup); let mut result = self.effective_children(sup, visited); - let mut claimed = vec![false; result.len()]; + // Each own child replaces the FIRST not-yet-claimed inherited child of its type + // and name; index the inherited ones by that key so the match is not quadratic. + let mut slots: HashMap<(&str, &str), (Vec, usize)> = HashMap::new(); + for (i, &c) in result.iter().enumerate() { + let c = self.node(c); + slots + .entry((c.type_name.as_str(), c.name.as_str())) + .or_default() + .0 + .push(i); + } + let mut replaced: Vec<(usize, NodeId)> = Vec::new(); let mut append = Vec::new(); for &own in &node.children { let o = self.node(own); - let hit = result.iter().enumerate().position(|(i, &c)| { - let c = self.node(c); - !claimed[i] && c.type_name == o.type_name && c.name == o.name - }); + let hit = slots + .get_mut(&(o.type_name.as_str(), o.name.as_str())) + .and_then(|(idx, next)| { + let i = idx.get(*next).copied(); + *next += 1; + i + }); match hit { - Some(i) => { - result[i] = own; - claimed[i] = true; - } + Some(i) => replaced.push((i, own)), None => append.push(own), } } + for (i, own) in replaced { + result[i] = own; + } result.extend(append); result } diff --git a/server/rust/metaobjects/src/serializer.rs b/server/rust/metaobjects/src/serializer.rs index 5bd3fc990c..692ac78246 100644 --- a/server/rust/metaobjects/src/serializer.rs +++ b/server/rust/metaobjects/src/serializer.rs @@ -212,7 +212,7 @@ fn rewrite_physical_name(attrs: &mut BTreeMap) { /// Whole-number doubles print as integers; a map of scalars sorts its keys (the /// `properties` shape); any other map keeps its order (a filter's clauses do). -fn normalize(v: Value) -> Value { +pub(crate) fn normalize(v: Value) -> Value { match v { Value::Number(n) => { if n.is_f64() diff --git a/server/rust/metaobjects/src/source.rs b/server/rust/metaobjects/src/source.rs index 3429650017..c2059108bf 100644 --- a/server/rust/metaobjects/src/source.rs +++ b/server/rust/metaobjects/src/source.rs @@ -18,6 +18,11 @@ pub enum ErrorSource { json_path: String, position: Option, }, + /// A node several files contributed to: every contributing file, sorted. + Merged { + files: Vec, + json_path: String, + }, /// A reference that did not resolve: the referring node and the reference. Resolved { files: Vec, @@ -57,6 +62,7 @@ impl ErrorSource { ErrorSource::Json { .. } => "json", ErrorSource::Yaml { .. } => "yaml", ErrorSource::Resolved { .. } => "resolved", + ErrorSource::Merged { .. } => "merged", } } @@ -65,6 +71,7 @@ impl ErrorSource { ErrorSource::Code => &[], ErrorSource::Json { files, .. } | ErrorSource::Yaml { files, .. } + | ErrorSource::Merged { files, .. } | ErrorSource::Resolved { files, .. } => files, } } @@ -74,6 +81,7 @@ impl ErrorSource { ErrorSource::Code => None, ErrorSource::Json { json_path, .. } | ErrorSource::Yaml { json_path, .. } + | ErrorSource::Merged { json_path, .. } | ErrorSource::Resolved { json_path, .. } => Some(json_path), } } @@ -90,6 +98,7 @@ impl ErrorSource { pub fn map_files(&mut self, f: impl Fn(&str) -> String) { if let ErrorSource::Json { files, .. } | ErrorSource::Yaml { files, .. } + | ErrorSource::Merged { files, .. } | ErrorSource::Resolved { files, .. } = self { for file in files.iter_mut() { diff --git a/server/rust/metaobjects/src/validate.rs b/server/rust/metaobjects/src/validate.rs deleted file mode 100644 index aaf8fda884..0000000000 --- a/server/rust/metaobjects/src/validate.rs +++ /dev/null @@ -1,43 +0,0 @@ -//! The validation passes, run in the order the TypeScript reference runs them. -//! -//! Each pass is one named function over the merged, super-resolved tree. Order is -//! part of the contract: the corpus compares error envelopes position by position, so -//! a pass added here goes where the reference runs it. Every pass is timed under its -//! own name (see [`crate::timing`]), so adding one shows in the benchmark table. - -use crate::errors::MetaError; -use crate::node::{NodeId, Tree}; -use crate::registry::TypeRegistry; -use crate::timing::{LoadTimings, PHASE_VALIDATE}; - -/// What a pass reads. -pub struct Ctx<'a> { - pub tree: &'a Tree, - pub root: NodeId, - pub registry: &'a TypeRegistry, - /// Strict mode, as the loader option of that name. - pub strict: bool, -} - -/// What a pass writes. Errors and warnings are separate channels, as in every port. -#[derive(Debug, Default)] -pub struct Findings { - pub errors: Vec, - pub warnings: Vec, -} - -/// One validation pass. -pub type PassFn = fn(&Ctx<'_>, &mut Findings); - -/// Every pass, in the reference's order, each under the name the benchmark prints. -pub const PASSES: &[(&str, PassFn)] = &[]; - -/// Run every pass, timing each under its own name and all of them under the -/// `validation` phase. -pub fn run(ctx: &Ctx<'_>, findings: &mut Findings, timings: &mut LoadTimings) { - let start = std::time::Instant::now(); - for (name, pass) in PASSES { - timings.pass(name, || pass(ctx, findings)); - } - timings.add_phase(PHASE_VALIDATE, start.elapsed()); -} diff --git a/server/rust/metaobjects/src/validate/attrs.rs b/server/rust/metaobjects/src/validate/attrs.rs new file mode 100644 index 0000000000..079a67f6d1 --- /dev/null +++ b/server/rust/metaobjects/src/validate/attrs.rs @@ -0,0 +1,682 @@ +//! `validateAttrSchema`: each node's `@`-attributes against its registered +//! `(type, subType)` schema, plus the strict-load provenance and child-placement +//! checks (ADR-0023, FR-033) and the `field.enum` / `@dbColumnType` content rules the +//! reference keeps in the same pass. +//! +//! Not ported: the reference's retired-vocabulary hints (`retired-vocabulary.ts`) +//! append a migration note to the `ERR_UNKNOWN_ATTR` / bad-value message and attach +//! suggestions. They change no load outcome, only message text. + +use std::collections::HashMap; + +use serde_json::Value; + +use crate::errors::{ + ERR_BAD_ATTR_VALUE, ERR_MISSING_REQUIRED_ATTR, ERR_PROVIDER_ATTR_CONFLICT, ERR_UNKNOWN_ATTR, +}; +use crate::json::{js_display, js_number}; +use crate::node::{NodeId, Tree}; +use crate::registry::{AttrSchema, TypeDefinition}; +use crate::validate::field::{DbColumnType, parse_db_column_type}; +use crate::validate::structure::preorder; +use crate::validate::util::{child_label, error_at}; +use crate::validate::{Ctx, Findings}; + +pub const ERR_CHILD_NOT_ALLOWED: &str = "ERR_CHILD_NOT_ALLOWED"; +pub const ERR_ENUM_EXTENDS_VALUES_CONFLICT: &str = "ERR_ENUM_EXTENDS_VALUES_CONFLICT"; + +const TYPE_FIELD: &str = "field"; +const TYPE_METADATA: &str = "metadata"; +const SUB_ENUM: &str = "enum"; +const SUB_STRING: &str = "string"; +const ATTR_SUBTYPE_PROPERTIES: &str = "properties"; +const ATTR_SUBTYPE_STRINGARRAY: &str = "stringarray"; +const A_VALUES: &str = "values"; +const A_COERCE_DEFAULT: &str = "coerceDefault"; +const A_DEFAULT: &str = "default"; +const A_INT_VALUE_MAP: &str = "intValueMap"; +const A_STRING_VALUE_MAP: &str = "stringValueMap"; +const A_DB_COLUMN_TYPE: &str = "dbColumnType"; +const A_MAX_LENGTH: &str = "maxLength"; +const INT32_MIN: f64 = -2_147_483_648.0; +const INT32_MAX: f64 = 2_147_483_647.0; + +/// What one `(type, subType)` accepts, built once per type: its own attributes, then +/// the common attributes it does not already declare. +struct Effective<'r> { + by_name: HashMap<&'r str, &'r AttrSchema>, + required: Vec<&'r AttrSchema>, + /// The first common attribute that collides with a per-type one, until reported. + pending_conflict: Option<&'r str>, + def: Option<&'r TypeDefinition>, +} + +fn runtime_type_name(v: &Value) -> &'static str { + match v { + Value::Array(_) => "array", + Value::Object(_) | Value::Null => "object", + Value::String(_) => "string", + Value::Number(_) => "number", + Value::Bool(_) => "boolean", + } +} + +fn is_integer(v: &Value) -> bool { + match v { + Value::Number(n) => { + n.is_i64() || n.is_u64() || n.as_f64().is_some_and(crate::json::is_js_integer) + } + _ => false, + } +} + +/// A MetaAttr's `validateValue`, dispatched on the attr subtype. +fn validate_value(sub_type: &str, name: &str, value: &Value) -> Vec { + let type_error = |sub: &str| { + vec![format!( + "attribute '@{name}' must be of type '{sub}' but got {}", + runtime_type_name(value) + )] + }; + let object_shape = matches!(value, Value::Object(_)); + match sub_type { + ATTR_SUBTYPE_STRINGARRAY => match value { + Value::Array(a) if a.iter().all(Value::is_string) => Vec::new(), + _ => vec![format!( + "attribute '@{name}' must be a string[] but got {}", + runtime_type_name(value) + )], + }, + "filter" | ATTR_SUBTYPE_PROPERTIES | "expression" => { + if object_shape { + Vec::new() + } else { + type_error(sub_type) + } + } + "intMap" => { + let Value::Object(map) = value else { + return type_error("intMap"); + }; + let mut errors = Vec::new(); + for (key, member) in map { + if !is_integer(member) { + errors.push(format!( + "attribute '@{name}' member '{key}' has value '{}' which is not an integer", + js_display(member) + )); + } else if let Some(x) = member + .as_f64() + .filter(|x| !(INT32_MIN..=INT32_MAX).contains(x)) + { + errors.push(format!( + "attribute '@{name}' member '{key}' has value '{}' which is outside the 32-bit signed integer range", + js_display(&Value::from(x as i64)) + )); + } + } + errors + } + "int" | "long" => match value { + Value::Number(n) if is_integer(value) => { + let _ = n; + Vec::new() + } + Value::Number(n) => vec![format!( + "attribute '@{name}' must be of type '{sub_type}' but got the fraction {}; this attribute is integral, so write an integer (for a validator @min/@max, use an integer bound)", + js_number(n) + )], + _ => type_error(sub_type), + }, + "double" => { + if value.is_number() { + Vec::new() + } else { + type_error(sub_type) + } + } + "boolean" => { + if value.is_boolean() { + Vec::new() + } else { + type_error(sub_type) + } + } + // string, class, base and anything unmapped read as a string attr. + _ => { + if value.is_string() { + Vec::new() + } else { + type_error(sub_type) + } + } + } +} + +/// `Array.prototype.includes` equality: numbers by value, everything else structural. +fn js_same(a: &Value, b: &Value) -> bool { + match (a, b) { + (Value::Number(x), Value::Number(y)) => x.as_f64() == y.as_f64(), + _ => a == b, + } +} + +fn is_enum_member(m: &str) -> bool { + let mut chars = m.chars(); + chars + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') +} + +const DB_COLUMN_TYPE_PAIRINGS: &str = "uuid (field.string), jsonb (field.string), text (field.string), varchar (field.string), character varying (field.string), varchar(n) (field.string), character varying(n) (field.string), character(n) (field.string)"; + +fn enum_members(tree: &Tree, id: NodeId) -> Vec { + match tree.attr(id, A_VALUES) { + Some(Value::Array(a)) => a.iter().map(js_display).collect(), + _ => Vec::new(), + } +} + +fn is_shared_enum_declaration(tree: &Tree, id: Option) -> bool { + id.is_some_and(|s| { + let n = tree.node(s); + n.type_name == TYPE_FIELD + && n.sub_type == SUB_ENUM + && n.is_abstract + && n.parent + .is_some_and(|p| tree.node(p).type_name == TYPE_METADATA) + }) +} + +fn own_value<'a>(tree: &'a Tree, id: NodeId, name: &str) -> Option<&'a Value> { + tree.own_attr(id, name).map(|a| &a.value) +} + +fn check_enum(tree: &Tree, id: NodeId, out: &mut Findings) { + let lbl = child_label(tree, id); + let super_node = tree.node(id).super_node; + let shared = is_shared_enum_declaration(tree, super_node); + let shared_label = || super_node.map(|s| child_label(tree, s)).unwrap_or_default(); + let mut push = |code: &'static str, msg: String| out.errors.push(error_at(tree, id, code, msg)); + + // Check 4: @values content. + if let Some(Value::Array(raw)) = own_value(tree, id, A_VALUES) { + if raw.is_empty() { + push( + ERR_BAD_ATTR_VALUE, + format!("{lbl} must declare at least one value in '@{A_VALUES}'."), + ); + } else { + let mut seen: Vec = Vec::new(); + for m in raw { + let m = js_display(m); + if !is_enum_member(&m) { + push( + ERR_BAD_ATTR_VALUE, + format!( + "{lbl} attribute '@{A_VALUES}' member '{m}' is not a valid identifier (must match ^[A-Za-z_][A-Za-z0-9_]*$). Non-identifier-safe member strings require a symbol↔value mapping (deferred)." + ), + ); + } else if seen.contains(&m) { + push( + ERR_BAD_ATTR_VALUE, + format!("{lbl} attribute '@{A_VALUES}' has duplicate member '{m}'."), + ); + } else { + seen.push(m); + } + } + } + if shared { + push( + ERR_ENUM_EXTENDS_VALUES_CONFLICT, + format!( + "{lbl} extends shared abstract enum '{}' AND declares its own '@{A_VALUES}' — a shared enum's member set is owned by the shared declaration; remove the own '@{A_VALUES}' to inherit it, or extend a non-shared enum instead.", + shared_label() + ), + ); + } + } + + // Check 5: enum fallback attrs name a member. + let members = enum_members(tree, id); + for attr in [A_COERCE_DEFAULT, A_DEFAULT] { + if let Some(Value::String(v)) = own_value(tree, id, attr) + && !members.contains(v) + { + push( + ERR_BAD_ATTR_VALUE, + format!( + "{lbl} attribute '@{attr}' value '{v}' is not one of '@{A_VALUES}': {}.", + members.join(", ") + ), + ); + } + } + + // Check 5b: @intValueMap content. + if let Some(raw) = + own_value(tree, id, A_INT_VALUE_MAP).filter(|v| v.is_object() || v.is_array()) + { + if shared { + push( + ERR_ENUM_EXTENDS_VALUES_CONFLICT, + format!( + "{lbl} extends shared abstract enum '{}' AND declares its own '@{A_INT_VALUE_MAP}' — a shared enum's integer backing is owned by the shared declaration; move '@{A_INT_VALUE_MAP}' onto '{}' to inherit it, or extend a non-shared enum instead.", + shared_label(), + shared_label() + ), + ); + } + let ents = entries(raw); + let (missing, extra) = key_diff(&members, ents.iter().map(|(k, _)| k.as_str())); + if !missing.is_empty() || !extra.is_empty() { + push( + ERR_BAD_ATTR_VALUE, + format!( + "{lbl} attribute '@{A_INT_VALUE_MAP}' keys must exactly match '@{A_VALUES}' members{}{}.", + list_note(" (missing: ", &missing), + list_note(" (unknown: ", &extra) + ), + ); + } + let mut seen: Vec<(f64, &str)> = Vec::new(); + for (member, value) in &ents { + let Some(n) = value.as_f64().filter(|_| is_integer(value)) else { + continue; // reported by the attr's own shape check + }; + match seen.iter().find(|(v, _)| *v == n) { + Some((_, owner)) => push( + ERR_BAD_ATTR_VALUE, + format!( + "{lbl} attribute '@{A_INT_VALUE_MAP}' members '{owner}' and '{member}' share the same value {}; every member must have a unique int.", + js_display(value) + ), + ), + None => seen.push((n, member)), + } + } + } + + // Check 5c: @stringValueMap content. + if let Some(raw) = own_value(tree, id, A_STRING_VALUE_MAP) { + let mut bad = |code: &'static str, msg: String| { + push( + code, + format!("{lbl} attribute '@{A_STRING_VALUE_MAP}' {msg}"), + ); + }; + if shared { + bad( + ERR_ENUM_EXTENDS_VALUES_CONFLICT, + format!( + "is declared on a field extending shared abstract enum '{}' — a shared enum's stored strings are owned by the shared declaration; move it onto '{}' to inherit it.", + shared_label(), + shared_label() + ), + ); + } else if tree.attr(id, A_INT_VALUE_MAP).is_some() { + bad( + ERR_BAD_ATTR_VALUE, + format!( + "is refused beside '@{A_INT_VALUE_MAP}': an @intValueMap enum is stored as integers, not strings. Keep one." + ), + ); + } else if tree.resolved_is_array(id) { + bad( + ERR_BAD_ATTR_VALUE, + format!( + "is refused on an array enum: its column holds the members as text[] elements, which no port maps through @{A_STRING_VALUE_MAP}." + ), + ); + } else if let Value::Object(map) = raw { + let (missing, extra) = key_diff(&members, map.keys().map(String::as_str)); + if !missing.is_empty() || !extra.is_empty() { + bad( + ERR_BAD_ATTR_VALUE, + format!( + "keys must exactly match '@{A_VALUES}' members{}{}.", + list_note(" (missing: ", &missing), + list_note(" (unknown: ", &extra) + ), + ); + } + let mut seen: Vec<(&str, &str)> = Vec::new(); + for (member, value) in map { + match value.as_str().filter(|s| !s.is_empty()) { + None => bad( + ERR_BAD_ATTR_VALUE, + format!("member '{member}' must map to a non-empty string."), + ), + Some(s) => match seen.iter().find(|(v, _)| *v == s) { + Some((_, owner)) => bad( + ERR_BAD_ATTR_VALUE, + format!( + "members '{owner}' and '{member}' share the stored string '{s}'; every member must have a unique one." + ), + ), + None => seen.push((s, member)), + }, + } + } + } else { + bad( + ERR_BAD_ATTR_VALUE, + "must be an object of { member: storedString }.".to_string(), + ); + } + } +} + +/// The entries of a JS object or array value, as `Object.entries` lists them. +fn entries(v: &Value) -> Vec<(String, &Value)> { + match v { + Value::Object(m) => m.iter().map(|(k, v)| (k.clone(), v)).collect(), + Value::Array(a) => a + .iter() + .enumerate() + .map(|(i, v)| (i.to_string(), v)) + .collect(), + _ => Vec::new(), + } +} + +fn key_diff<'a>( + members: &[String], + keys: impl Iterator + Clone, +) -> (Vec, Vec) { + let missing = members + .iter() + .filter(|m| !keys.clone().any(|k| k == m.as_str())) + .cloned() + .collect(); + let extra = keys + .filter(|k| !members.iter().any(|m| m == k)) + .map(str::to_string) + .collect(); + (missing, extra) +} + +fn list_note(prefix: &str, items: &[String]) -> String { + if items.is_empty() { + String::new() + } else { + format!("{prefix}{})", items.join(", ")) + } +} + +/// Check 6: `@dbColumnType` pairing and the `@maxLength` it must hold. +fn check_db_column_type(tree: &Tree, id: NodeId, out: &mut Findings) { + // ADR-0039: own: @dbColumnType is physical and never inherited. + let Some(Value::String(value)) = own_value(tree, id, A_DB_COLUMN_TYPE) else { + return; + }; + let lbl = child_label(tree, id); + let sub = &tree.node(id).sub_type; + let parsed = parse_db_column_type(value); + let length = match parsed { + Some(DbColumnType::Varchar(Some(n))) | Some(DbColumnType::Char(n)) => Some(n), + _ => None, + }; + if parsed.is_none() || sub != SUB_STRING { + out.errors.push(error_at( + tree, + id, + ERR_BAD_ATTR_VALUE, + format!( + "{lbl} attribute '@{A_DB_COLUMN_TYPE}' value '{value}' is not legal on field.{sub}. Legal @{A_DB_COLUMN_TYPE} pairings: {DB_COLUMN_TYPE_PAIRINGS}." + ), + )); + } else if let (Some(length), Some(Value::Number(max))) = (length, tree.attr(id, A_MAX_LENGTH)) + && max.as_f64().is_some_and(|m| m > f64::from(length)) + { + out.errors.push(error_at( + tree, + id, + ERR_BAD_ATTR_VALUE, + format!( + "{lbl} declares @{A_MAX_LENGTH}: {} over '@{A_DB_COLUMN_TYPE}: {value}', which holds {length}; a value the field accepts would not fit the column.", + js_number(max) + ), + )); + } +} + +/// Run the attribute-schema pass. +pub fn attr_schema(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + let registry = ctx.registry; + let mut cache: HashMap<(&str, &str), Effective<'_>> = HashMap::new(); + for id in preorder(tree, ctx.root) { + let node = tree.node(id); + let eff = cache + .entry((node.type_name.as_str(), node.sub_type.as_str())) + .or_insert_with(|| { + let def = registry.find(&node.type_name, &node.sub_type); + let mut by_name: HashMap<&str, &AttrSchema> = HashMap::new(); + let mut required = Vec::new(); + for a in def.map_or(&[][..], |d| d.attributes.as_slice()) { + by_name.insert(a.name.as_str(), a); + if a.required { + required.push(a); + } + } + let mut pending_conflict = None; + for ca in registry.common_attrs() { + if by_name.contains_key(ca.name.as_str()) { + pending_conflict.get_or_insert(ca.name.as_str()); + } else { + by_name.insert(ca.name.as_str(), ca); + if ca.required { + required.push(ca); + } + } + } + Effective { + by_name, + required, + pending_conflict, + def, + } + }); + let type_key = || format!("{}.{}", node.type_name, node.sub_type); + + if let Some(name) = eff.pending_conflict.take() { + out.errors.push(error_at( + tree, + id, + ERR_PROVIDER_ATTR_CONFLICT, + format!( + "Common attr '{name}' conflicts with per-type attr on {}", + type_key() + ), + )); + } + + if ctx.strict { + // Check 0 (ADR-0023): an own attribute no schema declares. + // ADR-0039: own: an inherited attribute was validated on its declaring node. + for (name, attr) in tree.own_attrs(id) { + if attr.sub_type == ATTR_SUBTYPE_PROPERTIES + || eff.by_name.contains_key(name.as_str()) + { + continue; + } + out.errors.push(error_at( + tree, + id, + ERR_UNKNOWN_ATTR, + format!( + "Unknown attribute '@{name}' on {} — not declared by any registered provider for {}", + child_label(tree, id), + type_key() + ), + )); + } + // Check 0b (FR-033): structural child placement. + if let Some(def) = eff.def { + // ADR-0039: own: an inherited child was placement-checked on its declarer. + for &child in tree.own_children(id) { + let c = tree.node(child); + if !def + .child_rules + .iter() + .any(|r| r.matches(&c.type_name, &c.sub_type, &c.name)) + { + out.errors.push(error_at( + tree, + id, + ERR_CHILD_NOT_ALLOWED, + format!( + "Child {} is not allowed under {} — no registered child rule for {} admits (type='{}', subType='{}', name='{}')", + child_label(tree, child), + child_label(tree, id), + type_key(), + c.type_name, + c.sub_type, + c.name + ), + )); + } + } + } + } + + if !eff.by_name.is_empty() { + // Check 1: required attributes, inherited ones counting (abstract nodes are templates). + if !node.is_abstract { + for spec in &eff.required { + if tree.attr(id, &spec.name).is_none() { + out.errors.push(error_at( + tree, + id, + ERR_MISSING_REQUIRED_ATTR, + format!( + "{} is missing required attribute '@{}'", + child_label(tree, id), + spec.name + ), + )); + } + } + } + // Checks 2 + 3: well-typed and in range. + // ADR-0039: own: an inherited attribute was validated on its declaring node. + for (name, attr) in tree.own_attrs(id) { + let Some(spec) = eff.by_name.get(name.as_str()) else { + continue; + }; + let value = &attr.value; + // A null value is an attribute that was authored but left unset (YAML `~`): + // the reference's tree builder drops it, so it is never judged. + if value.is_null() { + continue; + } + if spec.value_type.is_some() { + let errors = validate_value(&attr.sub_type, name, value); + if !errors.is_empty() { + for e in errors { + out.errors.push(error_at( + tree, + id, + ERR_BAD_ATTR_VALUE, + format!("{} {e}", child_label(tree, id)), + )); + } + continue; + } + } + let Some(allowed) = spec + .allowed_values + .as_deref() + .filter(|a| !a.is_empty() && name != A_DB_COLUMN_TYPE) + else { + continue; + }; + let offenders: Vec<&Value> = match value { + Value::Array(items) => items + .iter() + .filter(|v| !allowed.iter().any(|a| js_same(a, v))) + .collect(), + v if allowed.iter().any(|a| js_same(a, v)) => Vec::new(), + v => vec![v], + }; + for bad in offenders { + out.errors.push(error_at( + tree, + id, + ERR_BAD_ATTR_VALUE, + format!( + "{} attribute '@{name}' has value '{}' which is not one of the allowed values: {}", + child_label(tree, id), + js_display(bad), + allowed.iter().map(js_display).collect::>().join(", ") + ), + )); + } + } + } + + // Checks 4-6 run after the schema returns early in the reference only when the + // node has no schema at all, and field nodes always have one. + if node.type_name == TYPE_FIELD && !eff.by_name.is_empty() { + if node.sub_type == SUB_ENUM { + check_enum(tree, id, out); + } + check_db_column_type(tree, id, out); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn every_code_is_in_the_shared_catalogue() { + let raw = include_str!("../../../../../fixtures/conformance/ERROR-CODES.json"); + let doc: Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for code in [ERR_CHILD_NOT_ALLOWED, ERR_ENUM_EXTENDS_VALUES_CONFLICT] { + assert!( + codes.contains_key(code), + "{code} is not in ERROR-CODES.json" + ); + } + } + + #[test] + fn value_shapes_follow_the_attr_subtype() { + assert!(validate_value("int", "n", &json!(4.0)).is_empty()); + assert!(validate_value("int", "n", &json!(4)).is_empty()); + assert!(validate_value("int", "n", &json!(4.5))[0].contains("fraction 4.5")); + assert!(validate_value("boolean", "b", &json!("x"))[0].contains("got string")); + assert!(validate_value("stringarray", "f", &json!(["a", 1]))[0].contains("string[]")); + assert!(validate_value("filter", "f", &json!("legacy"))[0].contains("'filter'")); + assert_eq!( + validate_value("intMap", "m", &json!({"a": 1, "b": 1.5})).len(), + 1 + ); + assert!( + validate_value("intMap", "m", &json!({"a": 3_000_000_000_i64}))[0].contains("32-bit") + ); + } + + #[test] + fn db_column_types_parse_like_the_reference() { + assert_eq!(parse_db_column_type("uuid"), Some(DbColumnType::Uuid)); + assert_eq!( + parse_db_column_type("varchar(40)"), + Some(DbColumnType::Varchar(Some(40))) + ); + assert_eq!( + parse_db_column_type("character(3)"), + Some(DbColumnType::Char(3)) + ); + assert_eq!(parse_db_column_type("varchar(0)"), None); + assert_eq!(parse_db_column_type("varchar(1234567890)"), None); + assert_eq!(parse_db_column_type("char(3)"), None); + } +} diff --git a/server/rust/metaobjects/src/validate/field.rs b/server/rust/metaobjects/src/validate/field.rs new file mode 100644 index 0000000000..53a544abf0 --- /dev/null +++ b/server/rust/metaobjects/src/validate/field.rs @@ -0,0 +1,366 @@ +//! Field-level validation: the passes `validateFieldObjectStorage`, `validateFieldMap`, +//! `validateEnumMaxLength` and `validateFieldDefaults`, plus the `@dbColumnType` +//! parser the attribute-schema and expression passes share. + +use serde_json::Value; + +use super::util::error_at; +use super::{Ctx, Findings}; +use crate::errors::{ERR_BAD_ATTR_VALUE, MetaError}; +use crate::json::js_display; +use crate::node::NodeId; + +pub const ERR_ENUM_EXTENDS_VALUES_CONFLICT: &str = "ERR_ENUM_EXTENDS_VALUES_CONFLICT"; +pub const ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH: &str = "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH"; +pub const ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP: &str = "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP"; +pub const ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF: &str = "ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF"; +pub const ERR_STORAGE_FLATTENED_ARRAY: &str = "ERR_STORAGE_FLATTENED_ARRAY"; +pub const ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE: &str = + "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE"; + +const TYPE_OBJECT: &str = "object"; +const TYPE_FIELD: &str = "field"; +const SUB_ENUM: &str = "enum"; +const SUB_OBJECT: &str = "object"; +const SUB_MAP: &str = "map"; +const A_VALUES: &str = "values"; +const A_INT_VALUE_MAP: &str = "intValueMap"; +const A_STRING_VALUE_MAP: &str = "stringValueMap"; +const A_MAX_LENGTH: &str = "maxLength"; +const A_DEFAULT: &str = "default"; +const A_OBJECT_REF: &str = "objectRef"; +const A_STORAGE: &str = "storage"; +const A_FLATTENED_COLUMN_PREFIX: &str = "flattenedColumnPrefix"; +const A_VALUE_TYPE: &str = "valueType"; +const STORAGE_FLATTENED: &str = "flattened"; +const MAP_SCALAR_VALUE_SUBTYPES: &[&str] = &[ + "string", + "int", + "long", + "double", + "float", + "decimal", + "boolean", + "date", + "time", + "timestamp", + "uuid", +]; + +/// A parsed `@dbColumnType` (`parseDbColumnType`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DbColumnType { + Uuid, + Jsonb, + Text, + Varchar(Option), + Char(u32), +} + +/// Parse a `@dbColumnType` value, or `None` for one that is not legal. The spellings +/// are Postgres's own, matched exactly. +pub fn parse_db_column_type(value: &str) -> Option { + match value { + "uuid" => return Some(DbColumnType::Uuid), + "jsonb" => return Some(DbColumnType::Jsonb), + "text" => return Some(DbColumnType::Text), + "varchar" | "character varying" => return Some(DbColumnType::Varchar(None)), + _ => {} + } + let (kind, rest) = ["varchar(", "character varying(", "character("] + .iter() + .find_map(|p| value.strip_prefix(p).map(|r| (*p, r)))?; + let digits = rest.strip_suffix(')')?; + if digits.is_empty() + || digits.len() > 9 + || !digits.bytes().all(|b| b.is_ascii_digit()) + || digits.starts_with('0') + { + return None; + } + let n: u32 = digits.parse().ok()?; + Some(if kind == "character(" { + DbColumnType::Char(n) + } else { + DbColumnType::Varchar(Some(n)) + }) +} + +// ---- validateFieldObjectStorage / validateFieldMap ----------------------------------- + +fn non_empty_str(v: Option<&Value>) -> Option<&str> { + v.and_then(Value::as_str).filter(|s| !s.is_empty()) +} + +pub fn validate_field_object_storage(ctx: &Ctx<'_>, f: &mut Findings) { + let tree = ctx.tree; + for &obj in tree + .children(ctx.root) + .iter() + .filter(|&&c| tree.node(c).type_name == TYPE_OBJECT) + { + let oname = &tree.node(obj).name; + // ADR-0039: own — the concrete field is an OWN child; its attrs are read resolving. + for &fld in tree + .own_children(obj) + .iter() + .filter(|&&c| tree.node(c).type_name == TYPE_FIELD) + { + let n = tree.node(fld); + let has_ref = non_empty_str(tree.attr(fld, A_OBJECT_REF)).is_some(); + if n.sub_type == SUB_OBJECT && !has_ref { + f.errors.push(error_at(tree, fld, ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF, format!( + "field.object \"{oname}.{}\" has no @objectRef; a field.object models a typed nested value and requires one. Take the first of these that fits: a known key set → declare an object.value and point @objectRef at it; dynamic keys over a known value type → field.map with @objectRef (a value object) or @valueType (a scalar); a genuinely open bag no reader pins a key in → @dbColumnType: jsonb on a field.string.", n.name))); + continue; + } + let storage = tree.attr(fld, A_STORAGE); + let is_flat = storage.and_then(Value::as_str) == Some(STORAGE_FLATTENED); + if tree.attr(fld, A_FLATTENED_COLUMN_PREFIX).is_some() && !is_flat { + let shown = match storage { + None | Some(Value::Null) => "not set (jsonb)".to_string(), + Some(s) => format!("\"{}\"", js_display(s)), + }; + f.errors.push(error_at(tree, fld, ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE, format!( + "field.object \"{oname}.{}\" sets @flattenedColumnPrefix, but its @storage is {shown}; only a @storage \"flattened\" value object puts its members' columns in the owning table. Set @storage \"flattened\", or remove @flattenedColumnPrefix.", n.name))); + } + if is_flat && tree.resolved_is_array(fld) { + f.errors.push(error_at(tree, fld, ERR_STORAGE_FLATTENED_ARRAY, format!( + "field \"{oname}.{}\" sets @storage \"flattened\" with isArray=true; flattened storage requires a single nested value", n.name))); + } + } + } +} + +pub fn validate_field_map(ctx: &Ctx<'_>, f: &mut Findings) { + let tree = ctx.tree; + for &obj in tree + .children(ctx.root) + .iter() + .filter(|&&c| tree.node(c).type_name == TYPE_OBJECT) + { + let oname = &tree.node(obj).name; + for &fld in tree + .own_children(obj) + .iter() + .filter(|&&c| tree.node(c).type_name == TYPE_FIELD) + { + let n = tree.node(fld); + if n.sub_type != SUB_MAP { + continue; + } + let value_type = non_empty_str(tree.attr(fld, A_VALUE_TYPE)); + let has_ref = non_empty_str(tree.attr(fld, A_OBJECT_REF)).is_some(); + if value_type.is_some() == has_ref { + f.errors.push(error_at(tree, fld, ERR_BAD_ATTR_VALUE, format!( + "field.map \"{oname}.{}\" must set exactly one of @valueType (a scalar value subtype) or @objectRef (a value-object); {}", + n.name, if value_type.is_some() { "both are set" } else { "neither is set" }))); + continue; + } + if let Some(vt) = value_type.filter(|v| !MAP_SCALAR_VALUE_SUBTYPES.contains(v)) { + f.errors.push(error_at(tree, fld, ERR_BAD_ATTR_VALUE, format!( + "field.map \"{oname}.{}\" has @valueType \"{vt}\" which is not a scalar value subtype (string/int/long/double/float/decimal/boolean/date/time/timestamp/uuid). For a value-object-valued map use @objectRef instead.", n.name))); + } + } + } +} + +// ---- validateEnumMaxLength ----------------------------------------------------------- + +fn utf16_len(s: &str) -> usize { + s.encode_utf16().count() +} + +pub fn validate_enum_max_length(ctx: &Ctx<'_>, f: &mut Findings) { + fn visit(ctx: &Ctx<'_>, f: &mut Findings, node: NodeId) { + let tree = ctx.tree; + // ADR-0039: own children — every node is visited once, where it is declared. + for &c in tree.own_children(node) { + let cn = tree.node(c); + if cn.type_name == TYPE_FIELD && cn.sub_type == SUB_ENUM { + check(ctx, f, c); + } + if cn.type_name != TYPE_FIELD { + visit(ctx, f, c); + } + } + } + fn check(ctx: &Ctx<'_>, f: &mut Findings, field: NodeId) { + let tree = ctx.tree; + // ADR-0039: own — reported on the node that DECLARES one of these. + let declares = [A_MAX_LENGTH, A_VALUES, A_INT_VALUE_MAP, A_STRING_VALUE_MAP] + .iter() + .any(|a| tree.own_attr(field, a).is_some()); + let Some(max) = tree.attr(field, A_MAX_LENGTH).filter(|v| v.is_number()) else { + return; + }; + if !declares { + return; + } + let max_f = max.as_f64().unwrap_or(0.0); + let n = tree.node(field); + let label = match n.parent.map(|p| tree.node(p)) { + Some(p) if p.type_name == TYPE_OBJECT => format!("{}.{}", p.name, n.name), + _ => n.name.clone(), + }; + if tree.attr(field, A_INT_VALUE_MAP).is_some() { + f.errors.push(error_at(tree, field, ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, format!( + "field.enum \"{label}\" sets @maxLength {max} and @intValueMap; an @intValueMap enum is stored as an integer, so a column length does not apply. Remove @maxLength."))); + return; + } + let map = tree + .attr(field, A_STRING_VALUE_MAP) + .and_then(Value::as_object); + let mut too_long: Vec = match tree.attr(field, A_VALUES) { + Some(Value::Array(a)) => a + .iter() + .filter_map(Value::as_str) + .map(|m| { + map.and_then(|mm| mm.get(m)) + .and_then(Value::as_str) + .unwrap_or(m) + .to_string() + }) + .filter(|v| (utf16_len(v) as f64) > max_f) + .collect(), + _ => Vec::new(), + }; + too_long.sort_by_key(|v| std::cmp::Reverse(utf16_len(v))); + if let Some(first) = too_long.first() { + let len = utf16_len(first); + let kind = if map.is_none() { + "member" + } else { + "stored value" + }; + f.errors.push(error_at(tree, field, ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, format!( + "field.enum \"{label}\" @maxLength {max} is shorter than its {kind} \"{first}\" ({len} characters). Raise @maxLength to at least {len}, or shorten the member."))); + } + } + visit(ctx, f, ctx.root); +} + +// ---- validateFieldDefaults ----------------------------------------------------------- + +fn ascii_int(s: &str) -> bool { + let d = s.strip_prefix(['+', '-']).unwrap_or(s); + !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit()) +} + +/// `^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$` +fn ascii_number(s: &str) -> bool { + let s = s.strip_prefix(['+', '-']).unwrap_or(s); + let (mant, exp) = match s.find(['e', 'E']) { + Some(i) => (&s[..i], Some(&s[i + 1..])), + None => (s, None), + }; + if let Some(e) = exp { + let digits = e.strip_prefix(['+', '-']).unwrap_or(e); + if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) { + return false; + } + } + let (int, frac) = match mant.split_once('.') { + Some((i, fr)) => (i, Some(fr)), + None => (mant, None), + }; + let all_digits = |x: &str| x.bytes().all(|b| b.is_ascii_digit()); + if !all_digits(int) || frac.is_some_and(|fr| !all_digits(fr)) { + return false; + } + if int.is_empty() { + frac.is_some_and(|fr| !fr.is_empty()) + } else { + true + } +} + +fn finite_number(t: &str) -> bool { + ascii_number(t) && t.parse::().is_ok_and(f64::is_finite) +} + +fn stringify_default(v: &Value) -> String { + match v { + Value::Bool(b) => b.to_string(), + other => js_display(other), + } +} + +pub fn validate_field_defaults(ctx: &Ctx<'_>, f: &mut Findings) { + fn walk(ctx: &Ctx<'_>, out: &mut Vec, id: NodeId) { + let tree = ctx.tree; + let n = tree.node(id); + if n.type_name == TYPE_FIELD && n.sub_type != SUB_ENUM { + // ADR-0039: own — the @default declared on THIS node. + if let Some(raw) = tree + .own_attr(id, A_DEFAULT) + .map(|a| &a.value) + .filter(|v| !matches!(v, Value::Null | Value::Array(_) | Value::Object(_))) + { + let def = stringify_default(raw); + let t = def.trim(); + let ok = match n.sub_type.as_str() { + "int" | "long" | "currency" => ascii_int(t) || finite_number(t), + "double" | "float" | "decimal" => finite_number(t), + "boolean" => def == "true" || def == "false", + _ => true, + }; + if !ok { + out.push(error_at(tree, id, ERR_BAD_ATTR_VALUE, format!( + "field.{} \"{}\" @{A_DEFAULT} \"{def}\" is not coercible to the field's type", n.sub_type, n.name))); + } + } + } + for &c in tree.own_children(id) { + walk(ctx, out, c); + } + } + walk(ctx, &mut f.errors, ctx.root); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_are_in_the_catalogue() { + let raw = include_str!("../../../../../fixtures/conformance/ERROR-CODES.json"); + let doc: Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for c in [ + ERR_ENUM_EXTENDS_VALUES_CONFLICT, + ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, + ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, + ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF, + ERR_STORAGE_FLATTENED_ARRAY, + ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE, + ] { + assert!(codes.contains_key(c), "{c}"); + } + } + + #[test] + fn db_column_types() { + assert_eq!( + parse_db_column_type("varchar(20)"), + Some(DbColumnType::Varchar(Some(20))) + ); + assert_eq!( + parse_db_column_type("character(3)"), + Some(DbColumnType::Char(3)) + ); + assert_eq!( + parse_db_column_type("character varying"), + Some(DbColumnType::Varchar(None)) + ); + assert_eq!(parse_db_column_type("varchar(0)"), None); + assert_eq!(parse_db_column_type("varchar(1234567890)"), None); + assert_eq!(parse_db_column_type("VARCHAR"), None); + } + + #[test] + fn default_gates_are_ascii_only() { + assert!(ascii_int("-12") && !ascii_int("1_000") && !ascii_int("") && !ascii_int("0x10")); + assert!(finite_number("1.5e3") && finite_number(".5") && finite_number("5.")); + assert!(!finite_number("1e999") && !finite_number("NaN") && !finite_number(".")); + } +} diff --git a/server/rust/metaobjects/src/validate/field_expr.rs b/server/rust/metaobjects/src/validate/field_expr.rs new file mode 100644 index 0000000000..50aba05a95 --- /dev/null +++ b/server/rust/metaobjects/src/validate/field_expr.rs @@ -0,0 +1,1134 @@ +//! Cross-field validator conditions (`validateCrossFieldValidators`) and the +//! `@dbCheck` / `@constraintName` pass (`validateDbCheck`), with the expression +//! typing they need (a private port of `validateExprNode` / `inferExprType` / +//! `literalComparisonProblem`). + +use serde_json::Value; +use std::collections::HashMap; + +use super::util::{START_OF_UNITS, error_at, ops_for_subtype}; +use super::{Ctx, Findings}; +use crate::errors::{ERR_BAD_ATTR_VALUE, ERR_UNKNOWN_ATTR}; +use crate::json::js_display; +use crate::node::NodeId; + +pub const ERR_CROSS_FIELD_WITHOUT_CHECK: &str = "ERR_CROSS_FIELD_WITHOUT_CHECK"; +pub const ERR_CONSTRAINT_NAME_WITHOUT_CHECK: &str = "ERR_CONSTRAINT_NAME_WITHOUT_CHECK"; + +const TYPE_OBJECT: &str = "object"; +const TYPE_FIELD: &str = "field"; +const TYPE_VALIDATOR: &str = "validator"; +const SUB_ENUM: &str = "enum"; +const SUB_BOOLEAN: &str = "boolean"; +const SUB_STRING: &str = "string"; +const SUB_INT: &str = "int"; +const SUB_LONG: &str = "long"; +const SUB_DOUBLE: &str = "double"; +const SUB_FLOAT: &str = "float"; +const SUB_DECIMAL: &str = "decimal"; +const SUB_CURRENCY: &str = "currency"; +const SUB_DATE: &str = "date"; +const SUB_TIMESTAMP: &str = "timestamp"; +const SUB_UUID: &str = "uuid"; +const SUB_DURATION: &str = "duration"; +const SUB_OBJECT: &str = "object"; +const SUB_MAP: &str = "map"; + +const V_AT_LEAST_ONE: &str = "atLeastOne"; +const V_EXACTLY_ONE: &str = "exactlyOne"; +const V_REQUIRED_WHEN: &str = "requiredWhen"; +const V_PRESENT_IFF: &str = "presentIff"; +const CROSS_FIELD: &[&str] = &[ + "comparison", + V_REQUIRED_WHEN, + V_PRESENT_IFF, + V_AT_LEAST_ONE, + V_EXACTLY_ONE, +]; +const DB_CHECK_VALIDATORS: &[&str] = &["numeric", "length", "regex"]; + +const A_MAX: &str = "max"; +const A_FIELDS: &str = "fields"; +const A_WHEN: &str = "when"; +const A_EQUALS: &str = "equals"; +const A_CONDITION: &str = "condition"; +const A_DB_CHECK: &str = "dbCheck"; +const A_CONSTRAINT_NAME: &str = "constraintName"; +const A_VALUES: &str = "values"; + +const EXPR_CASE: &str = "case"; +const EXPR_NOW: &str = "now"; +const EXPR_NOW_START_OF: &str = "startOf"; +const EXPR_CAST: &str = "cast"; +const EXPR_CAST_AS: &str = "as"; +const EXPR_CAST_DB_COLUMN_TYPE: &str = "dbColumnType"; +const CASE_WHEN: &str = "when"; +const CASE_THEN: &str = "then"; +const CASE_ELSE: &str = "else"; +const CASE_OPERAND: &str = "operand"; +const OP_NOT: &str = "not"; +const OP_IS_NULL: &str = "isNull"; +const OP_IS_NOT_NULL: &str = "isNotNull"; +const COMPARISON_OPS: &[&str] = &["eq", "ne", "gt", "gte", "lt", "lte"]; +const LOGIC_OPS: &[&str] = &["and", "or"]; +pub(crate) const CAST_TARGETS: &[&str] = &[ + SUB_STRING, + SUB_INT, + SUB_LONG, + SUB_DOUBLE, + SUB_FLOAT, + SUB_DECIMAL, + SUB_BOOLEAN, + SUB_DATE, + SUB_TIMESTAMP, + SUB_UUID, +]; +const NUMERIC: &[&str] = &[ + SUB_INT, + SUB_LONG, + SUB_DOUBLE, + SUB_FLOAT, + SUB_DECIMAL, + SUB_CURRENCY, +]; + +/// What a literal compared with a field.duration must be. +const DURATION_LITERAL_FORM: &str = "an ISO-8601 duration (such as PT1H30M; no years or months)"; + +// ---- duration patterns (hand matchers for the reference's regexes) -------------- + +/// Match `(\d+)?(\d+)?...` over the whole of `s`, designators in order. +fn components(s: &str, designators: &[char], fraction_on: Option) -> bool { + let b: Vec = s.chars().collect(); + let (mut i, mut next) = (0, 0); + while i < b.len() { + let start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + if i == start { + return false; + } + if fraction_on.is_some() && i < b.len() && b[i] == '.' { + let f = i + 1; + i = f; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + if i == f || i >= b.len() || Some(b[i]) != fraction_on { + return false; + } + } + let Some(&c) = b.get(i) else { return false }; + let Some(idx) = designators.iter().position(|&d| d == c) else { + return false; + }; + if idx < next { + return false; + } + next = idx + 1; + i += 1; + } + true +} + +fn duration_shape(s: &str, date: &[char], fraction: bool, signed_pm: bool) -> bool { + let rest = if signed_pm { + s.strip_prefix(['+', '-']).unwrap_or(s) + } else { + s + }; + let Some(rest) = rest.strip_prefix('P') else { + return false; + }; + if rest.is_empty() { + return false; + } + let (date_part, time_part) = match rest.find('T') { + Some(t) => (&rest[..t], Some(&rest[t + 1..])), + None => (rest, None), + }; + if !components(date_part, date, None) { + return false; + } + match time_part { + None => true, + Some(t) => { + t.starts_with(|c: char| c.is_ascii_digit()) + && components(t, &['H', 'M', 'S'], if fraction { Some('S') } else { None }) + } + } +} + +/// `ISO_DURATION_RE`: a signed ISO-8601 duration, years and months allowed. +pub fn is_iso_duration(s: &str) -> bool { + duration_shape(s, &['Y', 'M', 'W', 'D'], false, true) +} + +/// `parseDurationLiteral` is defined: the field.duration literal form. +pub fn is_duration_literal(s: &str) -> bool { + duration_shape(s, &['W', 'D'], true, true) +} + +// ---- expression grammar ---------------------------------------------------------- + +fn kind_keys( + node: &serde_json::Map, +) -> Option<(&'static str, &'static [&'static str])> { + const KINDS: &[(&str, &[&str])] = &[ + ("field", &["field"]), + ("value", &["value"]), + (EXPR_NOW, &[EXPR_NOW, EXPR_NOW_START_OF]), + (EXPR_CASE, &[EXPR_CASE, CASE_ELSE, CASE_OPERAND]), + ("fn", &["fn", "args"]), + ("op", &["op", "left", "right", "arg", "args"]), + ]; + KINDS.iter().find(|(k, _)| node.contains_key(*k)).copied() +} + +struct FnSig { + min: usize, + max: usize, + params: &'static [&'static str], + result: &'static str, + ordered: bool, +} + +fn fn_sig(name: &str) -> Option { + let s = |min, max, params, result, ordered| FnSig { + min, + max, + params, + result, + ordered, + }; + Some(match name { + "coalesce" => s(1, usize::MAX, &["same"], "same", false), + "greatest" | "least" => s(1, usize::MAX, &["same"], "same", true), + "nullif" => s(2, 2, &["same", "same"], "same", false), + "lower" | "upper" => s(1, 1, &["string"], "string", false), + "btrim" => s(1, 2, &["string", "string"], "string", false), + "splitPart" => s(3, 3, &["string", "string", "int"], "string", false), + "concat" => s(1, usize::MAX, &["scalar"], "string", false), + "concatWs" => s(2, usize::MAX, &["string", "scalar"], "string", false), + "substring" => s(2, 3, &["string", "int", "int"], "string", false), + "replace" => s(3, 3, &["string", "string", "string"], "string", false), + "left" | "right" => s(2, 2, &["string", "int"], "string", false), + "length" => s(1, 1, &["string"], "int", false), + _ => return None, + }) +} + +fn js_type(v: &Value) -> &'static str { + match v { + Value::Null => "null", + Value::Array(_) => "array", + Value::Object(_) => "object", + Value::String(_) => "string", + Value::Number(_) => "number", + Value::Bool(_) => "boolean", + } +} + +fn is_text_dbcolumntype(v: &str) -> bool { + // text, varchar, character varying, varchar(n), character varying(n), character(n) + super::field::parse_db_column_type(v).is_some_and(|p| { + !matches!( + p, + super::field::DbColumnType::Uuid | super::field::DbColumnType::Jsonb + ) + }) +} + +/// Structural well-formedness of an expression tree; empty when valid. +pub(crate) fn validate_expr(node: &Value) -> Vec { + let Some(n) = node.as_object() else { + return vec![format!( + "expression node must be an object, got {}", + js_type(node) + )]; + }; + let kind = kind_keys(n); + if let Some((k, allowed)) = kind { + let extra: Vec<&str> = n + .keys() + .map(String::as_str) + .filter(|x| !allowed.contains(x)) + .collect(); + if !extra.is_empty() { + return vec![format!( + "expression '{k}' node takes only {}, not {}", + allowed.join(", "), + extra.join(", ") + )]; + } + } + if let Some(f) = n.get("field") { + return if f.as_str().is_some_and(|s| !s.is_empty()) { + vec![] + } else { + vec!["expression 'field' must be a non-empty string".into()] + }; + } + if let Some(v) = n.get("value") { + return if matches!( + v, + Value::Null | Value::String(_) | Value::Number(_) | Value::Bool(_) + ) { + vec![] + } else { + vec!["expression 'value' must be a scalar literal (string/number/boolean/null)".into()] + }; + } + if let Some(d) = n.get(EXPR_NOW) { + if !d.as_str().is_some_and(is_iso_duration) { + return vec![format!( + "expression '{EXPR_NOW}' must be an ISO-8601 duration string (e.g. '-P7D'), got {d}" + )]; + } + if let Some(s) = n.get(EXPR_NOW_START_OF) + && !s.as_str().is_some_and(|u| START_OF_UNITS.contains(&u)) + { + return vec![format!( + "expression '{EXPR_NOW_START_OF}' must be one of {}, got {s}", + START_OF_UNITS.join(", ") + )]; + } + return vec![]; + } + if let Some(arms) = n.get(EXPR_CASE) { + let Some(arms) = arms.as_array().filter(|a| !a.is_empty()) else { + return vec![format!( + "'{EXPR_CASE}' requires a non-empty array of {{ {CASE_WHEN}, {CASE_THEN} }} arms" + )]; + }; + let mut errs = Vec::new(); + for arm in arms { + match arm.as_object() { + Some(a) + if a.contains_key(CASE_WHEN) + && a.contains_key(CASE_THEN) + && a.keys().all(|k| k == CASE_WHEN || k == CASE_THEN) => + { + errs.extend(validate_expr(&a[CASE_WHEN])); + errs.extend(validate_expr(&a[CASE_THEN])); + } + _ => errs.push(format!( + "every '{EXPR_CASE}' arm must be {{ {CASE_WHEN}, {CASE_THEN} }}" + )), + } + } + for key in [CASE_ELSE, CASE_OPERAND] { + if let Some(e) = n.get(key) { + errs.extend(validate_expr(e)); + } + } + return errs; + } + if n.contains_key(EXPR_CAST) { + let extra: Vec<&str> = n + .keys() + .map(String::as_str) + .filter(|k| *k != EXPR_CAST && *k != EXPR_CAST_AS && *k != EXPR_CAST_DB_COLUMN_TYPE) + .collect(); + if !extra.is_empty() { + return vec![format!( + "expression '{EXPR_CAST}' takes only '{EXPR_CAST_AS}' and '{EXPR_CAST_DB_COLUMN_TYPE}' beside it, not {}", + extra.join(", ") + )]; + } + let to = n.get(EXPR_CAST_AS).and_then(Value::as_str); + let Some(to) = to.filter(|t| CAST_TARGETS.contains(t)) else { + return vec![format!( + "'{EXPR_CAST}' requires '{EXPR_CAST_AS}': one of {}", + CAST_TARGETS.join(", ") + )]; + }; + if let Some(sp) = n.get(EXPR_CAST_DB_COLUMN_TYPE) + && (!sp.as_str().is_some_and(is_text_dbcolumntype) || to != SUB_STRING) + { + return vec![format!( + "'{EXPR_CAST}' '{EXPR_CAST_DB_COLUMN_TYPE}' is a text spelling of @dbColumnType (text, varchar, character varying, varchar(n), character varying(n), character(n)) with '{EXPR_CAST_AS}: {SUB_STRING}'" + )]; + } + return validate_expr(&n[EXPR_CAST]); + } + if let Some(f) = n.get("fn") { + let name = f.as_str().unwrap_or(""); + let Some(sig) = fn_sig(name).filter(|_| f.is_string()) else { + return vec![format!( + "unknown expression fn '{}'", + f.as_str().map_or_else(|| f.to_string(), str::to_string) + )]; + }; + let args = n.get("args").and_then(Value::as_array); + let Some(args) = args.filter(|a| a.len() >= sig.min.max(1)) else { + return vec![if sig.min <= 1 { + format!("'{name}' requires a non-empty args array") + } else { + format!("'{name}' requires at least {} args", sig.min) + }]; + }; + if args.len() > sig.max { + return vec![format!( + "'{name}' takes at most {} args, got {}", + sig.max, + args.len() + )]; + } + return args.iter().flat_map(validate_expr).collect(); + } + if let Some(op) = n.get("op") { + let Some(op) = op.as_str() else { + return vec!["expression 'op' must be a string".into()]; + }; + if COMPARISON_OPS.contains(&op) { + return if n.contains_key("left") && n.contains_key("right") { + let mut e = validate_expr(&n["left"]); + e.extend(validate_expr(&n["right"])); + e + } else { + vec![format!("comparison op '{op}' requires 'left' and 'right'")] + }; + } + if op == OP_IS_NULL || op == OP_IS_NOT_NULL || op == OP_NOT { + return match n.get("arg") { + Some(a) => validate_expr(a), + None => vec![format!("op '{op}' requires 'arg'")], + }; + } + if LOGIC_OPS.contains(&op) { + return match n + .get("args") + .and_then(Value::as_array) + .filter(|a| !a.is_empty()) + { + Some(a) => a.iter().flat_map(validate_expr).collect(), + None => vec![format!("op '{op}' requires a non-empty args array")], + }; + } + return vec![format!("unknown expression op '{op}'")]; + } + vec!["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}, {cast,…}".into()] +} + +pub(crate) type Ty = Option; + +fn literal_type(v: &Value) -> Ty { + match v { + Value::String(_) => Some(SUB_STRING.into()), + Value::Bool(_) => Some(SUB_BOOLEAN.into()), + Value::Number(n) => { + let whole = n.is_i64() + || n.is_u64() + || n.as_f64() + .is_some_and(|f| f.is_finite() && f.fract() == 0.0); + Some(if whole { SUB_INT } else { SUB_DOUBLE }.into()) + } + _ => None, + } +} + +fn is_adaptable(n: &Value) -> bool { + n.get("value").is_some_and(Value::is_number) || n.get(EXPR_NOW).is_some() +} + +fn adapts_to(n: &Value, to: &str) -> bool { + if n.get(EXPR_NOW).is_some() { + return to == SUB_DATE || to == SUB_TIMESTAMP; + } + if literal_type(&n["value"]).as_deref() == Some(SUB_INT) { + return NUMERIC.contains(&to); + } + to == SUB_DOUBLE || to == SUB_FLOAT || to == SUB_DECIMAL +} + +/// The one type of some results, or the differing types when they do not unify. +fn unify(nodes: &[&Value], types: &[Ty]) -> (Ty, Option>) { + let typed: Vec<(&Value, &String)> = nodes + .iter() + .zip(types) + .filter_map(|(n, t)| t.as_ref().map(|t| (*n, t))) + .collect(); + let anchor = typed.iter().find(|(n, _)| !is_adaptable(n)); + let unified = anchor.or(typed.first()).map(|(_, t)| (*t).clone()); + let fits = typed.iter().all(|(n, t)| { + Some(*t) == unified.as_ref() + || (anchor.is_some_and(|(_, at)| is_adaptable(n) && adapts_to(n, at))) + }); + if fits { + (unified, None) + } else { + let mut seen: Vec = Vec::new(); + for (_, t) in &typed { + if !seen.contains(t) { + seen.push((*t).clone()); + } + } + (unified, Some(seen)) + } +} + +fn cast_problem(from: Option<&str>, to: &str, int_enum: bool) -> Option { + let from = from?; + if from == SUB_OBJECT || from == SUB_MAP { + return Some(format!("a field.{from} value cannot be cast")); + } + if from == to { + return None; + } + let integer = |t: &str| t == SUB_INT || t == SUB_LONG; + if from == SUB_ENUM { + if to == SUB_STRING { + return int_enum.then(|| "an int-stored enum (@intValueMap) cast to string gives its integer, not its member; cast it to int".to_string()); + } + if integer(to) { + return (!int_enum).then(|| { + "only an enum stored as an integer (@intValueMap) can be cast to a number" + .to_string() + }); + } + return Some(format!("an enum cannot be cast to {to}")); + } + if to == SUB_STRING || from == SUB_STRING { + return None; + } + if NUMERIC.contains(&to) { + if from == SUB_BOOLEAN { + return (to != SUB_INT).then(|| format!("a boolean casts only to int, not {to}")); + } + return (!NUMERIC.contains(&from)).then(|| format!("a {from} cannot be cast to {to}")); + } + if to == SUB_BOOLEAN { + return (from != SUB_INT) + .then(|| format!("a {from} cannot be cast to boolean; only an int can")); + } + if to == SUB_DATE || to == SUB_TIMESTAMP { + return (from != SUB_DATE && from != SUB_TIMESTAMP) + .then(|| format!("a {from} cannot be cast to {to}")); + } + Some(format!("a {from} cannot be cast to {to}")) +} + +pub(crate) struct Infer { + pub(crate) ty: Ty, + pub(crate) errors: Vec, +} + +type Resolve<'a> = &'a dyn Fn(&str) -> Ty; + +fn infer(node: &Value, resolve: Resolve<'_>) -> Infer { + infer_with(node, resolve, &|_| false) +} + +/// `inferExprType` with `isIntStoredEnum`: whether a named field is an int-stored enum. +pub(crate) fn infer_with( + node: &Value, + resolve: Resolve<'_>, + ienum: &dyn Fn(&str) -> bool, +) -> Infer { + let structural = validate_expr(node); + if !structural.is_empty() { + return Infer { + ty: None, + errors: structural, + }; + } + let n = node.as_object().expect("validated as an object"); + let done = |ty: Ty, errors: Vec| Infer { ty, errors }; + if let Some(f) = n.get("field") { + let name = f.as_str().unwrap_or(""); + return match resolve(name) { + Some(t) => done(Some(t), vec![]), + None => done( + None, + vec![format!( + "expression field '{name}' does not resolve to a projection field (not an aggregate) or a base entity field" + )], + ), + }; + } + if let Some(v) = n.get("value") { + return done(literal_type(v), vec![]); + } + if n.contains_key(EXPR_NOW) { + return done(Some(SUB_TIMESTAMP.into()), vec![]); + } + if let Some(arms) = n.get(EXPR_CASE).and_then(Value::as_array) { + let mut errors = Vec::new(); + let operand = n.get(CASE_OPERAND).map(|o| infer_with(o, resolve, ienum)); + if let Some(o) = &operand { + errors.extend(o.errors.iter().cloned()); + } + let mut results: Vec = Vec::new(); + let mut nodes: Vec<&Value> = Vec::new(); + for arm in arms { + let (when, then) = (&arm[CASE_WHEN], &arm[CASE_THEN]); + let w = infer_with(when, resolve, ienum); + errors.extend(w.errors.iter().cloned()); + if operand.is_none() && w.ty.as_deref().is_some_and(|t| t != SUB_BOOLEAN) { + errors.push(format!( + "a searched '{EXPR_CASE}' needs a boolean '{CASE_WHEN}', got {}", + w.ty.as_deref().unwrap_or("") + )); + } + if let (Some(Infer { ty: Some(ot), .. }), Some(wt)) = (&operand, &w.ty) + && when.get("value").is_none() + && wt != ot + { + errors.push(format!("a simple '{EXPR_CASE}' compares its {ot} '{CASE_OPERAND}' with a {wt} '{CASE_WHEN}'")); + } + let t = infer_with(then, resolve, ienum); + errors.extend(t.errors); + results.push(t.ty); + nodes.push(then); + } + if let Some(e) = n.get(CASE_ELSE) { + let r = infer_with(e, resolve, ienum); + errors.extend(r.errors); + results.push(r.ty); + nodes.push(e); + } + let (ty, differing) = unify(&nodes, &results); + if let Some(d) = differing { + errors.push(format!( + "'{EXPR_CASE}' results have differing types ({})", + d.join(", ") + )); + } + return done(ty, errors); + } + if let Some(inner) = n.get(EXPR_CAST) { + let operand = infer_with(inner, resolve, ienum); + let to = n[EXPR_CAST_AS].as_str().unwrap_or("").to_string(); + let int_enum = inner + .get("field") + .and_then(Value::as_str) + .is_some_and(ienum); + let problem = cast_problem(operand.ty.as_deref(), &to, int_enum); + let mut errors = operand.errors; + if let Some(p) = problem { + errors.push(format!("'{EXPR_CAST}': {p}")); + } + return done(Some(to), errors); + } + if let Some(f) = n.get("fn") { + let name = f.as_str().unwrap_or(""); + let sig = fn_sig(name).expect("validated function"); + let args = n["args"].as_array().expect("validated args"); + let results: Vec = args.iter().map(|a| infer_with(a, resolve, ienum)).collect(); + let mut errors: Vec = results + .iter() + .flat_map(|r| r.errors.iter().cloned()) + .collect(); + let (mut same, mut same_nodes): (Vec, Vec<&Value>) = (Vec::new(), Vec::new()); + for (i, (a, an)) in results.iter().zip(args).enumerate() { + let kind = sig.params[i.min(sig.params.len() - 1)]; + let Some(t) = a.ty.as_deref() else { continue }; + match kind { + "same" => { + same.push(Some(t.to_string())); + same_nodes.push(an); + } + "string" if t != SUB_STRING => errors.push(format!( + "'{name}' argument {} must be a string, got {t}", + i + 1 + )), + "int" if t != SUB_INT => errors.push(format!( + "'{name}' argument {} must be an int, got {t}{}", + i + 1, + if t == SUB_LONG { + "; cast it ({ cast: , as: int })" + } else { + "" + } + )), + "scalar" if t == SUB_OBJECT || t == SUB_MAP => errors.push(format!( + "'{name}' argument {} must be a scalar, got {t}", + i + 1 + )), + _ => {} + } + } + let (unified, differing) = unify(&same_nodes, &same); + if let Some(d) = differing { + errors.push(format!( + "'{name}' arguments have differing types ({})", + d.join(", ") + )); + } + if sig.ordered + && unified + .as_deref() + .is_some_and(|u| u == SUB_BOOLEAN || u == SUB_OBJECT || u == SUB_MAP) + { + errors.push(format!( + "'{name}' needs ordered arguments, got {}", + unified.as_deref().unwrap_or("") + )); + } + let ty = match sig.result { + "same" => unified, + "int" => Some(SUB_INT.into()), + _ => Some(SUB_STRING.into()), + }; + return done(ty, errors); + } + let op = n["op"].as_str().unwrap_or(""); + if COMPARISON_OPS.contains(&op) { + let l = infer_with(&n["left"], resolve, ienum); + let r = infer_with(&n["right"], resolve, ienum); + let mut errors = l.errors; + errors.extend(r.errors); + if let Some(lt) = &l.ty + && !ops_for_subtype(lt).contains(&op) + { + errors.push(format!("op '{op}' is not legal for a {lt} operand")); + } + return done(Some(SUB_BOOLEAN.into()), errors); + } + if op == OP_IS_NULL || op == OP_IS_NOT_NULL { + return done( + Some(SUB_BOOLEAN.into()), + infer_with(&n["arg"], resolve, ienum).errors, + ); + } + let kids: Vec<&Value> = if op == OP_NOT { + vec![&n["arg"]] + } else { + n["args"] + .as_array() + .map(|a| a.iter().collect()) + .unwrap_or_default() + }; + let mut errors = Vec::new(); + for k in kids { + let kt = infer_with(k, resolve, ienum); + errors.extend(kt.errors); + if let Some(t) = kt.ty.as_deref().filter(|t| *t != SUB_BOOLEAN) { + errors.push(format!("op '{op}' requires boolean operands, got {t}")); + } + } + done(Some(SUB_BOOLEAN.into()), errors) +} + +/// Every node of an expression tree, root first. +pub(crate) fn expression_nodes<'a>( + node: &'a Value, + out: &mut Vec<&'a serde_json::Map>, +) { + let Some(n) = node.as_object() else { return }; + out.push(n); + for key in ["left", "right", "arg", EXPR_CAST, CASE_OPERAND, CASE_ELSE] { + if let Some(c) = n.get(key) { + expression_nodes(c, out); + } + } + if let Some(args) = n.get("args").and_then(Value::as_array) { + for a in args { + expression_nodes(a, out); + } + } + if let Some(arms) = n.get(EXPR_CASE).and_then(Value::as_array) { + for arm in arms.iter().filter_map(Value::as_object) { + for key in [CASE_WHEN, CASE_THEN] { + if let Some(c) = arm.get(key) { + expression_nodes(c, out); + } + } + } + } +} + +fn expr_view_only_node(node: &Value) -> Option { + let n = node.as_object()?; + if n.contains_key(EXPR_CAST) { + return Some(EXPR_CAST.into()); + } + if n.contains_key(EXPR_CASE) { + return Some(EXPR_CASE.into()); + } + if n.contains_key(EXPR_NOW) { + return Some(EXPR_NOW.into()); + } + if let Some(f) = n.get("fn") + && f.as_str() != Some("coalesce") + { + return Some(f.as_str().map_or_else(|| f.to_string(), str::to_string)); + } + if let Some(f) = n.get("field").and_then(Value::as_str) + && f.contains('.') + { + return Some(format!("the path \"{f}\"")); + } + for key in ["left", "right", "arg"] { + if let Some(c) = n.get(key) + && let Some(hit) = expr_view_only_node(c) + { + return Some(hit); + } + } + n.get("args") + .and_then(Value::as_array) + .and_then(|a| a.iter().find_map(expr_view_only_node)) +} + +/// A field as the literal check sees it: subtype, name and enum members. +pub(crate) struct FieldView<'a> { + pub(crate) name: &'a str, + pub(crate) sub: &'a str, + pub(crate) members: Option<&'a Vec>, +} + +pub(crate) fn literal_comparison_problem<'a>( + expr: &Value, + field_of: &dyn Fn(&str) -> Option>, +) -> Option { + let check = |lit: &Value, reference: &Value| -> Option { + let lit = lit.as_object()?; + let value = lit.get("value").filter(|v| !v.is_null())?; + let name = reference.as_object()?.get("field")?.as_str()?; + let field = field_of(name)?; + let kind = if field.sub == SUB_BOOLEAN { + "boolean" + } else if NUMERIC.contains(&field.sub) { + "number" + } else { + "string" + }; + if js_type(value) != kind { + return Some(format!( + "compares \"{}\" (field.{}) with {value}; it needs a {kind}.", + field.name, field.sub + )); + } + if let Some(members) = field.members.filter(|_| field.sub == SUB_ENUM) + && !members.iter().any(|m| js_display(m) == js_display(value)) + { + let list: Vec = members.iter().map(js_display).collect(); + return Some(format!( + "compares \"{}\" with {value}, which is not one of its @values ({}).", + field.name, + list.join(", ") + )); + } + if field.sub == SUB_DURATION && !value.as_str().is_some_and(is_duration_literal) { + return Some(format!( + "compares \"{}\" with {value}, which is not {DURATION_LITERAL_FORM}.", + field.name + )); + } + None + }; + let mut nodes = Vec::new(); + expression_nodes(expr, &mut nodes); + for n in nodes { + if let (Some(l), Some(r)) = (n.get("left"), n.get("right")) + && let Some(p) = check(l, r).or_else(|| check(r, l)) + { + return Some(p); + } + if let (Some(operand), Some(arms)) = ( + n.get(CASE_OPERAND), + n.get(EXPR_CASE).and_then(Value::as_array), + ) { + for arm in arms.iter().filter_map(Value::as_object) { + if let Some(w) = arm.get(CASE_WHEN) + && let Some(p) = check(w, operand) + { + return Some(p); + } + } + } + } + None +} + +// ---- the passes ------------------------------------------------------------------ + +fn field_children(ctx: &Ctx<'_>, obj: NodeId) -> Vec { + ctx.tree + .children(obj) + .iter() + .copied() + .filter(|&c| ctx.tree.node(c).type_name == TYPE_FIELD) + .collect() +} + +fn condition_problem<'a>( + ctx: &Ctx<'a>, + condition: &Value, + fields: &HashMap<&str, NodeId>, +) -> Option { + let mut nodes = Vec::new(); + expression_nodes(condition, &mut nodes); + if let Some(u) = nodes + .iter() + .find(|n| n.contains_key(EXPR_CASE) || n.contains_key(EXPR_NOW)) + { + let which = if u.contains_key(EXPR_CASE) { + EXPR_CASE + } else { + EXPR_NOW + }; + return Some(format!( + "is not a valid expression: a condition takes no '{which}' node, since a CHECK can hold neither a CASE nor the current time." + )); + } + if let Some(v) = expr_view_only_node(condition) { + return Some(format!( + "uses {v}, which a CHECK condition cannot hold: it takes fields, literals, comparisons, null tests, and / or / not, and coalesce." + )); + } + let tree = ctx.tree; + let resolve = |name: &str| fields.get(name).map(|&f| tree.node(f).sub_type.clone()); + let inferred = infer(condition, &resolve); + if !inferred.errors.is_empty() { + return Some(format!( + "is not a valid expression: {}.", + inferred.errors.join("; ") + )); + } + if inferred.ty.as_deref() != Some(SUB_BOOLEAN) { + return Some(format!( + "must be a boolean expression (a comparison, a null test, or and / or / not of them), not a field.{}.", + inferred.ty.as_deref().unwrap_or("undefined") + )); + } + let has_null = nodes.iter().any(|n| { + n.contains_key("left") + && n.contains_key("right") + && [&n["left"], &n["right"]].iter().any(|side| { + side.as_object() + .is_some_and(|s| s.get("value").is_some_and(Value::is_null)) + }) + }); + if has_null { + return Some("compares with null, which is never true: use isNull or isNotNull.".into()); + } + let field_of = |name: &str| { + fields.get(name).map(|&f| FieldView { + name: &tree.node(f).name, + sub: &tree.node(f).sub_type, + members: tree.attr(f, A_VALUES).and_then(Value::as_array), + }) + }; + literal_comparison_problem(condition, &field_of) +} + +pub fn validate_cross_field_validators(ctx: &Ctx<'_>, f: &mut Findings) { + let tree = ctx.tree; + for &obj in tree + .children(ctx.root) + .iter() + .filter(|&&c| tree.node(c).type_name == TYPE_OBJECT) + { + let field_nodes = field_children(ctx, obj); + let fields: HashMap<&str, NodeId> = field_nodes + .iter() + .map(|&x| (tree.node(x).name.as_str(), x)) + .collect(); + let oname = &tree.node(obj).name; + // ADR-0039: own — each validator is checked where it is declared. + for &v in tree.own_children(obj) { + let vn = tree.node(v); + if vn.type_name != TYPE_VALIDATOR || !CROSS_FIELD.contains(&vn.sub_type.as_str()) { + continue; + } + let push = |f: &mut Findings, code: &'static str, msg: String| { + f.errors.push(error_at(tree, v, code, msg)) + }; + // ADR-0039: own — the attr is checked on the validator that declares it. + if vn.sub_type == V_AT_LEAST_ONE && tree.own_attr(v, A_MAX).is_some() { + if ctx.strict { + continue; + } + push( + f, + ERR_UNKNOWN_ATTR, + format!( + "validator.atLeastOne \"{oname}.{}\" carries @max, which atLeastOne does not take. For \"exactly one of these fields\", declare validator.exactlyOne instead; for \"at least one\", remove @max.", + vn.name + ), + ); + continue; + } + if vn.sub_type == V_EXACTLY_ONE { + let n = match tree.attr(v, A_FIELDS) { + Some(Value::String(_)) => 1, + Some(Value::Array(a)) => a.iter().filter(|x| x.is_string()).count(), + _ => 0, + }; + if n < 2 { + push( + f, + ERR_BAD_ATTR_VALUE, + format!( + "validator.exactlyOne \"{oname}.{}\" @fields names {n} field{}; it needs two or more. For one field, make that field required.", + vn.name, + if n == 1 { "" } else { "s" } + ), + ); + continue; + } + } + if vn.sub_type == V_REQUIRED_WHEN || vn.sub_type == V_PRESENT_IFF { + let when = tree + .attr(v, A_WHEN) + .and_then(Value::as_str) + .and_then(|w| fields.get(w).copied()); + let equals = tree.attr(v, A_EQUALS); + if let Some(w) = when.filter(|&w| tree.node(w).sub_type == SUB_DURATION) + && !equals + .and_then(Value::as_str) + .is_some_and(is_duration_literal) + { + push( + f, + ERR_BAD_ATTR_VALUE, + format!( + "validator.{} \"{oname}.{}\" @equals {} gates field.duration \"{}\"; it needs {DURATION_LITERAL_FORM}.", + vn.sub_type, + vn.name, + equals.map_or_else(|| "undefined".to_string(), Value::to_string), + tree.node(w).name + ), + ); + continue; + } + } + let Some(condition) = tree.attr(v, A_CONDITION) else { + continue; + }; + let label = format!( + "validator.{} \"{oname}.{}\" @condition", + vn.sub_type, vn.name + ); + let mut refs: Vec = Vec::new(); + let mut nodes = Vec::new(); + expression_nodes(condition, &mut nodes); + for n in nodes { + if let Some(Value::String(s)) = n.get("field") + && !refs.contains(s) + { + refs.push(s.clone()); + } + } + let mut unknown: Vec<&String> = refs + .iter() + .filter(|r| !fields.contains_key(r.as_str())) + .collect(); + unknown.sort(); + if !unknown.is_empty() { + let names: Vec = unknown.iter().map(|u| format!("\"{u}\"")).collect(); + push( + f, + ERR_BAD_ATTR_VALUE, + format!( + "{label} names {}, which {} of \"{oname}\".", + names.join(", "), + if unknown.len() == 1 { + "is not a field" + } else { + "are not fields" + } + ), + ); + continue; + } + if let Some(problem) = condition_problem(ctx, condition, &fields) { + push(f, ERR_BAD_ATTR_VALUE, format!("{label} {problem}")); + } + } + } +} + +pub fn validate_db_check(ctx: &Ctx<'_>, f: &mut Findings) { + fn visit(ctx: &Ctx<'_>, f: &mut Findings, id: NodeId, owner: Option<&str>) { + let tree = ctx.tree; + let n = tree.node(id); + let checked = (n.type_name == TYPE_VALIDATOR + && (DB_CHECK_VALIDATORS.contains(&n.sub_type.as_str()) + || CROSS_FIELD.contains(&n.sub_type.as_str()))) + || (n.type_name == TYPE_FIELD && n.sub_type == SUB_ENUM); + if checked + && (tree.own_attr(id, A_DB_CHECK).is_some() + || tree.own_attr(id, A_CONSTRAINT_NAME).is_some()) + { + let name = tree + .attr(id, A_CONSTRAINT_NAME) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()); + let label = format!( + "{}.{} \"{}{}\"", + n.type_name, + n.sub_type, + owner.map_or(String::new(), |o| format!("{o}.")), + n.name + ); + let db_false = tree.attr(id, A_DB_CHECK) == Some(&Value::Bool(false)); + if db_false && CROSS_FIELD.contains(&n.sub_type.as_str()) { + f.errors.push(error_at(tree, id, ERR_CROSS_FIELD_WITHOUT_CHECK, format!( + "{label} sets @dbCheck: false, but this validator is enforced only by its CHECK, so the rule would be enforced nowhere. Remove the validator, or remove @dbCheck: false."))); + } else if let (true, Some(name)) = (db_false, name) { + f.errors.push(error_at(tree, id, ERR_CONSTRAINT_NAME_WITHOUT_CHECK, format!( + "{label} sets @dbCheck: false and @constraintName \"{name}\"; with no CHECK there is nothing for the name to name. Remove @constraintName, or remove @dbCheck: false."))); + } + } + let next = if n.type_name == TYPE_OBJECT || n.type_name == TYPE_FIELD { + Some(n.name.as_str()) + } else { + owner + }; + for &c in tree.own_children(id) { + visit(ctx, f, c, next); + } + } + for &c in ctx.tree.own_children(ctx.root) { + visit(ctx, f, c, None); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_are_in_the_catalogue() { + let raw = include_str!("../../../../../fixtures/conformance/ERROR-CODES.json"); + let doc: Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for c in [ + ERR_CROSS_FIELD_WITHOUT_CHECK, + ERR_CONSTRAINT_NAME_WITHOUT_CHECK, + ERR_UNKNOWN_ATTR, + ERR_BAD_ATTR_VALUE, + ] { + assert!(codes.contains_key(c), "{c}"); + } + } + + #[test] + fn duration_literals() { + for ok in ["PT1H30M", "-PT5S", "P1W", "P1DT2H", "PT0.5S", "+P2D"] { + assert!(is_duration_literal(ok), "{ok}"); + } + for bad in [ + "P", "PT", "P1Y", "P1M", "1H", "PT1", "PT1H2", "P1DT", "PT1.H", "PT.5S", "PT1M1H", + ] { + assert!(!is_duration_literal(bad), "{bad}"); + } + assert!(is_iso_duration("P1Y2M")); + assert!(!is_iso_duration("P")); + } + + #[test] + fn infer_types_a_comparison() { + let e: Value = serde_json::json!({"op":"eq","left":{"field":"a"},"right":{"value":1}}); + let r = infer(&e, &|n| (n == "a").then(|| "int".to_string())); + assert_eq!(r.ty.as_deref(), Some("boolean")); + assert!(r.errors.is_empty()); + let bad = infer(&serde_json::json!({"field":"a"}), &|_| Some("int".into())); + assert_eq!(bad.ty.as_deref(), Some("int")); + } +} diff --git a/server/rust/metaobjects/src/validate/field_policy.rs b/server/rust/metaobjects/src/validate/field_policy.rs new file mode 100644 index 0000000000..06eae93020 --- /dev/null +++ b/server/rust/metaobjects/src/validate/field_policy.rs @@ -0,0 +1,387 @@ +//! `validateEnumNormalizeAmbiguity` / `validateEnumNormalizeCollision` +//! (`core/field/validate-enum-normalize-ambiguity.ts`) and `validateFieldMutability` +//! (`core/field/validate-field-mutability.ts`). + +use serde_json::Value; + +use super::util::error_at; +use super::{Ctx, Findings}; +use crate::errors::MetaError; +use crate::json::js_display; +use crate::node::NodeId; + +pub const WARN_ENUM_NORMALIZE_AMBIGUOUS: &str = "WARN_ENUM_NORMALIZE_AMBIGUOUS"; +pub const WARN_MUTABILITY_VALUE_OBJECT: &str = "WARN_MUTABILITY_VALUE_OBJECT"; +pub const WARN_MUTABILITY_READONLY_HOST: &str = "WARN_MUTABILITY_READONLY_HOST"; +pub const ERR_ENUM_NORMALIZE_COLLISION: &str = "ERR_ENUM_NORMALIZE_COLLISION"; +pub const ERR_MUTABILITY_AUTOSET_CONFLICT: &str = "ERR_MUTABILITY_AUTOSET_CONFLICT"; +pub const ERR_MUTABILITY_DOWNGRADE: &str = "ERR_MUTABILITY_DOWNGRADE"; +pub const ERR_READONLY_ASSIGNED_PRIMARY: &str = "ERR_READONLY_ASSIGNED_PRIMARY"; + +const TYPE_OBJECT: &str = "object"; +const TYPE_FIELD: &str = "field"; +const TYPE_IDENTITY: &str = "identity"; +const TYPE_SOURCE: &str = "source"; +const SUB_ENUM: &str = "enum"; +const SUB_VALUE: &str = "value"; +const SUB_PROJECTION: &str = "projection"; +const SUB_PRIMARY: &str = "primary"; +const A_VALUES: &str = "values"; +const A_NORMALIZE: &str = "normalize"; +const A_MUTABILITY: &str = "mutability"; +const A_AUTO_SET: &str = "autoSet"; +const A_GENERATION: &str = "generation"; +const A_FIELDS: &str = "fields"; +const A_KIND: &str = "kind"; +const NORMALIZE_DEFAULT: &str = "strip"; +const GENERATION_ASSIGNED: &str = "assigned"; +/// Declaration order is the tightening order. +const MUTABILITY_MODES: &[&str] = &["readWrite", "writeOnce", "readOnly"]; +const READ_ONLY_SOURCE_KINDS: &[&str] = + &["view", "materializedView", "storedProc", "tableFunction"]; + +fn strip_normalize(s: &str) -> String { + s.chars() + .filter_map(|c| match c { + 'a'..='z' => Some(c.to_ascii_uppercase()), + 'A'..='Z' | '0'..='9' => Some(c), + _ => None, + }) + .collect() +} + +/// Fewest-segments word-break of `target` into two or more `dict` entries. +fn segment_into<'a>(target: &str, dict: &[(&'a str, &str)]) -> Option> { + let n = target.len(); + let mut best: Vec>> = vec![None; n + 1]; + best[0] = Some(Vec::new()); + for i in 0..n { + let Some(prefix) = best[i].clone() else { + continue; + }; + for (member, stripped) in dict { + let end = i + stripped.len(); + if end > n || !target[i..].starts_with(stripped) { + continue; + } + let mut cand = prefix.clone(); + cand.push(member); + if best[end].as_ref().is_none_or(|cur| cand.len() < cur.len()) { + best[end] = Some(cand); + } + } + } + best[n].take().filter(|s| s.len() >= 2) +} + +/// `(mode, explicit)`: own/inherited, then the owning object, then the default. +fn effective_normalize(ctx: &Ctx<'_>, field: NodeId) -> (String, bool) { + let tree = ctx.tree; + // ADR-0039: resolving — an enum extending an abstract enum sees its @normalize. + if let Some(Value::String(m)) = tree.attr(field, A_NORMALIZE) { + return (m.clone(), true); + } + if let Some(p) = tree + .node(field) + .parent + .filter(|&p| tree.node(p).type_name == TYPE_OBJECT) + && let Some(Value::String(m)) = tree.attr(p, A_NORMALIZE) + { + return (m.clone(), true); + } + (NORMALIZE_DEFAULT.to_string(), false) +} + +/// Every field.enum in the tree with the members it declares itself (more than one), +/// when its effective mode is the default. +fn for_each_enum(ctx: &Ctx<'_>, mut f: impl FnMut(NodeId, Vec, bool)) { + fn visit(ctx: &Ctx<'_>, id: NodeId, f: &mut impl FnMut(NodeId, Vec, bool)) { + let tree = ctx.tree; + let n = tree.node(id); + if n.type_name == TYPE_FIELD && n.sub_type == SUB_ENUM { + // ADR-0039: own — the vocabulary DECLARED here; an inheriting enum shares the super's. + if let Some(Value::Array(vals)) = tree.own_attr(id, A_VALUES).map(|a| &a.value) + && vals.len() > 1 + { + let (mode, explicit) = effective_normalize(ctx, id); + if mode == NORMALIZE_DEFAULT { + f(id, vals.iter().map(js_display).collect(), explicit); + } + } + } + // ADR-0039: own — a structural walk of what each node declares. + for &c in tree.own_children(id) { + visit(ctx, c, f); + } + } + visit(ctx, ctx.root, &mut f); +} + +pub fn validate_enum_normalize_ambiguity(ctx: &Ctx<'_>, out: &mut Findings) { + for_each_enum(ctx, |id, members, explicit| { + let entries: Vec<(&str, String)> = members + .iter() + .map(|m| (m.as_str(), strip_normalize(m))) + .collect(); + for (i, (member, stripped)) in entries.iter().enumerate() { + if stripped.is_empty() { + continue; + } + // Exclude the member itself BY INDEX: two members can strip alike. + let others: Vec<(&str, &str)> = entries + .iter() + .enumerate() + .filter(|(j, (_, s))| *j != i && !s.is_empty()) + .map(|(_, (m, s))| (*m, s.as_str())) + .collect(); + if let Some(seg) = segment_into(stripped, &others) { + let plus = seg + .iter() + .map(|s| format!("'{s}'")) + .collect::>() + .join(" + "); + let delimited = seg + .iter() + .map(|s| s.to_lowercase()) + .collect::>() + .join("|"); + let name = &ctx.tree.node(id).name; + out.warnings.push(MetaError::at( + WARN_ENUM_NORMALIZE_AMBIGUOUS, + format!( + "field.enum \"{name}\" member '{member}' is the concatenation of {plus} under @{A_NORMALIZE}: '{NORMALIZE_DEFAULT}'{}, which erases separators. A delimited value such as \"{delimited}\" would coerce silently to '{member}' and be reported as extracted rather than malformed. Set @{A_NORMALIZE}: 'collapse' on this field if it can receive delimited input.", + if explicit { "" } else { " (the default)" } + ), + ctx.tree.node(id).source.clone(), + )); + break; + } + } + }); +} + +pub fn validate_enum_normalize_collision(ctx: &Ctx<'_>, out: &mut Findings) { + for_each_enum(ctx, |id, members, explicit| { + let mut by_key: indexmap::IndexMap> = indexmap::IndexMap::new(); + for m in &members { + let key = strip_normalize(m); + if !key.is_empty() { + by_key.entry(key).or_default().push(m); + } + } + for (key, ms) in by_key { + let mut distinct: Vec<&str> = Vec::new(); + for m in ms { + if !distinct.contains(&m) { + distinct.push(m); + } + } + if distinct.len() < 2 { + continue; + } + let list = distinct + .iter() + .map(|d| format!("'{d}'")) + .collect::>() + .join(", "); + let name = &ctx.tree.node(id).name; + out.errors.push(error_at(ctx.tree, id, ERR_ENUM_NORMALIZE_COLLISION, format!( + "field.enum \"{name}\" members {list} all normalize to '{key}' under @{A_NORMALIZE}: '{NORMALIZE_DEFAULT}'{}, which upper-cases and deletes everything outside A-Z0-9, so a reply naming one of them is indistinguishable from the others. Rename the members so they differ after that fold, or set @{A_NORMALIZE}: 'collapse' (keeps '_' distinct) or 'none' (exact match) on this field.", + if explicit { "" } else { " (the default)" }))); + break; + } + }); +} + +// ---- field mutability --------------------------------------------------------------- + +fn mode_of(v: Option<&Value>) -> Option { + v.and_then(Value::as_str) + .and_then(|s| MUTABILITY_MODES.iter().position(|m| *m == s)) +} + +/// The effective mode (resolving, ADR-0039); absent is `readWrite` (rank 0). +fn effective_mode(ctx: &Ctx<'_>, field: NodeId) -> usize { + mode_of(ctx.tree.attr(field, A_MUTABILITY)).unwrap_or(0) +} + +fn write_host_read_only(ctx: &Ctx<'_>, obj: NodeId) -> bool { + let tree = ctx.tree; + if tree.node(obj).sub_type == SUB_PROJECTION { + return true; + } + // ADR-0039: resolving — a source may be inherited via extends. + let sources: Vec = tree + .children(obj) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_SOURCE) + .collect(); + !sources.is_empty() + && sources.iter().all(|&s| { + let kind = tree + .attr(s, A_KIND) + .and_then(Value::as_str) + .filter(|k| !k.is_empty()) + .unwrap_or("table"); + READ_ONLY_SOURCE_KINDS.contains(&kind) + }) +} + +fn primary_assigned_names(ctx: &Ctx<'_>, obj: NodeId) -> Vec { + let tree = ctx.tree; + let mut out = Vec::new(); + for &id in tree.children(obj).iter() { + let n = tree.node(id); + if n.type_name != TYPE_IDENTITY || n.sub_type != SUB_PRIMARY { + continue; + } + if tree.attr(id, A_GENERATION).and_then(Value::as_str) != Some(GENERATION_ASSIGNED) { + continue; + } + match tree.attr(id, A_FIELDS) { + Some(Value::Array(a)) => { + out.extend(a.iter().filter_map(Value::as_str).map(str::to_string)) + } + Some(Value::String(s)) => out.push(s.clone()), + _ => {} + } + } + out +} + +/// The declaring node of a same-named field up the extends chain. +fn inherited_field(ctx: &Ctx<'_>, obj: NodeId, name: &str) -> Option { + let tree = ctx.tree; + let mut cursor = tree.node(obj).super_node; + let mut hops = 0; + while let Some(c) = cursor { + // ADR-0039: own — each level's OWN fields locate the declaring node. + if let Some(&f) = tree + .own_children(c) + .iter() + .find(|&&x| tree.node(x).type_name == TYPE_FIELD && tree.node(x).name == name) + { + return Some(f); + } + hops += 1; + if hops > tree.len() { + break; + } + cursor = tree.node(c).super_node; + } + None +} + +pub fn validate_field_mutability(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for &obj in tree + .children(ctx.root) + .iter() + .filter(|&&c| tree.node(c).type_name == TYPE_OBJECT) + { + let on = tree.node(obj); + let is_value = on.sub_type == SUB_VALUE; + let host_never_written = write_host_read_only(ctx, obj); + // ADR-0039: own — own-vs-super comparisons by design. + for &fld in tree + .own_children(obj) + .iter() + .filter(|&&c| tree.node(c).type_name == TYPE_FIELD) + { + let fname = &tree.node(fld).name; + let own = mode_of(tree.own_attr(fld, A_MUTABILITY).map(|a| &a.value)); + if is_value && let Some(m) = own.filter(|&m| m != 0) { + out.warnings.push(MetaError::at( + WARN_MUTABILITY_VALUE_OBJECT, + format!("field \"{fname}\" on object.value \"{}\" declares @mutability: \"{}\"; value objects have no persistence semantics, so the write contract is advisory (codegen may use it for record/struct treatment).", on.name, MUTABILITY_MODES[m]), + tree.node(fld).source.clone(), + )); + } + if let Some(m) = own + && let Some(parent_field) = inherited_field(ctx, obj, fname) + && let Some(pm) = + mode_of(tree.own_attr(parent_field, A_MUTABILITY).map(|a| &a.value)) + && m < pm + { + out.errors.push(error_at(tree, fld, ERR_MUTABILITY_DOWNGRADE, format!( + "field \"{fname}\" on \"{}\" sets @mutability: \"{}\", but its extends-chain parent declares \"{}\". A subtype may only TIGHTEN an inherited mode ({}), never loosen it (FR-037 R1).", + on.name, MUTABILITY_MODES[m], MUTABILITY_MODES[pm], MUTABILITY_MODES.join(" < ")))); + } + } + let fields: Vec = tree + .children(obj) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_FIELD) + .collect(); + for &fld in &fields { + let mode = effective_mode(ctx, fld); + let fname = &tree.node(fld).name; + if mode != 0 && tree.attr(fld, A_AUTO_SET).is_some() { + out.errors.push(error_at(tree, fld, ERR_MUTABILITY_AUTOSET_CONFLICT, format!( + "field \"{fname}\" on \"{}\" declares @autoSet together with @mutability: \"{}\". @autoSet already means the SERVER supplies the value; @mutability says who may write it. Drop @mutability (an @autoSet field is already excluded from every input shape) or drop @autoSet (FR-037 R1).", + on.name, MUTABILITY_MODES[mode]))); + } + if mode == 1 && host_never_written { + out.warnings.push(MetaError::at( + WARN_MUTABILITY_READONLY_HOST, + format!("field \"{fname}\" on \"{}\" declares @mutability: \"writeOnce\", but its host is never written (a projection, or a read-only source @kind). The declaration is inert — nothing creates a row here for it to be settable on.", on.name), + tree.node(fld).source.clone(), + )); + } + } + if !is_value { + let assigned = primary_assigned_names(ctx, obj); + if !assigned.is_empty() { + for &fld in &fields { + let fname = &tree.node(fld).name; + if assigned.contains(fname) && effective_mode(ctx, fld) == 2 { + out.errors.push(error_at(tree, fld, ERR_READONLY_ASSIGNED_PRIMARY, format!( + "field \"{fname}\" on \"{}\" is @mutability: \"readOnly\" AND the target of identity.primary with @generation: \"assigned\"; the application has no path to populate the identity value. Use @mutability: \"writeOnce\" if the intent is \"set once on create, never changed\" (FR-037 R1).", + on.name))); + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_are_in_the_catalogue() { + let raw = include_str!("../../../../../fixtures/conformance/ERROR-CODES.json"); + let doc: Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for c in [ + ERR_ENUM_NORMALIZE_COLLISION, + ERR_MUTABILITY_AUTOSET_CONFLICT, + ERR_MUTABILITY_DOWNGRADE, + ERR_READONLY_ASSIGNED_PRIMARY, + ] { + assert!(codes.contains_key(c), "{c}"); + } + } + + #[test] + fn strip_folds_ascii_only() { + assert_eq!(strip_normalize("read_Write-1ß"), "READWRITE1"); + } + + #[test] + fn word_break_finds_the_fewest_segments() { + let dict = [("READ", "READ"), ("WRITE", "WRITE"), ("RW", "READWRITE")]; + assert_eq!( + segment_into("READWRITE", &dict[..2]), + Some(vec!["READ", "WRITE"]) + ); + assert_eq!(segment_into("READ", &dict[..2]), None); + assert_eq!( + segment_into("READWRITE", &dict), + Some(vec!["RW"]).filter(|s| s.len() >= 2) + ); + } +} diff --git a/server/rust/metaobjects/src/validate/mod.rs b/server/rust/metaobjects/src/validate/mod.rs new file mode 100644 index 0000000000..98592ce9d6 --- /dev/null +++ b/server/rust/metaobjects/src/validate/mod.rs @@ -0,0 +1,190 @@ +//! The validation passes, run in the order the TypeScript reference runs them. +//! +//! Each pass is one named function over the merged, super-resolved tree. Order is +//! part of the contract: the corpus compares error envelopes position by position, so +//! a pass added here goes where the reference runs it. Every pass is timed under its +//! own name (see [`crate::timing`]), so adding one shows in the benchmark table. + +pub mod attrs; +pub mod field; +pub mod field_expr; +pub mod field_policy; +pub mod origin; +pub mod persistence; +pub mod prompt; +pub mod refs; +pub mod relationships; +pub mod reporting; +pub mod structure; +pub mod util; + +use crate::errors::MetaError; +use crate::naming::NamingCtx; +use crate::node::{NodeId, Tree}; +use crate::registry::TypeRegistry; +use crate::timing::{LoadTimings, PHASE_VALIDATE}; + +/// What a pass reads. +pub struct Ctx<'a> { + pub tree: &'a Tree, + pub root: NodeId, + pub registry: &'a TypeRegistry, + /// Strict mode, as the loader option of that name. + pub strict: bool, + /// The root's objects by resolution key, built once per load. + pub objects: &'a util::ObjectIndex, + /// The project's physical naming and the registry its names resolve in. + pub naming: NamingCtx<'a>, +} + +/// What a pass writes. Errors and warnings are separate channels, as in every port. +#[derive(Debug, Default)] +pub struct Findings { + pub errors: Vec, + pub warnings: Vec, +} + +/// One validation pass. +pub type PassFn = fn(&Ctx<'_>, &mut Findings); + +/// Every pass, in the reference's order, each under the name the benchmark prints. +/// +/// The order below is `MetaDataLoader.load` in the TypeScript reference +/// (`loader/meta-data-loader.ts`). A pass joins the list at its place in that +/// order. Every reference pass has a Rust port; the table lists them in the order +/// they run: +/// +/// ```text +/// validateSubtypeRules (errors + warnings) validateMaxOccurs +/// validateIdentityPassthrough validateDataGridSortFields +/// validateFilterableHasIndex (warning) validateExtenderSubtypeScope (warning) +/// validateFilterableHasSupportedOps validateSortableHasSupportedSubtype +/// validateOriginPaths validateDerivedFieldProvidability +/// validateDataGridFilterValues validateProjectionFilter +/// validateOriginSegmentsAndCorrelation validateProjectionUnionAndGrain +/// validateDerivedCycles validateReporting +/// validateRelationships validateOneSideReferenceResolution +/// validateM2MJunctionPairing validateIndexLookupFields +/// validateColumnNameCollisions validateRetiredRequirementLinks +/// runRegisteredValidation validateTemplatePayloadRefs +/// validateAttrSchema (errors + warnings) validateFieldObjectStorage +/// validateFieldMap validateEnumMaxLength +/// validateIdentitySequence validateCrossFieldValidators +/// validateDbCheck validateSourceRoles +/// validateSourceEscapes validateSourcePhysicalNames +/// validateFieldMutability validateEnumNormalizeAmbiguity (warning) +/// validateEnumNormalizeCollision validateSourceParameterRef +/// validateDiscriminator validateFieldDefaults +/// ``` +pub const PASSES: &[(&str, PassFn)] = &[ + ("subtype rules", structure::subtype_rules), + ("max occurs", structure::max_occurs), + ("identity passthrough", structure::identity_passthrough), + ( + "data grid sort fields", + persistence::validate_data_grid_sort_fields, + ), + ( + "filterable has index", + persistence::validate_filterable_has_index, + ), + ( + "extender subtype scope", + origin::validate_extender_subtype_scope, + ), + ( + "filterable supported ops", + persistence::validate_filterable_has_supported_ops, + ), + ( + "sortable supported subtype", + persistence::validate_sortable_has_supported_subtype, + ), + ("origin paths", origin::validate_origin_paths), + ( + "derived field providability", + origin::validate_derived_field_providability, + ), + ( + "data grid filter values", + persistence::validate_data_grid_filter_values, + ), + ("projection filter", origin::validate_projection_filter), + ( + "origin segments and correlation", + origin::validate_origin_segments_and_correlation, + ), + ( + "projection union and grain", + origin::validate_projection_union_and_grain, + ), + ("derived cycles", origin::validate_derived_cycles), + ("reporting", reporting::validate_reporting), + ("relationships", relationships::validate_relationships), + ( + "one-side reference resolution", + relationships::validate_one_side_reference_resolution, + ), + ( + "m2m junction pairing", + relationships::validate_m2m_junction_pairing, + ), + ( + "index lookup fields", + persistence::validate_index_lookup_fields, + ), + ( + "column name collisions", + persistence::validate_column_name_collisions, + ), + ( + "retired requirement links", + prompt::validate_retired_requirement_links, + ), + ("registered validation", refs::registered_validation), + ( + "template payload refs", + prompt::validate_template_payload_refs, + ), + ("attr schema", attrs::attr_schema), + ("field object storage", field::validate_field_object_storage), + ("field map", field::validate_field_map), + ("enum max length", field::validate_enum_max_length), + ("identity sequence", structure::identity_sequence), + ( + "cross-field validators", + field_expr::validate_cross_field_validators, + ), + ("db check", field_expr::validate_db_check), + ("source roles", persistence::validate_source_roles), + ("source escapes", persistence::validate_source_escapes), + ( + "source physical names", + persistence::validate_source_physical_names, + ), + ("field mutability", field_policy::validate_field_mutability), + ( + "enum normalize ambiguity", + field_policy::validate_enum_normalize_ambiguity, + ), + ( + "enum normalize collision", + field_policy::validate_enum_normalize_collision, + ), + ( + "source parameter ref", + persistence::validate_source_parameter_ref, + ), + ("discriminator", structure::discriminator), + ("field defaults", field::validate_field_defaults), +]; + +/// Run every pass, timing each under its own name and all of them under the +/// `validation` phase. +pub fn run(ctx: &Ctx<'_>, findings: &mut Findings, timings: &mut LoadTimings) { + let start = std::time::Instant::now(); + for (name, pass) in PASSES { + timings.pass(name, || pass(ctx, findings)); + } + timings.add_phase(PHASE_VALIDATE, start.elapsed()); +} diff --git a/server/rust/metaobjects/src/validate/origin.rs b/server/rust/metaobjects/src/validate/origin.rs new file mode 100644 index 0000000000..e2660c4045 --- /dev/null +++ b/server/rust/metaobjects/src/validate/origin.rs @@ -0,0 +1,2693 @@ +//! Origin and projection validation: ports of `validateOriginPaths`, +//! `validateDerivedFieldProvidability`, `validateOriginSegmentsAndCorrelation`, +//! `validateDerivedCycles`, `validateProjectionFilter` and +//! `validateProjectionUnionAndGrain` (`loader/validation-passes.ts`). +//! +//! ADR-0039: resolving accessors by default; `own_*` only where the comment names the +//! sanctioned case (origin.* never inherits, ADR-0029, so an origin is always its own). + +use std::borrow::Cow; +use std::collections::{HashMap, HashSet}; + +use serde_json::Value; + +use crate::errors::{MetaError, WARN_LEGACY}; +use crate::loader::split_child_tail; +use crate::naming::{NamingCtx, collection_name_of}; +use crate::node::{NodeId, Tree}; +use crate::source::ErrorSource; +use crate::validate::field_expr::{ + CAST_TARGETS, FieldView, expression_nodes, infer_with, literal_comparison_problem, + validate_expr, +}; +use crate::validate::util::{ObjectIndex, ops_for_field}; +use crate::validate::{Ctx, Findings}; + +pub const ERR_INVALID_ORIGIN: &str = "ERR_INVALID_ORIGIN"; +pub const ERR_SUBTYPE_RULE_VIOLATION: &str = "ERR_SUBTYPE_RULE_VIOLATION"; +pub const ERR_EXTENDS_ORIGIN_MISMATCH: &str = "ERR_EXTENDS_ORIGIN_MISMATCH"; +pub const ERR_PASSTHROUGH_TYPE_MISMATCH: &str = "ERR_PASSTHROUGH_TYPE_MISMATCH"; +pub const ERR_AMBIGUOUS_PATH: &str = "ERR_AMBIGUOUS_PATH"; +pub const ERR_ORIGIN_CARDINALITY: &str = "ERR_ORIGIN_CARDINALITY"; +pub const ERR_COLLECT_MEMBER_UNRESOLVED: &str = "ERR_COLLECT_MEMBER_UNRESOLVED"; +pub const ERR_COLLECT_WHOLE_OBJECT: &str = "ERR_COLLECT_WHOLE_OBJECT"; +pub const ERR_UNKNOWN_EXPR_NODE: &str = "ERR_UNKNOWN_EXPR_NODE"; +pub const ERR_COMPUTED_TYPE_MISMATCH: &str = "ERR_COMPUTED_TYPE_MISMATCH"; +pub const ERR_DERIVED_FIELD_NO_READ_SOURCE: &str = "ERR_DERIVED_FIELD_NO_READ_SOURCE"; +pub const ERR_BAD_ATTR_FILTER: &str = "ERR_BAD_ATTR_FILTER"; +pub const ERR_BAD_ATTR_VALUE: &str = "ERR_BAD_ATTR_VALUE"; + +const T_OBJECT: &str = "object"; +const T_FIELD: &str = "field"; +const T_ORIGIN: &str = "origin"; +const T_IDENTITY: &str = "identity"; +const T_RELATIONSHIP: &str = "relationship"; +const T_SOURCE: &str = "source"; +const T_SEGMENT: &str = "segment"; +const SUB_ENTITY: &str = "entity"; +const SUB_VALUE: &str = "value"; +const SUB_PROJECTION: &str = "projection"; +const O_PASSTHROUGH: &str = "passthrough"; +const O_AGGREGATE: &str = "aggregate"; +const O_COMPUTED: &str = "computed"; +const O_FIRST: &str = "first"; +const O_FUNCTION: &str = "function"; +const ASSEMBLY: &[&str] = &[O_AGGREGATE, O_COMPUTED, O_FIRST, O_FUNCTION]; +const ID_REFERENCE: &str = "reference"; +const ID_PRIMARY: &str = "primary"; +const ID_SECONDARY: &str = "secondary"; +const AGG_ANY: &str = "any"; +const AGG_ALL: &str = "all"; +const AGG_COLLECT: &str = "collect"; +const COLUMN_AGGS: &[&str] = &["sum", "avg", "min", "max"]; +const SORT_ORDER: &[&str] = &["asc", "desc"]; +const CORRELATED_OPS: &[&str] = &[ + "eq", + "ne", + "gt", + "gte", + "lt", + "lte", + "isDistinctFrom", + "isNotDistinctFrom", +]; +const NULL_SAFE_OPS: &[&str] = &["isDistinctFrom", "isNotDistinctFrom"]; +const READ_ONLY_KINDS: &[&str] = &["view", "materializedView", "storedProc", "tableFunction"]; +const FILTER_AND: &str = "and"; +const FILTER_OR: &str = "or"; + +// --------------------------------------------------------------------------- +// The model view every pass here shares. +// --------------------------------------------------------------------------- + +/// Root-level objects by resolution key (ADR-0042 / ADR-0059). +struct M<'a> { + tree: &'a Tree, + index: &'a ObjectIndex, + naming: NamingCtx<'a>, +} + +type Errs = Vec; + +fn push(errs: &mut Errs, code: &'static str, msg: String, src: &ErrorSource) { + errs.push(MetaError::at(code, msg, src.clone())); +} + +/// `resolvedSource(src, referrer, target)`. +fn resolved_src(src: &ErrorSource, referrer: String, target: &str) -> ErrorSource { + ErrorSource::Resolved { + files: src.files().to_vec(), + json_path: src.json_path().unwrap_or("$").to_string(), + referrer, + target: target.to_string(), + } +} + +impl<'a> M<'a> { + fn new(ctx: &Ctx<'a>) -> Self { + M { + tree: ctx.tree, + index: ctx.objects, + naming: ctx.naming, + } + } + + fn pkg(&self, id: NodeId) -> &'a str { + let n = self.tree.node(id); + n.package + .as_deref() + .or(n.file_default_package.as_deref()) + .unwrap_or("") + } + + fn find_object(&self, name: &str, pkg: &str) -> Option { + self.index.resolve(name, pkg) + } + + fn is(&self, id: NodeId, ty: &str, sub: &str) -> bool { + let n = self.tree.node(id); + n.type_name == ty && n.sub_type == sub + } + + fn kids(&self, id: NodeId) -> Cow<'a, [NodeId]> { + self.tree.children(id) + } + + fn find_child(&self, obj: NodeId, ty: &str, name: &str) -> Option { + self.kids(obj).iter().copied().find(|&c| { + let n = self.tree.node(c); + n.type_name == ty && n.name == name + }) + } + + fn find_field(&self, obj: NodeId, name: &str) -> Option { + self.find_child(obj, T_FIELD, name) + } + + fn fields(&self, obj: NodeId) -> Vec { + self.kids(obj) + .iter() + .copied() + .filter(|&c| self.tree.node(c).type_name == T_FIELD) + .collect() + } + + fn own_fields(&self, obj: NodeId) -> Vec { + // ADR-0039: own: origin validation runs on the own-declared field + origin layer + // (origin.* never inherits, ADR-0029). + self.tree + .own_children(obj) + .iter() + .copied() + .filter(|&c| self.tree.node(c).type_name == T_FIELD) + .collect() + } + + /// The origin child a field carries, as `ownChildren().find(type == origin)`. + fn origin_of(&self, field: NodeId) -> Option { + // ADR-0039: own: origin.* never inherits (ADR-0029). + self.tree + .own_children(field) + .iter() + .copied() + .find(|&c| self.tree.node(c).type_name == T_ORIGIN) + } + + fn origins_of(&self, field: NodeId) -> Vec { + // ADR-0039: own: origin.* never inherits (ADR-0029). + self.tree + .own_children(field) + .iter() + .copied() + .filter(|&c| self.tree.node(c).type_name == T_ORIGIN) + .collect() + } + + /// Resolving string attr; `None` when absent or not a string. + fn attr_str(&self, id: NodeId, name: &str) -> Option<&'a str> { + self.tree.attr(id, name).and_then(Value::as_str) + } + + /// Own attr value (origin.* and projection layer attrs never inherit). + fn own(&self, id: NodeId, name: &str) -> Option<&'a Value> { + // ADR-0039: own: the attr is read on the layer that declares it (ADR-0029). + self.tree.own_attr(id, name).map(|a| &a.value) + } + + fn own_nonempty(&self, id: NodeId, name: &str) -> Option<&'a str> { + self.own(id, name) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + } + + /// `refTarget(node, attr)`: the declaring layer's value, resolved in that layer's package. + fn ref_target(&self, node: NodeId, attr: &str) -> Option { + self.index.ref_target(self.tree, node, attr) + } + + fn type_label(&self, field: NodeId) -> String { + format!( + "field.{}{}", + self.tree.node(field).sub_type, + if self.tree.resolved_is_array(field) { + "[]" + } else { + "" + } + ) + } + + fn super_chain_contains(&self, start: NodeId, target: NodeId) -> bool { + let mut cur = Some(start); + let mut n = 0; + while let Some(c) = cur { + if c == target { + return true; + } + n += 1; + if n > self.tree.len() { + return false; + } + cur = self.tree.node(c).super_node; + } + false + } + + fn collection_hop_name(&self, holder: NodeId) -> Option { + let plural = collection_name_of(self.tree, holder, &self.naming).ok()?; + let mut c = plural.chars(); + Some(match c.next() { + Some(f) => f.to_lowercase().chain(c).collect(), + None => plural, + }) + } + + /// Every identity.reference onto `target` from a concrete object whose reverse hop is `hop`. + fn reverse_hops(&self, target: NodeId, hop: &str) -> Vec<(NodeId, NodeId)> { + let mut found = Vec::new(); + for &holder in self.index.objects() { + if self.tree.node(holder).is_abstract + || self.collection_hop_name(holder).as_deref() != Some(hop) + { + continue; + } + for &r in self.kids(holder).iter() { + if self.is(r, T_IDENTITY, ID_REFERENCE) + && self.ref_target(r, "references") == Some(target) + { + found.push((holder, r)); + } + } + } + found + } + + fn find_reference(&self, obj: NodeId, name: &str) -> Option { + self.kids(obj) + .iter() + .copied() + .find(|&c| self.is(c, T_IDENTITY, ID_REFERENCE) && self.tree.node(c).name == name) + } +} + +// --------------------------------------------------------------------------- +// Path helpers. +// --------------------------------------------------------------------------- + +struct FromTarget { + entity: NodeId, + field: NodeId, +} + +/// `resolveFlattenedMember(entity, "head.tail")`. +fn flattened_member(m: &M<'_>, entity: NodeId, path: &str) -> Option { + let dot = path.find('.')?; + if dot < 1 || dot == path.len() - 1 || path[dot + 1..].contains('.') { + return None; + } + let embedding = m.find_field(entity, &path[..dot])?; + if m.tree.node(embedding).sub_type != "object" + || m.tree.attr(embedding, "storage").and_then(Value::as_str) != Some("flattened") + { + return None; + } + let vo = m.ref_target(embedding, "objectRef")?; + m.find_field(vo, &path[dot + 1..]) +} + +fn validate_from_path( + m: &M<'_>, + from: &str, + host: NodeId, + field_name: &str, + src: &ErrorSource, + errs: &mut Errs, + label: &str, +) -> Option { + let h = m.tree.node(host); + let referrer = format!("{}::{field_name}", h.fqn()); + let pkg = m.pkg(host); + let rs = || resolved_src(src, referrer.clone(), from); + let dot = from.find('.'); + let Some(dot) = dot.filter(|&d| d >= 1 && d != from.len() - 1) else { + push( + errs, + ERR_INVALID_ORIGIN, + format!( + "{label} \"{from}\" on {}.{field_name}: must be of form \"Entity.field\".", + h.name + ), + &rs(), + ); + return None; + }; + let (entity_name, field_part) = (&from[..dot], &from[dot + 1..]); + let Some(entity) = m.find_object(entity_name, pkg) else { + push( + errs, + ERR_INVALID_ORIGIN, + format!( + "{label} \"{from}\" on {}.{field_name}: no such entity \"{entity_name}\".", + h.name + ), + &rs(), + ); + return None; + }; + let Some(field) = m + .find_field(entity, field_part) + .or_else(|| flattened_member(m, entity, field_part)) + else { + push( + errs, + ERR_INVALID_ORIGIN, + format!( + "{label} \"{from}\" on {}.{field_name}: no such field \"{field_part}\" on {entity_name}.", + h.name + ), + &rs(), + ); + return None; + }; + Some(FromTarget { entity, field }) +} + +struct Walked { + hops: Vec, + terminal: NodeId, + /// Hops walked backwards, keyed to the hop name the path wrote. + reverse: Vec<(NodeId, String)>, +} + +impl Walked { + fn is_reverse(&self, hop: NodeId) -> Option<&str> { + self.reverse + .iter() + .find(|(h, _)| *h == hop) + .map(|(_, n)| n.as_str()) + } +} + +fn validate_via_path( + m: &M<'_>, + via: &str, + host: NodeId, + field_name: &str, + src: &ErrorSource, + errs: &mut Errs, +) -> Option { + let tree = m.tree; + let h = tree.node(host); + let referrer = format!("{}::{field_name}", h.fqn()); + let rs = |t: &str| resolved_src(src, referrer.clone(), t); + let at = format!("origin.@via \"{via}\" on {}.{field_name}", h.name); + let segments: Vec<&str> = via.split('.').collect(); + if segments.len() < 2 { + push( + errs, + ERR_INVALID_ORIGIN, + format!("{at}: must be of form \"Entity.relationship[.relationship...]\"."), + &rs(via), + ); + return None; + } + let Some(mut cur) = m.find_object(segments[0], m.pkg(host)) else { + push( + errs, + ERR_INVALID_ORIGIN, + format!("{at}: no such entity \"{}\".", segments[0]), + &rs(via), + ); + return None; + }; + let mut valid = vec![segments[0].to_string()]; + let mut hops = Vec::new(); + let mut reverse = Vec::new(); + for rel_name in &segments[1..] { + let rel = m + .find_child(cur, T_RELATIONSHIP, rel_name) + .or_else(|| m.find_reference(cur, rel_name)); + let Some(rel) = rel else { + let reversed = m.reverse_hops(cur, rel_name); + if reversed.len() == 1 { + valid.push(rel_name.to_string()); + hops.push(reversed[0].1); + reverse.push((reversed[0].1, rel_name.to_string())); + cur = reversed[0].0; + continue; + } + if reversed.len() > 1 { + push( + errs, + ERR_AMBIGUOUS_PATH, + format!( + "{at}: the reverse hop \"{rel_name}\" from {} matches {} identity.reference nodes onto it — ambiguous.", + tree.node(cur).name, + reversed.len() + ), + &rs(via), + ); + return None; + } + push( + errs, + ERR_INVALID_ORIGIN, + format!( + "{at}: no such relationship or reference \"{rel_name}\" on {}. Deepest valid prefix was \"{}\".", + tree.node(cur).name, + valid.join(".") + ), + &rs(via), + ); + return None; + }; + let is_ref = m.is(rel, T_IDENTITY, ID_REFERENCE); + let target = m + .attr_str(rel, if is_ref { "references" } else { "objectRef" }) + .filter(|s| !s.is_empty()); + let kind = if is_ref { "reference" } else { "relationship" }; + let Some(target) = target else { + push( + errs, + ERR_INVALID_ORIGIN, + format!( + "{at}: {kind} \"{rel_name}\" on {} is missing @{}.", + tree.node(cur).name, + if is_ref { "references" } else { "objectRef" } + ), + &rs(via), + ); + return None; + }; + let Some(next) = m.find_object(target, m.pkg(cur)) else { + push( + errs, + ERR_INVALID_ORIGIN, + format!("{at}: {kind} \"{rel_name}\" points to non-existent entity \"{target}\"."), + &rs(target), + ); + return None; + }; + valid.push(rel_name.to_string()); + hops.push(rel); + cur = next; + } + Some(Walked { + hops, + terminal: cur, + reverse, + }) +} + +fn hop_cardinality<'a>( + m: &'a M<'_>, + rel: NodeId, + walked: Option<&Walked>, + unique_reverse_is_one: bool, +) -> Option<&'a str> { + if walked.is_some_and(|w| w.is_reverse(rel).is_some()) { + return Some(if unique_reverse_is_one && reverse_hop_is_unique(m, rel) { + "one" + } else { + "many" + }); + } + if m.is(rel, T_IDENTITY, ID_REFERENCE) { + return Some("one"); + } + m.attr_str(rel, "cardinality") +} + +fn identity_field_set(m: &M<'_>, node: NodeId) -> String { + let mut list: Vec = match m.tree.attr(node, "fields") { + Some(Value::Array(a)) => a.iter().map(crate::json::js_display).collect(), + Some(Value::String(s)) => s.split(',').map(str::to_string).collect(), + _ => Vec::new(), + }; + list = list + .into_iter() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(); + list.sort(); + list.join(",") +} + +fn reverse_hop_is_unique(m: &M<'_>, rel: NodeId) -> bool { + let Some(holder) = m.tree.node(rel).parent else { + return false; + }; + let fields = identity_field_set(m, rel); + if fields.is_empty() { + return false; + } + m.kids(holder).iter().any(|&c| { + let n = m.tree.node(c); + n.type_name == T_IDENTITY + && (n.sub_type == ID_PRIMARY || n.sub_type == ID_SECONDARY) + && m.tree.attr(c, "where").is_none() + && m.tree.attr(c, "expr").is_none() + && identity_field_set(m, c) == fields + }) +} + +/// `_refNamedOwner`: the entity NAMED in a node's dotted extends ref. +fn ref_named_owner(m: &M<'_>, node: NodeId, pkg: &str) -> Option { + let r = m.tree.node(node).super_ref.as_deref()?; + let (owner, tail) = split_child_tail(r); + if tail.is_empty() || owner.is_empty() { + return None; + } + m.find_object(owner, pkg) +} + +fn anchors_by_identity(m: &M<'_>, obj: NodeId, depth: usize) -> bool { + if depth > m.tree.len() { + return false; + } + // ADR-0039: own: an anchor is a locally declared extends-bound identity at some level. + if m.tree.own_children(obj).iter().any(|&c| { + m.tree.node(c).type_name == T_IDENTITY + && m.tree + .node(c) + .super_node + .is_some_and(|s| m.tree.node(s).type_name == T_IDENTITY) + }) { + return true; + } + match m.tree.node(obj).super_node { + Some(s) if m.is(s, T_OBJECT, SUB_PROJECTION) => anchors_by_identity(m, s, depth + 1), + _ => false, + } +} + +fn derive_base( + m: &M<'_>, + obj: NodeId, + field_name: &str, + src: &ErrorSource, + errs: &mut Errs, +) -> Option { + derive_base_d(m, obj, field_name, src, errs, 0) +} + +fn derive_base_d( + m: &M<'_>, + obj: NodeId, + field_name: &str, + src: &ErrorSource, + errs: &mut Errs, + depth: usize, +) -> Option { + let tree = m.tree; + let o = tree.node(obj); + if o.sub_type != SUB_PROJECTION { + return Some(obj); + } + if depth > tree.len() { + return None; + } + let pkg = m.pkg(obj); + // ADR-0039: own: this projection's OWN declared identities carry the extends refs. + let own_ids: Vec = tree + .own_children(obj) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == T_IDENTITY) + .collect(); + for &id in &own_ids { + if let Some(ext) = tree.node(id).super_node + && tree.node(ext).type_name == T_IDENTITY + { + if let Some(named) = ref_named_owner(m, id, pkg) { + return Some(named); + } + if let Some(owner) = tree.node(ext).parent + && tree.node(owner).type_name == T_OBJECT + { + return Some(owner); + } + } + } + let sup_proj = o + .super_node + .filter(|&s| tree.node(s).type_name == T_OBJECT && tree.node(s).sub_type == SUB_PROJECTION); + if own_ids.is_empty() + && let Some(sp) = sup_proj + && anchors_by_identity(m, sp, 0) + { + return derive_base_d(m, sp, field_name, src, errs, depth + 1); + } + let mut targets: Vec = Vec::new(); + for f in m.own_fields(obj) { + let Some(sup) = tree.node(f).super_node else { + continue; + }; + let owner = ref_named_owner(m, f, pkg).or(tree.node(sup).parent); + if let Some(owner) = owner + && tree.node(owner).type_name == T_OBJECT + && tree.node(owner).sub_type != SUB_VALUE + && owner != obj + && !targets.contains(&owner) + { + targets.push(owner); + } + } + if targets.len() == 1 { + return Some(targets[0]); + } + if targets.is_empty() + && let Some(sp) = sup_proj + { + return derive_base_d(m, sp, field_name, src, errs, depth + 1); + } + if targets.len() > 1 { + let names: Vec = targets + .iter() + .map(|&t| format!("\"{}\"", tree.node(t).name)) + .collect(); + push( + errs, + ERR_AMBIGUOUS_PATH, + format!( + "origin on {}.{field_name}: cannot derive the base entity — the projection's fields extend multiple entities ({}) and no identity extends an entity identity.", + o.name, + names.join(", ") + ), + src, + ); + } else { + push( + errs, + ERR_INVALID_ORIGIN, + format!( + "origin on {}.{field_name}: cannot derive the base entity for @via inference — the projection has no extended identity and no entity-targeted field extends.", + o.name + ), + src, + ); + } + None +} + +fn is_base_relation_target(m: &M<'_>, target: NodeId, base: NodeId, host: NodeId) -> bool { + m.super_chain_contains(base, target) || m.super_chain_contains(host, target) +} + +#[allow(clippy::too_many_arguments)] +fn infer_via_single_hop( + m: &M<'_>, + base: NodeId, + target: NodeId, + host: NodeId, + field_name: &str, + from: &str, + label: &str, + src: &ErrorSource, + errs: &mut Errs, +) -> Option> { + let tree = m.tree; + let candidates: Vec = m + .kids(base) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == T_RELATIONSHIP) + .filter(|&r| m.ref_target(r, "objectRef") == Some(target)) + .collect(); + let referrer = format!("{}::{field_name}", tree.node(host).fqn()); + if candidates.len() == 1 { + return Some(candidates); + } + let (code, msg) = if candidates.is_empty() { + ( + ERR_INVALID_ORIGIN, + format!( + "{label} \"{from}\" on {}.{field_name}: no @via and no single-hop relationship from base entity \"{}\" to \"{}\" — cannot infer the path.", + tree.node(host).name, + tree.node(base).name, + tree.node(target).name + ), + ) + } else { + ( + ERR_AMBIGUOUS_PATH, + format!( + "{label} \"{from}\" on {}.{field_name}: no @via and {} relationships from base entity \"{}\" to \"{}\" — ambiguous.", + tree.node(host).name, + candidates.len(), + tree.node(base).name, + tree.node(target).name + ), + ) + }; + push(errs, code, msg, &resolved_src(src, referrer, from)); + None +} + +fn check_passthrough_cardinality( + m: &M<'_>, + hops: &[NodeId], + host: NodeId, + field_name: &str, + src: &ErrorSource, + errs: &mut Errs, + walked: Option<&Walked>, +) { + for &rel in hops { + if hop_cardinality(m, rel, walked, true) == Some("many") { + let n = &m.tree.node(rel).name; + push( + errs, + ERR_ORIGIN_CARDINALITY, + format!( + "origin.passthrough on {}.{field_name}: @via hop \"{}\" is to-many {} — a row-multiplying passthrough — you meant aggregate (ADR-0029).", + m.tree.node(host).name, + walked.and_then(|w| w.is_reverse(rel)).unwrap_or(n), + if walked.is_some_and(|w| w.is_reverse(rel).is_some()) { + format!("(reverse hop over identity.reference \"{n}\")") + } else { + "(@cardinality \"many\")".to_string() + } + ), + src, + ); + return; + } + } +} + +fn check_aggregate_cardinality( + m: &M<'_>, + hops: &[NodeId], + host: NodeId, + field_name: &str, + src: &ErrorSource, + errs: &mut Errs, + walked: Option<&Walked>, +) { + if hops.is_empty() { + return; + } + if hops + .iter() + .all(|&r| hop_cardinality(m, r, walked, false) == Some("one")) + { + push( + errs, + ERR_ORIGIN_CARDINALITY, + format!( + "origin.aggregate on {}.{field_name}: every @via hop is to-one — aggregating over a to-one path — you meant passthrough (ADR-0029).", + m.tree.node(host).name + ), + src, + ); + } +} + +/// `resolveFilterPath`: `None` without a dot, `Err(why)` on a bad hop or field. +struct FilterPath { + field: NodeId, +} + +fn resolve_filter_path(m: &M<'_>, base: NodeId, key: &str) -> Option> { + let segs: Vec<&str> = key.split('.').collect(); + if segs.len() < 2 { + return None; + } + let (hops, field_name) = (&segs[..segs.len() - 1], segs[segs.len() - 1]); + let mut cur = base; + for hop in hops { + let cn = &m.tree.node(cur).name; + let next = if let Some(r) = m.find_reference(cur, hop) { + match m + .ref_target(r, "references") + .filter(|&t| m.tree.node(t).type_name == T_OBJECT) + { + Some(t) => t, + None => return Some(Err(format!("reference \"{cn}.{hop}\" does not resolve"))), + } + } else if let Some(rel) = m.find_child(cur, T_RELATIONSHIP, hop) { + if m.attr_str(rel, "cardinality") != Some("one") { + return Some(Err(format!( + "\"{cn}.{hop}\" is to-many; a filter path may only walk to-one hops" + ))); + } + match m + .ref_target(rel, "objectRef") + .filter(|&t| m.tree.node(t).type_name == T_OBJECT) + { + Some(t) => t, + None => { + return Some(Err(format!("relationship \"{cn}.{hop}\" does not resolve"))); + } + } + } else { + return Some(Err(format!( + "\"{cn}\" declares no identity.reference or to-one relationship named \"{hop}\"" + ))); + }; + cur = next; + } + match m.find_field(cur, field_name) { + Some(field) => Some(Ok(FilterPath { field })), + None => Some(Err(format!( + "\"{}\" declares no field \"{field_name}\"", + m.tree.node(cur).name + ))), + } +} + +/// A grain projection's element value object (rc.21 part B, U14). +fn grain_value_object(m: &M<'_>, obj: NodeId) -> Option { + if m.tree.node(obj).sub_type != SUB_PROJECTION { + return None; + } + let grain = m.attr_str(obj, "grain")?; + let base = derive_base(m, obj, "@grain", &m.tree.node(obj).source, &mut Vec::new())?; + let field = m.find_field(base, grain)?; + m.ref_target(field, "objectRef") +} + +#[allow(clippy::too_many_arguments)] +fn order_by_keys( + m: &M<'_>, + order_by: Option<&Value>, + related: Option, + host: NodeId, + field_name: &str, + label: &str, + src: &ErrorSource, + errs: &mut Errs, + code: &'static str, +) { + let (Some(Value::Array(list)), Some(related)) = (order_by, related) else { + return; + }; + for raw in list { + let Some(raw) = raw.as_str() else { continue }; + let (key, dir) = match raw.find(':') { + Some(i) => (&raw[..i], Some(&raw[i + 1..])), + None => (raw, None), + }; + let at = format!("{label} on {}.{field_name}", m.tree.node(host).name); + if m.find_field(related, key).is_none() { + push( + errs, + code, + format!( + "{at}: @orderBy key \"{raw}\" — no such field \"{key}\" on {}.", + m.tree.node(related).name + ), + src, + ); + } else if let Some(d) = dir + && !SORT_ORDER.contains(&d) + { + push( + errs, + code, + format!("{at}: @orderBy key \"{raw}\" — direction must be one of asc|desc."), + src, + ); + } + } +} + +// --------------------------------------------------------------------------- +// validateOriginPaths +// --------------------------------------------------------------------------- + +pub fn validate_origin_paths(ctx: &Ctx<'_>, out: &mut Findings) { + let m = M::new(ctx); + let mut errs = Vec::new(); + for &obj in m.index.objects() { + let is_value_host = m.tree.node(obj).sub_type == SUB_VALUE; + for field in m.own_fields(obj) { + for origin in m.origins_of(field) { + origin_one(&m, obj, field, origin, is_value_host, &mut errs); + } + } + } + out.errors.extend(errs); +} + +fn origin_one( + m: &M<'_>, + obj: NodeId, + field: NodeId, + origin: NodeId, + is_value_host: bool, + errs: &mut Errs, +) { + let tree = m.tree; + let o = tree.node(origin); + let on = &tree.node(obj).name; + let fname = tree.node(field).name.as_str(); + let src = &o.source; + if is_value_host && ASSEMBLY.contains(&o.sub_type.as_str()) { + push( + errs, + ERR_SUBTYPE_RULE_VIOLATION, + format!( + "value object '{}' field '{fname}' hosts origin.{} — assembly origins live on object.projection (#210, ADR-0028)", + tree.node(obj).fqn(), + o.sub_type + ), + src, + ); + return; + } + match o.sub_type.as_str() { + O_PASSTHROUGH => passthrough(m, obj, field, origin, is_value_host, errs), + O_AGGREGATE => aggregate(m, obj, field, origin, errs), + O_COMPUTED => computed(m, obj, field, origin, errs), + O_FIRST => first(m, obj, field, origin, errs), + O_FUNCTION => function_origin(m, obj, field, origin, errs), + _ => {} + } + let _ = on; +} + +fn passthrough( + m: &M<'_>, + obj: NodeId, + field: NodeId, + origin: NodeId, + is_value_host: bool, + errs: &mut Errs, +) { + let tree = m.tree; + let on = &tree.node(obj).name; + let fname = tree.node(field).name.as_str(); + let src = &tree.node(origin).source; + let Some(from) = m.own_nonempty(origin, "from") else { + push( + errs, + ERR_INVALID_ORIGIN, + format!("origin.passthrough on {on}.{fname}: missing @from."), + src, + ); + return; + }; + let target = validate_from_path(m, from, obj, fname, src, errs, "origin.passthrough.@from"); + let convert = m.own(origin, "convert") == Some(&Value::Bool(true)); + if let Some(t) = &target + && Some(t.entity) == grain_value_object(m, obj) + { + check_passthrough_type(m, field, t.field, from, convert, obj, src, errs); + let tf = tree.node(t.field); + if tree.resolved_is_array(t.field) || tf.sub_type == "object" || tf.sub_type == "map" { + push( + errs, + ERR_INVALID_ORIGIN, + format!( + "origin.passthrough on {on}.{fname}: @from \"{from}\" is not a scalar member of the @grain element." + ), + src, + ); + } + if m.own(origin, "via").is_some() { + push( + errs, + ERR_INVALID_ORIGIN, + format!( + "origin.passthrough on {on}.{fname}: @from \"{from}\" reads the @grain element, which takes no @via." + ), + src, + ); + } + if tf.sub_type == "enum" + && (tree.attr(t.field, "intValueMap").is_some() + || tree.attr(t.field, "stringValueMap").is_some()) + { + push( + errs, + ERR_INVALID_ORIGIN, + format!( + "origin.passthrough on {on}.{fname}: @from \"{from}\" is an enum with a value map, but a @grain element holds the member's symbol." + ), + src, + ); + } + return; + } + if let Some(t) = &target { + check_extends_origin(m, field, t.field, from, obj, src, errs); + check_passthrough_type(m, field, t.field, from, convert, obj, src, errs); + } + if let Some(via) = m.own_nonempty(origin, "via") { + if let Some(w) = validate_via_path(m, via, obj, fname, src, errs) { + check_passthrough_cardinality(m, &w.hops, obj, fname, src, errs, Some(&w)); + } + } else if let Some(t) = &target + && !is_value_host + && let Some(base) = derive_base(m, obj, fname, src, errs) + && !is_base_relation_target(m, t.entity, base, obj) + && let Some(hops) = infer_via_single_hop( + m, + base, + t.entity, + obj, + fname, + from, + "origin.passthrough.@from", + src, + errs, + ) + { + check_passthrough_cardinality(m, &hops, obj, fname, src, errs, None); + } +} + +#[allow(clippy::too_many_arguments)] +fn check_passthrough_type( + m: &M<'_>, + field: NodeId, + from_field: NodeId, + from: &str, + convert: bool, + obj: NodeId, + src: &ErrorSource, + errs: &mut Errs, +) { + if convert { + return; + } + let (declared, source) = (m.type_label(field), m.type_label(from_field)); + if declared == source { + return; + } + let tree = m.tree; + push( + errs, + ERR_PASSTHROUGH_TYPE_MISMATCH, + format!( + "origin.passthrough on {}.{}: field is {declared} but its @from source \"{from}\" is {source} — set @convert: true to acknowledge a deliberate type change.", + tree.node(obj).name, + tree.node(field).name + ), + &resolved_src( + src, + format!("{}::{}", tree.node(obj).fqn(), tree.node(field).name), + from, + ), + ); +} + +fn check_extends_origin( + m: &M<'_>, + field: NodeId, + from_field: NodeId, + from: &str, + obj: NodeId, + src: &ErrorSource, + errs: &mut Errs, +) { + let tree = m.tree; + let Some(sup) = tree.node(field).super_node else { + return; + }; + if tree.node(sup).type_name != T_FIELD { + return; + } + let Some(owner) = tree.node(sup).parent else { + return; + }; + if tree.node(owner).type_name != T_OBJECT { + return; + } + if m.super_chain_contains(sup, from_field) { + return; + } + push( + errs, + ERR_EXTENDS_ORIGIN_MISMATCH, + format!( + "origin.passthrough on {}.{}: @from \"{from}\" disagrees with the field's extends target \"{}.{}\" — extends (shape lineage) and origin.passthrough (data lineage) must point at the same entity field (FR-024).", + tree.node(obj).name, + tree.node(field).name, + tree.node(owner).name, + tree.node(sup).name + ), + &resolved_src( + src, + format!("{}::{}", tree.node(obj).fqn(), tree.node(field).name), + from, + ), + ); +} + +fn aggregate(m: &M<'_>, obj: NodeId, field: NodeId, origin: NodeId, errs: &mut Errs) { + let tree = m.tree; + let on = tree.node(obj).name.as_str(); + let fname = tree.node(field).name.as_str(); + let src = &tree.node(origin).source; + let agg = m.own(origin, "agg").and_then(Value::as_str); + let of = m.own_nonempty(origin, "of"); + let has_filter = m.own(origin, "filter").is_some(); + let has_distinct = m.own(origin, "distinct").is_some(); + let order_by = m.own(origin, "orderBy"); + let has_order_by = order_by.is_some(); + let is_predicate = matches!(agg, Some(AGG_ANY | AGG_ALL)); + let is_collect = agg == Some(AGG_COLLECT); + let agg_s = agg.unwrap_or("undefined"); + let is_array = tree.resolved_is_array(field); + let fsub = tree.node(field).sub_type.as_str(); + let bad = |errs: &mut Errs, msg: String| push(errs, ERR_INVALID_ORIGIN, msg, src); + + if is_collect && !is_array { + bad( + errs, + format!( + "origin.aggregate @agg:collect on {on}.{fname}: the carrying field must be isArray:true (collect produces a list)." + ), + ); + } else if !is_collect && is_array { + bad( + errs, + format!( + "origin.aggregate @agg:{agg_s} on {on}.{fname}: a non-collect aggregate reduces to a scalar — the field must be isArray:false." + ), + ); + } + if is_predicate && fsub != "boolean" { + bad( + errs, + format!( + "origin.aggregate @agg:{agg_s} on {on}.{fname}: a predicate quantifier yields a boolean — the field must be field.boolean." + ), + ); + } + if has_distinct && !is_collect { + bad( + errs, + format!("origin.aggregate on {on}.{fname}: @distinct is valid only on @agg:collect."), + ); + } + if has_order_by && !is_collect { + bad( + errs, + format!("origin.aggregate on {on}.{fname}: @orderBy is valid only on @agg:collect."), + ); + } + if is_collect && has_distinct && has_order_by { + bad( + errs, + format!( + "origin.aggregate @agg:collect on {on}.{fname}: @orderBy and @distinct are mutually exclusive." + ), + ); + } + + if is_predicate { + if !has_filter { + bad( + errs, + format!( + "origin.aggregate @agg:{agg_s} on {on}.{fname}: a predicate quantifier requires @filter." + ), + ); + } + if of.is_some() { + bad( + errs, + format!( + "origin.aggregate @agg:{agg_s} on {on}.{fname}: @of is forbidden — a quantifier ranges over rows, not a column." + ), + ); + } + match m.own_nonempty(origin, "via") { + None => bad( + errs, + format!( + "origin.aggregate @agg:{agg_s} on {on}.{fname}: requires an explicit @via." + ), + ), + Some(via) => { + if let Some(w) = validate_via_path(m, via, obj, fname, src, errs) { + check_aggregate_cardinality(m, &w.hops, obj, fname, src, errs, Some(&w)); + } + } + } + return; + } + + let Some(of) = of else { + if !is_collect { + bad( + errs, + format!("origin.aggregate on {on}.{fname}: missing @of."), + ); + return; + } + whole_object_collect(m, obj, field, origin, has_distinct, order_by, errs); + return; + }; + + let of_target = validate_from_path(m, of, obj, fname, src, errs, "origin.aggregate.@of"); + if let Some(t) = &of_target + && agg.is_some_and(|a| COLUMN_AGGS.contains(&a)) + && (tree.node(t.field).sub_type == "object" || tree.attr(t.field, "objectRef").is_some()) + { + push( + errs, + ERR_INVALID_ORIGIN, + format!( + "origin.aggregate @agg:{agg_s} on {on}.{fname}: @of \"{of}\" is a value-object field (field.{}), which has no single column to aggregate.", + tree.node(t.field).sub_type + ), + &resolved_src(src, format!("{}::{fname}", tree.node(obj).fqn()), of), + ); + } + if is_collect + && let Some(t) = &of_target + && fsub != tree.node(t.field).sub_type + { + bad( + errs, + format!( + "origin.aggregate @agg:collect on {on}.{fname}: field element type field.{fsub} does not match the @of column type field.{} — collect preserves the element type.", + tree.node(t.field).sub_type + ), + ); + } + if is_collect && has_order_by && !has_distinct { + order_by_keys( + m, + order_by, + of_target.as_ref().map(|t| t.entity), + obj, + fname, + "origin.aggregate @agg:collect", + src, + errs, + ERR_INVALID_ORIGIN, + ); + } + if let Some(via) = m.own_nonempty(origin, "via") { + if let Some(w) = validate_via_path(m, via, obj, fname, src, errs) { + check_aggregate_cardinality(m, &w.hops, obj, fname, src, errs, Some(&w)); + } + return; + } + let Some(t) = of_target else { return }; + let Some(base) = derive_base(m, obj, fname, src, errs) else { + return; + }; + if is_base_relation_target(m, t.entity, base, obj) { + bad( + errs, + format!( + "origin.aggregate on {on}.{fname}: missing @via (aggregates require a relationship path)." + ), + ); + return; + } + if let Some(hops) = infer_via_single_hop( + m, + base, + t.entity, + obj, + fname, + of, + "origin.aggregate.@of", + src, + errs, + ) { + check_aggregate_cardinality(m, &hops, obj, fname, src, errs, None); + } +} + +fn whole_object_collect( + m: &M<'_>, + obj: NodeId, + field: NodeId, + origin: NodeId, + has_distinct: bool, + order_by: Option<&Value>, + errs: &mut Errs, +) { + let tree = m.tree; + let on = tree.node(obj).name.as_str(); + let fname = tree.node(field).name.as_str(); + let src = &tree.node(origin).source; + let object_ref = m.attr_str(field, "objectRef").filter(|s| !s.is_empty()); + if tree.node(field).sub_type != "object" || object_ref.is_none() { + push( + errs, + ERR_COLLECT_WHOLE_OBJECT, + format!( + "origin.aggregate @agg:collect on {on}.{fname}: @of is omitted, so this is a whole-object rollup — the carrying field must be a field.object declaring @objectRef." + ), + src, + ); + return; + } + let object_ref = object_ref.unwrap_or(""); + let owner = tree.node(field).parent.unwrap_or(obj); + let ref_target = m.find_object(object_ref, m.pkg(owner)); + if let Some(rt) = ref_target + && tree.node(rt).sub_type != SUB_VALUE + { + push( + errs, + ERR_SUBTYPE_RULE_VIOLATION, + format!( + "origin.aggregate @agg:collect on {on}.{fname}: @objectRef '{object_ref}' resolves to object.{} — a whole-object rollup must target an object.value (#210, ADR-0028).", + tree.node(rt).sub_type + ), + src, + ); + return; + } + let Some(via) = m.own_nonempty(origin, "via") else { + push( + errs, + ERR_COLLECT_WHOLE_OBJECT, + format!( + "origin.aggregate @agg:collect on {on}.{fname}: @via is required on a whole-object rollup." + ), + src, + ); + return; + }; + if has_distinct { + push( + errs, + ERR_COLLECT_WHOLE_OBJECT, + format!( + "origin.aggregate @agg:collect on {on}.{fname}: @distinct is not supported on a whole-object rollup." + ), + src, + ); + return; + } + if let Some(w) = validate_via_path(m, via, obj, fname, src, errs) { + check_aggregate_cardinality(m, &w.hops, obj, fname, src, errs, Some(&w)); + order_by_keys( + m, + order_by, + Some(w.terminal), + obj, + fname, + "origin.aggregate @agg:collect", + src, + errs, + ERR_COLLECT_WHOLE_OBJECT, + ); + if let Some(rt) = ref_target { + let terminal_fields = m.fields(w.terminal); + for member in m.fields(rt) { + let mn = &tree.node(member).name; + let Some(&matched) = terminal_fields.iter().find(|&&f| tree.node(f).name == *mn) + else { + push( + errs, + ERR_COLLECT_MEMBER_UNRESOLVED, + format!( + "origin.aggregate @agg:collect on {on}.{fname}: value-object member '{mn}' has no matching field on '{}'.", + tree.node(w.terminal).name + ), + src, + ); + continue; + }; + let (a, b) = (m.type_label(member), m.type_label(matched)); + if a != b { + push( + errs, + ERR_COLLECT_WHOLE_OBJECT, + format!( + "origin.aggregate @agg:collect on {on}.{fname}: value-object member '{mn}' is {a} but '{}.{mn}' is {b}.", + tree.node(w.terminal).name + ), + src, + ); + } + } + } + } +} + +fn computed(m: &M<'_>, obj: NodeId, field: NodeId, origin: NodeId, errs: &mut Errs) { + let tree = m.tree; + let on = tree.node(obj).name.as_str(); + let fname = tree.node(field).name.as_str(); + let src = &tree.node(origin).source; + let Some(expr) = m.own(origin, "expr").filter(|v| v.is_object()) else { + return; + }; + let structural = validate_expr(expr); + if !structural.is_empty() { + for msg in structural { + push( + errs, + ERR_UNKNOWN_EXPR_NODE, + format!("origin.computed on {on}.{fname}: {msg}"), + src, + ); + } + return; + } + let Some(base) = derive_base(m, obj, fname, src, errs) else { + return; + }; + let field_node = |name: &str| -> Option { + if obj != base + && name != fname + && let Some(own) = m.find_field(obj, name) + { + return Some(own); + } + let base_field = m.find_field(base, name); + if base_field.is_some() || obj == base || !name.contains('.') { + return base_field; + } + match resolve_filter_path(m, base, name) { + Some(Ok(p)) => Some(p.field), + _ => None, + } + }; + let resolve = |name: &str| -> Option { + let node = field_node(name)?; + if node != field + && let Some(no) = m.origin_of(node) + && tree.node(no).sub_type == O_AGGREGATE + && m.own(no, "agg").and_then(Value::as_str) == Some(AGG_COLLECT) + { + return None; + } + Some(tree.node(node).sub_type.clone()) + }; + let is_int_enum = |name: &str| -> bool { + field_node(name).is_some_and(|n| { + tree.node(n).sub_type == "enum" && tree.attr(n, "intValueMap").is_some() + }) + }; + let inferred = infer_with(expr, &resolve, &is_int_enum); + if !inferred.errors.is_empty() { + for msg in inferred.errors { + push( + errs, + ERR_INVALID_ORIGIN, + format!("origin.computed on {on}.{fname}: {msg}"), + src, + ); + } + return; + } + let view = |name: &str| -> Option> { + let id = field_node(name)?; + let n = tree.node(id); + Some(FieldView { + name: &n.name, + sub: &n.sub_type, + members: if n.sub_type == "enum" { + tree.attr(id, "values").and_then(Value::as_array) + } else { + None + }, + }) + }; + if let Some(problem) = literal_comparison_problem(expr, &view) { + push( + errs, + ERR_INVALID_ORIGIN, + format!("origin.computed on {on}.{fname}: @expr {problem}"), + src, + ); + return; + } + if let Some(t) = &inferred.ty + && *t != tree.node(field).sub_type + { + push( + errs, + ERR_COMPUTED_TYPE_MISMATCH, + format!( + "origin.computed on {on}.{fname}: @expr infers field.{t} but the field is declared field.{} — a computed column's type is derived from its expression and must match (no @convert escape).", + tree.node(field).sub_type + ), + src, + ); + } +} + +fn first(m: &M<'_>, obj: NodeId, field: NodeId, origin: NodeId, errs: &mut Errs) { + let tree = m.tree; + let on = tree.node(obj).name.as_str(); + let fname = tree.node(field).name.as_str(); + let src = &tree.node(origin).source; + let Some(of) = m.own_nonempty(origin, "of") else { + push( + errs, + ERR_INVALID_ORIGIN, + format!("origin.first on {on}.{fname}: missing @of."), + src, + ); + return; + }; + if tree.attr(field, "required") == Some(&Value::Bool(true)) { + push( + errs, + ERR_INVALID_ORIGIN, + format!( + "origin.first on {on}.{fname}: the field must not be @required — an empty related set (after @filter) yields null." + ), + src, + ); + } + let of_target = validate_from_path(m, of, obj, fname, src, errs, "origin.first.@of"); + if let Some(t) = &of_target + && tree.node(field).sub_type != tree.node(t.field).sub_type + { + push( + errs, + ERR_INVALID_ORIGIN, + format!( + "origin.first on {on}.{fname}: field field.{} does not match the @of column field.{} — first projects the column unchanged, so the types must match.", + tree.node(field).sub_type, + tree.node(t.field).sub_type + ), + src, + ); + } + if let Some(via) = m.own_nonempty(origin, "via") { + if let Some(w) = validate_via_path(m, via, obj, fname, src, errs) { + check_aggregate_cardinality(m, &w.hops, obj, fname, src, errs, Some(&w)); + } + } else if let Some(t) = &of_target + && let Some(base) = derive_base(m, obj, fname, src, errs) + && !is_base_relation_target(m, t.entity, base, obj) + && let Some(hops) = infer_via_single_hop( + m, + base, + t.entity, + obj, + fname, + of, + "origin.first.@of", + src, + errs, + ) + { + check_aggregate_cardinality(m, &hops, obj, fname, src, errs, None); + } + order_by_keys( + m, + m.own(origin, "orderBy"), + of_target.as_ref().map(|t| t.entity), + obj, + fname, + "origin.first", + src, + errs, + ERR_INVALID_ORIGIN, + ); +} + +fn as_list(v: Option<&Value>) -> Vec<&Value> { + match v { + None => Vec::new(), + Some(Value::Array(a)) => a.iter().collect(), + Some(x) => vec![x], + } +} + +fn is_identifier(s: &str) -> bool { + let mut c = s.chars(); + c.next() + .is_some_and(|f| f.is_ascii_alphabetic() || f == '_') + && c.all(|x| x.is_ascii_alphanumeric() || x == '_') +} + +fn function_origin(m: &M<'_>, obj: NodeId, field: NodeId, origin: NodeId, errs: &mut Errs) { + let tree = m.tree; + let src = &tree.node(origin).source; + let fname = tree.node(field).name.as_str(); + let where_ = format!("origin.function on {}.{fname}", tree.node(obj).name); + let bad = |errs: &mut Errs, msg: String| push(errs, ERR_INVALID_ORIGIN, msg, src); + for attr in ["function", "schema"] { + if let Some(v) = m.own(origin, attr) + && !v.as_str().is_some_and(is_identifier) + { + bad( + errs, + format!( + "{where_}: @{attr} {v} is not a plain identifier ([A-Za-z_][A-Za-z0-9_]*); a function is named, never written as SQL." + ), + ); + } + } + let args = as_list(m.own(origin, "args")); + let params = as_list(m.own(origin, "params")); + let returns = m.own(origin, "returns"); + for t in params.iter().copied().chain(returns) { + if !t.as_str().is_some_and(|s| CAST_TARGETS.contains(&s)) { + bad( + errs, + format!( + "{where_}: {t} is not a parameter or return type; use one of {}.", + CAST_TARGETS.join(", ") + ), + ); + } + } + if let Some(r) = returns.and_then(Value::as_str) + && r != tree.node(field).sub_type + { + bad( + errs, + format!( + "{where_}: @returns {r}, but the field is field.{}; the declared return type must be the field's type.", + tree.node(field).sub_type + ), + ); + } + if params.len() != args.len() { + bad( + errs, + format!( + "{where_}: @params declares {} parameter type(s) for {} argument(s); declare one per @args entry.", + params.len(), + args.len() + ), + ); + } + let is_projection = tree.node(obj).sub_type == SUB_PROJECTION; + let base = if is_projection { + derive_base(m, obj, fname, src, &mut Vec::new()) + } else { + Some(obj) + }; + for (index, name) in args.iter().enumerate() { + let name_s = name.as_str(); + let own = name_s + .filter(|n| *n != fname) + .and_then(|n| m.find_field(obj, n)); + let own_origin = own.and_then(|o| m.origin_of(o)); + let arg = own.or_else(|| name_s.zip(base).and_then(|(n, b)| m.find_field(b, n))); + let shown = name_s.map_or_else(|| name.to_string(), str::to_string); + match arg { + None => bad( + errs, + format!( + "{where_}: @args names \"{shown}\", which is not a field of the projection or its base entity." + ), + ), + Some(_) if name_s == Some(fname) => bad( + errs, + format!( + "{where_}: @args names \"{shown}\", which is not a field of the projection or its base entity." + ), + ), + Some(_) if own_origin.is_some_and(|o| tree.node(o).sub_type == O_AGGREGATE) => bad( + errs, + format!( + "{where_}: @args names \"{shown}\", an origin.aggregate; a function takes values of the row, not of the group." + ), + ), + Some(a) + if { + let s = tree.node(a).sub_type.as_str(); + s == "object" || s == "map" || tree.resolved_is_array(a) + } => + { + bad( + errs, + format!( + "{where_}: @args names \"{shown}\", a field.{}; a function argument is a scalar.", + tree.node(a).sub_type + ), + ) + } + Some(a) => { + if let Some(p) = params.get(index).and_then(|p| p.as_str()) + && tree.node(a).sub_type != p + { + bad( + errs, + format!( + "{where_}: argument {} \"{shown}\" is a field.{}, but parameter {} is declared {p}.", + index + 1, + tree.node(a).sub_type, + index + 1 + ), + ); + } + } + } + } +} + +// --------------------------------------------------------------------------- +// validateDerivedFieldProvidability +// --------------------------------------------------------------------------- + +fn effective_projection_filter(m: &M<'_>, proj: NodeId) -> Option { + let mut levels: Vec = Vec::new(); + let mut cur = Some(proj); + let mut seen = HashSet::new(); + while let Some(n) = cur { + if !seen.insert(n) { + break; + } + // ADR-0039: own: each level contributes the @filter declared on it. + if let Some(v) = m.own(n, "filter") { + levels.insert(0, v.clone()); + } + cur = m.tree.node(n).super_node; + } + match levels.len() { + 0 => None, + 1 => levels.pop(), + _ => { + let members: Vec = levels + .into_iter() + .flat_map(|f| { + if let Value::Object(o) = &f + && o.len() == 1 + && let Some(Value::Array(a)) = o.get(FILTER_AND) + { + return a.clone(); + } + vec![f] + }) + .collect(); + Some(serde_json::json!({ FILTER_AND: members })) + } + } +} + +fn filter_keys<'v>(filter: &'v Value, out: &mut Vec<&'v str>) { + let Value::Object(o) = filter else { return }; + for (k, v) in o { + if k == FILTER_AND || k == FILTER_OR { + if let Value::Array(a) = v { + for s in a { + filter_keys(s, out); + } + } + } else { + out.push(k); + } + } +} + +fn expression_field_refs(expr: Option<&Value>) -> Vec<&str> { + let Some(expr) = expr else { return Vec::new() }; + let mut nodes = Vec::new(); + expression_nodes(expr, &mut nodes); + nodes + .into_iter() + .filter_map(|n| n.get("field").and_then(Value::as_str)) + .collect() +} + +fn reach_function_args(m: &M<'_>, f: NodeId, reached: &mut HashSet) { + let Some(origin) = m + .origin_of(f) + .filter(|&o| m.tree.node(o).sub_type == O_FUNCTION) + else { + return; + }; + let Some(host) = m.tree.node(f).parent else { + return; + }; + for a in as_list(m.own(origin, "args")) { + if let Some(n) = a.as_str() + && let Some(arg) = m.find_field(host, n) + && reached.insert(arg) + { + reach_function_args(m, arg, reached); + } + } +} + +fn projection_reached_entity_fields(m: &M<'_>) -> HashSet { + let tree = m.tree; + let mut reached = HashSet::new(); + for &obj in m.index.objects() { + if tree.node(obj).sub_type != SUB_PROJECTION { + continue; + } + let mut silent = Vec::new(); + let base = derive_base(m, obj, "@filter", &tree.node(obj).source, &mut silent); + let filter = effective_projection_filter(m, obj); + if let Some(base) = base.filter(|&b| b != obj) + && let Some(filter) = &filter + { + let mut keys = Vec::new(); + filter_keys(filter, &mut keys); + for key in keys { + match resolve_filter_path(m, base, key) { + Some(Ok(p)) => { + reached.insert(p.field); + } + None => { + if let Some(f) = m.find_field(base, key) { + reached.insert(f); + } + } + Some(Err(_)) => {} + } + } + } + for field in m.fields(obj) { + for origin in m.origins_of(field) { + match tree.node(origin).sub_type.as_str() { + O_PASSTHROUGH => { + if let Some(from) = m.own(origin, "from").and_then(Value::as_str) + && let Some(t) = validate_from_path( + m, + from, + obj, + &tree.node(field).name, + &tree.node(origin).source, + &mut silent, + "origin.passthrough.@from", + ) + { + reached.insert(t.field); + } + } + O_COMPUTED => { + let Some(base) = base.filter(|&b| b != obj) else { + continue; + }; + for name in expression_field_refs(m.own(origin, "expr")) { + if name.contains('.') + && let Some(Ok(p)) = resolve_filter_path(m, base, name) + { + reached.insert(p.field); + } + } + } + _ => {} + } + } + } + } + let snapshot: Vec = reached.iter().copied().collect(); + for f in snapshot { + reach_function_args(m, f, &mut reached); + } + reached +} + +pub fn validate_derived_field_providability(ctx: &Ctx<'_>, out: &mut Findings) { + let m = M::new(ctx); + let tree = m.tree; + let mut reached: Option> = None; + for &obj in m.index.objects() { + if tree.node(obj).sub_type != SUB_ENTITY { + continue; + } + let has_read = m.kids(obj).iter().any(|&c| { + tree.node(c).type_name == T_SOURCE + && READ_ONLY_KINDS.contains(&m.attr_str(c, "kind").unwrap_or("table")) + }); + if has_read { + continue; + } + for field in m.own_fields(obj) { + let Some(origin) = m.origin_of(field) else { + continue; + }; + let sub = tree.node(origin).sub_type.as_str(); + if matches!(sub, O_FIRST | O_COMPUTED | O_FUNCTION) + && reached + .get_or_insert_with(|| projection_reached_entity_fields(&m)) + .contains(&field) + { + continue; + } + out.errors.push(MetaError::at( + ERR_DERIVED_FIELD_NO_READ_SOURCE, + format!( + "derived field \"{}.{}\" carries an origin.* but entity \"{}\" declares no read-capable source — derived fields do not exist on the writable table.", + tree.node(obj).name, + tree.node(field).name, + tree.node(obj).name + ), + tree.node(field).source.clone(), + )); + } + } +} + +// --------------------------------------------------------------------------- +// validateOriginSegmentsAndCorrelation +// --------------------------------------------------------------------------- + +fn origin_related_entity(m: &M<'_>, origin: NodeId, obj: NodeId) -> Option { + let tree = m.tree; + if let Some(of) = m.own_nonempty(origin, "of") { + let pname = tree + .node(origin) + .parent + .map_or("", |p| tree.node(p).name.as_str()); + return validate_from_path( + m, + of, + obj, + pname, + &tree.node(origin).source, + &mut Vec::new(), + "", + ) + .map(|t| t.entity); + } + let via = m.own(origin, "via")?.as_str()?; + let mut parts = via.split('.'); + let mut cur = m.find_object(parts.next()?, m.pkg(obj)); + for hop in parts { + let c = cur?; + let rel = m.kids(c).iter().copied().find(|&k| { + let n = tree.node(k); + (n.type_name == T_RELATIONSHIP || n.type_name == T_IDENTITY) && n.name == hop + }); + cur = match rel { + None => m.reverse_hops(c, hop).first().map(|h| h.0), + Some(r) => m.ref_target( + r, + if tree.node(r).type_name == T_RELATIONSHIP { + "objectRef" + } else { + "references" + }, + ), + }; + } + cur +} + +fn check_correlated( + m: &M<'_>, + filter: &Value, + base: NodeId, + where_: &str, + src: &ErrorSource, + errs: &mut Errs, + on_projection: bool, +) { + let Value::Object(f) = filter else { return }; + for (key, clause) in f { + if key == FILTER_AND || key == FILTER_OR { + if let Value::Array(a) = clause { + for s in a { + check_correlated(m, s, base, where_, src, errs, on_projection); + } + } + continue; + } + let Value::Object(ops) = clause else { continue }; + for (op, value) in ops { + let operand = value.as_object().filter(|o| o.contains_key("field")); + let null_safe = NULL_SAFE_OPS.contains(&op.as_str()); + let Some(operand) = operand else { + if null_safe { + push( + errs, + ERR_BAD_ATTR_FILTER, + format!( + "{where_}: @filter on \"{key}\" uses \"{op}\", which compares with a base-row field: write {{ {op}: {{ field: \"\" }} }}." + ), + src, + ); + } + continue; + }; + let name = operand.get("field").and_then(Value::as_str); + if !CORRELATED_OPS.contains(&op.as_str()) { + push( + errs, + ERR_BAD_ATTR_FILTER, + format!( + "{where_}: @filter on \"{key}\" compares with a base-row field using \"{op}\"; a correlated operand takes {}.", + CORRELATED_OPS.join(", ") + ), + src, + ); + } else if name.is_none_or(|n| m.find_field(base, n).is_none()) { + let path = name + .filter(|n| n.contains('.') && on_projection) + .and_then(|n| resolve_filter_path(m, base, n)); + if let Some(Ok(_)) = path { + continue; + } + let shown = name.unwrap_or("undefined"); + let msg = match path { + Some(Err(why)) => format!( + "{where_}: @filter on \"{key}\" compares with the base-row path \"{shown}\": {why}." + ), + _ if name.is_some_and(|n| n.contains('.')) && !on_projection => format!( + "{where_}: @filter on \"{key}\" compares with the path \"{shown}\"; a path operand is legal only on a projection." + ), + _ => format!( + "{where_}: @filter on \"{key}\" names base-row field \"{shown}\", which \"{}\" does not declare.", + m.tree.node(base).name + ), + }; + push(errs, ERR_BAD_ATTR_FILTER, msg, src); + } + } + } +} + +pub fn validate_origin_segments_and_correlation(ctx: &Ctx<'_>, out: &mut Findings) { + let m = M::new(ctx); + let tree = m.tree; + let mut errs = Vec::new(); + for &obj in m.index.objects() { + let sub = tree.node(obj).sub_type.as_str(); + if sub != SUB_PROJECTION && sub != SUB_ENTITY { + continue; + } + for field in m.own_fields(obj) { + for origin in m.origins_of(field) { + let osub = tree.node(origin).sub_type.as_str(); + if osub != O_FIRST && osub != O_AGGREGATE { + continue; + } + let src = &tree.node(origin).source; + let where_ = format!( + "origin.{osub} on {}.{}", + tree.node(obj).name, + tree.node(field).name + ); + if let Some(seg) = m.own(origin, "segment").and_then(Value::as_str) + && let Some(related) = origin_related_entity(&m, origin, obj) + && m.find_child(related, T_SEGMENT, seg).is_none() + { + push( + &mut errs, + ERR_INVALID_ORIGIN, + format!( + "{where_}: @segment \"{seg}\" is not a segment declared on \"{}\", the entity whose rows it scopes.", + tree.node(related).name + ), + src, + ); + } + let Some(filter) = m.own(origin, "filter") else { + continue; + }; + let Some(base) = derive_base(&m, obj, &tree.node(field).name, src, &mut Vec::new()) + else { + continue; + }; + check_correlated( + &m, + filter, + base, + &where_, + src, + &mut errs, + sub == SUB_PROJECTION, + ); + } + } + } + out.errors.extend(errs); +} + +// --------------------------------------------------------------------------- +// validateDerivedCycles +// --------------------------------------------------------------------------- + +pub fn validate_derived_cycles(ctx: &Ctx<'_>, out: &mut Findings) { + let m = M::new(ctx); + let tree = m.tree; + for &obj in m.index.objects() { + let fields = m.fields(obj); + // Cheap exit: a cycle needs a function or computed origin. + if !fields.iter().any(|&f| { + m.origin_of(f) + .is_some_and(|o| matches!(tree.node(o).sub_type.as_str(), O_FUNCTION | O_COMPUTED)) + }) { + continue; + } + let by_name: HashMap<&str, NodeId> = fields + .iter() + .map(|&f| (tree.node(f).name.as_str(), f)) + .collect(); + let is_projection = tree.node(obj).sub_type == SUB_PROJECTION; + let deps = |f: NodeId| -> Vec { + let Some(origin) = m.origin_of(f) else { + return Vec::new(); + }; + let mut names: Vec<&str> = Vec::new(); + let mut self_allowed = false; + match tree.node(origin).sub_type.as_str() { + O_FUNCTION => { + for n in as_list(m.own(origin, "args")) { + if let Some(s) = n.as_str() { + names.push(s); + } + } + } + O_COMPUTED => { + self_allowed = !is_projection; + for n in expression_field_refs(m.own(origin, "expr")) { + names.push(n.split('.').next().unwrap_or(n)); + } + } + _ => {} + } + names + .into_iter() + .filter_map(|n| by_name.get(n).copied()) + .filter(|&d| (self_allowed || d != f) && m.origin_of(d).is_some()) + .collect() + }; + let mut done: HashSet = HashSet::new(); + let mut reported: HashSet = HashSet::new(); + #[allow(clippy::too_many_arguments)] + fn visit( + m: &M<'_>, + obj: NodeId, + f: NodeId, + path: &mut Vec, + deps: &dyn Fn(NodeId) -> Vec, + done: &mut HashSet, + reported: &mut HashSet, + out: &mut Findings, + ) { + let tree = m.tree; + if let Some(at) = path.iter().position(|&p| p == f) { + let mut cycle: Vec<&str> = path[at..] + .iter() + .map(|&x| tree.node(x).name.as_str()) + .collect(); + let mut key_parts = cycle.clone(); + key_parts.sort(); + cycle.push(tree.node(f).name.as_str()); + if reported.insert(key_parts.join(",")) { + let src = m.origin_of(f).map_or_else( + || tree.node(f).source.clone(), + |o| tree.node(o).source.clone(), + ); + out.errors.push(MetaError::at( + ERR_INVALID_ORIGIN, + format!( + "{}.{}: a derived field depends on itself through {}; a view inlines each dependency on the same row, so the cycle has no SQL. Break it.", + tree.node(obj).name, + tree.node(f).name, + cycle.join(" → ") + ), + src, + )); + } + return; + } + if done.contains(&f) { + return; + } + path.push(f); + for d in deps(f) { + visit(m, obj, d, path, deps, done, reported, out); + } + path.pop(); + done.insert(f); + } + for &f in &fields { + if m.origin_of(f).is_some() { + visit( + &m, + obj, + f, + &mut Vec::new(), + &deps, + &mut done, + &mut reported, + out, + ); + } + } + } +} + +// --------------------------------------------------------------------------- +// validateProjectionFilter +// --------------------------------------------------------------------------- + +struct FilterField { + derived: bool, + ops: &'static [&'static str], + reported: bool, +} + +// --------------------------------------------------------------------------- +// validateExtenderSubtypeScope (warning only) +// --------------------------------------------------------------------------- + +const ATTR_DISCRIMINATOR_NAME: &str = "discriminator"; + +/// The discriminator field of the TPH level `obj` belongs to (its own, or an ancestor's). +fn tph_discriminator_of<'a>(m: &M<'a>, obj: NodeId) -> Option<&'a str> { + let mut cur = Some(obj); + let mut n = 0; + while let Some(c) = cur { + if m.tree.node(c).type_name != T_OBJECT || n > m.tree.len() { + return None; + } + // ADR-0039: own: the level that declares the discriminator. + if let Some(d) = m.own(c, ATTR_DISCRIMINATOR_NAME).and_then(Value::as_str) { + return Some(d); + } + n += 1; + cur = m.tree.node(c).super_node; + } + None +} + +/// Whether `obj` extends `ancestor`, directly or through levels (never itself). +fn is_descendant_of(m: &M<'_>, obj: NodeId, ancestor: NodeId) -> bool { + m.tree + .node(obj) + .super_node + .is_some_and(|s| m.super_chain_contains(s, ancestor)) +} + +/// rc.21 part B (I2): warn when an extender's view widened with the identity-anchor rule: a +/// projection with no identity of its own whose super anchors a TPH base by identity, that binds a +/// field to a column only a subtype carries, and scopes no row by the discriminator. +pub fn validate_extender_subtype_scope(ctx: &Ctx<'_>, out: &mut Findings) { + let m = M::new(ctx); + let tree = m.tree; + for &obj in m.index.objects() { + let o = tree.node(obj); + // An abstract extender emits no view, so nothing it declares widened one. + if o.sub_type != SUB_PROJECTION || o.is_abstract { + continue; + } + // ADR-0039: own: the anchor rule applies to an extender that declares no identity of its own. + if tree + .own_children(obj) + .iter() + .any(|&c| tree.node(c).type_name == T_IDENTITY) + { + continue; + } + let Some(sup) = o.super_node else { continue }; + if !m.is(sup, T_OBJECT, SUB_PROJECTION) || !anchors_by_identity(&m, sup, 0) { + continue; + } + let Some(base) = derive_base(&m, obj, "@extends", &o.source, &mut Vec::new()) else { + continue; + }; + let Some(discriminator) = tph_discriminator_of(&m, base) else { + continue; + }; + if let Some(filter) = effective_projection_filter(&m, obj) { + let mut keys = Vec::new(); + filter_keys(&filter, &mut keys); + if keys.contains(&discriminator) { + continue; + } + } + let pkg = m.pkg(obj); + let mut subtype_fields: Vec = Vec::new(); + let mut subtype: Option = None; + // ADR-0039: own: only the extender's OWN fields chose its base before rc.21. + for f in m.own_fields(obj) { + let Some(owner) = ref_named_owner(&m, f, pkg) else { + continue; + }; + if owner == base || !is_descendant_of(&m, owner, base) { + continue; + } + let fnode = tree.node(f); + let tail = fnode + .super_ref + .as_deref() + .and_then(|r| r.rsplit('.').next()) + .unwrap_or(&fnode.name); + subtype_fields.push(format!( + "\"{}\" ({}.{tail})", + fnode.name, + tree.node(owner).name + )); + subtype.get_or_insert(owner); + } + if let Some(sub) = subtype { + let base_name = &tree.node(base).name; + out.warnings.push(MetaError::at( + WARN_LEGACY, + format!( + "object.projection {}: {} read columns only a subtype carries, over the TPH base {base_name} with no @filter on its discriminator \"{discriminator}\", so the view returns every {base_name} row (rc.21: an extender keeps its super's identity anchor; before, its base was the subtype). To keep a subtype-scoped view, add @filter {{ {discriminator}: }} or declare identity.primary {{ extends: {}.primary }}.", + o.name, + subtype_fields.join(", "), + tree.node(sub).name + ), + ErrorSource::Code, + )); + } + } +} + +fn entity_field_aggregates(m: &M<'_>, f: NodeId) -> bool { + m.origin_of(f) + .is_some_and(|o| m.tree.node(o).sub_type == O_AGGREGATE) +} + +fn computed_reads_aggregate(m: &M<'_>, f: NodeId, obj: NodeId, seen: &mut HashSet) -> bool { + if !seen.insert(f) { + return false; + } + let Some(origin) = m + .origin_of(f) + .filter(|&o| m.tree.node(o).sub_type == O_COMPUTED) + else { + return false; + }; + let fname = &m.tree.node(f).name; + for name in expression_field_refs(m.own(origin, "expr")) { + if name == fname { + continue; + } + let Some(other) = m.find_field(obj, name) else { + continue; + }; + if entity_field_aggregates(m, other) || computed_reads_aggregate(m, other, obj, seen) { + return true; + } + } + false +} + +pub fn validate_projection_filter(ctx: &Ctx<'_>, out: &mut Findings) { + let m = M::new(ctx); + let tree = m.tree; + for &obj in m.index.objects() { + if tree.node(obj).sub_type != SUB_PROJECTION { + continue; + } + let Some(filter) = effective_projection_filter(&m, obj) else { + continue; + }; + let Value::Object(fobj) = &filter else { + continue; + }; + let src = &tree.node(obj).source; + let mut fields: HashMap = HashMap::new(); + for f in m.fields(obj) { + let derived = m.origin_of(f).is_some_and(|o| { + let s = tree.node(o).sub_type.as_str(); + s != O_PASSTHROUGH + && (s != O_COMPUTED + || computed_reads_aggregate(&m, f, obj, &mut HashSet::new())) + }); + fields.insert( + tree.node(f).name.clone(), + FilterField { + derived, + ops: ops_for_field(m.tree, f), + reported: false, + }, + ); + } + let pname = tree.node(obj).name.as_str(); + let base = derive_base(&m, obj, "@filter", src, &mut Vec::new()); + if let Some(base) = base.filter(|&b| b != obj) { + for f in m.fields(base) { + fields + .entry(tree.node(f).name.clone()) + .or_insert_with(|| FilterField { + derived: entity_field_aggregates(&m, f), + ops: ops_for_field(m.tree, f), + reported: false, + }); + } + let mut keys = Vec::new(); + filter_keys(&filter, &mut keys); + for key in keys { + if fields.contains_key(key) { + continue; + } + match resolve_filter_path(&m, base, key) { + None => {} + Some(Err(why)) => { + push( + &mut out.errors, + ERR_BAD_ATTR_FILTER, + format!( + "projection \"{pname}\" @filter path \"{key}\" does not resolve: {why}." + ), + src, + ); + fields.insert( + key.to_string(), + FilterField { + derived: false, + ops: &[], + reported: true, + }, + ); + } + Some(Ok(p)) => { + fields.insert( + key.to_string(), + FilterField { + derived: entity_field_aggregates(&m, p.field), + ops: ops_for_field(m.tree, p.field), + reported: false, + }, + ); + } + } + } + } + check_filter_refs(fobj, &fields, pname, src, &mut out.errors); + } +} + +fn check_filter_refs( + filter: &serde_json::Map, + fields: &HashMap, + pname: &str, + src: &ErrorSource, + errs: &mut Errs, +) { + let mut err = |msg: String| push(errs, ERR_BAD_ATTR_FILTER, msg, src); + check_filter_inner(filter, fields, pname, &mut err); +} + +fn check_filter_inner( + filter: &serde_json::Map, + fields: &HashMap, + pname: &str, + err: &mut dyn FnMut(String), +) { + for (key, clause) in filter { + if key == FILTER_AND || key == FILTER_OR { + let Value::Array(a) = clause else { + err(format!( + "projection \"{pname}\" @filter \"{key}\" must be an array of sub-clauses." + )); + continue; + }; + for sub in a { + match sub { + Value::Object(o) => check_filter_inner(o, fields, pname, err), + _ => err(format!( + "projection \"{pname}\" @filter \"{key}\" contains a non-object sub-clause." + )), + } + } + continue; + } + let field = fields.get(key.as_str()); + if field.is_some_and(|f| f.reported) { + continue; + } + let Some(field) = field else { + err(format!( + "projection \"{pname}\" @filter references \"{key}\", which is not a declared field of the projection or of its base entity." + )); + continue; + }; + if field.derived { + err(format!( + "projection \"{pname}\" @filter references \"{key}\", an aggregate-derived field. A view-level WHERE runs before aggregation." + )); + continue; + } + let Value::Object(ops) = clause else { + err(format!( + "projection \"{pname}\" @filter on \"{key}\" must be an {{ op: value }} object." + )); + continue; + }; + if ops.is_empty() { + err(format!( + "projection \"{pname}\" @filter on \"{key}\" declares no operator." + )); + continue; + } + for op in ops.keys() { + if !field.ops.contains(&op.as_str()) { + err(format!( + "projection \"{pname}\" @filter on \"{key}\" uses op \"{op}\", which is not allowed for its type. Allowed ops: {}.", + field.ops.join(", ") + )); + } + } + } +} + +// --------------------------------------------------------------------------- +// validateProjectionUnionAndGrain +// --------------------------------------------------------------------------- + +pub fn validate_projection_union_and_grain(ctx: &Ctx<'_>, out: &mut Findings) { + let m = M::new(ctx); + let tree = m.tree; + for &obj in m.index.objects() { + if tree.node(obj).sub_type != SUB_PROJECTION { + continue; + } + let src = &tree.node(obj).source; + let pname = tree.node(obj).name.clone(); + let mut bad = |msg: String| { + push( + &mut out.errors, + ERR_BAD_ATTR_VALUE, + format!("object.projection {pname}: {msg}"), + src, + ); + }; + let union = m.own(obj, "union"); + if m.own(obj, "unionAll").is_some() && union.is_none() { + bad("@unionAll needs @union.".to_string()); + } + if let Some(union) = union { + let mine: Vec = m.fields(obj).iter().map(|&f| describe(&m, f)).collect(); + for name in as_list(Some(union)) { + let member = name + .as_str() + .and_then(|n| m.find_object(n, m.pkg(obj))) + .filter(|&x| tree.node(x).sub_type == SUB_PROJECTION); + let Some(member) = member else { + bad(format!( + "@union names \"{}\", which is not an object.projection.", + name.as_str() + .map_or_else(|| name.to_string(), str::to_string) + )); + continue; + }; + if member == obj { + bad("@union names the projection itself.".to_string()); + continue; + } + if m.own(member, "union").is_some() { + bad(format!( + "@union member \"{}\" declares its own @union; name its members here instead.", + tree.node(member).name + )); + } + let theirs: Vec = + m.fields(member).iter().map(|&f| describe(&m, f)).collect(); + if mine != theirs { + bad(format!( + "@union member \"{}\" has a different shape: ({}) where this view is ({}). A union's members have the same fields, in order.", + tree.node(member).name, + theirs.join(", "), + mine.join(", ") + )); + } + } + } + let grain = m.own(obj, "grain"); + let ordinal = m.own(obj, "grainOrdinal"); + if ordinal.is_some() && grain.is_none() { + bad("@grainOrdinal needs @grain.".to_string()); + } + if let Some(Value::String(grain)) = grain { + let base = derive_base(&m, obj, "@grain", src, &mut Vec::new()); + let field = base.and_then(|b| m.find_field(b, grain)); + let ok = field.is_some_and(|f| { + tree.node(f).sub_type == "object" + && tree.resolved_is_array(f) + && tree + .attr(f, "storage") + .is_none_or(|s| s.as_str() == Some("jsonb")) + && m.ref_target(f, "objectRef").is_some() + }); + if !ok { + bad(format!( + "@grain \"{grain}\" must name a field.object array (isArray, jsonb storage, with @objectRef) of the base entity{}.", + base.map_or(String::new(), |b| format!(" \"{}\"", tree.node(b).name)) + )); + } + for f in m.fields(obj) { + if m.origins_of(f) + .iter() + .any(|&o| tree.node(o).sub_type == O_AGGREGATE) + { + bad(format!( + "\"{}\" is an origin.aggregate; a @grain view has one row per element and groups nothing.", + tree.node(f).name + )); + } + } + if let Some(ord) = ordinal { + let f = ord.as_str().and_then(|n| m.find_field(obj, n)); + let fine = f.is_some_and(|f| { + matches!(tree.node(f).sub_type.as_str(), "int" | "long") + && m.origin_of(f).is_none() + && tree.node(f).super_ref.is_none() + }); + if !fine { + bad(format!( + "@grainOrdinal \"{}\" must name a field.int or field.long of the projection, with no origin and no extends.", + ord.as_str().map_or_else(|| ord.to_string(), str::to_string) + )); + } + } + } + } +} + +fn describe(m: &M<'_>, f: NodeId) -> String { + let tree = m.tree; + let n = tree.node(f); + let arr = if tree.resolved_is_array(f) { "[]" } else { "" }; + let col = m + .attr_str(f, "column") + .map_or(String::new(), |c| format!(" @column {c}")); + let shape = if n.sub_type == "enum" { + let get = |k: &str| tree.attr(f, k).cloned().unwrap_or(Value::Null); + format!( + " {}", + Value::Array(vec![ + get("values"), + get("intValueMap"), + get("stringValueMap") + ]) + ) + } else { + String::new() + }; + format!("{}: field.{}{arr}{col}{shape}", n.name, n.sub_type) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_code_is_in_the_shared_catalogue() { + let raw = include_str!("../../../../../fixtures/conformance/ERROR-CODES.json"); + let doc: Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for code in [ + ERR_INVALID_ORIGIN, + ERR_SUBTYPE_RULE_VIOLATION, + ERR_EXTENDS_ORIGIN_MISMATCH, + ERR_PASSTHROUGH_TYPE_MISMATCH, + ERR_AMBIGUOUS_PATH, + ERR_ORIGIN_CARDINALITY, + ERR_COLLECT_MEMBER_UNRESOLVED, + ERR_COLLECT_WHOLE_OBJECT, + ERR_UNKNOWN_EXPR_NODE, + ERR_COMPUTED_TYPE_MISMATCH, + ERR_DERIVED_FIELD_NO_READ_SOURCE, + ERR_BAD_ATTR_FILTER, + ERR_BAD_ATTR_VALUE, + ] { + assert!( + codes.contains_key(code), + "{code} is not in ERROR-CODES.json" + ); + } + } + + #[test] + fn identifiers_are_plain() { + assert!(is_identifier("fn_1")); + assert!(!is_identifier("1fn")); + assert!(!is_identifier("a b")); + } +} diff --git a/server/rust/metaobjects/src/validate/persistence.rs b/server/rust/metaobjects/src/validate/persistence.rs new file mode 100644 index 0000000000..9010623d28 --- /dev/null +++ b/server/rust/metaobjects/src/validate/persistence.rs @@ -0,0 +1,841 @@ +//! Source, persistence, grid and index validation passes (the TypeScript +//! `validateSource*`, `validateColumnNameCollisions`, `validateIndexLookupFields`, +//! `validateDataGrid*`, `validateFilterableHas*` and `validateSortableHas*`). +//! +//! ADR-0039: effective (resolving) reads are the default. The `own_*` reads below +//! each carry a comment naming the sanctioned case (declaration-layer checks). + +use std::collections::{HashMap, HashSet}; + +use serde_json::{Map, Value}; + +use super::util::{error_at, ops_for_field, ops_for_subtype}; +use super::{Ctx, Findings}; +use crate::errors::{MetaError, WARN_LEGACY}; +use crate::json::js_display; +use crate::naming::{resolve_column_name, resolve_flattened_column_name}; +use crate::node::{NodeId, Tree}; + +pub const ERR_SOURCE_NO_PRIMARY: &str = "ERR_SOURCE_NO_PRIMARY"; +pub const ERR_SOURCE_MULTIPLE_PRIMARY: &str = "ERR_SOURCE_MULTIPLE_PRIMARY"; +pub const ERR_ENTITY_PRIMARY_SOURCE_READONLY: &str = "ERR_ENTITY_PRIMARY_SOURCE_READONLY"; +pub const ERR_SQL_BODY_WITH_UNMANAGED: &str = "ERR_SQL_BODY_WITH_UNMANAGED"; +pub const ERR_SQL_BODY_ON_WRITABLE_KIND: &str = "ERR_SQL_BODY_ON_WRITABLE_KIND"; +pub const ERR_ORIGIN_UNDER_SQL_BODY: &str = "ERR_ORIGIN_UNDER_SQL_BODY"; +pub const WARN_ORIGIN_UNDER_UNMANAGED: &str = "WARN_ORIGIN_UNDER_UNMANAGED"; +pub const ERR_BAD_ATTR_VALUE: &str = "ERR_BAD_ATTR_VALUE"; +pub const ERR_PHYSICAL_NAME_MULTIPLE: &str = "ERR_PHYSICAL_NAME_MULTIPLE"; +pub const ERR_PHYSICAL_NAME_KIND_MISMATCH: &str = "ERR_PHYSICAL_NAME_KIND_MISMATCH"; +pub const WARN_LEGACY_PHYSICAL_NAME_ALIAS: &str = "WARN_LEGACY_PHYSICAL_NAME_ALIAS"; +pub const ERR_PARAMETER_REF_UNRESOLVED: &str = "ERR_PARAMETER_REF_UNRESOLVED"; +pub const ERR_PARAMETER_REF_NOT_VALUE_OBJECT: &str = "ERR_PARAMETER_REF_NOT_VALUE_OBJECT"; +pub const ERR_PARAMETER_REF_ON_NON_CALLABLE_KIND: &str = "ERR_PARAMETER_REF_ON_NON_CALLABLE_KIND"; +pub const ERR_COLUMN_NAME_COLLISION: &str = "ERR_COLUMN_NAME_COLLISION"; +pub const ERR_INVALID_INDEX: &str = "ERR_INVALID_INDEX"; +pub const ERR_BAD_DEFAULT_SORT_FIELD: &str = "ERR_BAD_DEFAULT_SORT_FIELD"; +pub const ERR_BAD_ATTR_FILTER: &str = "ERR_BAD_ATTR_FILTER"; +pub const ERR_FILTERABLE_UNSUPPORTED_SUBTYPE: &str = "ERR_FILTERABLE_UNSUPPORTED_SUBTYPE"; +pub const ERR_SORTABLE_UNSUPPORTED_SUBTYPE: &str = "ERR_SORTABLE_UNSUPPORTED_SUBTYPE"; + +const TYPE_OBJECT: &str = "object"; +const TYPE_FIELD: &str = "field"; +const TYPE_SOURCE: &str = "source"; +const TYPE_IDENTITY: &str = "identity"; +const TYPE_INDEX: &str = "index"; +const TYPE_LAYOUT: &str = "layout"; +const TYPE_ORIGIN: &str = "origin"; +const OBJECT_ENTITY: &str = "entity"; +const OBJECT_VALUE: &str = "value"; +const OBJECT_PROJECTION: &str = "projection"; +const SOURCE_RDB: &str = "rdb"; +const LAYOUT_DATA_GRID: &str = "dataGrid"; +const IDENTITY_SECONDARY: &str = "secondary"; +const INDEX_LOOKUP: &str = "lookup"; +const FIELD_OBJECT: &str = "object"; +const STORAGE_FLATTENED: &str = "flattened"; + +const ATTR_ROLE: &str = "role"; +const ATTR_KIND: &str = "kind"; +const ATTR_SQL: &str = "sql"; +const ATTR_UNMANAGED: &str = "unmanaged"; +const ATTR_PARAMETER_REF: &str = "parameterRef"; +const ATTR_FILTER: &str = "filter"; +const ATTR_FILTERABLE: &str = "filterable"; +const ATTR_SORTABLE: &str = "sortable"; +const ATTR_DB_INDEXED: &str = "db.indexed"; +const ATTR_COLUMN: &str = "column"; +const ATTR_STORAGE: &str = "storage"; +const ATTR_OBJECT_REF: &str = "objectRef"; +const ATTR_FIELDS: &str = "fields"; +const ATTR_EXPR: &str = "expr"; +const ATTR_DEFAULT_SORT_FIELD: &str = "defaultSortField"; + +const ROLE_PRIMARY: &str = "primary"; +const KIND_TABLE: &str = "table"; +const KIND_VIEW: &str = "view"; +const KIND_MATERIALIZED_VIEW: &str = "materializedView"; +const KIND_STORED_PROC: &str = "storedProc"; +const KIND_TABLE_FUNCTION: &str = "tableFunction"; +const READ_ONLY_KINDS: [&str; 4] = [ + KIND_VIEW, + KIND_MATERIALIZED_VIEW, + KIND_STORED_PROC, + KIND_TABLE_FUNCTION, +]; + +/// Physical-name alias attr, by `@kind` (ADR-0018). +const ALIAS_BY_KIND: [(&str, &str); 5] = [ + (KIND_TABLE, "table"), + (KIND_VIEW, "view"), + (KIND_MATERIALIZED_VIEW, "materializedView"), + (KIND_STORED_PROC, "proc"), + (KIND_TABLE_FUNCTION, "function"), +]; +const ALL_ALIASES: [&str; 5] = ["table", "view", "materializedView", "proc", "function"]; + +// ---- small readers ---------------------------------------------------------- + +fn str_attr<'a>(tree: &'a Tree, id: NodeId, name: &str) -> Option<&'a str> { + tree.attr(id, name).and_then(Value::as_str) +} + +fn nonempty_str_attr<'a>(tree: &'a Tree, id: NodeId, name: &str) -> Option<&'a str> { + str_attr(tree, id, name).filter(|s| !s.is_empty()) +} + +fn effective_kind(tree: &Tree, s: NodeId) -> &str { + nonempty_str_attr(tree, s, ATTR_KIND).unwrap_or(KIND_TABLE) +} + +fn is_read_only(tree: &Tree, s: NodeId) -> bool { + READ_ONLY_KINDS.contains(&effective_kind(tree, s)) +} + +fn sql_body_set(tree: &Tree, s: NodeId) -> bool { + nonempty_str_attr(tree, s, ATTR_SQL).is_some() +} + +fn is_unmanaged(tree: &Tree, s: NodeId) -> bool { + tree.attr(s, ATTR_UNMANAGED) == Some(&Value::Bool(true)) +} + +/// The root's direct object children (the root has no super). +fn objects<'a>(tree: &'a Tree, root: NodeId) -> impl Iterator + 'a { + tree.own_children(root) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_OBJECT) +} + +/// Own `source.rdb` children: the declaration layer (ADR-0039 own: the checks judge +/// what THIS object declares; an inherited source was judged where it is declared). +fn own_rdb_sources<'a>(tree: &'a Tree, obj: NodeId) -> impl Iterator + 'a { + tree.own_children(obj).iter().copied().filter(|&c| { + let n = tree.node(c); + n.type_name == TYPE_SOURCE && n.sub_type == SOURCE_RDB + }) +} + +/// A JavaScript `String.prototype.trim() === ""`. +fn js_blank(s: &str) -> bool { + s.chars() + .all(|c| (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}') +} + +// ---- reference resolution (ADR-0059 R2, objects only) --------------------------- + +// ---- validateSourceRoles ---------------------------------------------------------- + +pub fn validate_source_roles(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for obj in objects(tree, ctx.root) { + // ADR-0039 own: the one-primary rule counts sources declared on THIS object. + let sources: Vec = tree + .own_children(obj) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_SOURCE) + .collect(); + if sources.is_empty() { + continue; + } + let role = |s: NodeId| nonempty_str_attr(tree, s, ATTR_ROLE).unwrap_or(ROLE_PRIMARY); + let primaries = sources.iter().filter(|&&s| role(s) == ROLE_PRIMARY).count(); + let name = &tree.node(obj).name; + if primaries == 0 { + out.errors.push(error_at( + tree, + obj, + ERR_SOURCE_NO_PRIMARY, + format!( + "object \"{name}\" declares {} source(s) but none has role \"{ROLE_PRIMARY}\"", + sources.len() + ), + )); + } else if primaries > 1 { + out.errors.push(error_at( + tree, + obj, + ERR_SOURCE_MULTIPLE_PRIMARY, + format!( + "object \"{name}\" declares {primaries} sources with role \"{ROLE_PRIMARY}\"; exactly one is required" + ), + )); + } + if tree.node(obj).sub_type == OBJECT_ENTITY { + for &s in &sources { + if role(s) == ROLE_PRIMARY && is_read_only(tree, s) { + out.errors.push(error_at( + tree, + s, + ERR_ENTITY_PRIMARY_SOURCE_READONLY, + format!( + "entity \"{name}\" has a primary source of read-only kind \"{}\" — read-only kinds are legal only in non-primary roles; a derived read model is an object.projection (FR-024, ADR-0028)", + effective_kind(tree, s) + ), + )); + } + } + } + } +} + +// ---- validateSourceEscapes -------------------------------------------------------- + +/// A projection's effective `@filter` is present when any level of its `extends` +/// chain declares one (ADR-0039 own: each level contributes its own declaration). +fn has_effective_projection_filter(tree: &Tree, projection: NodeId) -> bool { + let mut seen = vec![]; + let mut cur = Some(projection); + while let Some(n) = cur { + if seen.contains(&n) { + break; + } + seen.push(n); + if tree + .own_attr(n, ATTR_FILTER) + .is_some_and(|a| !a.value.is_null()) + { + return true; + } + cur = tree.node(n).super_node; + } + false +} + +pub fn validate_source_escapes(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for obj in objects(tree, ctx.root) { + let name = &tree.node(obj).name; + let (mut sql_host, mut unmanaged_host) = (false, false); + for s in own_rdb_sources(tree, obj) { + let sql_set = sql_body_set(tree, s); + let unmanaged = is_unmanaged(tree, s); + if sql_set && unmanaged { + out.errors.push(error_at(tree, s, ERR_SQL_BODY_WITH_UNMANAGED, format!( + "source.rdb on object \"{name}\" declares both @sql and @unmanaged — these are the mutually exclusive non-default states of one DDL-ownership axis (an author-supplied body contradicts \"someone else owns this DDL\")"))); + } + if sql_set && !is_read_only(tree, s) { + out.errors.push(error_at(tree, s, ERR_SQL_BODY_ON_WRITABLE_KIND, format!( + "source.rdb on object \"{name}\" declares @sql with a writable @kind (\"{}\") — @sql is legal only on a read-only kind (view/materializedView/storedProc/tableFunction); a writable table is either fully modeled or marked @unmanaged, never opaque-bodied", + effective_kind(tree, s)))); + } + // The raw attr, not the narrowed body: present-but-empty must be seen. + if let Some(raw) = tree.attr(s, ATTR_SQL) + && raw.as_str().is_none_or(js_blank) + { + out.errors.push(error_at(tree, s, ERR_BAD_ATTR_VALUE, format!( + "source.rdb on object \"{name}\" sets @sql to an empty/whitespace-only value; @sql requires a non-empty SQL body"))); + } + sql_host |= sql_set; + unmanaged_host |= unmanaged; + } + if !sql_host && !unmanaged_host { + continue; + } + // ADR-0039 own: origin.* never inherits (ADR-0029), so derived-ness is own-only. + for &f in tree.own_children(obj) { + if tree.node(f).type_name != TYPE_FIELD + || !tree + .own_children(f) + .iter() + .any(|&c| tree.node(c).type_name == TYPE_ORIGIN) + { + continue; + } + let fname = &tree.node(f).name; + if sql_host { + out.errors.push(error_at(tree, f, ERR_ORIGIN_UNDER_SQL_BODY, format!( + "field \"{name}.{fname}\" carries an origin.* (derived) child, but \"{name}\" has a read source carrying @sql — the synthesized derivation and the author's verbatim SQL are two sources of truth for the same body"))); + } else { + out.warnings.push(error_at(tree, f, WARN_ORIGIN_UNDER_UNMANAGED, format!( + "field \"{name}.{fname}\" carries an origin.* (derived) child, but \"{name}\" has a source marked @unmanaged — the tool never touches this object's DDL, so the derivation is documented lineage only (not acted on); this is informational, not an error"))); + } + } + if sql_host + && tree.node(obj).sub_type == OBJECT_PROJECTION + && has_effective_projection_filter(tree, obj) + { + out.errors.push(error_at(tree, obj, ERR_ORIGIN_UNDER_SQL_BODY, format!( + "projection \"{name}\" declares both @filter and an @sql read source — a view-level @filter lowers to the outer WHERE of a synthesized body; with @sql the author owns the body (and its WHERE), so the two cannot be combined"))); + } + } +} + +// ---- validateSourcePhysicalNames ----------------------------------------------------- + +pub fn validate_source_physical_names(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for obj in objects(tree, ctx.root) { + let name = &tree.node(obj).name; + for s in own_rdb_sources(tree, obj) { + // ADR-0039 own: the "exactly one alias, non-empty" rule is a per-source + // own-declaration constraint; resolving would conflate an inherited alias. + let own_str = |a: &str| tree.own_attr(s, a).and_then(|x| x.value.as_str()); + for a in ALL_ALIASES { + if own_str(a) == Some("") { + out.errors.push(error_at(tree, s, ERR_BAD_ATTR_VALUE, format!( + "source.rdb on object \"{name}\" sets @{a} to an empty string; physical name attrs require a non-empty value"))); + } + } + let set: Vec<&str> = ALL_ALIASES + .into_iter() + .filter(|a| own_str(a).is_some_and(|v| !v.is_empty())) + .collect(); + if set.len() > 1 { + let list = set + .iter() + .map(|a| format!("@{a}")) + .collect::>() + .join(", "); + out.errors.push(error_at(tree, s, ERR_PHYSICAL_NAME_MULTIPLE, format!( + "source.rdb on object \"{name}\" declares multiple physical-name aliases ({list}); set exactly one"))); + continue; + } + let Some(&chosen) = set.first() else { continue }; + let kind = effective_kind(tree, s); + let expected = ALIAS_BY_KIND + .iter() + .find(|(k, _)| *k == kind) + .map(|(_, a)| *a); + if expected == Some(chosen) { + continue; + } + if chosen == "table" { + out.warnings.push(error_at(tree, s, WARN_LEGACY_PHYSICAL_NAME_ALIAS, format!( + "source.rdb on object \"{name}\" uses @table with @kind: \"{kind}\"; prefer the kind-matching alias @{} (ADR-0018)", + expected.unwrap_or("undefined")))); + continue; + } + let for_alias = ALIAS_BY_KIND + .iter() + .find(|(_, a)| *a == chosen) + .map_or("(unknown)", |(k, _)| *k); + out.errors.push(error_at(tree, s, ERR_PHYSICAL_NAME_KIND_MISMATCH, format!( + "source.rdb on object \"{name}\" uses @{chosen} with @kind: \"{kind}\"; @{chosen} is only valid for @kind: \"{for_alias}\""))); + } + } +} + +// ---- validateSourceParameterRef --------------------------------------------------------- + +pub fn validate_source_parameter_ref(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for obj in objects(tree, ctx.root) { + let n = tree.node(obj); + let referrer_pkg = n + .package + .as_deref() + .or(n.file_default_package.as_deref()) + .unwrap_or(""); + for s in own_rdb_sources(tree, obj) { + // Resolving: a source may inherit @parameterRef via extends. + let Some(reference) = nonempty_str_attr(tree, s, ATTR_PARAMETER_REF) else { + continue; + }; + let kind = effective_kind(tree, s); + if kind != KIND_STORED_PROC && kind != KIND_TABLE_FUNCTION { + out.errors.push(error_at(tree, s, ERR_PARAMETER_REF_ON_NON_CALLABLE_KIND, format!( + "source.rdb on object \"{}\" has @parameterRef but @kind is \"{kind}\"; only \"storedProc\" or \"tableFunction\" accept parameters", n.name))); + continue; + } + let idx = ctx.objects; + let Some(target) = idx.resolve(reference, referrer_pkg) else { + out.errors.push(error_at(tree, s, ERR_PARAMETER_REF_UNRESOLVED, format!( + "source.rdb on object \"{}\" @parameterRef = \"{reference}\" does not resolve to any known object", n.name))); + continue; + }; + let t = tree.node(target); + if t.sub_type != OBJECT_VALUE { + let reason = if t.sub_type == OBJECT_ENTITY { + "an object.entity (entities have identity; parameter shapes are value-objects)" + .to_string() + } else { + format!("an object.{}", t.sub_type) + }; + out.errors.push(error_at(tree, s, ERR_PARAMETER_REF_NOT_VALUE_OBJECT, format!( + "source.rdb on object \"{}\" @parameterRef = \"{reference}\" resolves to {reason}; use an object.value", n.name))); + } + } + } +} + +// ---- validateColumnNameCollisions ------------------------------------------------------------ + +struct PhysicalColumn { + column: String, + field: NodeId, + /// Set for a flattened member: the member's field node. + member: Option, +} + +impl PhysicalColumn { + fn label(&self, tree: &Tree) -> String { + match self.member { + Some(m) => format!("{}.{}", tree.node(self.field).name, tree.node(m).name), + None => tree.node(self.field).name.clone(), + } + } + + fn named(&self) -> NodeId { + self.member.unwrap_or(self.field) + } +} + +fn has_explicit_column(tree: &Tree, f: NodeId) -> bool { + nonempty_str_attr(tree, f, ATTR_COLUMN).is_some() +} + +pub fn validate_column_name_collisions(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for obj in objects(tree, ctx.root) { + if tree.node(obj).is_abstract { + continue; + } + let kids = tree.children(obj); + let mut has_source = false; + let (mut all_read_only, mut sql_view) = (true, false); + for &c in kids.iter() { + if tree.node(c).type_name == TYPE_SOURCE { + has_source = true; + all_read_only &= is_read_only(tree, c); + sql_view |= effective_kind(tree, c) == KIND_VIEW && sql_body_set(tree, c); + } + } + if !has_source || (all_read_only && sql_view) { + continue; + } + let mut seen: HashMap = HashMap::new(); + for &f in kids.iter() { + if tree.node(f).type_name != TYPE_FIELD + // ADR-0039 own: origin.* never inherits (ADR-0029), so derived-ness is own-only. + || tree.own_children(f).iter().any(|&c| tree.node(c).type_name == TYPE_ORIGIN) + { + continue; + } + let mut columns: Vec = Vec::new(); + if tree.node(f).sub_type == FIELD_OBJECT + && str_attr(tree, f, ATTR_STORAGE) == Some(STORAGE_FLATTENED) + { + let idx = ctx.objects; + if let Some(target) = idx.ref_target(tree, f, ATTR_OBJECT_REF) + && tree.node(target).type_name == TYPE_OBJECT + { + for &m in tree.children(target).iter() { + if tree.node(m).type_name == TYPE_FIELD { + match resolve_flattened_column_name(tree, f, m, &ctx.naming) { + Ok(column) => columns.push(PhysicalColumn { + column, + field: f, + member: Some(m), + }), + Err(e) => out.errors.push(e), + } + } + } + } + } else { + match resolve_column_name(tree, f, &ctx.naming) { + Ok(column) => columns.push(PhysicalColumn { + column, + field: f, + member: None, + }), + Err(e) => out.errors.push(e), + } + } + for col in columns { + if let Some(first) = seen.get(&col.column) { + let hint = if first.member.is_some() || col.member.is_some() { + "Give one flattened field a different @flattenedColumnPrefix, or rename one field." + } else if has_explicit_column(tree, first.named()) + && has_explicit_column(tree, col.named()) + { + "Rename one field, or point one @column at a different column." + } else { + "Rename one field, or give one an explicit @column so the two columns differ." + }; + out.errors.push(error_at(tree, f, ERR_COLUMN_NAME_COLLISION, format!( + "fields \"{}\" and \"{}\" on \"{}\" both resolve to physical column \"{}\". {hint}", + first.label(tree), col.label(tree), tree.node(obj).name, col.column))); + } else { + seen.insert(col.column.clone(), col); + } + } + } + } +} + +// ---- validateIndexLookupFields ------------------------------------------------------------------ + +/// The closing sentence of the contradiction hint (`attr-contradictions.ts`). +fn contradiction_hint(label: &str) -> String { + let (why, effect) = if label == "index.lookup" { + ( + "an index keys off plain columns (@fields) or a key expression (@expr), never both", + "the index in your database is the expression one and dropping @fields changes no emitted DDL", + ) + } else { + ( + "a unique key keys off plain columns (@fields) or a key expression (@expr), never both", + "the constraint in your database is the expression one and dropping @fields changes no emitted DDL", + ) + }; + format!( + "{why} — drop one. Declaring both previously loaded but silently discarded @fields, so {effect}. `meta upgrade --apply` drops it for you." + ) +} + +pub fn validate_index_lookup_fields(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for obj in objects(tree, ctx.root) { + let kids = tree.children(obj); + let keyed = |c: NodeId| { + let n = tree.node(c); + (n.type_name == TYPE_INDEX && n.sub_type == INDEX_LOOKUP) + || (n.type_name == TYPE_IDENTITY && n.sub_type == IDENTITY_SECONDARY) + }; + if !kids.iter().any(|&c| keyed(c)) { + continue; + } + let mut names: Vec<&str> = Vec::new(); + let mut set: HashSet<&str> = HashSet::new(); + for &c in kids.iter() { + if tree.node(c).type_name == TYPE_FIELD && set.insert(&tree.node(c).name) { + names.push(&tree.node(c).name); + } + } + let oname = &tree.node(obj).name; + for &node in kids.iter().filter(|&&c| keyed(c)) { + let n = tree.node(node); + let label = format!("{}.{}", n.type_name, n.sub_type); + let fields_attr = tree.attr(node, ATTR_FIELDS); + let has_expr = str_attr(tree, node, ATTR_EXPR).is_some_and(|e| !js_blank(e)); + if fields_attr.is_some() && has_expr { + out.errors.push(error_at(tree, node, ERR_INVALID_INDEX, format!( + "{label} \"{}\" on \"{oname}\" declares BOTH @{ATTR_FIELDS} and @{ATTR_EXPR}: {}", + n.name, contradiction_hint(&label)))); + continue; + } + let fields: &[Value] = fields_attr + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice); + if fields.is_empty() && !has_expr { + out.errors.push(error_at(tree, node, ERR_INVALID_INDEX, format!( + "{label} \"{}\" on \"{oname}\" declares no key: it must have @{ATTR_FIELDS} (one or more columns) or @{ATTR_EXPR} (a key expression)", + n.name))); + continue; + } + for fv in fields { + if fv.as_str().is_none_or(|s| !set.contains(s)) { + let avail = if names.is_empty() { + "(none)".to_string() + } else { + names.join(", ") + }; + out.errors.push(error_at(tree, node, ERR_INVALID_INDEX, format!( + "{label} \"{}\" on \"{oname}\" references field \"{}\" which does not exist on \"{oname}\". Available fields: {avail}", + n.name, js_display(fv)))); + } + } + } + } +} + +// ---- grid and filterable/sortable passes ------------------------------------------------------------- + +fn effective_field_names<'a>(tree: &'a Tree, kids: &[NodeId]) -> Vec<&'a str> { + let mut seen = HashSet::new(); + kids.iter() + .filter(|&&c| tree.node(c).type_name == TYPE_FIELD) + .map(|&c| tree.node(c).name.as_str()) + .filter(|n| seen.insert(*n)) + .collect() +} + +fn data_grids<'a>(tree: &'a Tree, kids: &'a [NodeId]) -> impl Iterator + 'a { + kids.iter().copied().filter(|&c| { + let n = tree.node(c); + n.type_name == TYPE_LAYOUT && n.sub_type == LAYOUT_DATA_GRID + }) +} + +pub fn validate_data_grid_sort_fields(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for obj in objects(tree, ctx.root) { + let kids = tree.children(obj); + let mut names: Option<(Vec<&str>, HashSet<&str>)> = None; + for layout in data_grids(tree, &kids) { + let Some(sort) = str_attr(tree, layout, ATTR_DEFAULT_SORT_FIELD) else { + continue; + }; + let (list, set) = names.get_or_insert_with(|| { + let l = effective_field_names(tree, &kids); + let s = l.iter().copied().collect(); + (l, s) + }); + if !set.contains(sort) { + out.errors.push(error_at(tree, layout, ERR_BAD_DEFAULT_SORT_FIELD, format!( + "dataGrid layout \"{}\" on entity \"{}\" has @defaultSortField \"{sort}\" but no such field exists on \"{}\". Available fields: {}", + tree.node(layout).name, tree.node(obj).name, tree.node(obj).name, list.join(", ")))); + } + } + } +} + +pub fn validate_filterable_has_index(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for obj in objects(tree, ctx.root) { + let kids = tree.children(obj); + let mut indexed: Option> = None; + for &f in kids.iter() { + if tree.node(f).type_name != TYPE_FIELD + || tree.attr(f, ATTR_FILTERABLE) != Some(&Value::Bool(true)) + || tree.attr(f, ATTR_DB_INDEXED) == Some(&Value::Bool(true)) + { + continue; + } + let set = indexed.get_or_insert_with(|| { + let mut s = HashSet::new(); + for &i in kids + .iter() + .filter(|&&c| tree.node(c).type_name == TYPE_IDENTITY) + { + match tree.attr(i, ATTR_FIELDS) { + Some(Value::String(v)) => { + s.extend(v.split(',').map(|x| x.trim().to_string())) + } + Some(Value::Array(a)) => { + s.extend(a.iter().filter_map(|x| x.as_str().map(String::from))) + } + _ => {} + } + } + s + }); + let fname = &tree.node(f).name; + if set.contains(fname.as_str()) { + continue; + } + out.warnings.push(MetaError::code(WARN_LEGACY, format!( + "[filterable-without-index] field \"{}.{fname}\" has @filterable: true but is not part of any identity. Filtering on this field will sequential-scan. Add @db.indexed: true to the field (when supported), or remove @filterable: true.", + tree.node(obj).name))); + } + } +} + +pub fn validate_filterable_has_supported_ops(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for obj in objects(tree, ctx.root) { + for &f in tree.children(obj).iter() { + if tree.node(f).type_name != TYPE_FIELD + || tree.attr(f, ATTR_FILTERABLE) != Some(&Value::Bool(true)) + { + continue; + } + let (oname, fname) = (&tree.node(obj).name, &tree.node(f).name); + if tree.resolved_is_array(f) { + out.errors.push(error_at(tree, f, ERR_FILTERABLE_UNSUPPORTED_SUBTYPE, format!( + "Field \"{oname}.{fname}\" has @filterable: true but is an array (isArray: true). No filter operator applies to a collection column. Remove @filterable from this field."))); + continue; + } + if !ops_for_subtype(&tree.node(f).sub_type).is_empty() { + continue; + } + out.errors.push(error_at(tree, f, ERR_FILTERABLE_UNSUPPORTED_SUBTYPE, format!( + "Field \"{oname}.{fname}\" has @filterable: true but its subtype \"{}\" has no filter-operator band. Remove @filterable, or use a field subtype that supports filtering (string/enum/uuid/number/currency/date/boolean).", + tree.node(f).sub_type))); + } + } +} + +pub fn validate_sortable_has_supported_subtype(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for obj in objects(tree, ctx.root) { + for &f in tree.children(obj).iter() { + if tree.node(f).type_name != TYPE_FIELD + || tree.attr(f, ATTR_SORTABLE) != Some(&Value::Bool(true)) + { + continue; + } + let is_array = tree.resolved_is_array(f); + if !is_array && !ops_for_subtype(&tree.node(f).sub_type).is_empty() { + continue; + } + let why = if is_array { + "is an array (isArray: true) — a collection column has no ordering.".to_string() + } else { + format!( + "its subtype \"{}\" cannot be ordered.", + tree.node(f).sub_type + ) + }; + out.errors.push(error_at(tree, f, ERR_SORTABLE_UNSUPPORTED_SUBTYPE, format!( + "Field \"{}.{}\" has @sortable: true but {why} Remove @sortable from this field.", + tree.node(obj).name, tree.node(f).name))); + } + } +} + +fn check_filter_clauses( + filter: &Map, + allow: &IndexAllow, + entity: &str, + layout: NodeId, + tree: &Tree, + out: &mut Vec, +) { + for (key, clause) in filter { + if key == "or" || key == "and" { + if let Value::Array(subs) = clause { + for sub in subs.iter().filter_map(Value::as_object) { + check_filter_clauses(sub, allow, entity, layout, tree, out); + } + } + continue; + } + let lname = &tree.node(layout).name; + let Some(ops) = allow.get(key) else { + let keys: Vec<&str> = allow.keys().collect(); + let list = if keys.is_empty() { + "(none)".to_string() + } else { + keys.join(", ") + }; + out.push(error_at(tree, layout, ERR_BAD_ATTR_FILTER, format!( + "dataGrid layout \"{lname}\" on entity \"{entity}\" has @filter over non-filterable field \"{key}\". Filterable fields: {list}"))); + continue; + }; + if let Value::Object(c) = clause { + for op in c.keys().filter(|op| !ops.contains(&op.as_str())) { + out.push(error_at(tree, layout, ERR_BAD_ATTR_FILTER, format!( + "dataGrid layout \"{lname}\" on entity \"{entity}\" @filter uses disallowed op \"{key}.{op}\". Allowed ops for \"{key}\": {}", + ops.join(", ")))); + } + } + } +} + +/// Filterable field name to its operator band, in first-insertion order. +struct IndexAllow(indexmap::IndexMap); + +impl IndexAllow { + fn get(&self, k: &str) -> Option<&'static [&'static str]> { + self.0.get(k).copied() + } + + fn keys(&self) -> impl Iterator { + self.0.keys().map(String::as_str) + } +} + +pub fn validate_data_grid_filter_values(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for obj in objects(tree, ctx.root) { + let kids = tree.children(obj); + let mut allow: Option = None; + for layout in data_grids(tree, &kids) { + // Type errors (the legacy string form) are reported by the attr-schema pass. + let Some(Value::Object(filter)) = tree.attr(layout, ATTR_FILTER) else { + continue; + }; + let allow = allow.get_or_insert_with(|| { + let mut m = indexmap::IndexMap::new(); + for &f in kids.iter() { + if tree.node(f).type_name == TYPE_FIELD + && tree.attr(f, ATTR_FILTERABLE) == Some(&Value::Bool(true)) + { + m.insert(tree.node(f).name.clone(), ops_for_field(tree, f)); + } + } + IndexAllow(m) + }); + check_filter_clauses( + filter, + allow, + &tree.node(obj).name, + layout, + tree, + &mut out.errors, + ); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::loader::Loader; + use crate::providers::default_registry; + + #[test] + fn every_code_is_in_the_shared_catalogue() { + let raw = include_str!("../../../../../fixtures/conformance/ERROR-CODES.json"); + let doc: Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for c in [ + ERR_SOURCE_NO_PRIMARY, + ERR_SOURCE_MULTIPLE_PRIMARY, + ERR_ENTITY_PRIMARY_SOURCE_READONLY, + ERR_SQL_BODY_WITH_UNMANAGED, + ERR_SQL_BODY_ON_WRITABLE_KIND, + ERR_ORIGIN_UNDER_SQL_BODY, + ERR_BAD_ATTR_VALUE, + ERR_PHYSICAL_NAME_MULTIPLE, + ERR_PHYSICAL_NAME_KIND_MISMATCH, + ERR_PARAMETER_REF_UNRESOLVED, + ERR_PARAMETER_REF_NOT_VALUE_OBJECT, + ERR_PARAMETER_REF_ON_NON_CALLABLE_KIND, + ERR_COLUMN_NAME_COLLISION, + ERR_INVALID_INDEX, + ERR_BAD_DEFAULT_SORT_FIELD, + ERR_BAD_ATTR_FILTER, + ERR_FILTERABLE_UNSUPPORTED_SUBTYPE, + ERR_SORTABLE_UNSUPPORTED_SUBTYPE, + ] { + assert!(codes.contains_key(c), "{c} is not in ERROR-CODES.json"); + } + } + + #[test] + fn resolves_bare_qualified_and_relative_refs() { + let registry = default_registry().unwrap(); + let doc = + r#"{"metadata.root":{"package":"a::b","children":[{"object.value":{"name":"P"}}]}}"#; + let r = Loader::new(®istry).load_sources(&[("m.json".into(), doc.into())]); + let idx = crate::validate::util::ObjectIndex::build(&r.tree, r.root); + assert!(idx.resolve("P", "a::b").is_some()); + assert!(idx.resolve("a::b::P", "").is_some()); + assert!(idx.resolve("::a::b::P", "x").is_some()); + assert!(idx.resolve("..::b::P", "a::c").is_some()); + assert!(idx.resolve("P", "a").is_none()); + assert!(idx.resolve("..::..::..::P", "a::b").is_none()); + } + + #[test] + fn js_blank_follows_javascript_trim() { + assert!(js_blank(" \u{feff}\t")); + assert!(!js_blank("\u{85}")); + assert!(!js_blank(" x ")); + } +} diff --git a/server/rust/metaobjects/src/validate/prompt.rs b/server/rust/metaobjects/src/validate/prompt.rs new file mode 100644 index 0000000000..00cb418af2 --- /dev/null +++ b/server/rust/metaobjects/src/validate/prompt.rs @@ -0,0 +1,336 @@ +//! Prompt and requirement vocabulary checks: `template.*` payload references and +//! the retired-requirement link rules. +//! +//! `validateTemplatePayloadRefs` and `validateRetiredRequirementLinks` in the +//! TypeScript reference (`loader/validation-passes.ts`). + +use std::collections::HashSet; + +use serde_json::Value; + +use super::util::{ObjectIndex, error_at}; +use super::{Ctx, Findings}; +use crate::errors::MetaError; +use crate::node::{NodeId, Tree}; +use crate::source::ErrorSource; + +pub const ERR_INVALID_TEMPLATE: &str = "ERR_INVALID_TEMPLATE"; +pub const ERR_SUBTYPE_RULE_VIOLATION: &str = "ERR_SUBTYPE_RULE_VIOLATION"; +pub const ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS: &str = + "ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS"; +pub const ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED: &str = + "ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED"; + +const TYPE_TEMPLATE: &str = "template"; +const TYPE_OBJECT: &str = "object"; +const TYPE_FIELD: &str = "field"; +const TYPE_SOURCE: &str = "source"; +const TYPE_REQUIREMENT: &str = "requirement"; +const SUBTYPE_OUTPUT: &str = "output"; +const SUBTYPE_PROMPT: &str = "prompt"; +const OBJECT_SUBTYPE_VALUE: &str = "value"; +const OBJECT_SUBTYPE_PROJECTION: &str = "projection"; +const FIELD_SUBTYPE_OBJECT: &str = "object"; +const ATTR_KIND: &str = "kind"; +const KIND_EMAIL: &str = "email"; +const ATTR_SUBJECT_REF: &str = "subjectRef"; +const ATTR_HTML_BODY_REF: &str = "htmlBodyRef"; +const ATTR_TEXT_REF: &str = "textRef"; +const ATTR_PAYLOAD_REF: &str = "payloadRef"; +const ATTR_RESPONSE_REF: &str = "responseRef"; +const ATTR_REQUIRED_SLOTS: &str = "requiredSlots"; +const ATTR_OBJECT_REF: &str = "objectRef"; +const ATTR_STATUS: &str = "status"; +const ATTR_IMPLEMENTED_BY: &str = "implementedBy"; +const ATTR_SUPERSEDED_BY: &str = "supersededBy"; +const STATUS_RETIRED: &str = "retired"; + +/// A node's own package, else its file's, else empty (`node.package ?? node.fileDefaultPackage ?? ""`). +fn declared_package(tree: &Tree, id: NodeId) -> String { + let n = tree.node(id); + n.package + .clone() + .or_else(|| n.file_default_package.clone()) + .unwrap_or_default() +} + +/// Every `template.*` node anywhere in the declaration tree, in document order. +fn all_templates(tree: &Tree, id: NodeId, out: &mut Vec) { + // ADR-0039: own — structural walk over the PHYSICAL declaration tree collecting + // every declared template.* node (each visited once at its declaration site). + for &c in tree.own_children(id) { + if tree.node(c).type_name == TYPE_TEMPLATE { + out.push(c); + } + all_templates(tree, c, out); + } +} + +/// A template-level payload target is an `object.value` or a SOURCELESS +/// `object.projection` (#210, #248). +fn is_legal_payload_target(tree: &Tree, obj: NodeId) -> bool { + match tree.node(obj).sub_type.as_str() { + OBJECT_SUBTYPE_VALUE => true, + // ADR-0039: resolving — a source anywhere in the extends chain binds the + // projection to a backing store, which disqualifies it as a payload shape. + OBJECT_SUBTYPE_PROJECTION => !tree + .children(obj) + .iter() + .any(|&c| tree.node(c).type_name == TYPE_SOURCE), + _ => false, + } +} + +/// Nested payload targets stay value-only (#210); `visited` is shared across the +/// whole pass so a bad nested target reachable from two templates reports once. +fn check_nested_value_only( + ctx: &Ctx<'_>, + index: &ObjectIndex, + payload: NodeId, + findings: &mut Findings, + visited: &mut HashSet, +) { + let tree = ctx.tree; + if !visited.insert(payload) { + return; + } + // ADR-0039: resolving — a payload shape may inherit fields via extends. + for &field in tree.children(payload).iter() { + let f = tree.node(field); + if f.type_name != TYPE_FIELD || f.sub_type != FIELD_SUBTYPE_OBJECT { + continue; + } + let Some(r) = tree + .attr(field, ATTR_OBJECT_REF) + .and_then(Value::as_str) + .filter(|r| !r.is_empty()) + else { + continue; + }; + // ADR-0042: a bare ref resolves in the DECLARING owner's package. + let owner = f.parent.unwrap_or(payload); + let Some(target) = index.resolve(r, &declared_package(tree, owner)) else { + continue; // dangling: the @objectRef resolution check owns it + }; + let t = tree.node(target); + if t.sub_type != OBJECT_SUBTYPE_VALUE { + findings.errors.push(error_at( + tree, + field, + ERR_SUBTYPE_RULE_VIOLATION, + format!( + "payload '{}' field '{}' @objectRef '{r}' resolves to {TYPE_OBJECT}.{} — a nested \ + payload target must be an object.value (template-level refs may also target a \ + sourceless object.projection, nested refs may not) (#210, ADR-0028, ADR-0044)", + tree.node(payload).fqn(), + f.name, + t.sub_type + ), + )); + continue; + } + check_nested_value_only(ctx, index, target, findings, visited); + } +} + +fn resolved(tree: &Tree, id: NodeId, target: String) -> ErrorSource { + let n = tree.node(id); + ErrorSource::Resolved { + files: n.source.files().to_vec(), + json_path: n.source.json_path().unwrap_or("$").to_string(), + referrer: n.fqn(), + target, + } +} + +pub fn validate_template_payload_refs(ctx: &Ctx<'_>, findings: &mut Findings) { + let tree = ctx.tree; + let mut templates = Vec::new(); + all_templates(tree, ctx.root, &mut templates); + if templates.is_empty() { + return; + } + let index = ctx.objects; + let mut nested_visited = HashSet::new(); + let has_string = |t: NodeId, name: &str| tree.attr(t, name).is_some_and(Value::is_string); + for tmpl in templates { + let node = tree.node(tmpl); + let name = &node.name; + let bad = |findings: &mut Findings, msg: String| { + findings + .errors + .push(error_at(tree, tmpl, ERR_INVALID_TEMPLATE, msg)); + }; + // ADR-0039: resolving throughout — a template may inherit its refs via extends. + match node.sub_type.as_str() { + SUBTYPE_OUTPUT => { + if tree.attr(tmpl, ATTR_KIND).and_then(Value::as_str) == Some(KIND_EMAIL) { + if !has_string(tmpl, ATTR_SUBJECT_REF) { + bad( + findings, + format!("template \"{name}\" @kind \"email\" requires @subjectRef"), + ); + } + if !has_string(tmpl, ATTR_HTML_BODY_REF) { + bad( + findings, + format!("template \"{name}\" @kind \"email\" requires @htmlBodyRef"), + ); + } + } else if !has_string(tmpl, ATTR_TEXT_REF) { + bad( + findings, + format!("template \"{name}\" @kind \"document\" requires @textRef"), + ); + } + } + SUBTYPE_PROMPT => { + if !has_string(tmpl, ATTR_TEXT_REF) { + bad(findings, format!("template \"{name}\" requires @textRef")); + } + } + _ => {} + } + + // ADR-0042: a bare ref resolves in the template's package. + let referrer_pkg = declared_package(tree, tmpl); + let Some(payload_ref) = tree.attr(tmpl, ATTR_PAYLOAD_REF).and_then(Value::as_str) else { + continue; // absence is the required-attr schema check's + }; + let payload = index + .resolve(payload_ref, &referrer_pkg) + .filter(|&p| is_legal_payload_target(tree, p)); + let Some(payload) = payload else { + findings.errors.push(MetaError::at( + ERR_INVALID_TEMPLATE, + format!( + "template \"{name}\" @payloadRef \"{payload_ref}\" does not resolve to an \ + object.value or sourceless object.projection at root" + ), + resolved(tree, tmpl, payload_ref.to_string()), + )); + continue; + }; + check_nested_value_only(ctx, index, payload, findings, &mut nested_visited); + if let Some(response_ref) = tree.attr(tmpl, ATTR_RESPONSE_REF).and_then(Value::as_str) { + match index + .resolve(response_ref, &referrer_pkg) + .filter(|&p| is_legal_payload_target(tree, p)) + { + None => findings.errors.push(MetaError::at( + ERR_INVALID_TEMPLATE, + format!( + "template \"{name}\" @responseRef \"{response_ref}\" does not resolve to an \ + object.value or sourceless object.projection at root" + ), + resolved(tree, tmpl, response_ref.to_string()), + )), + Some(res) => { + check_nested_value_only(ctx, index, res, findings, &mut nested_visited); + } + } + } + let slots: Vec<&str> = match tree.attr(tmpl, ATTR_REQUIRED_SLOTS) { + Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(), + Some(Value::String(s)) => vec![s.as_str()], + _ => Vec::new(), + }; + if slots.is_empty() { + continue; + } + let fields: Vec<&str> = tree + .children(payload) + .iter() + .map(|&c| tree.node(c)) + .filter(|c| c.type_name == TYPE_FIELD) + .map(|c| c.name.as_str()) + .collect(); + for slot in slots { + if !fields.contains(&slot) { + findings.errors.push(MetaError::at( + ERR_INVALID_TEMPLATE, + format!( + "template \"{name}\" @requiredSlots \"{slot}\" is not a field on payload \ + \"{payload_ref}\". Available fields: {}", + fields.join(", ") + ), + resolved(tree, tmpl, format!("{payload_ref}.{slot}")), + )); + } + } + } +} + +pub fn validate_retired_requirement_links(ctx: &Ctx<'_>, findings: &mut Findings) { + walk_requirements(ctx.tree, ctx.root, findings); +} + +fn walk_requirements(tree: &Tree, id: NodeId, findings: &mut Findings) { + // ADR-0039: resolving — a requirement that inherits its status through `extends` + // is judged on its EFFECTIVE status. Hierarchy is nesting, so any depth. + for &child in tree.children(id).iter() { + let n = tree.node(child); + if n.type_name == TYPE_REQUIREMENT { + let status = tree.attr(child, ATTR_STATUS); + let retired = status.and_then(Value::as_str) == Some(STATUS_RETIRED); + if retired && tree.attr(child, ATTR_IMPLEMENTED_BY).is_some() { + findings.errors.push(error_at( + tree, + child, + ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS, + format!( + "requirement.{} \"{}\" is @status: {STATUS_RETIRED} and declares \ + @{ATTR_IMPLEMENTED_BY}. A retired capability has no implementation — that is \ + what retiring it means. Delete the attribute; if the nodes are still there, \ + the capability is not retired. What used to implement it belongs in `notes`, \ + and what REPLACED it in @{ATTR_SUPERSEDED_BY}.", + n.sub_type, n.name + ), + )); + } + if !retired && tree.attr(child, ATTR_SUPERSEDED_BY).is_some() { + let shown = match status { + None => "(absent)".to_string(), + Some(Value::String(s)) => s.clone(), + Some(v) => v.to_string(), + }; + findings.errors.push(error_at( + tree, + child, + ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED, + format!( + "requirement.{} \"{}\" declares @{ATTR_SUPERSEDED_BY} but its @{ATTR_STATUS} is \ + \"{shown}\". That attribute names the requirement which REPLACED a withdrawn \ + one, so it is legal only on @{ATTR_STATUS}: {STATUS_RETIRED}.", + n.sub_type, n.name + ), + )); + } + } + walk_requirements(tree, child, findings); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_code_is_in_the_shared_table() { + let table: Value = serde_json::from_str(include_str!( + "../../../../../fixtures/conformance/ERROR-CODES.json" + )) + .unwrap(); + for code in [ + ERR_INVALID_TEMPLATE, + ERR_SUBTYPE_RULE_VIOLATION, + ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS, + ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED, + ] { + assert!( + table["codes"].get(code).is_some(), + "{code} is not in ERROR-CODES.json" + ); + } + } +} diff --git a/server/rust/metaobjects/src/validate/refs.rs b/server/rust/metaobjects/src/validate/refs.rs new file mode 100644 index 0000000000..f82f02e980 --- /dev/null +++ b/server/rust/metaobjects/src/validate/refs.rs @@ -0,0 +1,209 @@ +//! `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. + +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::validate::structure::preorder; +use crate::validate::util::error_at; +use crate::validate::{Ctx, Findings}; + +pub const ERR_INVALID_RELATIONSHIP: &str = "ERR_INVALID_RELATIONSHIP"; +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, + } +} + +/// 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 { + let n = tree.node(id); + n.package + .as_deref() + .or(n.file_default_package.as_deref()) + .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 { + let mut declarer = Some(node); + let mut hops = 0; + // ADR-0039: own: locating the layer that physically declares the attribute. + while let Some(d) = declarer { + if tree.own_attr(d, attr).is_some() || hops > tree.len() { + break; + } + hops += 1; + declarer = tree.node(d).super_node; + } + effective_package_of(tree, tree.top_level_of(declarer.unwrap_or(node))) +} + +/// Every top-level node, by type then resolution key (ADR-0042: no short-name fallback). +struct Symbols { + by_type: HashMap>, +} + +impl Symbols { + fn build(tree: &Tree, root: NodeId) -> Self { + let mut by_type: HashMap> = HashMap::new(); + for &c in tree.children(root).iter() { + by_type + .entry(tree.node(c).type_name.clone()) + .or_default() + .insert(tree.resolution_key(c), c); + } + Self { by_type } + } + + fn resolve(&self, type_name: &str, keys: &[String]) -> Option { + let bucket = self.by_type.get(type_name)?; + keys.iter().find_map(|k| bucket.get(k).copied()) + } +} + +/// 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 candidates: Vec = tree + .children(root) + .iter() + .copied() + .filter(|&c| { + let n = tree.node(c); + n.type_name == TYPE_OBJECT && n.name == short + }) + .map(|c| tree.resolution_key(c)) + .collect(); + if candidates.is_empty() { + return String::new(); + } + format!( + " An object named \"{short}\" exists in: {}. Qualify it with its package (FQN).", + candidates.join(", ") + ) +} + +fn check_descriptor( + ctx: &Ctx<'_>, + symbols: &Symbols, + node: NodeId, + desc: &ReferenceDescriptor, + out: &mut Findings, +) { + let tree = ctx.tree; + // 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 ref_pkg = referrer_package_for(tree, node, &desc.attr); + 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; + } + 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), + format!( + "{}.{} \"{qname}\" @{} \"{raw}\" does not resolve to {want}.{hint}", + n.type_name, n.sub_type, desc.attr + ), + )); +} + +/// Run every registered reference descriptor 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(); + for id in preorder(tree, ctx.root) { + let n = tree.node(id); + let def = *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); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_code_is_in_the_shared_catalogue() { + let raw = include_str!("../../../../../fixtures/conformance/ERROR-CODES.json"); + let doc: serde_json::Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for code in [ + ERR_INVALID_RELATIONSHIP, + ERR_INVALID_REFERENCE, + ERR_UNRESOLVED_OBJECT_REF, + ] { + assert!( + codes.contains_key(code), + "{code} is not in ERROR-CODES.json" + ); + } + } +} diff --git a/server/rust/metaobjects/src/validate/relationships.rs b/server/rust/metaobjects/src/validate/relationships.rs new file mode 100644 index 0000000000..d625cd23e6 --- /dev/null +++ b/server/rust/metaobjects/src/validate/relationships.rs @@ -0,0 +1,545 @@ +//! Relationship validation: the M:N slim-vocabulary rules (`validateRelationships`), +//! `@cardinality: one` reference resolution (`validateOneSideReferenceResolution`) and +//! junction pairing (`validateM2MJunctionPairing`), in the reference's order. +//! +//! References are read as bound targets: the package a reference resolves in is that of +//! the top-level node that physically declares the attribute (ADR-0059 R3/R7), so an +//! inherited reference keeps the meaning it had where it was written. + +use std::collections::HashSet; + +use serde_json::Value; + +use super::refs::did_you_mean_hint; +use super::util::{ObjectIndex, error_at}; +use super::{Ctx, Findings}; +use crate::errors::{ERR_BAD_ATTR_VALUE, MetaError}; +use crate::loader::{resolved_source, split_child_tail}; +use crate::node::{NodeId, Tree}; + +pub const ERR_INVALID_RELATIONSHIP: &str = "ERR_INVALID_RELATIONSHIP"; + +const TYPE_OBJECT: &str = "object"; +const TYPE_IDENTITY: &str = "identity"; +const TYPE_RELATIONSHIP: &str = "relationship"; +const TYPE_SOURCE: &str = "source"; +const SUB_ENTITY: &str = "entity"; +const SUB_REFERENCE: &str = "reference"; +const SUB_RDB: &str = "rdb"; +const ATTR_THROUGH: &str = "through"; +const ATTR_SOURCE_REF_FIELD: &str = "sourceRefField"; +const ATTR_SYMMETRIC: &str = "symmetric"; +const ATTR_CARDINALITY: &str = "cardinality"; +const ATTR_OBJECT_REF: &str = "objectRef"; +const ATTR_REFERENCES: &str = "references"; +const ATTR_FIELDS: &str = "fields"; +const ATTR_KIND: &str = "kind"; +const CARDINALITY_ONE: &str = "one"; +const CARDINALITY_MANY: &str = "many"; +/// Source kinds that are read-only (a view-like source); `table` is the writable default. +const READ_ONLY_KINDS: &[&str] = &["view", "materializedView", "storedProc", "tableFunction"]; +/// Suffixes stripped from a candidate's name/FK field when building pairing keys, in order. +const PAIRING_SUFFIXES: &[&str] = &["reference", "ref", "id", "key"]; + +fn str_attr<'a>(tree: &'a Tree, id: NodeId, name: &str) -> Option<&'a str> { + tree.attr(id, name).and_then(Value::as_str) +} + +fn nonempty_attr<'a>(tree: &'a Tree, id: NodeId, name: &str) -> Option<&'a str> { + str_attr(tree, id, name).filter(|s| !s.is_empty()) +} + +/// The root's top-level objects, in order. +fn objects(tree: &Tree, root: NodeId) -> impl Iterator + '_ { + tree.own_children(root) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_OBJECT) +} + +/// An object's effective relationships. +fn relationships(tree: &Tree, obj: NodeId) -> Vec { + tree.children(obj) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_RELATIONSHIP) + .collect() +} + +/// An object's effective `identity.reference` children. +fn reference_identities(tree: &Tree, obj: NodeId) -> Vec { + tree.children(obj) + .iter() + .copied() + .filter(|&c| { + let n = tree.node(c); + n.type_name == TYPE_IDENTITY && n.sub_type == SUB_REFERENCE + }) + .collect() +} + +/// The `@fields` of an identity, as written (non-strings dropped, a scalar reads as none). +fn identity_fields(tree: &Tree, id: NodeId) -> Vec<&str> { + match tree.attr(id, ATTR_FIELDS) { + Some(Value::Array(items)) => items.iter().filter_map(Value::as_str).collect(), + _ => Vec::new(), + } +} + +/// The FK column a reference is anchored on (its first field). +fn fk_field(tree: &Tree, r: NodeId) -> Option<&str> { + identity_fields(tree, r).first().copied() +} + +fn parent_of(tree: &Tree, rel: NodeId) -> NodeId { + tree.node(rel).parent.unwrap_or(rel) +} + +fn rel_label(tree: &Tree, entity: NodeId, rel: NodeId) -> String { + format!("{}.{}", tree.node(entity).name, tree.node(rel).name) +} + +/// `validateRelationships`: rule (d) M:N-only attributes on a non-M:N relationship, +/// then (b) symmetric xor sourceRefField, (a) symmetric is self-join-only, (c) the +/// junction is one entity declaring exactly two references. Each declaration is checked +/// once, against the entity that declares it. +pub fn validate_relationships(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + let objs = ctx.objects; + let mut checked: HashSet = HashSet::new(); + for obj in objects(tree, ctx.root) { + for rel in relationships(tree, obj) { + if !checked.insert(rel) { + continue; + } + check_relationship(tree, objs, rel, out); + } + } +} + +fn check_relationship(tree: &Tree, objs: &ObjectIndex, rel: NodeId, out: &mut Findings) { + let declaring = parent_of(tree, rel); + let referrer_pkg = tree.effective_package(declaring); + let label = rel_label(tree, declaring, rel); + // ADR-0039: resolving: a relationship may inherit its M:N attributes via extends. + let through = nonempty_attr(tree, rel, ATTR_THROUGH); + let source_ref_field = nonempty_attr(tree, rel, ATTR_SOURCE_REF_FIELD); + let symmetric = tree.attr(rel, ATTR_SYMMETRIC) == Some(&Value::Bool(true)); + let cardinality = str_attr(tree, rel, ATTR_CARDINALITY); + let object_ref = tree.attr(rel, ATTR_OBJECT_REF); + let is_m2m = through.is_some() && cardinality == Some(CARDINALITY_MANY); + + if !is_m2m { + if through.is_some() { + out.errors.push(error_at( + tree, + rel, + ERR_INVALID_RELATIONSHIP, + format!("relationship \"{label}\" sets @{ATTR_THROUGH} but is not a M:N relationship (requires @{ATTR_CARDINALITY}: \"{CARDINALITY_MANY}\")."), + )); + } + if source_ref_field.is_some() && cardinality != Some(CARDINALITY_ONE) { + out.errors.push(error_at( + tree, + rel, + ERR_INVALID_RELATIONSHIP, + format!("relationship \"{label}\" sets @{ATTR_SOURCE_REF_FIELD} but is neither a M:N relationship (requires @{ATTR_THROUGH} with @{ATTR_CARDINALITY}: \"{CARDINALITY_MANY}\") nor a @{ATTR_CARDINALITY}: \"{CARDINALITY_ONE}\" relationship."), + )); + } + if symmetric { + out.errors.push(error_at( + tree, + rel, + ERR_INVALID_RELATIONSHIP, + format!( + "relationship \"{label}\" sets @{ATTR_SYMMETRIC} but is not a M:N relationship." + ), + )); + } + return; + } + let through = through.unwrap_or_default(); + + if symmetric && source_ref_field.is_some() { + out.errors.push(error_at( + tree, + rel, + ERR_BAD_ATTR_VALUE, + format!("relationship \"{label}\" sets both @{ATTR_SYMMETRIC} and @{ATTR_SOURCE_REF_FIELD}; they are mutually exclusive."), + )); + } + + // ADR-0042: compare node identity, never stripped short names. + let is_self_join = object_ref + .and_then(Value::as_str) + .is_some_and(|r| objs.resolve(split_child_tail(r).0, &referrer_pkg) == Some(declaring)); + if symmetric && !is_self_join { + let shown = object_ref.and_then(Value::as_str).unwrap_or("undefined"); + out.errors.push(error_at( + tree, + rel, + ERR_BAD_ATTR_VALUE, + format!("relationship \"{label}\" sets @{ATTR_SYMMETRIC} but @{ATTR_OBJECT_REF} \"{shown}\" is not the declaring entity \"{}\"; @{ATTR_SYMMETRIC} is self-join-only.", tree.node(declaring).name), + )); + } + + let Some(junction) = objs.resolve(split_child_tail(through).0, &referrer_pkg) else { + let source = resolved_source( + &tree.node(rel).source, + format!("{}::{}", tree.node(declaring).fqn(), tree.node(rel).name), + through.to_string(), + ); + out.errors.push(MetaError::at( + ERR_INVALID_RELATIONSHIP, + format!( + "relationship \"{label}\" @{ATTR_THROUGH} \"{through}\" does not resolve to an entity.{}", + did_you_mean_hint(tree, ctx_root(tree, rel), through) + ), + source, + )); + return; + }; + let jn = tree.node(junction); + if jn.sub_type != SUB_ENTITY { + out.errors.push(error_at( + tree, + rel, + ERR_INVALID_RELATIONSHIP, + format!("relationship \"{label}\" @{ATTR_THROUGH} \"{through}\" resolves to {}.{}, not an entity — a junction is a persisted join table and must be object.entity.", jn.type_name, jn.sub_type), + )); + return; + } + let refs = reference_identities(tree, junction); + if refs.len() != 2 { + out.errors.push(error_at( + tree, + rel, + ERR_INVALID_RELATIONSHIP, + format!("relationship \"{label}\" @{ATTR_THROUGH} \"{through}\" must declare exactly two identity.reference children (one per FK side); found {}.", refs.len()), + )); + return; + } + if let Some(declared) = source_ref_field { + let fks: Vec<&str> = refs.iter().filter_map(|&r| fk_field(tree, r)).collect(); + if !fks.contains(&declared) { + let available = if fks.is_empty() { + "(none)".to_string() + } else { + fks.join(", ") + }; + out.errors.push(error_at( + tree, + rel, + ERR_INVALID_RELATIONSHIP, + format!("relationship \"{label}\" @{ATTR_SOURCE_REF_FIELD} \"{declared}\" does not match any identity.reference FK field on junction \"{through}\". Available: {available}."), + )); + } + } +} + +/// The root node: the top of any node's parent chain. +fn ctx_root(tree: &Tree, mut id: NodeId) -> NodeId { + while let Some(p) = tree.node(id).parent { + id = p; + } + id +} + +fn strip_one_suffix(value: &str) -> &str { + for suffix in PAIRING_SUFFIXES { + if value.len() > suffix.len() && value.ends_with(suffix) { + return &value[..value.len() - suffix.len()]; + } + } + value +} + +/// Does a reference answer to the (lowercased) relationship name: by its own name or +/// FK field, each with and without one stripped suffix. +fn pairs_with(tree: &Tree, r: NodeId, wanted: &str) -> bool { + let name = tree.node(r).name.to_lowercase(); + let fk = fk_field(tree, r).map(str::to_lowercase); + let hits = |v: &str| !v.is_empty() && (v == wanted || strip_one_suffix(v) == wanted); + hits(&name) || fk.as_deref().is_some_and(hits) +} + +/// `name(fkField)`, or `name(fieldA, fieldB)` for a composite reference. Display only. +fn format_candidates(tree: &Tree, candidates: &[NodeId]) -> String { + candidates + .iter() + .map(|&c| { + format!( + "{}({})", + tree.node(c).name, + identity_fields(tree, c).join(", ") + ) + }) + .collect::>() + .join(", ") +} + +/// Rule (e): a `@cardinality: one` relationship must resolve to exactly one +/// `identity.reference` of the entity (ADR-0029 section 5; #368). Checked against the +/// effective entity, so an inherited relationship made ambiguous by a subtype's second +/// reference is caught. +pub fn validate_one_side_reference_resolution(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + let objs = ctx.objects; + for obj in objects(tree, ctx.root) { + let mut refs: Option> = None; + for rel in relationships(tree, obj) { + // ADR-0039: resolving: @cardinality/@objectRef may be inherited. + if str_attr(tree, rel, ATTR_CARDINALITY) != Some(CARDINALITY_ONE) { + continue; + } + let Some(object_ref) = nonempty_attr(tree, rel, ATTR_OBJECT_REF) else { + continue; + }; + // ADR-0059 R7: match by the bound target; an unresolved one has its own pass. + let Some(target) = objs.ref_target(tree, rel, ATTR_OBJECT_REF) else { + continue; + }; + let refs = refs.get_or_insert_with(|| reference_identities(tree, obj)); + let candidates: Vec = refs + .iter() + .copied() + .filter(|&r| fk_field(tree, r).is_some()) + .filter(|&r| objs.ref_target(tree, r, ATTR_REFERENCES) == Some(target)) + .collect(); + let name = &tree.node(obj).name; + let rel_name = &tree.node(rel).name; + if let Some(declared) = nonempty_attr(tree, rel, ATTR_SOURCE_REF_FIELD) { + if candidates + .iter() + .any(|&c| fk_field(tree, c) == Some(declared)) + { + continue; + } + out.errors.push(error_at( + tree, + rel, + ERR_INVALID_RELATIONSHIP, + format!("relationship \"{name}.{rel_name}\" sets @{ATTR_SOURCE_REF_FIELD} \"{declared}\", which names no identity.reference targeting \"{object_ref}\". Candidates: {}.", format_candidates(tree, &candidates)), + )); + continue; + } + if candidates.len() <= 1 { + continue; + } + let wanted = rel_name.to_lowercase(); + let paired = candidates + .iter() + .filter(|&&c| pairs_with(tree, c, &wanted)) + .count(); + if paired == 1 { + continue; + } + out.errors.push(error_at( + tree, + rel, + ERR_INVALID_RELATIONSHIP, + format!("relationship \"{name}.{rel_name}\" is ambiguous: \"{name}\" declares {} identity.reference nodes targeting \"{object_ref}\" and the relationship name does not pair with exactly one. Candidates: {}. Set @{ATTR_SOURCE_REF_FIELD} to the FK field this relationship navigates.", candidates.len(), format_candidates(tree, &candidates)), + )); + } + } +} + +/// A projection: its own sources include a read-only one and no writable one. +fn is_projection_object(tree: &Tree, obj: NodeId) -> bool { + let (mut read_only, mut writable) = (false, false); + // ADR-0039: own: projection-ness is the entity's OWN declared source @kind. + for &c in tree.own_children(obj) { + let n = tree.node(c); + if n.type_name != TYPE_SOURCE || n.sub_type != SUB_RDB { + continue; + } + let kind = nonempty_attr(tree, c, ATTR_KIND).unwrap_or("table"); + if READ_ONLY_KINDS.contains(&kind) { + read_only = true; + } else { + writable = true; + } + } + read_only && !writable +} + +/// The junction shape faults rule (d) already reports, so rule (f) stays silent on them. +fn junction_shape_owned_by_rule_d( + tree: &Tree, + objs: &ObjectIndex, + rel: NodeId, + referrer_pkg: &str, +) -> bool { + let Some(through) = nonempty_attr(tree, rel, ATTR_THROUGH) else { + return true; + }; + let Some(junction) = objs.resolve(split_child_tail(through).0, referrer_pkg) else { + return true; + }; + if tree.node(junction).sub_type != SUB_ENTITY { + return true; + } + let refs = reference_identities(tree, junction); + if refs.len() != 2 { + return true; + } + if let Some(declared) = nonempty_attr(tree, rel, ATTR_SOURCE_REF_FIELD) { + return !refs.iter().any(|&r| fk_field(tree, r) == Some(declared)); + } + false +} + +/// `deriveM2MFields`: the failure message when the junction's two references cannot be +/// paired with the navigating entity `source` and the `@objectRef` target. +fn derive_m2m_failure( + tree: &Tree, + objs: &ObjectIndex, + rel: NodeId, + source: NodeId, +) -> Option { + let declaring = parent_of(tree, rel); + let declaring = if tree.node(declaring).type_name == TYPE_OBJECT { + declaring + } else { + source + }; + let label = rel_label(tree, declaring, rel); + let through = str_attr(tree, rel, ATTR_THROUGH)?; + let Some(junction) = objs.ref_target(tree, rel, ATTR_THROUGH) else { + return Some(format!( + "relationship \"{label}\" @through \"{through}\" does not resolve to an entity" + )); + }; + let Some(target_name) = str_attr(tree, rel, ATTR_OBJECT_REF) else { + return Some(format!( + "relationship \"{label}\" is missing @objectRef (the M:N target)" + )); + }; + let refs = reference_identities(tree, junction); + if refs.len() != 2 { + return Some(format!( + "junction \"{through}\" for relationship \"{label}\" must declare exactly two identity.reference children (found {})", + refs.len() + )); + } + let is_subject = |e: Option| e.is_some_and(|e| e == declaring || e == source); + let target_node = objs.ref_target(tree, rel, ATTR_OBJECT_REF); + let is_self_join = match target_node { + Some(t) => is_subject(Some(t)), + None => { + let short = target_name.rsplit("::").next().unwrap_or(target_name); + short == tree.node(declaring).name || short == tree.node(source).name + } + }; + let ref_entity = |r: NodeId| objs.ref_target(tree, r, ATTR_REFERENCES); + if !is_self_join { + let source_ref = refs.iter().copied().find(|&r| is_subject(ref_entity(r))); + let target_ref = + target_node.and_then(|t| refs.iter().copied().find(|&r| ref_entity(r) == Some(t))); + let has_fk = |r: Option| r.is_some_and(|r| fk_field(tree, r).is_some()); + if !has_fk(source_ref) || !has_fk(target_ref) { + let mut subjects = vec![tree.node(declaring).name.as_str()]; + if declaring != source && tree.node(declaring).name != tree.node(source).name { + subjects.push(tree.node(source).name.as_str()); + } + let subject = subjects + .iter() + .map(|n| format!("\"{n}\"")) + .collect::>() + .join(" or "); + let short = target_name.rsplit("::").next().unwrap_or(target_name); + return Some(format!( + "junction \"{through}\" for relationship \"{label}\" must declare one identity.reference to {subject} and one to \"{short}\"" + )); + } + return None; + } + if tree.attr(rel, ATTR_SYMMETRIC) == Some(&Value::Bool(true)) { + return refs.iter().any(|&r| fk_field(tree, r).is_none()).then(|| { + format!( + "symmetric junction \"{through}\" for \"{label}\" has a reference with no @fields" + ) + }); + } + let Some(declared) = nonempty_attr(tree, rel, ATTR_SOURCE_REF_FIELD) else { + return Some(format!( + "self-join relationship \"{label}\" through \"{through}\" is ambiguous: set @sourceRefField (directed) or @symmetric (undirected)" + )); + }; + let Some(source_ref) = refs + .iter() + .copied() + .find(|&r| fk_field(tree, r) == Some(declared)) + else { + return Some(format!( + "@sourceRefField \"{declared}\" on \"{label}\" does not match any identity.reference FK field on junction \"{through}\"" + )); + }; + let distinct = refs.iter().copied().find(|&r| r != source_ref); + distinct + .is_none_or(|r| fk_field(tree, r).is_none()) + .then(|| { + format!("junction \"{through}\" for \"{label}\" has no distinct target-side reference") + }) +} + +/// Rule (f): a M:N junction must pair: one reference resolving to the navigating entity, +/// one to the `@objectRef` target. Scope mirrors codegen: each concrete, non-projection +/// object against its effective relationships, not deduped by declaration. +pub fn validate_m2m_junction_pairing(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + let objs = ctx.objects; + for obj in objects(tree, ctx.root) { + if tree.node(obj).is_abstract || is_projection_object(tree, obj) { + continue; + } + for rel in relationships(tree, obj) { + if str_attr(tree, rel, ATTR_CARDINALITY) != Some(CARDINALITY_MANY) + || tree.attr(rel, ATTR_THROUGH).is_none() + { + continue; + } + let Some(message) = derive_m2m_failure(tree, objs, rel, obj) else { + continue; + }; + let declaring = parent_of(tree, rel); + let referrer_pkg = tree.effective_package(declaring); + if junction_shape_owned_by_rule_d(tree, objs, rel, &referrer_pkg) { + continue; + } + let name = &tree.node(obj).name; + out.errors.push(error_at( + tree, + rel, + ERR_INVALID_RELATIONSHIP, + format!("relationship \"{name}.{}\" cannot be resolved through its @{ATTR_THROUGH} junction: {message}. Without a reference to \"{name}\" the junction rows cannot be filtered to this entity, so no traversal is derivable.", tree.node(rel).name), + )); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_code_is_in_the_shared_catalogue() { + let raw = include_str!("../../../../../fixtures/conformance/ERROR-CODES.json"); + let doc: serde_json::Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for code in [ERR_INVALID_RELATIONSHIP, ERR_BAD_ATTR_VALUE] { + assert!( + codes.contains_key(code), + "{code} is not in ERROR-CODES.json" + ); + } + } + + #[test] + fn suffix_stripping_keeps_the_whole_word() { + assert_eq!(strip_one_suffix("hometeamref"), "hometeam"); + assert_eq!(strip_one_suffix("ref"), "ref"); + assert_eq!(strip_one_suffix("teamid"), "team"); + assert_eq!(strip_one_suffix("team"), "team"); + } +} diff --git a/server/rust/metaobjects/src/validate/reporting.rs b/server/rust/metaobjects/src/validate/reporting.rs new file mode 100644 index 0000000000..ed6ba26a76 --- /dev/null +++ b/server/rust/metaobjects/src/validate/reporting.rs @@ -0,0 +1,1814 @@ +//! `validateReporting` (FR-044): cross-node rules for the reporting vocabulary +//! (dimensions, measures, segments, `object.report`) and the relative-date filter +//! value (rules F1/F2). The rule ids match the TypeScript reference +//! (`loader/reporting-validation.ts`); the error text is the contract. +//! +//! One broken rule yields one error: a member that fails a structural rule is not +//! checked further. Members are read through the resolving `children()` (ADR-0039): +//! pass 1 checks members against the entity that declares them, pass 2 the inherited +//! ones against each inheritor, and a repeat of an already-reported failure is dropped. + +#![allow(clippy::collapsible_if)] // nested `if let` mirrors the reference rule-by-rule + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::rc::Rc; + +use serde_json::{Map, Value}; + +use super::field_expr::is_iso_duration; +use super::util::{ + ObjectIndex, START_OF_UNITS, child_label, find_hop, ops_for_field, split_dotted, +}; +use super::{Ctx, Findings}; +use crate::errors::MetaError; +use crate::json::js_display; +use crate::node::{NodeId, PACKAGE_SEP, Tree}; + +pub const ERR_INVALID_DIMENSION: &str = "ERR_INVALID_DIMENSION"; +pub const ERR_INVALID_MEASURE: &str = "ERR_INVALID_MEASURE"; +pub const ERR_INVALID_REPORT: &str = "ERR_INVALID_REPORT"; +pub const ERR_REPORT_FOREIGN_MEASURE: &str = "ERR_REPORT_FOREIGN_MEASURE"; +pub const ERR_BAD_ATTR_FILTER: &str = "ERR_BAD_ATTR_FILTER"; + +const T_OBJECT: &str = "object"; +const T_FIELD: &str = "field"; +const T_IDENTITY: &str = "identity"; +const T_SOURCE: &str = "source"; +const T_DIMENSION: &str = "dimension"; +const T_MEASURE: &str = "measure"; +const T_SEGMENT: &str = "segment"; +const T_ORIGIN: &str = "origin"; +const S_ENTITY: &str = "entity"; +const S_PROJECTION: &str = "projection"; +const S_REPORT: &str = "report"; +const S_AGGREGATE: &str = "aggregate"; +const S_DERIVED: &str = "derived"; +const S_FIRST: &str = "first"; +const S_TIME: &str = "time"; +const A_OF: &str = "of"; +const A_VIA: &str = "via"; +const A_GRAINS: &str = "grains"; +const A_AGG: &str = "agg"; +const A_DISTINCT: &str = "distinct"; +const A_FILTER: &str = "filter"; +const A_SEGMENT: &str = "segment"; +const A_NUMERATOR: &str = "numerator"; +const A_DENOMINATOR: &str = "denominator"; +const A_EXPR: &str = "expr"; +const A_DEFAULT: &str = "default"; +const A_FROM: &str = "from"; +const A_DIMENSIONS: &str = "dimensions"; +const A_MEASURES: &str = "measures"; +const A_SPINE: &str = "spine"; +const A_OBJECT_REF: &str = "objectRef"; +const A_STORAGE: &str = "storage"; +const A_CARDINALITY: &str = "cardinality"; +const A_KIND: &str = "kind"; +const ATTR_SUBTYPE_FILTER: &str = "filter"; +const CARDINALITY_ONE: &str = "one"; +const STORAGE_FLATTENED: &str = "flattened"; +const KIND_TABLE: &str = "table"; +const KIND_VIEW: &str = "view"; +const READ_ONLY_KINDS: [&str; 4] = ["view", "materializedView", "storedProc", "tableFunction"]; +const TIME_GRAINS: [&str; 6] = ["hour", "day", "week", "month", "quarter", "year"]; +const GRAIN_HOUR: &str = "hour"; +const DERIVED_FNS: [&str; 4] = ["add", "subtract", "multiply", "divide"]; +const MEASURE_AGGS: [&str; 7] = ["count", "sum", "avg", "min", "max", "any", "all"]; +const AGG_COUNT: &str = "count"; +const AGG_SUM: &str = "sum"; +const AGG_AVG: &str = "avg"; +const AGG_MIN: &str = "min"; +const AGG_MAX: &str = "max"; +const AGG_ANY: &str = "any"; +const AGG_ALL: &str = "all"; +const NOW: &str = "now"; +const START_OF: &str = "startOf"; +const NUMERIC: [&str; 6] = ["int", "long", "double", "float", "decimal", "currency"]; +const UNORDERED: [&str; 3] = ["boolean", "object", "map"]; +const TEMPORAL: [&str; 2] = ["date", "timestamp"]; +const RELATIVE_OPS: [&str; 4] = ["gt", "gte", "lt", "lte"]; + +type Err<'a> = &'a dyn Fn(&str); + +// ---- small readers ---------------------------------------------------------- + +fn str_attr<'a>(tree: &'a Tree, id: NodeId, name: &str) -> Option<&'a str> { + tree.attr(id, name).and_then(Value::as_str) +} + +fn string_list(v: Option<&Value>) -> Vec<&str> { + match v { + Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(), + Some(Value::String(s)) => vec![s.as_str()], + _ => Vec::new(), + } +} + +fn object_attr<'a>(tree: &'a Tree, id: NodeId, name: &str) -> Option<&'a Map> { + tree.attr(id, name).and_then(Value::as_object) +} + +fn is_integral_number(v: &Value) -> bool { + v.as_f64() + .is_some_and(|f| f.is_finite() && f.fract() == 0.0) +} + +fn is_self_or_ancestor(tree: &Tree, candidate: Option, entity: NodeId) -> bool { + let Some(candidate) = candidate else { + return false; + }; + let mut cur = Some(entity); + let mut steps = 0usize; + while let Some(n) = cur { + if n == candidate { + return true; + } + steps += 1; + if steps > tree.len() { + return false; + } + cur = tree.node(n).super_node; + } + false +} + +fn node_label(tree: &Tree, id: NodeId) -> String { + let n = tree.node(id); + let parent = n.parent; + match parent { + Some(p) if tree.node(p).parent.is_some() => { + format!("{} in {}", child_label(tree, id), node_label(tree, p)) + } + _ => format!( + "{}.{} '{}'", + n.type_name, + n.sub_type, + tree.resolution_key(id) + ), + } +} + +// ---- shared state --------------------------------------------------------------- + +/// Collects errors, dropping the repeat of a failure an inherited member re-raises. +struct Sink<'a> { + tree: &'a Tree, + errors: RefCell>, + seen: RefCell>>, +} + +impl<'a> Sink<'a> { + fn push(&self, node: NodeId, code: &'static str, head: &str, body: &str, suffix: &str) { + let base = format!("{code}\0{head}{body}"); + let key = format!("{base}\0{suffix}"); + let mut seen = self.seen.borrow_mut(); + let keys = seen.entry(node).or_default(); + if keys.contains(&base) || keys.contains(&key) { + return; + } + keys.insert(if suffix.is_empty() { base } else { key }); + self.errors.borrow_mut().push(MetaError::at( + code, + format!("{head}{suffix}{body}"), + self.tree.node(node).source.clone(), + )); + } +} + +struct Env<'a> { + tree: &'a Tree, + index: &'a ObjectIndex, + /// Effective children per object, computed once: the tree is not frozen during + /// validation, so `Tree::children` would recompute them on every call. + kids: RefCell>>, +} + +impl<'a> Env<'a> { + fn kids(&self, obj: NodeId) -> Rc<[NodeId]> { + if let Some(k) = self.kids.borrow().get(&obj) { + return Rc::clone(k); + } + let k: Rc<[NodeId]> = self.tree.children(obj).into_owned().into(); + self.kids.borrow_mut().insert(obj, Rc::clone(&k)); + k + } + + fn child_of_type(&self, obj: NodeId, ty: &str, name: &str) -> Option { + let tree = self.tree; + self.kids(obj).iter().copied().find(|&c| { + let n = tree.node(c); + n.type_name == ty && n.name == name + }) + } + + fn field_of(&self, obj: NodeId, name: &str) -> Option { + self.child_of_type(obj, T_FIELD, name) + } + + fn objects(&self) -> impl Iterator + '_ { + self.index.objects().iter().copied() + } + + /// `resolveObjectRef` (see [`ObjectIndex::resolve`]). + fn resolve_object(&self, reference: &str, referrer_pkg: &str) -> Option { + self.index.resolve(reference, referrer_pkg) + } + + /// `refTarget(node, attr)`. + fn ref_target(&self, node: NodeId, attr: &str) -> Option { + self.index.ref_target(self.tree, node, attr) + } + + fn is_flattened(&self, field: NodeId) -> bool { + self.tree.node(field).sub_type == "object" + && str_attr(self.tree, field, A_STORAGE) == Some(STORAGE_FLATTENED) + } + + fn ref_target_object(&self, field: NodeId) -> Option { + self.ref_target(field, A_OBJECT_REF) + .filter(|&t| self.tree.node(t).type_name == T_OBJECT) + } + + fn flattened_member(&self, embedding: NodeId, name: &str) -> Option { + if !self.is_flattened(embedding) { + return None; + } + self.field_of(self.ref_target_object(embedding)?, name) + } + + /// `resolveReportingFieldRefNamed`. + fn field_ref(&self, r: &str, declaring: NodeId, host: Option) -> Option { + let tree = self.tree; + let seg = r.rfind(PACKAGE_SEP).map_or(0, |i| i + PACKAGE_SEP.len()); + let dot = seg + r[seg..].find('.')?; + if dot == 0 { + return None; + } + let path: Vec<&str> = r[dot + 1..].split('.').collect(); + if path.len() > 2 { + return None; + } + let named = self.resolve_object(&r[..dot], &tree.effective_package(declaring))?; + if host.is_some_and(|h| !is_self_or_ancestor(tree, Some(named), h)) { + return None; + } + let field = self.field_of(host.unwrap_or(named), path[0])?; + match path.get(1) { + None => Some(field), + Some(m) => self.flattened_member(field, m), + } + } + + /// `reportingViaHops`: the hop names of `via`, when its owner is `from` or an ancestor. + fn via_hops<'r>(&self, via: &'r str, declaring: NodeId, from: NodeId) -> Option> { + let (owner, hops) = split_dotted(via)?; + let owner = self.resolve_object(owner, &self.tree.effective_package(declaring))?; + is_self_or_ancestor(self.tree, Some(owner), from).then_some(hops) + } + + /// One hop: a relationship, else an `identity.reference`, and its target object. + fn hop(&self, current: NodeId, name: &str) -> Option<(NodeId, bool)> { + find_hop(self.tree, current, name) + } + + fn hop_target(&self, hop: NodeId, is_ref: bool) -> Option { + self.index.hop_target(self.tree, hop, is_ref) + } + + fn resolve_dimension_of(&self, dim: NodeId, from: NodeId) -> Option { + let tree = self.tree; + let of = str_attr(tree, dim, A_OF).unwrap_or(""); + let declaring = tree.node(dim).parent.unwrap_or(from); + match str_attr(tree, dim, A_VIA) { + None => self.field_ref(of, declaring, Some(from)), + Some(via) => { + let mut current = from; + for h in self.via_hops(via, declaring, from)? { + let (hop, is_ref) = self.hop(current, h)?; + current = self.hop_target(hop, is_ref)?; + } + self.field_ref(of, current, Some(current)) + } + } + } + + /// `measureResultSubType`. + fn measure_result(&self, m: NodeId, from: NodeId) -> Option<&'a str> { + let tree = self.tree; + let sub = tree.node(m).sub_type.as_str(); + if sub == "ratio" || sub == S_DERIVED { + return Some("decimal"); + } + let agg = measure_agg(tree, m); + if agg == Some(AGG_COUNT) { + return Some("long"); + } + if agg == Some(AGG_ANY) || agg == Some(AGG_ALL) { + return Some("boolean"); + } + let cols = of_columns(tree, m); + let declaring = tree.node(m).parent.unwrap_or(from); + let of = self.field_ref(cols.first().copied().unwrap_or(""), declaring, Some(from))?; + let src = tree.node(of).sub_type.as_str(); + Some(match agg { + Some(AGG_SUM) => match src { + "currency" => "currency", + "int" | "long" => "long", + "double" | "float" => "double", + _ => "decimal", + }, + Some(AGG_AVG) => match src { + "double" | "float" => "double", + _ => "decimal", + }, + _ => src, + }) + } +} + +fn measure_agg(tree: &Tree, m: NodeId) -> Option<&str> { + str_attr(tree, m, A_AGG).filter(|a| MEASURE_AGGS.contains(a)) +} + +fn of_columns(tree: &Tree, m: NodeId) -> Vec<&str> { + string_list(tree.attr(m, A_OF)) +} + +fn is_time(tree: &Tree, dim: NodeId) -> bool { + tree.node(dim).sub_type == S_TIME +} + +fn grains(tree: &Tree, dim: NodeId) -> Vec<&str> { + string_list(tree.attr(dim, A_GRAINS)) + .into_iter() + .filter(|g| TIME_GRAINS.contains(g)) + .collect() +} + +// ---- derived expressions ---------------------------------------------------------- + +/// `isDerivedExpr`: `{field}`, `{value}` or `{fn, args:[a, b]}`, recursively. +fn is_derived_expr(v: &Value) -> bool { + let Some(o) = v.as_object() else { + return false; + }; + if o.len() == 1 { + if let Some(f) = o.get("field") { + return f.as_str().is_some_and(|s| !s.is_empty()); + } + if let Some(n) = o.get("value") { + return n.as_f64().is_some_and(f64::is_finite); + } + return false; + } + if let (2, Some(f), Some(Value::Array(args))) = (o.len(), o.get("fn"), o.get("args")) { + return f.as_str().is_some_and(|s| DERIVED_FNS.contains(&s)) + && args.len() == 2 + && args.iter().all(is_derived_expr); + } + false +} + +fn derived_fields<'a>(v: &'a Value, out: &mut Vec<&'a str>) { + let Some(o) = v.as_object() else { + return; + }; + if let Some(f) = o.get("field").and_then(Value::as_str) { + if !out.contains(&f) { + out.push(f); + } + } else if let Some(Value::Array(args)) = o.get("args") { + for a in args { + derived_fields(a, out); + } + } +} + +fn measure_expr(tree: &Tree, m: NodeId) -> Option<&Value> { + tree.attr(m, A_EXPR).filter(|v| is_derived_expr(v)) +} + +// ---- entry point ------------------------------------------------------------------ + +pub fn validate_reporting(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + let env = Env { + tree, + index: ctx.objects, + kids: RefCell::new(HashMap::new()), + }; + let sink = Sink { + tree, + errors: RefCell::new(Vec::new()), + seen: RefCell::new(HashMap::new()), + }; + let entities: Vec = env + .objects() + .filter(|&o| tree.node(o).sub_type == S_ENTITY) + .collect(); + for declared_here in [true, false] { + for &entity in &entities { + check_entity_members(&env, entity, declared_here, &sink); + } + } + for report in env.objects().filter(|&o| tree.node(o).sub_type == S_REPORT) { + check_report(&env, report, &sink); + } + check_no_relative_dates(&env, ctx.root, &sink); + out.errors.extend(sink.errors.into_inner()); +} + +// ---- members of an entity --------------------------------------------------------- + +struct Member { + id: NodeId, + host: NodeId, + declaring: NodeId, + declared_here: bool, +} + +impl Member { + fn head(&self, tree: &Tree) -> String { + let n = tree.node(self.id); + format!( + "{} '{}' on entity '{}'", + n.type_name, + n.name, + tree.resolution_key(self.declaring) + ) + } + + fn suffix(&self, tree: &Tree) -> String { + if self.declared_here { + String::new() + } else { + format!(" (inherited by '{}')", tree.resolution_key(self.host)) + } + } + + fn fail(&self, env: &Env<'_>, sink: &Sink<'_>, code: &'static str, body: &str) { + let tree = env.tree; + sink.push(self.id, code, &self.head(tree), body, &self.suffix(tree)); + } + + /// The FQN a member message names for `entity`: the declaring entity in place of the host. + fn shown(&self, tree: &Tree, entity: NodeId) -> String { + tree.resolution_key(if entity == self.host { + self.declaring + } else { + entity + }) + } +} + +fn check_entity_members(env: &Env<'_>, entity: NodeId, declared_here: bool, sink: &Sink<'_>) { + let tree = env.tree; + for &id in env.kids(entity).iter() { + let ty = tree.node(id).type_name.as_str(); + if ty != T_DIMENSION && ty != T_MEASURE && ty != T_SEGMENT { + continue; + } + let declaring = tree.node(id).parent.unwrap_or(entity); + if (declaring == entity) != declared_here { + continue; + } + let mc = Member { + id, + host: entity, + declaring, + declared_here, + }; + match ty { + T_DIMENSION => check_dimension(env, &mc, sink), + T_MEASURE => check_measure(env, &mc, sink), + _ => { + if let Some(filter) = object_attr(tree, id, A_FILTER) { + let head = || mc.head(tree); + let suffix = || mc.suffix(tree); + check_filter( + env, + filter, + entity, + &|| tree.resolution_key(declaring), + &head, + id, + &suffix, + sink, + ); + } + } + } + } +} + +/// What a to-one walk resolves against and how its messages name it (D2 vs R8). +enum Walk { + D2 { declaring: NodeId }, + Spine { from: NodeId }, +} + +impl Walk { + fn attr(&self) -> &'static str { + match self { + Walk::D2 { .. } => A_VIA, + Walk::Spine { .. } => A_SPINE, + } + } + fn anchor(&self) -> NodeId { + match self { + Walk::D2 { declaring } => *declaring, + Walk::Spine { from } => *from, + } + } + fn start(&self, tree: &Tree) -> String { + let key = tree.resolution_key(self.anchor()); + match self { + Walk::D2 { .. } => format!("the owning entity '{key}'"), + Walk::Spine { .. } => format!("@from '{key}'"), + } + } + fn start_short(&self, tree: &Tree) -> String { + match self { + Walk::D2 { .. } => "the owning entity".to_string(), + Walk::Spine { .. } => self.start(tree), + } + } + fn to_one_reason(&self) -> &'static str { + match self { + Walk::D2 { .. } => { + "A dimension follows only @cardinality: one relationships and identity.reference hops, so grouping can never multiply the measured rows." + } + Walk::Spine { .. } => { + "A @spine follows only @cardinality: one relationships and identity.reference hops, so each fact row joins at most one row of the spine entity and is never counted twice." + } + } + } +} + +/// Walk `Owner.hop[.hop...]` from `host`; returns the terminal entity, or `None` after +/// reporting the first failure through `err`. +fn walk_to_one( + env: &Env<'_>, + host: NodeId, + via: &str, + err: Err<'_>, + walk: &Walk, +) -> Option { + let tree = env.tree; + let named = format!("@{} '{via}'", walk.attr()); + let name_of = |e: NodeId| tree.resolution_key(if e == host { walk.anchor() } else { e }); + let Some((owner, hops)) = split_dotted(via) else { + err(&format!( + "{named} must be Owner.hop[.hop...], starting at {}.", + walk.start_short(tree) + )); + return None; + }; + let owner = env.resolve_object(owner, &tree.effective_package(walk.anchor())); + if !is_self_or_ancestor(tree, owner, host) { + err(&format!("{named} must start at {}.", walk.start(tree))); + return None; + } + let mut current = host; + for hop_name in hops { + let Some((hop, is_ref)) = env.hop(current, hop_name) else { + err(&format!( + "{named} names '{hop_name}', which is not a relationship or identity.reference of '{}'.", + name_of(current) + )); + return None; + }; + if !is_ref && str_attr(tree, hop, A_CARDINALITY) != Some(CARDINALITY_ONE) { + err(&format!( + "{named} crosses relationship '{hop_name}' on '{}', which is not to-one. {}", + name_of(current), + walk.to_one_reason() + )); + return None; + } + let Some(target) = env.hop_target(hop, is_ref) else { + err(&format!( + "{named} hop '{hop_name}' on '{}' targets no object.", + name_of(current) + )); + return None; + }; + current = target; + } + Some(current) +} + +/// R12: the column an `@of` path names on `entity` (`field`, or `field.member` of a +/// flattened value object). +fn of_column( + env: &Env<'_>, + entity: NodeId, + path: &[&str], + item: &str, + err: Err<'_>, + field_missing: &dyn Fn() -> String, +) -> Option { + let tree = env.tree; + let Some(field) = env.field_of(entity, path[0]) else { + err(&field_missing()); + return None; + }; + let Some(member_name) = path.get(1) else { + return Some(field); + }; + let value_object = if tree.node(field).sub_type == "object" { + env.ref_target_object(field) + } else { + None + }; + let Some(value_object) = value_object else { + err(&format!( + "@of '{item}' names member '{member_name}' of '{}', a field.{} with no value object.", + path[0], + tree.node(field).sub_type + )); + return None; + }; + if !env.is_flattened(field) { + let storage = str_attr(tree, field, A_STORAGE).unwrap_or("jsonb (the default)"); + err(&format!( + "@of '{item}' names a member of '{}', whose value object is stored as {storage}. A report reads a member only under @storage: flattened, where the member has a column of its own.", + path[0] + )); + return None; + } + let member = env.field_of(value_object, member_name); + if member.is_none() { + err(&format!( + "@of '{item}' names no member '{member_name}' on value object '{}'.", + tree.resolution_key(value_object) + )); + } + member +} + +fn has_object_ref(tree: &Tree, field: NodeId) -> bool { + tree.attr(field, A_OBJECT_REF).is_some() +} + +fn check_dimension(env: &Env<'_>, mc: &Member, sink: &Sink<'_>) { + let tree = env.tree; + let dim = mc.id; + let err = |m: &str| mc.fail(env, sink, ERR_INVALID_DIMENSION, &format!(": {m}")); + let mut of_entity = mc.host; + let via = str_attr(tree, dim, A_VIA); + if let Some(via) = via { + match walk_to_one( + env, + mc.host, + via, + &|m| err(m), + &Walk::D2 { + declaring: mc.declaring, + }, + ) { + Some(t) => of_entity = t, + None => return, + } + } + let Some(of) = str_attr(tree, dim, A_OF) else { + return; + }; + let parts = split_dotted(of).filter(|(_, p)| p.len() <= 2); + let Some((owner, path)) = parts else { + err(&format!( + "@of '{of}' must be Entity.field or Entity.field.member." + )); + return; + }; + let owner_pkg = tree.effective_package(if via.is_none() { + mc.declaring + } else { + of_entity + }); + let named = env.resolve_object(owner, &owner_pkg); + if !is_self_or_ancestor(tree, named, of_entity) { + if via.is_none() { + err(&format!( + "@of '{of}' must name a field of the owning entity '{}'. Reach another entity's field with @via.", + tree.resolution_key(mc.declaring) + )); + } else { + err(&format!( + "@of '{of}' must name a field of '{}', the entity @via '{}' reaches.", + mc.shown(tree, of_entity), + via.unwrap_or("") + )); + } + return; + } + let field_name = path[0]; + let lookup = if via.is_none() { + of_entity + } else { + named.unwrap_or(of_entity) + }; + let missing = || { + if lookup != of_entity && env.field_of(of_entity, field_name).is_some() { + format!( + "@of '{of}' names no field '{field_name}' on '{}': only '{}', the entity @via reaches, declares it. Name it '{}.{field_name}'.", + mc.shown(tree, lookup), + mc.shown(tree, of_entity), + tree.node(of_entity).name + ) + } else { + format!( + "@of '{of}' names no field '{field_name}' on '{}'.", + mc.shown(tree, lookup) + ) + } + }; + let Some(field) = of_column(env, lookup, &path, of, &|m| err(m), &missing) else { + return; + }; + let fsub = tree.node(field).sub_type.as_str(); + // D5 — a dimension groups by a scalar. + if fsub == "object" || has_object_ref(tree, field) { + err(&format!( + "@of '{of}' is a field.{fsub}{}, which a report cannot group by. Group by a scalar field of it.", + if has_object_ref(tree, field) { + " with an @objectRef" + } else { + "" + } + )); + return; + } + if !is_time(tree, dim) { + return; + } + if !TEMPORAL.contains(&fsub) { + err(&format!( + "a time dimension's @of must be a field.date or field.timestamp, but '{of}' is field.{fsub}." + )); + return; + } + if fsub == "date" && grains(tree, dim).contains(&GRAIN_HOUR) { + err(&format!( + "grain 'hour' is impossible on '{of}', a field.date (a date has no hour). Remove 'hour' from @grains." + )); + } +} + +fn check_measure(env: &Env<'_>, mc: &Member, sink: &Sink<'_>) { + let tree = env.tree; + let m = mc.id; + let err = |msg: &str| mc.fail(env, sink, ERR_INVALID_MEASURE, &format!(": {msg}")); + let declared_default = tree.attr(m, A_DEFAULT); + let invalid_default = declared_default.is_some_and(|v| !is_integral_number(v)); + let sub = tree.node(m).sub_type.as_str(); + if sub == "ratio" { + check_ratio_operands(env, mc, &err); + return; + } + if sub == S_DERIVED { + check_derived_expr(env, mc, &err); + return; + } + if sub != S_AGGREGATE { + return; + } + let Some(of_field) = check_aggregate_columns(env, mc, &err) else { + return; + }; + if !invalid_default && let Some(d) = declared_default { + let agg = measure_agg(tree, m); + if agg == Some(AGG_COUNT) { + err( + "@default cannot apply to @agg: count. A count is never null (it is 0 when nothing matches); remove @default.", + ); + } else if (agg == Some(AGG_ANY) || agg == Some(AGG_ALL)) + && d.as_f64().is_some_and(|f| f != 0.0 && f != 1.0) + { + err(&format!( + "@default '{}' on @agg '{}' must be 0 (false) or 1 (true): the measure is a boolean.", + js_display(d), + agg.unwrap_or("") + )); + } else if (agg == Some(AGG_MIN) || agg == Some(AGG_MAX)) + && of_field.is_some_and(|f| !NUMERIC.contains(&tree.node(f).sub_type.as_str())) + { + let f = of_field.map_or("", |f| tree.node(f).sub_type.as_str()); + err(&format!( + "@default is a number, but '{}', the @of of @agg '{}', is a field.{f}. A default is supported on numeric measures only.", + of_columns(tree, m).first().copied().unwrap_or(""), + agg.unwrap_or("") + )); + } + } + // M5 — @segment names a segment of the owning entity. + let segment = str_attr(tree, m, A_SEGMENT); + if let Some(seg) = segment + && env.child_of_type(mc.host, T_SEGMENT, seg).is_none() + { + err(&format!( + "@segment '{seg}' names no segment of '{}'.", + tree.resolution_key(mc.declaring) + )); + } + if let Some(filter) = object_attr(tree, m, A_FILTER) { + let head = || mc.head(tree); + let suffix = || mc.suffix(tree); + check_filter( + env, + filter, + mc.host, + &|| tree.resolution_key(mc.declaring), + &head, + m, + &suffix, + sink, + ); + } +} + +/// M0-M4; `None` when one fired, else `Some(single resolved @of field)`. +fn check_aggregate_columns( + env: &Env<'_>, + mc: &Member, + err: &dyn Fn(&str), +) -> Option> { + let tree = env.tree; + let m = mc.id; + let agg = measure_agg(tree, m); + let columns = of_columns(tree, m); + if columns.is_empty() + && let Some(a) = agg + { + { + if a != AGG_ANY && a != AGG_ALL { + err(&format!( + "@agg '{a}' needs @of, the column it aggregates. Only @agg any / all may omit @of, to ask whether some row (any) or every row (all) passes the measure's @filter or @segment." + )); + return None; + } + if object_attr(tree, m, A_FILTER).is_none() && str_attr(tree, m, A_SEGMENT).is_none() { + err(&format!( + "@agg '{a}' without @of quantifies the measure's row condition, but it declares neither @filter nor @segment. Name a field.boolean in @of, or add the condition." + )); + return None; + } + return Some(None); + } + } + let declaring_key = || tree.resolution_key(mc.declaring); + let mut fields = Vec::new(); + for item in &columns { + let parts = split_dotted(item).filter(|(_, p)| p.len() <= 2); + let Some((owner, path)) = parts else { + err(&format!( + "@of '{item}' must be Entity.field or Entity.field.member." + )); + return None; + }; + let named = env.resolve_object(owner, &tree.effective_package(mc.declaring)); + if !is_self_or_ancestor(tree, named, mc.host) { + err(&format!( + "@of '{item}' must name a field of the owning entity '{}'. A measure aggregates its own entity's rows; declare it on the entity that owns the column.", + declaring_key() + )); + return None; + } + let missing = || { + format!( + "@of '{item}' names no field '{}' on '{}'.", + path[0], + declaring_key() + ) + }; + let field = of_column(env, mc.host, &path, item, err, &missing)?; + let fsub = tree.node(field).sub_type.as_str(); + if fsub == "object" || has_object_ref(tree, field) { + err(&format!( + "@of '{item}' is a field.{fsub}{}, which a report cannot aggregate. Aggregate a scalar field of it.", + if has_object_ref(tree, field) { + " with an @objectRef" + } else { + "" + } + )); + return None; + } + fields.push(field); + } + let distinct = tree.attr(m, A_DISTINCT) == Some(&Value::Bool(true)); + if columns.len() > 1 && (agg != Some(AGG_COUNT) || !distinct) { + err(&format!( + "@of lists {} columns; a tuple is legal only with @agg: count and @distinct: true (a distinct count of the tuple).", + columns.len() + )); + return None; + } + if distinct && agg.is_some_and(|a| a != AGG_COUNT) { + err(&format!( + "@distinct: true requires @agg: count, not '{}'.", + agg.unwrap_or("") + )); + return None; + } + let field = if fields.len() == 1 { + Some(fields[0]) + } else { + None + }; + let (Some(field), Some(agg)) = (field, agg) else { + return Some(field); + }; + let item = columns[0]; + let fsub = tree.node(field).sub_type.as_str(); + if (agg == AGG_SUM || agg == AGG_AVG) && !NUMERIC.contains(&fsub) { + err(&format!( + "@agg '{agg}' needs a numeric field (field.int, long, double, float, decimal or currency), but '{item}' is field.{fsub}." + )); + return None; + } + if (agg == AGG_MIN || agg == AGG_MAX) && UNORDERED.contains(&fsub) { + err(&format!( + "@agg '{agg}' cannot order '{item}', a field.{fsub}." + )); + return None; + } + if (agg == AGG_ANY || agg == AGG_ALL) && fsub != "boolean" { + err(&format!( + "@agg '{agg}' needs a field.boolean, but '{item}' is field.{fsub}." + )); + return None; + } + Some(Some(field)) +} + +/// M6 — each operand names a measure.aggregate of the same entity whose result is a number. +fn check_ratio_operands(env: &Env<'_>, mc: &Member, err: &dyn Fn(&str)) { + let tree = env.tree; + for (attr, r) in [ + (A_NUMERATOR, str_attr(tree, mc.id, A_NUMERATOR)), + (A_DENOMINATOR, str_attr(tree, mc.id, A_DENOMINATOR)), + ] { + let Some(r) = r else { + continue; + }; + match env.child_of_type(mc.host, T_MEASURE, r) { + None => err(&format!( + "@{attr} '{r}' names no measure of '{}'.", + tree.resolution_key(mc.declaring) + )), + Some(t) if tree.node(t).sub_type != S_AGGREGATE => err(&format!( + "@{attr} '{r}' is a measure.{}; a ratio's operands must be measure.aggregate (a ratio of ratios is not supported).", + tree.node(t).sub_type + )), + Some(t) => { + if let Some(result) = env.measure_result(t, mc.host) { + if !NUMERIC.contains(&result) { + err(&format!( + "@{attr} '{r}' is a {result} measure; a ratio divides numbers, so its operands must be numeric measures (a count, a sum, an avg, or a min or max of a numeric field)." + )); + } + } + } + } + } +} + +/// M11 — a measure.derived's `@expr` operands. +fn check_derived_expr(env: &Env<'_>, mc: &Member, err: &dyn Fn(&str)) { + let tree = env.tree; + if tree.attr(mc.id, A_EXPR).is_none() { + return; + } + let Some(expr) = measure_expr(tree, mc.id) else { + err(&format!("@expr is not an arithmetic expression. Each node is {{ field: }}, {{ value: }} or {{ fn: {} , args: [, ] }}.", DERIVED_FNS.join(" | ")).replace(" , ", ", ")); + return; + }; + let key = tree.resolution_key(mc.declaring); + let mut names = Vec::new(); + derived_fields(expr, &mut names); + for name in names { + let target = env.child_of_type(mc.host, T_MEASURE, name); + let dim = env.child_of_type(mc.host, T_DIMENSION, name); + match (target, dim) { + (Some(_), Some(_)) => err(&format!( + "@expr names '{name}', which is both a measure and a dimension of '{key}'. Rename one." + )), + (Some(t), None) => { + if tree.node(t).sub_type == S_DERIVED { + err(&format!( + "@expr names '{name}', a measure.derived. A derived measure reads aggregates, ratios and dimensions, not another derived measure." + )); + } else if let Some(result) = env.measure_result(t, mc.host) { + if !NUMERIC.contains(&result) { + err(&format!( + "@expr names measure '{name}', whose result is a {result}, not a number." + )); + } + } + } + (None, Some(d)) => { + if is_time(tree, d) { + err(&format!( + "@expr names '{name}', a dimension.time. Arithmetic reads a numeric attribute dimension." + )); + } else if let Some(f) = env.resolve_dimension_of(d, mc.host) { + let fsub = &tree.node(f).sub_type; + if !NUMERIC.contains(&fsub.as_str()) { + err(&format!( + "@expr names dimension '{name}', whose @of is a field.{fsub}, not a number." + )); + } + } + } + (None, None) => err(&format!( + "@expr names '{name}', which is no measure or dimension of '{key}'." + )), + } + } +} + +// ---- filters (S1 / F2) -------------------------------------------------------------- + +fn is_relative(v: &Value) -> bool { + v.as_object().is_some_and(|o| o.contains_key(NOW)) +} + +fn relative_operand(v: &Value) -> Option<&Map> { + match v { + Value::Array(a) => a.iter().find(|x| is_relative(x)).and_then(Value::as_object), + _ if is_relative(v) => v.as_object(), + _ => None, + } +} + +fn operand_contains_relative(v: &Value) -> bool { + if is_relative(v) { + return true; + } + match v { + Value::Array(a) => a.iter().any(operand_contains_relative), + Value::Object(o) => o.values().any(operand_contains_relative), + _ => false, + } +} + +fn filter_contains_relative(filter: &Value) -> bool { + let Some(o) = filter.as_object() else { + return false; + }; + for (key, clause) in o { + if key == "or" || key == "and" { + if clause + .as_array() + .is_some_and(|a| a.iter().any(filter_contains_relative)) + { + return true; + } + continue; + } + if is_relative(clause) { + return true; + } + if clause + .as_object() + .is_some_and(|c| c.values().any(operand_contains_relative)) + { + return true; + } + } + false +} + +fn quote_value(v: Option<&Value>) -> String { + match v { + Some(Value::String(s)) => s.clone(), + Some(other) => other.to_string(), + None => "undefined".to_string(), + } +} + +/// F2 — why a relative-date operand under `op` on `key` is refused. +fn relative_date_problem( + key: &str, + op: &str, + rel: &Map, + sub: Option<&str>, +) -> Option { + if !rel.keys().all(|k| k == NOW || k == START_OF) { + return Some(format!( + "@filter on '{key}' has a malformed relative date {}; a relative date is {{ now: \"\" }} with an optional startOf, and no other keys.", + Value::Object(rel.clone()) + )); + } + if let Some(sub) = sub { + if !TEMPORAL.contains(&sub) { + return Some(format!( + "@filter on '{key}' uses a relative date ({{ now: ... }}), but '{key}' is field.{sub}; relative dates apply only to field.date and field.timestamp." + )); + } + } + if !RELATIVE_OPS.contains(&op) { + return Some(format!( + "@filter on '{key}' puts a relative date under op '{op}'; relative dates are legal only under gt, gte, lt and lte." + )); + } + let duration = rel.get(NOW); + if !duration + .and_then(Value::as_str) + .is_some_and(is_iso_duration) + { + return Some(format!( + "@filter on '{key}' has relative date '{}', which is not an ISO-8601 duration (e.g. '-P7D', '-PT12H').", + quote_value(duration) + )); + } + if let Some(s) = rel.get(START_OF) { + if !s.as_str().is_some_and(|s| START_OF_UNITS.contains(&s)) { + return Some(format!( + "@filter on '{key}' has startOf '{}'; startOf is one of {}.", + quote_value(Some(s)), + START_OF_UNITS.join(", ") + )); + } + } + None +} + +#[allow(clippy::too_many_arguments)] +fn check_filter( + env: &Env<'_>, + filter: &Map, + entity: NodeId, + entity_key: &dyn Fn() -> String, + head: &dyn Fn() -> String, + host: NodeId, + suffix: &dyn Fn() -> String, + sink: &Sink<'_>, +) { + let tree = env.tree; + let err = |m: &str| { + sink.push( + host, + ERR_BAD_ATTR_FILTER, + &head(), + &format!(": {m}"), + &suffix(), + ) + }; + for (key, clause) in filter { + if key == "or" || key == "and" { + let Some(arr) = clause.as_array() else { + err(&format!("@filter '{key}' must be an array of sub-clauses.")); + continue; + }; + for sub in arr { + match sub.as_object() { + Some(o) => check_filter(env, o, entity, entity_key, head, host, suffix, sink), + None => err(&format!( + "@filter '{key}' contains a non-object sub-clause." + )), + } + } + continue; + } + let Some(field) = env.field_of(entity, key) else { + err(&format!( + "@filter names '{key}', which is not a field of '{}'.", + entity_key() + )); + continue; + }; + let Some(clause) = clause.as_object().filter(|c| !c.is_empty()) else { + err(&format!( + "@filter on '{key}' must be an {{ op: value }} object." + )); + continue; + }; + let allowed = ops_for_field(tree, field); + let fsub = tree.node(field).sub_type.as_str(); + for (op, operand) in clause { + if !allowed.contains(&op.as_str()) { + let list = if allowed.is_empty() { + "(none)".to_string() + } else { + allowed.join(", ") + }; + err(&format!( + "@filter on '{key}' uses op '{op}', which is not allowed for field.{fsub}. Allowed ops: {list}." + )); + continue; + } + if let Some(rel) = relative_operand(operand) { + if let Some(p) = relative_date_problem(key, op, rel, Some(fsub)) { + err(&p); + } + } + } + } +} + +// ---- object.report (R1-R13) -------------------------------------------------------- + +fn dimension_items(tree: &Tree, report: NodeId) -> Vec<(&str, Option<&str>)> { + string_list(tree.attr(report, A_DIMENSIONS)) + .into_iter() + .map(|raw| match raw.find(':') { + None => (raw, None), + Some(i) => (&raw[..i], Some(&raw[i + 1..])), + }) + .collect() +} + +fn derived_field_name(name: &str, grain: Option<&str>) -> String { + match grain { + None | Some("") => name.to_string(), + Some(g) => { + let mut c = g.chars(); + let first: String = c + .next() + .map(|f| f.to_uppercase().collect()) + .unwrap_or_default(); + format!("{name}{first}{}", c.as_str()) + } + } +} + +fn is_writable(tree: &Tree, source: NodeId) -> bool { + !READ_ONLY_KINDS.contains(&effective_kind(tree, source)) +} + +fn effective_kind(tree: &Tree, source: NodeId) -> &str { + str_attr(tree, source, A_KIND).unwrap_or(KIND_TABLE) +} + +fn check_report(env: &Env<'_>, report: NodeId, sink: &Sink<'_>) { + let tree = env.tree; + let label = format!("report '{}'", tree.resolution_key(report)); + let err_at = + |node: NodeId, code: &'static str, body: &str| sink.push(node, code, &label, body, ""); + let err = |body: &str| err_at(report, ERR_INVALID_REPORT, body); + + // R4 — ADR-0039 own: the rule is about what the author declared on THIS report. + for &child in tree.own_children(report) { + let ty = tree.node(child).type_name.as_str(); + if ty == T_FIELD || ty == T_IDENTITY { + err_at( + child, + ERR_INVALID_REPORT, + &format!( + " declares {}; a report's fields and identity are derived from @dimensions and @measures, never declared.", + child_label(tree, child) + ), + ); + } + } + // R5 / R10 — ADR-0039 resolving: an inherited source binds the report just the same. + let kids = env.kids(report); + let sources: Vec = kids + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == T_SOURCE) + .collect(); + for &s in &sources { + if is_writable(tree, s) { + err_at( + s, + ERR_INVALID_REPORT, + &format!( + ": {} is writable; a report is read-only, so its source must declare a read-only @kind (view, materializedView, storedProc or tableFunction).", + child_label(tree, s) + ), + ); + } + } + for &s in &sources { + if !is_writable(tree, s) && effective_kind(tree, s) != KIND_VIEW { + err_at( + s, + ERR_INVALID_REPORT, + &format!( + ": {} has @kind '{}'; a report is read through a view, so its source must be @kind: view. For a view or materialized view you create yourself, declare @kind: view with @unmanaged: true.", + child_label(tree, s), + effective_kind(tree, s) + ), + ); + } + } + // R11 + if tree.node(report).is_abstract { + err( + ": is abstract; a report cannot be abstract, because its fields are derived from its own @dimensions and @measures and no port reads or serves an abstract report. Remove abstract: true.", + ); + } + // R1 + let Some(from_ref) = str_attr(tree, report, A_FROM) else { + return; + }; + let pkg = tree.effective_package(report); + let Some(from) = env.resolve_object(from_ref, &pkg) else { + err(&format!( + ": @from '{from_ref}' does not resolve to an object." + )); + return; + }; + let fnode = tree.node(from); + if fnode.type_name != T_OBJECT || fnode.sub_type != S_ENTITY { + err(&format!( + ": @from '{from_ref}' is an {}.{}; a report aggregates the rows of an object.entity.", + fnode.type_name, fnode.sub_type + )); + return; + } + let from_key = tree.resolution_key(from); + + // R6 bookkeeping + let mut derived: HashMap = HashMap::new(); + let mut claim = |field_name: String, what: String| match derived.get(&field_name) { + Some(prior) if *prior == what => { + err(&format!(": @measures lists '{field_name}' more than once.")) + } + Some(prior) => err(&format!( + ": {prior} and {what} both derive report field '{field_name}'. Report field names must be unique; rename the measure or drop one item." + )), + None => { + derived.insert(field_name, what); + } + }; + + // R2 + let items = dimension_items(tree, report); + let mut seen_items: HashSet = HashSet::new(); + for &(name, grain) in &items { + let raw = match grain { + None => name.to_string(), + Some(g) => format!("{name}:{g}"), + }; + if !seen_items.insert(raw.clone()) { + err(&format!(": @dimensions lists '{raw}' more than once.")); + continue; + } + let Some(dim) = env.child_of_type(from, T_DIMENSION, name) else { + err(&format!( + ": @dimensions item '{raw}' names no dimension of @from '{from_key}'." + )); + continue; + }; + if is_time(tree, dim) { + let gs = grains(tree, dim); + match grain { + None => { + err(&format!( + ": @dimensions item '{raw}' names time dimension '{name}' without a grain; write '{name}:' with a grain from its @grains ({}).", + gs.join(", ") + )); + continue; + } + Some(g) if !gs.contains(&g) => { + err(&format!( + ": @dimensions item '{raw}' uses grain '{g}', which time dimension '{name}' does not declare. Its @grains: {}.", + gs.join(", ") + )); + continue; + } + Some(_) => {} + } + } else if grain.is_some() { + err(&format!( + ": @dimensions item '{raw}' gives a grain to attribute dimension '{name}'; only a time dimension takes a grain." + )); + continue; + } + claim( + derived_field_name(name, grain), + format!("dimension item '{raw}'"), + ); + } + + // R3 + let measure_items = string_list(tree.attr(report, A_MEASURES)); + for item in &measure_items { + if let Some(name) = check_report_measure(env, report, from, item, &label, sink) { + claim(name.to_string(), format!("measure '{name}'")); + } + } + + // R12 / R13 + check_value_object_units(env, &items, &measure_items, from, &err); + check_derived_dimensions(env, &items, &measure_items, from, &err); + + // R7 + if let Some(seg) = str_attr(tree, report, A_SEGMENT) { + if env.child_of_type(from, T_SEGMENT, seg).is_none() { + err(&format!( + ": @segment '{seg}' names no segment of @from '{from_key}'." + )); + } + } + + // R8 / R9 + let spine = str_attr(tree, report, A_SPINE).filter(|s| !s.is_empty()); + if let Some(spine) = spine { + let terminal = walk_to_one( + env, + from, + spine, + &|m| err(&format!(": {m}")), + &Walk::Spine { from }, + ); + if let Some(terminal) = terminal { + let spine_hops = split_dotted(spine).map(|(_, p)| p).unwrap_or_default(); + if items.is_empty() { + err(&format!( + ": @spine '{spine}' needs at least one dimension. The report's rows are the dimension tuples of '{}'; with no dimension it would be one totals row.", + tree.resolution_key(terminal) + )); + } + let mut checked: HashSet<&str> = HashSet::new(); + for &(name, _) in &items { + if !checked.insert(name) { + continue; + } + let Some(dim) = env.child_of_type(from, T_DIMENSION, name) else { + continue; + }; + let Some(via) = str_attr(tree, dim, A_VIA) else { + err(&format!( + ": dimension '{name}' is read from @from '{from_key}', so it has no value in a row that has no facts. With @spine '{spine}' every dimension must be reached through it: declare the dimension over a field of '{}' (or an entity to-one from it) with an @via that begins '{spine}'.", + tree.resolution_key(terminal) + )); + continue; + }; + let discard = |_: &str| {}; + let walk = Walk::D2 { + declaring: tree.node(dim).parent.unwrap_or(from), + }; + if walk_to_one(env, from, via, &discard, &walk).is_none() { + continue; + } + let hops = split_dotted(via).map(|(_, p)| p).unwrap_or_default(); + if spine_hops + .iter() + .enumerate() + .all(|(i, h)| hops.get(i) == Some(h)) + { + continue; + } + err(&format!( + ": dimension '{name}' is reached by @via '{via}', which does not begin with the hops of @spine '{spine}'. Hop names are compared as written: if both name the same join, write the same hops; otherwise the dimension is not reached through the spine." + )); + } + } + } + + // S1 / F2 + if let Some(filter) = object_attr(tree, report, A_FILTER) { + let key = || from_key.clone(); + check_filter( + env, + filter, + from, + &key, + &|| label.clone(), + report, + &String::new, + sink, + ); + } +} + +fn item_name(item: &str) -> &str { + item.rfind('.').map_or(item, |i| &item[i + 1..]) +} + +fn check_report_measure<'a>( + env: &Env<'_>, + report: NodeId, + from: NodeId, + item: &'a str, + label: &str, + sink: &Sink<'_>, +) -> Option<&'a str> { + let tree = env.tree; + let from_key = tree.resolution_key(from); + let mut owner: Option; + let parts = split_dotted(item); + match parts { + Some((o, path)) if path.len() == 1 => { + owner = env.resolve_object(o, &tree.effective_package(report)); + let name = path[0]; + if is_self_or_ancestor(tree, owner, from) + && env.child_of_type(from, T_MEASURE, name).is_some() + { + return Some(name); + } + if let Some(ow) = owner { + if env.child_of_type(ow, T_MEASURE, name).is_none() { + owner = None; + } + } + } + _ if !item.contains('.') => { + if env.child_of_type(from, T_MEASURE, item).is_some() { + return Some(item); + } + owner = env.objects().find(|&o| { + tree.node(o).sub_type == S_ENTITY && env.child_of_type(o, T_MEASURE, item).is_some() + }); + } + _ => owner = None, + } + match owner { + Some(ow) => { + let owner_key = tree.resolution_key(ow); + sink.push(report, ERR_REPORT_FOREIGN_MEASURE, label, &format!(" lists measure '{}', which belongs to '{owner_key}', not @from '{from_key}'. All measures of a report come from @from; make a second report over '{owner_key}'.", item_name(item)), ""); + } + None => sink.push(report, ERR_INVALID_REPORT, label, &format!(": @measures item '{item}' names no measure of @from '{from_key}' or of any other entity."), ""), + } + None +} + +/// The measures `listed` aggregates through (itself; a ratio's operands; a derived +/// measure's named operands, ratios read through theirs). +fn aggregates_read(env: &Env<'_>, listed: NodeId, from: NodeId) -> Vec { + let tree = env.tree; + let measure = |n: &str| env.child_of_type(from, T_MEASURE, n); + let operands_of = |m: Option, out: &mut Vec| { + let Some(m) = m else { + return; + }; + if tree.node(m).sub_type == "ratio" { + out.extend(str_attr(tree, m, A_NUMERATOR).and_then(measure)); + out.extend(str_attr(tree, m, A_DENOMINATOR).and_then(measure)); + } else { + out.push(m); + } + }; + let mut out = Vec::new(); + if tree.node(listed).sub_type == S_DERIVED { + if let Some(expr) = measure_expr(tree, listed) { + let mut names = Vec::new(); + derived_fields(expr, &mut names); + for n in names { + operands_of(measure(n), &mut out); + } + } + } else { + operands_of(Some(listed), &mut out); + } + out +} + +/// R12 — amounts in different units are never combined. +fn check_value_object_units( + env: &Env<'_>, + items: &[(&str, Option<&str>)], + measure_items: &[&str], + from: NodeId, + err: &dyn Fn(&str), +) { + let tree = env.tree; + let mut grouped: HashSet = HashSet::new(); + for &(name, _) in items { + let Some(dim) = env.child_of_type(from, T_DIMENSION, name) else { + continue; + }; + if is_time(tree, dim) || str_attr(tree, dim, A_VIA).is_some() { + continue; + } + if let Some((_, path)) = split_dotted(str_attr(tree, dim, A_OF).unwrap_or("")) { + if path.len() == 2 { + grouped.insert(path.join(".")); + } + } + } + let mut checked: HashSet = HashSet::new(); + for item in measure_items { + let Some(listed) = env.child_of_type(from, T_MEASURE, item_name(item)) else { + continue; + }; + for m in aggregates_read(env, listed, from) { + if tree.node(m).sub_type != S_AGGREGATE || !checked.insert(m) { + continue; + } + let agg = measure_agg(tree, m); + if !matches!(agg, Some(AGG_SUM | AGG_AVG | AGG_MIN | AGG_MAX)) { + continue; + } + let of = of_columns(tree, m).first().copied().unwrap_or(""); + let Some((owner, path)) = split_dotted(of) else { + continue; + }; + if path.len() != 2 { + continue; + } + let (field_name, member_name) = (path[0], path[1]); + let Some(field) = env.field_of(from, field_name) else { + continue; + }; + if !env.is_flattened(field) { + continue; + } + let Some(vo) = env.ref_target_object(field) else { + continue; + }; + let Some(member) = env.field_of(vo, member_name) else { + continue; + }; + if !NUMERIC.contains(&tree.node(member).sub_type.as_str()) { + continue; + } + // ADR-0039: resolving — a unit member the value object inherits qualifies too. + for &unit in env.kids(vo).iter() { + let u = tree.node(unit); + if u.type_name != T_FIELD + || NUMERIC.contains(&u.sub_type.as_str()) + || grouped.contains(&format!("{field_name}.{}", u.name)) + { + continue; + } + err(&format!( + ": measure '{}' takes @agg '{}' of '{of}', a member of value object '{}', but the report does not group by its member '{}', so amounts with different '{}' values would be combined. List an attribute dimension of @from whose @of is '{owner}.{field_name}.{}'.", + tree.node(m).name, + agg.unwrap_or(""), + tree.resolution_key(vo), + u.name, + u.name, + u.name + )); + } + } + } +} + +/// R13 — a derived measure reads only dimensions the report groups by. +fn check_derived_dimensions( + env: &Env<'_>, + items: &[(&str, Option<&str>)], + measure_items: &[&str], + from: NodeId, + err: &dyn Fn(&str), +) { + let tree = env.tree; + let listed: HashSet<&str> = items.iter().map(|&(n, _)| n).collect(); + for item in measure_items { + let Some(m) = env.child_of_type(from, T_MEASURE, item_name(item)) else { + continue; + }; + if tree.node(m).sub_type != S_DERIVED { + continue; + } + let Some(expr) = measure_expr(tree, m) else { + continue; + }; + let mut names = Vec::new(); + derived_fields(expr, &mut names); + for name in names { + if listed.contains(name) + || env.child_of_type(from, T_MEASURE, name).is_some() + || env.child_of_type(from, T_DIMENSION, name).is_none() + { + continue; + } + err(&format!( + ": measure '{}' reads dimension '{name}', which @dimensions does not list. A derived measure reads a dimension's value for each group, so the report must group by it.", + tree.node(m).name + )); + } + } +} + +// ---- F1: relative-date values only on reporting hosts ------------------------------ + +fn is_reporting_filter_host(tree: &Tree, id: NodeId) -> bool { + let n = tree.node(id); + n.type_name == T_SEGMENT + || (n.type_name == T_MEASURE && n.sub_type == S_AGGREGATE) + || (n.type_name == T_OBJECT && n.sub_type == S_REPORT) +} + +fn is_relative_view_host(tree: &Tree, id: NodeId) -> bool { + let n = tree.node(id); + (n.type_name == T_OBJECT && n.sub_type == S_PROJECTION) + || (n.type_name == T_ORIGIN && (n.sub_type == S_FIRST || n.sub_type == S_AGGREGATE)) +} + +fn check_relative_shapes( + env: &Env<'_>, + filter: &Value, + host: NodeId, + target: Option, + sink: &Sink<'_>, +) { + let Some(o) = filter.as_object() else { + return; + }; + for (key, clause) in o { + if key == "or" || key == "and" { + if let Value::Array(a) = clause { + for sub in a { + check_relative_shapes(env, sub, host, target, sink); + } + } + continue; + } + let Some(c) = clause.as_object() else { + continue; + }; + for (op, operand) in c { + let Some(rel) = relative_operand(operand) else { + continue; + }; + let sub = target + .and_then(|t| env.field_of(t, key)) + .map(|f| env.tree.node(f).sub_type.as_str()); + if let Some(p) = relative_date_problem(key, op, rel, sub) { + sink.push( + host, + ERR_BAD_ATTR_FILTER, + &node_label(env.tree, host), + &format!(": {p}"), + "", + ); + } + } + } +} + +fn check_no_relative_dates(env: &Env<'_>, node: NodeId, sink: &Sink<'_>) { + let tree = env.tree; + if is_relative_view_host(tree, node) { + let target = if tree.node(node).type_name == T_ORIGIN { + env.index.origin_filter_entity(tree, node) + } else { + Some(node) + }; + // ADR-0039 own: only locally declared filters are lowered (origin.* never inherits). + for (_, attr) in tree.own_attrs(node) { + if attr.sub_type == ATTR_SUBTYPE_FILTER { + check_relative_shapes(env, &attr.value, node, target, sink); + } + } + } else if !is_reporting_filter_host(tree, node) { + // ADR-0039 own: the walk visits every declared node once, at its declaration. + for (name, attr) in tree.own_attrs(node) { + if attr.sub_type == ATTR_SUBTYPE_FILTER && filter_contains_relative(&attr.value) { + sink.push(node, ERR_BAD_ATTR_FILTER, &node_label(tree, node), &format!(": @{name} uses a relative date ({{ now: ... }}), which is legal only in the @filter of a segment, measure.aggregate, object.report, object.projection, origin.aggregate or origin.first."), ""); + } + } + } + // ADR-0039 own: a tree walk; each declared node is visited once, at its declaration. + for &child in tree.own_children(node) { + check_no_relative_dates(env, child, sink); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_code_is_in_the_shared_catalogue() { + let raw = include_str!("../../../../../fixtures/conformance/ERROR-CODES.json"); + let doc: Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for c in [ + ERR_INVALID_DIMENSION, + ERR_INVALID_MEASURE, + ERR_INVALID_REPORT, + ERR_REPORT_FOREIGN_MEASURE, + ERR_BAD_ATTR_FILTER, + ] { + assert!(codes.contains_key(c), "{c} is not in ERROR-CODES.json"); + } + } + + #[test] + fn iso_duration_matches_the_reference_pattern() { + for ok in ["-P7D", "P1Y2M", "-PT12H", "+P1W", "P1DT1H30M5S"] { + assert!(is_iso_duration(ok), "{ok}"); + } + for bad in [ + "P", "PT", "P1YT", "7D", "-P1H", "P1D1Y", "P1.5D", "PT1H1D", "", + ] { + assert!(!is_iso_duration(bad), "{bad}"); + } + } + + #[test] + fn derived_field_names_capitalise_the_grain() { + assert_eq!(derived_field_name("placed", Some("day")), "placedDay"); + assert_eq!(derived_field_name("region", None), "region"); + } + + #[test] + fn split_dotted_splits_after_the_last_package_separator() { + assert_eq!( + split_dotted("a::b::P.x.y"), + Some(("a::b::P", vec!["x", "y"])) + ); + assert_eq!(split_dotted("P"), None); + assert_eq!(split_dotted("P.x."), None); + } +} diff --git a/server/rust/metaobjects/src/validate/structure.rs b/server/rust/metaobjects/src/validate/structure.rs new file mode 100644 index 0000000000..3b0903f052 --- /dev/null +++ b/server/rust/metaobjects/src/validate/structure.rs @@ -0,0 +1,801 @@ +//! Structural validation: subtype rules, `maxOccurs`, projection identity +//! pass-through, identity sequences and TPH discriminators. +//! +//! Ports of `subtype-rules.ts`, `validate-max-occurs.ts`, +//! `core/identity/validate-identity-passthrough.ts`, `validateIdentitySequence` +//! (`loader/validation-passes.ts`) and `core/object/validate-discriminator.ts`. + +use std::collections::HashMap; + +use serde_json::Value; + +use crate::errors::{MetaError, WARN_LEGACY}; +use crate::json::{js_display, js_number}; +use crate::node::{NodeId, Tree}; +use crate::source::ErrorSource; +use crate::validate::util::error_at; +use crate::validate::{Ctx, Findings}; + +pub const ERR_IDENTITY_NAME_REQUIRED: &str = "ERR_IDENTITY_NAME_REQUIRED"; +pub const ERR_SUBTYPE_RULE_VIOLATION: &str = "ERR_SUBTYPE_RULE_VIOLATION"; +pub const ERR_PROJECTION_INHERITED_SOURCE: &str = "ERR_PROJECTION_INHERITED_SOURCE"; +pub const ERR_PROJECTION_SOURCE_WRITABLE: &str = "ERR_PROJECTION_SOURCE_WRITABLE"; +pub const ERR_TOO_MANY_OCCURRENCES: &str = "ERR_TOO_MANY_OCCURRENCES"; +pub const ERR_PROJECTION_IDENTITY_NOT_EXTENDED: &str = "ERR_PROJECTION_IDENTITY_NOT_EXTENDED"; +pub const ERR_IDENTITY_KEY_MISMATCH: &str = "ERR_IDENTITY_KEY_MISMATCH"; +pub const ERR_SEQUENCE_WITHOUT_INCREMENT: &str = "ERR_SEQUENCE_WITHOUT_INCREMENT"; +pub const ERR_SEQUENCE_START_OUT_OF_RANGE: &str = "ERR_SEQUENCE_START_OUT_OF_RANGE"; +pub const ERR_DISCRIMINATOR_FIELD_NOT_FOUND: &str = "ERR_DISCRIMINATOR_FIELD_NOT_FOUND"; +pub const ERR_DISCRIMINATOR_VALUE_DUPLICATE: &str = "ERR_DISCRIMINATOR_VALUE_DUPLICATE"; +pub const ERR_DISCRIMINATOR_VALUE_MISSING: &str = "ERR_DISCRIMINATOR_VALUE_MISSING"; +pub const ERR_DISCRIMINATOR_VALUE_TYPE_MISMATCH: &str = "ERR_DISCRIMINATOR_VALUE_TYPE_MISMATCH"; + +const TYPE_OBJECT: &str = "object"; +const TYPE_IDENTITY: &str = "identity"; +const TYPE_SOURCE: &str = "source"; +const TYPE_FIELD: &str = "field"; +const SUB_ENTITY: &str = "entity"; +const SUB_VALUE: &str = "value"; +const SUB_PROJECTION: &str = "projection"; +const SUB_PRIMARY: &str = "primary"; +const SUB_REFERENCE: &str = "reference"; +const ATTR_FIELDS: &str = "fields"; +const ATTR_ENFORCE: &str = "enforce"; +const ATTR_KIND: &str = "kind"; +const ATTR_GENERATION: &str = "generation"; +const ATTR_SEQUENCE_START: &str = "sequenceStart"; +const ATTR_SEQUENCE_NAME: &str = "sequenceName"; +const ATTR_DISCRIMINATOR: &str = "discriminator"; +const ATTR_DISCRIMINATOR_VALUE: &str = "discriminatorValue"; +const ATTR_VALUES: &str = "values"; +const DEFAULT_SOURCE_KIND: &str = "table"; +const READ_ONLY_KINDS: &[&str] = &["view", "materializedView", "storedProc", "tableFunction"]; +const GENERATION_INCREMENT: &str = "increment"; +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 { + let mut out = Vec::with_capacity(tree.len()); + let mut stack = vec![root]; + while let Some(id) = stack.pop() { + out.push(id); + // ADR-0039: own: a structural walk visits every physical node once at its site. + stack.extend(tree.own_children(id).iter().rev().copied()); + } + out +} + +fn is(tree: &Tree, id: NodeId, type_name: &str, sub_type: &str) -> bool { + let n = tree.node(id); + n.type_name == type_name && n.sub_type == sub_type +} + +fn is_type(tree: &Tree, id: NodeId, type_name: &str) -> bool { + tree.node(id).type_name == type_name +} + +/// The effective `@kind` of a source node (resolving; `table` when unset). +fn effective_kind(tree: &Tree, id: NodeId) -> &str { + match tree.attr(id, ATTR_KIND) { + Some(Value::String(s)) if !s.is_empty() => s, + _ => DEFAULT_SOURCE_KIND, + } +} + +// ---- subtype rules --------------------------------------------------------- + +/// `validateSubtypeRules`: value purity, entity identity, projection licensing and +/// named identities. Warnings are the reference's legacy strings. +pub fn subtype_rules(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for id in preorder(tree, ctx.root) { + let node = tree.node(id); + if node.type_name == TYPE_IDENTITY && node.name.is_empty() { + let owner = node.parent.map(|p| tree.node(p).fqn()); + let at = match owner.as_deref() { + Some(o) if !o.is_empty() => format!(" under '{o}'"), + _ => String::new(), + }; + out.errors.push(error_at( + tree, + id, + ERR_IDENTITY_NAME_REQUIRED, + format!( + "identity.{}{at} has no name — identity nodes require an author-chosen name (e.g. \"id\") so dotted extends refs can address them (FR-024)", + node.sub_type + ), + )); + } + if node.type_name == TYPE_OBJECT { + match node.sub_type.as_str() { + SUB_VALUE => value_purity(tree, id, out), + SUB_ENTITY => entity_identity(tree, id, out), + SUB_PROJECTION => projection_licensing(tree, id, out), + _ => {} + } + } + } +} + +fn value_purity(tree: &Tree, id: NodeId, out: &mut Findings) { + let fqn = tree.node(id).fqn(); + for &child in tree.children(id).iter() { + let c = tree.node(child); + if c.type_name == TYPE_IDENTITY { + if c.sub_type == SUB_REFERENCE { + // ADR-0046: a navigation-only reference is the sanctioned exception. + if tree.attr(child, ATTR_ENFORCE) == Some(&Value::Bool(false)) { + continue; + } + out.errors.push(error_at( + tree, + child, + ERR_SUBTYPE_RULE_VIOLATION, + format!( + "value object '{fqn}' has an enforced reference (identity.{} '{}') — a value is not persisted and has no table to hold a physical FK; declare a navigation-only reference with @enforce: false (FR-024, ADR-0028, ADR-0046)", + c.sub_type, c.name + ), + )); + continue; + } + out.errors.push(error_at( + tree, + child, + ERR_SUBTYPE_RULE_VIOLATION, + format!( + "value object '{fqn}' must not have an identity (identity.{} '{}') — value objects are pure data shapes; use subType: \"entity\" for records with identity (FR-024, ADR-0028)", + c.sub_type, c.name + ), + )); + } else if c.type_name == TYPE_SOURCE { + out.errors.push(error_at( + tree, + child, + ERR_SUBTYPE_RULE_VIOLATION, + format!( + "value object '{fqn}' must not have a source (source.{}) — value objects are not persisted shapes; use subType: \"entity\" or \"projection\" for stored objects (FR-024, ADR-0028)", + c.sub_type + ), + )); + } + } +} + +fn entity_identity(tree: &Tree, id: NodeId, out: &mut Findings) { + let node = tree.node(id); + if node.is_abstract { + return; + } + let has_primary = tree + .children(id) + .iter() + .any(|&c| is(tree, c, TYPE_IDENTITY, SUB_PRIMARY)); + if !has_primary { + out.warnings.push(MetaError::at( + WARN_LEGACY, + format!( + "entity object '{}' has no primary identity (add an identity child or mark @isAbstract: true)", + node.fqn() + ), + ErrorSource::Code, + )); + } +} + +fn projection_licensing(tree: &Tree, id: NodeId, out: &mut Findings) { + let node = tree.node(id); + let fqn = node.fqn(); + let sup = node.super_node; + if let Some(s) = sup + && !is(tree, s, TYPE_OBJECT, SUB_PROJECTION) + { + let sn = tree.node(s); + out.errors.push(error_at( + tree, + id, + ERR_SUBTYPE_RULE_VIOLATION, + format!( + "projection '{fqn}' extends '{}' which is {}.{} — a projection may only extend another projection (FR-024, ADR-0028)", + sn.fqn(), + sn.type_name, + sn.sub_type + ), + )); + } + let super_is_legal = sup.is_none_or(|s| is(tree, s, TYPE_OBJECT, SUB_PROJECTION)); + if !node.is_abstract && super_is_legal { + // ADR-0039: own: the count of sources the projection declares itself, against + // the effective count, finds the ones it inherits. + let own_count = tree + .own_children(id) + .iter() + .filter(|&&c| is_type(tree, c, TYPE_SOURCE)) + .count(); + let effective = tree.children(id); + let mut sources = effective.iter().filter(|&&c| is_type(tree, c, TYPE_SOURCE)); + let total = sources.clone().count(); + if total > own_count { + let sub = sources + .nth(own_count) + .map_or(node.sub_type.as_str(), |&s| tree.node(s).sub_type.as_str()); + out.errors.push(error_at( + tree, + id, + ERR_PROJECTION_INHERITED_SOURCE, + format!( + "projection '{fqn}' inherits a source (source.{sub}) through extends instead of declaring its own — a projection's extends is shape lineage, not a shared-storage hierarchy. Declare the source on this projection; an abstract projection base carries shape only (FR-024, ADR-0028)" + ), + )); + } + } + // ADR-0039: own: OWN sources only; an inherited source is validated where declared. + for &child in tree.own_children(id) { + if !is_type(tree, child, TYPE_SOURCE) { + continue; + } + let kind = effective_kind(tree, child); + if !READ_ONLY_KINDS.contains(&kind) { + out.errors.push(error_at( + tree, + child, + ERR_PROJECTION_SOURCE_WRITABLE, + format!( + "projection '{fqn}' has a writable source (@kind \"{kind}\") — a projection is a derived read-only representation; its sources must be read-only kinds (view, materializedView, storedProc, tableFunction) (FR-024, ADR-0028)" + ), + )); + } + } +} + +// ---- maxOccurs --------------------------------------------------------------- + +/// `validateMaxOccurs`: a type's `maxOccurs` against the children one node declares. +pub fn max_occurs(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + let mut limits: HashMap<(&str, &str), Option> = HashMap::new(); + for id in preorder(tree, ctx.root) { + // ADR-0039: own: maxOccurs constrains the declared layer; inherited children + // were counted at their declaring parent. + let children = tree.own_children(id); + if children.len() < 2 { + // One child exceeds only a limit of zero, which no type declares. + continue; + } + let mut groups: Vec<((&str, &str), Vec)> = Vec::new(); + let mut index: HashMap<(&str, &str), usize> = HashMap::new(); + for &c in children { + let n = tree.node(c); + let key = (n.type_name.as_str(), n.sub_type.as_str()); + match index.get(&key) { + Some(&i) => groups[i].1.push(c), + None => { + index.insert(key, groups.len()); + groups.push((key, vec![c])); + } + } + } + for ((t, s), group) in groups { + let max = *limits + .entry((t, s)) + .or_insert_with(|| ctx.registry.find(t, s).and_then(|d| d.max_occurs)); + let Some(max) = max else { continue }; + let Ok(limit) = usize::try_from(max) else { + continue; + }; + if group.len() > limit { + let name = &tree.node(id).name; + let owner = if name.is_empty() { + String::new() + } else { + format!(" under '{name}'") + }; + out.errors.push(error_at( + tree, + group[limit], + ERR_TOO_MANY_OCCURRENCES, + format!( + "{t}.{s} appears {} times{owner} but at most {max} is allowed", + group.len() + ), + )); + } + } + } +} + +// ---- projection identity pass-through --------------------------------------- + +/// An identity's `@fields` as a list: an array, or a comma string. +fn normalize_fields(raw: Option<&Value>) -> Option> { + match raw? { + Value::Array(items) => Some( + items + .iter() + .map(|v| js_display(v).trim().to_string()) + .collect(), + ), + Value::String(s) => Some( + s.split(',') + .map(str::trim) + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect(), + ), + _ => None, + } +} + +fn extends_chain_reaches(tree: &Tree, node: NodeId, target: NodeId) -> bool { + let mut cur = tree.node(node).super_node; + let mut hops = 0; + while let Some(c) = cur { + if c == target { + return true; + } + hops += 1; + if hops > tree.len() { + return false; + } + cur = tree.node(c).super_node; + } + false +} + +struct Passthrough { + entity: NodeId, + computed: Vec, + missing: Vec, +} + +fn resolve_passthrough(tree: &Tree, identity: NodeId) -> Option { + let extended = tree.node(identity).super_node?; + if !is_type(tree, extended, TYPE_IDENTITY) { + return None; + } + let entity = tree.node(extended).parent?; + if !is_type(tree, entity, TYPE_OBJECT) { + return None; + } + let owner = tree.node(identity).parent?; + let extended_fields = normalize_fields(tree.attr(extended, ATTR_FIELDS)).unwrap_or_default(); + let entity_children = tree.children(entity); + let mut computed = Vec::new(); + let mut missing = Vec::new(); + for name in extended_fields { + let Some(entity_field) = entity_children + .iter() + .copied() + .find(|&c| is_type(tree, c, TYPE_FIELD) && tree.node(c).name == name) + else { + missing.push(name); + continue; + }; + // ADR-0039: own: a pass-through field must be declared on the projection itself. + let local = tree.own_children(owner).iter().copied().find(|&c| { + is_type(tree, c, TYPE_FIELD) && extends_chain_reaches(tree, c, entity_field) + }); + match local { + Some(l) => computed.push(tree.node(l).name.clone()), + None => missing.push(name), + } + } + Some(Passthrough { + entity, + computed, + missing, + }) +} + +/// `validateIdentityPassthrough` (FR-024 B3). +pub fn identity_passthrough(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for &obj in tree.children(ctx.root).iter() { + if !is(tree, obj, TYPE_OBJECT, SUB_PROJECTION) { + continue; + } + let obj_name = &tree.node(obj).name; + // ADR-0039: own: the projection's own identities are the pass-through subjects. + for &identity in tree.own_children(obj) { + if !is_type(tree, identity, TYPE_IDENTITY) { + continue; + } + let iname = &tree.node(identity).name; + if tree.node(identity).super_ref.is_none() { + out.errors.push(error_at( + tree, + identity, + ERR_PROJECTION_IDENTITY_NOT_EXTENDED, + format!( + "identity '{iname}' on projection '{obj_name}' must extend an entity identity (e.g. extends: \"Customer.id\") — a projection identity is a pass-through (FR-024)" + ), + )); + continue; + } + // An unresolved or non-identity target was reported by super resolution. + let Some(res) = resolve_passthrough(tree, identity) else { + continue; + }; + if !res.missing.is_empty() { + let entity = &tree.node(res.entity).name; + let refs: Vec = res + .missing + .iter() + .map(|f| format!("'{entity}.{f}'")) + .collect(); + out.errors.push(error_at( + tree, + identity, + ERR_IDENTITY_KEY_MISMATCH, + format!( + "identity '{iname}' on projection '{obj_name}' does not correspond to its extended identity: no local field extends {} — every field of the extended identity needs a pass-through field on the projection (FR-024)", + refs.join(", ") + ), + )); + continue; + } + // ADR-0039: own: an explicit own @fields is compared with the computed key. + let explicit = normalize_fields( + tree.own_attr(identity, ATTR_FIELDS) + .map(|a| &a.value) + .filter(|v| !v.is_null()), + ); + if let Some(explicit) = explicit + && explicit != res.computed + { + out.errors.push(error_at( + tree, + identity, + ERR_IDENTITY_KEY_MISMATCH, + format!( + "identity '{iname}' on projection '{obj_name}' declares @fields [{}] but the computed pass-through key is [{}] — omit @fields (it is derived) or make them agree (FR-024)", + explicit.join(", "), + res.computed.join(", ") + ), + )); + } + } + } +} + +// ---- identity sequence -------------------------------------------------------- + +fn own_declared(tree: &Tree, id: NodeId, name: &str) -> bool { + tree.own_attr(id, name).is_some_and(|a| !a.value.is_null()) +} + +/// `validateIdentitySequence`: `@sequenceStart` / `@sequenceName` only on an +/// `increment` key, and the start inside the key's range. +pub fn identity_sequence(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + for &obj in tree.children(ctx.root).iter() { + if !is_type(tree, obj, TYPE_OBJECT) { + continue; + } + let obj_name = &tree.node(obj).name; + // ADR-0039: own: reported on the identity that declares the attribute. + for &id in tree.own_children(obj) { + if !is(tree, id, TYPE_IDENTITY, SUB_PRIMARY) { + continue; + } + let declared: Vec<&str> = [ATTR_SEQUENCE_START, ATTR_SEQUENCE_NAME] + .into_iter() + .filter(|a| own_declared(tree, id, a)) + .collect(); + if declared.is_empty() { + continue; + } + let iname = &tree.node(id).name; + let generation = tree.attr(id, ATTR_GENERATION); + if generation == Some(&Value::String(GENERATION_INCREMENT.into())) { + if let Some(Value::Number(n)) = tree.attr(id, ATTR_SEQUENCE_START) { + let start = n.as_f64().unwrap_or(f64::NAN); + let key_name = match tree.attr(id, ATTR_FIELDS) { + Some(Value::Array(a)) => a.first().map(js_display), + Some(other) => Some(js_display(other)), + None => None, + }; + let key = key_name.as_deref().and_then(|k| { + tree.children(obj) + .iter() + .copied() + .find(|&c| is_type(tree, c, TYPE_FIELD) && tree.node(c).name == k) + }); + let key_is_int = key.is_some_and(|k| tree.node(k).sub_type == "int"); + if start < 1.0 || (key_is_int && start > SEQUENCE_INT_MAX) { + let shown = key_name.as_deref().unwrap_or("undefined"); + let sub = key + .map(|k| format!(" (field.{})", tree.node(k).sub_type)) + .unwrap_or_default(); + let upper = if key_is_int { + format!(" and at most {}", SEQUENCE_INT_MAX as i64) + } else { + String::new() + }; + out.errors.push(error_at( + tree, + id, + ERR_SEQUENCE_START_OUT_OF_RANGE, + format!( + "identity.primary \"{obj_name}.{iname}\" @sequenceStart {} is out of range for its key \"{shown}\"{sub}: it must be at least 1{upper}.", + js_number(n) + ), + )); + } + } + continue; + } + let shown = match generation { + Some(Value::String(s)) => format!("\"{s}\""), + _ => "not set".to_string(), + }; + let names = declared + .iter() + .map(|a| format!("@{a}")) + .collect::>() + .join(" and "); + out.errors.push(error_at( + tree, + id, + ERR_SEQUENCE_WITHOUT_INCREMENT, + format!( + "identity.primary \"{obj_name}.{iname}\" sets {names}, but its @generation is {shown}; only an @generation \"increment\" key draws from a sequence. Set @generation \"increment\", or remove {names}." + ), + )); + } + } +} + +// ---- TPH discriminators -------------------------------------------------------- + +fn own_string<'a>(tree: &'a Tree, id: NodeId, name: &str) -> Option<&'a str> { + match tree.own_attr(id, name).map(|a| &a.value) { + Some(Value::String(s)) => Some(s), + _ => None, + } +} + +/// A field named `name` on `entity`: its own children first, then up the extends chain. +fn find_field_on_entity(tree: &Tree, entity: NodeId, name: &str) -> Option { + let mut cur = Some(entity); + let mut hops = 0; + while let Some(e) = cur { + // ADR-0039: own: returns the DECLARING field node, level by level. + if let Some(&f) = tree + .own_children(e) + .iter() + .find(|&&c| is_type(tree, c, TYPE_FIELD) && tree.node(c).name == name) + { + return Some(f); + } + hops += 1; + if hops > tree.len() { + return None; + } + cur = tree.node(e).super_node; + } + None +} + +/// The nearest entity (self first) up the extends chain that declares `@discriminator`. +fn find_discriminator_root(tree: &Tree, entity: NodeId) -> Option<(NodeId, &str)> { + let mut cur = Some(entity); + let mut hops = 0; + while let Some(e) = cur { + // ADR-0039: own: locates the physical declaration site of @discriminator. + if let Some(v) = own_string(tree, e, ATTR_DISCRIMINATOR).filter(|v| !v.is_empty()) { + return Some((e, v)); + } + hops += 1; + if hops > tree.len() { + return None; + } + cur = tree.node(e).super_node; + } + None +} + +fn is_int_literal(v: &str) -> bool { + let digits = v.strip_prefix('-').unwrap_or(v); + !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) +} + +/// The numeric value of an integer literal as one canonical string ("01" is "1"). +fn canonical_int(v: &str) -> String { + let (neg, digits) = match v.strip_prefix('-') { + Some(d) => (true, d), + None => (false, v), + }; + let trimmed = digits.trim_start_matches('0'); + if trimmed.is_empty() { + "0".to_string() + } else if neg { + format!("-{trimmed}") + } else { + trimmed.to_string() + } +} + +struct Binding<'a> { + subtype: NodeId, + value: &'a str, + numeric: bool, +} + +/// `validateDiscriminator` (FR-014): the TPH cross-attribute rules. +pub fn discriminator(ctx: &Ctx<'_>, out: &mut Findings) { + let tree = ctx.tree; + let entities: Vec = tree + .children(ctx.root) + .iter() + .copied() + .filter(|&c| is(tree, c, TYPE_OBJECT, SUB_ENTITY)) + .collect(); + + // Pass 1: @discriminator names a field. + for &obj in &entities { + let Some(disc) = own_string(tree, obj, ATTR_DISCRIMINATOR).filter(|d| !d.is_empty()) else { + continue; + }; + if find_field_on_entity(tree, obj, disc).is_none() { + out.errors.push(error_at( + tree, + obj, + ERR_DISCRIMINATOR_FIELD_NOT_FOUND, + format!( + "object.entity \"{}\" @discriminator: \"{disc}\" does not name a field on this entity (checked own children and the extends chain)", + tree.node(obj).name + ), + )); + } + } + + // Pass 2: @discriminatorValue matches the field's type; group by hierarchy root. + let mut roots: Vec>> = Vec::new(); + let mut root_index: HashMap = HashMap::new(); + for &obj in &entities { + let Some(value) = own_string(tree, obj, ATTR_DISCRIMINATOR_VALUE).filter(|v| !v.is_empty()) + else { + continue; + }; + let Some((disc_root, field_name)) = find_discriminator_root(tree, obj) else { + continue; + }; + let Some(field) = find_field_on_entity(tree, disc_root, field_name) else { + continue; // the root's own ERR_DISCRIMINATOR_FIELD_NOT_FOUND fires + }; + let fsub = tree.node(field).sub_type.as_str(); + let name = &tree.node(obj).name; + let numeric = fsub == "int" || fsub == "long"; + if fsub == "enum" { + let list: Vec = match tree.attr(field, ATTR_VALUES) { + Some(Value::Array(a)) => a.iter().map(js_display).collect(), + _ => Vec::new(), + }; + if !list.iter().any(|m| m == value) { + out.errors.push(error_at( + tree, + obj, + ERR_DISCRIMINATOR_VALUE_TYPE_MISMATCH, + format!( + "object.entity \"{name}\" @discriminatorValue: \"{value}\" is not a member of the discriminator enum field \"{field_name}\" @values [{}]", + list.join(", ") + ), + )); + } + } else if numeric && !is_int_literal(value) { + out.errors.push(error_at( + tree, + obj, + ERR_DISCRIMINATOR_VALUE_TYPE_MISMATCH, + format!( + "object.entity \"{name}\" @discriminatorValue: \"{value}\" does not coerce to numeric discriminator field \"{field_name}\" (field.{fsub})" + ), + )); + } + let slot = *root_index.entry(disc_root).or_insert_with(|| { + roots.push(Vec::new()); + roots.len() - 1 + }); + roots[slot].push(Binding { + subtype: obj, + value, + numeric, + }); + } + + // Pass 3: one claim per value within a root ("1" and "01" are one value). + for bindings in &roots { + let mut seen: HashMap = HashMap::new(); + for b in bindings { + let key = if b.numeric && is_int_literal(b.value) { + canonical_int(b.value) + } else { + b.value.to_string() + }; + match seen.get(&key) { + Some(&prev) => out.errors.push(error_at( + tree, + b.subtype, + ERR_DISCRIMINATOR_VALUE_DUPLICATE, + format!( + "object.entity \"{}\" @discriminatorValue: \"{}\" duplicates the value already claimed by \"{}\"", + tree.node(b.subtype).name, + b.value, + tree.node(prev).name + ), + )), + None => { + seen.insert(key, b.subtype); + } + } + } + } + + // Pass 4: every concrete subtype of a discriminator root declares a value. + for &obj in &entities { + if tree.node(obj).is_abstract + || own_string(tree, obj, ATTR_DISCRIMINATOR_VALUE).is_some() + || own_string(tree, obj, ATTR_DISCRIMINATOR).is_some() + { + continue; + } + let Some((disc_root, _)) = find_discriminator_root(tree, obj) else { + continue; + }; + if disc_root == obj { + continue; + } + out.errors.push(error_at( + tree, + obj, + ERR_DISCRIMINATOR_VALUE_MISSING, + format!( + "object.entity \"{}\" extends the @discriminator-bearing root \"{}\" but is missing @discriminatorValue (required on every concrete subtype)", + tree.node(obj).name, + tree.node(disc_root).name + ), + )); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_code_is_in_the_shared_catalogue() { + let raw = include_str!("../../../../../fixtures/conformance/ERROR-CODES.json"); + let doc: Value = serde_json::from_str(raw).unwrap(); + let codes = doc["codes"].as_object().unwrap(); + for code in [ + ERR_IDENTITY_NAME_REQUIRED, + ERR_SUBTYPE_RULE_VIOLATION, + ERR_PROJECTION_INHERITED_SOURCE, + ERR_PROJECTION_SOURCE_WRITABLE, + ERR_TOO_MANY_OCCURRENCES, + ERR_PROJECTION_IDENTITY_NOT_EXTENDED, + ERR_IDENTITY_KEY_MISMATCH, + ERR_SEQUENCE_WITHOUT_INCREMENT, + ERR_SEQUENCE_START_OUT_OF_RANGE, + ERR_DISCRIMINATOR_FIELD_NOT_FOUND, + ERR_DISCRIMINATOR_VALUE_DUPLICATE, + ERR_DISCRIMINATOR_VALUE_MISSING, + ERR_DISCRIMINATOR_VALUE_TYPE_MISMATCH, + ] { + assert!( + codes.contains_key(code), + "{code} is not in ERROR-CODES.json" + ); + } + } + + #[test] + fn integer_literals_compare_by_value() { + assert!(is_int_literal("-12") && is_int_literal("007")); + assert!(!is_int_literal("1\n") && !is_int_literal("") && !is_int_literal("-")); + assert_eq!(canonical_int("007"), "7"); + assert_eq!(canonical_int("-0"), "0"); + assert_eq!(canonical_int("-010"), "-10"); + } +} diff --git a/server/rust/metaobjects/src/validate/util.rs b/server/rust/metaobjects/src/validate/util.rs new file mode 100644 index 0000000000..1ecccf3d76 --- /dev/null +++ b/server/rust/metaobjects/src/validate/util.rs @@ -0,0 +1,202 @@ +//! Helpers the validation passes share. Keep this small: a pass reads the tree +//! through [`crate::node::Tree`] directly, and ADR-0039's rule holds here too — +//! the resolving accessors are the default, `own_*` only where a comment names the +//! sanctioned case. + +use std::collections::HashMap; + +use crate::errors::MetaError; +use crate::loader::{owner_candidate_keys, split_child_tail}; +use crate::node::{NodeId, PACKAGE_SEP, Tree}; +use crate::parser::TYPE_OBJECT; + +const A_REFERENCES: &str = "references"; +const A_OBJECT_REF: &str = "objectRef"; + +/// An error located where `id` was declared: its source is the node's own. +pub fn error_at( + tree: &Tree, + id: NodeId, + code: &'static str, + message: impl Into, +) -> MetaError { + MetaError::at(code, message, tree.node(id).source.clone()) +} + +/// A node as error messages name it: `type.subType 'name'`, or `type.subType` unnamed. +pub fn child_label(tree: &Tree, id: NodeId) -> String { + let n = tree.node(id); + if n.name.is_empty() { + format!("{}.{}", n.type_name, n.sub_type) + } else { + format!("{}.{} '{}'", n.type_name, n.sub_type, n.name) + } +} + +/// The grains `startOf` accepts on a relative date. +pub const START_OF_UNITS: &[&str] = &["day", "week", "month"]; + +// ---- the object index --------------------------------------------------------------- + +/// Root-level objects by resolution key (ADR-0042 / ADR-0059), first declaration +/// winning, plus the objects in document order. Built once per load and shared by +/// every pass through [`crate::validate::Ctx`] and by the reference-rewrite phase. +#[derive(Debug, Default)] +pub struct ObjectIndex { + by_key: HashMap, + objs: Vec, +} + +impl ObjectIndex { + pub fn build(tree: &Tree, root: NodeId) -> Self { + let mut by_key = HashMap::new(); + let mut objs = Vec::new(); + // ADR-0039 own: the root's top-level nodes are its declared children; a root extends nothing. + for &c in tree.own_children(root) { + if tree.node(c).type_name == TYPE_OBJECT { + by_key.entry(tree.resolution_key(c)).or_insert(c); + objs.push(c); + } + } + Self { by_key, objs } + } + + /// The root's top-level objects, in order. + pub fn objects(&self) -> &[NodeId] { + &self.objs + } + + /// `resolveObjectRef` for an OWNER reference (no child tail): `::Rest` exact, + /// `..::Rest` parent-relative (an over-dropped one resolves to nothing), `pkg::Name` + /// exact, bare `Name` the referrer's package then root level. + pub fn resolve(&self, owner: &str, referrer_pkg: &str) -> Option { + let get = |k: &str| self.by_key.get(k).copied(); + if owner.starts_with(PACKAGE_SEP) || owner.starts_with("..::") { + return owner_candidate_keys(owner, referrer_pkg) + .ok()? + .iter() + .find_map(|k| get(k)); + } + if referrer_pkg.is_empty() || owner.contains(PACKAGE_SEP) { + return get(owner); + } + get(&format!("{referrer_pkg}{PACKAGE_SEP}{owner}")).or_else(|| get(owner)) + } + + /// `refTarget(node, attr)`: the layer declaring `attr` up the super chain, its value + /// resolved from that layer's top-level package. + pub fn ref_target(&self, tree: &Tree, node: NodeId, attr: &str) -> Option { + let mut cur = Some(node); + let mut steps = 0usize; + while let Some(n) = cur { + steps += 1; + if steps > tree.len() { + return None; + } + // ADR-0039 own: locating the layer that declares the attr, walking the super chain. + if let Some(a) = tree.own_attr(n, attr) { + let value = a.value.as_str().filter(|s| !s.is_empty())?; + let (owner, _) = split_child_tail(value); + return self.resolve(owner, &tree.effective_package(tree.top_level_of(n))); + } + cur = tree.node(n).super_node; + } + None + } + + /// One to-one hop of a `@via` walk: the hop's target object. + pub fn hop_target(&self, tree: &Tree, hop: NodeId, is_ref: bool) -> Option { + self.ref_target(tree, hop, if is_ref { A_REFERENCES } else { A_OBJECT_REF }) + .filter(|&t| tree.node(t).type_name == TYPE_OBJECT) + } + + /// The entity an origin's `@filter` keys name: the `@of` entity, else the `@via` terminal. + pub fn origin_filter_entity(&self, tree: &Tree, origin: NodeId) -> Option { + let field = tree.node(origin).parent?; + let projection = tree.node(field).parent?; + let pkg = tree.effective_package(projection); + // ADR-0039 own: origin.* never inherits (ADR-0029). + let own = |name: &str| { + tree.own_attr(origin, name) + .and_then(|a| a.value.as_str()) + .filter(|s| !s.is_empty()) + }; + if let Some(of) = own("of") { + return self.resolve(split_child_tail(of).0, &pkg); + } + let (owner, hops) = split_dotted(own("via")?)?; + let mut current = self.resolve(owner, &pkg)?; + for h in hops { + let (hop, is_ref) = find_hop(tree, current, h)?; + current = self.hop_target(tree, hop, is_ref)?; + } + Some(current) + } +} + +/// Split `Owner.child[.child...]` at the first `.` after the last `::`. +pub fn split_dotted(r: &str) -> Option<(&str, Vec<&str>)> { + let seg = r.rfind(PACKAGE_SEP).map_or(0, |i| i + PACKAGE_SEP.len()); + let dot = seg + r[seg..].find('.')?; + if dot <= seg { + return None; + } + let path: Vec<&str> = r[dot + 1..].split('.').collect(); + if path.iter().any(|s| s.is_empty()) { + return None; + } + Some((&r[..dot], path)) +} + +/// One hop by name: a relationship, else an `identity.reference`; `true` when it is the latter. +pub fn find_hop(tree: &Tree, current: NodeId, name: &str) -> Option<(NodeId, bool)> { + // ADR-0039: resolving: a hop may be inherited through extends. + let kids = tree.children(current); + let rel = kids.iter().copied().find(|&c| { + let n = tree.node(c); + n.type_name == "relationship" && n.name == name + }); + match rel { + Some(r) => Some((r, false)), + None => kids + .iter() + .copied() + .find(|&c| { + let n = tree.node(c); + n.type_name == "identity" && n.sub_type == "reference" && n.name == name + }) + .map(|c| (c, true)), + } +} + +// ---- filter operator bands ---------------------------------------------------------- + +pub const OPS_STRING: &[&str] = &["eq", "ne", "in", "like", "isNull"]; +pub const OPS_NUMBER: &[&str] = &["eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"]; +pub const OPS_BOOLEAN: &[&str] = &["eq", "isNull"]; +pub const OPS_IDENTITY: &[&str] = &["eq", "ne", "in", "isNull"]; + +/// The filter-operator band of a field subtype; empty when it has none. +pub fn ops_for_subtype(sub_type: &str) -> &'static [&'static str] { + match sub_type { + "string" | "enum" | "uri" => OPS_STRING, + "int" | "long" | "double" | "float" | "decimal" | "currency" | "date" | "time" + | "timestamp" | "duration" => OPS_NUMBER, + "boolean" => OPS_BOOLEAN, + "uuid" | "inet" => OPS_IDENTITY, + _ => &[], + } +} + +/// The band for a field: an int-backed enum drops `like`. +pub fn ops_for_field(tree: &Tree, id: NodeId) -> &'static [&'static str] { + let n = tree.node(id); + if n.sub_type == "enum" + && tree + .attr(id, "intValueMap") + .is_some_and(serde_json::Value::is_object) + { + return OPS_IDENTITY; + } + ops_for_subtype(&n.sub_type) +} diff --git a/server/rust/metaobjects/tests/conformance-expected-failures.json b/server/rust/metaobjects/tests/conformance-expected-failures.json index b933daf43d..721f2af7f5 100644 --- a/server/rust/metaobjects/tests/conformance-expected-failures.json +++ b/server/rust/metaobjects/tests/conformance-expected-failures.json @@ -1,261 +1,6 @@ { "language": "rust", - "notes": "The Rust port is in preview. The loader reads JSON and YAML, merges, resolves extends and serializes; it does not yet run the validation passes (the unknown-attr provenance check, ERR_UNKNOWN_ATTR, among them), emit merge warnings, resolve the reporting rule that binds a bare entity name in the package its path already fixes, or run script.json operations. Every fixture listed here fails for one of those reasons and leaves the ledger when the step that covers it lands. The ledger may only shrink. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.", - "minPassing": 261, - "fixtures": [ - "error-agg-all-non-boolean", - "error-agg-any-missing-filter", - "error-agg-collect-element-type-mismatch", - "error-agg-collect-non-array", - "error-attr-bad-allowed-value", - "error-attr-filter-bad-field", - "error-attr-filter-bad-op", - "error-attr-filter-legacy-string", - "error-attr-int-fractional", - "error-attr-missing-required", - "error-attr-wrong-type", - "error-collect-distinct", - "error-collect-member-type-mismatch", - "error-collect-member-unresolved", - "error-collect-no-object-ref", - "error-collect-no-via", - "error-collect-orderby-not-terminal", - "error-collect-ref-not-value", - "error-collect-via-to-one", - "error-column-name-collision", - "error-column-name-collision-derived-view", - "error-column-name-collision-flattened-empty-prefix", - "error-column-name-collision-flattened-member-vs-field", - "error-column-name-collision-table-with-sql-view", - "error-computed-expr-not-object", - "error-computed-op-illegal-operand", - "error-computed-type-mismatch", - "error-computed-unknown-expr-node", - "error-computed-unresolved-field", - "error-data-grid-bad-sort-field", - "error-dbcolumntype-illegal-pairing", - "error-default-non-coercible-int", - "error-derived-field-no-read-source", - "error-dimension-grain-on-date", - "error-dimension-of-jsonb-member", - "error-dimension-of-unresolved", - "error-dimension-over-object", - "error-dimension-time-not-temporal", - "error-dimension-via-base-lacks-field", - "error-dimension-via-to-many", - "error-entity-primary-source-readonly", - "error-enum-chained-extends-values-conflict", - "error-enum-coerce-default-non-member", - "error-enum-default-non-member", - "error-enum-duplicate-member", - "error-enum-empty-values", - "error-enum-extends-intvaluemap-conflict", - "error-enum-extends-values-conflict", - "error-enum-intvaluemap-duplicate-value", - "error-enum-intvaluemap-key-mismatch", - "error-enum-intvaluemap-non-int", - "error-enum-max-length-int-value-map", - "error-enum-missing-values", - "error-enum-non-identifier-member", - "error-enum-normalize-bad-mode", - "error-enum-normalize-collision", - "error-enum-value-exceeds-max-length", - "error-enum-value-exceeds-max-length-every-field", - "error-extends-origin-mismatch", - "error-field-map-objectref-unresolved", - "error-field-mutability-autoset-conflict", - "error-field-mutability-downgrade", - "error-field-mutability-downgrade-writeonce", - "error-field-mutability-readonly-assigned-primary", - "error-field-object-flattened-column-prefix-default-storage", - "error-field-object-flattened-column-prefix-without-flattened-storage", - "error-field-object-no-object-ref", - "error-field-objectref-unresolved", - "error-field-object-storage-flattened-array", - "error-field-object-storage-no-object-ref", - "error-filterable-array-field", - "error-filterable-unsupported-subtype", - "error-filter-with-sql-body", - "error-first-of-type-mismatch", - "error-first-required-field", - "error-identity-key-mismatch", - "error-identity-name-required", - "error-identity-reference-unresolved", - "error-identity-secondary-fields-and-expr", - "error-identity-sequence-start-out-of-range", - "error-identity-sequence-without-increment", - "error-index-fields-and-expr", - "error-kind1-view-unregistered-attr", - "error-m2m-through-value", - "error-measure-all-default-not-boolean", - "error-measure-any-non-boolean", - "error-measure-any-without-condition", - "error-measure-default-non-numeric", - "error-measure-default-not-integer", - "error-measure-default-on-count", - "error-measure-default-on-count-integral-float", - "error-measure-default-on-count-non-numeric", - "error-measure-derived-ambiguous-operand", - "error-measure-derived-default", - "error-measure-derived-malformed-expr", - "error-measure-derived-non-numeric-dimension", - "error-measure-derived-non-numeric-measure", - "error-measure-derived-of-derived", - "error-measure-derived-time-dimension", - "error-measure-derived-unknown-operand", - "error-measure-distinct-not-count", - "error-measure-of-foreign", - "error-measure-of-jsonb-member", - "error-measure-of-member-of-scalar", - "error-measure-of-path-too-deep", - "error-measure-of-unknown-member", - "error-measure-over-object", - "error-measure-segment-unresolved", - "error-measure-sum-non-numeric", - "error-measure-sum-without-of", - "error-measure-tuple-without-distinct", - "error-merge-conflict-attr", - "error-merge-conflict-flattened-column-prefix-empty", - "error-origin-aggregate-no-to-many", - "error-origin-aggregate-value-object", - "error-origin-bad-aggregate-fn", - "error-origin-bad-via-path", - "error-origin-computed-case-mixed-types", - "error-origin-computed-case-non-boolean-when", - "error-origin-computed-case-unknown-key", - "error-origin-computed-cycle", - "error-origin-computed-literal-fractional", - "error-origin-computed-literal-not-enum-member", - "error-origin-computed-literal-wrong-kind", - "error-origin-computed-node-mixed-keys", - "error-origin-computed-now-bad-duration", - "error-origin-correlated-operand-unknown", - "error-origin-passthrough-array-mismatch", - "error-origin-passthrough-reverse-hop", - "error-origin-passthrough-to-many", - "error-origin-passthrough-type-mismatch", - "error-origin-reverse-hop-ambiguous", - "error-origin-segment-flattened-of", - "error-origin-segment-unresolved", - "error-origin-under-sql-body", - "error-origin-via-ambiguous", - "error-parameter-ref-not-value-object", - "error-parameter-ref-on-table-kind", - "error-parameter-ref-passthrough-type-mismatch", - "error-parameter-ref-unresolved", - "error-payload-nested-object-ref-entity", - "error-port-scoped-attr-wrong-type", - "error-projection-extends-entity", - "error-projection-extends-filter-sql-body", - "error-projection-filter-aggregate", - "error-projection-filter-dangling", - "error-projection-filter-path-to-many", - "error-projection-identity-not-extended", - "error-projection-inherited-source", - "error-projection-source-writable", - "error-provided-not-boolean", - "error-ratio-boolean-operand", - "error-ratio-non-numeric-operand", - "error-ratio-operand-not-aggregate", - "error-relationship-m2m-attr-on-1n", - "error-relationship-m2m-junction-unpairable", - "error-relationship-one-refs-ambiguous", - "error-relationship-one-unresolved-objectref-sourceref", - "error-relationship-symmetric-and-sourceref", - "error-relationship-symmetric-on-hetero", - "error-relationship-through-missing-junction-refs", - "error-relationship-unresolved-objectref", - "error-relative-date-bad-duration", - "error-relative-date-bad-startof", - "error-relative-date-datagrid-host", - "error-relative-date-extra-key", - "error-relative-date-non-temporal", - "error-relative-date-non-temporal-field", - "error-relative-date-view-host-malformed", - "error-report-abstract", - "error-report-declares-field", - "error-report-derived-dimension-not-listed", - "error-report-dimension-grain", - "error-report-field-collision", - "error-report-foreign-measure", - "error-report-from-not-entity", - "error-report-measure-unresolved", - "error-report-segment-unresolved", - "error-report-source-kind-materialized-view", - "error-report-source-kind-stored-proc", - "error-report-source-kind-table-function", - "error-report-spine-dimension-off-spine", - "error-report-spine-dimension-other-path", - "error-report-spine-no-dimensions", - "error-report-spine-not-from", - "error-report-spine-to-many", - "error-report-two-unresolved-dimensions", - "error-report-value-object-unit-derived-operand", - "error-report-value-object-unit-not-grouped", - "error-report-value-object-unit-ratio-operand", - "error-report-writable-source", - "error-requirement-level-fractional", - "error-requirement-retired-has-implementors", - "error-requirement-status-abandoned", - "error-requirement-superseded-by-not-retired", - "error-requirement-verified-by-retired", - "error-root-level-field-objectref-unresolved", - "error-segment-filter-bad-field", - "error-sortable-array-field", - "error-source-multiple-primary", - "error-source-no-primary", - "error-source-rdb-multiple-physical-names", - "error-source-rdb-physical-name-empty-string", - "error-source-rdb-physical-name-kind-mismatch", - "error-source-role-reserved", - "error-sql-body-empty", - "error-sql-body-on-writable-kind", - "error-sql-body-with-unmanaged", - "error-template-payload-ref-not-value", - "error-template-payload-ref-sourced-projection", - "error-template-payload-ref-unresolved", - "error-template-prompt-missing-payload-ref", - "error-template-required-slot-missing", - "error-template-response-ref-not-value", - "error-too-many-primary", - "error-tph-discriminator-field-not-found", - "error-tph-discriminator-numeric-equivalent", - "error-tph-discriminator-numeric-trailing-newline", - "error-tph-discriminator-value-duplicate", - "error-tph-discriminator-value-missing", - "error-tph-discriminator-value-type-mismatch", - "error-unknown-attr", - "error-unknown-attr-object", - "error-unknown-attr-requirement", - "error-unknown-attr-validator", - "error-validator-at-least-one-max-unknown", - "error-validator-condition-duration-literal", - "error-validator-condition-now", - "error-validator-condition-type", - "error-validator-condition-unknown-field", - "error-validator-condition-unknown-fields", - "error-validator-exactly-one-one-field", - "error-value-origin-aggregate", - "error-value-origin-computed", - "error-value-origin-first", - "error-value-reference-enforced", - "error-value-reference-unresolved", - "error-value-with-identity-secondary", - "error-value-with-source", - "error-xpkg-ambiguous-objectref", - "error-xpkg-bare-unique-elsewhere", - "error-xpkg-through-bare", - "extends-abstract-base", - "filter-ops-matrix", - "merge-conflict-unmarked-attr-redeclaration", - "projection-identity-borrows-secondary", - "provider-custom-vocabulary-missing-provider-fails", - "reporting-cross-package-short-names", - "source-rdb-legacy-table-for-view-rewrites", - "subtype-entity-missing-primary-warning", - "warning-duplicate-declaration", - "warning-enum-normalize-ambiguous", - "warning-filterable-inherited-without-index", - "warning-filterable-no-index" - ] + "notes": "The Rust port is in preview. It passes every fixture of the shared metamodel corpus, so the ledger is empty. The ledger may only shrink and is kept for the day a new fixture lands that Rust does not pass yet: list it here with the reason, and it leaves when the work that covers it lands. minPassing is the number of fixtures known to pass; the run fails when fewer do, and it may only rise.", + "minPassing": 526, + "fixtures": [] } diff --git a/server/rust/metaobjects/tests/enum_int_value_map.rs b/server/rust/metaobjects/tests/enum_int_value_map.rs new file mode 100644 index 0000000000..a53f4720d4 --- /dev/null +++ b/server/rust/metaobjects/tests/enum_int_value_map.rs @@ -0,0 +1,55 @@ +//! `@intValueMap` content checks (the reference's attr-schema Check 5b): the map is read +//! as `Object.entries` reads it, so an array value is checked by index, and an integral +//! float such as `1.0` is an integer (`Number.isInteger`) that can duplicate another. + +use metaobjects::LoadResult; +use metaobjects::loader::Loader; +use metaobjects::providers::default_registry; + +fn load(int_value_map: &str) -> LoadResult { + let doc = format!( + r#"{{"metadata.root": {{"package": "t", "children": [ + {{"object.entity": {{"name": "Order", "children": [ + {{"source.rdb": {{"@table": "orders"}}}}, + {{"field.long": {{"name": "id"}}}}, + {{"field.enum": {{"name": "status", "@values": ["A", "B"], "@intValueMap": {int_value_map}}}}}, + {{"identity.primary": {{"name": "id", "@fields": "id"}}}} + ]}}}} + ]}}}}"# + ); + Loader::new(&default_registry().unwrap()).load_sources(&[("meta.t.json".to_string(), doc)]) +} + +fn messages(r: &LoadResult) -> Vec<&str> { + r.errors.iter().map(|e| e.message.as_str()).collect() +} + +#[test] +fn a_well_formed_map_loads_clean() { + let r = load(r#"{"A": 1, "B": 2}"#); + assert!(r.errors.is_empty(), "{:?}", messages(&r)); +} + +#[test] +fn an_array_value_is_checked_by_index_against_the_members() { + let r = load("[1, 2]"); + assert!( + messages(&r).iter().any(|m| m.contains( + "keys must exactly match '@values' members (missing: A, B) (unknown: 0, 1)." + )), + "{:?}", + messages(&r) + ); +} + +#[test] +fn integral_floats_that_agree_are_a_duplicate() { + let r = load(r#"{"A": 1.0, "B": 1.0}"#); + assert!( + messages(&r).iter().any(|m| m.contains( + "members 'A' and 'B' share the same value 1; every member must have a unique int." + )), + "{:?}", + messages(&r) + ); +} diff --git a/server/rust/metaobjects/tests/extender_scope.rs b/server/rust/metaobjects/tests/extender_scope.rs new file mode 100644 index 0000000000..d98d622410 --- /dev/null +++ b/server/rust/metaobjects/tests/extender_scope.rs @@ -0,0 +1,64 @@ +//! `validateExtenderSubtypeScope`: the legacy warning the corpus does not pin. + +use metaobjects::loader::Loader; +use metaobjects::providers::default_registry; + +fn warnings(extra: &str, extends_abstract: bool, filter: &str, own_identity: &str) -> Vec { + let abs = if extends_abstract { + r#""abstract": true,"# + } else { + "" + }; + let doc = format!( + r#"{{"metadata.root": {{"package": "acme", "children": [ + {{"object.entity": {{"name": "Vehicle", "@discriminator": "kind", "children": [ + {{"source.rdb": {{"@table": "vehicles"}}}}, {{"field.long": {{"name": "id"}}}}, + {{"field.string": {{"name": "kind", "@maxLength": 10}}}}, + {{"identity.primary": {{"@fields": "id"}}}}]}}}}, + {{"object.entity": {{"name": "Truck", "extends": "Vehicle", "@discriminatorValue": "TRUCK", "children": [ + {{"field.string": {{"name": "payloadClass"}}}}]}}}}, + {{"object.projection": {{"name": "VehicleBase", "abstract": true, "children": [ + {{"field.long": {{"name": "vehicleId", "extends": "Vehicle.id"}}}}, + {{"identity.primary": {{"name": "id", "extends": "Vehicle.primary"}}}}]}}}}, + {{"object.projection": {{"name": "TruckRow", "extends": "VehicleBase", {abs} {filter} + "children": [ + {{"source.rdb": {{"@kind": "view", "@view": "v_trucks"}}}}, + {{"field.string": {{"name": "payload", "extends": "Truck.payloadClass"}}}}{own_identity}{extra}]}}}} + ]}}}}"# + ); + let registry = default_registry().expect("the built-in providers compose"); + let r = Loader::new(®istry).load_sources(&[("meta.a.json".to_string(), doc)]); + assert!(r.errors.is_empty(), "{:?}", r.errors); + r.warnings + .iter() + .map(|w| w.message.clone()) + .filter(|m| m.contains("TruckRow")) + .collect() +} + +#[test] +fn warns_with_the_reference_message() { + let w = warnings("", false, "", ""); + assert_eq!(w.len(), 1, "{w:?}"); + assert_eq!( + w[0], + "object.projection TruckRow: \"payload\" (Truck.payloadClass) read columns only a subtype carries, over the TPH base Vehicle with no @filter on its discriminator \"kind\", so the view returns every Vehicle row (rc.21: an extender keeps its super's identity anchor; before, its base was the subtype). To keep a subtype-scoped view, add @filter { kind: } or declare identity.primary { extends: Truck.primary }." + ); +} + +#[test] +fn an_abstract_extender_does_not_warn() { + assert!(warnings("", true, "", "").is_empty()); +} + +#[test] +fn a_discriminator_filter_scopes_it() { + assert!(warnings("", false, r#""@filter": {"kind": "TRUCK"},"#, "").is_empty()); +} + +#[test] +fn its_own_identity_scopes_it() { + let own = r#", {"field.long": {"name": "vehicleId", "extends": "Truck.id"}}, + {"identity.primary": {"name": "id", "extends": "Truck.primary"}}"#; + assert!(warnings("", false, "", own).is_empty()); +} diff --git a/server/rust/metaobjects/tests/metamodel_conformance.rs b/server/rust/metaobjects/tests/metamodel_conformance.rs index 2622db9485..abbe45daf8 100644 --- a/server/rust/metaobjects/tests/metamodel_conformance.rs +++ b/server/rust/metaobjects/tests/metamodel_conformance.rs @@ -17,9 +17,10 @@ use std::path::{Path, PathBuf}; use serde_json::Value; -use metaobjects::errors::MetaError; +use metaobjects::errors::{MetaError, WARN_LEGACY}; use metaobjects::json::{safe_whole_i64, to_js_pretty}; use metaobjects::loader::Loader; +use metaobjects::node::{NodeId, Tree}; use metaobjects::providers::{Provider, builtin_provider, compose_registry}; use metaobjects::registry::{AttrSchema, ChildRule, TypeDefinition, TypeRegistry}; use metaobjects::serializer::{canonical_serialize_effective, to_canonical_value}; @@ -103,8 +104,11 @@ fn provider(id: &str) -> Provider { struct Outcome { errors: Vec, + warnings: Vec, canonical: Option, effective: Option, + /// The loaded model, for `script.json` operations. + model: Option<(Tree, NodeId)>, } fn run_load(fixture: &Path) -> Outcome { @@ -118,30 +122,34 @@ fn run_load(fixture: &Path) -> Outcome { Err(e) => { return Outcome { errors: vec![e], + warnings: Vec::new(), canonical: None, effective: None, + model: None, }; } }; registry.seal(); let input = fixture.join("input"); + // The corpus loads strict, as every port's adapter does (ADR-0023). let result = Loader::new(®istry) + .strict(true) .load_dir(&input) .expect("fixture input is readable"); let prefix = format!("{}/", input.to_string_lossy()); - let errors = result - .errors - .into_iter() - .map(|mut e| { - e.source - .map_files(|f| f.strip_prefix(&prefix).unwrap_or(f).replace('\\', "/")); - e - }) - .collect(); + let relative = |mut e: MetaError| { + e.source + .map_files(|f| f.strip_prefix(&prefix).unwrap_or(f).replace('\\', "/")); + e + }; + let errors = result.errors.into_iter().map(relative).collect(); + let warnings = result.warnings.into_iter().map(relative).collect(); Outcome { errors, + warnings, canonical: Some(to_canonical_value(&result.tree, result.root, false)), effective: Some(canonical_serialize_effective(&result.tree, result.root)), + model: Some((result.tree, result.root)), } } @@ -235,14 +243,111 @@ fn check_envelope(i: usize, want: &Value, got: &MetaError, failures: &mut Vec Option { + let mut cur = root; + for seg in path { + let (ty, name) = seg.split_once(':')?; + cur = tree.children(cur).iter().copied().find(|&c| { + let n = tree.node(c); + n.type_name == ty && n.name == name + })?; + } + Some(cur) +} + +/// Run the `script.json` operations this port implements. `field.filter-ops` reads the +/// per-subtype filter-operator bands in `validate::util`; an operation this runner does +/// not know fails the fixture rather than passing silently. +fn run_script(script: &Value, tree: &Tree, root: NodeId) -> Vec { + let mut failures = Vec::new(); + let ops = script["operations"].as_array().cloned().unwrap_or_default(); + for (i, op) in ops.iter().enumerate() { + let path: Vec<&str> = op["navigate"] + .as_array() + .map(|a| a.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + let invoke = op["invoke"].as_str().unwrap_or_default(); + let Some(node) = navigate(tree, root, &path) else { + failures.push(format!("script[{i}]: cannot navigate {path:?}")); + continue; + }; + let names = |ids: &[NodeId]| -> Value { + Value::from( + ids.iter() + .map(|&c| tree.node(c).name.clone()) + .collect::>(), + ) + }; + let fields = |ids: &[NodeId]| -> Vec { + ids.iter() + .copied() + .filter(|&c| tree.node(c).type_name == "field") + .collect() + }; + let got = match invoke { + "object.effective-fields" => { + serde_json::json!({ "names": names(&fields(&tree.children(node))) }) + } + // ADR-0039: own — the operation under test is the own-only member set. + "object.own-fields" => { + serde_json::json!({ "names": names(&fields(tree.own_children(node))) }) + } + "object.find-field" => { + let want = op["args"]["name"].as_str().unwrap_or_default(); + match fields(&tree.children(node)) + .into_iter() + .find(|&c| tree.node(c).name == want) + { + Some(c) => serde_json::json!({ "name": tree.node(c).name }), + None => serde_json::json!({ "absent": true }), + } + } + "object.primary-identity" => { + match tree.children(node).iter().copied().find(|&c| { + let n = tree.node(c); + n.type_name == "identity" && n.sub_type == "primary" + }) { + Some(c) => serde_json::json!({ "subtype": tree.node(c).sub_type }), + None => serde_json::json!({ "absent": true }), + } + } + // The canonical per-field filter-operator band, in canonical operator order. + "field.filter-ops" => serde_json::json!({ + "names": metaobjects::validate::util::ops_for_field(tree, node) + }), + other => { + failures.push(format!( + "script[{i}]: operation {other:?} is not implemented in the Rust port yet" + )); + continue; + } + }; + if got != op["expect"] { + failures.push(format!( + "script[{i}] {invoke}: expected {}, got {got}", + op["expect"] + )); + } + } + failures +} + /// Run every check `fixture` declares. An empty list is a pass. fn check(fixture: &Path) -> Vec { let has = |f: &str| fixture.join(f).is_file(); let mut failures = Vec::new(); - if has("script.json") { - failures.push("script.json operations are not implemented in the Rust port yet".into()); - } let out = run_load(fixture); + if has("script.json") + && let Some((tree, root)) = &out.model + { + failures.extend(run_script( + &read_json(&fixture.join("script.json")), + tree, + *root, + )); + } let mut codes: Vec<&str> = out.errors.iter().map(|e| e.code).collect(); codes.sort_unstable(); @@ -300,12 +405,36 @@ fn check(fixture: &Path) -> Vec { check_envelope(i, w, g, &mut failures); } } - let want_warnings = raw + let want_warnings: Vec = raw .get("warnings") .and_then(Value::as_array) - .map_or(0, Vec::len); - if want_warnings != 0 { - failures.push(format!("warnings count: expected {want_warnings}, got 0")); + .cloned() + .unwrap_or_default(); + // Envelope warnings, as the errors: code first, then the source fields in + // declaration order. WARN_LEGACY entries are the string-list channel below. + let got: Vec<&MetaError> = out + .warnings + .iter() + .filter(|w| w.code != WARN_LEGACY) + .collect(); + if want_warnings.len() != got.len() { + failures.push(format!( + "warnings count: expected {}, got {}: {:?}", + want_warnings.len(), + got.len(), + got.iter().map(|w| w.code).collect::>() + )); + } else { + for (i, (w, g)) in want_warnings.iter().zip(&got).enumerate() { + if w["code"].as_str() != Some(g.code) { + failures.push(format!( + "warning[{i}].code: expected {}, got {}", + w["code"], g.code + )); + continue; + } + check_envelope(i, w, g, &mut failures); + } } } } @@ -330,11 +459,44 @@ fn check(fixture: &Path) -> Vec { } } - if has("expected-warnings.json") { - let want = read_json(&fixture.join("expected-warnings.json")); - if want.as_array().is_some_and(|a| !a.is_empty()) { - failures.push(format!("warnings: want {want} got []")); - } + // The legacy string-list channel: the loader's WARN_LEGACY messages, compared as a set. + let mut legacy: Vec<&str> = out + .warnings + .iter() + .filter(|w| w.code == WARN_LEGACY) + .map(|w| w.message.as_str()) + .collect(); + legacy.sort_unstable(); + let mut want_legacy: Vec = if has("expected-warnings.json") { + read_json(&fixture.join("expected-warnings.json")) + .as_array() + .map(|a| { + a.iter() + .filter_map(|v| v.as_str().map(String::from)) + .collect() + }) + .unwrap_or_default() + } else { + Vec::new() + }; + want_legacy.sort_unstable(); + // A script fixture pins behavior queried from the model, not the loader's advisory + // warnings: without an expected-warnings.json it does not compare them (as the reference runner). + let compare_legacy = has("expected-warnings.json") || !has("script.json"); + if compare_legacy && want_legacy.iter().map(String::as_str).collect::>() != legacy { + failures.push(format!("warnings: want {want_legacy:?} got {legacy:?}")); + } + // A fixture that declares no warning at all loads without one (a script fixture + // pins model queries instead, so its typed warnings are not compared either). + if !has("expected-warnings.json") + && !has("script.json") + && !has("expected-errors.json") + && out.warnings.iter().any(|w| w.code != WARN_LEGACY) + { + failures.push(format!( + "unexpected warning(s): {:?}", + out.warnings.iter().map(|w| w.code).collect::>() + )); } failures } @@ -372,12 +534,20 @@ fn metamodel_corpus() { ); let only = std::env::var("MO_FIXTURE").ok(); + // MO_FILTER= runs the fixtures whose name contains it and prints why each + // failing one fails; MO_REPORT=1 runs everything and lists, instead of asserting, + // the ledgered fixtures that now pass and every unlisted failure (a regression). + let filter = std::env::var("MO_FILTER").ok(); + let report = std::env::var("MO_REPORT").is_ok(); + let narrowed = only.is_some() || filter.is_some(); let mut passed = 0; let mut unexpected = Vec::new(); let mut fixed = Vec::new(); for dir in &dirs { let name = dir.file_name().unwrap().to_string_lossy().into_owned(); - if only.as_deref().is_some_and(|o| o != name) { + if only.as_deref().is_some_and(|o| o != name) + || filter.as_deref().is_some_and(|f| !name.contains(f)) + { continue; } let failures = check(dir); @@ -386,7 +556,7 @@ fn metamodel_corpus() { (true, false) => passed += 1, (true, true) => fixed.push(name), (false, true) => { - if only.is_some() { + if narrowed { eprintln!("{name} [known gap]: {}", failures.join("; ")); } } @@ -404,11 +574,16 @@ fn metamodel_corpus() { "warning: fixture fails in Rust and is not on the ledger (preview port, not a gate failure): {failure}" ); } + if report { + eprintln!("NOW PASSING (remove from the ledger): {fixed:?}"); + eprintln!("UNLISTED FAILURES: {}", unexpected.len()); + return; + } assert!( fixed.is_empty(), "these ledgered fixtures now pass; remove them from the ledger (it may only shrink): {fixed:?}" ); - if only.is_none() { + if !narrowed { assert!( passed as u64 >= min_passing, "{passed} fixtures pass but the ledger's minPassing is {min_passing}: a fixture that passed has regressed (see the warnings above)" diff --git a/server/rust/metaobjects/tests/naming_conformance.rs b/server/rust/metaobjects/tests/naming_conformance.rs index 1e540462e7..42638ce2ad 100644 --- a/server/rust/metaobjects/tests/naming_conformance.rs +++ b/server/rust/metaobjects/tests/naming_conformance.rs @@ -83,6 +83,19 @@ fn load(sources: &[(String, String)]) -> (Tree, NodeId) { (r.tree, r.root) } +/// Load a model the validator is expected to refuse, keeping the tree so a resolver can be +/// exercised on it directly (the resolver's own conflict check is defence in depth). +fn load_refused(sources: &[(String, String)], code: &str) -> (Tree, NodeId) { + let registry = default_registry().expect("the built-in providers compose"); + let r = Loader::new(®istry).load_sources(sources); + assert!( + r.errors.iter().all(|e| e.code == code) && !r.errors.is_empty(), + "{:?}", + r.errors + ); + (r.tree, r.root) +} + fn s(v: &Value) -> &str { v.as_str().expect("string") } @@ -430,14 +443,17 @@ fn physical_names() { #[test] fn a_conflicting_primary_source_pair_is_refused() { - let (tree, root) = load(&[( - "meta.a.json".to_string(), - r#"{"metadata.root": {"package": "acme", "children": [ + let (tree, root) = load_refused( + &[( + "meta.a.json".to_string(), + r#"{"metadata.root": {"package": "acme", "children": [ {"object.entity": {"name": "A", "children": [ {"source.rdb": {"@table": "a_one", "@schema": "s1"}}, {"source.rdb": {"name": "second", "@table": "a_two"}}]}}]}}"# - .to_string(), - )]); + .to_string(), + )], + "ERR_SOURCE_MULTIPLE_PRIMARY", + ); let registry = NamingRegistry::builtin(); let naming = PhysicalNaming::default(); let ctx = NamingCtx::new(®istry, &naming); diff --git a/server/rust/metaobjects/tests/naming_validation.rs b/server/rust/metaobjects/tests/naming_validation.rs new file mode 100644 index 0000000000..ee191868f3 --- /dev/null +++ b/server/rust/metaobjects/tests/naming_validation.rs @@ -0,0 +1,219 @@ +//! Validation that resolves physical names (column collisions) or collection names +//! (`@via` reverse hops) honours the project's `naming` setting and the reference's +//! own-only `@collectionName` rule. Oracle: the TypeScript `resolveColumnName`, +//! `resolveFlattenedColumnName` and `reverseHopName` behaviour. + +use metaobjects::LoadResult; +use metaobjects::config::parse_config_text; +use metaobjects::loader::Loader; +use metaobjects::naming::{NamingRegistry, PhysicalNaming}; +use metaobjects::providers::default_registry; + +fn load(doc: &str, naming: PhysicalNaming) -> LoadResult { + let registry = default_registry().expect("the built-in providers compose"); + Loader::new(®istry) + .naming(NamingRegistry::builtin(), naming) + .load_sources(&[("meta.t.json".to_string(), doc.to_string())]) +} + +fn columns(strategy: &str) -> PhysicalNaming { + PhysicalNaming { + columns: strategy.to_string(), + ..PhysicalNaming::default() + } +} + +fn collections(pluralizer: &str) -> PhysicalNaming { + PhysicalNaming { + collections: Some(pluralizer.to_string()), + ..PhysicalNaming::default() + } +} + +fn collides(r: &LoadResult) -> bool { + r.errors + .iter() + .any(|e| e.code == "ERR_COLUMN_NAME_COLLISION") +} + +fn entity_with_fields(a: &str, b: &str) -> String { + format!( + r#"{{"metadata.root": {{"package": "t", "children": [ + {{"object.entity": {{"name": "User", "children": [ + {{"source.rdb": {{"@table": "users"}}}}, + {{"field.long": {{"name": "id"}}}}, + {{"field.string": {{"name": "{a}"}}}}, + {{"field.string": {{"name": "{b}"}}}}, + {{"identity.primary": {{"name": "id", "@fields": "id"}}}} + ]}}}} + ]}}}}"# + ) +} + +#[test] +fn camel_and_snake_names_collide_only_under_a_folding_strategy() { + let doc = entity_with_fields("userId", "user_id"); + assert!(collides(&load(&doc, PhysicalNaming::default()))); + assert!(!collides(&load(&doc, columns("literal")))); + assert!(!collides(&load(&doc, columns("pascal")))); +} + +#[test] +fn pascal_still_collides_names_that_differ_only_in_the_first_letter() { + let doc = entity_with_fields("userId", "UserId"); + assert!(collides(&load(&doc, columns("pascal")))); + assert!(!collides(&load(&doc, columns("literal")))); +} + +#[test] +fn a_flattened_prefix_follows_the_column_strategy() { + let doc = r#"{"metadata.root": {"package": "t", "children": [ + {"object.value": {"name": "Address", "children": [ + {"field.string": {"name": "street"}}]}}, + {"object.entity": {"name": "Order", "children": [ + {"source.rdb": {"@table": "orders"}}, + {"field.long": {"name": "id"}}, + {"field.string": {"name": "home_address_street"}}, + {"field.object": {"name": "homeAddress", "@objectRef": "t::Address", "@storage": "flattened"}}, + {"identity.primary": {"name": "id", "@fields": "id"}} + ]}} + ]}}"#; + assert!(collides(&load(doc, PhysicalNaming::default()))); + assert!(!collides(&load(doc, columns("literal")))); +} + +fn hop_doc(holder_extra: &str, holder_name: &str, holder_super: &str, via: &str) -> String { + format!( + r#"{{"metadata.root": {{"package": "acme", "children": [ + {{"object.entity": {{"name": "Patient", "children": [ + {{"source.rdb": {{"@table": "patients"}}}}, + {{"field.long": {{"name": "id"}}}}, + {{"identity.primary": {{"name": "id", "@fields": "id"}}}} + ]}}}}, + {{"object.entity": {{"name": "Base", "abstract": true{holder_extra}}}}}, + {{"object.entity": {{"name": "{holder_name}"{holder_super}, "children": [ + {{"source.rdb": {{"@table": "holders"}}}}, + {{"field.long": {{"name": "id"}}}}, + {{"field.long": {{"name": "patientId"}}}}, + {{"field.boolean": {{"name": "onFile"}}}}, + {{"identity.primary": {{"name": "id", "@fields": "id"}}}}, + {{"identity.reference": {{"name": "patient", "@fields": "patientId", "@references": "acme::Patient"}}}} + ]}}}}, + {{"object.projection": {{"name": "Row", "children": [ + {{"source.rdb": {{"@kind": "view", "@view": "v_row"}}}}, + {{"field.long": {{"name": "id", "extends": "acme::Patient.id"}}}}, + {{"field.boolean": {{"name": "onFile", "children": [ + {{"origin.passthrough": {{"@from": "acme::{holder_name}.onFile", "@via": "acme::Patient.{via}"}}}}]}}}}, + {{"identity.primary": {{"name": "id", "extends": "acme::Patient.id"}}}} + ]}}}} + ]}}}}"# + ) +} + +fn hop_resolved(r: &LoadResult, hop: &str) -> bool { + r.errors.iter().any(|e| { + e.code == "ERR_ORIGIN_CARDINALITY" && e.message.contains(&format!("@via hop \"{hop}\"")) + }) +} + +#[test] +fn an_already_plural_holder_name_is_its_own_hop_name() { + let doc = hop_doc("", "Settings", "", "settings"); + let r = load(&doc, PhysicalNaming::default()); + assert!(hop_resolved(&r, "settings"), "{:?}", r.errors); +} + +#[test] +fn an_abstract_bases_collection_name_does_not_name_its_subtypes_hop() { + let extra = r#", "@collectionName": "things""#; + let sup = r#", "extends": "acme::Base""#; + let own = load( + &hop_doc(extra, "Consent", sup, "consents"), + PhysicalNaming::default(), + ); + assert!(hop_resolved(&own, "consents"), "{:?}", own.errors); + let leaked = load( + &hop_doc(extra, "Consent", sup, "things"), + PhysicalNaming::default(), + ); + assert!(!hop_resolved(&leaked, "things"), "{:?}", leaked.errors); +} + +#[test] +fn the_project_pluralizer_names_the_hop() { + let none = load(&hop_doc("", "Consent", "", "consent"), collections("none")); + assert!(hop_resolved(&none, "consent"), "{:?}", none.errors); + let standard = load( + &hop_doc("", "Consent", "", "consent"), + PhysicalNaming::default(), + ); + assert!(!hop_resolved(&standard, "consent"), "{:?}", standard.errors); +} + +fn project_registry() -> NamingRegistry { + let mut r = NamingRegistry::builtin(); + r.register_column_strategy("lower-first", |n| { + let mut c = n.chars(); + c.next() + .map(|f| f.to_lowercase().chain(c).collect()) + .unwrap_or_default() + }) + .unwrap(); + r.register_pluralizer("add-list", |n| format!("{n}List")) + .unwrap(); + r +} + +fn load_configured(doc: &str, registry: NamingRegistry, naming_json: &str) -> LoadResult { + let text = format!(r#"{{"schema_version": 1, "naming": {naming_json}}}"#); + let naming = parse_config_text(&text, "config.json", ®istry) + .expect("the config names registered strategies") + .config + .physical_naming(); + Loader::new(&default_registry().unwrap()) + .naming(registry, naming) + .load_sources(&[("meta.t.json".to_string(), doc.to_string())]) +} + +#[test] +fn a_registered_column_strategy_resolves_column_names() { + let doc = entity_with_fields("userId", "UserId"); + let r = load_configured(&doc, project_registry(), r#"{"columns": "lower-first"}"#); + assert!(collides(&r), "{:?}", r.errors); + let r = load_configured( + &entity_with_fields("userId", "user_id"), + project_registry(), + r#"{"columns": "lower-first"}"#, + ); + assert!(r.errors.is_empty(), "{:?}", r.errors); +} + +#[test] +fn a_registered_pluralizer_names_the_reverse_hop() { + let naming = r#"{"collections": "add-list"}"#; + let r = load_configured( + &hop_doc("", "Consent", "", "consentList"), + project_registry(), + naming, + ); + assert!(hop_resolved(&r, "consentList"), "{:?}", r.errors); + let r = load_configured( + &hop_doc("", "Consent", "", "consents"), + project_registry(), + naming, + ); + assert!(!hop_resolved(&r, "consents"), "{:?}", r.errors); +} + +#[test] +fn an_unregistered_strategy_is_one_error_not_one_per_field() { + let doc = entity_with_fields("userId", "name"); + let r = load(&doc, columns("no-such-strategy")); + let unknown: Vec<_> = r + .errors + .iter() + .filter(|e| e.message.contains("no-such-strategy")) + .collect(); + assert_eq!(unknown.len(), 1, "{:?}", r.errors); + assert_eq!(r.errors.len(), 1, "{:?}", r.errors); +} diff --git a/server/rust/metaobjects/tests/relationships.rs b/server/rust/metaobjects/tests/relationships.rs new file mode 100644 index 0000000000..36f8e38e80 --- /dev/null +++ b/server/rust/metaobjects/tests/relationships.rs @@ -0,0 +1,94 @@ +//! Relationship validation cases the shared corpus does not pin: the valid shapes +//! (so the rules do not over-reject) and the reference-ladder name pairing. + +use metaobjects::loader::Loader; +use metaobjects::providers::default_registry; + +fn codes(doc: &str) -> Vec<&'static str> { + let registry = default_registry().expect("the built-in providers compose"); + let r = Loader::new(®istry).load_sources(&[("meta.a.json".to_string(), doc.to_string())]); + r.errors.iter().map(|e| e.code).collect() +} + +fn entity(name: &str, extra: &str) -> String { + format!( + r#"{{"object.entity": {{"name": "{name}", "children": [ + {{"source.rdb": {{"@table": "t_{name}"}}}}, + {{"field.long": {{"name": "id"}}}}, + {{"identity.primary": {{"name": "pk", "@fields": ["id"]}}}}{extra}]}}}}"# + ) +} + +fn doc(entities: &[String]) -> String { + format!( + r#"{{"metadata.root": {{"package": "acme", "children": [{}]}}}}"#, + entities.join(",") + ) +} + +fn junction(a: &str, b: &str) -> String { + entity( + "Link", + &format!( + r#",{{"field.long": {{"name": "aId"}}}},{{"field.long": {{"name": "bId"}}}}, + {{"identity.reference": {{"name": "ra", "@fields": ["aId"], "@references": "{a}"}}}}, + {{"identity.reference": {{"name": "rb", "@fields": ["bId"], "@references": "{b}"}}}}"# + ), + ) +} + +fn m2m(attrs: &str) -> String { + format!( + r#",{{"relationship.association": {{"name": "others", "@cardinality": "many", + "@through": "Link", "@objectRef": "Tag"{attrs}}}}}"# + ) +} + +#[test] +fn a_heterogeneous_m2m_through_a_paired_junction_loads_clean() { + let d = doc(&[ + entity("Post", &m2m("")), + entity("Tag", ""), + junction("Post", "Tag"), + ]); + assert_eq!(codes(&d), Vec::<&str>::new()); +} + +#[test] +fn a_junction_that_never_names_the_navigating_entity_is_unpairable() { + let d = doc(&[ + entity("Post", &m2m("")), + entity("Tag", ""), + entity("Other", ""), + junction("Tag", "Other"), + ]); + assert_eq!(codes(&d), ["ERR_INVALID_RELATIONSHIP"]); +} + +#[test] +fn symmetric_is_valid_on_a_self_join() { + let rel = r#",{"relationship.association": {"name": "friends", "@cardinality": "many", + "@through": "Link", "@objectRef": "Person", "@symmetric": true}}"#; + let d = doc(&[entity("Person", rel), junction("Person", "Person")]); + assert_eq!(codes(&d), Vec::<&str>::new()); +} + +#[test] +fn a_one_side_relationship_pairs_with_one_of_two_references_by_name() { + let refs = r#",{"field.long": {"name": "homeId"}},{"field.long": {"name": "awayId"}}, + {"identity.reference": {"name": "home", "@fields": ["homeId"], "@references": "Team"}}, + {"identity.reference": {"name": "away", "@fields": ["awayId"], "@references": "Team"}}, + {"relationship.association": {"name": "home", "@cardinality": "one", "@objectRef": "Team"}}"#; + let d = doc(&[entity("Match", refs), entity("Team", "")]); + assert_eq!(codes(&d), Vec::<&str>::new()); +} + +#[test] +fn a_one_side_relationship_matching_no_reference_name_is_ambiguous() { + let refs = r#",{"field.long": {"name": "homeId"}},{"field.long": {"name": "awayId"}}, + {"identity.reference": {"name": "home", "@fields": ["homeId"], "@references": "Team"}}, + {"identity.reference": {"name": "away", "@fields": ["awayId"], "@references": "Team"}}, + {"relationship.association": {"name": "team", "@cardinality": "one", "@objectRef": "Team"}}"#; + let d = doc(&[entity("Match", refs), entity("Team", "")]); + assert_eq!(codes(&d), ["ERR_INVALID_RELATIONSHIP"]); +} diff --git a/server/rust/metaobjects/tests/yaml-conformance-expected-failures.json b/server/rust/metaobjects/tests/yaml-conformance-expected-failures.json index 8911dde1c7..431b43e568 100644 --- a/server/rust/metaobjects/tests/yaml-conformance-expected-failures.json +++ b/server/rust/metaobjects/tests/yaml-conformance-expected-failures.json @@ -1,12 +1,9 @@ { "language": "rust", "corpus": "fixtures/yaml-conformance", - "notes": "Every YAML-specific behaviour passes: the desugar, the coercion guard, positions, anchors, block scalars. The four fixtures below need passes that belong to the validation and reference-resolution step of this port, and leave the ledger when it lands: error-yaml-coerced-bool-in-int and error-yaml-coerced-num-in-enum expect the attribute-schema pass's ERR_BAD_ATTR_VALUE after the ERR_YAML_COERCION; yaml-ref-root-escape needs ADR-0059 R2 root-level `::` references and package-aware merging; yaml-reporting-via-of-bare needs ADR-0059 R3 (a bare `of` owner resolves in the package of the entity its via reaches). The ledger may only shrink and minPassing may only rise.", - "minPassing": 15, + "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": [ - "error-yaml-coerced-bool-in-int", - "error-yaml-coerced-num-in-enum", - "yaml-ref-root-escape", - "yaml-reporting-via-of-bare" + "yaml-ref-root-escape" ] }