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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions changelog.d/java-reference-facet.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
- **The Java loader reads and enforces the reference facet** (`ref` on a `type: "attr"` entry of
a provider definition, `spec/metamodel-definitions.md`), matching the TypeScript and C#
loaders; Kotlin runs on it. The spec reader validates the facet and carries it to the attr's
`ChildRequirement.getRef()` (or `CommonAttributeDef.ref()`). The lookup is typed by the target.
A dotted value resolves `System.child` and `pkg::System.child`, and a bare value is looked for
in the referrer's own containers first. A value that names nothing (`ERR_REF_UNRESOLVED`), the
wrong kind of node (`ERR_REF_WRONG_KIND`) or a node of another system (the facet's own code) is
refused. A canonical value is the path the lookup walked; a value whose canonical spelling
would not look up the same target is kept as written. The registry manifest writes `ref` only
on an attribute that has one. No definition file uses the facet yet, so no registry, manifest
or generated output changes. A provider's own code that is not an `ErrorCode` member now keeps
its spelling in `MetaDataException.getProviderCode()` (`getCode()` stays `ERR_UNKNOWN`;
`getCodeName()` gives either). A parent-relative `@references` value (`..::Address.id`) now
resolves its owner instead of reading the `..` as one. As in TypeScript, an `@objectRef` or
`@references` value whose `..::` climbs above the root package now raises
`ERR_BAD_ATTR_VALUE` instead of the reference's own code, and an inherited one is checked in
the package of the node that declares it, not the inheritor's. A dotted `extends` whose owner is a
top-level node other than an object (`acme::Parcels.base`) now resolves, as it does in
TypeScript and C#.

Upgrading: Java `ReferenceDescriptor` is now `(attr, facet)`. A provider that attaches
references to its type definition in code builds
`new ReferenceDescriptor(attr, new ReferenceFacet(...))`, or
`ReferenceFacet.of(targetType, errorCode)`. `targetType` and `errorCode` move onto
`ReferenceFacet` (where `errorCode` is optional), `targetSubType` becomes the list
`ReferenceFacet.targetSubTypes()`, and `dottedFieldPath` becomes `ReferenceFacet.fieldPath()`.
Java `SymbolTable` no longer has its public no-argument constructor (`SymbolTable`), which
built an empty table; build one from a loaded root with `SymbolTable.build(root)`.
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ public class MetaDataException extends RuntimeException {
*/
private final ErrorSource envelope;

/**
* A provider's own error code, as it spelled it, when the code is not one of
* {@link ErrorCode}'s (a reference facet's {@code errorCode}, for instance); {@code code} is
* then {@link ErrorCode#ERR_UNKNOWN}. {@code null} otherwise.
*/
private final String providerCode;

/**
* Creates a MetaDataException with a simple message.
* Backward compatible constructor.
Expand Down Expand Up @@ -166,6 +173,7 @@ public MetaDataException(String message, MetaData source, String operation,
super(buildEnhancedMessage(message, source, operation, additionalContext), cause);

this.code = code;
this.providerCode = null;
this.envelope = envelope;
this.metaDataPath = source != null ? MetaDataPath.buildPath(source) : null;
this.operation = operation;
Expand Down Expand Up @@ -195,6 +203,39 @@ public MetaDataException(String message, ErrorCode code, ErrorSource envelope) {
this(message, null, null, null, Collections.emptyMap(), code, envelope);
}

/**
* A loader finding raised under a code that may be a provider's own: an {@link ErrorCode}
* member sets {@link #getCode()}; any other code is kept as {@link #getProviderCode()}, with
* {@link #getCode()} {@link ErrorCode#ERR_UNKNOWN}.
*
* @param message the error message
* @param codeName the code as raised
* @param envelope the loader error envelope provenance; {@code null} permitted
*/
public static MetaDataException ofCodeName(String message, String codeName, ErrorSource envelope) {
return new MetaDataException(message, codeName, envelope, true);
}

private MetaDataException(String message, String codeName, ErrorSource envelope, boolean byName) {
super(buildEnhancedMessage(message, null, null, Collections.emptyMap()), null);
ErrorCode known = null;
if (codeName != null) {
try {
known = ErrorCode.valueOf(codeName);
} catch (IllegalArgumentException ex) {
known = null;
}
}
this.code = known != null ? known : ErrorCode.ERR_UNKNOWN;
this.providerCode = known == null ? codeName : null;
this.envelope = envelope;
this.metaDataPath = null;
this.operation = null;
this.context = new LinkedHashMap<>();
this.timestamp = System.currentTimeMillis();
this.threadName = Thread.currentThread().getName();
}

/**
* Builds an enhanced error message with context information.
*
Expand Down Expand Up @@ -247,6 +288,26 @@ public Optional<ErrorCode> getCode() {
return Optional.ofNullable(code);
}

/**
* A provider's own error code that is not an {@link ErrorCode} member, as the provider
* spelled it (a reference facet's {@code errorCode}, for instance), or empty.
*
* @return Optional containing the provider's code, or empty
*/
public Optional<String> getProviderCode() {
return Optional.ofNullable(providerCode);
}

/**
* The code as raised: {@link #getProviderCode()} when set, else {@link #getCode()}'s name,
* else empty.
*
* @return Optional containing the code's name, or empty
*/
public Optional<String> getCodeName() {
return providerCode != null ? Optional.of(providerCode) : getCode().map(Enum::name);
}

/**
* FR5a / ADR-0009 — Returns the loader error envelope provenance, if any.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ public static void registerTypes(MetaDataRegistry registry) {
// package-locally (dangling target = load error). Fires only when
// @objectRef is present (a scalar-valued map uses @valueType instead).
.reference(new com.metaobjects.validation.ReferenceDescriptor(
MetaObject.ATTR_OBJECT_REF, MetaObject.TYPE_OBJECT,
null, false, "ERR_UNRESOLVED_OBJECT_REF"));
MetaObject.ATTR_OBJECT_REF, com.metaobjects.validation.ReferenceFacet.of(
MetaObject.TYPE_OBJECT, "ERR_UNRESOLVED_OBJECT_REF")));
});

log.debug("Registered MapField type with unified registry");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ public static void registerTypes(MetaDataRegistry registry) {
// only when @objectRef is present (absence is
// ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF's job).
.reference(new com.metaobjects.validation.ReferenceDescriptor(
MetaObject.ATTR_OBJECT_REF, MetaObject.TYPE_OBJECT,
null, false, "ERR_UNRESOLVED_OBJECT_REF"));
MetaObject.ATTR_OBJECT_REF, com.metaobjects.validation.ReferenceFacet.of(
MetaObject.TYPE_OBJECT, "ERR_UNRESOLVED_OBJECT_REF")));
});

log.debug("Registered ObjectField type with unified registry");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ public static void registerTypes(MetaDataRegistry registry) {
// @references is a cross-reference to a real object (FK target) — the loader's
// registry-derived validation resolves it; "Entity.field" forms resolve the entity.
def.reference(new com.metaobjects.validation.ReferenceDescriptor(
ATTR_REFERENCES, com.metaobjects.object.MetaObject.TYPE_OBJECT, null, true, "ERR_INVALID_REFERENCE"));
ATTR_REFERENCES, new com.metaobjects.validation.ReferenceFacet(
com.metaobjects.object.MetaObject.TYPE_OBJECT, null, true, false, "ERR_INVALID_REFERENCE", null)));
def.optionalAttributeWithConstraints(ATTR_ENFORCE).ofType(BooleanAttribute.SUBTYPE_BOOLEAN).asSingle();
// RDB-physical FK constraint-name override contributed by the db provider
// (db.json extends identity.reference). Description sourced from the embedded
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -518,9 +518,14 @@ private MetaData resolveOwnerObject(PendingExtends p) {
}
String ownerRef = p.superName.substring(0, segStart) + parts[0];
// ADR-0059 R2/R3 — the owner resolves by the one resolver, in the declaring node's
// package (a nested referrer takes its enclosing top-level node's).
return References.resolveOwner(root, ownerRef, References.extendsPackageOf(p.child),
// package (a nested referrer takes its enclosing top-level node's). An object owner
// first, as before; failing that, a top-level node of any type (ADR-0029: the package
// qualifies the root-level node, whatever its type — a `System.child` extends), as the
// TS and C# resolvers do.
String pkg = References.extendsPackageOf(p.child);
MetaData owner = References.resolveOwner(root, ownerRef, pkg,
com.metaobjects.object.MetaObject.TYPE_OBJECT).node();
return owner != null ? owner : References.resolveOwner(root, ownerRef, pkg, null).node();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,27 +262,101 @@ public static MetaData topLevelRoot(MetaData node) {
* the last validation pass. A reference that does not resolve is left as written.
*/
public static void resolveReferences(MetaRoot root) {
visit(root, root);
resolveReferences(root, null);
}

/**
* As {@link #resolveReferences(MetaRoot)}; with {@code registry}, an attribute whose
* requirement carries the reference facet ({@code spec/metamodel-definitions.md}) is resolved
* too, by the facet's typed lookup.
*/
public static void resolveReferences(MetaRoot root, com.metaobjects.registry.MetaDataRegistry registry) {
visit(root, root, new FacetState(root, registry));
flushCaches(root);
}

private static void visit(MetaRoot root, MetaData node) {
/** The registry the facets come from and the symbol table, built on first use. */
private static final class FacetState {
private final MetaRoot root;
private final com.metaobjects.registry.MetaDataRegistry registry;
private final java.util.Map<com.metaobjects.registry.TypeDefinition,
java.util.Map<String, com.metaobjects.validation.ReferenceFacet>> facets = new java.util.IdentityHashMap<>();
private com.metaobjects.validation.SymbolTable symbols;

FacetState(MetaRoot root, com.metaobjects.registry.MetaDataRegistry registry) {
this.root = root;
this.registry = registry;
}

com.metaobjects.validation.SymbolTable symbols() {
if (symbols == null) symbols = com.metaobjects.validation.SymbolTable.build(root);
return symbols;
}

com.metaobjects.validation.ReferenceFacet facetOf(MetaData node, String attrName) {
if (registry == null || node.getType() == null || node.getSubType() == null) return null;
com.metaobjects.registry.TypeDefinition def = registry.getTypeDefinition(node.getType(), node.getSubType());
if (def == null) return null;
return facets.computeIfAbsent(def, d -> {
java.util.Map<String, com.metaobjects.validation.ReferenceFacet> byName = new java.util.HashMap<>();
for (com.metaobjects.validation.ReferenceDescriptor desc
: com.metaobjects.loader.validation.RegisteredValidation.referenceAttrDescriptors(d, registry)) {
byName.put(desc.attr(), desc.facet());
}
return byName;
}).get(attrName);
}
}

private static void visit(MetaRoot root, MetaData node, FacetState state) {
if (node != root) {
resolveExtends(root, node);
String declPkg = effectivePackageOf(node);
// ADR-0039: own — this pass rewrites the declared-here layer; an inherited attribute
// is resolved once, on the node that declares it.
for (MetaAttribute<?> attr : new ArrayList<>(node.getMetaAttrs(false))) {
if (isRefBearingAttr(node, attr.getName())) resolveAttr(root, node, attr, declPkg);
com.metaobjects.validation.ReferenceFacet facet = state.facetOf(node, attr.getName());
if (facet != null) {
bindAttr(attr, facetResolver(state.symbols(), node, facet, declPkg));
} else if (isRefBearingAttr(node, attr.getName())) {
resolveAttr(root, node, attr, declPkg);
}
}
}
// ADR-0039: own — structural walk over the physical declaration tree.
for (MetaData child : new ArrayList<>(node.getChildren(MetaData.class, false))) {
if (child instanceof MetaAttribute) continue;
visit(root, child);
visit(root, child, state);
}
}

/**
* A facet reference ({@code spec/metamodel-definitions.md}, rule 7): the target the typed
* lookup finds, spelled as the top-level owner it was reached through plus the child names
* walked. A {@code fieldPath} value keeps its field segment. A spelling that would not look up
* the same target again keeps the value as written.
*/
private static java.util.function.Function<String, Resolved> facetResolver(
com.metaobjects.validation.SymbolTable symbols, MetaData node,
com.metaobjects.validation.ReferenceFacet facet, String declPkg) {
return value -> {
List<MetaData> path = symbols.lookup(node, value, facet, declPkg).path();
if (path == null || path.isEmpty()) return null;
MetaData target = path.get(path.size() - 1);
String tail;
if (facet.fieldPath()) {
tail = splitChildTail(value).tail();
} else {
StringBuilder walked = new StringBuilder();
for (int i = 1; i < path.size(); i++) walked.append('.').append(path.get(i).getShortName());
tail = walked.toString();
}
String canonical = spellRef(path.get(0), declPkg, tail);
MetaData again = symbols.lookup(node, canonical, facet, declPkg).target();
return new Resolved(target, again == target ? canonical : value);
};
}

private static void flushCaches(MetaData node) {
node.invalidateCaches();
for (MetaData child : node.getChildren(MetaData.class, false)) flushCaches(child);
Expand Down Expand Up @@ -328,14 +402,19 @@ private static Resolved resolveOne(MetaRoot root, String value, String refPkg, S
return new Resolved(target, spellRef(target, !refPkg.isEmpty() ? refPkg : declPkg, s.tail()));
}

private static void resolveAttr(MetaRoot root, MetaData node, MetaAttribute<?> attr, String declPkg) {
String refPkg = referrerPackage(root, node, attr.getName(), declPkg);
bindAttr(attr, v -> resolveOne(root, v, refPkg, declPkg));
}

/** Record each resolved value's target on {@code attr} and rewrite it to its canonical spelling. */
@SuppressWarnings({"unchecked", "rawtypes"})
private static void resolveAttr(MetaRoot root, MetaData node, MetaAttribute attr, String declPkg) {
private static void bindAttr(MetaAttribute attr, java.util.function.Function<String, Resolved> resolveValue) {
Object value = attr.getValue();
String refPkg = referrerPackage(root, node, attr.getName(), declPkg);
if (value instanceof String) {
String v = (String) value;
if (v.isEmpty()) return;
Resolved r = resolveOne(root, v, refPkg, declPkg);
Resolved r = resolveValue.apply(v);
if (r == null) return;
attr.setResolvedTarget(r.target());
if (!r.canonical().equals(v)) {
Expand All @@ -350,7 +429,7 @@ private static void resolveAttr(MetaRoot root, MetaData node, MetaAttribute attr
List<Resolved> resolved = new ArrayList<>();
boolean any = false;
for (String v : items) {
Resolved r = v.isEmpty() ? null : resolveOne(root, v, refPkg, declPkg);
Resolved r = v.isEmpty() ? null : resolveValue.apply(v);
if (r != null) any = true;
resolved.add(r);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,8 @@ public static void run(MetaRoot root, MetaDataLoader loader) {
if (loader != null && loader.getTypeRegistry() != null) {
for (com.metaobjects.validation.ValidationError e :
com.metaobjects.loader.validation.RegisteredValidation.run(root, loader.getTypeRegistry())) {
collected.add(new MetaDataException(e.message(), toErrorCode(e.code()), e.source()));
// A provider's own code (a reference facet's errorCode) is kept as it was raised.
collected.add(MetaDataException.ofCodeName(e.message(), e.code(), e.source()));
}
}
pass(collected, () -> validateOrigins(root));
Expand Down Expand Up @@ -344,7 +345,7 @@ public static void run(MetaRoot root, MetaDataLoader loader) {
// ADR-0059 R5 — after the last validation pass, resolve every reference once: record the
// bound target and rewrite the value to its canonical spelling. The passes above resolved
// the AUTHORED strings, so their codes and order are unchanged.
References.resolveReferences(root);
References.resolveReferences(root, loader != null ? loader.getTypeRegistry() : null);
}

/** Run one validation pass, catching its finding (if any) into {@code collected} so the
Expand All @@ -369,7 +370,7 @@ private static java.util.List<MetaDataException> dedupe(
java.util.Map<String, MetaDataException> byKey = new java.util.LinkedHashMap<>();
for (int i = 0; i < in.size(); i++) {
MetaDataException e = in.get(i);
String code = e.getCode().map(Enum::name).orElse("");
String code = e.getCodeName().orElse("");
String env = e.getEnvelope().map(Object::toString).orElse("");
// No code AND no envelope → nothing to dedupe on; tag with the index so distinct
// such findings are not collapsed into one.
Expand All @@ -382,17 +383,6 @@ private static java.util.List<MetaDataException> dedupe(
return new java.util.ArrayList<>(byKey.values());
}

/** Map a (possibly downstream) error-code STRING to the {@link ErrorCode} enum, falling back
* to {@link ErrorCode#ERR_UNKNOWN} for a code not in the enum — so a downstream provider's
* custom code never throws out of the validation walk (the message carries the raw code). */
private static ErrorCode toErrorCode(String code) {
try {
return ErrorCode.valueOf(code);
} catch (IllegalArgumentException | NullPointerException ex) {
return ErrorCode.ERR_UNKNOWN;
}
}

/**
* Legacy entry point retained for callers that do not have a loader handle.
* Delegates to {@link #run(MetaRoot, MetaDataLoader)} with a {@code null}
Expand Down Expand Up @@ -2406,8 +2396,8 @@ private static List<String> junctionReferenceFkFields(MetaObject junction) {
// =========================================================================

// NOTE: identity.reference @references resolution moved to the validation registry
// (RegisteredValidation.defaultRegistry → a declarative reference descriptor with
// dottedFieldPath). See the registry run in run(...).
// (RegisteredValidation: a declarative reference descriptor whose facet sets
// fieldPath). See the registry run in run(...).

// =========================================================================
// field.object + @storage validation
Expand Down
Loading
Loading