diff --git a/changelog.d/csharp-reference-facet.md b/changelog.d/csharp-reference-facet.md new file mode 100644 index 0000000000..c9a7d8be5c --- /dev/null +++ b/changelog.d/csharp-reference-facet.md @@ -0,0 +1,19 @@ +- **The C# loader reads and enforces the reference facet** (`ref` on a `type: "attr"` entry of + a provider definition, `spec/metamodel-definitions.md`), matching the TypeScript loader: the + spec reader validates the facet and carries it to `AttrSchema.Ref`, the lookup is typed by the + target, a dotted value resolves `System.child` and `pkg::System.child`, a bare value is looked + for in the referrer's own containers first, and a value that names nothing + (`ERR_REF_UNRESOLVED`), the wrong kind of node (`ERR_REF_WRONG_KIND`) or a node of another + system (the facet's own code) is refused. A canonical value is the path the lookup walked, and + 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 `MetaError.ProviderCode` (`Code` stays + `ERR_UNKNOWN`; `CodeName` gives either). A parent-relative `@references` value + (`..::Address.id`) now resolves its owner instead of reading the `..` as one. + + Upgrading: C# `ReferenceDescriptor` is now `(Attr, Facet)`. A provider that sets + `TypeDefinition.References` in code builds `new ReferenceDescriptor(attr, new ReferenceFacet(...))`. + `TargetType` and `ErrorCode` move onto `ReferenceFacet` (where `ErrorCode` is optional), + `TargetSubType` becomes the list `ReferenceFacet.TargetSubTypes`, and `DottedFieldPath` becomes + `ReferenceFacet.FieldPath`. diff --git a/server/csharp/MetaObjects.Cli/GenCommand.cs b/server/csharp/MetaObjects.Cli/GenCommand.cs index 11da661015..03941fb4df 100644 --- a/server/csharp/MetaObjects.Cli/GenCommand.cs +++ b/server/csharp/MetaObjects.Cli/GenCommand.cs @@ -121,7 +121,7 @@ public static Outcome Run( string? projectRoot = null, string baseline = "default") { - var loadErrors = load.Errors.Select(e => e.Code.ToString()).ToList(); + var loadErrors = load.Errors.Select(e => e.CodeName).ToList(); if (loadErrors.Count > 0) return new Outcome(loadErrors, null); diff --git a/server/csharp/MetaObjects.Cli/VerifyCommand.cs b/server/csharp/MetaObjects.Cli/VerifyCommand.cs index 8d22fff977..828f7d3908 100644 --- a/server/csharp/MetaObjects.Cli/VerifyCommand.cs +++ b/server/csharp/MetaObjects.Cli/VerifyCommand.cs @@ -319,7 +319,7 @@ public static int RunRequirementGate(Options opts, bool requireImplementers, Tex { if (!loadFailureReported) { - foreach (var e in load.Errors) output.WriteLine($" load error: {e.Code}: {e.Message}"); + foreach (var e in load.Errors) output.WriteLine($" load error: {e.CodeName}: {e.Message}"); if (opts.Strict && load.Errors.Any(e => e.Code == ErrorCode.ERR_UNKNOWN_ATTR)) output.WriteLine($" hint: {UNKNOWN_ATTR_HINT}"); output.WriteLine("dotnet meta verify: FAILED (metadata did not load cleanly)"); @@ -435,7 +435,7 @@ private static Codegen.CodegenDrift.Result RunCodegenDrift(Options opts, List e.Code + ": " + e.Message)) + ").", + string.Join("; ", load.Errors.Select(e => e.CodeName + ": " + e.Message)) + ").", }; var names = opts.Generators ?? []; @@ -545,7 +545,7 @@ public static Outcome Run( /// public static Outcome Run(LoadResult load, string templatesRoot) { - var loadErrors = load.Errors.Select(e => e.Code.ToString()).ToList(); + var loadErrors = load.Errors.Select(e => e.CodeName).ToList(); var provider = new FilesystemProvider(templatesRoot); var errors = new List(); diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index ca89d5f88d..18c78b6620 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -238,7 +238,7 @@ public static GenOutcome RunGen( IReadOnlyList? entities = null, Func? configure = null) { - var loadErrors = load.Errors.Select(e => e.Code.ToString()).ToList(); + var loadErrors = load.Errors.Select(e => e.CodeName).ToList(); if (loadErrors.Count > 0) return new GenOutcome(loadErrors, null); var root = projectRoot ?? Directory.GetCurrentDirectory(); @@ -817,7 +817,7 @@ private static int RunGenCore(string[] rest, IReadOnlyList declared, genLoad = meta.Load(strict: true); if (genLoad.Errors.Count > 0) { - foreach (var e in genLoad.Errors) Console.Error.WriteLine($" load error: {e.Code}: {e.Message}"); + foreach (var e in genLoad.Errors) Console.Error.WriteLine($" load error: {e.CodeName}: {e.Message}"); if (genLoad.Errors.Any(e => e.Code == ErrorCode.ERR_UNKNOWN_ATTR)) Console.Error.WriteLine($" hint: {GenStrictHint}"); Console.Error.WriteLine($"{GenCommandName}: FAILED (metadata did not load cleanly; --strict)"); @@ -1032,7 +1032,7 @@ private static int RunVerifyArgs(string[] rest, IReadOnlyList declar var load = meta.Load(strict: !a.Lax); if (load.Errors.Count > 0) { - foreach (var e in load.Errors) Console.Error.WriteLine($" load error: {e.Code}: {e.Message}"); + foreach (var e in load.Errors) Console.Error.WriteLine($" load error: {e.CodeName}: {e.Message}"); Console.Error.WriteLine($"{VerifyCommandName}: FAILED (metadata did not load cleanly)"); return 1; } diff --git a/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs b/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs index 3fb2a3e008..7617444f9c 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ConformanceAdapter.cs @@ -251,14 +251,14 @@ private static LoadOutcome LoadFixtureCore( return new LoadOutcome( result.Root, - result.Errors.Select(e => e.Code.ToString()).ToList(), + result.Errors.Select(e => e.CodeName).ToList(), result.Warnings.ToList(), envelopes, warningEnvelopes); } private static ErrorEnvelopeRecord BuildEnvelope(MetaError err, string inputDir) => - BuildEnvelopeFromSource(err.Code.ToString(), err.Envelope, inputDir) with { Message = err.Message }; + BuildEnvelopeFromSource(err.CodeName, err.Envelope, inputDir) with { Message = err.Message }; private static ErrorEnvelopeRecord BuildWarningEnvelope(LoaderWarning w, string inputDir) => BuildEnvelopeFromSource(w.Code, w.Source, inputDir); diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs new file mode 100644 index 0000000000..53b9c78a38 --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/ReferenceFacetTests.cs @@ -0,0 +1,648 @@ +// The reference facet (spec/metamodel-definitions.md): the spec reader carries `ref` on an +// attr entry, the loader's generic resolver enforces it, the symbol table resolves +// `System.child` and `pkg::System.child`, the lookup is kind-typed, and the registry manifest +// writes the facet only when an attr has one. +// +// No shipped definition file uses the facet yet, so these tests compose a test provider with a +// small system vocabulary of their own: the types are registered in code, and the reference +// attributes come from a provider definition read by the spec reader. Mirrors the TS +// test/reference-facet.test.ts case for case. + +using System.Text.Json; +using MetaObjects; +using MetaObjects.Loader; +using MetaObjects.Meta; +using MetaObjects.Registry.Spec; +using MetaObjects.Validation; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +public sealed class ReferenceFacetTests +{ + private sealed class SystemTestNode(TypeId typeId, string name) : MetaData(typeId, name); + + private const string ProviderId = "test-reference-facet"; + + /// The reference attributes, as a provider definition: an `extends` entry per type. + private const string Definition = """ + { + "provider": "test-reference-facet", + "extends": [ + { "type": "app", "subType": "service", "children": [ + { "type": "attr", "subType": "string", "name": "runsAs", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "role", "sameSystem": true, "wrongSystemCode": "ERR_RUNSAS_OTHER_SYSTEM" } }, + { "type": "attr", "subType": "string", "name": "calls", "isArray": true, "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "app" } }, + { "type": "attr", "subType": "string", "name": "reads", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "resource", "fieldPath": true } } + ] }, + { "type": "grant", "subType": "rdb", "children": [ + { "type": "attr", "subType": "string", "name": "resource", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "resource", "targetSubTypes": ["rdb"], "sameSystem": true, + "wrongSystemCode": "ERR_GRANT_CROSSES_SYSTEM" } } + ] }, + { "type": "deployment", "subType": "test", "children": [ + { "type": "attr", "subType": "string", "name": "app", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "app" } }, + { "type": "attr", "subType": "string", "name": "anyRole", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "role", "errorCode": "ERR_TEST_ROLE" } }, + { "type": "attr", "subType": "string", "name": "pinnedRole", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "role", "sameSystem": true, "wrongSystemCode": "ERR_TEST_OUTSIDE" } }, + { "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Test.", + "ref": { "targetType": "role" } } + ] } + ] + } + """; + + private sealed class TestProvider : IMetaDataTypeProvider + { + public string Id => ProviderId; + public IReadOnlyList Dependencies => ["metaobjects-core-types"]; + + public void RegisterTypes(TypeRegistry registry) + { + Type("system", "software", "app", "role", "resource"); + Type("app", "service"); + Type("role", "service", "grant", "resource"); + Type("grant", "rdb"); + Type("resource", "rdb"); + Type("resource", "queue"); + Type("deployment", "test"); + registry.Extend(TYPE_METADATA, "root", childRules: + new[] { "system", "deployment", "app", "resource" }.Select(Any).ToList()); + registry.ApplyProviderExtends(SpecMetamodelReader.FromJson(Definition), ProviderId); + + void Type(string type, string subType, params string[] children) => + registry.Register(new TypeDefinition( + typeId: new TypeId(type, subType), + description: $"A test {type}.", + childRules: [new ChildRule(TYPE_ATTR, CHILD_RULE_WILDCARD, CHILD_RULE_WILDCARD), .. children.Select(Any)], + factory: (typeId, name) => new SystemTestNode(typeId, name), + attributes: [])); + } + + private static ChildRule Any(string type) => new(type, CHILD_RULE_WILDCARD, CHILD_RULE_WILDCARD); + } + + private static TypeRegistry Registry() => + Provider.ComposeRegistry([.. CoreTypes.LibraryProviders, new TestProvider()]); + + private static LoadResult Load(string text, MetaDataFormat format = MetaDataFormat.Yaml) => + new MetaDataLoader(Registry(), strict: true) + .Load([new InMemoryStringSource(text, id: format == MetaDataFormat.Yaml ? "systems.yaml" : "systems.json", format)]); + + private static List Codes(LoadResult r) => r.Errors.Select(e => e.CodeName).ToList(); + + private static void Clean(LoadResult r) => Assert.Empty(r.Errors.Select(e => $"{e.CodeName}: {e.Message}")); + + /// Two systems in package `acme`: Parcels (an app and a role both named `api`) and Ledger. + private static string Model(string parcelsExtra = "", string outside = "") => $""" + metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - resource.rdb: {"{"} name: db {"}"} + - resource.queue: {"{"} name: jobs {"}"} + - role.service: + name: api + children: + - grant.rdb: {"{"} name: g1, resource: db {"}"} + - app.service: + name: api + runsAs: api + {parcelsExtra} + - system.software: + name: Ledger + children: + - resource.rdb: {"{"} name: books {"}"} + - role.service: {"{"} name: clerk {"}"} + - app.service: {"{"} name: web, runsAs: clerk {"}"} + {outside} + """; + + /// A node by its path from the root; a step is `name` or `type:name`. + private static MetaData At(MetaData root, params string[] steps) => + steps.Aggregate(root, (n, step) => + { + int colon = step.IndexOf(':'); + string? type = colon < 0 ? null : step[..colon]; + string name = colon < 0 ? step : step[(colon + 1)..]; + return n.OwnChildren().First(c => c.Name == name && (type is null || c.Type == type)); + }); + + /// The node the loader bound on to (the first, for a list). + private static MetaData? BoundTo(MetaData node, string attr) => + node.ResolvedTargetOf(attr) ?? node.ResolvedTargetsOf(attr)?[0]; + + // ------------------------------------------------------------------ + // The spec reader + // ------------------------------------------------------------------ + + [Fact] + public void The_reader_lowers_ref_onto_the_attribute_schema() + { + var schema = Registry().FindAttrSchema("grant", "rdb", "resource"); + Assert.NotNull(schema?.Ref); + Assert.Equal("resource", schema!.Ref!.TargetType); + Assert.Equal(["rdb"], schema.Ref.TargetSubTypes!); + Assert.True(schema.Ref.SameSystem); + Assert.False(schema.Ref.FieldPath); + Assert.Null(schema.Ref.ErrorCode); + Assert.Equal("ERR_GRANT_CROSSES_SYSTEM", schema.Ref.WrongSystemCode); + } + + private static string WithRef(string reference, string subType = "string") => $$""" + { "provider": "bad", "types": [ { "type": "widget", "subType": "x", "description": "x", "children": [ + { "type": "attr", "subType": "{{subType}}", "name": "to", "min": 0, "max": 1, "description": "x", "ref": {{reference}} } + ] } ] } + """; + + [Theory] + [InlineData("""{ "targetType": "role" }""", "int", "only a string attr")] + [InlineData("""{ "targetType": "*" }""", "string", "targetType")] + [InlineData("""{ "targetType": "role", "targetSubTypes": [] }""", "string", "targetSubTypes")] + [InlineData("""{ "targetType": "role", "targetSubTypes": ["*"] }""", "string", "targetSubTypes")] + [InlineData("""{ "targetType": "role", "targetSubTypes": ["a", "a"] }""", "string", "targetSubTypes")] + [InlineData("""{ "targetType": "role", "sameSystem": true }""", "string", "wrongSystemCode")] + [InlineData("""{ "targetType": "role", "wrongSystemCode": "ERR_X" }""", "string", "wrongSystemCode")] + [InlineData("""{ "targetType": "role", "fieldPath": true, "sameSystem": true, "wrongSystemCode": "ERR_X" }""", "string", "fieldPath and sameSystem")] + [InlineData("""{ "targetType": "role", "errorCode": "bad" }""", "string", "loader code")] + [InlineData("""{ "targetType": "role", "targetSubType": "rdb" }""", "string", "unknown key \"targetSubType\"")] + [InlineData("""{ "targetType": "role", "fieldPath": "yes" }""", "string", "fieldPath must be a boolean")] + [InlineData("""[ "role" ]""", "string", "ref must be an object")] + public void The_reader_refuses_a_facet_the_format_does_not_allow(string reference, string subType, string why) + { + var ex = Assert.Throws(() => SpecMetamodelReader.FromJson(WithRef(reference, subType))); + Assert.Contains(why, ex.Message); + Assert.Contains("attr \"to\" on \"widget.x\"", ex.Message); + } + + [Fact] + public void The_reader_refuses_a_facet_on_a_structural_child() + { + const string json = """ + { "provider": "bad", "types": [ { "type": "widget", "subType": "x", "description": "x", "children": [ + { "type": "role", "subType": "*", "name": "*", "min": 0, "max": null, "ref": { "targetType": "role" } } + ] } ] } + """; + var ex = Assert.Throws(() => SpecMetamodelReader.FromJson(json)); + Assert.Contains("only an attr may be a reference", ex.Message); + } + + [Fact] + public void The_reader_carries_a_facet_on_a_types_entry_attr() + { + var reader = SpecMetamodelReader.FromJson(WithRef("""{ "targetType": "role", "targetSubTypes": ["b", "a"] }""")); + var facet = reader.AttrDoc("widget", "x", "to")?.Ref; + Assert.NotNull(facet); + Assert.Equal(["b", "a"], facet!.TargetSubTypes!); + } + + [Fact] + public void No_shipped_definition_file_uses_the_facet_yet() + { + var registry = Provider.ComposeRegistry(CoreTypes.LibraryProviders); + foreach (var id in registry.AllTypes()) + Assert.All(registry.AttrsOf(id.Type, id.SubType), a => Assert.Null(a.Ref)); + Assert.All(registry.GetCommonAttrs(), a => Assert.Null(a.Ref)); + } + + // ------------------------------------------------------------------ + // The loader + // ------------------------------------------------------------------ + + [Fact] + public void A_valid_model_loads_clean() + { + Clean(Load(Model())); + } + + [Fact] + public void A_role_and_an_app_both_named_api_the_lookup_is_kind_typed() + { + var r = Load(Model(" - app.service: { name: worker, runsAs: api, calls: [api, Parcels.api] }")); + Clean(r); + var worker = At(r.Root, "Parcels", "worker"); + // runsAs targets a role: the role `api`, not the app `api`. + Assert.Equal("role", NamingRefs.RefTarget(worker, "runsAs")?.Type); + Assert.Equal("acme::Parcels.api", worker.Attr("runsAs")); + // calls targets an app: both spellings bind the app `api`. + Assert.Equal(new[] { "acme::Parcels.api", "acme::Parcels.api" }, (IEnumerable)worker.Attr("calls")!); + Assert.All(worker.ResolvedTargetsOf("calls")!, t => Assert.Same(At(r.Root, "Parcels", "app:api"), t)); + } + + [Fact] + public void Unresolved_a_value_naming_no_node() + { + var r = Load(Model(" - app.service: { name: worker, calls: [nobody] }")); + Assert.Equal(["ERR_REF_UNRESOLVED"], Codes(r)); + Assert.Equal(ErrorCode.ERR_REF_UNRESOLVED, r.Errors[0].Code); + Assert.Contains("@calls \"nobody\"", r.Errors[0].Message); + } + + [Fact] + public void Wrong_kind_normative_case_a() + { + var r = Load(Model(" - app.service: { name: worker, runsAs: db }")); + Assert.Equal(["ERR_REF_WRONG_KIND"], Codes(r)); + Assert.Equal(ErrorCode.ERR_REF_WRONG_KIND, r.Errors[0].Code); + Assert.Contains("resource.rdb", r.Errors[0].Message); + } + + [Fact] + public void Unresolved_normative_case_b() + { + var r = Load(Model(" - app.service: { name: worker, runsAs: nobody }")); + Assert.Equal(["ERR_REF_UNRESOLVED"], Codes(r)); + } + + [Fact] + public void Wrong_kind_when_two_top_level_nodes_of_other_types_share_the_name() + { + const string outside = """ + - system.software: { name: Shared } + - deployment.test: { name: Shared } + """; + var r = Load(Model(" - app.service: { name: worker, runsAs: Shared }", outside)); + Assert.Equal(["ERR_REF_WRONG_KIND"], Codes(r)); + } + + [Fact] + public void Wrong_subtype_a_grant_rdb_naming_a_resource_queue() + { + var r = Load(Model(""" + - role.service: + name: mover + children: + - grant.rdb: { name: g2, resource: jobs } + """)); + Assert.Equal(["ERR_REF_WRONG_KIND"], Codes(r)); + Assert.Contains("resource.queue", r.Errors[0].Message); + Assert.Contains("system \"acme::Parcels\"", r.Errors[0].Message); + } + + [Fact] + public void Crosses_system_raises_the_facet_wrongSystemCode() + { + var r = Load(Model(""" + - role.service: + name: auditor + children: + - grant.rdb: { name: g3, resource: Ledger.books } + """)); + Assert.Equal(["ERR_GRANT_CROSSES_SYSTEM"], Codes(r)); + // A provider's own code is not a built-in member: Code is ERR_UNKNOWN, the spelling is kept. + Assert.Equal(ErrorCode.ERR_UNKNOWN, r.Errors[0].Code); + Assert.Equal("ERR_GRANT_CROSSES_SYSTEM", r.Errors[0].ProviderCode); + Assert.Contains("system \"acme::Ledger\"", r.Errors[0].Message); + } + + [Fact] + public void A_shared_model_refusal_keeps_the_provider_code() + { + string file = Path.Combine(Path.GetTempPath(), $"reference-facet-{Guid.NewGuid():N}.yaml"); + File.WriteAllText(file, Model(""" + - role.service: + name: auditor + children: + - grant.rdb: { name: g3, resource: Ledger.books } + """)); + try + { + var ex = Assert.Throws(() => MetaObjects.Config.SharedModel.Build( + new MetaObjects.Config.SharedModelInput("acme", [file], Providers: [new TestProvider()]))); + Assert.StartsWith("ERR_GRANT_CROSSES_SYSTEM: ", ex.Message); + } + finally + { + File.Delete(file); + } + } + + [Fact] + public void A_facet_errorCode_replaces_both_default_codes() + { + const string outside = """ + - deployment.test: { name: d1, anyRole: Parcels.nobody } + - deployment.test: { name: d2, anyRole: Parcels.db } + """; + Assert.Equal(["ERR_TEST_ROLE", "ERR_TEST_ROLE"], Codes(Load(Model("", outside)))); + } + + [Fact] + public void System_child_and_pkg_System_child_resolve_from_outside_any_system() + { + var r = Load(Model("", " - deployment.test: { name: d1, app: Parcels.api, anyRole: acme::Ledger.clerk }")); + Clean(r); + var d1 = At(r.Root, "d1"); + Assert.Equal("app", NamingRefs.RefTarget(d1, "app")?.Type); + Assert.Equal("acme::Parcels.api", d1.Attr("app")); + Assert.Equal("acme::Ledger.clerk", d1.Attr("anyRole")); + Assert.Same(At(r.Root, "Ledger", "clerk"), BoundTo(d1, "anyRole")); + } + + [Fact] + public void A_bare_value_from_outside_a_system_does_not_see_inside_one() + { + Assert.Equal(["ERR_REF_UNRESOLVED"], Codes(Load(Model("", " - deployment.test: { name: d1, app: web }")))); + } + + [Fact] + public void SameSystem_from_a_node_outside_any_system_fails_with_wrongSystemCode() + { + Assert.Equal(["ERR_TEST_OUTSIDE"], Codes(Load(Model("", " - deployment.test: { name: d1, pinnedRole: Parcels.api }")))); + } + + [Fact] + public void An_intermediate_segment_shared_by_two_children_is_ambiguous() + { + // `Parcels.api.g1`: `api` names both a role and an app under Parcels. + Assert.Equal(["ERR_REF_UNRESOLVED"], Codes(Load(Model("", " - deployment.test: { name: d1, app: Parcels.api.g1 }")))); + } + + [Fact] + public void An_over_dropping_parent_relative_value_is_a_bad_attr_value() + { + var r = Load(Model("", " - deployment.test: { name: d1, app: \"..::..::Parcels.api\" }")); + Assert.Equal(["ERR_BAD_ATTR_VALUE"], Codes(r)); + Assert.Contains("climbs above the root package", r.Errors[0].Message); + } + + // ------------------------------------------------------------------ + // Inheritance and canonical spelling + // ------------------------------------------------------------------ + + /// Load, serialize canonically, reload: the reloaded model loads clean and + /// on the node at names the node at + /// in both trees. Returns the value written. + private static object? RoundTrip(string yaml, string[] referrer, string attr, string[] target) + { + var first = Load(yaml); + Clean(first); + Assert.Same(At(first.Root, target), BoundTo(At(first.Root, referrer), attr)); + var second = Load(SerializerJson.CanonicalSerialize(first.Root), MetaDataFormat.Json); + Clean(second); + Assert.Same(At(second.Root, target), BoundTo(At(second.Root, referrer), attr)); + return At(second.Root, referrer).Attr(attr); + } + + [Fact] + public void An_inherited_reference_is_looked_up_where_it_was_written() + { + // Ledger has no role `api`: `web` inherits `runsAs: api` from Parcels' `base`. + var r = Load(""" + metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - role.service: { name: api } + - app.service: { name: base, runsAs: api } + - system.software: + name: Ledger + children: + - app.service: { name: web, extends: acme::Parcels.base } + """); + Clean(r); + Assert.Same(At(r.Root, "Parcels", "api"), NamingRefs.RefTarget(At(r.Root, "Ledger", "web"), "runsAs")); + } + + [Fact] + public void An_inherited_sameSystem_reference_is_judged_where_it_was_written() + { + // Ledger has its own role `api`, but `web`'s `runsAs: api` was written in Parcels. + var r = Load(""" + metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - role.service: { name: api } + - app.service: { name: base, runsAs: api } + - system.software: + name: Ledger + children: + - role.service: { name: api } + - app.service: { name: web, extends: acme::Parcels.base } + """); + Clean(r); + Assert.Same(At(r.Root, "Parcels", "role:api"), NamingRefs.RefTarget(At(r.Root, "Ledger", "web"), "runsAs")); + } + + private static string Inheriting(string extra) => $""" + metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - role.service: {"{"} name: clerk {"}"} + - system.software: + name: Ledger + extends: Parcels + children: + - app.service: {"{"} name: web, runsAs: clerk {"}"} + {extra} + """; + + [Fact] + public void An_inherited_child_keeps_the_path_it_was_addressed_by_and_is_in_that_system() + { + var written = RoundTrip( + Inheriting(" - deployment.test: { name: d1, anyRole: Ledger.clerk }"), + ["d1"], "anyRole", ["Parcels", "clerk"]); + Assert.Equal("acme::Ledger.clerk", written); + // `web` reaches the inherited `clerk` through its own system, so sameSystem holds. + var r = Load(Inheriting("")); + Clean(r); + Assert.Equal("acme::Ledger.clerk", At(r.Root, "Ledger", "web").Attr("runsAs")); + } + + [Fact] + public void A_path_through_a_shared_intermediate_name_keeps_the_value_as_written() + { + var written = RoundTrip(""" + metadata.root: + package: acme + children: + - system.software: + name: Parcels + children: + - app.service: { name: api } + - role.service: + name: api + children: + - resource.rdb: { name: local } + - grant.rdb: { name: g1, resource: local } + """, + ["Parcels", "role:api", "g1"], "resource", ["Parcels", "role:api", "local"]); + Assert.Equal("local", written); + } + + [Fact] + public void A_top_level_key_shared_by_two_types_keeps_the_value_as_written() + { + var written = RoundTrip(""" + metadata.root: + package: acme + children: + - deployment.test: { name: Shared } + - system.software: + name: Shared + children: + - role.service: { name: r } + - app.service: { name: a, runsAs: r } + """, + ["system:Shared", "a"], "runsAs", ["system:Shared", "r"]); + Assert.Equal("r", written); + } + + [Fact] + public void A_root_absolute_value_a_container_child_would_shadow_keeps_its_root_prefix() + { + var written = RoundTrip(""" + metadata.root: + children: + - app.service: { name: api } + - system.software: + name: S + children: + - app.service: { name: api } + - app.service: { name: worker, calls: ["::api"] } + """, + ["S", "worker"], "calls", ["app:api"]); + Assert.Equal(new[] { "::api" }, (IEnumerable)written!); + } + + [Fact] + public void A_fieldPath_value_names_a_top_level_target_never_a_container_child() + { + var r = Load(Model(" - app.service: { name: worker, reads: db.name }", " - resource.rdb: { name: db }")); + Clean(r); + var worker = At(r.Root, "Parcels", "worker"); + Assert.Same(At(r.Root, "db"), NamingRefs.RefTarget(worker, "reads")); + Assert.Equal("acme::db.name", worker.Attr("reads")); + } + + [Fact] + public void A_facet_attribute_named_like_a_core_reference_is_bound_by_its_facet() + { + var r = Load(Model("", " - deployment.test: { name: d1, via: Parcels.api }")); + Clean(r); + var d1 = At(r.Root, "d1"); + Assert.Equal("role", NamingRefs.RefTarget(d1, "via")?.Type); + Assert.Equal("acme::Parcels.api", d1.Attr("via")); + } + + // ------------------------------------------------------------------ + // The core object references keep their codes and hints + // ------------------------------------------------------------------ + + [Fact] + public void A_wrong_kind_object_reference_still_suggests_the_object_in_another_package() + { + // `@objectRef: Address` finds the field itself among its containers (wrong kind); the + // object `Address` exists only in package `common`. + var r = Load(""" + metadata.root: + children: + - object.value: { name: Address, package: common, children: [ { field.string: { name: street } } ] } + - object.value: + name: Order + package: shop + children: + - field.object: { name: Address, objectRef: Address } + """); + Assert.Equal(["ERR_UNRESOLVED_OBJECT_REF"], Codes(r)); + Assert.Contains("An object named \"Address\" exists in: common::Address.", r.Errors[0].Message); + } + + [Fact] + public void A_parent_relative_references_value_still_suggests_the_object_in_another_package() + { + // ADR-0059 §2: `..::Address.id` from `acme::shop` names `acme::Address`; only `common::Address` exists. + var r = Load(""" + metadata.root: + children: + - object.value: { name: Address, package: common, children: [ { field.string: { name: id } } ] } + - object.entity: + name: Order + package: acme::shop + children: + - field.long: { name: id } + - field.string: { name: addressId } + - identity.primary: { name: pk, fields: [id] } + - identity.reference: { name: address, fields: [addressId], references: "..::Address.id" } + """); + Assert.Equal(["ERR_INVALID_REFERENCE"], Codes(r)); + Assert.Contains("An object named \"Address\" exists in: common::Address.", r.Errors[0].Message); + } + + [Fact] + public void A_parent_relative_references_value_resolves_its_owner() + { + var r = Load(""" + metadata.root: + children: + - object.entity: + name: Address + package: acme + children: + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + - object.entity: + name: Order + package: acme::shop + children: + - field.long: { name: id } + - field.long: { name: addressId } + - identity.primary: { name: pk, fields: [id] } + - identity.reference: { name: address, fields: [addressId], references: "..::Address.id" } + """); + Clean(r); + var reference = At(r.Root, "Order", "address"); + Assert.Same(At(r.Root, "Address"), NamingRefs.RefTarget(reference, "references")); + Assert.Equal("acme::Address.id", reference.Attr("references")); + } + + // ------------------------------------------------------------------ + // The registry manifest + // ------------------------------------------------------------------ + + private static JsonElement ManifestAttr(JsonDocument manifest, string type, string subType, string name) => + manifest.RootElement.GetProperty("types").EnumerateArray() + .First(t => t.GetProperty("type").GetString() == type && t.GetProperty("subType").GetString() == subType) + .GetProperty("attrs").EnumerateArray() + .First(a => a.GetProperty("name").GetString() == name); + + [Fact] + public void The_manifest_writes_ref_only_on_an_attribute_that_has_one_in_the_fixed_key_order() + { + using var manifest = JsonDocument.Parse(RegistryManifest.Emit(Registry())); + var resource = ManifestAttr(manifest, "grant", "rdb", "resource"); + Assert.Equal( + ["name", "valueType", "isArray", "required", "ref", "description"], + resource.EnumerateObject().Select(p => p.Name).ToList()); + Assert.Equal( + """{"targetType":"resource","targetSubTypes":["rdb"],"sameSystem":true,"wrongSystemCode":"ERR_GRANT_CROSSES_SYSTEM"}""", + JsonSerializer.Serialize(resource.GetProperty("ref"))); + Assert.Equal( + """{"targetType":"role","errorCode":"ERR_TEST_ROLE"}""", + JsonSerializer.Serialize(ManifestAttr(manifest, "deployment", "test", "anyRole").GetProperty("ref"))); + Assert.Equal( + """{"targetType":"resource","fieldPath":true}""", + JsonSerializer.Serialize(ManifestAttr(manifest, "app", "service", "reads").GetProperty("ref"))); + } + + [Fact] + public void A_registry_with_no_facet_writes_no_ref_key() + { + Assert.DoesNotContain("\"ref\"", RegistryManifest.Emit(Provider.ComposeRegistry(CoreTypes.LibraryProviders))); + } +} diff --git a/server/csharp/MetaObjects/Config/SharedModel.cs b/server/csharp/MetaObjects/Config/SharedModel.cs index 56ec887c64..fe34f980ab 100644 --- a/server/csharp/MetaObjects/Config/SharedModel.cs +++ b/server/csharp/MetaObjects/Config/SharedModel.cs @@ -206,8 +206,9 @@ private static LoadResult Load(IReadOnlyList? providers, { var registry = Provider.ComposeRegistry(ProviderLoader.Compose(providers)); var result = new MetaDataLoader(registry, freeze: true, strict: true).Load(sources); - if (result.Errors.Count > 0) - throw new MetaModelException(result.Errors[0].Message, result.Errors[0].Code); + if (result.Errors is [var first, ..]) + throw new MetaModelException( + first.ProviderCode is null ? first.Message : $"{first.ProviderCode}: {first.Message}", first.Code); return result; } diff --git a/server/csharp/MetaObjects/CoreTypes.cs b/server/csharp/MetaObjects/CoreTypes.cs index eedcecca78..53a6506ce3 100644 --- a/server/csharp/MetaObjects/CoreTypes.cs +++ b/server/csharp/MetaObjects/CoreTypes.cs @@ -566,14 +566,16 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) if (rdef is not null) { rdef.References = [new MetaObjects.Validation.ReferenceDescriptor( - RELATIONSHIP_ATTR_OBJECT_REF, TYPE_OBJECT, null, false, "ERR_INVALID_RELATIONSHIP")]; + RELATIONSHIP_ATTR_OBJECT_REF, + new MetaObjects.Validation.ReferenceFacet(TYPE_OBJECT, ErrorCode: "ERR_INVALID_RELATIONSHIP"))]; } } var idRefDef = registry.Find(TYPE_IDENTITY, IDENTITY_SUBTYPE_REFERENCE); if (idRefDef is not null) { idRefDef.References = [new MetaObjects.Validation.ReferenceDescriptor( - IDENTITY_REFERENCE_ATTR_REFERENCES, TYPE_OBJECT, null, true, "ERR_INVALID_REFERENCE")]; + IDENTITY_REFERENCE_ATTR_REFERENCES, + new MetaObjects.Validation.ReferenceFacet(TYPE_OBJECT, FieldPath: true, ErrorCode: "ERR_INVALID_REFERENCE"))]; } // ADR-0042 — a field.object / field.map @objectRef must resolve (a dangling target @@ -587,7 +589,8 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) if (fdef is not null) { fdef.References = [new MetaObjects.Validation.ReferenceDescriptor( - FIELD_ATTR_OBJECT_REF, TYPE_OBJECT, null, false, "ERR_UNRESOLVED_OBJECT_REF")]; + FIELD_ATTR_OBJECT_REF, + new MetaObjects.Validation.ReferenceFacet(TYPE_OBJECT, ErrorCode: "ERR_UNRESOLVED_OBJECT_REF"))]; } } diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs index 2d340e59e8..98386e9f55 100644 --- a/server/csharp/MetaObjects/Errors.cs +++ b/server/csharp/MetaObjects/Errors.cs @@ -344,6 +344,10 @@ public enum ErrorCode ERR_CONSTRAINT_NAME_WITHOUT_CHECK, // A cross-field validator (enforced only by its CHECK) sets @dbCheck: false. ERR_CROSS_FIELD_WITHOUT_CHECK, + // The reference facet's two default codes (spec/metamodel-definitions.md): a value that + // names no node, and a value that names a node of the wrong type or subtype. + ERR_REF_UNRESOLVED, + ERR_REF_WRONG_KIND, } /// @@ -419,7 +423,18 @@ public sealed record MetaError( ErrorCode Code = ErrorCode.ERR_UNKNOWN, string? Source = null, string? Path = null, - ErrorSource? Envelope = null); + ErrorSource? Envelope = null) +{ + /// + /// A loader code a provider named that is not an member (a reference + /// facet's errorCode or wrongSystemCode, such as ERR_GRANT_CROSSES_SYSTEM). + /// is then . Null for a built-in code. + /// + public string? ProviderCode { get; init; } + + /// The code as the provider spelled it: when set, else . + public string CodeName => ProviderCode ?? Code.ToString(); +} /// Thrown for top-level structural parse failures the TS parser also throws on /// (malformed JSON, non-object root, unknown root type). The loader catches it and diff --git a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs index 7ffdc10198..528d813eb8 100644 --- a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs +++ b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs @@ -677,7 +677,7 @@ public LoadResult Load(IReadOnlyList sources) // ADR-0059 R5 — after the last validation pass, before freeze: resolve every // reference once, record its target and rewrite it to its canonical spelling. - ResolveReferences.Run(root); + ResolveReferences.Run(root, _registry); } // If nothing parsed successfully, synthesize an empty root so callers diff --git a/server/csharp/MetaObjects/Loader/ResolveReferences.cs b/server/csharp/MetaObjects/Loader/ResolveReferences.cs index 5c35778e88..0d726b8e45 100644 --- a/server/csharp/MetaObjects/Loader/ResolveReferences.cs +++ b/server/csharp/MetaObjects/Loader/ResolveReferences.cs @@ -10,6 +10,7 @@ // Mirrors typescript/packages/metadata/src/loader/resolve-references.ts. using MetaObjects.Meta; +using MetaObjects.Validation; namespace MetaObjects.Loader; @@ -20,9 +21,25 @@ internal static class ResolveReferences /// record the targets, and rewrite resolved values to their canonical spelling. Must run after /// the last validation pass and before Freeze(). /// - public static void Run(MetaData root) => Visit(root, root); + /// With , an attribute whose schema carries the reference + /// facet is resolved too, by the facet's typed lookup. + public static void Run(MetaData root, TypeRegistry? registry = null) + { + var state = new FacetState(root, registry); + Visit(root, root, state); + } + + /// The registry the facets come from and the symbol table, built on first use. + private sealed class FacetState(MetaData root, TypeRegistry? registry) + { + private SymbolTable? _symbols; + public SymbolTable Symbols => _symbols ??= SymbolTable.Build(root); - private static void Visit(MetaData root, MetaData node) + public ReferenceFacet? FacetOf(MetaData node, string name) => + registry?.FindAttrSchema(node.Type, node.SubType, name)?.Ref; + } + + private static void Visit(MetaData root, MetaData node, FacetState state) { if (!ReferenceEquals(node, root)) { @@ -34,15 +51,43 @@ private static void Visit(MetaData root, MetaData node) // is resolved once, on the node that declares it. foreach (string name in node.OwnAttrs().Keys.ToList()) { - if (NamingRefs.IsRefBearingAttr(node, name)) ResolveAttr(root, node, name, declPkg); + var facet = state.FacetOf(node, name); + if (facet is not null) + { + BindAttr(node, name, FacetResolver(state.Symbols, node, facet, declPkg)); + } + else if (NamingRefs.IsRefBearingAttr(node, name)) + { + ResolveAttr(root, node, name, declPkg); + } } } // ADR-0039: own — structural walk over the physical declaration tree. - foreach (var child in node.OwnChildren()) Visit(root, child); + foreach (var child in node.OwnChildren()) Visit(root, child, state); } private sealed record Resolved(MetaData Target, string Canonical); + /// + /// A facet reference (spec/metamodel-definitions.md, rule 7): the target the typed lookup + /// finds, spelled as the top-level owner it was reached through plus the child names walked. + /// A fieldPath value keeps its field segment. A spelling that would not look up the same + /// target again keeps the value as written. + /// + private static Func FacetResolver(SymbolTable symbols, MetaData node, ReferenceFacet facet, string declPkg) => + value => + { + var path = symbols.Lookup(node, value, facet, declPkg).Path; + if (path is not { Count: > 0 }) return null; + var target = path[^1]; + string tail = facet.FieldPath + ? NamingRefs.SplitChildTail(value).Tail + : string.Concat(path.Skip(1).Select(n => CHILD_REF_SEPARATOR + n.Name)); + string canonical = NamingRefs.SpellRef(path[0], declPkg, tail); + var again = symbols.Lookup(node, canonical, facet, declPkg).Target; + return new Resolved(target, ReferenceEquals(again, target) ? canonical : value); + }; + /// Resolve one reference string's owner in and spell it canonically. private static Resolved? ResolveOne(MetaData root, string value, string refPkg, string declPkg) { @@ -80,12 +125,19 @@ private static string ReferrerPackage(MetaData root, MetaData node, string attr, private static void ResolveAttr(MetaData root, MetaData node, string attr, string declPkg) { - object? value = node.OwnAttr(attr); string refPkg = ReferrerPackage(root, node, attr, declPkg); + BindAttr(node, attr, v => ResolveOne(root, v, refPkg, declPkg)); + } + + /// Record each resolved value's target on and rewrite it to its + /// canonical spelling. + private static void BindAttr(MetaData node, string attr, Func resolveValue) + { + object? value = node.OwnAttr(attr); if (value is string s) { if (s.Length == 0) return; - var r = ResolveOne(root, s, refPkg, declPkg); + var r = resolveValue(s); if (r is null) return; node.SetResolvedTarget(attr, r.Target); if (r.Canonical != s) node.SetCanonicalAttr(attr, r.Canonical); @@ -93,7 +145,7 @@ private static void ResolveAttr(MetaData root, MetaData node, string attr, strin } if (value is IReadOnlyList items) { - var resolved = items.Select(v => v.Length == 0 ? null : ResolveOne(root, v, refPkg, declPkg)).ToList(); + var resolved = items.Select(v => v.Length == 0 ? null : resolveValue(v)).ToList(); if (resolved.All(r => r is null)) return; node.SetResolvedTarget(attr, resolved.Select(r => r?.Target).ToList()); var canonical = items.Select((v, i) => resolved[i]?.Canonical ?? v).ToList(); diff --git a/server/csharp/MetaObjects/NamingRefs.cs b/server/csharp/MetaObjects/NamingRefs.cs index e47ace4e2d..a4cb5c526c 100644 --- a/server/csharp/MetaObjects/NamingRefs.cs +++ b/server/csharp/MetaObjects/NamingRefs.cs @@ -243,14 +243,20 @@ public static MetaData TopLevelNodeOf(MetaData node) /// of the top-level node that PHYSICALLY declares the attribute (walks the super chain to the /// layer that owns it), so an inherited reference means what it meant where it was written. /// - public static string ReferrerPackageFor(MetaData node, string attrName) + public static string ReferrerPackageFor(MetaData node, string attrName) => + EffectivePackageOf(TopLevelNodeOf(DeclaringNodeFor(node, attrName))); + + /// The node that physically declares for + /// : itself, or the ancestor along its + /// extends chain that wrote it ( when none does). + internal static MetaData DeclaringNodeFor(MetaData node, string attrName) { MetaData? declarer = node; var seen = new HashSet(ReferenceEqualityComparer.Instance); // ADR-0039: own — locating the layer that physically declares the attr. while (declarer is not null && !declarer.OwnHasAttr(attrName) && seen.Add(declarer)) declarer = declarer.SuperData; - return EffectivePackageOf(TopLevelNodeOf(declarer ?? node)); + return declarer ?? node; } /// @@ -318,9 +324,9 @@ public static string DidYouMeanSuperHint(MetaData root, string reference) private static (string ShortName, List Candidates)? SameNamedObjects(MetaData root, string reference) { - // Owner = everything before a dotted child tail (FR-024 `Owner.child`). - int dot = reference.IndexOf(CHILD_REF_SEPARATOR, StringComparison.Ordinal); - string owner = dot == -1 ? reference : reference[..dot]; + // Owner = everything before a dotted child tail (FR-024 `Owner.child`); the tail starts + // after the last `::`, so a parent-relative `..::Address.id` keeps `..::Address`. + string owner = SplitChildTail(reference).Owner; int sep = owner.LastIndexOf(PACKAGE_SEPARATOR, StringComparison.Ordinal); string shortName = sep == -1 ? owner : owner[(sep + PACKAGE_SEPARATOR.Length)..]; var candidates = root.Children() diff --git a/server/csharp/MetaObjects/Registry.cs b/server/csharp/MetaObjects/Registry.cs index 56dcd3e306..fe226d265f 100644 --- a/server/csharp/MetaObjects/Registry.cs +++ b/server/csharp/MetaObjects/Registry.cs @@ -74,7 +74,8 @@ public sealed record AttrSchema( string? Example = null, string? WhenToUse = null, IReadOnlyList? Ports = null, - IReadOnlyList? ImplementedIn = null); + IReadOnlyList? ImplementedIn = null, + MetaObjects.Validation.ReferenceFacet? Ref = null); // --------------------------------------------------------------------------- // TypeDefinition @@ -754,7 +755,8 @@ private static AttrSchema ToAttrSchema(MetaObjects.Registry.Spec.SpecExtendsAttr Required: a.Required, Default: a.Default, AllowedValues: a.AllowedValues, - IsArray: a.IsArray); + IsArray: a.IsArray, + Ref: a.Ref); // ------------------------------------------------------------------ // FR-033 (sub-step B1) — apply spec/metamodel descriptions (pre-seal) @@ -813,6 +815,8 @@ internal void ApplySpecDescriptions(MetaObjects.Registry.Spec.SpecMetamodelReade // and the ports that implement a cross-port attr so far (kind 1). Ports = a.Ports, ImplementedIn = a.ImplementedIn, + // The reference facet comes from the definition when it states one. + Ref = a.Ref ?? attr.Ref, }; }).ToList(); @@ -847,6 +851,7 @@ internal void ApplySpecDescriptions(MetaObjects.Registry.Spec.SpecMetamodelReade Rules = a.Rules, Example = a.Example, WhenToUse = a.WhenToUse, + Ref = a.Ref ?? attr.Ref, }; } } diff --git a/server/csharp/MetaObjects/Registry/Spec/SpecMetamodelReader.cs b/server/csharp/MetaObjects/Registry/Spec/SpecMetamodelReader.cs index 67e3a1d0d8..a252220b9b 100644 --- a/server/csharp/MetaObjects/Registry/Spec/SpecMetamodelReader.cs +++ b/server/csharp/MetaObjects/Registry/Spec/SpecMetamodelReader.cs @@ -24,9 +24,16 @@ // per-subtype scoping — that is sub-step B2. The model it parses (incl. structural // children + cardinality) is the durable foundation B2 extends; B1 uses only the // description-resolution surface. +// +// An attr entry may carry the reference facet (`ref`, spec/metamodel-definitions.md). The +// reader validates it against the format's rules (refusing a bad facet, or one on a structural +// child, with an InvalidOperationException) and carries it on SpecAttrEntry / SpecExtendsAttr, +// from where the registry lowers it onto AttrSchema.Ref for the loader to enforce. using System.Reflection; using System.Text.Json; +using System.Text.RegularExpressions; +using MetaObjects.Validation; namespace MetaObjects.Registry.Spec; @@ -60,7 +67,8 @@ public sealed record SpecAttrEntry( IReadOnlyList? AllowedValues, object? Default, IReadOnlyList? Ports = null, - IReadOnlyList? ImplementedIn = null) + IReadOnlyList? ImplementedIn = null, + ReferenceFacet? Ref = null) { /// Whether this attr is required — the JSON encodes requiredness as min: 1. public bool Required => Min == 1; @@ -96,7 +104,8 @@ public sealed record SpecExtendsAttr( bool IsArray, bool Required, IReadOnlyList? AllowedValues, - object? Default); + object? Default, + ReferenceFacet? Ref = null); /// /// FR-033 (provider re-home) — one extends directive from a named concern @@ -209,6 +218,32 @@ public static SpecMetamodelReader Load() return reader; } + /// + /// Parse provider definition documents given as JSON text, in the format of + /// spec/metamodel/*.json (spec/metamodel-definitions.md). For a provider whose + /// definition is not one of the embedded core files, such as a test vocabulary; its + /// extends directives apply through . + /// + /// If a document is unparseable or carries an + /// invalid reference facet. + internal static SpecMetamodelReader FromJson(params string[] definitions) + { + var reader = new SpecMetamodelReader(); + foreach (string json in definitions) + { + try + { + using JsonDocument doc = JsonDocument.Parse(json); + reader.Parse(doc.RootElement); + } + catch (JsonException e) + { + throw new InvalidOperationException($"failed parsing a provider definition: {e.Message}", e); + } + } + return reader; + } + private void Parse(JsonElement provider) { // FR-033 — the spec file's "provider" name keys its extends directives so a @@ -223,7 +258,7 @@ private void Parse(JsonElement provider) if (type == Wildcard && subType == Wildcard) { // The universal *.* entry: its attr children are the common attrs. - foreach (SpecAttrEntry a in ParseAttrChildren(t)) + foreach (SpecAttrEntry a in ParseAttrChildren(t, providerName, Key(type, subType))) { _commonAttrDocs[a.Name] = a; } @@ -239,12 +274,12 @@ private void Parse(JsonElement provider) Str(t, "description"), Str(t, "rules"), Str(t, "example"), Str(t, "whenToUse"), StrList(t, "implementedIn"), StrList(t, "ports")); var attrs = new Dictionary(StringComparer.Ordinal); - foreach (SpecAttrEntry a in ParseAttrChildren(t)) + foreach (SpecAttrEntry a in ParseAttrChildren(t, providerName, key)) { attrs[a.Name] = a; } _typeAttrDocs[key] = attrs; - _typeStructChildren[key] = ParseStructChildren(t); + _typeStructChildren[key] = ParseStructChildren(t, providerName, key); _typeExtendsBase[key] = Bool(t, "extendsBase"); } } @@ -284,7 +319,7 @@ private void Parse(JsonElement provider) } var attrs = new Dictionary(StringComparer.Ordinal); var directiveAttrs = new List(); - foreach (SpecAttrEntry a in ParseAttrChildren(e)) + foreach (SpecAttrEntry a in ParseAttrChildren(e, providerName, type)) { attrs[a.Name] = a; // The JSON `subType` of an attr child is its value-type (string / @@ -295,11 +330,12 @@ private void Parse(JsonElement provider) IsArray: a.IsArray, Required: a.Required, AllowedValues: a.AllowedValues, - Default: a.Default)); + Default: a.Default, + Ref: a.Ref)); } // A pack that owns a type also lets an existing type hold it: a structural // child under `extends` is a child rule added to the target. - List structChildren = ParseStructChildren(e); + List structChildren = ParseStructChildren(e, providerName, type); _extendsBlocks.Add(new ExtendsBlock(type, subTypes, wildcard, attrs)); if (providerName is not null) { @@ -329,7 +365,7 @@ public IReadOnlyList ExtendsDirectives(string providerName ? list : Array.Empty(); - private static List ParseAttrChildren(JsonElement owner) + private static List ParseAttrChildren(JsonElement owner, string? provider, string typeKey) { var outList = new List(); if (!owner.TryGetProperty("children", out JsonElement children) || children.ValueKind != JsonValueKind.Array) @@ -374,12 +410,15 @@ private static List ParseAttrChildren(JsonElement owner) AllowedValues: allowed, Default: def, Ports: StrList(c, "ports"), - ImplementedIn: StrList(c, "implementedIn"))); + ImplementedIn: StrList(c, "implementedIn"), + Ref: c.TryGetProperty(RefKey, out JsonElement refEl) + ? ToReferenceFacet(refEl, Str(c, "subType"), Where(provider, "attr", Str(c, "name"), typeKey)) + : null)); } return outList; } - private static List ParseStructChildren(JsonElement owner) + private static List ParseStructChildren(JsonElement owner, string? provider, string typeKey) { var outList = new List(); if (!owner.TryGetProperty("children", out JsonElement children) || children.ValueKind != JsonValueKind.Array) @@ -393,6 +432,12 @@ private static List ParseStructChildren(JsonElement owner) { continue; // attr children are the attrs block (B1) — not structural } + if (c.TryGetProperty(RefKey, out _)) + { + throw new InvalidOperationException( + $"{Where(provider, "child", Str(c, "name"), typeKey)} has an invalid reference facet: " + + "only an attr may be a reference."); + } (int? min, int? max, bool maxIsNull) = Cardinality(c); bool? named = null; if (c.TryGetProperty("named", out JsonElement n) && n.ValueKind != JsonValueKind.Null) @@ -411,6 +456,89 @@ private static List ParseStructChildren(JsonElement owner) return outList; } + /// The child-entry key that carries the reference facet. + private const string RefKey = "ref"; + + /// The only attr value type a reference may have. + private const string StringValueType = "string"; + + /// A loader error code, as a facet names one. + private static readonly Regex LoaderCode = new("^ERR_[A-Z0-9_]+$", RegexOptions.CultureInvariant); + + /// The facet's keys, in the format's order. + private static readonly string[] FacetKeys = + ["targetType", "targetSubTypes", "fieldPath", "sameSystem", "errorCode", "wrongSystemCode"]; + + private static string Where(string? provider, string kind, string? name, string typeKey) => + $"provider definition ({provider ?? "?"}): {kind} \"{name}\" on \"{typeKey}\""; + + /// + /// Read an attr entry's reference facet, refusing a facet the format does not allow + /// (spec/metamodel-definitions.md, "The reference facet"; the JSON schema states the + /// same rules). Mirrors the TS toReferenceFacet. + /// + private static ReferenceFacet ToReferenceFacet(JsonElement r, string? valueType, string where) + { + void Fail(string why) => throw new InvalidOperationException($"{where} has an invalid reference facet: {why}."); + if (r.ValueKind != JsonValueKind.Object) Fail("ref must be an object"); + foreach (JsonProperty p in r.EnumerateObject()) + { + if (!FacetKeys.Contains(p.Name)) Fail($"unknown key \"{p.Name}\""); + } + if (valueType != StringValueType) Fail($"only a string attr may be a reference (this one is \"{valueType}\")"); + + string? targetType = r.TryGetProperty("targetType", out JsonElement tt) && tt.ValueKind == JsonValueKind.String + ? tt.GetString() : null; + if (string.IsNullOrEmpty(targetType) || targetType == Wildcard) Fail("targetType must name one type, never \"*\""); + + List? targetSubTypes = null; + if (r.TryGetProperty("targetSubTypes", out JsonElement ts)) + { + if (ts.ValueKind != JsonValueKind.Array) Fail(SubTypesRule); + targetSubTypes = []; + foreach (JsonElement s in ts.EnumerateArray()) + { + string? sub = s.ValueKind == JsonValueKind.String ? s.GetString() : null; + if (string.IsNullOrEmpty(sub) || sub == Wildcard || targetSubTypes.Contains(sub)) Fail(SubTypesRule); + targetSubTypes.Add(sub!); + } + if (targetSubTypes.Count == 0) Fail(SubTypesRule); + } + + bool? OptBool(string key) + { + if (!r.TryGetProperty(key, out JsonElement b)) return null; + if (b.ValueKind is not (JsonValueKind.True or JsonValueKind.False)) Fail($"{key} must be a boolean"); + return b.GetBoolean(); + } + bool? fieldPath = OptBool("fieldPath"); + bool? sameSystem = OptBool("sameSystem"); + if (fieldPath == true && sameSystem == true) Fail("fieldPath and sameSystem cannot both be true"); + + string? OptCode(string key) + { + if (!r.TryGetProperty(key, out JsonElement c)) return null; + string? code = c.ValueKind == JsonValueKind.String ? c.GetString() : null; + if (code is null || !LoaderCode.IsMatch(code)) Fail($"{key} must be a loader code (ERR_ and upper case)"); + return code; + } + string? errorCode = OptCode("errorCode"); + string? wrongSystemCode = OptCode("wrongSystemCode"); + if ((sameSystem == true) != (wrongSystemCode is not null)) + { + Fail("wrongSystemCode is present exactly when sameSystem is true"); + } + return new ReferenceFacet( + targetType!, + targetSubTypes, + fieldPath ?? false, + sameSystem ?? false, + errorCode, + wrongSystemCode); + } + + private const string SubTypesRule = "targetSubTypes must be a non-empty list of distinct subtype names, never \"*\""; + private static (int? Min, int? Max, bool MaxIsNull) Cardinality(JsonElement c) { int? min = null; diff --git a/server/csharp/MetaObjects/RegistryManifest.cs b/server/csharp/MetaObjects/RegistryManifest.cs index 02b6eae8c1..fa4d64c5d0 100644 --- a/server/csharp/MetaObjects/RegistryManifest.cs +++ b/server/csharp/MetaObjects/RegistryManifest.cs @@ -158,6 +158,7 @@ private sealed record ManifestAttr( IReadOnlyList? AllowedValues, IReadOnlyList? ImplementedIn, IReadOnlyList? Ports, + MetaObjects.Validation.ReferenceFacet? Ref, string Description, string? Rules, string? Example, @@ -288,7 +289,7 @@ private static ManifestAttr ToManifestAttr(AttrSchema a) IReadOnlyList? implementedIn = a.ImplementedIn is { Count: > 0 } k ? k.OrderBy(x => x, StringComparer.Ordinal).ToList() : null; - return new ManifestAttr(a.Name, valueType, isArray, a.Required, allowedValues, implementedIn, ports, a.Description, a.Rules, a.Example, a.WhenToUse); + return new ManifestAttr(a.Name, valueType, isArray, a.Required, allowedValues, implementedIn, ports, a.Ref, a.Description, a.Rules, a.Example, a.WhenToUse); } // ------------------------------------------------------------------ @@ -532,6 +533,8 @@ private static void WriteAttr(Utf8JsonWriter writer, ManifestAttr a) // act on a language-specific attr); each sorted, only when named. WriteStringArrayIfAny(writer, "implementedIn", a.ImplementedIn); WriteStringArrayIfAny(writer, "ports", a.Ports); + // The reference facet (spec/metamodel-definitions.md), ONLY when the attr has one. + if (a.Ref is not null) WriteRef(writer, a.Ref); // FR-033 — description (required) then the optional docs facets, each // emitted ONLY when present. writer.WriteString("description", a.Description); @@ -541,6 +544,29 @@ private static void WriteAttr(Utf8JsonWriter writer, ManifestAttr a) writer.WriteEndObject(); } + /// + /// Write an attr's reference facet. Key order is fixed: targetType, then + /// targetSubTypes (sorted), fieldPath and sameSystem (each only when + /// true), errorCode, wrongSystemCode (each only when present). An absent key is + /// the facet's default, so two ports that read the same facet write the same bytes. + /// + private static void WriteRef(Utf8JsonWriter writer, MetaObjects.Validation.ReferenceFacet r) + { + writer.WriteStartObject("ref"); + writer.WriteString("targetType", r.TargetType); + if (r.TargetSubTypes is not null) + { + writer.WriteStartArray("targetSubTypes"); + foreach (string s in r.TargetSubTypes.OrderBy(x => x, StringComparer.Ordinal)) writer.WriteStringValue(s); + writer.WriteEndArray(); + } + if (r.FieldPath) writer.WriteBoolean("fieldPath", true); + if (r.SameSystem) writer.WriteBoolean("sameSystem", true); + if (r.ErrorCode is not null) writer.WriteString("errorCode", r.ErrorCode); + if (r.WrongSystemCode is not null) writer.WriteString("wrongSystemCode", r.WrongSystemCode); + writer.WriteEndObject(); + } + /// /// Write one structural child rule (FR-033 constraint graph). Key order: /// childType, childSubType, childName, then optional diff --git a/server/csharp/MetaObjects/Shared/BaseTypes.cs b/server/csharp/MetaObjects/Shared/BaseTypes.cs index 92bdb62418..3633480845 100644 --- a/server/csharp/MetaObjects/Shared/BaseTypes.cs +++ b/server/csharp/MetaObjects/Shared/BaseTypes.cs @@ -55,6 +55,12 @@ public static class BaseTypes public const string TYPE_BINDING = "binding"; /// ADR-0066 — an allowed move between two members of a field.enum (transition.action). public const string TYPE_TRANSITION = "transition"; + /// + /// ADR-0070 — the system type. Not a registered base type yet (core registers it in + /// 1.4.0, so it is not in ): the reference facet's sameSystem + /// check reads it to find a node's system, its nearest ancestor of this type. + /// + public const string TYPE_SYSTEM = "system"; public static readonly string[] BASE_TYPES = [ diff --git a/server/csharp/MetaObjects/Validation/RegisteredValidation.cs b/server/csharp/MetaObjects/Validation/RegisteredValidation.cs index 8eb41ddca6..91ce36a92e 100644 --- a/server/csharp/MetaObjects/Validation/RegisteredValidation.cs +++ b/server/csharp/MetaObjects/Validation/RegisteredValidation.cs @@ -24,86 +24,127 @@ public static class RegisteredValidation public static IReadOnlyList Run(MetaData root, TypeRegistry registry) { var ctx = new ValidationContext(SymbolTable.Build(root)); - Walk(root, registry, ctx); + var descriptorCache = new Dictionary>(ReferenceEqualityComparer.Instance); + Walk(root, root, registry, ctx, descriptorCache); return ctx.Errors; } - private static void Walk(MetaData node, TypeRegistry registry, ValidationContext ctx) + private static void Walk( + MetaData root, + MetaData node, + TypeRegistry registry, + ValidationContext ctx, + Dictionary> descriptorCache) { var def = registry.Find(node.Type, node.SubType); if (def is not null) { - foreach (var desc in def.References) + if (!descriptorCache.TryGetValue(def, out var descriptors)) { - // ADR-0039: resolving — a reference attr (e.g. @objectRef/@through) may be - // inherited via extends; read the effective value (TS validation-registry.ts:66). - if (node.Attr(desc.Attr) is not string raw || raw.Length == 0) continue; - int dot = raw.IndexOf('.'); - var entityRef = (desc.DottedFieldPath && dot >= 0) ? raw[..dot] : raw; - // ADR-0059 R3: an inherited reference resolves in the package of the top-level - // node that physically declares it, not the inheritor's. - string pkg = NamingRefs.ReferrerPackageFor(node, desc.Attr); - try { NamingRefs.OwnerCandidateKeys(entityRef, pkg); } - catch (RefOverDropException) - { - ctx.Error("ERR_BAD_ATTR_VALUE", node, - $"{node.Type}.{node.SubType} \"{node.Name}\" @{desc.Attr} \"{raw}\" climbs above the root package — each '..::' drops one segment of the declaring package."); - continue; - } - var target = ctx.Symbols.ResolveObject(entityRef, pkg); - // Qualify the node name with its owning entity (e.g. "Order.items") so the - // error is locatable from the message alone, not just the source envelope. - var qname = string.IsNullOrEmpty(node.Parent?.Name) ? node.Name : $"{node.Parent!.Name}.{node.Name}"; - if (target is null) - { - // ADR-0042 §5: a did-you-mean hint listing same-short-name objects in other packages. - ctx.Error(desc.ErrorCode, node, - $"{node.Type}.{node.SubType} \"{qname}\" @{desc.Attr} \"{raw}\" does not resolve to an object." + - NamingRefs.DidYouMeanHint(node.Root(), entityRef)); - } - else if (target.Type != desc.TargetType || - (desc.TargetSubType is not null && target.SubType != desc.TargetSubType)) - { - var want = desc.TargetSubType is not null ? $"{desc.TargetType}.{desc.TargetSubType}" : desc.TargetType; - ctx.Error(desc.ErrorCode, node, - $"{node.Type}.{node.SubType} \"{qname}\" @{desc.Attr} \"{raw}\" resolves to " + - $"{target.Type}.{target.SubType}, not a {want}."); - } + descriptors = [.. def.References, .. ReferenceAttrDescriptors(def, registry)]; + descriptorCache[def] = descriptors; } + foreach (var desc in descriptors) CheckReference(root, node, desc, ctx); def.Validate?.Invoke(node, ctx); } - foreach (var child in node.OwnChildren()) Walk(child, registry, ctx); + foreach (var child in node.OwnChildren()) Walk(root, child, registry, ctx, descriptorCache); } - private sealed class SymbolTable : ISymbolTable + /// Reference descriptors for every attribute of (and every common + /// attribute) whose schema carries the reference facet (spec/metamodel-definitions.md). + private static List ReferenceAttrDescriptors(TypeDefinition def, TypeRegistry registry) { - // ADR-0042: key every top-level object by its canonical resolution key ONLY (the FQN, - // or the bare name for a root-level/empty-package object) — NO bare-name fallback, so a - // bare ref never binds a same-named object in another package. Mirrors TS SymbolTableImpl. - private readonly Dictionary _byKey = new(StringComparer.Ordinal); + var outList = new List(); + var seen = new HashSet(StringComparer.Ordinal); + foreach (var attr in def.Attributes.Concat(registry.GetCommonAttrs())) + { + if (!seen.Add(attr.Name) || attr.Ref is null) continue; + outList.Add(new ReferenceDescriptor(attr.Name, attr.Ref)); + } + return outList; + } - public static SymbolTable Build(MetaData root) + /// Enforce one reference attribute on , every value of it when it + /// is a list (spec/metamodel-definitions.md, "What the loader checks, in order"). + private static void CheckReference(MetaData root, MetaData node, ReferenceDescriptor desc, ValidationContext ctx) + { + var facet = desc.Facet; + // ADR-0039: resolving — a reference attr (e.g. @objectRef/@through) may be inherited via + // extends; read the effective value (TS validation-registry.ts). + IReadOnlyList values = node.Attr(desc.Attr) switch { - var t = new SymbolTable(); - foreach (var c in root.OwnChildren()) + string one => [one], + IEnumerable many => many.ToList(), + _ => [], + }; + if (values.Count == 0) return; + // ADR-0059 R3 and rule 5: an inherited reference is looked up from the node that + // physically declares it, in that node's package, not from the inheritor. + var declarer = NamingRefs.DeclaringNodeFor(node, desc.Attr); + string pkg = NamingRefs.EffectivePackageOf(NamingRefs.TopLevelNodeOf(declarer)); + // Qualify the node name with its owning entity (e.g. "Order.items") so the error is + // locatable from the message alone, not just the source envelope. + var qname = string.IsNullOrEmpty(node.Parent?.Name) ? node.Name : $"{node.Parent!.Name}.{node.Name}"; + string Label(string value) => $"{node.Type}.{node.SubType} \"{qname}\" @{desc.Attr} \"{value}\""; + string wantKind = facet.TargetSubTypes is null + ? (facet.TargetType == TYPE_OBJECT ? "an object" : $"a {facet.TargetType}") + : string.Join(" or ", facet.TargetSubTypes.Select(s => $"{facet.TargetType}.{s}")); + foreach (string value in values) + { + if (value.Length == 0) continue; // absence is the required-attr pass's job + var found = ctx.Symbols.Lookup(declarer, value, facet, pkg); + if (found.OverDrop) + { + ctx.Error("ERR_BAD_ATTR_VALUE", node, + $"{Label(value)} climbs above the root package — each '..::' drops one segment of the declaring package."); + continue; + } + if (found.Path is not { Count: > 0 } path) { - if (c.Type == TYPE_OBJECT) t._byKey[c.ResolutionKey()] = c; + // ADR-0042 §5: `did-you-mean` is object-scoped (its candidate scan is over + // objects), so only append it for object targets. + string hint = facet.TargetType == TYPE_OBJECT ? NamingRefs.DidYouMeanHint(root, value) : ""; + if (found.WrongKind is { } w) + { + ctx.Error(facet.ErrorCode ?? ReferenceFacet.WrongKindCode, node, + $"{Label(value)} names {w.Type}.{w.SubType} \"{w.Name}\", not {wantKind}.{hint}"); + continue; + } + ctx.Error(facet.ErrorCode ?? ReferenceFacet.UnresolvedCode, node, + $"{Label(value)} does not resolve to {wantKind}.{hint}"); + continue; + } + var target = path[^1]; + // The system the path went through: an inherited child is in the system it was reached through. + var theirs = path.LastOrDefault(n => n.Type == TYPE_SYSTEM); + string where = theirs is null ? "no system" : $"system \"{theirs.ResolutionKey()}\""; + string resolved = $"{Label(value)} resolves to {target.Type}.{target.SubType} \"{target.Name}\" in {where}"; + if (facet.TargetSubTypes is not null && !facet.TargetSubTypes.Contains(target.SubType)) + { + // The typed lookup already guarantees target.Type == TargetType; only the subType + // can still mismatch. + ctx.Error(facet.ErrorCode ?? ReferenceFacet.WrongKindCode, node, $"{resolved}, not {wantKind}."); + continue; + } + if (facet.SameSystem) + { + var mine = SystemOf(declarer); + if (mine is null || !ReferenceEquals(mine, theirs)) + { + string from = mine is null ? "a node outside any system" : $"system \"{mine.ResolutionKey()}\""; + ctx.Error(facet.WrongSystemCode ?? ReferenceFacet.WrongKindCode, node, + $"{resolved}, but it must be in the same system as the node that declares it, which is in {from}."); + } } - return t; } + } - /// ADR-0059 R2 resolution: ::Rest root-absolute, ..::Rest parent-relative, - /// pkg::Name exact, bare Name in the referrer's own package then root-level. Exact keys - /// only. An over-dropping ..:: resolves to nothing here; the walk reports it. - public MetaData? ResolveObject(string reference, string referrerPkg) - { - IReadOnlyList keys; - try { keys = NamingRefs.OwnerCandidateKeys(reference, referrerPkg); } - catch (RefOverDropException) { return null; } - foreach (string key in keys) - if (_byKey.TryGetValue(key, out var hit)) return hit; - return null; - } + /// The system of a node: its nearest ancestor, or itself, of type system. + private static MetaData? SystemOf(MetaData node) + { + for (MetaData? n = node; n is not null; n = n.Parent) + if (n.Type == TYPE_SYSTEM) return n; + return null; } private sealed class ValidationContext(ISymbolTable symbols) : IValidationContext @@ -114,13 +155,15 @@ private sealed class ValidationContext(ISymbolTable symbols) : IValidationContex public void Error(string code, MetaData node, string message) { // The core descriptors use built-in codes; a downstream provider's custom code - // (not a defined enum member — including a numeric string) maps to ERR_UNKNOWN for - // now (the message carries the detail). Enum.IsDefined guards numeric-string parses + // (not a defined enum member — including a numeric string) maps to ERR_UNKNOWN and + // keeps its spelling in ProviderCode. Enum.IsDefined guards numeric-string parses // so behaviour matches Python's value-lookup mapping exactly. - var ec = System.Enum.TryParse(code, out var parsed) - && System.Enum.IsDefined(typeof(ErrorCode), parsed) - ? parsed : ErrorCode.ERR_UNKNOWN; - Errors.Add(new MetaError(message, ec, Envelope: node.Source)); + bool builtIn = System.Enum.TryParse(code, out var parsed) + && System.Enum.IsDefined(typeof(ErrorCode), parsed); + Errors.Add(new MetaError(message, builtIn ? parsed : ErrorCode.ERR_UNKNOWN, Envelope: node.Source) + { + ProviderCode = builtIn ? null : code, + }); } } } diff --git a/server/csharp/MetaObjects/Validation/SymbolTable.cs b/server/csharp/MetaObjects/Validation/SymbolTable.cs new file mode 100644 index 0000000000..b0180b6baa --- /dev/null +++ b/server/csharp/MetaObjects/Validation/SymbolTable.cs @@ -0,0 +1,175 @@ +// The symbol table every reference check resolves against — built once per load (the binder +// analogue). Two lookups: +// +// Resolve(type, ref, pkg) — a top-level node of one type, by ADR-0059 R2 form. +// Lookup(referrer, value, facet, pkg) — the reference facet's lookup +// (spec/metamodel-definitions.md, "How a reference is looked up"): the final segment is +// typed by the facet, a dotted value walks `System.child` (or `pkg::System.child`) through +// children by name, and a bare value is looked for in the referrer's own containers, +// nearest first, before the top level. When the typed lookup finds nothing, an untyped one +// along the same order tells a value that names the wrong kind of node from one that names +// nothing. +// +// Mirrors typescript/packages/metadata/src/loader/symbol-table.ts. + +using MetaObjects.Meta; + +namespace MetaObjects.Validation; + +internal sealed class SymbolTable : ISymbolTable +{ + private readonly MetaData _root; + + /// Top-level nodes per type, keyed by resolution key. Indexed PER TYPE so a reference + /// can target a non-object node kind and so a template and an object sharing + /// pkg::Name never collide. + private readonly Dictionary> _byType = new(StringComparer.Ordinal); + + /// Every top-level node by resolution key, of any type: the owner of a dotted path + /// matches by name of any type, and two of different types under one key are ambiguous. + private readonly Dictionary> _byKey = new(StringComparer.Ordinal); + + /// Per-node child index, built the first time a lookup steps into the node. + private readonly Dictionary>> _childIndexes = + new(ReferenceEqualityComparer.Instance); + + private SymbolTable(MetaData root) => _root = root; + + public static SymbolTable Build(MetaData root) + { + var t = new SymbolTable(root); + // ADR-0039: root has no super; Children()==OwnChildren() but resolving is the default. + foreach (var child in root.Children()) + { + if (!t._byType.TryGetValue(child.Type, out var bucket)) + { + bucket = new Dictionary(StringComparer.Ordinal); + t._byType[child.Type] = bucket; + } + // ADR-0042: key by the canonical resolution key ONLY (the FQN, or the bare name for a + // root-level/empty-package node) — NO bare-name fallback, so a bare ref never binds a + // same-named node in another package. + string key = child.ResolutionKey(); + bucket[key] = child; + if (t._byKey.TryGetValue(key, out var all)) all.Add(child); + else t._byKey[key] = [child]; + } + return t; + } + + /// ADR-0059 R2 resolution within the bucket: ::Rest + /// root-absolute, ..::Rest parent-relative, pkg::Name exact, bare Name in the + /// referrer's own package then root-level. Exact keys only. An over-dropping ..:: resolves + /// to nothing here; the walk reports it as ERR_BAD_ATTR_VALUE. + public MetaData? Resolve(string type, string reference, string referrerPkg) + { + if (!_byType.TryGetValue(type, out var bucket)) return null; + IReadOnlyList keys; + try { keys = NamingRefs.OwnerCandidateKeys(reference, referrerPkg); } + catch (RefOverDropException) { return null; } + foreach (string key in keys) + if (bucket.TryGetValue(key, out var hit)) return hit; + return null; + } + + public MetaData? ResolveObject(string reference, string referrerPkg) => Resolve(TYPE_OBJECT, reference, referrerPkg); + + public ReferenceMatch Lookup(MetaData referrer, string value, ReferenceFacet facet, string referrerPkg) + { + // A `fieldPath` value is `Target.field`: only the top-level `Target` is resolved. + string reference = facet.FieldPath ? NamingRefs.SplitChildTail(value).Owner : value; + try { NamingRefs.OwnerCandidateKeys(NamingRefs.SplitChildTail(reference).Owner, referrerPkg); } + catch (RefOverDropException) { return new ReferenceMatch(OverDrop: true); } + // A `fieldPath` target is top-level: the referrer's containers are not searched. + MetaData? from = facet.FieldPath ? null : referrer; + var path = Find(from, reference, facet.TargetType, referrerPkg); + if (path is not null) return new ReferenceMatch(Path: path); + // Rule 6: the untyped lookup, along the same order, only picks the error code. + var wrongKind = Find(from, reference, null, referrerPkg); + return wrongKind is not null ? new ReferenceMatch(WrongKind: wrongKind[^1]) : new ReferenceMatch(); + } + + /// The path, top-level owner first, to the node names whose + /// final segment is of (any type when null). With no + /// , no container is searched. + private IReadOnlyList? Find(MetaData? referrer, string reference, string? type, string referrerPkg) + { + var (owner, tail) = NamingRefs.SplitChildTail(reference); + if (tail.Length == 0) + { + // Rule 4: a bare value is looked for among the children of each container of the + // referrer, nearest first, up to and including its top-level node. + if (referrer is not null && !owner.Contains(PACKAGE_SEPARATOR, StringComparison.Ordinal)) + { + for (var c = referrer.Parent; c is not null && !ReferenceEquals(c, _root); c = c.Parent) + { + var hit = ChildNamed(c, owner, type); + if (hit is not null) return [.. ContainersTo(c), hit]; + } + } + var top = type is not null ? Resolve(type, owner, referrerPkg) : FirstOrNull(TopLevelNamed(owner, referrerPkg)); + return top is not null ? [top] : null; + } + // Rule 3: `Owner.child[.grand]` — the owner by its form, then each segment by name. + string[] segments = tail[CHILD_REF_SEPARATOR.Length..].Split(CHILD_REF_SEPARATOR); + if (segments.Any(p => p.Length == 0)) return null; + var owners = TopLevelNamed(owner, referrerPkg); + if (owners.Count != 1) return null; + var walked = new List { owners[0] }; + // Rule 2: an intermediate segment matches a child by name, of any type; two children + // sharing the name make the step ambiguous. + for (int i = 0; i < segments.Length - 1; i++) + { + if (!ChildIndex(walked[^1]).TryGetValue(segments[i], out var named) || named.Count != 1) return null; + walked.Add(named[0]); + } + // Rule 1: the final segment is typed. + var last = ChildNamed(walked[^1], segments[^1], type); + if (last is null) return null; + walked.Add(last); + return walked; + } + + private static MetaData? FirstOrNull(IReadOnlyList nodes) => nodes.Count > 0 ? nodes[0] : null; + + /// The physical containers from the top-level node down to , inclusive. + private List ContainersTo(MetaData container) + { + var path = new List(); + for (MetaData? c = container; c is not null && !ReferenceEquals(c, _root); c = c.Parent) path.Insert(0, c); + return path; + } + + /// The top-level nodes of any type under the first key, by ADR-0059 R2 form, that has any. + private IReadOnlyList TopLevelNamed(string owner, string referrerPkg) + { + IReadOnlyList keys; + try { keys = NamingRefs.OwnerCandidateKeys(owner, referrerPkg); } + catch (RefOverDropException) { return []; } + foreach (string key in keys) + if (_byKey.TryGetValue(key, out var hits)) return hits; + return []; + } + + /// The first child of named , of + /// when given. + private MetaData? ChildNamed(MetaData parent, string name, string? type) + { + if (!ChildIndex(parent).TryGetValue(name, out var named)) return null; + return type is null ? named[0] : named.FirstOrDefault(c => c.Type == type); + } + + private Dictionary> ChildIndex(MetaData parent) + { + if (_childIndexes.TryGetValue(parent, out var index)) return index; + index = new Dictionary>(StringComparer.Ordinal); + // ADR-0039: resolving — a child inherited through `extends` is addressable too. + foreach (var child in parent.Children()) + { + if (index.TryGetValue(child.Name, out var list)) list.Add(child); + else index[child.Name] = [child]; + } + _childIndexes[parent] = index; + return index; + } +} diff --git a/server/csharp/MetaObjects/Validation/ValidationTypes.cs b/server/csharp/MetaObjects/Validation/ValidationTypes.cs index 279d0cce8f..85e36a3e3b 100644 --- a/server/csharp/MetaObjects/Validation/ValidationTypes.cs +++ b/server/csharp/MetaObjects/Validation/ValidationTypes.cs @@ -3,23 +3,82 @@ namespace MetaObjects.Validation; /// -/// Declares that one attribute on a node is a cross-reference to another node. A provider -/// attaches these to its TypeDefinition; the registry-derived walk resolves them against the -/// symbol table — so a new reference attr validates for free. Mirrors the TS/Java model. +/// The reference facet (spec/metamodel-definitions.md, "The reference facet"): what a +/// reference attribute may point at. A provider definition carries it as ref on a +/// type: "attr" child; the spec reader lowers it onto the attribute's +/// , and the loader enforces it with no code per provider. +/// Mirrors the TS ReferenceFacet. /// -public sealed record ReferenceDescriptor( - string Attr, +/// The type the value must resolve to. Never *. +/// The subtypes of the value may +/// resolve to. Null: any. Never empty. +/// The value is Target.field: only the top-level Target is resolved. +/// The target must be in the same system as the node that declares the attribute. +/// Raised when the value does not resolve or resolves to the wrong kind. +/// Null: and . +/// Raised when fails. Present exactly +/// when is true. +public sealed record ReferenceFacet( string TargetType, - string? TargetSubType, - bool DottedFieldPath, - string ErrorCode); + IReadOnlyList? TargetSubTypes = null, + bool FieldPath = false, + bool SameSystem = false, + string? ErrorCode = null, + string? WrongSystemCode = null) +{ + /// The code a facet with no raises when its value names no node. + public const string UnresolvedCode = "ERR_REF_UNRESOLVED"; + + /// The code a facet with no raises when its value names a node of the wrong kind. + public const string WrongKindCode = "ERR_REF_WRONG_KIND"; +} -/// Resolve a ref string to its object node under the ADR-0042 package-local -/// contract. is the effective package of the node that -/// declares the ref (a bare ref resolves in that package, else root-level). +/// +/// Declares that one attribute on a node is a cross-reference to another node: the attribute +/// name plus its reference facet. A provider either attaches these to its TypeDefinition in +/// code, or (the data form) sets ref on the attribute in its definition file; the +/// registry-derived walk enforces both against the symbol table — so a new reference attr +/// validates for free. Mirrors the TS/Java model. +/// +public sealed record ReferenceDescriptor(string Attr, ReferenceFacet Facet); + +/// +/// What one reference value names: the path to the target, or the wrong-kind node the untyped +/// lookup found instead, or neither. marks a ..:: that climbs above +/// the root package. +/// +/// The nodes the lookup walked, from the top-level owner to the target (the last +/// entry). A child inherited through extends is reached through the node it was looked up +/// in, so the path is the address the value used, not the target's physical parents. +public sealed record ReferenceMatch( + IReadOnlyList? Path = null, + MetaData? WrongKind = null, + bool OverDrop = false) +{ + /// The node the value names, or null. + public MetaData? Target => Path is { Count: > 0 } p ? p[^1] : null; +} + +/// Resolve a ref string to a top-level node under the ADR-0042 package-local +/// contract. referrerPkg is the effective package of the node that declares the ref (a +/// bare ref resolves in that package, else root-level). public interface ISymbolTable { + /// A top-level node of by ADR-0059 R2 form. + MetaData? Resolve(string type, string reference, string referrerPkg); + + /// The common case — an object-target reference. MetaData? ResolveObject(string reference, string referrerPkg); + + /// + /// Look up one reference value under a facet (spec/metamodel-definitions.md, "How a + /// reference is looked up"): kind-typed final segment, System.child and + /// pkg::System.child paths, a bare value found in the referrer's own containers first, + /// and an untyped second lookup that only tells "wrong kind" from "unresolved". + /// is the node that declares the attribute; + /// its R3 package. + /// + ReferenceMatch Lookup(MetaData referrer, string value, ReferenceFacet facet, string referrerPkg); } /// Handed to every validator: the symbol table + an error sink. diff --git a/spec/metamodel-definitions.md b/spec/metamodel-definitions.md index c942159753..b9967de5a9 100644 --- a/spec/metamodel-definitions.md +++ b/spec/metamodel-definitions.md @@ -174,7 +174,7 @@ facet that sets `sameSystem` before then can never pass and no definition file s ## Status -The format and the schema are specified here. No definition file uses `ref` yet, and no port's -spec reader reads it. Each port learns to read and enforce the facet in its own change, while no +The format and the schema are specified here. No definition file uses `ref` yet. Ports whose +spec reader reads and enforces `ref`: C#. Each port learns to read and enforce the facet in its own change, while no definition file uses it, so no registry output changes. The four existing core references then move from code into the definition files, keeping their codes.