diff --git a/CLAUDE.md b/CLAUDE.md index 78ae6bd..41c6410 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,7 @@ Schema is a C# library for defining and managing data structure schemas. It cons - **Schema** - Core library providing schema definition types (classes, enums, members, types) - **Schema.Test** - MSTest unit tests for the core library - **Schema.Cpp** - The C++ generator, in its own project because `ktsu.Coder` ships no `net8.0` -- **Schema.Cpp.Test** - Its tests, including the three acceptance tests against Holotype's target document +- **Schema.Cpp.Test** - Its tests, including the three acceptance tests against Holotype's target document and one that compiles the generated reflection table - **Schema.Editor** - ImGui-based visual editor application for creating and editing `.schema.json` files - **Schema.Editor.Test** - Headless UI tests for the editor, driven through `ktsu.ImGui.App.Testing` - **Schema.Tool** - Command line entry point for validating schemas and running their code generators @@ -202,6 +202,51 @@ nested in the class that names it. Holotype's target document nests it, which wa belonged to the component that declared it; here an enum is a top-level element any class may name, so nesting it in the one class using it today would move the type the moment a second class used it. +### The reflection table + +`CppGeneratorOptions.Reflection` adds two files: `reflect`, the vocabulary, and `reflection`, the +table. It is off by default, because they are two files a target that does not read them did not +ask for. + +**What it is for.** A generated struct carries a name, a type and an order. Everything else the +schema says about a member — its unit, its range, whether it wraps, whether two states of it can be +blended, how it is quantised on the wire, what an editor should draw — the header can only put in a +comment, which is to say it cannot say it at all. The table is where those facts become data, and a +validator, a serialiser, a network codec and an editor all read it rather than each being a +generator with its own copy. That also makes them work on a schema loaded at run time, which +generated code cannot. The rule it suggests: **generate what has to be a *type*, and write by hand +what only needs to *read* a type's description.** + +**The offsets are the compiler's.** The table says `offsetof(Class, member)` and +`sizeof(Class::member)`, so the numbers are whatever the compiler chose for that target, that ABI, +those packing rules. Reflection therefore cannot drift from the layout it describes: it is derived +from it, by the only thing that knows. A generator that worked offsets out itself would be a second +implementation of the C++ ABI and would be wrong somewhere eventually. + +**A member's kind and its representation are both carried.** `kind` is what the schema declares — +`Semantic` for a member typed `Kilograms` — and `representation` is what the bytes are, with a +semantic type followed down its chain of refinement (`Float`). One field could not do both: reading +a value out of a save file needs the second, and showing the member to a person wants the first. + +**The dimension comes from the unit.** A member's unit text is resolved through `UnitRegistry` and +the unit's own `DimensionInfo` supplies the eight exponents, so the numbers in the table cannot +disagree with the unit beside them. A member that measures nothing is dimensionless, which is the +same shape rather than a missing one. + +`reflect` is **shipped rather than generated**, like `ktsu.Semantics.Cpp`'s prelude and for the same +reason: `template struct Describe;` declares a type parameter and `concept Reflected` +is a concept, neither of which the AST models — a generator names a generic type, it never declares +one. Two lists in it are substituted, though: `TypeKind` is every `[JsonDerivedType]` on `BaseType` +and `Interpolation` is the enum of that name, each written twice (the enumeration and the names +beside it) from one list, because the alternative is a `switch` that nothing would keep in step. +That is why the C++ side emits its own vocabulary rather than being written against one a target +already has — a type added to the schema appears in C++ with no edit in either repository. + +The table is anchored by `template<> struct Describe`, which is `ktsu.Coder`'s +`ClassDeclaration.SpecialisationArguments` and was the last thing the AST could not say. The +alternative was a `DescribeRigidBody` every consumer spells for itself, which is what a lookup by +type exists to avoid. + ### Contracts `ktsu.Schema.Contracts` is the abstraction seam the models implement: `Schema : ISchema`, diff --git a/Directory.Packages.props b/Directory.Packages.props index 97cd530..a8c962a 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -5,7 +5,7 @@ - + diff --git a/Schema.Cpp.Test/ReflectionTableTests.cs b/Schema.Cpp.Test/ReflectionTableTests.cs new file mode 100644 index 0000000..68393af --- /dev/null +++ b/Schema.Cpp.Test/ReflectionTableTests.cs @@ -0,0 +1,520 @@ +// Copyright (c) 2023-2026 ktsu-dev contributors + +namespace ktsu.Schema.Cpp.Test; + +using System.Diagnostics; +using System.IO; +using System.Text.Json.Serialization; + +using ktsu.Schema.Cpp; +using ktsu.Schema.Models; +using ktsu.Schema.Models.Metadata; +using ktsu.Schema.Models.Names; +using ktsu.Schema.Models.Types; +using ktsu.Semantics.Strings; + +using Microsoft.VisualStudio.TestTools.UnitTesting; + +using SchemaEnumType = ktsu.Schema.Models.Types.Enum; + +/// +/// Covers the reflection table: what a generated header can only put in a comment, written as data +/// a program can read. +/// +/// +/// The table is what makes the rest of the schema's vocabulary reach C++ at all. A unit, a range, a +/// wrap flag, a network quantisation and an editor hint are all facts the struct cannot carry, and +/// a program that needs them either reads a table or has them written into it a second time by +/// hand - which is the drift this whole stack exists to stop. +/// +[TestClass] +public sealed class ReflectionTableTests +{ + /// + /// Two files a target that does not read them did not ask for, so they are asked for. + /// + [TestMethod] + public void EmitsNothingUnlessAsked() + { + IReadOnlyDictionary files = Generate(HolotypeOptions with { Reflection = false }); + + Assert.DoesNotContain("reflect.gen.hpp", files.Keys); + Assert.DoesNotContain("reflection.gen.hpp", files.Keys); + Assert.Contains("RigidBody.gen.hpp", files.Keys, "the ordinary headers are unaffected"); + } + + /// The vocabulary and the table are two files, and both are new. + [TestMethod] + public void EmitsTheVocabularyAndTheTable() + { + IReadOnlyDictionary files = Generate(); + + Assert.Contains("reflect.gen.hpp", files.Keys); + Assert.Contains("reflection.gen.hpp", files.Keys); + } + + /// + /// The vocabulary names every type a member can have, because the schema library is where the + /// list lives. + /// + /// + /// This is the reason the C++ side emits its own vocabulary rather than being written against + /// one the target already has: a type added to the schema appears here with no edit in either + /// repository. The two spellings - the enumeration and the names beside it - are generated from + /// one list, and the count is what says they still are. + /// + [TestMethod] + public void TheVocabularyNamesEveryTypeTheSchemaHas() + { + string vocabulary = Generate()["reflect.gen.hpp"]; + + int declared = typeof(BaseType).GetCustomAttributes(typeof(JsonDerivedTypeAttribute), inherit: false).Length; + + Assert.AreEqual(declared, CppReflection.TypeKinds.Count, "the table's kinds are not the schema's"); + Assert.AreEqual(declared, Enumerators(vocabulary, "TypeKind"), "the enumeration has drifted from the list"); + Assert.AreEqual(declared, Enumerators(vocabulary, "kTypeKindNames"), "the names have drifted from the enumeration"); + + foreach (string kind in (string[])["Float", "Semantic", "Vector3", "Enum", "Handle", "Optional"]) + { + Assert.Contains($"\t\t{kind},", vocabulary, StringComparison.Ordinal); + Assert.Contains($"\t\t\"{kind}\",", vocabulary, StringComparison.Ordinal); + } + } + + /// + /// The offsets are the compiler's answer, not the generator's. + /// + /// + /// The single most important property of the table, and the reason it cannot drift from the + /// layout it describes. A generator that worked out offsets itself would be a second + /// implementation of the C++ ABI, and would be wrong on some platform eventually - so the test + /// is not only that offsetof is there but that no number is. + /// + [TestMethod] + public void AsksTheCompilerForTheLayout() + { + string table = Generate()["reflection.gen.hpp"]; + + Assert.Contains( + ".offset = static_cast(offsetof(holo::components::RigidBody, velocity))", + table, + StringComparison.Ordinal); + Assert.Contains( + ".size = static_cast(sizeof(holo::components::RigidBody::velocity))", + table, + StringComparison.Ordinal); + Assert.Contains("alignof(holo::components::RigidBody)", table, StringComparison.Ordinal); + + foreach (string offset in (string[])[".offset = 0", ".offset = 4", ".offset = 12"]) + { + Assert.DoesNotContain(offset, table, StringComparison.Ordinal); + } + } + + /// + /// The table is reached from the type rather than by spelling a convention. + /// + [TestMethod] + public void DescribesTheClassByItsType() + { + string table = Generate()["reflection.gen.hpp"]; + + Assert.Contains("template <>\nstruct Describe", Normalised(table), StringComparison.Ordinal); + Assert.Contains("static constexpr ClassInfo info", table, StringComparison.Ordinal); + Assert.Contains(".members = kRigidBodyMembers", table, StringComparison.Ordinal); + } + + /// + /// The dimension is the unit's own, resolved through the same registry validation uses. + /// + /// + /// Derived rather than restated, so the eight numbers cannot disagree with the unit text beside + /// them. A member that measures nothing is dimensionless, which is the same shape rather than a + /// missing one. + /// + [TestMethod] + public void CarriesTheDimensionOfTheUnitItNames() + { + string table = Generate()["reflection.gen.hpp"]; + + // Metres per second: length 1, time -1, and nothing else. + Assert.Contains(".dimension = { 1, 0, -1, 0, 0, 0, 0, 0 }", table, StringComparison.Ordinal); + + // Kilograms. + Assert.Contains(".dimension = { 0, 1, 0, 0, 0, 0, 0, 0 }", table, StringComparison.Ordinal); + } + + /// + /// A semantic type is what the schema declares and a float is what the bytes are, and the table + /// says both. + /// + /// + /// One field could not do it. Anything reading a value out of untyped bytes needs the + /// representation; anything showing the member to a person wants the declared kind, because + /// "Kilograms" is the answer and "Float" is not. + /// + [TestMethod] + public void TellsTheDeclaredKindFromTheRepresentation() + { + string mass = Entry(Generate()["reflection.gen.hpp"], "Mass"); + + Assert.Contains(".kind = TypeKind::Semantic", mass, StringComparison.Ordinal); + Assert.Contains(".representation = TypeKind::Float", mass, StringComparison.Ordinal); + } + + /// + /// Every property is written, including the ones taking their default. + /// + /// + /// What a person writing this by hand would leave out, and it would be wrong: designated + /// initialisers with gaps trip -Wmissing-field-initializers, and generated code needing + /// a warning suppressed around it does not survive a build stricter than the one it was written + /// against. + /// + [TestMethod] + public void WritesEveryPropertyEvenWhenItIsTheDefault() + { + string restitution = Entry(Generate()["reflection.gen.hpp"], "Restitution"); + + foreach (string property in Properties) + { + Assert.Contains($".{property} = ", restitution, StringComparison.Ordinal); + } + } + + /// + /// An enum's values are named, and their numbers are read back out of the generated enum. + /// + /// + /// The number is the index today, because the generated enumeration writes no explicit values. + /// Casting the enumerator rather than writing the index is what keeps this describing what is + /// true the moment that stops being so. + /// + [TestMethod] + public void NamesAnEnumsValuesThroughTheGeneratedEnum() + { + string table = Generate()["reflection.gen.hpp"]; + + Assert.Contains( + "{ .name = \"Dynamic\", .value = static_cast(holo::components::BodyKind::Dynamic) }", + table, + StringComparison.Ordinal); + Assert.Contains(".enum_values = kRigidBodyBodyKindValues", table, StringComparison.Ordinal); + Assert.Contains(".enum_values = {}", table, StringComparison.Ordinal); + } + + /// + /// Declaration order is layout, so the table is in it too. + /// + /// + /// The offsets would still be right if the table were sorted - they come from the compiler - + /// but anything walking the members to write them out in order would produce a different byte + /// stream than the struct does. + /// + [TestMethod] + public void KeepsMembersInDeclarationOrder() + { + string table = Generate()["reflection.gen.hpp"]; + + int previous = -1; + foreach (string name in (string[])["Velocity", "Mass", "Heading", "Restitution", "BodyKind"]) + { + int position = table.IndexOf($".name = \"{name}\"", StringComparison.Ordinal); + + Assert.IsGreaterThan(previous, position, $"{name} is out of declaration order"); + previous = position; + } + } + + /// + /// Every class is listed, so a tool can walk them without naming any of them. + /// + [TestMethod] + public void ListsEveryClassTheSchemaDeclares() + { + Assert.Contains( + "inline constexpr const ClassInfo* kAll[] = { &Describe::info };", + Generate()["reflection.gen.hpp"], + StringComparison.Ordinal); + } + + /// + /// The table compiles, and says what it was generated to say. + /// + /// + /// Every claim below is a static_assert, so this needs no run: a wrong answer is a + /// compile error and -fsyntax-only reaches it. That matters here more than anywhere + /// else, because the two things the table exists to guarantee - that an offset is the + /// compiler's and that a lookup by type finds the right descriptor - are exactly the things + /// asserting on the text cannot check. + /// + /// Over a schema of plain types rather than Holotype's exemplar, whose headers name an engine + /// this test does not have. + /// + /// + [TestMethod] + public void TheTableCompilesAndSaysWhatItWasGeneratedToSay() + { + string directory = Emit(PlainSchema(), new CppGeneratorOptions { Reflection = true }); + + File.WriteAllText(Path.Join(directory, "meaning.cpp"), """ + #include "reflection.gen.hpp" + + using namespace plain::reflect; + + // The descriptor is found by type, which is the whole reason it is a specialisation. + static_assert(describe().members.size() == 4); + static_assert(describe().travels_as_bytes); + static_assert(describe().has("Mass")); + static_assert(!describe().has("Nonexistent")); + + // The offset in the table is the offset the compiler chose, which is what stops the + // table describing a layout other than the one beside it. + static_assert(describe().member("Mass").offset == offsetof(plain::Body, mass)); + static_assert(describe().member("Alive").offset == offsetof(plain::Body, alive)); + static_assert(describe().member("Mass").size == sizeof(plain::Body::mass)); + + // A semantic type declares one thing and stores another, and the table says both. + static_assert(describe().member("Mass").kind == TypeKind::Semantic); + static_assert(describe().member("Mass").representation == TypeKind::Float); + + // The metadata the struct itself cannot carry. + static_assert(describe().member("Mass").has_range); + static_assert(describe().member("Mass").range.minimum == 0.5); + static_assert(describe().member("Heading").range.wrap); + static_assert(describe().member("Heading").interpolation == Interpolation::Spherical); + static_assert(describe().member("Heading").editor_hint == "dial"); + static_assert(describe().member("Kind").enum_values.size() == 2); + static_assert(describe().member("Kind").enum_values[1].name == "Dynamic"); + + // The two spellings of the kind list agree, which is what generating both from one + // list is for. + static_assert(to_string(TypeKind::Float) == "Float"); + static_assert(to_string(Interpolation::Spherical) == "Spherical"); + + // Every class, without naming one. + static_assert(std::size(kAll) == 1); + + int main() { return 0; } + """); + + (int exitCode, string output) = Compile(directory, "meaning.cpp"); + + Assert.AreEqual(0, exitCode, $"the generated table should compile and hold:\n{output}"); + } + + /// Every property of a member the table carries, in the order it writes them. + private static readonly string[] Properties = + [ + "name", "description", "unit", "kind", "representation", "dimension", "offset", "size", + "has_range", "range", "interpolation", "editor_hint", "has_network", "network", "enum_values", + ]; + + private static string Normalised(string text) => text.ReplaceLineEndings("\n"); + + /// How many entries one of the vocabulary's generated lists has. + private static int Enumerators(string vocabulary, string named) + { + string text = Normalised(vocabulary); + int at = text.IndexOf(named, StringComparison.Ordinal); + int end = text.IndexOf("\n\t};", at, StringComparison.Ordinal); + + return text[at..end].Split('\n').Count(line => line.EndsWith(',')); + } + + /// + /// The one member entry naming this member, ending at the closing brace of the entry itself + /// rather than at the first one inside it. + /// + private static string Entry(string table, string member) + { + string text = Normalised(table); + int at = text.IndexOf($".name = \"{member}\"", StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, at, $"the table should describe {member}"); + + int end = text.IndexOf("\n },", at, StringComparison.Ordinal); + return text[at..(end < 0 ? text.Length : end)]; + } + + private static IReadOnlyDictionary Generate() => Generate(HolotypeOptions); + + private static IReadOnlyDictionary Generate(CppGeneratorOptions options) + { + Models.Schema schema = ExemplarSchema(); + return new CppCodeGenerator(options).Generate(schema, schema.GetCodeGenerator("Cpp".As())!); + } + + private static string Emit(Models.Schema schema, CppGeneratorOptions options) + { + string directory = Path.Join(Path.GetTempPath(), $"schema-reflect-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directory); + + IReadOnlyDictionary files = + new CppCodeGenerator(options).Generate(schema, schema.GetCodeGenerator("Cpp".As())!); + + foreach ((string name, string text) in files) + { + File.WriteAllText(Path.Join(directory, name), text); + } + + return directory; + } + + private static (int ExitCode, string Output) Compile(string directory, string file) + { + string? compiler = Find("g++") ?? Find("clang++"); + if (compiler is null) + { + Assert.Inconclusive("no C++ compiler on PATH, so the generated table was not compiled."); + } + + using Process process = new() + { + StartInfo = new ProcessStartInfo(compiler!) + { + WorkingDirectory = directory, + RedirectStandardError = true, + RedirectStandardOutput = true, + }, + }; + + foreach (string argument in (string[])["-std=c++20", "-Wall", "-Wextra", "-fsyntax-only", "-I.", file]) + { + process.StartInfo.ArgumentList.Add(argument); + } + + process.Start(); + string output = process.StandardError.ReadToEnd() + process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + + return (process.ExitCode, output); + } + + private static string? Find(string executable) + { + string name = Path.GetFileName(executable); + + return (Environment.GetEnvironmentVariable("PATH") ?? string.Empty) + .Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries) + .Select(directory => Path.Join(directory, name)) + .FirstOrDefault(File.Exists); + } + + /// What Holotype tells the generator, with the table asked for. + private static CppGeneratorOptions HolotypeOptions => new() + { + Reflection = true, + Vector3 = new CppTypeSpelling("holo::Vector3", "holotype/core/vector.hpp"), + ExistingTypes = new Dictionary(StringComparer.Ordinal) + { + ["MetresPerSecond"] = new("holo::MetresPerSecond", "holotype/core/units.hpp"), + ["Kilograms"] = new("holo::Kilograms", "holotype/core/units.hpp"), + ["Radians"] = new("holo::Radians", "holotype/core/units.hpp"), + ["Scalar"] = new("holo::Scalar", "holotype/core/units.hpp"), + }, + }; + + /// Holotype's exemplar component, as the schema a person would write. + private static Models.Schema ExemplarSchema() + { + Models.Schema schema = Configured("holo::components"); + + foreach (string unit in (string[])["MetresPerSecond", "Kilograms", "Radians", "Scalar"]) + { + schema.AddSemanticType(unit.As())!.SetUnderlyingType(new Float()); + } + + SchemaEnum bodyKind = schema.AddEnum("BodyKind".As())!; + bodyKind.TryAddValue("Static".As()); + bodyKind.TryAddValue("Kinematic".As()); + bodyKind.TryAddValue("Dynamic".As()); + + SchemaClass rigidBody = schema.AddClass("RigidBody".As())!; + rigidBody.Description = "Physical state integrated by the physics system each frame.".As(); + rigidBody.TravelsAsBytes = true; + + SchemaMember velocity = rigidBody.AddMember("Velocity".As())!; + velocity.Description = "Linear velocity in world space.".As(); + velocity.SetType(new Vector3 { ElementType = Named("MetresPerSecond") }); + velocity.Unit = "m/s".As(); + velocity.Interpolation = Interpolation.Linear; + velocity.Network = new MemberNetwork { Quantise = 0.01, Delta = true }; + + SchemaMember mass = rigidBody.AddMember("Mass".As())!; + mass.SetType(Named("Kilograms")); + mass.Unit = "kg".As(); + mass.Range = new MemberRange { Minimum = 0.001, Maximum = 1000000 }; + mass.DefaultValue = new NumberDefault { Value = 1.0 }; + + SchemaMember heading = rigidBody.AddMember("Heading".As())!; + heading.SetType(Named("Radians")); + heading.Unit = "Radian".As(); + heading.Range = new MemberRange { Minimum = 0, Maximum = 6.2831853, Wrap = true }; + heading.Network = new MemberNetwork { Quantise = 0.001 }; + heading.Editor = "dial".As(); + + SchemaMember restitution = rigidBody.AddMember("Restitution".As())!; + restitution.SetType(Named("Scalar")); + restitution.Unit = "1".As(); + restitution.Range = new MemberRange { Minimum = 0, Maximum = 1 }; + restitution.DefaultValue = new NumberDefault { Value = 0.5 }; + + SchemaMember kind = rigidBody.AddMember("BodyKind".As())!; + kind.SetType(new SchemaEnumType { EnumName = "BodyKind".As() }); + kind.DefaultValue = new TextDefault { Value = "Dynamic" }; + + return schema; + } + + /// + /// A schema whose C++ needs nothing the standard library does not have, so it can be compiled + /// here. + /// + private static Models.Schema PlainSchema() + { + Models.Schema schema = Configured("plain"); + + schema.AddSemanticType("Kilograms".As())!.SetUnderlyingType(new Float()); + + SchemaEnum kinds = schema.AddEnum("BodyKind".As())!; + kinds.TryAddValue("Static".As()); + kinds.TryAddValue("Dynamic".As()); + + SchemaClass body = schema.AddClass("Body".As())!; + body.Description = "A body of plain types.".As(); + body.TravelsAsBytes = true; + + SchemaMember mass = body.AddMember("Mass".As())!; + mass.SetType(Named("Kilograms")); + mass.Unit = "kg".As(); + mass.Range = new MemberRange { Minimum = 0.5, Maximum = 100 }; + + SchemaMember heading = body.AddMember("Heading".As())!; + heading.SetType(new Float()); + heading.Range = new MemberRange { Minimum = 0, Maximum = 6.2831853, Wrap = true }; + heading.Interpolation = Interpolation.Spherical; + heading.Editor = "dial".As(); + + SchemaMember kind = body.AddMember("Kind".As())!; + kind.SetType(new SchemaEnumType { EnumName = "BodyKind".As() }); + + SchemaMember alive = body.AddMember("Alive".As())!; + alive.SetType(new Bool()); + + return schema; + } + + private static Models.Schema Configured(string containing) + { + Models.Schema schema = new(); + + SchemaCodeGenerator configuration = schema.AddCodeGenerator("Cpp".As())!; + configuration.Language = CppCodeGenerator.LanguageId.As(); + configuration.Namespace = containing.As(); + + return schema; + } + + private static Semantic Named(string semanticType) => + new() { SemanticTypeName = semanticType.As() }; +} diff --git a/Schema.Cpp/CppCodeGenerator.cs b/Schema.Cpp/CppCodeGenerator.cs index ca189f3..362a402 100644 --- a/Schema.Cpp/CppCodeGenerator.cs +++ b/Schema.Cpp/CppCodeGenerator.cs @@ -84,6 +84,20 @@ public IReadOnlyDictionary Generate(Models.Schema schema, Schema Emit(files, builder.Interface(schemaInterface)); } + if (Options.Reflection) + { + // The vocabulary is shipped rather than generated and is the same bytes for every + // schema of one target, so writing it beside each is harmless; the table beside it is + // the part derived from this schema. + files[$"{CppReflection.Header}{Options.HeaderExtension}"] = CppReflection.Prelude( + string.IsNullOrEmpty(configuration.Namespace) + ? CppReflection.Namespace + : $"{configuration.Namespace}::{CppReflection.Namespace}", + $"Generated by {Options.GeneratedBy}. Do not edit."); + + Emit(files, new CppReflectionBuilder(schema, configuration, Options).Tables()); + } + return files; } diff --git a/Schema.Cpp/CppGeneratorOptions.cs b/Schema.Cpp/CppGeneratorOptions.cs index 807b9e6..9fc100b 100644 --- a/Schema.Cpp/CppGeneratorOptions.cs +++ b/Schema.Cpp/CppGeneratorOptions.cs @@ -119,4 +119,18 @@ public sealed record CppGeneratorOptions /// Gets how the target spells the name of a member, function or parameter. /// public CppMemberNaming MemberNaming { get; init; } = CppMemberNaming.SnakeCase; + + /// + /// Gets a value indicating whether to emit the reflection table beside the headers. + /// + /// + /// Off by default, because it is two files a target that does not read them did not ask for. + /// + /// What it buys is everything the header can only put in a comment: a unit, a range, whether + /// two states of a member can be blended, how it is quantised on the wire, what an editor + /// should draw. A generated struct carries none of that, and a program that needs it either + /// reads a table or has the facts written into it a second time by hand. + /// + /// + public bool Reflection { get; init; } } diff --git a/Schema.Cpp/CppReflection.cs b/Schema.Cpp/CppReflection.cs new file mode 100644 index 0000000..d52397c --- /dev/null +++ b/Schema.Cpp/CppReflection.cs @@ -0,0 +1,146 @@ +// Copyright (c) 2023-2026 ktsu-dev contributors + +namespace ktsu.Schema.Cpp; + +using System.Collections.ObjectModel; +using System.IO; +using System.Reflection; +using System.Text.Json.Serialization; + +using ktsu.Schema.Models.Metadata; +using ktsu.Schema.Models.Types; + +/// +/// The vocabulary a generated reflection table is written in, and the two enumerations of it that +/// come from the schema library rather than from C++. +/// +/// +/// The header itself is shipped rather than generated, for the same reason +/// ktsu.Semantics.Cpp ships its Quantity: almost none of it is derived from anything, +/// and the parts that are cannot be said by the AST at all. template <typename T> struct +/// Describe; declares a type parameter, which the AST deliberately does not model — a generator +/// names a generic type, it never declares one — and a concept is not a node either. +/// +/// Two lists are derived, though, and they are why the file is substituted rather than copied: +/// is every type a member can have and is +/// every way two values can be blended, both read off the schema library. A type added there +/// appears here with no edit in this file and none in the target's tree, which is the whole reason +/// the C++ side of this stack emits its own vocabulary instead of sharing Holotype's. +/// +/// +/// Each list is written into the header twice, as the enumeration and as the names beside it, and +/// that is deliberate rather than redundant: the alternative is a switch, which the AST +/// cannot say and which nothing would then keep in step with the enumeration. Two spellings +/// generated from one list cannot disagree. +/// +/// +internal static class CppReflection +{ + /// The namespace the vocabulary and the tables are generated into, under the target's own. + internal const string Namespace = "reflect"; + + /// The name of the shipped header, without an extension. + internal const string Header = "reflect"; + + /// The name of the generated header, without an extension. + internal const string TablesHeader = "reflection"; + + private const string NamespaceToken = "@NAMESPACE@"; + private const string BannerToken = "@BANNER@"; + private const string TypeKindsToken = "@TYPEKINDS@"; + private const string TypeKindNamesToken = "@TYPEKINDNAMES@"; + private const string InterpolationsToken = "@INTERPOLATIONS@"; + private const string InterpolationNamesToken = "@INTERPOLATIONNAMES@"; + + /// + /// Every type a member can have, named as the schema file names it. + /// + /// + /// Read off 's polymorphic discriminators, which is the same list + /// answers from — so the enumerator and the TypeName + /// written to a .schema.json are the same word, and a consumer holding one can compare + /// it to the other. + /// + /// Sorted rather than left in declaration order. Attribute order is not something the runtime + /// promises, and a generated enumeration whose numbering depends on it would be stable only by + /// luck. + /// + /// + internal static IReadOnlyList TypeKinds { get; } = new ReadOnlyCollection( + [ + .. typeof(BaseType).GetCustomAttributes() + .Select(derived => derived.TypeDiscriminator?.ToString() ?? derived.DerivedType.Name) + .OrderBy(name => name, StringComparer.Ordinal), + ]); + + /// Every way two states of a member can be blended. + internal static IReadOnlyList Interpolations { get; } = new ReadOnlyCollection( + [.. System.Enum.GetNames()]); + + /// + /// Reads the shipped header and fills in what the target and the schema library decide. + /// + /// The namespace the vocabulary is generated into. + /// The line the file opens with. + /// The header, with line endings normalised. + internal static string Prelude(string containing, string banner) + { + Assembly assembly = typeof(CppReflection).Assembly; + string resource = assembly.GetManifestResourceNames() + .Single(name => name.EndsWith($".{Header}.hpp", StringComparison.Ordinal)); + + using Stream stream = assembly.GetManifestResourceStream(resource)!; + using StreamReader reader = new(stream); + + return reader.ReadToEnd() + .Replace(NamespaceToken, containing, StringComparison.Ordinal) + .Replace(BannerToken, banner, StringComparison.Ordinal) + .Replace(TypeKindsToken, Enumerators(TypeKinds), StringComparison.Ordinal) + .Replace(TypeKindNamesToken, Names(TypeKinds), StringComparison.Ordinal) + .Replace(InterpolationsToken, Enumerators(Interpolations), StringComparison.Ordinal) + .Replace(InterpolationNamesToken, Names(Interpolations), StringComparison.Ordinal) + .ReplaceLineEndings("\n"); + } + + /// + /// How a member's declared type is named in the table. + /// + /// The type. + /// The enumerator, qualified by the enumeration. + internal static string Kind(BaseType type) => + $"TypeKind::{Ensure.NotNull(type).TypeName}"; + + /// + /// How the bytes a member occupies are named in the table. + /// + /// + /// A semantic type is followed down its chain of refinement to the type it is stored as, which + /// is the whole reason the table carries this beside the declared kind: Kilograms tells + /// a person what the member is and tells a codec nothing about how to read it. + /// + /// A chain that reaches nothing real answers with the declared kind, the same way + /// Schema.Validation treats an unresolved semantic type — already reported elsewhere, + /// rather than walked further from here. + /// + /// + /// The type. + /// The enumerator, qualified by the enumeration. + internal static string Representation(BaseType type) => + Ensure.NotNull(type) is Semantic semantic && semantic.Declaration?.Representation() is BaseType stored + ? Kind(stored) + : Kind(type); + + /// + /// How a member's interpolation is named in the table. + /// + /// The interpolation. + /// The enumerator, qualified by the enumeration. + internal static string Blend(Interpolation interpolation) => + $"Interpolation::{interpolation}"; + + private static string Enumerators(IReadOnlyList names) => + string.Join("\n", names.Select(name => $"\t\t{name},")); + + private static string Names(IReadOnlyList names) => + string.Join("\n", names.Select(name => $"\t\t\"{name}\",")); +} diff --git a/Schema.Cpp/CppReflectionBuilder.cs b/Schema.Cpp/CppReflectionBuilder.cs new file mode 100644 index 0000000..58069c2 --- /dev/null +++ b/Schema.Cpp/CppReflectionBuilder.cs @@ -0,0 +1,375 @@ +// Copyright (c) 2023-2026 ktsu-dev contributors + +namespace ktsu.Schema.Cpp; + +using ktsu.Coder.Ast; +using ktsu.Schema.Models; +using ktsu.Schema.Models.Metadata; +using ktsu.Semantics.Quantities; + +using SchemaEnumType = ktsu.Schema.Models.Types.Enum; + +/// +/// Builds the table that lets a program read a generated class without being written against it. +/// +/// +/// A schema says a great deal that C++ cannot: a unit, a range, whether two states of a member can +/// be blended, how it should be quantised on the wire, what an editor should draw for it. The +/// generated header says all of it in comments, which is to say it says none of it. This is where +/// those facts become data. +/// +/// The offsets are not computed here. The table says offsetof(Class, member), so the +/// offset is whatever the compiler chose for that target, that ABI, those packing rules. A +/// generator that worked them out itself would be a second implementation of the C++ ABI and would +/// be wrong somewhere eventually. The same goes for sizeof and alignof. +/// +/// +/// What reads it is written once, by hand. A validator, a serialiser, a network codec and an +/// editor all walk this rather than each being a generator with its own copy of the same facts — +/// which is also what lets them work on a schema loaded at run time, where generated code cannot. +/// The rule that suggests: generate what has to be a type, and write by hand what only +/// needs to read a type's description. +/// +/// +/// The schema being generated. +/// The generator configuration, which names the namespace. +/// What the target says about the types this generator cannot invent. +internal sealed class CppReflectionBuilder(Models.Schema schema, SchemaCodeGenerator configuration, CppGeneratorOptions options) +{ + /// The axes of Dimension, in the order it declares them. + /// + /// The keys ktsu.Semantics.Quantities writes in a dimensional formula, which is where + /// these numbers come from: the member names a unit, the registry resolves it, and the unit + /// knows its own dimension. A generated table therefore cannot disagree with the unit the + /// schema wrote, because it is derived from it rather than restated beside it. + /// + private static readonly string[] Axes = + [ + "length", "mass", "time", "angle", "electricCurrent", "temperature", "amountOfSubstance", "luminousIntensity", + ]; + + /// + /// Builds the header carrying every class's table and the descriptor that anchors it. + /// + /// The file. + public SourceFile Tables() + { + SourceFile file = new(CppReflection.TablesHeader) { IsHeader = true }; + + file.HeaderComment.Add($"Generated by {options.GeneratedBy}. Do not edit."); + file.HeaderComment.Add(string.Empty); + file.HeaderComment.Add("Editing this file is editing the wrong thing: it is derived from the schema,"); + file.HeaderComment.Add("and the next build overwrites it. Change the schema instead."); + file.HeaderComment.Add(string.Empty); + file.HeaderComment.Add("Every offset and size here is the compiler's answer rather than this generator's,"); + file.HeaderComment.Add("so the table cannot drift from the layout it describes."); + + // offsetof is 's, and the widths the table stores are 's. The standard + // library first and the target's own after it, each sorted, which is the order the rest of + // this generator's files are written in; an empty import is the group separator. + file.Imports.Add(""); + file.Imports.Add(""); + file.Imports.Add(string.Empty); + + foreach (string header in Headers()) + { + file.Imports.Add(header); + } + + NamespaceDeclaration containing = new(Containing); + + foreach (SchemaClass schemaClass in schema.Classes) + { + foreach (AstNode node in Described(schemaClass)) + { + containing.Members.Add(node); + } + } + + containing.Members.Add(Everything()); + file.Members.Add(containing); + return file; + } + + /// + /// The namespace the vocabulary and the tables share, under the target's own. + /// + /// + /// Under it rather than beside it, so a target that generates two schemas into one namespace + /// gets one vocabulary: the shipped header is the same bytes for every schema, and writing it + /// twice into the same place is therefore harmless rather than a conflict. + /// + private string Containing => + string.IsNullOrEmpty(configuration.Namespace) + ? CppReflection.Namespace + : $"{configuration.Namespace}::{CppReflection.Namespace}"; + + /// Spells a generated type's name as the table has to reach it, from inside the vocabulary's namespace. + private string Qualified(string name) => + string.IsNullOrEmpty(configuration.Namespace) ? name : $"{configuration.Namespace}::{name}"; + + /// + /// The headers the table needs: the vocabulary it is written in, every class it describes, and + /// any enum it names a value of. + /// + private SortedSet Headers() + { + SortedSet headers = [$"\"{CppReflection.Header}{options.HeaderExtension}\""]; + + foreach (SchemaClass schemaClass in schema.Classes) + { + headers.Add($"\"{schemaClass.Name}{options.HeaderExtension}\""); + + foreach (SchemaEnum named in schemaClass.Members.Select(Enumerated).OfType()) + { + headers.Add($"\"{named.Name}{options.HeaderExtension}\""); + } + } + + return headers; + } + + /// + /// One class: the values of any enum it names, its members, and the descriptor that attaches + /// the two to the type. + /// + private IEnumerable Described(SchemaClass schemaClass) + { + string name = CppNaming.Type(schemaClass.Name.ToString(), "Class"); + + foreach ((SchemaMember member, SchemaEnum named) in Enumerations(schemaClass)) + { + yield return Values(schemaClass, member, named); + } + + yield return Members(schemaClass); + yield return Descriptor(schemaClass, name); + } + + /// + /// The names and numbers of one enum-typed member's values. + /// + /// + /// The number is read back out of the generated C++ enum rather than assumed to be the index. + /// They are the same today, because the generated enumeration writes no explicit values; the + /// moment it does, this keeps describing what is true rather than what used to be. + /// + private FieldDeclaration Values(SchemaClass schemaClass, SchemaMember member, SchemaEnum named) + { + string type = Qualified(CppNaming.Type(named.Name.ToString(), "Enum")); + ConstructionExpression values = new(); + + foreach (string value in named.Values.Select(value => value.ToString())) + { + ConstructionExpression entry = new(); + entry.Arguments.Add(new MemberInitialiser("name", new LiteralExpression(value))); + entry.Arguments.Add(new MemberInitialiser( + "value", + new VariableReference($"static_cast({type}::{CppNaming.Type(value, "Enum value")})"))); + + values.Arguments.Add(entry); + } + + return Table(ValuesTable(schemaClass, member), "EnumValue", values); + } + + /// Every member of one class, in declaration order, which is the order they are laid out in. + private FieldDeclaration Members(SchemaClass schemaClass) + { + ConstructionExpression members = new(); + + foreach (SchemaMember member in schemaClass.Members) + { + members.Arguments.Add(Described(schemaClass, member)); + } + + return Table($"k{schemaClass.Name}Members", "MemberInfo", members); + } + + /// + /// One member, with every property written out including the ones taking their default. + /// + /// + /// Omitting a default is what a person writing this by hand would do, and it is wrong here: + /// designated initialisers with gaps trip -Wmissing-field-initializers, and generated + /// code that needs a warning suppressed around it is generated code that does not survive a + /// build stricter than the one it was written against. + /// + private ConstructionExpression Described(SchemaClass schemaClass, SchemaMember member) + { + string owner = Qualified(CppNaming.Type(schemaClass.Name.ToString(), "Class")); + string field = CppNaming.Member(member.Name.ToString(), options.MemberNaming, "Member"); + + ConstructionExpression described = new(); + described.Arguments.Add(new MemberInitialiser("name", new LiteralExpression(member.Name.ToString()))); + described.Arguments.Add(new MemberInitialiser("description", new LiteralExpression(member.Description.ToString()))); + described.Arguments.Add(new MemberInitialiser("unit", new LiteralExpression(member.Unit?.ToString() ?? string.Empty))); + described.Arguments.Add(new MemberInitialiser("kind", new VariableReference(CppReflection.Kind(member.Type)))); + described.Arguments.Add(new MemberInitialiser("representation", new VariableReference(CppReflection.Representation(member.Type)))); + described.Arguments.Add(new MemberInitialiser("dimension", Dimension(member))); + + // The compiler answers both of these. That is the whole reason the table cannot drift from + // the layout it describes. + described.Arguments.Add(new MemberInitialiser( + "offset", + new VariableReference($"static_cast(offsetof({owner}, {field}))"))); + described.Arguments.Add(new MemberInitialiser( + "size", + new VariableReference($"static_cast(sizeof({owner}::{field}))"))); + + described.Arguments.Add(new MemberInitialiser("has_range", new LiteralExpression(member.Range is not null))); + described.Arguments.Add(new MemberInitialiser("range", Range(member.Range))); + described.Arguments.Add(new MemberInitialiser("interpolation", new VariableReference(CppReflection.Blend(member.Interpolation)))); + described.Arguments.Add(new MemberInitialiser("editor_hint", new LiteralExpression(member.Editor?.ToString() ?? string.Empty))); + described.Arguments.Add(new MemberInitialiser("has_network", new LiteralExpression(member.Network is not null))); + described.Arguments.Add(new MemberInitialiser("network", Network(member.Network))); + described.Arguments.Add(new MemberInitialiser("enum_values", EnumValues(schemaClass, member))); + + return described; + } + + /// + /// The exponents of the unit the member names, or all zeroes when it names none. + /// + /// + /// A member that measures nothing — an identifier, a name, a flag — is dimensionless, and so is + /// a member whose unit does not resolve. The second is not silently the same as the first: + /// Schema.Validate reports an unresolvable unit, so reaching here with one means the + /// schema was generated without being validated first. + /// + private static ConstructionExpression Dimension(SchemaMember member) + { + ConstructionExpression dimension = new(); + Dictionary formula = member.TryResolveUnit(out IUnit? unit, out _) && unit is not null + ? unit.Dimension.DimensionalFormula + : new Dictionary(StringComparer.Ordinal); + + foreach (string axis in Axes) + { + dimension.Arguments.Add(new LiteralExpression(formula.TryGetValue(axis, out int exponent) ? exponent : 0)); + } + + return dimension; + } + + private static ConstructionExpression Range(MemberRange? range) + { + ConstructionExpression written = new(); + written.Arguments.Add(new LiteralExpression(range?.Minimum ?? 0.0)); + written.Arguments.Add(new LiteralExpression(range?.Maximum ?? 0.0)); + written.Arguments.Add(new LiteralExpression(range?.Wrap ?? false)); + return written; + } + + private static ConstructionExpression Network(MemberNetwork? network) + { + ConstructionExpression written = new(); + written.Arguments.Add(new LiteralExpression(network?.Quantise ?? 0.0)); + written.Arguments.Add(new LiteralExpression(network?.Delta ?? false)); + return written; + } + + private Expression EnumValues(SchemaClass schemaClass, SchemaMember member) => + Enumerated(member) is null + ? new ConstructionExpression() + : new VariableReference(ValuesTable(schemaClass, member)); + + /// + /// The descriptor: what makes the table reachable from the type rather than by convention. + /// + /// + /// A specialisation rather than a class named after its subject, because the alternative is + /// that every consumer spells Describe plus the class's name for itself and nothing + /// checks that it got it right. describe<RigidBody>() either finds a table or is a + /// compile error naming the type that has none. + /// + private ClassDeclaration Descriptor(SchemaClass schemaClass, string name) + { + ClassDeclaration describe = new("Describe") + { + Kind = TypeDeclarationKind.Struct, + SpecialisationArguments = { new TypeReference(Qualified(name)) }, + }; + + ConstructionExpression info = new(); + info.Arguments.Add(new MemberInitialiser("name", new LiteralExpression(schemaClass.Name.ToString()))); + info.Arguments.Add(new MemberInitialiser("description", new LiteralExpression(schemaClass.Description.ToString()))); + info.Arguments.Add(new MemberInitialiser( + "size", + new VariableReference($"static_cast(sizeof({Qualified(name)}))"))); + info.Arguments.Add(new MemberInitialiser( + "alignment", + new VariableReference($"static_cast(alignof({Qualified(name)}))"))); + info.Arguments.Add(new MemberInitialiser("travels_as_bytes", new LiteralExpression(schemaClass.TravelsAsBytes))); + info.Arguments.Add(new MemberInitialiser("members", new VariableReference($"k{schemaClass.Name}Members"))); + + describe.Members.Add(new FieldDeclaration("info", "ClassInfo") + { + IsStatic = true, + IsConstant = true, + InitialValue = info, + }); + + return describe; + } + + /// + /// Every class the schema declares, in declaration order, so a tool can walk them all without + /// naming any of them. + /// + private FieldDeclaration Everything() + { + ConstructionExpression all = new(); + + foreach (SchemaClass schemaClass in schema.Classes) + { + string name = Qualified(CppNaming.Type(schemaClass.Name.ToString(), "Class")); + all.Arguments.Add(new VariableReference($"&Describe<{name}>::info")); + } + + FieldDeclaration everything = new("kAll", new TypeReference("ClassInfo") + { + IsReadOnly = true, + Indirection = TypeIndirection.Pointer, + IsArray = true, + }) + { + IsConstant = true, + InitialValue = all, + }; + + everything.Documentation.Add("Every class this schema declares, in declaration order."); + return everything; + } + + private static FieldDeclaration Table(string name, string type, ConstructionExpression entries) + { + FieldDeclaration table = new(name, new TypeReference(type) { IsArray = true }) + { + IsConstant = true, + InitialValue = entries, + }; + + return table; + } + + private static string ValuesTable(SchemaClass schemaClass, SchemaMember member) => + $"k{schemaClass.Name}{member.Name}Values"; + + /// The enum a member names, or null when it names none. + private SchemaEnum? Enumerated(SchemaMember member) => + member.Type is SchemaEnumType named ? schema.GetEnum(named.EnumName) : null; + + /// + /// Each member that names an enum, paired with the enum it names. + /// + /// + /// A projection rather than a loop with a test inside it: a member that names no enum + /// contributes nothing, which is what an empty sequence says, and the caller then does one + /// thing to everything it is handed. + /// + private IEnumerable<(SchemaMember Member, SchemaEnum Named)> Enumerations(SchemaClass schemaClass) => + schemaClass.Members.SelectMany(member => Enumerated(member) is SchemaEnum named + ? new[] { (Member: member, Named: named) } + : []); +} diff --git a/Schema.Cpp/Prelude/reflect.hpp b/Schema.Cpp/Prelude/reflect.hpp new file mode 100644 index 0000000..75c47c2 --- /dev/null +++ b/Schema.Cpp/Prelude/reflect.hpp @@ -0,0 +1,233 @@ +// @BANNER@ +// +// The vocabulary a generated reflection table is written in. +// +// Nothing here describes any particular class. `Describe` is specialised once per class in the +// table beside this file, and a validator, a serialiser, a network codec and an editor all read +// that instead of each being a generator with its own copy of the same facts. +// +// Two properties matter more than the rest. +// +// The first is that offsets are not computed here or by the generator. A generated table says +// `offsetof(Class, member)`, so the offset is whatever the compiler chose for this target, this +// ABI, these packing rules. Reflection therefore cannot drift from the layout it describes: it is +// derived from it, by the only thing that knows. A generator that computed offsets itself would be +// a second implementation of the C++ ABI, and would be wrong somewhere eventually. +// +// The second is that all of it is constexpr. A descriptor costs nothing at run time, has no static +// initialisation order to get wrong, and something built on it folds away when its inputs are +// known. +// +// Two of the enumerations below are generated from the schema library's own -- `TypeKind` from the +// types a member can have, `Interpolation` from the ways two values can be blended -- so a type +// added there appears here without an edit. Each is written twice, as the enumeration and as the +// names beside it, from one list: two spellings of one fact that cannot disagree, which is what a +// switch would not have given. + +#pragma once + +#include +#include +#include +#include + +namespace @NAMESPACE@ +{ + + // What a member is. Mirrors the schema's own set of types, which is why it is generated rather + // than written here: the schema is where a type is added, and a hand-kept copy would fall + // behind it silently. + enum class TypeKind : std::uint8_t + { +@TYPEKINDS@ + }; + + inline constexpr std::string_view kTypeKindNames[] = { +@TYPEKINDNAMES@ + }; + + [[nodiscard]] constexpr std::string_view to_string(TypeKind kind) + { + return kTypeKindNames[static_cast(kind)]; + } + + // Whether a value between two states of a member means anything, and along what. An + // orientation takes the shortest arc; an identifier is not something to be halfway through. + enum class Interpolation : std::uint8_t + { +@INTERPOLATIONS@ + }; + + inline constexpr std::string_view kInterpolationNames[] = { +@INTERPOLATIONNAMES@ + }; + + [[nodiscard]] constexpr std::string_view to_string(Interpolation interpolation) + { + return kInterpolationNames[static_cast(interpolation)]; + } + + // Exponents over the SI base units, with angle as an eighth axis. A member's C++ type already + // carries this where it is a semantic type, so this exists for the code that cannot see the + // type: an editor deciding what suffix to draw, a validator checking a number parsed from a + // save file. + struct Dimension + { + std::int8_t length = 0; + std::int8_t mass = 0; + std::int8_t time = 0; + std::int8_t angle = 0; + std::int8_t current = 0; + std::int8_t temperature = 0; + std::int8_t amount = 0; + std::int8_t luminous = 0; + + [[nodiscard]] constexpr bool dimensionless() const + { + return length == 0 && mass == 0 && time == 0 && angle == 0 && current == 0 && + temperature == 0 && amount == 0 && luminous == 0; + } + + [[nodiscard]] friend constexpr bool operator==(const Dimension&, const Dimension&) = default; + }; + + struct Range + { + double minimum = 0.0; + double maximum = 0.0; + + // A wrapping member declares its range as a period rather than a bound: 40 radians on a + // [0, 2pi) heading is un-normalised, not invalid. Anything checking a range has to read + // this too, or it rejects every angle nobody has reduced yet. + bool wrap = false; + }; + + // How a member is quantised on the wire, in the member's own unit. + struct Network + { + double quantise = 0.0; + bool delta = false; + }; + + struct EnumValue + { + std::string_view name; + std::int64_t value = 0; + }; + + struct MemberInfo + { + std::string_view name; + std::string_view description; + + // The unit as the schema wrote it ("m/s"), for display. `dimension` is the same fact in + // the form code should branch on. + std::string_view unit; + + // What the schema declares the member as. A semantic type is `Semantic` here, because that + // is the word the schema file uses and an editor showing the member wants it. + TypeKind kind = TypeKind::None; + + // What the bytes at `offset` actually are, with a semantic type followed down its chain of + // refinement to the type it is stored as. Equal to `kind` for everything else. Anything + // reading a value out of untyped bytes -- a save file, a packet -- branches on this one; + // anything showing the member to a person branches on the other. + TypeKind representation = TypeKind::None; + + Dimension dimension; + + // Both come from the compiler, through offsetof and sizeof in the generated table. + std::uint32_t offset = 0; + std::uint32_t size = 0; + + // std::optional is not used for any of these: this is a static table entry that an editor + // reads every byte of, so a flag beside the value keeps it trivially copyable and + // dumpable. + bool has_range = false; + Range range; + + Interpolation interpolation = Interpolation::None; + + // Free text rather than an enumeration, because the set of useful controls is open: a + // dial, a colour wheel, a curve, a file picker. An editor that does not recognise a hint + // falls back to the control the member's type implies, so an unknown one costs nothing. + std::string_view editor_hint; + + bool has_network = false; + Network network; + + // Empty unless kind == TypeKind::Enum. + std::span enum_values; + }; + + struct ClassInfo + { + std::string_view name; + std::string_view description; + std::uint32_t size = 0; + std::uint32_t alignment = 0; + + // Whether the schema says an instance is copied whole -- across a language boundary, into + // a save file, onto the wire -- without anyone reading a member on the way. That is what + // makes the offsets below load-bearing rather than merely true. + bool travels_as_bytes = false; + + std::span members; + + static constexpr std::size_t npos = static_cast(-1); + + // Lookup answers an index rather than a pointer, and that is not a style preference. Under + // -fsanitize=address, GCC stops treating the address of a sanitized global as a constant + // expression, so a constexpr function returning `&members[i]` compiles everywhere except + // under the sanitizer -- and the sanitizer build is the one that has to agree with the + // others. An index has no such problem. + [[nodiscard]] constexpr std::size_t index_of(std::string_view member_name) const + { + for(std::size_t i = 0; i < members.size(); ++i) + { + if(members[i].name == member_name) + { + return i; + } + } + return npos; + } + + [[nodiscard]] constexpr bool has(std::string_view member_name) const + { + return index_of(member_name) != npos; + } + + // Throws when the member is absent, which in a constant expression is a compile error + // naming the line that asked rather than a silent wrong answer. + [[nodiscard]] constexpr const MemberInfo& member(std::string_view member_name) const + { + for(const auto& candidate : members) + { + if(candidate.name == member_name) + { + return candidate; + } + } + throw "no member of that name on this class"; + } + }; + + // Specialised by the generated table, once per class. Left undefined here so that reflecting + // on a type nobody generated a table for is a compile error naming that type, rather than a + // link error or an empty descriptor. + template + struct Describe; + + template + [[nodiscard]] constexpr const ClassInfo& describe() + { + return Describe::info; + } + + // True when T has a generated descriptor. Lets code ask "is this a schema class?" without + // instantiating Describe and failing. + template + concept Reflected = requires { Describe::info; }; + +} // namespace @NAMESPACE@ diff --git a/Schema.Cpp/Schema.Cpp.csproj b/Schema.Cpp/Schema.Cpp.csproj index 8f4c040..70523ec 100644 --- a/Schema.Cpp/Schema.Cpp.csproj +++ b/Schema.Cpp/Schema.Cpp.csproj @@ -15,11 +15,25 @@ + + + + + + + + +