Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Centralize Firmament choice and match resolution
Yuechen Li9c14bfbba5c7
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentCompileTimeChoiceTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentCompileTimeChoiceTests.csnew file mode 100644index 00000000..bf42cbac--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentCompileTimeChoiceTests.cs@@ -0,0 +1,158 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentCompileTimeChoiceTests+{+ private static string Root => FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/CompileTimeChoicesRfc");+ public static IEnumerable<object?[]> Cases()+ {+ using var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(Root, "cases.json")));+ foreach (var row in manifest.RootElement.EnumerateArray())+ yield return [row.GetProperty("name").GetString()!, row.GetProperty("shouldBuild").GetBoolean(),+ row.TryGetProperty("reference", out var reference) ? reference.GetString() : null,+ row.TryGetProperty("diagnostic", out var diagnostic) ? diagnostic.GetString() : null];+ }++ [Theory]+ [MemberData(nameof(Cases))]+ public void ChoicesAdmitAllArmsBeforeBuildingOnlyTheSelectedValue(string name, bool admitted, string? reference, string? diagnostic)+ {+ var source = File.ReadAllText(Path.Combine(Root, name + ".firmament"));+ var parsed = FirmamentV2Parser.Parse(source);+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(parsed.IsSuccess == admitted, name + ": " + string.Join("\n", parsed.Diagnostics) + "\n" + parsed.DiagnosticSource);+ Assert.True(built.IsSuccess == admitted, name + ": " + string.Join("\n", built.Diagnostics));+ if (diagnostic is not null)+ {+ Assert.Contains(parsed.Diagnostics, d => d == diagnostic || d.StartsWith(diagnostic + ":", StringComparison.Ordinal));+ Assert.Contains(parsed.SyntaxDiagnostics, d => d.Code == diagnostic && d.SourceSpan is not null && !string.IsNullOrWhiteSpace(d.Message));+ }+ if (reference is null || !admitted) return;+ var expected = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Path.Combine(Root, reference + ".firmament")));+ Assert.True(expected.IsSuccess, string.Join("\n", expected.Diagnostics));+ Assert.Equal(expected.Value!.StepText, built.Value!.StepText);+ }++ [Fact]+ public void DecodedInvalidEnumArgumentUsesItsOriginalApplicationLocation()+ {+ var source = File.ReadAllText(Path.Combine(Root, "unknown-choice.firmament"));+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.False(parsed.IsSuccess);+ var error = Assert.Single(parsed.SyntaxDiagnostics, d => d.Code == ConceptIrResolver.UnknownEnumVariant);+ var span = Assert.IsType<FirmamentV2SourceSpan>(error.SourceSpan);+ Assert.Contains("Struct Result", source.Substring(span.Start, span.Length), StringComparison.Ordinal);+ Assert.False(string.IsNullOrWhiteSpace(error.LocationNote));+ }++ [Fact]+ public void SelectedRecordKeepsToleranceProvenancePmiAndApplicationIdentity()+ {+ var source = File.ReadAllText(Path.Combine(Root, "pmi-selected-record.firmament"));+ var compact = FirmamentV2Parser.Parse(source).Document!;+ var requirement = Assert.Single(compact.BoundPmi!.Dimensions);+ Assert.Equal(0.1, requirement.DimensionTolerance!.Plus);+ Assert.Equal(0.05, requirement.DimensionTolerance.Minus);+ Assert.Contains(requirement.DimensionOrigins, o => o.Binding == "standardBore.diameter"+ && source.Substring(o.SourceSpan.Start, o.SourceSpan.Length).Contains("tol", StringComparison.Ordinal));+ Assert.DoesNotContain(requirement.DimensionOrigins, o => o.Binding.StartsWith("largeBore", StringComparison.Ordinal));+ Assert.Contains(compact.BoundLets!, v => v.Origins.Any(o => o.Binding == "Feature Drill.inspection") && v.Tolerance?.Plus == 0.1);+ var standardSource = source.Replace("choice: BoreChoice = Compact", "choice: BoreChoice = Standard", StringComparison.Ordinal);+ var standard = FirmamentV2Parser.Parse(standardSource).Document!;+ Assert.Equal(80, standard.Solid.Box!.Size[0]);+ Assert.Equal(10, Assert.Single(Assert.Single(standard.ModifyBlocks!).SemanticHoles).ShaftDiameter);+ Assert.Equal(Assert.Single(compact.FeatureInvocations!).ApplicationIdentity, Assert.Single(standard.FeatureInvocations!).ApplicationIdentity);+ var built = FirmamentBuildAndExport.CompileSource(standardSource);+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics));+ var callout = Assert.Single(Step242SemanticPmiInspector.Inspect(built.Value!.StepText).Items, i => i.Kind == "Diameter");+ Assert.Equal(10, callout.Value);+ Assert.Equal(0.2, callout.TolerancePlus);+ Assert.Equal(0.2, callout.ToleranceMinus);+ }++ [Fact]+ public void FormatterOnlyChangesTheMatchKeywordAtItsSyntaxPosition()+ {+ var source = File.ReadAllText(Path.Combine(Root, "template-compact.firmament"));+ var formatted = FirmamentLanguageAnalysisService.Format(source, "choice.firmament", "1").Text;+ Assert.Contains("match choice", formatted, StringComparison.Ordinal);+ Assert.DoesNotContain("Match choice", formatted, StringComparison.Ordinal);+ Assert.True(FirmamentBuildAndExport.CompileSource(formatted).IsSuccess);+ Assert.Equal(formatted, FirmamentLanguageAnalysisService.Format(formatted, "choice.firmament", "2").Text);+ }++ [Fact]+ public void OptionsUsesTheSamePublicHostSchemaAndAdmissionAsEnum()+ {+ var source = File.ReadAllText(Path.Combine(Root, "template-compact.firmament"))+ .Replace("Struct Result = Plate<choice: Compact>", "", StringComparison.Ordinal);+ string? schema = null;+ string? step = null;+ foreach (var text in new[] { source, source.Replace("Enum SizeChoice", "Options SizeChoice", StringComparison.Ordinal) })+ {+ var metadata = FirmamentTemplateHostBridge.InspectModule(text, out var diagnostics);+ Assert.Empty(diagnostics);+ Assert.Equal(new[] { "Compact", "Standard" }, Assert.Single(metadata.Enums).Cases);+ var serialized = JsonSerializer.Serialize(metadata);+ if (schema is not null) Assert.Equal(schema, serialized);+ schema = serialized;+ var expansion = FirmamentTemplateHostBridge.Expand(text, "Plate", "Result",+ new Dictionary<string, FirmamentHostArgument> { ["choice"] = new("Compact") }, out diagnostics);+ Assert.NotNull(expansion);+ var built = FirmamentBuildAndExport.CompileSource(expansion.ExpandedSource);+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics));+ if (step is not null) Assert.Equal(step, built.Value!.StepText);+ step = built.Value!.StepText;+ }+ }++ [Fact]+ public void SelectingAToleranceDoesNotCreatePmiWithoutAProjection()+ {+ var source = File.ReadAllText(Path.Combine(Root, "pmi-selected-record.firmament"));+ var syntax = Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxParser.Parse(source).Document;+ var pmi = Assert.Single(Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxTraversal.Declarations(syntax), d => d.Type.Name.Text == "Pmi");+ var withoutPmi = source.Remove(pmi.Span.Start, pmi.Span.Length);+ var baseline = FirmamentBuildAndExport.CompileSource(source);+ var built = FirmamentBuildAndExport.CompileSource(withoutPmi);+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics));+ Assert.Empty(Step242SemanticPmiInspector.Inspect(built.Value!.StepText).Items);+ Assert.Equal(Aetheris.Kernel.Core.Brep.Verification.BrepMassProperties.Evaluate(baseline.Value!.RuntimeBody!).SignedVolume,+ Aetheris.Kernel.Core.Brep.Verification.BrepMassProperties.Evaluate(built.Value.RuntimeBody!).SignedVolume, 9);+ }++ [Theory]+ [InlineData("duplicate-enum-case", "firmament-static-enum-duplicate-variant")]+ [InlineData("missing-unselected", "firmament-static-match-non-exhaustive")]+ public void DomainSourceExpansionCannotEraseInvalidChoices(string name, string code)+ {+ var source = File.ReadAllText(Path.Combine(Root, name + ".firmament"));+ Assert.Null(FirmamentTemplateSourceCompiler.Expand(source, out var diagnostics));+ Assert.Contains(diagnostics, d => d.StartsWith(code, StringComparison.Ordinal));+ Assert.Null(FirmamentTemplateHostBridge.Expand(source.Replace("Struct Result = Plate<choice: Compact>", "", StringComparison.Ordinal),+ "Plate", "Result", new Dictionary<string, FirmamentHostArgument> { ["choice"] = new("Compact") }, out diagnostics));+ Assert.Contains(diagnostics, d => d.StartsWith(code, StringComparison.Ordinal));+ Assert.Contains(diagnostics, d => d.StartsWith(code + ": ", StringComparison.Ordinal) && d.Length > code.Length + 4);+ }++ [Fact]+ public void ExistingFinitePatternSelectorRejectsAnUnlistedCountWithItsAdmittedCases()+ {+ var source = StandardProductTemplateLibrary.GetTemplateSource("FlangedAdapterTemplate", "FlangedAdapterPolicy");+ var expansion = FirmamentTemplateHostBridge.Expand(source, "FlangedAdapterTemplate", "Flange5",+ new Dictionary<string, FirmamentHostArgument>+ {+ ["P"] = new("", "FlangedAdapterPolicy", new Dictionary<string, string>+ {+ ["OuterDiameter"] = "80mm", ["BodyThickness"] = "12mm", ["BoreDiameter"] = "30mm",+ ["BoltHoleDiameter"] = "6.6mm", ["BoltCount"] = "5", ["Material"] = "\"Standard.Materials.Aluminum.6061_T6\""+ })+ }, out var diagnostics);+ Assert.Null(expansion);+ Assert.Contains(diagnostics, d => d.StartsWith(ConceptIrResolver.SelectedBranchEvaluationFailure + ": ", StringComparison.Ordinal)+ && d.Contains("'5'", StringComparison.Ordinal) && d.Contains("4, 6, 8", StringComparison.Ordinal));+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2StaticLogicTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2StaticLogicTests.csindex 2f40a849..2c3ec183 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2StaticLogicTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2StaticLogicTests.cs@@ -34,7 +34,7 @@ public sealed class FirmamentV2StaticLogicTests{var parse = FirmamentV2Parser.Parse(Source().Replace(" HeavyDuty => 2mm\n", string.Empty, StringComparison.Ordinal));Assert.False(parse.IsSuccess);- Assert.Contains(parse.Diagnostics, d => d == ConceptIrResolver.NonExhaustiveMatch + ":Missing arm: HeavyDuty");+ Error(parse, ConceptIrResolver.NonExhaustiveMatch, "HeavyDuty");}[Fact]@@ -42,7 +42,7 @@ public sealed class FirmamentV2StaticLogicTests{var parse = FirmamentV2Parser.Parse(Source().Replace(" HeavyDuty => 2mm", " Standard => 2mm", StringComparison.Ordinal));Assert.False(parse.IsSuccess);- Assert.Contains(parse.Diagnostics, d => d == ConceptIrResolver.DuplicateMatchArm + ":Standard:unreachable");+ Error(parse, ConceptIrResolver.DuplicateMatchArm, "Standard");}[Fact]@@ -50,7 +50,7 @@ public sealed class FirmamentV2StaticLogicTests{var parse = FirmamentV2Parser.Parse(Source().Replace(" Standard => 1.5mm", " Standard => 90deg", StringComparison.Ordinal));Assert.False(parse.IsSuccess);- Assert.Contains(parse.Diagnostics, d => d.Contains(ConceptIrResolver.MatchArmTypeMismatch + ":BracketConcept.ChamferDistance:Standard:expected-Length:actual-Angle", StringComparison.Ordinal));+ Error(parse, ConceptIrResolver.MatchArmTypeMismatch, "Standard", "Length", "Angle");}[Fact]@@ -63,20 +63,20 @@ public sealed class FirmamentV2StaticLogicTestsAssert.Contains(unknownVariant.Diagnostics, d => d == ConceptIrResolver.UnknownEnumVariant + ":BracketVariant.Unknown");var invalidBool = FirmamentV2Parser.Parse(Source().Replace(" false => 3mm", " Standard => 3mm", StringComparison.Ordinal));- Assert.Contains(invalidBool.Diagnostics, d => d == ConceptIrResolver.InvalidBooleanArm + ":Standard");+ Error(invalidBool, ConceptIrResolver.InvalidBooleanArm, "Standard", "Bool");}[Fact]public void EnumDuplicate_InvalidScrutinee_AndSelectedFailureAreDiagnosed(){var duplicate = FirmamentV2Parser.Parse(Source().Replace(" HeavyDuty\n", " HeavyDuty\n HeavyDuty\n", StringComparison.Ordinal));- Assert.Contains(duplicate.Diagnostics, d => d == ConceptIrResolver.DuplicateEnumVariant + ":BracketVariant.HeavyDuty");+ Error(duplicate, ConceptIrResolver.DuplicateEnumVariant, "BracketVariant", "HeavyDuty");var invalidScrutinee = FirmamentV2Parser.Parse(Source().Replace("WallThickness: Match UseHeavyWall", "WallThickness: Match ChamferDistance", StringComparison.Ordinal));- Assert.Contains(invalidScrutinee.Diagnostics, d => d.StartsWith(ConceptIrResolver.InvalidMatchScrutinee + ":BracketConcept.ChamferDistance:Length", StringComparison.Ordinal));+ Error(invalidScrutinee, ConceptIrResolver.InvalidMatchScrutinee, "Length");var selectedFailure = FirmamentV2Parser.Parse(Source().Replace(" Standard => 1.5mm", " Standard => MissingValue", StringComparison.Ordinal));- Assert.Contains(selectedFailure.Diagnostics, d => d == ConceptIrResolver.SelectedBranchEvaluationFailure + ":BracketConcept.ChamferDistance:Standard");+ Error(selectedFailure, FirmamentV2Parser.ExpressionUnknownSymbol, "MissingValue");}[Fact]@@ -85,7 +85,15 @@ public sealed class FirmamentV2StaticLogicTestsvar cyclic = Source().Replace("Variant: BracketVariant = Standard", "Variant: BracketVariant = SelectedVariant\n SelectedVariant: Match Variant { Compact => Compact Standard => Standard HeavyDuty => HeavyDuty }", StringComparison.Ordinal);var parse = FirmamentV2Parser.Parse(cyclic);Assert.False(parse.IsSuccess);- Assert.Contains(parse.Diagnostics, d => d.StartsWith(ConceptIrResolver.CircularDependency + ":Variant -> SelectedVariant -> Variant", StringComparison.Ordinal));+ Error(parse, FirmamentV2Parser.ExpressionCycle, "Variant", "SelectedVariant");+ }++ private static void Error(FirmamentV2ParseResult parse, string code, params string[] details)+ {+ Assert.False(parse.IsSuccess);+ var diagnostic = Assert.Single(parse.SyntaxDiagnostics.Where(d => d.Code == code));+ Assert.NotNull(diagnostic.SourceSpan);+ Assert.All(details, detail => Assert.Contains(detail, diagnostic.Message, StringComparison.Ordinal));}internal static string Source(string variant = "Standard") => $$"""diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.csindex 8f021053..114cbd76 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs@@ -14,6 +14,14 @@ internal static class CanonicalStaticAuthoringinternal sealed record Result(string Source, FirmamentV2StaticAuthoringDocument? Document);private sealed record Template(string Name, string Type, string Parameter, string Body, FirmamentV2SourceSpan Span);+ // Historical Pattern sources select one of explicitly listed finite+ // collections. This is not a general or exhaustive Int value match.+ internal static IReadOnlyList<string> FinitePatternDomain(MatchSyntax match) => match.Arms+ .Select(a => FirmamentChoiceBinding.Pattern(a.Pattern, "Int")).OfType<string>().Distinct(StringComparer.Ordinal).ToArray();++ internal static bool IsFinitePatternSelector(DocumentSyntax document, MatchSyntax match) => FirmamentSyntaxTraversal.Declarations(document)+ .Any(d => d.Type.Name.Text == "Pattern" && d.Clauses.Any(c => c.Kind == ClauseKind.Over && c.Value.Span == match.Span));+/// <summary>Assembly consumes the same checked Record/Set values, but yields product-tree declarations.</summary>internal static Result? ExpandAssemblyPatterns(string source, List<string> diagnostics, bool spatial = false){@@ -21,6 +29,7 @@ internal static class CanonicalStaticAuthoringdiagnostics.AddRange(binding.Diagnostics.Select(d => d.Code + ": " + d.Message));if (binding.Diagnostics.Count > 0) return null;source = binding.Source;+// Assembly frames consume the same checked Record leaves as mechanical// geometry. Alpha-bound identities preserve lexical scope; the existing// substitution owner transports their nominal values to domain readers.@@ -192,6 +201,12 @@ internal static class CanonicalStaticAuthoringif (binding.Diagnostics.Count > 0) return null;scalars?.UseDataBinding(binding);source = binding.Source;+ if (scalars is null)+ {+ var choices = new FirmamentChoiceBinding(source);+ diagnostics.AddRange(choices.Diagnostics.Select(d => d.Code + ": " + d.Message));+ if (choices.Diagnostics.Any(d => d.Severity is "error" or "fatal")) return null;+ }var points = ConceptPointAuthoring.Expand(source, diagnostics);if (points is null) return null;source = points.Source;@@ -222,11 +237,11 @@ internal static class CanonicalStaticAuthoring// Enums are static type declarations. Modern template binding has consumed their// variants already, so keep them out of the material grammar just like Records.- foreach (Match header in Regex.Matches(source, @"\bEnum\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant))- {- var close = MatchPair(source, source.IndexOf('{', header.Index), '{', '}');- if (close >= 0) changes.Add((header.Index, close - header.Index + 1, string.Empty));- }+ var choiceTypes = new FirmamentChoiceBinding(source).Types;+ foreach (var declaration in FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)+ .Where(d => d.Type.Name.Text == "Enum" || d.Type.Name.Text == "Static"+ && choiceTypes.ContainsKey(FirmamentSyntaxValues.Reference(d.Annotation) ?? "")))+ changes.Add((declaration.Span.Start, declaration.Span.Length, string.Empty));var catalog = FirmamentV2TemplateExpansion.ReadDataCatalog(source, diagnostics, scalars);foreach (var record in catalog.Types.Values)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.csindex df76983e..c00e47f4 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs@@ -164,6 +164,15 @@ internal sealed record ConceptPhase3Resolution(internal static class ConceptIrResolver{+ internal sealed record SpatialField(string Type, bool Required = true);+ // Published by the spatial owner for compile-time admission and spelling.+ internal static IReadOnlyDictionary<string, IReadOnlyDictionary<string, SpatialField>> SpatialFields { get; } =+ new Dictionary<string, IReadOnlyDictionary<string, SpatialField>>(StringComparer.Ordinal)+ {+ ["Box3"] = new Dictionary<string, SpatialField> { ["Size"] = new("Length[3]") },+ ["Grid"] = new Dictionary<string, SpatialField> { ["Within"] = new("Region2"), ["Columns"] = new("Int"), ["Rows"] = new("Int") },+ ["Plane"] = new Dictionary<string, SpatialField> { ["Origin"] = new("Point3|Length[3]"), ["Normal"] = new("Int[3]|Float[3]|Vector3"), ["Up"] = new("Int[3]|Float[3]|Vector3", false) }+ };// Static expansion is deliberately bounded: Pattern is compile-time declaration generation, not iteration.private const int MaxStaticPatternExpansion = 1024;public const string MissingMember = "firmament-concept-missing-member";@@ -194,14 +203,21 @@ internal static class ConceptIrResolverprivate static readonly Regex ConceptStructHeader = new(@"\bConcept\s+Struct\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*(?<concept>[A-Za-z_][A-Za-z0-9_]*))?\s*\{", RegexOptions.CultureInvariant);private static readonly Regex MaterializedHeader = new(@"\b(?<kind>Struct|Model)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*(?<concept>[A-Za-z_][A-Za-z0-9_]*))?\s*(?<units>mm\s*)?\{", RegexOptions.CultureInvariant);- private static readonly Regex EnumHeader = new(@"\bEnum\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- public static ConceptPhase3Resolution? Resolve(string source, List<string> diagnostics)+ public static ConceptPhase3Resolution? Resolve(string source, List<string> diagnostics) => Resolve(source, diagnostics, null);++ internal static ConceptPhase3Resolution? Resolve(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars){// Match roles are compile-time conformance metadata. They deliberately do not lower to AIR,// but they must remain available to the static evaluator so invalid domains and selected-arm// failures are diagnosed before feature lowering.- var enums = ParseEnums(source, diagnostics);+ if (scalars is null)+ {+ scalars = new(source);+ scalars.Initialize(new Dictionary<string, TemplateRecordTypeIr>(), diagnostics);+ }+ var choiceErrorStart = scalars.Diagnostics.Count;+ var enums = scalars.Choices.Types.Values.Select(t => new ConceptIrEnumDefinition(t.Name, t.Cases, t.Span)).ToArray();var definitions = ParseDefinitions(source, diagnostics);var materializedMatches = MaterializedHeader.Matches(source).Cast<Match>().Where(m => !IsPrecededByConcept(source, m.Index)).ToArray();@@ -223,7 +239,7 @@ internal static class ConceptIrResolvervar close = FindMatchingBrace(source, open);if (close < 0) { diagnostics.Add(InvalidSpatialDerivation); continue; }var body = source[(open + 1)..close];- var members = ResolveMembers(name, body, open + 1, materialized.Groups["name"].Value, enums, staticSelections, diagnostics);+ var members = ResolveMembers(name, body, open + 1, materialized.Groups["name"].Value, enums, staticSelections, diagnostics, scalars);var satisfies = match.Groups["concept"].Success ? new[] { match.Groups["concept"].Value } : [];ValidateConformance(name, satisfies, members, definitions, diagnostics);var instance = new ConceptIrStructInstance(name, satisfies, members, false, "CompileTimeOnlyErased", new(match.Index, close - match.Index + 1));@@ -235,6 +251,7 @@ internal static class ConceptIrResolver}}+ if (scalars.Diagnostics.Skip(choiceErrorStart).Any(d => d.Severity is "error" or "fatal")) return null;var bodyText = source[(materializedOpen + 1)..materializedClose];ValidateIndexedReferences(bodyText, instanceList, diagnostics);var box = Regex.Match(bodyText, @"\bBox\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);@@ -623,27 +640,9 @@ internal static class ConceptIrResolverprivate static IReadOnlyList<ConceptIrEnumDefinition> ParseEnums(string source, List<string> diagnostics){- var result = new List<ConceptIrEnumDefinition>();- var names = new HashSet<string>(StringComparer.Ordinal);- foreach (Match match in EnumHeader.Matches(source))- {- var name = match.Groups["name"].Value;- var open = source.IndexOf('{', match.Index); var close = FindMatchingBrace(source, open);- if (close < 0) { diagnostics.Add(InvalidSpatialDerivation); continue; }- if (!IsPascalCase(name)) diagnostics.Add($"{InvalidEnumName}:{name}");- if (!names.Add(name)) { diagnostics.Add(DuplicateDeclaration + ":Enum:" + name); continue; }- var variants = new List<string>(); var seen = new HashSet<string>(StringComparer.Ordinal);- foreach (var raw in source[(open + 1)..close].Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries))- {- var variant = raw.Trim();- if (variant.Length == 0) continue;- if (!Regex.IsMatch(variant, @"^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.CultureInvariant) || !IsPascalCase(variant)) { diagnostics.Add($"{InvalidEnumName}:{name}.{variant}"); continue; }- if (!seen.Add(variant)) { diagnostics.Add($"{DuplicateEnumVariant}:{name}.{variant}"); continue; }- variants.Add(variant);- }- result.Add(new(name, variants, new(match.Index, close - match.Index + 1)));- }- return result;+ var binding = new FirmamentChoiceBinding(source);+ diagnostics.AddRange(binding.Diagnostics.Select(d => d.Code + ":" + d.Message));+ return binding.Types.Values.Select(t => new ConceptIrEnumDefinition(t.Name, t.Cases, t.Span)).ToArray();}private static IReadOnlyDictionary<string, ParsedConceptMember> ParseConceptMembers(string body, int bodyOffset, List<string> diagnostics)@@ -665,31 +664,6 @@ internal static class ConceptIrResolverreturn result;}- private static IReadOnlyList<ParsedMatchArm> ParseMatchArms(string body, int bodyOffset)- {- var headers = new List<(int Index, Match Match)>(); var depth = 0;- for (var lineStart = 0; lineStart < body.Length;)- {- var lineEnd = body.IndexOf('\n', lineStart); if (lineEnd < 0) lineEnd = body.Length;- var line = body[lineStart..lineEnd];- if (depth == 0)- {- var match = Regex.Match(line, @"^\s*(?<pattern>[A-Za-z_][A-Za-z0-9_]*)\s*=>\s*(?<rest>.*?)\s*$", RegexOptions.CultureInvariant);- if (match.Success) headers.Add((lineStart, match));- }- depth += line.Count(c => c == '{') - line.Count(c => c == '}');- lineStart = lineEnd == body.Length ? body.Length : lineEnd + 1;- }- var result = new List<ParsedMatchArm>();- for (var i = 0; i < headers.Count; i++)- {- var (start, match) = headers[i]; var end = i + 1 < headers.Count ? headers[i + 1].Index : body.Length;- var arrow = body.IndexOf("=>", start, end - start, StringComparison.Ordinal);- result.Add(new(match.Groups["pattern"].Value, body[(arrow + 2)..end].Trim(), new(bodyOffset + start, end - start)));- }- return result;- }-private static bool MatchesDeclaredType(string? declaredType, ConceptIrValue value){if (declaredType is null) return true;@@ -741,14 +715,18 @@ internal static class ConceptIrResolverstring materializedName,IReadOnlyList<ConceptIrEnumDefinition> enums,List<ConceptIrStaticSelection> selections,- List<string> diagnostics)+ List<string> diagnostics, FirmamentCompileTimeValues? scalars = null){+ if (scalars is null)+ {+ scalars = new("");+ scalars.UseChoiceTypes(enums.Select(e => new FirmamentChoiceBinding.Choice(e.Name, e.Variants, e.SourceSpan)));+ }var members = ParseConceptMembers(body, bodyOffset, diagnostics);- return new StaticMemberEvaluator(instanceName, materializedName, members, enums, selections, diagnostics).EvaluateAll();+ return new StaticMemberEvaluator(instanceName, materializedName, members, enums, selections, diagnostics, scalars).EvaluateAll();}private sealed record ParsedConceptMember(string Name, string? DeclaredType, string Expression, FirmamentV2SourceSpan SourceSpan);- private sealed record ParsedMatchArm(string Pattern, string Expression, FirmamentV2SourceSpan SourceSpan);private sealed class StaticMemberEvaluator(string instanceName,@@ -756,14 +734,19 @@ internal static class ConceptIrResolverIReadOnlyDictionary<string, ParsedConceptMember> members,IReadOnlyList<ConceptIrEnumDefinition> enums,List<ConceptIrStaticSelection> selections,- List<string> diagnostics)+ List<string> diagnostics, FirmamentCompileTimeValues scalars){private readonly Dictionary<string, ConceptIrValue> _resolved = new(StringComparer.Ordinal);private readonly List<string> _stack = [];public IReadOnlyDictionary<string, ConceptIrValue> EvaluateAll(){- foreach (var name in members.Keys) EvaluateMember(name);+ var before = scalars.Diagnostics.Count;+ foreach (var name in members.Keys)+ {+ EvaluateMember(name);+ if (scalars.Diagnostics.Skip(before).Any(d => d.Severity is "error" or "fatal")) break;+ }return _resolved;}@@ -795,7 +778,7 @@ internal static class ConceptIrResolverexpression = expression.Trim();var provenance = $"{instanceName}.{target.Name}";if (expression.StartsWith(materializedName + ".", StringComparison.Ordinal)) { diagnostics.Add(MaterializedPhaseReference); return null; }- if (expression.StartsWith("Match ", StringComparison.Ordinal)) return EvaluateMatch(expression, target);+ if (FirmamentSyntaxParser.ParseExpression(expression).Expression is MatchSyntax match) return EvaluateMatch(match, target);var box = Regex.Match(expression, @"^Box3\s*\{(?<body>.*)\}$", RegexOptions.Singleline | RegexOptions.CultureInvariant);if (box.Success)@@ -893,50 +876,26 @@ internal static class ConceptIrResolverreturn true;}- private ConceptIrValue? EvaluateMatch(string expression, ParsedConceptMember target)+ private ConceptIrValue? EvaluateMatch(MatchSyntax match, ParsedConceptMember target){- var header = Regex.Match(expression, @"^Match\s+(?<scrutinee>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- if (!header.Success) { diagnostics.Add(InvalidMatchScrutinee); return null; }- var scrutineeName = header.Groups["scrutinee"].Value;- var scrutinee = EvaluateMember(scrutineeName);- if (scrutinee is not (ConceptIrEnumValue or ConceptIrBoolValue)) { diagnostics.Add($"{InvalidMatchScrutinee}:{instanceName}.{scrutineeName}:{(scrutinee is null ? "unresolved" : TypeOf(scrutinee))}"); return null; }- var open = expression.IndexOf('{', header.Index); var close = FindMatchingBrace(expression, open);- if (close < 0) { diagnostics.Add(InvalidMatchScrutinee); return null; }- var arms = ParseMatchArms(expression[(open + 1)..close], target.SourceSpan.Start + open + 1);- var expectedPatterns = scrutinee is ConceptIrEnumValue enumValue- ? enums.Single(e => e.Name == enumValue.EnumType).Variants- : new[] { "true", "false" };- var seen = new HashSet<string>(StringComparer.Ordinal);- foreach (var arm in arms)- {- if (!expectedPatterns.Contains(arm.Pattern, StringComparer.Ordinal))- {- diagnostics.Add(scrutinee is ConceptIrBoolValue ? $"{InvalidBooleanArm}:{arm.Pattern}" : $"{UnknownEnumVariant}:{((ConceptIrEnumValue)scrutinee).EnumType}.{arm.Pattern}");- continue;- }- if (!seen.Add(arm.Pattern)) diagnostics.Add($"{DuplicateMatchArm}:{arm.Pattern}:unreachable");- }- foreach (var missing in expectedPatterns.Where(p => !seen.Contains(p))) diagnostics.Add($"{NonExhaustiveMatch}:Missing arm: {missing}");- if (seen.Count != arms.Count || expectedPatterns.Any(p => !seen.Contains(p))) return null;-- var armValues = new List<(ParsedMatchArm Arm, ConceptIrValue? Value)>();- foreach (var arm in arms) armValues.Add((arm, EvaluateExpression(arm.Expression, target, false)));- var first = armValues.FirstOrDefault(x => x.Value is not null).Value;- if (first is not null)- {- var expectedType = TypeOf(first);- foreach (var (arm, value) in armValues.Where(x => x.Value is not null && TypeOf(x.Value) != expectedType))- diagnostics.Add($"{MatchArmTypeMismatch}:{instanceName}.{target.Name}:{arm.Pattern}:expected-{expectedType}:actual-{TypeOf(value!)}");- if (armValues.Any(x => x.Value is not null && TypeOf(x.Value) != expectedType)) return null;- }- var selectedPattern = scrutinee is ConceptIrEnumValue selectedEnum ? selectedEnum.Variant : ((ConceptIrBoolValue)scrutinee).Value.ToString().ToLowerInvariant();- var selected = armValues.Single(x => x.Arm.Pattern == selectedPattern);- if (selected.Value is null) { diagnostics.Add($"{SelectedBranchEvaluationFailure}:{instanceName}.{target.Name}:{selectedPattern}"); return null; }- selections.Add(new(- $"{instanceName}.{target.Name}", $"{instanceName}.{scrutineeName}",- scrutinee is ConceptIrEnumValue e ? e.EnumType : "Bool", selectedPattern, selectedPattern,- TypeOf(selected.Value).ToString(), FormatValue(selected.Value), target.SourceSpan, $"{instanceName}.{target.Name}"));- return selected.Value;+ var inputs = members.ToDictionary(p => p.Key, p => new FirmamentCompileTimeValues.ChoiceInput(+ p.Value.DeclaredType ?? "", FirmamentSyntaxParser.ParseExpression(p.Value.Expression).Expression!), StringComparer.Ordinal);+ var selectedArms = new Dictionary<string, string>(StringComparer.Ordinal);+ var before = scalars.Diagnostics.Count;+ var resolved = scalars.ResolveChoices(match, diagnostics, inputs, expected: target.DeclaredType, selected: selectedArms);+ scalars.LocateChoiceErrors(before, scalars.OriginalDeclaration("Struct", instanceName, "Concept"),+ "Location identifies the original enclosing Concept Struct; match arms were bound before spatial evaluation.");+ if (scalars.Diagnostics.Skip(before).Any(d => d.Severity is "error" or "fatal")) return null;+ var selected = EvaluateExpression(FirmamentSyntaxWriter.Expression(resolved), target, false);+ var scrutineeName = FirmamentSyntaxValues.Reference(match.Scrutinee) ?? FirmamentSyntaxWriter.Expression(match.Scrutinee);+ var selectedPattern = selectedArms.GetValueOrDefault(scrutineeName) ?? "";+ if (selected is null) { diagnostics.Add($"{SelectedBranchEvaluationFailure}:{instanceName}.{target.Name}:{selectedPattern}"); return null; }+ var domain = inputs.GetValueOrDefault(scrutineeName)?.Type;+ if (string.IsNullOrEmpty(domain)) domain = selectedPattern is "true" or "false" ? "Bool"+ : enums.FirstOrDefault(e => e.Variants.Contains(selectedPattern, StringComparer.Ordinal))?.Name;+ selections.Add(new($"{instanceName}.{target.Name}", $"{instanceName}.{scrutineeName}", domain ?? "Bool", selectedPattern, selectedPattern,+ TypeOf(selected).ToString(), FormatValue(selected), target.SourceSpan, $"{instanceName}.{target.Name}"));+ return selected;}}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentChoiceBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentChoiceBinding.csnew file mode 100644index 00000000..282d84ca--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentChoiceBinding.cs@@ -0,0 +1,144 @@+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++/// <summary>Shared finite-domain admission. Selection is separate from value+/// evaluation: every arm is bound, but only the selected value is evaluated by+/// its existing scalar or spatial owner.</summary>+internal sealed class FirmamentChoiceBinding+{+ internal sealed record Choice(string Name, IReadOnlyList<string> Cases, FirmamentV2SourceSpan Span);+ internal IReadOnlyDictionary<string, Choice> Types { get; }+ internal IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics { get; }++ internal FirmamentChoiceBinding(IEnumerable<Choice> types)+ {+ Types = types.ToDictionary(t => t.Name, StringComparer.Ordinal);+ Diagnostics = [];+ }++ internal FirmamentChoiceBinding(string source)+ {+ var types = new Dictionary<string, Choice>(StringComparer.Ordinal);+ var errors = new List<FirmamentV2ValidationDiagnostic>();+ foreach (var d in FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)+ .Where(d => d.Type.Name.Text == "Enum" && d.Name is not null))+ {+ if (!char.IsUpper(d.Name!.Text[0]) && !d.Name.Text.StartsWith("__firmamentData_", StringComparison.Ordinal))+ Error(ConceptIrResolver.InvalidEnumName, $"Enum type '{d.Name.Text}' must use PascalCase.", d.Name.Span);+ var cases = new List<string>();+ foreach (var statement in d.Body?.Statements ?? [])+ {+ if (statement is not ExpressionStatementSyntax { Value: ReferenceSyntax r }+ || r.Name.Text.Length == 0 || !char.IsUpper(r.Name.Text[0]))+ { Error(ConceptIrResolver.InvalidEnumName, "An Enum case must be a PascalCase tag without fields or payload.", statement.Span); continue; }+ if (cases.Contains(r.Name.Text, StringComparer.Ordinal))+ Error(ConceptIrResolver.DuplicateEnumVariant, $"Duplicate case '{r.Name.Text}' in {d.Name!.Text}.", r.Span);+ else cases.Add(r.Name.Text);+ }+ if (cases.Count == 0) Error("firmament-static-enum-empty", $"Enum '{d.Name!.Text}' must declare at least one case.", d.Span);+ if (!types.TryAdd(d.Name!.Text, new(d.Name.Text, cases, d.Span)))+ Error("firmament-binding-duplicate-name", $"Duplicate Enum '{d.Name.Text}'.", d.Span);+ }+ Types = types;+ Diagnostics = errors;+ void Error(string code, string message, FirmamentV2SourceSpan span) => errors.Add(new(code, "error", message)+ { SourceSpan = span, Stage = "Choice binding" });+ }++ internal string? Check(MatchSyntax match, string? domain, Func<ExpressionSyntax, string?> typeOf,+ Action<FirmamentV2ValidationDiagnostic> error, IReadOnlyList<string>? finitePatternDomain = null)+ {+ var expected = domain == "Int" && finitePatternDomain is not null ? finitePatternDomain+ : domain == "Bool" ? new[] { "true", "false" }+ : domain is not null && Types.TryGetValue(domain, out var choice) ? choice.Cases : null;+ if (expected is null)+ { Fail(ConceptIrResolver.InvalidMatchScrutinee, $"match requires an Enum or Bool; found {domain ?? "an unresolved value"}.", match.Scrutinee.Span); return null; }+ if (match.Arms.Count == 0)+ { Fail(ConceptIrResolver.NonExhaustiveMatch, "match requires at least one arm.", match.Span); return null; }+ var seen = new HashSet<string>(StringComparer.Ordinal);+ var failed = false;+ foreach (var arm in match.Arms)+ {+ var tag = Pattern(arm.Pattern, domain!);+ if (tag is null || !expected.Contains(tag, StringComparer.Ordinal))+ { Fail(domain == "Bool" ? ConceptIrResolver.InvalidBooleanArm : ConceptIrResolver.UnknownEnumVariant,+ $"Unknown case '{FirmamentSyntaxWriter.Expression(arm.Pattern)}' for {domain}.", arm.Pattern.Span); failed = true; }+ else if (!seen.Add(tag))+ { Fail(ConceptIrResolver.DuplicateMatchArm, $"Duplicate match arm '{tag}' for {domain}.", arm.Pattern.Span); failed = true; }+ }+ foreach (var missing in expected.Where(c => !seen.Contains(c)))+ { Fail(ConceptIrResolver.NonExhaustiveMatch, $"Non-exhaustive match on {domain}. Missing arm: {missing}.", match.Span); failed = true; }+ string? result = null;+ foreach (var arm in match.Arms)+ {+ var type = typeOf(arm.Value);+ if (type is null) { failed = true; continue; }+ result ??= type;+ if (result != type)+ { Fail(ConceptIrResolver.MatchArmTypeMismatch, $"Match arm '{FirmamentSyntaxWriter.Expression(arm.Pattern)}' requires {result}; found {type}.", arm.Value.Span); failed = true; }+ }+ return failed ? null : result;+ void Fail(string code, string message, FirmamentV2SourceSpan span) => error(new(code, "error", message)+ { SourceSpan = span, Stage = "Choice binding" });+ }++ internal static string? Pattern(ExpressionSyntax expression, string domain) => expression switch+ {+ ReferenceSyntax r when domain != "Int" && r.Name.Text != "_" => r.Name.Text,+ LiteralSyntax { Kind: LiteralKind.Number } n when domain == "Int"+ && long.TryParse(n.Raw, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var integer) => integer.ToString(System.Globalization.CultureInfo.InvariantCulture),+ LiteralSyntax { Kind: LiteralKind.Boolean } b when domain == "Bool" => b.Raw,+ MemberSyntax { Target: ReferenceSyntax type } m when type.Name.Text == domain => m.Member.Text,+ _ => null+ };++ internal static IReadOnlyList<MatchSyntax> OutermostMatches(DocumentSyntax document)+ {+ var result = new List<MatchSyntax>();+ var coveredUntil = -1;+ foreach (var match in FirmamentSyntaxTraversal.Expressions(document).OfType<MatchSyntax>()+ .OrderBy(m => m.Span.Start).ThenByDescending(m => m.Span.Length))+ if (match.Span.Start >= coveredUntil)+ { result.Add(match); coveredUntil = match.Span.Start + match.Span.Length; }+ return result;+ }++ // Type algebra is shared by choice admission and scalar inference. Values+ // and domain objects are evaluated only by their existing owners.+ internal static string? Infer(ExpressionSyntax e, Func<ExpressionSyntax, string?> reference,+ Func<MatchSyntax, string?> match) => e switch+ {+ ReferenceSyntax or MemberSyntax or CallSyntax or IndexSyntax or WithSyntax => reference(e),+ MatchSyntax m => match(m),+ ToleranceSyntax t => Infer(t.Nominal, reference, match),+ TypedValueSyntax t => FirmamentSyntaxValues.Reference(t.Type),+ ObjectSyntax o => FirmamentSyntaxValues.Reference(o.Type),+ QuantitySyntax q => q.Unit.Text switch { "mm" => "Length", "deg" => "Angle", "s" or "ms" => "Time", _ => null },+ LiteralSyntax { Kind: LiteralKind.Boolean } => "Bool",+ LiteralSyntax { Kind: LiteralKind.String } => "String",+ LiteralSyntax { Kind: LiteralKind.Number } n => n.Raw.Contains('.') || n.Raw.Contains('e', StringComparison.OrdinalIgnoreCase) ? "Float" : "Int",+ SequenceSyntax { Kind: SequenceKind.Tuple, Items.Count: 1 } g => Infer(g.Items[0].Value, reference, match),+ SequenceSyntax { Kind: SequenceKind.List } list => SequenceType(list, reference, match),+ UnarySyntax u => Infer(u.Operand, reference, match) is { } type+ ? u.Operator == UnaryOperator.Not ? type == "Bool" ? "Bool" : null+ : u.Operator is UnaryOperator.Positive or UnaryOperator.Negative && type is "Int" or "Float" or "Length" or "Angle" or "Time" ? type : null : null,+ BinarySyntax b => BinaryType(Infer(b.Left, reference, match), b.Operator, Infer(b.Right, reference, match)),+ _ => null+ };++ private static string? SequenceType(SequenceSyntax list, Func<ExpressionSyntax, string?> reference, Func<MatchSyntax, string?> match)+ {+ var types = list.Items.Select(a => Infer(a.Value, reference, match)).ToArray();+ if (types.Length == 0 || types.Any(t => t is null)) return null;+ var type = types.All(t => t is "Int" or "Float") && types.Contains("Float") ? "Float" : types[0];+ return types.All(t => t == type || type == "Float" && t == "Int") ? type + "[" + types.Length + "]" : null;+ }++ internal static string? BinaryType(string? left, BinaryOperator op, string? right)+ {+ if (left is null || right is null) return null;+ if (!FirmamentV2Parser.TryParseLetType(left, out var l) || !FirmamentV2Parser.TryParseLetType(right, out var r)) return null;+ return FirmamentV2Parser.CompileTimeArithmeticType(l, FirmamentSyntaxWriter.Operator(op), r)?.ToString();+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeChoices.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeChoices.csnew file mode 100644index 00000000..c5b1f349--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeChoices.cs@@ -0,0 +1,399 @@+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++internal sealed partial class FirmamentCompileTimeValues+{+ internal sealed record ChoiceInput(string Type, ExpressionSyntax Value);+ private static string CanonicalValueType(string type) => FirmamentV2Parser.TryParseLetType(type, out var primitive) ? primitive.ToString() : type;+ private FirmamentChoiceBinding? choices;+ internal FirmamentChoiceBinding Choices => choices ??= new(source);+ internal void UseChoiceTypes(IEnumerable<FirmamentChoiceBinding.Choice> types) => choices = new(types);+ private readonly Dictionary<string, ChoiceInput> choiceInputs = new(StringComparer.Ordinal);+ private readonly List<string> activeChoices = [];++ internal IReadOnlyDictionary<string, ChoiceInput> ChoiceLocals(DocumentSyntax document,+ IReadOnlyDictionary<string, ChoiceInput> parameters)+ {+ var result = new Dictionary<string, ChoiceInput>(parameters, StringComparer.Ordinal);+ foreach (var d in document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Static" && d.Name is not null && d.Initializer is not null))+ result[d.Name!.Text] = new(FirmamentSyntaxValues.Reference(d.Annotation)+ ?? (d.Annotation is not null ? FirmamentSyntaxWriter.Expression(d.Annotation) : null)+ ?? (d.Initializer is ObjectSyntax o ? FirmamentSyntaxValues.Reference(o.Type) : null) ?? "", d.Initializer!);+ return result;+ }++ internal IReadOnlyDictionary<string, ChoiceInput> ChoiceScope(DocumentSyntax document, MatchSyntax match,+ IReadOnlyDictionary<string, ChoiceInput> parameters)+ {+ var inputs = new Dictionary<string, ChoiceInput>(ChoiceLocals(document, parameters), StringComparer.Ordinal);+ foreach (var d in FirmamentSyntaxTraversal.Declarations(document).Where(d => d.Body is not null && Encloses(d.Body.ContentSpan, match.Span))+ .OrderByDescending(d => d.Body!.ContentSpan.Length))+ {+ foreach (var p in d.Parameters.Concat(d.Modifiers.Where(m => m.Name.Text == "Template").SelectMany(m => m.Arguments)))+ if (p.Name is not null && FirmamentSyntaxValues.Reference(p.Value) is { } type)+ inputs[p.Name.Text] = new(type, p.Default ?? new ReferenceSyntax(p.Name, p.Name.Span));+ inputs = new(ChoiceLocals(new(document.SourceFile, d.Body!.Statements, [], d.Body.Span), inputs), StringComparer.Ordinal);+ if (d.Type.Name.Text == "Struct" && d.Modifiers.Any(m => m.Name.Text == "Concept"))+ {+ var outer = inputs.ToDictionary(p => p.Key, p => p.Value.Value, StringComparer.Ordinal);+ foreach (var field in d.Body.Statements.OfType<FieldSyntax>())+ {+ var typed = field.Value as TypedValueSyntax;+ inputs[field.Name.Text] = new(typed is null ? "" : FirmamentSyntaxValues.Reference(typed.Type) ?? "",+ new FirmamentSyntaxSubstitution(outer).Expression(typed?.Value ?? field.Value));+ }+ }+ }+ return inputs;+ }++ internal static bool Encloses(FirmamentV2SourceSpan parent, FirmamentV2SourceSpan child) =>+ parent.Start <= child.Start && parent.Start + parent.Length >= child.Start + child.Length;++ private ChoiceInput? ChoiceInputFor(string name, IReadOnlyDictionary<string, ChoiceInput>? locals,+ List<string> codes, bool evaluate, int depth = 0)+ {+ if (locals?.TryGetValue(name, out var local) == true) return local;+ var rootEnd = name.IndexOf('.');+ if (evaluate && rootEnd > 0 && locals?.TryGetValue(name[..rootEnd], out var root) == true+ && root.Value is ReferenceSyntax receipt && recordValues.TryGetValue(receipt.Name.Text, out var record)+ && record.TypeName == root.Type && RecordFieldType(root.Type, name[(rootEnd + 1)..]) is { } fieldType)+ {+ var fields = FirmamentV2TemplateExpansion.FlattenRecordFields(record, recordTypes, recordValues, codes);+ if (fields.TryGetValue(name[(rootEnd + 1)..], out var memberValue))+ return CheckedChoiceInput(fieldType, FirmamentSyntaxParser.ParseExpression(memberValue).Expression!);+ }+ if (choiceInputs.TryGetValue(name, out var input)) return input;+ if (depth >= 128)+ { ChoiceError(new(FirmamentV2Parser.ExpressionCycle, "error", $"Record choice projection exceeds the finite dependency depth at '{name}'.") { Stage = "Choice binding" }, codes); return null; }+ var dot = name.LastIndexOf('.');+ if (dot < 1 || ChoiceInputFor(name[..dot], locals, codes, evaluate, depth + 1) is not { } owner+ || RecordFieldType(owner.Type, name[(dot + 1)..]) is not { } type) return null;+ if (!evaluate) return new(type, new ReferenceSyntax(new(name, owner.Value.Span), owner.Value.Span));+ var value = owner.Value is MatchSyntax selection ? ResolveChoices(selection, codes, locals, owner.Type) : owner.Value;+ if (value is ReferenceSyntax alias) return ChoiceInputFor(alias.Name.Text + name[dot..], locals, codes, true, depth + 1);+ var body = value is ObjectSyntax obj ? obj.Body : (value as WithSyntax)?.Body;+ if (body?.Statements.OfType<FieldSyntax>().FirstOrDefault(f => f.Name.Text == name[(dot + 1)..]) is { } field) return new(type, field.Value);+ if (value is WithSyntax derived && FirmamentSyntaxValues.Reference(derived.Target) is { } parent)+ return ChoiceInputFor(parent + name[dot..], locals, codes, true, depth + 1);+ return null;+ }++ private void InitializeChoices(IReadOnlyDictionary<string, TemplateRecordTypeIr> records, List<string> codes, string? bindingSource = null)+ {+ foreach (var diagnostic in Choices.Diagnostics) ChoiceError(diagnostic, codes);+ foreach (var d in Scope(FirmamentSyntaxParser.Parse(bindingSource ?? source).Document.Statements)+ .Where(d => d.Type.Name.Text == "Static" && d.Name is not null))+ {+ var type = FirmamentSyntaxValues.Reference(d.Annotation) ?? (d.Initializer is ObjectSyntax o ? FirmamentSyntaxValues.Reference(o.Type) : null);+ if (type is not null && d.Initializer is not null) choiceInputs[d.Name!.Text] = new(type, d.Initializer);+ if (type is not null && records.TryGetValue(type, out var schema)+ && (d.Body ?? (d.Initializer as ObjectSyntax)?.Body) is { } body)+ foreach (var f in body.Statements.OfType<FieldSyntax>())+ if (schema.Fields.TryGetValue(f.Name.Text, out var fieldType))+ choiceInputs[d.Name!.Text + "." + f.Name.Text] = new(fieldType, f.Value);+ }+ foreach (var (name, input) in choiceInputs.Where(p => Choices.Types.ContainsKey(p.Value.Type)).ToArray())+ _ = ChoiceTag(new ReferenceSyntax(new(name, input.Value.Span), input.Value.Span), input.Type, null, codes, new(StringComparer.Ordinal));+ }++ internal void LocateChoiceErrors(int start, FirmamentV2SourceSpan? location, string note)+ {+ for (var i = start; i < diagnostics.Count; i++)+ if (diagnostics[i].Stage == "Choice binding") diagnostics[i] = diagnostics[i] with+ { SourceSpan = location, IsOriginalSource = location is not null, LocationNote = note };+ }++ private void ChoiceError(FirmamentV2ValidationDiagnostic error, List<string> codes, int sourceOffset = 0)+ {+ codes.Add(error.Code);+ var span = error.SourceSpan is { } located ? located with { Start = located.Start + sourceOffset } : null;+ diagnostics.Add(error with { SourceSpan = span is null ? null : dataBinding?.OriginalSpan(span) ?? span,+ IsOriginalSource = true });+ }++ internal bool IsChoice(string type) => Choices.Types.ContainsKey(type);++ internal ChoiceInput CheckedChoiceInput(string type, ExpressionSyntax value)+ {+ // A decoded argument is a value receipt, not another lookup in the+ // callee's namespace. Qualification prevents a case from capturing a+ // parameter with the same authored spelling.+ if (IsChoice(type) && value is ReferenceSyntax tag && Choices.Types[type].Cases.Contains(tag.Name.Text, StringComparer.Ordinal))+ value = new MemberSyntax(new ReferenceSyntax(new(type, value.Span), value.Span), tag.Name, value.Span);+ return new(type, value);+ }++ internal bool TryChoiceTransfer(string expression, string type, List<string> codes, out string tag)+ {+ var parsed = FirmamentSyntaxParser.ParseExpression(expression);+ tag = "";+ if (parsed.Expression is null) return false;+ var resolved = ResolveChoices(parsed.Expression, codes, expected: type);+ var value = ChoiceTag(resolved, type, null, codes, new(StringComparer.Ordinal));+ if (value is null) return false;+ tag = value;+ return true;+ }++ internal ExpressionSyntax ResolveChoices(ExpressionSyntax expression, List<string> codes,+ IReadOnlyDictionary<string, ChoiceInput>? locals = null, string? expected = null,+ IDictionary<string, string>? selected = null, bool select = true, int sourceOffset = 0, bool finitePatternSelector = false)+ {+ string? TypeOf(ExpressionSyntax e, string? context = null, HashSet<string>? stack = null)+ {+ stack ??= new(StringComparer.Ordinal);+ if (e is ToleranceSyntax tolerance)+ {+ var nominal = TypeOf(tolerance.Nominal, context, stack);+ if (nominal is null) return null;+ if (!FirmamentV2Parser.TryParseLetType(nominal, out var primitive))+ { Fail(FirmamentV2Parser.ToleranceInvalidType, "tol requires a Length or Angle value.", tolerance.ToleranceSpan); return null; }+ return FirmamentV2Parser.BindTolerance(tolerance, primitive, Fail) is null ? null : nominal;+ }+ string? Reference(ExpressionSyntax reference)+ {+ var name = FirmamentSyntaxValues.Reference(reference);+ if (name is not null)+ {+ if (reference is MemberSyntax { Target: ReferenceSyntax qualifiedOwner } qualifiedCase+ && Choices.Types.TryGetValue(qualifiedOwner.Name.Text, out var domain)+ && domain.Cases.Contains(qualifiedCase.Member.Text, StringComparer.Ordinal)) return domain.Name;+ if (ChoiceInputFor(name, locals, codes, false) is { } local)+ {+ if (local.Type.Length > 0) return CanonicalValueType(local.Type);+ if (stack.Count >= 128 || !stack.Add(name)) { Fail(FirmamentV2Parser.ExpressionCycle, $"Compile-time dependency cycle at '{name}'.", reference.Span); return null; }+ var inferred = TypeOf(local.Value, context, stack); stack.Remove(name); return inferred;+ }+ if (values.TryGetValue(name, out var value)) return value.Type.ToString();+ if (definitions.TryGetValue(name, out var definition))+ {+ if (!stack.Add(name)) { Fail(FirmamentV2Parser.ExpressionCycle, $"Compile-time dependency cycle at '{name}'.", reference.Span); return null; }+ var type = FirmamentSyntaxValues.Reference(definition.Annotation) ?? (definition.Initializer is null ? null : TypeOf(definition.Initializer, null, stack));+ stack.Remove(name); return type;+ }+ var dot = name.LastIndexOf('.');+ if (dot > 0 && Choices.Types.TryGetValue(name[..dot], out var qualified) && qualified.Cases.Contains(name[(dot + 1)..], StringComparer.Ordinal)) return qualified.Name;+ if (context is not null && Choices.Types.TryGetValue(context, out var contextual) && contextual.Cases.Contains(name, StringComparer.Ordinal)) return context;+ var candidates = Choices.Types.Values.Where(t => t.Cases.Contains(name, StringComparer.Ordinal)).ToArray();+ if (candidates.Length == 1) return candidates[0].Name;+ }+ if (reference is CallSyntax call)+ {+ if (call.Target is ReferenceSyntax constructor && constructor.Name.Text is "Point2" or "Point3" or "Vector2" or "Vector3")+ {+ var dimensions = constructor.Name.Text.EndsWith('3') ? 3 : 2;+ var types = call.Arguments.Select(a => TypeOf(a.Value, null, stack)).ToArray();+ if (types.Length == dimensions && call.Arguments.All(a => a.Name is null && a.Default is null)+ && types.All(t => constructor.Name.Text.StartsWith("Point", StringComparison.Ordinal) ? t == "Length" : t is "Int" or "Float"))+ return constructor.Name.Text;+ }+ if (call.Target is MemberSyntax member)+ {+ var parent = TypeOf(member.Target, null, stack);+ var axis = call.Arguments.Count == 1 && call.Arguments[0].Name is null && call.Arguments[0].Default is null+ && FirmamentSyntaxValues.Reference(call.Arguments[0].Value) is "+X" or "-X" or "+Y" or "-Y" or "+Z" or "-Z";+ if (parent == "Box3" && member.Member.Text == "Face" && axis) return "Plane";+ if (member.Member.Text == "Axis" && parent is "Point3" or "Box3" && axis) return "Axis";+ if (member.Member.Text == "Inset" && parent == "Plane" && call.Arguments.Count == 1+ && TypeOf(call.Arguments[0].Value, "Length", stack) == "Length") return "Region2";+ }+ }+ if (reference is MemberSyntax field && TypeOf(field.Target, null, stack) is { } owner)+ {+ if (RecordFieldType(owner, field.Member.Text) is { } fieldType) return fieldType;+ if (owner == "Box3" && field.Member.Text == "Center") return "Point3";+ }+ if (reference is IndexSyntax index && TypeOf(index.Target, null, stack) is { } indexed+ && indexed.EndsWith(']') && indexed.IndexOf('[') is var bracket && bracket > 0+ && index.Index is not null && TypeOf(index.Index, "Int", stack) == "Int") return indexed[..bracket];+ Fail(FirmamentV2Parser.ExpressionUnknownSymbol, $"Cannot resolve compile-time value '{name ?? FirmamentSyntaxWriter.Expression(reference)}'.", reference.Span);+ return null;+ }+ if (e is TypedValueSyntax typed)+ {+ var type = FirmamentSyntaxValues.Reference(typed.Type);+ var actual = TypeOf(typed.Value, type, stack);+ if (type is not null && CanonicalValueType(type) == actual) return actual;+ Fail(FirmamentV2Parser.ExpressionTypeMismatch, $"Typed value requires {type}; found {actual}.", typed.Span); return null;+ }+ if (e is WithSyntax derived)+ {+ var type = TypeOf(derived.Target, null, stack);+ if (type is not null && recordTypes.TryGetValue(type, out var schema))+ { CheckRecord(derived.Body, schema, false, stack); return type; }+ Fail(FirmamentV2Parser.ExpressionTypeMismatch, "with requires a bound Record value.", derived.Target.Span); return null;+ }+ if (e is ObjectSyntax obj && FirmamentSyntaxValues.Reference(obj.Type) is { } objectType)+ {+ if (recordTypes.TryGetValue(objectType, out var schema)) CheckRecord(obj.Body, schema, true, stack);+ else if (ConceptIrResolver.SpatialFields.TryGetValue(objectType, out var spatialSchema))+ {+ var seen = new HashSet<string>(StringComparer.Ordinal);+ foreach (var statement in obj.Body.Statements)+ {+ if (statement is not FieldSyntax f)+ { Fail(FirmamentV2Parser.ExpressionUnsupported, $"{objectType} requires named value fields.", statement.Span); continue; }+ var name = spatialSchema.Keys.FirstOrDefault(k => FirmamentSyntaxFields.SameField(k, f.Name.Text));+ if (name is null) { Fail("firmament-v2-canonical-field-unknown", $"Unknown field '{f.Name.Text}' in {objectType}.", f.Name.Span); continue; }+ if (!seen.Add(name)) Fail("firmament-v2-field-duplicate", $"Duplicate field '{f.Name.Text}' in {objectType}.", f.Name.Span);+ var actual = TypeOf(f.Value, null, stack);+ if (actual is not null && !spatialSchema[name].Type.Split('|').Contains(actual, StringComparer.Ordinal))+ Fail(ConceptIrResolver.MatchArmTypeMismatch, $"Field '{f.Name.Text}' in {objectType} requires {spatialSchema[name].Type}; found {actual}.", f.Value.Span);+ }+ foreach (var missing in spatialSchema.Where(p => p.Value.Required && !seen.Contains(p.Key)))+ Fail(FirmamentV2Parser.ExpressionTypeMismatch, $"Missing required field '{missing.Key}' in {objectType}.", obj.Span);+ }+ else Fail(FirmamentV2Parser.ExpressionUnsupported, $"Constructor '{objectType}' is not an admitted compile-time value type.", obj.Span);+ return objectType == "Grid" ? "Point3[]" : objectType;+ }+ if (e is BinarySyntax { Operator: BinaryOperator.Equal or BinaryOperator.NotEqual } comparison)+ {+ var left = TypeOf(comparison.Left, null, stack);+ var right = TypeOf(comparison.Right, left, stack);+ if (left is not null && left == right)+ {+ if (IsChoice(left) || FirmamentV2Parser.TryParseLetType(left, out _)) return "Bool";+ Fail(FirmamentV2Parser.ExpressionUnsupported, $"Equality is not admitted for {left}; select an Enum case or compare scalar fields.", comparison.Span);+ return null;+ }+ Fail(FirmamentV2Parser.ExpressionTypeMismatch, $"Equality requires the same type; found {left ?? "unresolved"} and {right ?? "unresolved"}.", comparison.Span);+ return null;+ }+ var inferred = FirmamentChoiceBinding.Infer(e, Reference, m => Choices.Check(m, TypeOf(m.Scrutinee, null, stack),+ arm => TypeOf(arm, context, new(stack, StringComparer.Ordinal)), d => ChoiceError(d, codes, sourceOffset),+ finitePatternSelector && m.Span == expression.Span ? CanonicalStaticAuthoring.FinitePatternDomain(m) : null));+ if (inferred is null && e is not (ReferenceSyntax or MemberSyntax or CallSyntax or MatchSyntax))+ Fail(FirmamentV2Parser.ExpressionTypeMismatch, "Cannot bind the type of this compile-time expression.", e.Span);+ return inferred;+ }+ void CheckRecord(BlockSyntax body, TemplateRecordTypeIr schema, bool requireAll, HashSet<string> stack)+ {+ var fields = body.Statements.OfType<FieldSyntax>().ToArray();+ foreach (var statement in body.Statements.Where(s => s is not FieldSyntax))+ Fail(FirmamentV2TemplateExpansion.Prefix + "record-field-declaration", $"Record {schema.Name} requires named value fields.", statement.Span);+ foreach (var duplicate in fields.GroupBy(f => f.Name.Text).Where(g => g.Count() > 1))+ Fail(FirmamentV2TemplateExpansion.Prefix + "record-duplicate-field", $"Duplicate field '{duplicate.Key}' in {schema.Name}.", duplicate.Last().Span);+ if (requireAll)+ foreach (var missing in schema.Fields.Keys.Where(k => fields.All(f => f.Name.Text != k)))+ Fail(FirmamentV2TemplateExpansion.Prefix + "record-missing-field", $"Missing field '{missing}' in {schema.Name}.", body.Span);+ foreach (var f in fields)+ if (!schema.Fields.TryGetValue(f.Name.Text, out var fieldType))+ Fail(FirmamentV2TemplateExpansion.Prefix + "record-extra-field", $"Unknown field '{f.Name.Text}' in {schema.Name}.", f.Span);+ else if (TypeOf(f.Value, fieldType, stack) is { } actual && actual != CanonicalValueType(fieldType))+ Fail(ConceptIrResolver.MatchArmTypeMismatch, $"Field '{f.Name.Text}' requires {fieldType}; found {actual}.", f.Value.Span);+ }+ ExpressionSyntax Select(MatchSyntax match)+ {+ var type = TypeOf(match, expected);+ if (type is null || !select) return match;+ var domain = TypeOf(match.Scrutinee);+ var scrutinee = new ChoiceRewriter(Select).Expression(match.Scrutinee);+ var tag = domain is null ? null : ChoiceTag(scrutinee, domain, locals, codes, new(StringComparer.Ordinal));+ if (tag is null) return match;+ var arm = match.Arms.SingleOrDefault(a => FirmamentChoiceBinding.Pattern(a.Pattern, domain!) == tag);+ if (arm is null)+ {+ Fail(ConceptIrResolver.SelectedBranchEvaluationFailure, $"Pattern selector has no arm for '{tag}'. Admitted cases: {string.Join(", ", match.Arms.Select(a => FirmamentSyntaxWriter.Expression(a.Pattern)))}.", match.Scrutinee.Span);+ return match;+ }+ selected?[FirmamentSyntaxValues.Reference(match.Scrutinee) ?? FirmamentSyntaxWriter.Expression(match.Scrutinee)] = tag;+ return new ChoiceRewriter(Select).Expression(arm.Value);+ }+ void Fail(string code, string message, FirmamentV2SourceSpan span) => ChoiceError(new(code, "error", message)+ { SourceSpan = span, Stage = "Choice binding" }, codes, sourceOffset);+ var resolved = new ChoiceRewriter(Select).Expression(expression);+ return select ? BindEnumEqualities(resolved, locals, codes, new(StringComparer.Ordinal)) : resolved;+ }++ private string? ChoiceTag(ExpressionSyntax expression, string type, IReadOnlyDictionary<string, ChoiceInput>? locals,+ List<string> codes, HashSet<string> stack)+ {+ if (expression is MemberSyntax { Target: ReferenceSyntax owner } qualifiedCase && owner.Name.Text == type+ && Choices.Types.TryGetValue(type, out var domain) && domain.Cases.Contains(qualifiedCase.Member.Text, StringComparer.Ordinal)) return qualifiedCase.Member.Text;+ var name = FirmamentSyntaxValues.Reference(expression);+ var input = name is null ? null : ChoiceInputFor(name, locals, codes, true);+ if (input is not null)+ {+ if (input.Type.Length > 0 && CanonicalValueType(input.Type) != type) { Fail(FirmamentV2Parser.ExpressionTypeMismatch, $"Expected {type}; '{name}' has nominal type {input.Type}."); return null; }+ if (activeChoices.Count >= 128 || activeChoices.Contains(name!, StringComparer.Ordinal))+ { Fail(FirmamentV2Parser.ExpressionCycle, "Compile-time choice dependency cycle: " + string.Join(" -> ", activeChoices.Append(name!)) + "."); return null; }+ activeChoices.Add(name!);+ try+ {+ var before = diagnostics.Count;+ var value = ResolveChoices(input.Value, codes, locals, type);+ return diagnostics.Count > before ? null : ChoiceTag(value, type, locals, codes, stack);+ }+ finally { activeChoices.Remove(name!); }+ }+ if (type is "Bool" or "Int")+ {+ expression = BindEnumEqualities(expression, locals, codes, stack);+ var bindings = values.Values.ToDictionary(v => v.Name, v => v, StringComparer.Ordinal);+ var substitution = new Dictionary<string, ExpressionSyntax>(StringComparer.Ordinal);+ Expand(expression, new(StringComparer.Ordinal));+ var normalized = new FirmamentSyntaxSubstitution(substitution).Expression(expression);+ var text = FirmamentSyntaxWriter.Expression(normalized);+ var parsed = FirmamentSyntaxParser.ParseExpression(text).Expression;+ if (parsed is null) return null;+ var bound = FirmamentV2Parser.BindCompileTimeScalars([Scalar("__choiceCondition", type, parsed, parsed.Span)], text, "inline", codes, bindings.Values.ToArray());+ foreach (var d in bound.Diagnostics) ChoiceError(d with { SourceSpan = expression.Span }, codes);+ var result = bound.Values.FirstOrDefault(v => v.Name == "__choiceCondition")?.Value;+ return result?.Value is bool b ? b ? "true" : "false" : result?.NumericValue?.ToString("0", System.Globalization.CultureInfo.InvariantCulture);+ void Expand(ExpressionSyntax e, HashSet<string> visiting)+ {+ foreach (var r in FirmamentSyntaxTraversal.Expressions(e).Where(r => r is ReferenceSyntax or MemberSyntax))+ {+ var n = FirmamentSyntaxValues.Reference(r);+ if (n is null || !visiting.Add(n) || visiting.Count > 128) continue;+ var value = locals?.GetValueOrDefault(n)?.Value ?? choiceInputs.GetValueOrDefault(n)?.Value ?? definitions.GetValueOrDefault(n)?.Initializer;+ if (value is null) continue;+ Expand(value, visiting);+ substitution[n] = new FirmamentSyntaxSubstitution(substitution).Expression(value);+ }+ }++ }+ var caseName = FirmamentChoiceBinding.Pattern(expression, type);+ if (caseName is not null && Choices.Types.TryGetValue(type, out var choice) && choice.Cases.Contains(caseName, StringComparer.Ordinal)) return caseName;+ Fail(ConceptIrResolver.UnknownEnumVariant, $"'{FirmamentSyntaxWriter.Expression(expression)}' is not a case of {type}.");+ return null;+ void Fail(string code, string message) => ChoiceError(new(code, "error", message) { SourceSpan = expression.Span, Stage = "Choice binding" }, codes);+ }++ private ExpressionSyntax BindEnumEqualities(ExpressionSyntax expression, IReadOnlyDictionary<string, ChoiceInput>? locals,+ List<string> codes, HashSet<string> stack)+ {+ return new EnumEqualityProjection(compare =>+ {+ var domain = KnownType(compare.Left) ?? KnownType(compare.Right);+ if (domain is null || !IsChoice(domain)) return null;+ var left = ChoiceTag(compare.Left, domain, locals, codes, stack);+ var right = ChoiceTag(compare.Right, domain, locals, codes, stack);+ if (left is null || right is null) return null;+ var result = compare.Operator == BinaryOperator.Equal ? left == right : left != right;+ return new LiteralSyntax(LiteralKind.Boolean, result ? "true" : "false", compare.Span);+ }).Expression(expression);++ string? KnownType(ExpressionSyntax e)+ {+ var n = FirmamentSyntaxValues.Reference(e);+ var t = n is null ? null : locals?.GetValueOrDefault(n)?.Type ?? choiceInputs.GetValueOrDefault(n)?.Type;+ if (t is not null) return CanonicalValueType(t);+ return e is MemberSyntax { Target: ReferenceSyntax owner } && IsChoice(owner.Name.Text) ? owner.Name.Text : null;+ }+ }++ private sealed class ChoiceRewriter(Func<MatchSyntax, ExpressionSyntax> select) : FirmamentSyntaxRewriter+ {+ internal override ExpressionSyntax Expression(ExpressionSyntax e) => e is MatchSyntax m ? select(m) : base.Expression(e);+ }++ private sealed class EnumEqualityProjection(Func<BinarySyntax, ExpressionSyntax?> bind) : FirmamentSyntaxRewriter+ {+ internal override ExpressionSyntax Expression(ExpressionSyntax expression) => expression is BinarySyntax { Operator: BinaryOperator.Equal or BinaryOperator.NotEqual } binary+ ? bind(binary) ?? base.Expression(expression) : base.Expression(expression);+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.csindex de1093a8..e6cc8068 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs@@ -9,7 +9,7 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;/// nominal strings. The mechanical binder consumes their nominal AST and PMI consumes their IR./// This is not an evaluator: all scalar semantics belong to the existing typed dependency binder./// </summary>-internal sealed class FirmamentCompileTimeValues(string source)+internal sealed partial class FirmamentCompileTimeValues(string source){private readonly Dictionary<string, FirmamentV2BoundLet> values = new(StringComparer.Ordinal);private readonly HashSet<string> identifiers = FirmamentLanguageAnalysisService.Lex(source)@@ -69,13 +69,23 @@ internal sealed class FirmamentCompileTimeValues(string source)internal void BindExpandedScalars(string expanded, List<string> codes){+ var expandedChoices = new FirmamentChoiceBinding(expanded);+ choices = new(Choices.Types.Values.Concat(expandedChoices.Types.Values).GroupBy(t => t.Name).Select(g => g.Last()));+ var choiceErrorStart = diagnostics.Count;+ foreach (var error in expandedChoices.Diagnostics) ChoiceError(error, codes);+ recordTypes = recordTypes.Concat(FirmamentV2TemplateExpansion.ParseRecordTypes(expanded, codes, templateLocals: true))+ .GroupBy(p => p.Key, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Last().Value, StringComparer.Ordinal);+ InitializeChoices(recordTypes, codes, expanded);+ LocateChoiceErrors(choiceErrorStart, null, "Binding checked specialized Static values; an exact original-source span is unavailable.");var declarations = Scope(FirmamentSyntaxParser.Parse(expanded).Document.Statements).Where(d => d.Type.Name.Text == "Static" && d.Name is not null && d.Initializer is not null&& !definitions.ContainsKey(d.Name.Text)&& d.Body is null && d.Initializer is not (ObjectSyntax or WithSyntax or IndexSyntax)&& (d.Annotation is null || IsScalar(FirmamentSyntaxValues.Reference(d.Annotation) ?? ""))).ToArray();if (declarations.Length == 0) return;- var bound = FirmamentV2Parser.BindCompileTimeScalars(declarations, expanded, "inline", codes, values.Values.ToArray());+ var projected = declarations.Select(d => d with { Initializer = ResolveChoices(d.Initializer!, codes,+ expected: FirmamentSyntaxValues.Reference(d.Annotation)) }).ToArray();+ var bound = FirmamentV2Parser.BindCompileTimeScalars(projected, expanded, "inline", codes, values.Values.ToArray());foreach (var diagnostic in bound.Diagnostics){var original = originalScopes.GetValueOrDefault("Static " + diagnostic.Target);@@ -92,6 +102,7 @@ internal sealed class FirmamentCompileTimeValues(string source)internal void Initialize(IReadOnlyDictionary<string, TemplateRecordTypeIr> records, List<string> codes){+ recordTypes = FirmamentV2TemplateExpansion.ParseRecordTypes(source, codes, templateLocals: true);var syntax = FirmamentSyntaxParser.Parse(source);var declarations = Scope(syntax.Document.Statements).ToArray();foreach (var d in declarations.Where(d => d.Type.Name.Text == "Static" && d.Name is not null))@@ -150,6 +161,7 @@ internal sealed class FirmamentCompileTimeValues(string source)}}foreach (var d in statics) Record(d);+ InitializeChoices(recordTypes, codes);// A legacy collection reader may retain only a literal prefix. Every tol// in a Static value must belong to a checked scalar initializer before// that reader can erase the containing declaration.@@ -166,7 +178,9 @@ internal sealed class FirmamentCompileTimeValues(string source){ SourceSpan = tolerance.ToleranceSpan, IsOriginalSource = true, Stage = "Binding" });}if (definitions.Count == 0) return;- var bound = FirmamentV2Parser.BindCompileTimeScalars(definitions.Select(p => p.Value with { Name = new(p.Key, p.Value.Name!.Span) }).ToArray(), source, "inline", codes);+ var bound = FirmamentV2Parser.BindCompileTimeScalars(definitions.Select(p => p.Value with+ { Name = new(p.Key, p.Value.Name!.Span), Initializer = ResolveChoices(p.Value.Initializer!, codes,+ expected: FirmamentSyntaxValues.Reference(p.Value.Annotation)) }).ToArray(), source, "inline", codes);diagnostics.AddRange(bound.Diagnostics.Select(d => d with { IsOriginalSource = true,SourceSpan = d.SourceSpan is { } span ? dataBinding?.OriginalSpan(span) ?? span : null }));foreach (var value in bound.Values)@@ -205,7 +219,8 @@ internal sealed class FirmamentCompileTimeValues(string source)if (parsed.Expression is null || parsed.Diagnostics.Any(d => d.Severity is "error" or "fatal")) return false;var name = FreshName();var localCodes = new List<string>();- var bound = FirmamentV2Parser.BindCompileTimeScalars([Scalar(name, type, parsed.Expression, parsed.Expression.Span)],+ var resolved = ResolveChoices(parsed.Expression, codes, expected: type);+ var bound = FirmamentV2Parser.BindCompileTimeScalars([Scalar(name, type, resolved, parsed.Expression.Span)],expression, "inline", localCodes, values.Values.ToArray());codes.AddRange(localCodes);diagnostics.AddRange(bound.Diagnostics.Select(d => d with { SourceSpan = originalConsumer ? span : null, IsOriginalSource = originalConsumer,@@ -248,6 +263,7 @@ internal sealed class FirmamentCompileTimeValues(string source)internal string Field(string record, string field, string expression, string type, FirmamentV2SourceSpan span, List<string> codes){+ if (IsChoice(type)) return TryChoiceTransfer(expression, type, codes, out var tag) ? tag : expression;if (!IsScalar(type)) return expression;if (values.TryGetValue(record + "." + field, out var value) && value.Tolerance is null && IsLiteral(expression)) return expression;return TryTransfer(values.ContainsKey(record + "." + field) ? record + "." + field : expression,@@ -264,8 +280,12 @@ internal sealed class FirmamentCompileTimeValues(string source)internal void SetRecords(IReadOnlyDictionary<string, TemplateRecordTypeIr> types, IReadOnlyDictionary<string, TemplateStaticRecordIr> records){- recordTypes = types;+ recordTypes = recordTypes.Concat(types).GroupBy(p => p.Key, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Last().Value, StringComparer.Ordinal);foreach (var record in records) recordValues[record.Key] = record.Value;+ foreach (var record in records.Values)+ foreach (var field in FirmamentV2TemplateExpansion.FlattenRecordFields(record, types, recordValues, []))+ if (RecordFieldType(record.TypeName, field.Key) is { } type && IsChoice(type))+ choiceInputs[record.Name + "." + field.Key] = new(type, FirmamentSyntaxParser.ParseExpression(field.Value).Expression!);// Table rows and aliases may not have authored scalar field declarations.// Admit their leaves through the same typed graph used by literal Records.foreach (var record in records.Values)@@ -301,7 +321,7 @@ internal sealed class FirmamentCompileTimeValues(string source): (dataBinding?.DisplayName(name[..dot]) ?? name[..dot]) + name[dot..];}- private string? RecordFieldType(string type, string path)+ internal string? RecordFieldType(string type, string path){string? fieldType = null;foreach (var part in path.Split('.'))diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.csindex 0a222f74..5486edd5 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs@@ -20,8 +20,8 @@ public sealed record FirmamentLanguageFormat(string Document, string Revision, spublic static class FirmamentLanguageAnalysisService{internal sealed record Lexeme(int Start, int Length, string Text, string Shape, string? Error = null);- private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "With", "with", "Expose", "Include", "Subassembly", "Assembly", "Part", "Template", "Function", "Record", "Pattern", "Over", "Using", "As", "as", "Output", "tol", "Concept", "Require", "Motion", "Track", "Keyframes", "Keyframe"];- private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Function", "Pattern", "Section", "SectionChain", "FrameTransform", "Points", "Path", "Semantic", "Enum", "Concept", "Motion", "Track", "Keyframes", "Keyframe"];+ private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "Enum", "Options", "match", "Match", "With", "with", "Expose", "Include", "Subassembly", "Assembly", "Part", "Template", "Function", "Record", "Pattern", "Over", "Using", "As", "as", "Output", "tol", "Concept", "Require", "Motion", "Track", "Keyframes", "Keyframe"];+ private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Function", "Pattern", "Section", "SectionChain", "FrameTransform", "Points", "Path", "Semantic", "Enum", "Options", "Concept", "Motion", "Track", "Keyframes", "Keyframe"];private static readonly HashSet<string> Types = ["Length", "Angle", "Time", "Float", "Int", "Bool", "Box3", "Plane", "Point2", "Point3"];private static readonly HashSet<string> Choices = FirmamentSemanticSchemas.All.SelectMany(construct => construct.Fields).SelectMany(field => field.Choices).ToHashSet(StringComparer.Ordinal);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.csindex a1314647..9285b8d9 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs@@ -26,6 +26,8 @@ public static class FirmamentSourceSpellingArgumentNullException.ThrowIfNull(source);var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(t => t.Shape != "comment").ToArray();var syntax = FirmamentSyntaxParser.Parse(source).Document;+ var matchPositions = FirmamentSyntaxTraversal.Expressions(syntax).OfType<MatchSyntax>().Select(m => m.Span.Start).ToHashSet();+ var authoredNames = FirmamentSyntaxTraversal.Declarations(syntax).Where(d => d.Name is not null).Select(d => d.Name!.Span.Start).ToHashSet();var endpointPositions = new Dictionary<int, string>();foreach (var trace in FirmamentSyntaxTraversal.Expressions(syntax).OfType<TraceSyntax>()){@@ -97,7 +99,14 @@ public static class FirmamentSourceSpellingcontinue;}if (t.Text == "}") { if (scopes.Count > 0) scopes.Pop(); continue; }- if (t.Shape != "identifier" || scopes.Any(s => s.AuthoredData)) continue;+ if (t.Shape != "identifier") continue;+ if (matchPositions.Contains(t.Start))+ {+ var keyword = preferred ? "match" : "Match";+ for (var c = 0; c < t.Length; c++) output[t.Start + c] = keyword[c];+ continue;+ }+ if (scopes.Any(s => s.AuthoredData)) continue;var fieldPosition = i + 1 < tokens.Length && tokens[i + 1].Text == ":";string? canonical = null;if (fieldPosition && symmetryFields.TryGetValue(t.Start, out var symmetryField)) canonical = symmetryField;@@ -111,6 +120,7 @@ public static class FirmamentSourceSpellingcanonical = Links.FirstOrDefault(pair => (t.Text == pair.Key || t.Text == pair.Value) &&(pair.Key == "As" ? aliasPositions.Contains(t.Start) : IsLink(tokens, i, pair.Key))).Key;}+ if (authoredNames.Contains(t.Start)) canonical = null;if (canonical is null) continue;var spelling = preferred ? Links.GetValueOrDefault(canonical) ?? PreferredField(canonical) : canonical;// All supported spelling aliases retain spans (important for diagnostics).@@ -210,6 +220,7 @@ public static class FirmamentSourceSpelling}}// Bounded owner vocabularies not yet projected through generated schema.+ foreach (var owner in ConceptIrResolver.SpatialFields) Add(owner.Key, string.Join(' ', owner.Value.Keys));Add("Model", "Units Material");Add("Scene", "Units");Add("Garment", "Fabric MeshSize");diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.csindex 93c709c3..25fa2814 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs@@ -84,7 +84,9 @@ public static class FirmamentTemplateSourceCompiler{ArgumentNullException.ThrowIfNull(source);var collected = new List<string>();- var expansion = FirmamentV2TemplateExpansion.Expand(source, collected);+ var values = new FirmamentCompileTimeValues(source);+ var expansion = FirmamentV2TemplateExpansion.Expand(source, collected, values);+ collected.AddRange(values.Diagnostics.Select(d => d.Code + ": " + d.Message));diagnostics = collected.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();return expansion is null ? null : new(expansion.Source, expansion.Instantiations);}@@ -136,7 +138,7 @@ public static class FirmamentTemplateHostBridge.Select(record => new FirmamentTemplateRecordMetadata(dataBinding.DisplayName(record.Name),record.Fields.Select(field => new FirmamentTemplateRecordFieldMetadata(field.Key, dataBinding.DisplayName(field.Value))).ToArray())).ToArray();- var enums = FirmamentV2TemplateExpansion.InspectEnums(moduleSource)+ var enums = FirmamentV2TemplateExpansion.InspectEnums(moduleSource, collected).Where(item => Visible("type", item.Key)).Select(item => new FirmamentTemplateEnumMetadata(dataBinding.DisplayName(item.Key), item.Value.ToArray())).ToArray();@@ -175,8 +177,10 @@ public static class FirmamentTemplateHostBridgediagnostics = ["firmament-host-argument-duplicate"];return null;}+ var values = new FirmamentCompileTimeValues(moduleSource);var expansion = FirmamentV2TemplateExpansion.ExpandHostInvocation(- moduleSource, templateName, instanceName, hostArguments, collected);+ moduleSource, templateName, instanceName, hostArguments, collected, values);+ collected.AddRange(values.Diagnostics.Select(d => d.Code + ": " + d.Message));diagnostics = collected.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();if (expansion is null) return null;var instance = expansion.Instantiations.First(item =>diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex d70cd5a0..b97a5cf7 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -30,6 +30,7 @@ public sealed record FirmamentV2LiteralExpression(FirmamentV2LiteralValue Value)public sealed record FirmamentV2DottedReferenceExpression(string RecordName, string FieldName, string Source) : FirmamentV2ValueExpression;public sealed record FirmamentV2IdentifierReferenceExpression(string Name, string Source) : FirmamentV2ValueExpression;public sealed record FirmamentV2BinaryExpression(FirmamentV2ValueExpression Left, string Operator, FirmamentV2ValueExpression Right, string Source) : FirmamentV2ValueExpression;+public sealed record FirmamentV2UnaryExpression(string Operator, FirmamentV2ValueExpression Operand, string Source) : FirmamentV2ValueExpression;public sealed record FirmamentV2LetDeclaration(string Name, FirmamentV2PrimitiveType DeclaredType, FirmamentV2ValueExpression ValueExpression, FirmamentV2SourceSpan SourceSpan, FirmamentV2Tolerance? Tolerance = null){public FirmamentV2LiteralValue LiteralValue => ValueExpression is FirmamentV2LiteralExpression literal ? literal.Value : throw new InvalidOperationException("Let value is not a literal.");diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.csindex afb456d4..6936e116 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs@@ -132,6 +132,17 @@ internal static class FirmamentV2FeatureExpansionforeach (var definition in definitions.Values){var returned = definition.Return.Value;+ if (scalars is not null)+ {+ var inputs = definition.Syntax.Parameters.Where(p => p.Name is not null).ToDictionary(p => p.Name!.Text,+ p => new FirmamentCompileTimeValues.ChoiceInput(TypeName(p.Value), new ReferenceSyntax(p.Name!, p.Name!.Span)), StringComparer.Ordinal);+ foreach (var local in definition.Locals) inputs[local.Name!.Text] = new(TypeName(local.Annotation!), local.Initializer!);+ var before = scalars.Diagnostics.Count;+ foreach (var value in definition.Syntax.Parameters.Select(p => p.Default).OfType<ExpressionSyntax>()+ .Concat(definition.Locals.Select(l => l.Initializer!)).Append(returned))+ _ = scalars.ResolveChoices(value, diagnostics, inputs, select: false);+ scalars.LocateChoiceErrors(before, OriginalDefinition(definition.Syntax), "Location identifies the original enclosing Feature definition; its body was checked before expansion.");+ }if (returned is ObjectSyntax { Name: not null })Error(UnsupportedBody + ":" + definition.Syntax.Name!.Text + ":named-return", "A return constructor is unnamed. Name its consuming invocation with Feature name = Recipe(arguments).", returned.Span, definition.Syntax);else if (returned is CallSyntax { Target: ReferenceSyntax call })@@ -188,6 +199,15 @@ internal static class FirmamentV2FeatureExpansionbool BindValue(ExpressionSyntax expression, string type, string name, FirmamentV2SourceSpan span, out ExpressionSyntax bound){bound = expression; var text = FirmamentSyntaxWriter.Expression(expression);+ if (scalars?.IsChoice(type) == true)+ {+ var before = scalars.Diagnostics.Count;+ var choiceTransferred = scalars.TryChoiceTransfer(text, type, diagnostics, out var tag);+ scalars.LocateChoiceErrors(before, OriginalDefinition(definition.Syntax),+ "Location identifies the original enclosing Feature definition; the argument was decoded at its invocation.");+ if (!choiceTransferred) return false;+ bound = ParseValue(tag); return true;+ }if (scalars?.IsRecordType(type) == true){if (!scalars.TryRecordTransfer(text, type, $"Feature {definition.Syntax.Name!.Text}.{name}", call.Span, diagnostics, out var fields))@@ -219,7 +239,12 @@ internal static class FirmamentV2FeatureExpansionif (p.Default is null) { Error(ArgumentCount + $":{definition.Syntax.Name!.Text}:missing-{name}", $"Missing required Feature argument '{name}'.", call.Span, definition.Syntax); resolving.Remove(name); return; }foreach (var dependency in FirmamentSyntaxTraversal.Expressions(p.Default).OfType<ReferenceSyntax>())if (definition.Syntax.Parameters.FirstOrDefault(x => x.Name!.Text == dependency.Name.Text) is { } other) BindParameter(other);- value = new FirmamentSyntaxSubstitution(environment).Expression(p.Default);+ var defaults = definition.Syntax.Parameters.Where(p => p.Name is not null && environment.ContainsKey(p.Name.Text))+ .ToDictionary(p => p.Name!.Text, p => scalars?.CheckedChoiceInput(TypeName(p.Value), environment[p.Name!.Text]) ?? new(TypeName(p.Value), environment[p.Name!.Text]), StringComparer.Ordinal);+ var before = scalars?.Diagnostics.Count ?? 0;+ var resolved = scalars?.ResolveChoices(p.Default, diagnostics, defaults, expected: TypeName(p.Value)) ?? p.Default;+ scalars?.LocateChoiceErrors(before, OriginalDefinition(definition.Syntax), "Location identifies the original enclosing Feature default.");+ value = new FirmamentSyntaxSubstitution(environment).Expression(resolved);}var type = TypeName(p.Value);if (type is "Point2" or "Point3") value = ResolvePoint(value!, explicitArgument ? callScope : definition.Scope);@@ -227,10 +252,29 @@ internal static class FirmamentV2FeatureExpansionresolving.Remove(name);}foreach (var p in definition.Syntax.Parameters) BindParameter(p);+ var choiceInputs = new Dictionary<string, FirmamentCompileTimeValues.ChoiceInput>(StringComparer.Ordinal);+ foreach (var parameter in definition.Syntax.Parameters)+ {+ if (environment.TryGetValue(parameter.Name!.Text, out var input)) choiceInputs[parameter.Name.Text] = scalars?.CheckedChoiceInput(TypeName(parameter.Value), input) ?? new(TypeName(parameter.Value), input);+ if (scalars?.IsRecordType(TypeName(parameter.Value)) == true)+ foreach (var field in environment.Where(p => p.Key.StartsWith(parameter.Name!.Text + ".", StringComparison.Ordinal)))+ if (scalars.RecordFieldType(TypeName(parameter.Value), field.Key[(parameter.Name!.Text.Length + 1)..]) is { } type)+ choiceInputs[field.Key] = scalars.CheckedChoiceInput(type, field.Value);+ }+ ExpressionSyntax ResolveChoices(ExpressionSyntax expression)+ {+ if (scalars is null) return expression;+ var before = scalars.Diagnostics.Count;+ var resolved = scalars.ResolveChoices(expression, diagnostics, choiceInputs);+ scalars.LocateChoiceErrors(before, OriginalDefinition(definition.Syntax), "Location identifies the original enclosing Feature definition; parameter values were checked at its invocation.");+ return resolved;+ }foreach (var local in definition.Locals){- var expression = new FirmamentSyntaxSubstitution(environment).Expression(local.Initializer!); var type = TypeName(local.Annotation!);- if (BindValue(expression, type, local.Name!.Text, local.Span, out var bound)) environment[local.Name.Text] = bound;+ var expression = new FirmamentSyntaxSubstitution(environment).Expression(ResolveChoices(local.Initializer!));+ var type = TypeName(local.Annotation!);+ if (BindValue(expression, type, local.Name!.Text, local.Span, out var bound))+ { environment[local.Name.Text] = bound; choiceInputs[local.Name.Text] = scalars?.CheckedChoiceInput(type, bound) ?? new(type, bound); }else Error(LocalType + $":{definition.Syntax.Name!.Text}:{local.Name.Text}:expected-{type}", $"Feature local '{local.Name.Text}' requires {type}.", local.Span, definition.Syntax);}if (Failed()) return [];@@ -238,7 +282,8 @@ internal static class FirmamentV2FeatureExpansion: stack.Count == 0 ? resultName : resultName + "__Call" + stack.Count.ToString(CultureInfo.InvariantCulture);var renames = definition.Construction.ToDictionary(d => d.Name!.Text, d => prefix + "__" + d.Name!.Text, StringComparer.Ordinal);var transform = new FirmamentSyntaxSubstitution(environment, renames);- var output = definition.Construction.Select(transform.Statement).ToList(); var returned = transform.Expression(definition.Return.Value);+ var output = definition.Construction.Select(transform.Statement).ToList();+ var returned = transform.Expression(ResolveChoices(definition.Return.Value));if (returned is CallSyntax { Target: ReferenceSyntax nestedName } nestedCall&& definition.Scope.Resolve("Feature", nestedName.Name.Text) is { } nestedSyntax && definitions.TryGetValue(nestedSyntax, out var nested)){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.csindex b3f65b02..0f686bfb 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs@@ -48,10 +48,10 @@ public static partial class FirmamentV2Parser{if (syntax.Statements.Concat(model.Body.Statements).OfType<DeclarationSyntax>().Any(d => d.Type.Name.Text == "Static"))return CanonicalFailure(diagnostics, "firmament-v2-static-scalar-consumer-unsupported: Concept-valued material construction requires its existing typed Template inputs.");- return ParseConceptModelingDocument(source, diagnostics, templateInstantiations);+ return ParseConceptModelingDocument(source, diagnostics, templateInstantiations, compileTime);}var outerStatements = syntax.Statements.Where(s => !ReferenceEquals(s, model)).ToArray();- var staticValues = BindStaticValues(syntax, model, source, diagnostics, compileTime?.MaterialInputs(source));+ var staticValues = BindStaticValues(syntax, model, source, diagnostics, compileTime?.MaterialInputs(source), compileTime);model = staticValues.Model;BindMechanicalScope(outerStatements.Where(s => s is not DeclarationSyntax { Type.Name.Text: "Static" }).ToArray(), diagnostics);BindMechanicalScope(model.Body!.Statements.Where(s => s is not DeclarationSyntax { Type.Name.Text: "Static" }).ToArray(), diagnostics);@@ -81,7 +81,7 @@ public static partial class FirmamentV2Parser{// The construction adapter consumes serialized bound AST fields. An// unused Static is data, never a reason to reject a material owner.- var construction = BindMechanicalConstruction(source, model, diagnostics, templateInstantiations);+ var construction = BindMechanicalConstruction(source, model, diagnostics, templateInstantiations, compileTime);return construction.Document is null ? construction : construction with{Document = construction.Document with { Lets = staticValues.Declarations, BoundLets = staticValues.Values },diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex c5a4b812..74545196 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -596,7 +596,7 @@ public static partial class FirmamentV2Parserif (syntax.Document.Statements.OfType<DeclarationSyntax>().Any(d => d.Type.Name.Text is "Model" or "Struct" or "Concept"|| d.Modifiers.Any(m => m.Name.Text == "Concept")))return Recognized(WithFeatureMetadata(- AttachVolumeAssertionsAndSymbols(WithPolygonMetadata(ParseConceptModelingDocument(RemoveCanonicalVolumeAssertions(source), diagnostics, templateExpansion.Instantiations), polygonExpansion), source, canonicalStaticExpansion.Document, diagnostics),+ AttachVolumeAssertionsAndSymbols(WithPolygonMetadata(ParseConceptModelingDocument(RemoveCanonicalVolumeAssertions(source), diagnostics, templateExpansion.Instantiations, compileTime), polygonExpansion), source, canonicalStaticExpansion.Document, diagnostics),featureExpansion, compileTime)) with { ParserRoute = "ConceptModeling" };if (ContainsRawBackendId(source)) diagnostics.Add(RawBackendIdReferenceForbidden);@@ -730,7 +730,7 @@ public static partial class FirmamentV2Parser|| tokens[0].Text == "{" && tokens[1].Shape == "string")) return false;for (var index = 0; index < tokens.Length; index++)if (tokens[index].Shape == "identifier"- && tokens[index].Text is "Model" or "model" or "Struct" or "Assembly" or "Scene" or "Concept" or "Interface" or "Template" or "template" or "Pattern" or "Profile" or "Panel"+ && tokens[index].Text is "Model" or "model" or "Struct" or "Assembly" or "Scene" or "Concept" or "Interface" or "Template" or "template" or "Pattern" or "Profile" or "Panel" or "Enum" or "Options"&& (index + 1 == tokens.Length || tokens[index + 1].Text != ":")) return true;return false;}@@ -1007,8 +1007,16 @@ public static partial class FirmamentV2ParserFirmamentV2IdentifierReferenceExpression r => EvalId(r),FirmamentV2DottedReferenceExpression r => EvalDotted(r),FirmamentV2BinaryExpression b => EvalBinary(b),+ FirmamentV2UnaryExpression u => EvalNot(u),_ => null};+ private FirmamentV2BoundExpression? EvalNot(FirmamentV2UnaryExpression unary)+ {+ var operand = Eval(unary.Operand);+ if (operand is null) return null;+ if (unary.Operator != "!" || operand.InferredType != FirmamentV2PrimitiveType.Bool) { _diagnostics.Add(ExpressionInvalidOperator); return null; }+ return operand with { Value = new(FirmamentV2PrimitiveType.Bool, !(bool)operand.Value.Value), AliasTolerance = null };+ }private FirmamentV2BoundExpression? EvalId(FirmamentV2IdentifierReferenceExpression r){if (_records.ContainsKey(r.Name)) { _diagnostics.Add(ExpressionRecordUsedAsValue); _diagnostics.Add(LetReferenceRecordUsedAsValue); return null; }@@ -1030,13 +1038,25 @@ public static partial class FirmamentV2Parserif (type is null) { _diagnostics.Add(ExpressionInvalidOperator); return null; }if (b.Operator == "/" && IsZero(r.Value)) { _diagnostics.Add(ExpressionDivisionByZero); return null; }var val = Compute(type.Value, l.Value, b.Operator, r.Value, b.Source);- return new(type.Value, val, new HashSet<string>(l.Dependencies.Concat(r.Dependencies), StringComparer.Ordinal), new(0, b.Source.Length), null, l.AliasTolerance is not null || r.AliasTolerance is not null || l.UsesTolerancedValueInArithmetic || r.UsesTolerancedValueInArithmetic);+ var arithmetic = b.Operator is "+" or "-" or "*" or "/";+ return new(type.Value, val, new HashSet<string>(l.Dependencies.Concat(r.Dependencies), StringComparer.Ordinal), new(0, b.Source.Length), null,+ arithmetic && (l.AliasTolerance is not null || r.AliasTolerance is not null || l.UsesTolerancedValueInArithmetic || r.UsesTolerancedValueInArithmetic));}private static bool IsZero(FirmamentV2LiteralValue v) => v.NumericValue is double d && d == 0d;internal static FirmamentV2PrimitiveType? ResultType(FirmamentV2PrimitiveType a, string op, FirmamentV2PrimitiveType b) =>- FirmamentNumericEvaluation.ResultType(a, op, b);+ op is "&&" or "||" ? a == FirmamentV2PrimitiveType.Bool && b == a ? FirmamentV2PrimitiveType.Bool : null+ : op is "==" or "!=" ? a == b ? FirmamentV2PrimitiveType.Bool : null+ : op is "<" or "<=" or ">" or ">=" ? a == b && a is FirmamentV2PrimitiveType.Int or FirmamentV2PrimitiveType.Float or FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle or FirmamentV2PrimitiveType.Time ? FirmamentV2PrimitiveType.Bool : null+ : FirmamentNumericEvaluation.ResultType(a, op, b);private static FirmamentV2LiteralValue Compute(FirmamentV2PrimitiveType type, FirmamentV2LiteralValue l, string op, FirmamentV2LiteralValue r, string raw){+ if (type == FirmamentV2PrimitiveType.Bool)+ {+ var order = l.NumericValue is { } ln && r.NumericValue is { } rn ? ln.CompareTo(rn) : Equals(l.Value, r.Value) ? 0 : 1;+ var result = op switch { "&&" => (bool)l.Value && (bool)r.Value, "||" => (bool)l.Value || (bool)r.Value,+ "==" => order == 0, "!=" => order != 0, "<" => order < 0, "<=" => order <= 0, ">" => order > 0, _ => order >= 0 };+ return new(type, result, Raw: raw);+ }var a = Convert.ToDouble(l.NumericValue, CultureInfo.InvariantCulture); var b = Convert.ToDouble(r.NumericValue, CultureInfo.InvariantCulture);var operation = op switch { "+" => BinaryOperator.Add, "-" => BinaryOperator.Subtract, "*" => BinaryOperator.Multiply, "/" => BinaryOperator.Divide, _ => throw new InvalidOperationException("Unbound arithmetic operator.") };if (!FirmamentNumericEvaluation.TryBinary(new(a, l.Unit ?? ""), operation, new(b, r.Unit ?? ""), out var computed))@@ -1131,7 +1151,7 @@ public static partial class FirmamentV2Parser/// production profile and section-stack readers remain semantic adapters; this/// method owns the root, units, disposition, and normalized declaration list./// </summary>- private static FirmamentV2ParseResult BindMechanicalConstruction(string source, DeclarationSyntax model, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations)+ private static FirmamentV2ParseResult BindMechanicalConstruction(string source, DeclarationSyntax model, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations, FirmamentCompileTimeValues? compileTime = null){source = MechanicalConstructionSource(source, model, diagnostics);if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);@@ -1251,7 +1271,7 @@ public static partial class FirmamentV2Parserreturn FirmamentV2ParseResult.Success(document, diagnostics.Distinct(StringComparer.Ordinal).ToArray()) with { BoundProfile = resolved, ExtrusionHeight = profile.Height, BoundSource = adapterSource };}- var concept = ParseConceptModelingDocument(declarations.Any(d => d.Type.Name.Text == "Struct" && !d.Modifiers.Any(m => m.Name.Text == "Concept")) ? adapterSource : source, diagnostics, templateInstantiations);+ var concept = ParseConceptModelingDocument(declarations.Any(d => d.Type.Name.Text == "Struct" && !d.Modifiers.Any(m => m.Name.Text == "Concept")) ? adapterSource : source, diagnostics, templateInstantiations, compileTime);if (!concept.IsSuccess || concept.Document is null) return concept;var conceptSolids = concept.Document.Solids.ToDictionary(solid => solid.Name, StringComparer.Ordinal);var (conceptPmi, conceptPmiBlock, conceptBoundPmi) = ParsePmi(@@ -1842,14 +1862,16 @@ public static partial class FirmamentV2Parserreturn FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray());}- private static FirmamentV2ParseResult ParseConceptModelingDocument(string source, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations = null)+ private static FirmamentV2ParseResult ParseConceptModelingDocument(string source, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations = null, FirmamentCompileTimeValues? scalars = null){- var resolution = ConceptIrResolver.Resolve(source, diagnostics);+ var before = scalars?.Diagnostics.Count ?? 0;+ var resolution = ConceptIrResolver.Resolve(source, diagnostics, scalars);if (resolution is null || diagnostics.Any(IsFatalDiagnosticCode)){diagnostics.Add("firmament-v2-parse-failed");diagnostics.Sort(StringComparer.Ordinal);- return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).ToArray());+ return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).ToArray())+ with { SyntaxDiagnostics = scalars?.Diagnostics.Skip(before).ToArray() ?? [] };}var solid = new FirmamentV2SolidBinding(diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.csindex d038d906..4e9f9857 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs@@ -14,7 +14,7 @@ public static partial class FirmamentV2Parser// Static scalars share the existing typed dependency binder and tolerance IR.// Only syntax is projected here; there is no text substitution or second evaluator.private static StaticValueBinding BindStaticValues(DocumentSyntax syntax, DeclarationSyntax model, string source,- List<string> diagnostics, IReadOnlyList<FirmamentV2BoundLet>? inputs = null)+ List<string> diagnostics, IReadOnlyList<FirmamentV2BoundLet>? inputs = null, FirmamentCompileTimeValues? compileTime = null){var declarations = new List<FirmamentV2LetDeclaration>();var located = new List<FirmamentV2ValidationDiagnostic>();@@ -29,24 +29,18 @@ public static partial class FirmamentV2Parser}foreach (var nested in MechanicalDeclarations(model.Body!.Statements).Where(d => d.Type.Name.Text == "Static" && !statics.Contains(d)))Error("firmament-v2-static-scalar-scope-unsupported", "Declare scalar Static values directly in the Model or its module; nested construction scopes do not introduce scalar environments.", nested.Span, nested.Name?.Text);- FirmamentV2PrimitiveType? InferType(ExpressionSyntax? e, HashSet<string> visiting) => e switch+ FirmamentV2PrimitiveType? InferType(ExpressionSyntax? e, HashSet<string> visiting){- ToleranceSyntax t => InferType(t.Nominal, visiting),- QuantitySyntax { Unit.Text: "mm" } => FirmamentV2PrimitiveType.Length,- QuantitySyntax { Unit.Text: "deg" } => FirmamentV2PrimitiveType.Angle,- QuantitySyntax { Unit.Text: "s" or "ms" } => FirmamentV2PrimitiveType.Time,- LiteralSyntax { Kind: LiteralKind.Boolean } => FirmamentV2PrimitiveType.Bool,- LiteralSyntax { Kind: LiteralKind.String } => FirmamentV2PrimitiveType.String,- LiteralSyntax { Kind: LiteralKind.Number } n => n.Raw.Contains('.') || n.Raw.Contains('e', StringComparison.OrdinalIgnoreCase) ? FirmamentV2PrimitiveType.Float : FirmamentV2PrimitiveType.Int,- UnarySyntax u => InferType(u.Operand, visiting),- SequenceSyntax { Kind: SequenceKind.Tuple, Items.Count: 1 } g => InferType(g.Items[0].Value, visiting),- ReferenceSyntax r when visiting.Count < 128 && visiting.Add(r.Name.Text) => InferReference(r.Name.Text, visiting),- MemberSyntax m when FirmamentSyntaxValues.Reference(m) is { } member && visiting.Count < 128 && visiting.Add(member) => InferReference(member, visiting),- BinarySyntax b when InferType(b.Left, new(visiting, StringComparer.Ordinal)) is { } l- && InferType(b.Right, new(visiting, StringComparer.Ordinal)) is { } r => ExpressionBinder.ResultType(l,- b.Operator switch { BinaryOperator.Add => "+", BinaryOperator.Subtract => "-", BinaryOperator.Multiply => "*", BinaryOperator.Divide => "/", _ => "" }, r),- _ => null- };+ if (e is null) return null;+ var type = FirmamentChoiceBinding.Infer(e, reference =>+ {+ var name = FirmamentSyntaxValues.Reference(reference);+ if (name is null || visiting.Count >= 128 || visiting.Contains(name)) return null;+ var nested = new HashSet<string>(visiting, StringComparer.Ordinal) { name };+ return InferReference(name, nested)?.ToString();+ }, match => match.Arms.Count == 0 ? null : InferType(match.Arms[0].Value, visiting)?.ToString());+ return type is not null && TryParseLetType(type, out var primitive) ? primitive : null;+ }FirmamentV2PrimitiveType? InferReference(string name, HashSet<string> visiting){var matches = statics.Where(d => d.Name?.Text == name).ToArray();@@ -59,7 +53,7 @@ public static partial class FirmamentV2Parser{var typeName = FirmamentSyntaxValues.Reference(d.Annotation);var declared = typeName is not null && TryParseLetType(typeName, out var explicitType) ? explicitType- : d.Annotation is null ? InferType(d.Initializer, new(StringComparer.Ordinal)) : null;+ : d.Annotation is null ? inputs?.FirstOrDefault(v => v.Name == d.Name?.Text)?.Type ?? InferType(d.Initializer, new(StringComparer.Ordinal)) : null;if (d.Name is null || declared is not { } type|| d.Initializer is null || d.Body is not null || d.Modifiers.Count > 0 || d.Type.Arguments.Count > 0|| d.Parameters.Count > 0 || d.Clauses.Count > 0 || d.ResultType is not null || d.Occurrence)@@ -70,30 +64,13 @@ public static partial class FirmamentV2Parser}if (!names.Add(d.Name.Text)) { Error(DuplicateName, $"Duplicate compile-time name '{d.Name.Text}'.", d.Span, d.Name.Text); continue; }var valueSyntax = d.Initializer;+ if (inputs?.FirstOrDefault(v => v.Name == d.Name.Text) is { } prebound)+ valueSyntax = Literal(prebound, valueSyntax.Span);FirmamentV2Tolerance? tolerance = null;if (valueSyntax is ToleranceSyntax t){valueSyntax = t.Nominal;- if (type is not (FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle))- Error(ToleranceInvalidType, "tol requires a Length or Angle value.", t.ToleranceSpan, d.Name.Text);- else- {- var unit = type == FirmamentV2PrimitiveType.Length ? "mm" : "deg";- var asymmetric = t.Plus is UnarySyntax { Operator: UnaryOperator.Positive };- if (asymmetric && t.Minus is null)- Error(ToleranceMissingMinus, "A +upper tolerance requires -lower; use tol 0.1mm for a symmetric allowance.", t.ToleranceSpan, d.Name.Text);- else if (!FirmamentSyntaxValues.TryMeasure(t.Plus, unit, out var plus)- || t.Minus is not null && !FirmamentSyntaxValues.TryMeasure(t.Minus, unit, out _))- Error(ToleranceUnitMismatch, $"Tolerance must have the value's dimensional unit ({unit}).", t.ToleranceSpan, d.Name.Text);- else- {- var minus = t.Minus is null ? plus : FirmamentSyntaxValues.TryMeasure(t.Minus, unit, out var m) ? m : double.NaN;- if (plus < 0 || minus < 0)- Error(ToleranceNegativeBilateral, "Tolerance allowances must be finite nonnegative magnitudes; write tol +upper -lower.", t.ToleranceSpan, d.Name.Text);- else tolerance = new(asymmetric ? FirmamentV2ToleranceKind.Asymmetric : FirmamentV2ToleranceKind.Bilateral,- plus, minus, unit, type, t.ToleranceSpan);- }- }+ tolerance = BindTolerance(t, type, (code, message, span) => Error(code, message, span, d.Name.Text));}if (ValueExpression(valueSyntax, type) is { } expression)declarations.Add(new(d.Name.Text, type, expression, d.Span, tolerance));@@ -137,6 +114,7 @@ public static partial class FirmamentV2Parservar map = values.ToDictionary(v => v.Name, StringComparer.Ordinal);ExpressionSyntax Nominal(ExpressionSyntax e) => e switch{+ MatchSyntax m when compileTime is not null => Select(m),MemberSyntax m when FirmamentSyntaxValues.Reference(m) is { } name && map.TryGetValue(name, out var value) => Literal(value, e.Span),ReferenceSyntax r when map.TryGetValue(r.Name.Text, out var value) => Literal(value, e.Span),BinarySyntax b => b with { Left = Nominal(b.Left), Right = Nominal(b.Right) },@@ -147,6 +125,13 @@ public static partial class FirmamentV2ParserToleranceSyntax t => RejectInline(t),_ => e};+ ExpressionSyntax Select(MatchSyntax match)+ {+ var before = compileTime!.Diagnostics.Count;+ var selected = compileTime.ResolveChoices(match, diagnostics);+ located.AddRange(compileTime.Diagnostics.Skip(before));+ return selected is MatchSyntax ? selected : Nominal(selected);+ }ExpressionSyntax RejectInline(ToleranceSyntax t){Error(ToleranceUnsupported, "Declare a named Static value with tol, use its nominal value in geometry, then project it with Pmi dimension: name.", t.ToleranceSpan);@@ -171,13 +156,18 @@ public static partial class FirmamentV2Parserif (e is SequenceSyntax { Kind: SequenceKind.Tuple, Items.Count: 1 } group) return ValueExpression(group.Items[0].Value, expected);if (e is BinarySyntax b){- var op = b.Operator switch { BinaryOperator.Add => "+", BinaryOperator.Subtract => "-", BinaryOperator.Multiply => "*", BinaryOperator.Divide => "/", _ => null };+ var op = b.Operator switch { BinaryOperator.Add => "+", BinaryOperator.Subtract => "-", BinaryOperator.Multiply => "*", BinaryOperator.Divide => "/",+ BinaryOperator.Equal => "==", BinaryOperator.NotEqual => "!=", BinaryOperator.Less => "<", BinaryOperator.LessEqual => "<=", BinaryOperator.Greater => ">", BinaryOperator.GreaterEqual => ">=",+ BinaryOperator.And => "&&", BinaryOperator.Or => "||", _ => null };return op is not null && ValueExpression(b.Left, expected) is { } l && ValueExpression(b.Right, expected) is { } rgt? new FirmamentV2BinaryExpression(l, op, rgt, text) : null;}+ if (e is UnarySyntax { Operator: UnaryOperator.Not } not && ValueExpression(not.Operand, FirmamentV2PrimitiveType.Bool) is { } operand)+ return new FirmamentV2UnaryExpression("!", operand, text);var unit = e is QuantitySyntax q ? q.Unit.Text : e is UnarySyntax { Operand: QuantitySyntax uq } ? uq.Unit.Text : "";var inferred = unit switch { "mm" => FirmamentV2PrimitiveType.Length, "deg" => FirmamentV2PrimitiveType.Angle, "s" or "ms" => FirmamentV2PrimitiveType.Time,- "" => expected is FirmamentV2PrimitiveType.String or FirmamentV2PrimitiveType.Bool ? expected+ "" => e is LiteralSyntax { Kind: LiteralKind.Boolean } ? FirmamentV2PrimitiveType.Bool+ : e is LiteralSyntax { Kind: LiteralKind.String } ? FirmamentV2PrimitiveType.String: text.Contains('.') || text.Contains('e', StringComparison.OrdinalIgnoreCase) ? FirmamentV2PrimitiveType.Float : FirmamentV2PrimitiveType.Int, _ => (FirmamentV2PrimitiveType?)null };if (inferred is null) return null;if (inferred is FirmamentV2PrimitiveType.String or FirmamentV2PrimitiveType.Bool)@@ -199,6 +189,26 @@ public static partial class FirmamentV2Parser}}+ internal static FirmamentV2Tolerance? BindTolerance(ToleranceSyntax syntax, FirmamentV2PrimitiveType type,+ Action<string, string, FirmamentV2SourceSpan> error)+ {+ void Fail(string code, string message) => error(code, message, syntax.ToleranceSpan);+ if (type is not (FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle))+ { Fail(ToleranceInvalidType, "tol requires a Length or Angle value."); return null; }+ var unit = type == FirmamentV2PrimitiveType.Length ? "mm" : "deg";+ var asymmetric = syntax.Plus is UnarySyntax { Operator: UnaryOperator.Positive };+ if (asymmetric && syntax.Minus is null)+ { Fail(ToleranceMissingMinus, "A +upper tolerance requires -lower; use tol 0.1mm for a symmetric allowance."); return null; }+ if (!FirmamentSyntaxValues.TryMeasure(syntax.Plus, unit, out var plus)+ || syntax.Minus is not null && !FirmamentSyntaxValues.TryMeasure(syntax.Minus, unit, out _))+ { Fail(ToleranceUnitMismatch, $"Tolerance must have the value's dimensional unit ({unit})."); return null; }+ var minus = syntax.Minus is null ? plus : FirmamentSyntaxValues.TryMeasure(syntax.Minus, unit, out var m) ? m : double.NaN;+ if (!double.IsFinite(plus) || !double.IsFinite(minus) || plus < 0 || minus < 0)+ { Fail(ToleranceNegativeBilateral, "Tolerance allowances must be finite nonnegative magnitudes; write tol +upper -lower."); return null; }+ return new(asymmetric ? FirmamentV2ToleranceKind.Asymmetric : FirmamentV2ToleranceKind.Bilateral,+ plus, minus, unit, type, syntax.ToleranceSpan);+ }+// Template/Feature scalar arguments use precisely the same dimensional graph binder as Static.// The caller owns scope and supplies AST declarations and already checked input values.internal static (IReadOnlyList<FirmamentV2BoundLet> Values, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.csindex 60f0a673..c8248dd6 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs@@ -15,10 +15,14 @@ internal sealed record TemplateDeclarationIr(string Name, string TargetKind, strinternal FirmamentTemplateSyntax.Scope? BodyScope { get; init; }internal List<TemplateApplicationIr> BodyApplications { get; } = [];internal string? IdentityNamespace { get; set; }+ internal FirmamentV2SourceSpan BodySpan { get; init; } = new(0, 0);}internal abstract record TemplateParameterIr(string Name, FirmamentV2SourceSpan SourceSpan);internal sealed record TemplateTypeParameterIr(string Name, string ConstraintConcept, FirmamentV2SourceSpan SourceSpan) : TemplateParameterIr(Name, SourceSpan);-internal sealed record TemplateValueParameterIr(string Name, string TypeName, string? DefaultExpression, FirmamentV2SourceSpan SourceSpan) : TemplateParameterIr(Name, SourceSpan);+internal sealed record TemplateValueParameterIr(string Name, string TypeName, string? DefaultExpression, FirmamentV2SourceSpan SourceSpan) : TemplateParameterIr(Name, SourceSpan)+{+ internal FirmamentV2SourceSpan? DefaultSpan { get; init; }+}internal sealed record TemplateApplicationIr(string TargetKind, string InstanceName, string TemplateName, ImmutableArray<TemplateArgumentIr> Arguments, FirmamentV2SourceSpan SourceSpan){internal TemplateDeclarationIr? BoundTemplate { get; init; }@@ -139,8 +143,8 @@ internal static class FirmamentV2TemplateExpansion.ToDictionary(field => field.Key, field => field.Value, StringComparer.Ordinal))).ToArray();- internal static IReadOnlyDictionary<string, IReadOnlyList<string>> InspectEnums(string source) =>- ParseEnums(source).OrderBy(item => item.Key, StringComparer.Ordinal)+ internal static IReadOnlyDictionary<string, IReadOnlyList<string>> InspectEnums(string source, List<string>? diagnostics = null) =>+ ParseEnums(source, diagnostics).OrderBy(item => item.Key, StringComparer.Ordinal).ToDictionary(item => item.Key,item => (IReadOnlyList<string>)item.Value.OrderBy(value => value, StringComparer.Ordinal).ToArray(),StringComparer.Ordinal);@@ -171,7 +175,7 @@ internal static class FirmamentV2TemplateExpansionstring templateName,string instanceName,IReadOnlyDictionary<string, HostArgument> hostArguments,- List<string> diagnostics)+ List<string> diagnostics, FirmamentCompileTimeValues? scalars = null){ArgumentException.ThrowIfNullOrWhiteSpace(templateName);ArgumentException.ThrowIfNullOrWhiteSpace(instanceName);@@ -197,10 +201,17 @@ internal static class FirmamentV2TemplateExpansionreturn null;}- var enums = ParseEnums(source);- var recordTypes = ParseRecordTypes(source, diagnostics);- var tables = ParseStaticTables(source, recordTypes, enums, diagnostics);- var staticRecords = ParseStaticRecords(source, recordTypes, enums, tables, diagnostics).ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal);+ scalars ??= new(source);+ scalars.UseDataBinding(dataBinding);+ var catalog = ReadDataCatalog(source, diagnostics, scalars, initialize: true);+ if (scalars.Diagnostics.Any(d => d.Severity is "error" or "fatal"))+ {+ diagnostics.AddRange(scalars.Diagnostics.Select(d => d.Code + ": " + d.Message));+ return null;+ }+ var enums = catalog.Enums;+ var recordTypes = catalog.Types;+ var staticRecords = catalog.Records.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal);var arguments = ImmutableArray.CreateBuilder<TemplateArgumentIr>();foreach (var pair in hostArguments.OrderBy(pair => pair.Key, StringComparer.Ordinal)){@@ -248,13 +259,14 @@ internal static class FirmamentV2TemplateExpansiontemplateName,arguments.ToImmutable(),new FirmamentV2SourceSpan(source.Length, 0));- var bound = Bind(template, application, source, enums, recordTypes, staticRecords, diagnostics);+ scalars.SetRecords(recordTypes, staticRecords);+ var bound = Bind(template, application, source, enums, recordTypes, staticRecords, diagnostics, scalars);if (bound is null || HasErrors(diagnostics)) return null;if (!ValidateRecordMembers(template.Body, bound, diagnostics)) return null;if (!EvaluateRequires(Substitute(template.Body, bound), application.InstanceName,- DisplaySignature(template), diagnostics, out var requireResults, source)) return null;- var body = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);+ DisplaySignature(template), diagnostics, out var requireResults, source, scalars)) return null;+ var body = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches, template, scalars);if (body is null) return null;body = Substitute(body, bound);body = RemoveRequires(body);@@ -338,14 +350,15 @@ internal static class FirmamentV2TemplateExpansionpublic static Result? Expand(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null, string? originalSource = null){+ scalars ??= new(source);var dataBinding = new FirmamentDataBinding(source);- diagnostics.AddRange(dataBinding.Diagnostics.Select(d => scalars is null ? d.Code + ": " + d.Message : d.Code));- scalars?.AddExpansionDiagnostics(dataBinding.Diagnostics);+ diagnostics.AddRange(dataBinding.Diagnostics.Select(d => d.Code));+ scalars.AddExpansionDiagnostics(dataBinding.Diagnostics);if (dataBinding.Diagnostics.Count > 0) return null;- scalars?.UseDataBinding(dataBinding);+ scalars.UseDataBinding(dataBinding);source = dataBinding.Source;var syntax = new FirmamentTemplateSyntax(source, diagnostics);- if (scalars is not null && syntax.Diagnostics.Count > 0)+ if (syntax.Diagnostics.Count > 0){var origins = new FirmamentSyntaxOrigins(FirmamentSyntaxParser.Parse(originalSource ?? source).Document,FirmamentSyntaxParser.Parse(source).Document);@@ -363,13 +376,28 @@ internal static class FirmamentV2TemplateExpansionif (HasErrors(diagnostics)) return null;var catalog = ReadDataCatalog(source, diagnostics, scalars, initialize: true);+ if (scalars.Diagnostics.Any(d => d.Severity is "error" or "fatal")) return null;var enums = catalog.Enums;var recordTypes = catalog.Types;var tables = catalog.Tables;var staticRecords = catalog.Records;+ if (scalars is not null)+ foreach (var definition in syntax.Declarations)+ {+ var inputs = definition.Parameters.OfType<TemplateValueParameterIr>().ToDictionary(p => p.Name,+ p => new FirmamentCompileTimeValues.ChoiceInput(p.TypeName,+ new ReferenceSyntax(new(p.Name, p.SourceSpan), p.SourceSpan)), StringComparer.Ordinal);+ var bodySyntax = FirmamentSyntaxParser.Parse(definition.Body).Document;+ foreach (var parameter in definition.Parameters.OfType<TemplateValueParameterIr>().Where(p => p.DefaultExpression is not null))+ if (FirmamentSyntaxParser.ParseExpression(parameter.DefaultExpression!).Expression is { } value)+ _ = scalars.ResolveChoices(value, diagnostics, inputs, parameter.TypeName, select: false,+ sourceOffset: parameter.DefaultSpan?.Start ?? parameter.SourceSpan.Start);+ foreach (var match in FirmamentChoiceBinding.OutermostMatches(bodySyntax))+ _ = scalars.ResolveChoices(match, diagnostics, scalars.ChoiceScope(bodySyntax, match, inputs), select: false, sourceOffset: definition.BodySpan.Start, finitePatternSelector: CanonicalStaticAuthoring.IsFinitePatternSelector(bodySyntax, match));+ }var concepts = new FirmamentConcepts(source, scalars);diagnostics.AddRange(concepts.Diagnostics.Select(d => d.Code + ": " + d.Message));- scalars?.AddConceptDiagnostics(concepts.Diagnostics, producerSource: source);+ scalars.AddConceptDiagnostics(concepts.Diagnostics, producerSource: source);if (HasErrors(diagnostics)) return null;var changes = declarations.Select(d => (d.SourceSpan.Start, d.SourceSpan.Length, Text: string.Empty)).ToList();var instantiations = new List<ConceptIrTemplateInstantiation>();@@ -383,7 +411,7 @@ internal static class FirmamentV2TemplateExpansionif (!ValidateRecordMembers(template.Body, bound, diagnostics)) continue;if (!EvaluateRequires(Substitute(template.Body, bound, scalars), application.InstanceName,DisplaySignature(template), diagnostics, out var requireResults, source, scalars)) continue;- var body = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);+ var body = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches, template, scalars ?? new(source));if (body is null) continue;body = Substitute(body, bound);body = RemoveRequires(body);@@ -406,15 +434,15 @@ internal static class FirmamentV2TemplateExpansion// Rebind symbol identities before Feature/default admission, never by// sharing the unspecialized definition's value environment.var concrete = new FirmamentDataBinding(source);- diagnostics.AddRange(concrete.Diagnostics.Select(d => scalars is null ? d.Code + ": " + d.Message : d.Code));- scalars?.AddExpansionDiagnostics(concrete.Diagnostics.Select(d => d with { SourceSpan = null, IsOriginalSource = false,+ diagnostics.AddRange(concrete.Diagnostics.Select(d => d.Code));+ scalars.AddExpansionDiagnostics(concrete.Diagnostics.Select(d => d with { SourceSpan = null, IsOriginalSource = false,LocationNote = "Binding failed in specialized source; an original instance location is unavailable." }));if (concrete.Diagnostics.Count > 0) return null;source = concrete.Source;- scalars?.BindExpandedScalars(source, diagnostics);+ scalars.BindExpandedScalars(source, diagnostics);_ = ReadDataCatalog(source, diagnostics, scalars);}- if (HasErrors(diagnostics)) return null;+ if (HasErrors(diagnostics) || scalars.Diagnostics.Any(d => d.Severity is "error" or "fatal")) return null;return new(source, instantiations);}@@ -476,13 +504,43 @@ internal static class FirmamentV2TemplateExpansionvar expression = supplied.TryGetValue(p.Name, out var suppliedValue) ? suppliedValue : p.DefaultExpression;if (expression is null) { diagnostics.Add(MissingArgument + ":" + p.Name + ":expected-signature:" + expectedSignature); return null; }resolving.Add(p.Name);- var referenced = template.Parameters.OfType<TemplateValueParameterIr>().SingleOrDefault(x => x.Name == expression);+ if (!supplied.ContainsKey(p.Name) && scalars is not null && FirmamentSyntaxParser.ParseExpression(expression).Expression is { } defaultSyntax+ && FirmamentSyntaxTraversal.Expressions(defaultSyntax).Any(e => e is MatchSyntax))+ {+ foreach (var dependency in FirmamentSyntaxTraversal.Expressions(defaultSyntax).OfType<ReferenceSyntax>()+ .Select(r => template.Parameters.OfType<TemplateValueParameterIr>().FirstOrDefault(other => other.Name == r.Name.Text)).OfType<TemplateValueParameterIr>())+ _ = Resolve(dependency);+ var inputs = template.Parameters.OfType<TemplateValueParameterIr>().Where(other => values.ContainsKey(other.Name))+ .ToDictionary(other => other.Name, other => scalars.CheckedChoiceInput(other.TypeName,+ FirmamentSyntaxParser.ParseExpression(values[other.Name]).Expression!), StringComparer.Ordinal);+ var before = scalars.Diagnostics.Count;+ expression = FirmamentSyntaxWriter.Expression(scalars.ResolveChoices(defaultSyntax, diagnostics, inputs, p.TypeName));+ scalars.LocateChoiceErrors(before, scalars.OriginalDeclaration(template.TargetKind, template.Name, "Template"),+ "Location identifies the original enclosing Template default.");+ }+ var referenced = supplied.ContainsKey(p.Name) ? null : template.Parameters.OfType<TemplateValueParameterIr>().SingleOrDefault(x => x.Name == expression);var value = referenced is null ? expression : Resolve(referenced);resolving.RemoveAt(resolving.Count - 1);if (value is null) return null;+ if (scalars?.IsChoice(p.TypeName) == true)+ {+ var before = scalars.Diagnostics.Count;+ if (scalars.TryChoiceTransfer(value, p.TypeName, diagnostics, out var tag)) value = tag;+ scalars.LocateChoiceErrors(before, scalars.OriginalDeclaration(application.TargetKind, application.InstanceName),+ "Location identifies the original Template application; the argument was decoded during specialization.");+ }if (scalars?.IsScalar(p.TypeName) == true && scalars.TryTransfer(value, p.TypeName,$"Template {template.Name}.{p.Name}", application.SourceSpan, diagnostics, out var checkedValue)) value = checkedValue;- if (!TypeMatches(value, p.TypeName, enums, scalars: scalars)) { diagnostics.Add((supplied.ContainsKey(p.Name) ? TypeMismatch : BadDefault) + $":{p.Name}:expected-{p.TypeName}:actual-{value}:expected-signature:{expectedSignature}"); return null; }+ if (!TypeMatches(value, p.TypeName, enums, scalars: scalars))+ {+ var code = supplied.ContainsKey(p.Name) ? TypeMismatch : BadDefault;+ diagnostics.Add(code + $":{p.Name}:expected-{p.TypeName}:actual-{value}:expected-signature:{expectedSignature}");+ var location = scalars?.OriginalDeclaration(application.TargetKind, application.InstanceName);+ scalars?.AddExpansionDiagnostics([new(code, "error", $"Template input '{p.Name}' requires {p.TypeName}; supplied '{value}'.", Target: p.Name)+ { SourceSpan = location, IsOriginalSource = location is not null, Stage = "Template binding",+ LocationNote = "Location identifies the original Template application." }]);+ return null;+ }values[p.Name] = value;if (!supplied.ContainsKey(p.Name)) defaults.Add(p.Name);return value;@@ -594,9 +652,12 @@ internal static class FirmamentV2TemplateExpansionreturn transported;}- private static IReadOnlyDictionary<string, ImmutableHashSet<string>> ParseEnums(string source) => Regex.Matches(source, @"\bEnum\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{(?<body>.*?)\}", RegexOptions.Singleline | RegexOptions.CultureInvariant).Cast<Match>().ToDictionary(- m => m.Groups["name"].Value,- m => Regex.Matches(m.Groups["body"].Value, @"[A-Za-z_][A-Za-z0-9_]*", RegexOptions.CultureInvariant).Select(v => v.Value).ToImmutableHashSet(StringComparer.Ordinal), StringComparer.Ordinal);+ private static IReadOnlyDictionary<string, ImmutableHashSet<string>> ParseEnums(string source, List<string>? diagnostics = null)+ {+ var binding = new FirmamentChoiceBinding(source);+ diagnostics?.AddRange(binding.Diagnostics.Select(d => d.Code + ": " + d.Message));+ return binding.Types.ToDictionary(p => p.Key, p => p.Value.Cases.ToImmutableHashSet(StringComparer.Ordinal), StringComparer.Ordinal);+ }private static bool MatchesCoordinates(string value, string type){if (FirmamentSyntaxParser.ParseExpression(value).Expression is not CallSyntax { Target: ReferenceSyntax target } call@@ -659,10 +720,11 @@ internal static class FirmamentV2TemplateExpansionreturn Visit(FirmamentSyntaxParser.Parse(source).Document.Statements);}- private static IReadOnlyDictionary<string, TemplateRecordTypeIr> ParseRecordTypes(string source, List<string> diagnostics)+ internal static IReadOnlyDictionary<string, TemplateRecordTypeIr> ParseRecordTypes(string source, List<string> diagnostics, bool templateLocals = false){var result = new Dictionary<string, TemplateRecordTypeIr>(StringComparer.Ordinal);- foreach (var declaration in DataDeclarations(source).Where(d => d.Type.Name.Text == "Record" && d.Name is not null && d.Body is not null))+ var declarations = templateLocals ? FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document) : DataDeclarations(source);+ foreach (var declaration in declarations.Where(d => d.Type.Name.Text == "Record" && d.Name is not null && d.Body is not null && !d.Modifiers.Any(m => m.Name.Text == "Inventory"))){var fields = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);foreach (var statement in declaration.Body!.Statements)@@ -723,13 +785,23 @@ internal static class FirmamentV2TemplateExpansionvar pending = DataDeclarations(source).Where(d => d.Type.Name.Text == "Static" && d.Name is not null&& (d.Body is not null && recordTypes.ContainsKey(FirmamentSyntaxValues.Reference(d.Annotation) ?? "")|| d.Initializer is ObjectSyntax or WithSyntax+ || d.Initializer is MatchSyntax && recordTypes.ContainsKey(FirmamentSyntaxValues.Reference(d.Annotation) ?? "")|| d.Initializer is IndexSyntax { Target: ReferenceSyntax target } && tables.ContainsKey(target.Name.Text)|| d.Initializer is ReferenceSyntax && recordTypes.ContainsKey(FirmamentSyntaxValues.Reference(d.Annotation) ?? ""))).ToList();while (pending.Count > 0){var progressed = false;- foreach (var declaration in pending.ToArray())+ foreach (var pendingDeclaration in pending.ToArray()){+ var declaration = pendingDeclaration;+ if (declaration.Initializer is MatchSyntax selection && scalars is not null)+ {+ var before = scalars.Diagnostics.Count;+ declaration = declaration with { Initializer = scalars.ResolveChoices(selection, diagnostics,+ expected: FirmamentSyntaxValues.Reference(declaration.Annotation)) };+ if (scalars.Diagnostics.Skip(before).Any(d => d.Severity is "error" or "fatal"))+ { pending.Remove(pendingDeclaration); progressed = true; continue; }+ }var name = declaration.Name!.Text;var annotatedType = FirmamentSyntaxValues.Reference(declaration.Annotation);if (declaration.Initializer is WithSyntax with)@@ -793,7 +865,7 @@ internal static class FirmamentV2TemplateExpansion{var literal = declaration.Initializer as ObjectSyntax;var type = annotatedType ?? FirmamentSyntaxValues.Reference(literal?.Type);- if (type is null || !recordTypes.TryGetValue(type, out var schema)) { pending.Remove(declaration); progressed = true; continue; }+ if (type is null || !recordTypes.TryGetValue(type, out var schema)) { pending.Remove(pendingDeclaration); progressed = true; continue; }var literalType = FirmamentSyntaxValues.Reference(literal?.Type) ?? type;if (literalType != type) diagnostics.Add(WrongRecordType + ":" + name + ":expected-" + type + ":actual-" + literalType);var body = literal?.Body ?? declaration.Body!;@@ -803,7 +875,7 @@ internal static class FirmamentV2TemplateExpansionCheck(fields, schema, name, RecordFieldTypeMismatch, scalarOnly: true);result[name] = new(name, type, fields.ToImmutableDictionary(StringComparer.Ordinal), declaration.Span);}- pending.Remove(declaration); progressed = true;+ pending.Remove(pendingDeclaration); progressed = true;}if (progressed) continue;foreach (var declaration in pending)@@ -893,52 +965,36 @@ internal static class FirmamentV2TemplateExpansionif (!record.Fields.ContainsKey(member)) diagnostics.Add(UnknownRecordMember + $":{record.Parameter}.{member}:record-{record.TypeName}");return !HasErrors(diagnostics);}- private static string? ResolveTemplateMatches(string body, BoundTemplateArguments bound, List<string> diagnostics, out IReadOnlyDictionary<string, string> selectedMatches)+ private static string? ResolveTemplateMatches(string body, BoundTemplateArguments bound, List<string> diagnostics,+ out IReadOnlyDictionary<string, string> selectedMatches, TemplateDeclarationIr template, FirmamentCompileTimeValues scalars){- // Enum parameters are resolved here so M3's downstream Match evaluator receives only the selected value.var selected = new Dictionary<string, string>(StringComparer.Ordinal);- while (true)+ selectedMatches = selected;+ var locals = new Dictionary<string, FirmamentCompileTimeValues.ChoiceInput>(StringComparer.Ordinal);+ foreach (var p in template.Parameters.OfType<TemplateValueParameterIr>())+ if (bound.ValueArguments.TryGetValue(p.Name, out var value))+ locals[p.Name] = scalars.CheckedChoiceInput(p.TypeName, FirmamentSyntaxParser.ParseExpression(value).Expression!);+ foreach (var record in bound.RecordArguments)+ foreach (var field in record.Value.Fields)+ if (scalars.RecordFieldType(template.Parameters.OfType<TemplateValueParameterIr>().Single(p => p.Name == record.Key).TypeName, field.Key) is { } type)+ locals[record.Key + "." + field.Key] = scalars.CheckedChoiceInput(type, FirmamentSyntaxParser.ParseExpression(field.Value).Expression!);+ var syntax = FirmamentSyntaxParser.Parse(body);+ var edits = new List<(FirmamentV2SourceSpan Span, string Value)>();+ var before = scalars.Diagnostics.Count;+ foreach (var match in FirmamentChoiceBinding.OutermostMatches(syntax.Document)+ .Where(m => !FirmamentSyntaxTraversal.Declarations(syntax.Document).Any(d => d.Body is not null+ && (d.Type.Name.Text == "Feature" || d.Modifiers.Any(m => m.Name.Text == "Template"))+ && FirmamentCompileTimeValues.Encloses(d.Body.ContentSpan, m.Span)))){- var match = Regex.Match(body, @"\bMatch\s+(?<name>[A-Za-z_][A-Za-z0-9_]*(?:\s*\.\s*[A-Za-z_][A-Za-z0-9_]*)?)\s*\{", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1));- if (!match.Success) { selectedMatches = selected; return body; }- var name = Regex.Replace(match.Groups["name"].Value, @"\s+", string.Empty, RegexOptions.CultureInvariant);- string? selectedArm = null;- if (!bound.ValueArguments.TryGetValue(name, out selectedArm))- {- var dot = name.IndexOf('.');- if (dot > 0 && bound.RecordArguments.TryGetValue(name[..dot], out var record))- record.Fields.TryGetValue(name[(dot + 1)..], out selectedArm);- }- if (selectedArm is null) { selectedMatches = selected; return body; }- var open = match.Index + match.Value.LastIndexOf('{'); var close = Matching(body, open, '{', '}');- if (close < 0) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); selectedMatches = selected; return null; }- var arm = Regex.Match(body[(open + 1)..close], $@"(?m)^\s*{Regex.Escape(selectedArm)}\s*=>\s*", RegexOptions.CultureInvariant);- if (!arm.Success) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); selectedMatches = selected; return null; }- var armValueStart = open + 1 + arm.Index + arm.Length;- var value = StaticMatchArmValue(body, armValueStart, close);- if (value is null) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); selectedMatches = selected; return null; }- selected[name] = selectedArm;- body = body.Remove(match.Index, close - match.Index + 1).Insert(match.Index, value);+ var resolved = scalars.ResolveChoices(match, diagnostics, scalars.ChoiceScope(syntax.Document, match, locals), selected: selected, sourceOffset: template.BodySpan.Start, finitePatternSelector: CanonicalStaticAuthoring.IsFinitePatternSelector(syntax.Document, match));+ edits.Add((match.Span, FirmamentSyntaxWriter.Expression(resolved)));}+ if (scalars.Diagnostics.Skip(before).Any(d => d.Severity is "error" or "fatal")) return null;+ foreach (var edit in edits.OrderByDescending(e => e.Span.Start))+ body = body.Remove(edit.Span.Start, edit.Span.Length).Insert(edit.Span.Start, edit.Value);+ return body;}- // A Match arm may be a scalar static expression or a balanced spatial initializer such as Grid { ... }.- // Preserve the whole selected initializer; truncating at its first brace would leak malformed source downstream.- private static string? StaticMatchArmValue(string body, int start, int enclosingClose)- {- while (start < enclosingClose && char.IsWhiteSpace(body[start])) start++;- if (start >= enclosingClose) return null;- var initializer = Regex.Match(body[start..enclosingClose], @"^[A-Za-z_][A-Za-z0-9_]*\s*\{", RegexOptions.CultureInvariant);- if (initializer.Success)- {- var open = start + initializer.Value.LastIndexOf('{');- var close = Matching(body, open, '{', '}');- return close < 0 || close > enclosingClose ? null : body[start..(close + 1)].Trim();- }- var end = body.IndexOfAny(['\r', '\n'], start);- if (end < 0 || end > enclosingClose) end = enclosingClose;- return body[start..end].Trim();- }private static bool EvaluateRequires(string body, string instance, string signature, List<string> diagnostics,out IReadOnlyDictionary<string, string> results, string moduleSource, FirmamentCompileTimeValues? scalars = null){@@ -1055,7 +1111,7 @@ internal static class FirmamentV2TemplateExpansionif (!ValidateRecordMembers(template.Body, bound, diagnostics)) continue;if (!EvaluateRequires(Substitute(template.Body, bound, scalars), application.InstanceName,DisplaySignature(template), diagnostics, out var requireResults, moduleSource, scalars)) continue;- var specializedBody = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);+ var specializedBody = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches, template, scalars ?? new(moduleSource));if (specializedBody is null) continue;specializedBody = Substitute(specializedBody, bound);specializedBody = RemoveRequires(specializedBody);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.csindex 60b3bdf2..8f014c8f 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs@@ -176,6 +176,8 @@ internal sealed class FirmamentDataBindingforeach (var a in c.Arguments) Expression(a.Value, scope, false);if (c.Target is not ReferenceSyntax) Expression(c.Target, scope, false);return;+ case MemberSyntax { Target: ReferenceSyntax owner } m when scope.Resolve("type", owner.Name.Text) is { Declaration.Type.Name.Text: "Enum" } choice:+ Rename(owner.Name, choice.Identity); return;case MemberSyntax m: Expression(m.Target, scope, type); return;case WithSyntax w:Expression(w.Target, scope, false);@@ -190,7 +192,7 @@ internal sealed class FirmamentDataBindingcase TypedValueSyntax t: Expression(t.Type, scope, true); Expression(t.Value, scope, false); return;case ToleranceSyntax t:Expression(t.Nominal, scope, false); Expression(t.Plus, scope, false); if (t.Minus is not null) Expression(t.Minus, scope, false); return;- case MatchSyntax m: Expression(m.Scrutinee, scope, false); foreach (var a in m.Arms) Expression(a.Value, scope, false); return;+ case MatchSyntax m: Expression(m.Scrutinee, scope, false); foreach (var a in m.Arms) { Expression(a.Pattern, scope, false); Expression(a.Value, scope, false); } return;case AliasSyntax a: Expression(a.Value, scope, type); return;case ProvenanceSyntax p: Expression(p.Value, scope, type); return;case FrameSyntax f:diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.csindex dca8bb97..fd0b1906 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs@@ -166,6 +166,9 @@ public static class FirmamentSyntaxParserif (occurrence) Expect("<");var modifiers = new List<TypeSyntax>();var type = Type();+ // A declaration alias retains its authored token span. It is the+ // same nominal type declaration, not source-text preprocessing.+ if (type.Name.Text == "Options") type = type with { Name = type.Name with { Text = "Enum" } };// Prefixes are finite syntax roles, not a list of admitted engineering types.while ((type.Name.Text is "Template" or "Concept" or "Construction" or "Radial" or "Linear" or "Mirror" or "Mirrored" or "Semantic"&& Current.Kind == SyntaxTokenKind.Identifier && (Peek(1).Kind == SyntaxTokenKind.Identifier || Peek(1).Text == "<"))@@ -382,8 +385,9 @@ public static class FirmamentSyntaxParserthrow Fail("firmament-syntax-entity-reference", "Expected a numeric STEP entity identifier after '#'.");at++; left = new LiteralSyntax(LiteralKind.EntityReference, source[start..(Previous.Span.Start + Previous.Span.Length)], Span(start));}- else if (Take("Match"))+ else if (StartsMatch()){+ at++;var scrutinee = Expression(allowObject: false);Expect("{");var arms = new List<MatchArmSyntax>();@@ -501,6 +505,23 @@ public static class FirmamentSyntaxParserfinally { depth--; }}+ private bool StartsMatch()+ {+ if (!Is("Match") && !Is("match")) return false;+ if (Peek(1).Text != "(") return Peek(1).Kind is SyntaxTokenKind.Identifier or SyntaxTokenKind.Number+ && Peek(1).Text is not ("as" or "As" or "with" or "from" or "to") || Peek(1).Text is "!" or "+" or "-";+ // Preserve a callable authored name `match(...)`. A parenthesized+ // scrutinee is a match expression only when followed by its arms.+ var nesting = 0;+ for (var i = at + 1; i < tokens.Length; i++)+ {+ if (tokens[i].Text == "(") nesting++;+ else if (tokens[i].Text == ")" && --nesting == 0)+ return i + 1 < tokens.Length && tokens[i + 1].Text == "{";+ }+ return false;+ }+private IReadOnlyList<ArgumentSyntax> Arguments(string close, bool declarationParameters = false){var args = new List<ArgumentSyntax>();diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.csindex 0638770f..54a1704b 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs@@ -90,7 +90,7 @@ internal sealed class FirmamentSyntaxWriter(string? source = null)return text;}- private static string Operator(BinaryOperator op) => op switch+ internal static string Operator(BinaryOperator op) => op switch{BinaryOperator.Pipeline => "|>", BinaryOperator.Direction => "->", BinaryOperator.Or => "||", BinaryOperator.And => "&&",BinaryOperator.Equal => "==", BinaryOperator.NotEqual => "!=", BinaryOperator.Less => "<", BinaryOperator.LessEqual => "<=",diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentTemplateSyntax.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentTemplateSyntax.csindex b8d6e0b3..74912647 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentTemplateSyntax.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentTemplateSyntax.cs@@ -92,7 +92,7 @@ internal sealed class FirmamentTemplateSyntaxparameters.Add(new TemplateTypeParameterIr(type.Name.Text, constraint.Name.Text, parameter.Span));else if (parameter.Value is ReferenceSyntax value)parameters.Add(new TemplateValueParameterIr(parameter.Name.Text, value.Name.Text,- parameter.Default is null ? null : Text(parameter.Default.Span), parameter.Span));+ parameter.Default is null ? null : Text(parameter.Default.Span), parameter.Span) { DefaultSpan = parameter.Default?.Span });else diagnostics.Add(FirmamentV2TemplateExpansion.InvalidParameter + ":" + parameter.Name.Text);}var template = new TemplateDeclarationIr(declaration.Name.Text, kind,@@ -100,6 +100,7 @@ internal sealed class FirmamentTemplateSyntaxparameters.ToImmutable(), Text(declaration.Body.ContentSpan), declaration.Span){DefinitionScope = scope,+ BodySpan = declaration.Body.ContentSpan,BodyScope = new(scope, scope.Identity + "/" + kind + " " + declaration.Name.Text + "@" + declaration.Span.Start),};if (!scope.Declare(declaration, template)) Error(FirmamentV2TemplateExpansion.DuplicateName + ":" + template.Name, $"Template '{template.Name}' is already declared in scope '{scope.Identity}'.", declaration);diff --git a/docs/development/FIRMAMENT-COMPILE-TIME-CHOICES-RFC.md b/docs/development/FIRMAMENT-COMPILE-TIME-CHOICES-RFC.mdnew file mode 100644index 00000000..39bfe901--- /dev/null+++ b/docs/development/FIRMAMENT-COMPILE-TIME-CHOICES-RFC.md@@ -0,0 +1,334 @@+# Firmament compile-time choices: RFC assessment++Date: 2026-10-16. Baseline evaluated compiler: `c8f48b5b`.++Implementation status: implemented in the production admission path. The baseline+findings below are historical; current qualification and compatibility decisions+are recorded in the implementation section at the end.++## Decision++Proceed with a bounded, fully typed compile-time choice feature. Use lowercase+`match` as the preferred expression keyword; retain `Match` for compatibility.+Accept `Options` as a contextual declaration alias for `Enum`, with exactly the+same nominal type, cases, scope, diagnostics and host representation. `Enum`+remains valid. The alias must not introduce a second kind of choice.++At the baseline, the existing implementation was **not safe to advertise as+exhaustive across Firmament**. The initial assessment preserved executable+requirements and corrected the documentation. The approved implementation now+extends those requirements into production binding; it does not add a new parser+route or a runtime branch engine.++## Intended authoring model++```firmament+// Approved and implemented syntax.+Options MountSize { Compact Standard }++Template<size: MountSize>+Struct MountingPlate {+ Box stock {+ size: [match size {+ Compact => 40mm+ Standard => 80mm+ }, 20mm, 5mm]+ }+}++Struct SmallPlate = MountingPlate<size: Compact>+```++This expresses a finite product choice without duplicating the construction+recipe. A Record can bundle the choice with other requirements; a Table is often+clearer for a large matrix of standard dimensions. Pattern constructs every+entry in a collection; `match` produces one value. `Options` means **choose one**,+not a bit mask or a set of enabled alternatives.++Use PascalCase for declaration kinds, type names and case names; camelCase for+value names and fields; lowercase for the expression keyword `match`. Neither+alias should change authored symbol casing.++## Baseline production-path experiment++The initial [26 source specimens](../../fixtures/Regression/CompileTimeChoicesRfc/README.md)+run through the repository CLI's normal `validate` and `build`, followed by STEP+`analyze` for accepted sources. These are requirement witnesses, including negative+cases; they are not speculative kernel fixtures. Explicit references prove that+the Feature's Hole return type and the Concept's Box/Modify/EdgeFinish consumer+already construct geometry without choice binding.++| Requirement | Baseline observation | Initial disposition |+| --- | --- | --- |+| Compact / Standard Template variants | Both validate and build | Useful existing capability |+| Reorder Template arms | Same result | Preserve |+| Boolean Template choice | Builds chosen dimensions | Preserve and consolidate |+| Enum-valued Record passed into Template | Builds chosen dimensions | Preserve and consolidate |+| Concept chooses Box3 bounds | Builds chosen bounds | Preserve |+| Missing unselected Template case | **Validates and builds** | Safety defect |+| Missing selected Template case | Rejects with generic unsupported-construct | Rejection is honest; diagnostic incomplete |+| Duplicate selected Template arm | **Validates and builds first arm** | Safety defect |+| Unknown Template arm | **Validates and builds** | Safety defect |+| Wrong dimensional type in unselected Template arm | **Validates and builds** | Safety defect |+| Unresolved name in unselected Template arm | **Validates and builds** | Safety defect |+| Duplicate enum case in Template lane | **Validates and builds** | Safety defect |+| Unknown selected enum value | Rejects with typed argument diagnostic | Preserve |+| Missing / duplicate Concept arm | Rejects with coverage / duplicate diagnostic | Preserve without cascades |+| Incompatible Concept arm type | Rejects with arm-type diagnostic | Preserve |+| Lowercase `match` | Rejected later as malformed primitive | Missing syntax/binding integration |+| `Options` declaration | Rejected as unknown parameter type | Missing alias integration |+| Inline semicolon-separated Template arms | Reject after specialization | Expansion extraction depends on line layout |+| Scalar Static choice expression | Rejects as unsupported expression | Missing shared value binding |+| Feature choice in Hole diameter | Rejects as invalid Diameter | Missing shared value binding |++All 26 cases have matching validate/build acceptance outcomes. That agreement+does not establish correctness: six invalid definitions are accepted by both.+The RFC gate meets 14/26 requirements: six false acceptances, five unsupported+proposed forms, and one rejection without the required coverage diagnostic remain.+The proposed gate also requires the missing-selected-arm case to report+non-exhaustiveness, rather than accepting an unrelated generic failure.+There is a diagnostic presentation gap as well: validate includes detail suffixes+in several `code` values, while build separates the canonical code from that+detail. The runner checks the code family and records this normalization mismatch+separately; it does not claim the JSON codes are identical. Concept failures also+include secondary spatial-derivation and generic Phase3 errors at enclosing anchors.++Six accepted choice specimens (two Template variants, reordered arms, Boolean,+Record argument and Concept bounds) reproduce their explicit reference STEP+bytes. Imported world-space bounds, surface families and topology also match.+The ordinary compact stock has bounds `[-20,-10,0]..[20,10,5]` mm; standard stock+has `[-40,-10,0]..[40,10,5]` mm. These asymmetric bounds verify the selected result,+not just the presence of a diagnostic. Concept parity uses a chamfered reference.+No general volume, PMI, browser or animation qualification is claimed here.++## Root causes and correct ownership++The structural parser already has `MatchSyntax`, scrutinee expressions, arms and+source spans. `FirmamentV2TemplateExpansion.ResolveTemplateMatches` nevertheless+extracts a selected arm from text before downstream value checking. It checks+neither the complete declared case domain nor unselected arms; its scalar arm+extraction ends at a newline. `ParseEnums` in that owner also collapses case names+into a set without rejecting duplicates.++`ConceptIr` has a separate evaluator with coverage, duplicate and arm-type checks.+Its enum reader has different separator behavior from the Template reader.+Scalar Static and Feature binding do not gain these semantics merely because the+parser recognizes a Match node. Alias-only edits would leave all of this intact.++The implementation should extend the existing compile-time value/dependency binder+and lexical data-symbol owner. Bind a nominal enum domain and typed Match node+once; let Template, Record, Static, Feature and Concept consume that result.+Remove the text-selected Template Match path when qualified. Do not introduce a+new expression engine, source preprocessing pass or diagnostic allowlist.+`Options` differs in length from `Enum`, so routing it through the existing+equal-length casing normalizer would also break that normalizer's span contract.+Handle the alias structurally and retain original source spelling/spans.++## Safety contract for implementation++1. A choice type is finite, nonempty and nominal. Reject duplicate cases and+ invalid/unknown cases. Respect lexical scopes and module exports; two types+ sharing a case name do not become interchangeable.+2. A scrutinee must bind to a compile-time enum or Bool. Support existing typed+ Boolean expressions through their owner; reject unresolved or cyclic inputs.+3. Require every enum case, or both Boolean cases, exactly once. Initially omit+ wildcard arms, guards, payload enums, fallthrough and implicit defaults. Adding+ a case must invalidate incomplete consumers rather than choose a fallback.+4. Resolve names and type-check **all** arms before selecting. Arms must satisfy+ one contextual result type, including dimensional and nominal Record types.+ Match is an expression, not an arbitrary statement-block executor.+5. Evaluate only the selected value after admission. Do not build unselected+ geometry or require unselected kernel construction to succeed. Type checking+ all arms is distinct from materializing all arms. Rejecting undefined names+ in every arm does not imply executing every arm.+6. Preserve the selected value's tolerance, semantic identity and source+ provenance. A matching nominal number alone is insufficient. PMI remains an+ explicit projection; selecting a toleranced value must not export PMI by itself.+7. Use the same admission result for validate and build. Diagnostics must identify+ the scrutinee, enum and missing/duplicate/unknown case or conflicting arm type,+ with the original arm span. Avoid the present generic error and Concept cascade.+8. Erase selection before engineering lowering. No runtime branch, state machine+ or viewer-owned interpretation is needed. Preserve existing named application+ identities and selected-reference geometry.+9. Carry `Options` through language-service, schema, host/SDK and formatting+ projections as the same Enum type. The parser must accept both Match spellings+ at expression positions without globally rewriting user identifiers or strings.++The minimum useful complete implementation covers Static initializers, Record+fields, Template arguments/defaults/bodies, Feature value arguments and Concept+values using this shared contract. Statement-level conditional construction,+switching Feature recipe types and arbitrary conditional Assembly statements are+separate extensions; this RFC does not silently promise them.++## Qualification and remaining gate++Reproduce the RFC gate with:++```powershell+dotnet build Aetheris.slnx -c Release --no-restore -m:1 -nr:false -p:UseSharedCompilation=false+python fixtures/Regression/CompileTimeChoicesRfc/run.py+```++The initial runner intentionally exited nonzero while requirements remained unmet.+The implementation gate now requires every specimen to pass.+Do not weaken negative cases to make the RFC green. Raw CLI JSON, STEP artifacts,+geometry comparisons and test logs stay in ignored+`artifacts/local/compile-time-choices/`.++Qualification completed for this evaluation:++- Release solution build: zero errors, 26 warnings (including WebAssembly+ SQLite native-signature warnings); `build.log` retains the output.+- Core fast lane: 1,076 passed; `fast.log`.+- Full solution lane: 5,244 passed across 20 projects, zero failures or skips;+ includes all 2,752 Firmament tests and all seven Editable V8 tests; `full.log`.+- RFC gate: 14/26 requirements met, exit 1 as intended; `qualification.log`+ and `results.json`. All six available choice/reference geometry pairs also+ have identical STEP bytes. The failed requirements are listed above.+- Repository content-location guard and diff whitespace checks passed.++These existing-suite results establish the evaluation assets' compatibility;+they do not certify the unimplemented feature. Compiler semantics and existing+goldens were not modified. .NET lanes ran serially with node reuse disabled.++The implementation gate must additionally cover nominal-type confusion, scoped+shadowing/imports, empty enums, nested/dependent matches, cycles, selected-only+evaluation, typed-tolerance/PMI provenance, stable identities and SDK diagnostics.+Those are unqualified here, not claimed successes. Re-run the full existing suite+and canonical geometry qualification when compiler semantics change.++## Initial assessment verdict (historical)++**RFC evaluation complete: worth implementing, with one shared typed admission+path. Existing implementation not accepted as exhaustive.** The geometry witnesses+show practical value, and the negative cases isolate the semantic work needed.+Lowercase `match` and the `Options` alias are appropriate surface decisions once+that contract is implemented. No further user language decision is required for+this bounded design.+++## Implementation++The shared finite-domain contract now owns AST Enum/Options declarations and+Match arm admission. Template specialization no longer selects a branch with a+regex or cuts a scalar arm at a newline. Existing scalar dependency binding owns+selected arithmetic, Boolean comparisons and tolerances; existing spatial and+engineering lowerers still own geometry. Record schemas and spatial-owner field+metadata type-check arms without evaluating unselected geometry.++Static enum bindings retain their nominal type. Scalar Static and Record values,+Template arguments/defaults/bodies, Feature arguments/defaults/locals and Concept+values consume the same choice admission. Typed Record results, including checked+`with` overrides, stay nominal. Binding preserves tolerance receipts and explicit+PMI projection. Source and host expansion APIs reject invalid choices instead of+erasing them, and preserve explanatory diagnostics at their existing API boundary.++Additional repairs discovered during qualification:++- Concept member references such as Bounds in a selected Grid bind in their+ enclosing AST scope. Nested Template and Feature definitions retain their own+ selection owner rather than being evaluated by an outer specialization.+- Checked enum arguments are qualified internally so a case cannot be captured by+ a callee parameter with the same name. Explicit Template arguments resolve in+ caller scope; formal-parameter alias resolution applies to defaults.+- AST declaration-name spans protect `let diameter` from being capitalized as the+ Hole field Diameter. Actual construct fields still use existing casing aliases.+- The source-expansion and Forge host boundaries carry the same error messages;+ the public Enum schema is identical for Options.+- Claude's upstream `941aabe7` inspector copy update was fast-forwarded without+ conflicts; its reader-facing read-only explanations are retained.++### Compatibility decisions++`Enum` and `Options` are one nominal declaration kind. Both Match spellings remain+admitted, while the formatter prefers lowercase `match` at expression positions.+A callable authored name `match(...)` remains usable. No global token replacement+changes authored names, strings, Record fields or domain symbols.++The existing StandardProducts flange uses `Pattern ... Over Match P.BoltCount`+to select the 4-, 6- or 8-point collection. This is legitimate shipped source.+Its explicit finite Pattern-source context retains bounded numeric selection;+all arms bind to compatible collections, duplicate/unknown cases reject, and an+unlisted value fails with the admitted cases. This compatibility decision does+not admit ordinary Int value matching or assert exhaustive coverage of integers.+The existing 8-bolt geometry witness and an unlisted-count rejection cover it.++The original static-choice specimen omitted required Model units. Added+`units: mm`; the baseline unsupported-expression error had hidden that independent+source defect. This corrects the witness, not unit admission. Original negative+specimens and their required code families remain intact. The corpus additionally+covers nested matches, scoped/private data, defaults and locals, enum identity,+cycles, qualified cases, spatial field/name errors, selected-only evaluation,+Record results, typed tolerances and PMI.++### Diagnostic contract++Choice failures have stable codes, error severity, explanatory messages, source+file projection and spans. Missing/duplicate/unknown cases identify the domain+and case; type errors identify the arm or field and conflicting types. Static+and retained Template arm locations use original spans. Feature and Concept+adapters can project an enclosing original declaration instead of an exact arm;+the diagnostic location note identifies that enclosing context. Expanded Static+values disclose unavailable original-expression provenance rather than inventing+an exact location. This pass does not introduce a general source-map debugger.++No failed admission retries V1. Existing warnings remain warnings; a nominal+scalar comparison does not manufacture a tolerance-drop arithmetic warning.++### Final qualification++Detailed logs and STEP artifacts remain under ignored+`artifacts/local/compile-time-choices/`.++- Production CLI gate: 57/57 requirements met, 34 accepted and 23 rejected;+ validate and build agree for every specimen. All 29 accepted/reference pairs+ have matching imported geometry and byte-identical STEP. See `final-cli.log`+ and `final-cli/results.json`.+- Original FrontendX4 authoring corpus: 32/32 pass, including the chimera and its+ recorded geometry, with no reference updates; `frontend-x4.log`.+- Both new complete documentation examples validate and build; `doc-examples/`.+- SDK build and all 14 SDK transport tests pass; `sdk-build.log`, `sdk-tests.log`.+ A real headless Edge WebAssembly worker builds Options, rejects a missing arm+ with an explanatory original-source diagnostic, retains byte-identical last+ valid STEP after that failed draft, and rebuilds restored valid source;+ `browser.json` and `browser.log`. This is SDK/browser qualification, not a new+ Helios UI acceptance run.+- Final Release solution build: zero errors (30 warnings, including existing+ nullable/analyzer and WASM SQLite interop warnings); `final-build.log`.+- Choice tests: 65/65; `final-choices.log`. Fast Core lane: 1,076/1,076;+ `final-fast.log`. Complete solution lane: 5,309 passed across 20 projects,+ zero failures or skips, including all 2,817 Firmament tests and all seven+ Editable V8 tests; `final-full.log`. The FrictionLab project reports no tests+ available; it is not counted as a passing test project.+- .NET lanes ran serially with node reuse and shared compilation disabled.+ Final process inventory contains no remaining dotnet/testhost processes.+ The tests' temporary legacy assembly migration output was removed.++The decoded invalid enum argument is anchored to its original Template application+(line 9 in the unknown-choice witness), with an enclosing-location note.++The existing CLI validation adapter still emits a colon-suffixed legacy Template+argument code alongside its canonical structured diagnostic for the unknown-choice+specimen. Both commands reject it and preserve the useful message. The corpus+records that normalization difference explicitly rather than claiming universal+CLI code normalization. A general cleanup of legacy diagnostic adapters is outside+this choice-binding change.++### Code-quality review and verdict++The review checks the parser/spelling seam, shared type admission, selected-value+transport, scalar evaluator reuse, scoped binding, diagnostic provenance and the+existing Template/Feature/Concept adapters. No new regex, whole-document dispatch,+error-code fatality allowlist, source macro system or kernel implementation was+introduced. Removed Template and Concept Match arm scanners are replaced by the+same AST contract; generated source remains at existing lowering boundaries.+Per-compilation state owns choice dependencies. Ordinary Enum dispatch does not+use JudgmentEngine. Diff whitespace, changed-file UTF-8 validation and the+repository content-location guard pass; all new source evidence lives under+`fixtures/Regression/CompileTimeChoicesRfc/`.++**Success.** The bounded compile-time choice capability works through production+admission, engineering build and the browser SDK, with matching reference geometry. Statement branching, payload+enums, wildcard/guard syntax, general Int matching, arbitrary geometry-result+switching and exact expanded-source maps remain outside this pass. No further+user language decision is required for the implemented surface.diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.mdindex 78f37922..d823f4d4 100644--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md@@ -1,5 +1,18 @@# October 2026 Firmament language decision register+Compile-time choices amendment (2026-10-16):+[implementation and qualification](FIRMAMENT-COMPILE-TIME-CHOICES-RFC.md) supersedes+the earlier enum-Static/total-Match deferral for the qualified engineering value+consumers. `Options` aliases `Enum`; preferred `match` retains `Match` compatibility.+Ordinary Enum/Bool value matches require complete unique cases and compatible+arm types before selected-only evaluation. Scalar Static, Record, Template,+Feature and Concept consumers share that admission and preserve selected+requirements into explicit PMI. The existing numeric Pattern-source selector+remains a bounded compatibility construct; this does not introduce general Int+matching, statement-level conditional construction or a new geometry capability.+Fine-grained expansion source mapping and all-domain expression consolidation+remain separate work, as described in the report.+X4 authoring retest amendment (2026-10-15): [repairs and final qualification](../release/FIRMAMENT-FRONTEND-X4.md) close all 32 checks in Claude's current corpus. The decisions at the end of this register supersede only their qualified portions of the historical dispositions below.X2 production binding amendment (2026-10-15):diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex c3ff2151..eb3a02d7 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -65,7 +65,7 @@ mutation or general-purpose computation.| `Feature` | A reusable recipe returning one typed semantic result. || `Template` | Typed compile-time specialization of a declared product or bounded feature recipe. || `Record` / `Static` | A data shape / an immutable compile-time binding. A Record is not a body. |-| `Enum` / `Match` | A finite choice type / compile-time selection of one result. |+| `Options` / `Enum`, `match` | A finite choice type and exhaustive compile-time selection of one value. || `Set<T>` | All named entries of type T, available together for finite repetition. || `Semantic` | A named engineering interface containing published datums, axes, points or dimensions. || `Path` | An ordered construction chain, open or closed; it creates no material. `Concept Path` is a compatibility spelling. |@@ -346,21 +346,66 @@ rules. See [Sheet Metal](sheet-metal.md) and [FEA](fea.md).### Choices versus collections-`Enum` and `Match` remain useful; `Set<T>` does not supersede them:+`Options` (also spelled `Enum`) declares mutually exclusive choices. `match`+selects one compile-time value. `Set<T>` holds every entry for Pattern to+construct. These are different operations; a choice declaration does not+construct a body for each case.-| Intent | Form | Compile-time meaning |-| --- | --- | --- |-| Choose Compact or Standard | `Enum SizeChoice { Compact Standard }` | Define alternatives; a typed parameter holds one case. |-| Compute a value for the selected case | `Match choice { Compact => 1mm Standard => 2mm }` | Select one arm in an admitted Template/static expression position. |-| Construct every mount | `Static mounts: Set<Point2> { ... }` and `Pattern` | Bind all entries; expand the recipe for each named entry. |--Enum cases are tags, not coordinates or a collection of feature instances.-Match is not a runtime branch or a general statement executor. Pattern repeats-construction; it does not choose an enum case. Match support is bounded by its-consumer: the Template binder supports typed choices, while Model scalar Static-initializers currently admit literals, aliases and arithmetic. Do not infer-general Match support from its presence in the syntax tree. See-[Templates](templates.md) and the Pattern examples below.+**Complete file — choose one plate width:**++```firmament+Model ConfiguredPlate {+ units: mm+ Options SizeChoice { Compact Standard }+ Static size: SizeChoice = Compact+ Static width: Length = match size {+ Compact => 40mm+ Standard => 80mm+ }+ Box stock { size: [width, 20mm, 5mm] }+}+```++Use PascalCase for type and case names, camelCase for values and fields, and+lowercase `match` for the expression keyword. `Enum` and `Options` are the same+nominal type declaration; `Options` does not mean a set of enabled flags.+The older `Match` spelling remains compatible. Formatting changes the expression+keyword to `match` without renaming authored symbols, cases or strings.++Every Enum case, or both `true` and `false` for Bool, must appear exactly once.+Missing, duplicate and unknown cases reject, including cases that would not be+selected. There is no wildcard/default arm, fallthrough, guard or payload-enum+syntax. Cases can be qualified (`SizeChoice.Compact`); a value of another Enum+is not interchangeable merely because both types have a `Compact` case.++All arms must bind names and have the same result type. `Length` and `Angle`+cannot share a result; nor can two different Record types with identical fields.+Only the selected value is evaluated. An unselected arithmetic expression does+not execute, and an unselected spatial value does not construct geometry.+This does not excuse misspelled names, fields or incompatible tolerances in that+arm. Ordinary declarations still have their own admission rules.++Use choice expressions in scalar Static initializers, admitted Record fields,+Template inputs/defaults/bodies, Feature inputs/defaults/locals, and existing+Concept spatial values such as Box3 bounds and Grid point sets. Boolean scalar+comparisons can be scrutinees: `match diameter > 8mm { true => 6mm; false => 4mm }`.+Arms may occupy separate lines or use semicolons on one line. A selected Record+retains its nominal type; a selected dimensional requirement retains its+tolerance allowance and original-source provenance. PMI remains explicit:+selecting a toleranced value alone creates no annotation. The allowance's syntax+is still `tol`, as described above.++`match` is an expression, not a statement executor. It does not conditionally+execute arbitrary Feature, Part, Mate or Assembly declaration blocks. Domain+constructors and collection forms must still be admitted by their ordinary+consumer; structural parsing is not permission to construct a new value type.++One compatibility form is intentionally narrower: existing numeric selectors in+`Pattern ... over Match count { 4 => bolts4; 6 => bolts6; 8 => bolts8 }` choose+among finite collections. They retain their existing Pattern owner, check all+arms, and reject an unlisted count. This is not general exhaustive Int matching.+Use `Options` for new categorical choices and Tables for standard-value matrices.+See [Templates](templates.md) for typed specialization.## Constructing from a layoutdiff --git a/docs/public/firmament/templates.md b/docs/public/firmament/templates.mdindex aea5b3d0..0ce4fe57 100644--- a/docs/public/firmament/templates.md+++ b/docs/public/firmament/templates.md@@ -68,21 +68,37 @@ The older `Template MountHole(MountSpec spec)` and `MountHole(Current)` spelling## Parameters-`Enum` defines mutually exclusive parameter choices; `Match` computes the value-for the selected choice during specialization. `Set<T>` instead contains all-of its named entries at once, for iteration with Pattern. These constructs-have different jobs and remain supported. See the working+`Options` and `Enum` define the same finite nominal choice type. Preferred+`match` selects one result; legacy `Match` remains accepted. Every Enum case,+or both Bool cases, must occur exactly once, and all arms must bind names and+produce the same type before selection. Unknown, duplicate and missing cases+reject even in an unselected arm. Only the selected value is evaluated.++A typed choice may travel through a scalar Static, a Record, a Template parameter+or default, and a Feature parameter or local. Record results must retain the same+nominal Record type; identical fields do not make unrelated Records interchangeable.+Arms may be separated by newlines or semicolons. Toleranced selections preserve+the selected requirement's allowance and provenance through the existing typed+transport; PMI still requires an explicit projection.++```firmament+Options PlateSize { Compact Standard }+Template<size: PlateSize = Standard,+ width: Length = match size { Compact => 40mm; Standard => 80mm }>+Struct PlateFamily {+ Box stock { size: [width, 20mm, 5mm] }+}+Struct Plate = PlateFamily<size: Compact>+```++`Set<T>` contains all entries at once for Pattern; it does not replace choices.+See the working[`table-driven-mounting-plate.firmament`](../../../fixtures/Canonical/Templates/table-driven-mounting-plate.firmament)for enum-valued Record data, and [Writing Firmament](syntax.md#choices-versus-collections)-for their language roles and bounded Match admission. An enum declaration does-not itself generate one body per case.-Each specialization must resolve a matching arm. This pass does not add a-whole-enum exhaustiveness guarantee for unselected alternatives across all-existing Match consumers.-Enum values are admitted in typed Template parameters and Record fields. The-primitive Model scalar Static lane does not yet bind standalone enum-valued-constants; that is a binder-consolidation task, not a reason to replace choices-with Set.+for the expression contract and the bounded legacy numeric Pattern-source selector.+A match expression does not execute arbitrary declaration blocks or admit new+geometry capabilities. Static Enum values use an explicit nominal type annotation,+such as `Static size: PlateSize = Compact`.Scalar `Static` bindings and typed Record fields can carry[typed tolerances](pmi.md#project-a-compile-time-tolerance). Scalar or whole-Recorddiff --git a/fixtures/Regression/CompileTimeChoicesRfc/README.md b/fixtures/Regression/CompileTimeChoicesRfc/README.mdnew file mode 100644index 00000000..cc870cbe--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/README.md@@ -0,0 +1,42 @@+# Compile-time choices regression gate++These preserve the approved RFC requirements and the production regression gate. `cases.json` states the intended acceptance, optional stable+diagnostic code family, and geometry reference for each source. Invalid specimens must+reject even when their problematic arm is not selected.++From the repository root, after a Release CLI build:++```powershell+python fixtures/Regression/CompileTimeChoicesRfc/run.py+```++The runner uses the production CLI for `validate`, `build`, and STEP `analyze`.+It compares imported bounds, body/shell/face/edge/vertex counts and surface+families against explicit reference source. It also records byte equality of+the STEP artifacts as stronger evidence where available. Outputs go to ignored+`artifacts/local/compile-time-choices/`; `--output` can select another directory.+No fixture or reference is updated by running it.++Exit 1 means at least one required behavior is unmet; the qualification gate requires exit 0. In particular, accepting+an invalid specimen is a failure, even if it emits plausible geometry. A rejection+with a required diagnostic missing is also a failure. The assessment retains the historical baseline gaps separately from current implementation evidence. Do not turn the+known gaps into expected successes to obtain a green result.++Code-family checks accept the existing colon-suffixed validation codes. The+results separately record `canonicalDiagnosticCodes`; accepting the family does+not claim that validate/build JSON code normalization is consistent.++`Options` and lowercase `match` are production spellings; `Enum` and `Match` remain compatible. The Feature specimen uses+the already-supported `Hole<Shaft>` return type, and the Concept specimens use+the established Box/Modify/EdgeFinish consumer. The explicit references establish+that these are real engineering consumers rather than speculative kernel tests.++See [the assessment](../../../docs/development/FIRMAMENT-COMPILE-TIME-CHOICES-RFC.md).++The static-choice specimen now includes the required Model units header; its+original expression-binding failure had hidden that separate source defect.+Other original negative sources and their code-family requirements remain intact.+Additional cases cover selected-only evaluation, scopes and nominal identity,+nested matches, private Template values, defaults and locals, Record/with results,+tolerance/PMI parity and keyword/name collisions. Numeric Pattern-source selection+retains its existing bounded compatibility owner; general Int matches reject.diff --git a/fixtures/Regression/CompileTimeChoicesRfc/bool-template.firmament b/fixtures/Regression/CompileTimeChoicesRfc/bool-template.firmamentnew file mode 100644index 00000000..88bcdb98--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/bool-template.firmament@@ -0,0 +1,8 @@+Template<choice: Bool>+Struct Plate {+ Box Stock { Size: [Match choice {+ true => 40mm+ false => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: true>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/boolean-expression.firmament b/fixtures/Regression/CompileTimeChoicesRfc/boolean-expression.firmamentnew file mode 100644index 00000000..08de725b--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/boolean-expression.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [match 3mm > 2mm {+ true => 40mm+ false => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/case-parameter-collision.firmament b/fixtures/Regression/CompileTimeChoicesRfc/case-parameter-collision.firmamentnew file mode 100644index 00000000..e2b02e46--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/case-parameter-collision.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<Compact: SizeChoice, Standard: SizeChoice>+Struct Plate {+ Box Stock { Size: [match Compact {+ Compact => 40mm+ Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<Compact: Standard, Standard: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/cases.json b/fixtures/Regression/CompileTimeChoicesRfc/cases.jsonnew file mode 100644index 00000000..288867f2--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/cases.json@@ -0,0 +1,308 @@+[+ {+ "name": "template-compact",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "template-standard",+ "shouldBuild": true,+ "reference": "standard-reference"+ },+ {+ "name": "compact-reference",+ "shouldBuild": true,+ "reference": null+ },+ {+ "name": "standard-reference",+ "shouldBuild": true,+ "reference": null+ },+ {+ "name": "lowercase-match",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "options-alias",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "missing-unselected",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-match-non-exhaustive"+ },+ {+ "name": "missing-selected",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-match-non-exhaustive"+ },+ {+ "name": "duplicate-selected",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-match-duplicate-arm"+ },+ {+ "name": "unknown-arm",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-enum-unknown-variant"+ },+ {+ "name": "wrong-unselected-dimension",+ "shouldBuild": false,+ "reference": null+ },+ {+ "name": "unresolved-unselected",+ "shouldBuild": false,+ "reference": null+ },+ {+ "name": "unknown-choice",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-template-value-argument-type-mismatch"+ },+ {+ "name": "inline-arms",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "reordered-arms",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "bool-template",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "static-choice",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "feature-choice",+ "shouldBuild": true,+ "reference": "feature-reference"+ },+ {+ "name": "concept-compact",+ "shouldBuild": true,+ "reference": "concept-reference"+ },+ {+ "name": "concept-missing-unselected",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-match-non-exhaustive"+ },+ {+ "name": "concept-duplicate",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-match-duplicate-arm"+ },+ {+ "name": "concept-wrong-dimension",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-match-arm-type-mismatch"+ },+ {+ "name": "duplicate-enum-case",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-enum-duplicate-variant"+ },+ {+ "name": "record-choice",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "concept-reference",+ "shouldBuild": true,+ "reference": null+ },+ {+ "name": "feature-reference",+ "shouldBuild": true,+ "reference": null+ },+ {+ "name": "unselected-division",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "nested-match",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "boolean-expression",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "unused-incomplete-template",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-match-non-exhaustive"+ },+ {+ "name": "empty-enum",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-enum-empty"+ },+ {+ "name": "wildcard",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-enum-unknown-variant"+ },+ {+ "name": "nominal-confusion",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-v2-expression-type-mismatch"+ },+ {+ "name": "enum-cycle",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-v2-expression-cycle"+ },+ {+ "name": "match-cycle",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-v2-expression-cycle"+ },+ {+ "name": "scoped-choice",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "record-result",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "pmi-reference",+ "shouldBuild": true,+ "reference": null+ },+ {+ "name": "pmi-selected-record",+ "shouldBuild": true,+ "reference": "pmi-reference"+ },+ {+ "name": "template-default",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "unused-incomplete-feature",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-match-non-exhaustive"+ },+ {+ "name": "feature-default",+ "shouldBuild": true,+ "reference": "feature-reference"+ },+ {+ "name": "feature-local",+ "shouldBuild": true,+ "reference": "feature-reference"+ },+ {+ "name": "direct-field",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "unselected-spatial-name",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-v2-expression-unknown-symbol"+ },+ {+ "name": "unselected-spatial-field",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-v2-canonical-field-unknown"+ },+ {+ "name": "unselected-invalid-tolerance",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-v2-tolerance-unit-mismatch"+ },+ {+ "name": "qualified-cases",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "nominal-record-result",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-match-arm-type-mismatch"+ },+ {+ "name": "parenthesized-condition",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "enum-equality",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "private-template-values",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "match-call-compatibility",+ "shouldBuild": true,+ "reference": "feature-reference"+ },+ {+ "name": "integer-value-match",+ "shouldBuild": false,+ "reference": null,+ "diagnostic": "firmament-static-match-invalid-scrutinee-type"+ },+ {+ "name": "record-with-result",+ "shouldBuild": true,+ "reference": "compact-reference"+ },+ {+ "name": "case-parameter-collision",+ "shouldBuild": true,+ "reference": "standard-reference"+ },+ {+ "name": "feature-record-choice",+ "shouldBuild": true,+ "reference": "feature-reference"+ }+]diff --git a/fixtures/Regression/CompileTimeChoicesRfc/compact-reference.firmament b/fixtures/Regression/CompileTimeChoicesRfc/compact-reference.firmamentnew file mode 100644index 00000000..6a6f7cdf--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/compact-reference.firmament@@ -0,0 +1 @@+Struct Result { Box Stock { Size: [40mm, 20mm, 5mm] } }diff --git a/fixtures/Regression/CompileTimeChoicesRfc/concept-compact.firmament b/fixtures/Regression/CompileTimeChoicesRfc/concept-compact.firmamentnew file mode 100644index 00000000..b9fbfac2--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/concept-compact.firmament@@ -0,0 +1,16 @@+Enum SizeChoice {+ Compact+ Standard+}+Concept Struct Design {+ choice: SizeChoice = Compact+ Bounds: Match choice {+ Compact => Box3 { Size: [40mm, 20mm, 5mm] }+ Standard => Box3 { Size: [80mm, 20mm, 5mm] }+ }+ TopPlane: Bounds.Face(+Z)+}+Struct Result {+ Box Stock { Bounds: Design.Bounds }+ Modify Stock { EdgeFinish Break { Face: +Z; Target: Boundary; Kind: Chamfer; Distance: 1mm } }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/concept-duplicate.firmament b/fixtures/Regression/CompileTimeChoicesRfc/concept-duplicate.firmamentnew file mode 100644index 00000000..8154f122--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/concept-duplicate.firmament@@ -0,0 +1,17 @@+Enum SizeChoice {+ Compact+ Standard+}+Concept Struct Design {+ choice: SizeChoice = Compact+ Bounds: Match choice {+ Compact => Box3 { Size: [40mm, 20mm, 5mm] }+ Compact => Box3 { Size: [40mm, 20mm, 5mm] }+ Standard => Box3 { Size: [80mm, 20mm, 5mm] }+ }+ TopPlane: Bounds.Face(+Z)+}+Struct Result {+ Box Stock { Bounds: Design.Bounds }+ Modify Stock { EdgeFinish Break { Face: +Z; Target: Boundary; Kind: Chamfer; Distance: 1mm } }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/concept-missing-unselected.firmament b/fixtures/Regression/CompileTimeChoicesRfc/concept-missing-unselected.firmamentnew file mode 100644index 00000000..29537388--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/concept-missing-unselected.firmament@@ -0,0 +1,15 @@+Enum SizeChoice {+ Compact+ Standard+}+Concept Struct Design {+ choice: SizeChoice = Compact+ Bounds: Match choice {+ Compact => Box3 { Size: [40mm, 20mm, 5mm] }+ }+ TopPlane: Bounds.Face(+Z)+}+Struct Result {+ Box Stock { Bounds: Design.Bounds }+ Modify Stock { EdgeFinish Break { Face: +Z; Target: Boundary; Kind: Chamfer; Distance: 1mm } }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/concept-reference.firmament b/fixtures/Regression/CompileTimeChoicesRfc/concept-reference.firmamentnew file mode 100644index 00000000..1351c749--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/concept-reference.firmament@@ -0,0 +1,13 @@+Enum SizeChoice {+ Compact+ Standard+}+Concept Struct Design {+ choice: SizeChoice = Compact+ Bounds: Box3 { Size: [40mm, 20mm, 5mm] }+ TopPlane: Bounds.Face(+Z)+}+Struct Result {+ Box Stock { Bounds: Design.Bounds }+ Modify Stock { EdgeFinish Break { Face: +Z; Target: Boundary; Kind: Chamfer; Distance: 1mm } }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/concept-wrong-dimension.firmament b/fixtures/Regression/CompileTimeChoicesRfc/concept-wrong-dimension.firmamentnew file mode 100644index 00000000..4bdc394a--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/concept-wrong-dimension.firmament@@ -0,0 +1,16 @@+Enum SizeChoice {+ Compact+ Standard+}+Concept Struct Design {+ choice: SizeChoice = Compact+ Bounds: Match choice {+ Compact => Box3 { Size: [40mm, 20mm, 5mm] }+ Standard => 80deg+ }+ TopPlane: Bounds.Face(+Z)+}+Struct Result {+ Box Stock { Bounds: Design.Bounds }+ Modify Stock { EdgeFinish Break { Face: +Z; Target: Boundary; Kind: Chamfer; Distance: 1mm } }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/direct-field.firmament b/fixtures/Regression/CompileTimeChoicesRfc/direct-field.firmamentnew file mode 100644index 00000000..da19bac9--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/direct-field.firmament@@ -0,0 +1,6 @@+Model Result {+ units: mm+ Options SizeChoice { Compact Standard }+ Static choice: SizeChoice = Compact+ Box Stock { size: [match choice { Compact => 40mm; Standard => 80mm }, 20mm, 5mm] }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/duplicate-enum-case.firmament b/fixtures/Regression/CompileTimeChoicesRfc/duplicate-enum-case.firmamentnew file mode 100644index 00000000..d51c3e5d--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/duplicate-enum-case.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard Compact }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/duplicate-selected.firmament b/fixtures/Regression/CompileTimeChoicesRfc/duplicate-selected.firmamentnew file mode 100644index 00000000..65d9e265--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/duplicate-selected.firmament@@ -0,0 +1,10 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ Compact => 70mm+ Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/empty-enum.firmament b/fixtures/Regression/CompileTimeChoicesRfc/empty-enum.firmamentnew file mode 100644index 00000000..0cee1252--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/empty-enum.firmament@@ -0,0 +1,9 @@+Options SizeChoice {}+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/enum-cycle.firmament b/fixtures/Regression/CompileTimeChoicesRfc/enum-cycle.firmamentnew file mode 100644index 00000000..0c33f525--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/enum-cycle.firmament@@ -0,0 +1,7 @@+Model Result {+ units: mm+ Options SizeChoice { Compact Standard }+ Static a: SizeChoice = b+ Static b: SizeChoice = a+ Box Stock { size: [40mm, 20mm, 5mm] }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/enum-equality.firmament b/fixtures/Regression/CompileTimeChoicesRfc/enum-equality.firmamentnew file mode 100644index 00000000..06bfcf31--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/enum-equality.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [match choice == Compact {+ true => 40mm+ false => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/feature-choice.firmament b/fixtures/Regression/CompileTimeChoicesRfc/feature-choice.firmamentnew file mode 100644index 00000000..63eb4625--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/feature-choice.firmament@@ -0,0 +1,13 @@+Model Result {+ units: mm++ Enum SizeChoice { Compact Standard }+ Feature Bore(choice: SizeChoice) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: Match choice {+ Compact => 6mm+ Standard => 10mm+ } end: ThroughAll }+ }+ Box Stock { size: [40mm, 20mm, 5mm] }+ Modify Stock { Feature mount = Bore(choice: Compact) }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/feature-default.firmament b/fixtures/Regression/CompileTimeChoicesRfc/feature-default.firmamentnew file mode 100644index 00000000..184cd74b--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/feature-default.firmament@@ -0,0 +1,10 @@+Model Result {+ units: mm++ Enum SizeChoice { Compact Standard }+ Feature Bore(choice: SizeChoice = Compact, diameter: Length = match choice { Compact => 6mm; Standard => 10mm }) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: diameter end: ThroughAll }+ }+ Box Stock { size: [40mm, 20mm, 5mm] }+ Modify Stock { Feature mount = Bore() }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/feature-local.firmament b/fixtures/Regression/CompileTimeChoicesRfc/feature-local.firmamentnew file mode 100644index 00000000..9b468eb0--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/feature-local.firmament@@ -0,0 +1,11 @@+Model Result {+ units: mm++ Enum SizeChoice { Compact Standard }+ Feature Bore(choice: SizeChoice) -> Hole<Shaft> {+ let diameter: Length = match choice { Compact => 6mm; Standard => 10mm }+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: diameter end: ThroughAll }+ }+ Box Stock { size: [40mm, 20mm, 5mm] }+ Modify Stock { Feature mount = Bore(choice: Compact) }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/feature-record-choice.firmament b/fixtures/Regression/CompileTimeChoicesRfc/feature-record-choice.firmamentnew file mode 100644index 00000000..8f127975--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/feature-record-choice.firmament@@ -0,0 +1,15 @@+Model Result {+ units: mm++ Enum SizeChoice { Compact Standard }+ Record BoreSpec { choice: SizeChoice }+ Static spec: BoreSpec = BoreSpec { choice: Compact }+ Feature Bore(spec: BoreSpec) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: Match spec.choice {+ Compact => 6mm+ Standard => 10mm+ } end: ThroughAll }+ }+ Box Stock { size: [40mm, 20mm, 5mm] }+ Modify Stock { Feature mount = Bore(spec: spec) }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/feature-reference.firmament b/fixtures/Regression/CompileTimeChoicesRfc/feature-reference.firmamentnew file mode 100644index 00000000..d6b587a5--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/feature-reference.firmament@@ -0,0 +1,3 @@+Model Result {+ units: mm+ Box Stock { size: [40mm, 20mm, 5mm] } Modify Stock { Hole<Shaft> mount { on: +Z center: Point2(0mm, 0mm) diameter: 6mm end: ThroughAll } } }diff --git a/fixtures/Regression/CompileTimeChoicesRfc/inline-arms.firmament b/fixtures/Regression/CompileTimeChoicesRfc/inline-arms.firmamentnew file mode 100644index 00000000..0d27db29--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/inline-arms.firmament@@ -0,0 +1,6 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice { Compact => 40mm; Standard => 80mm }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/integer-value-match.firmament b/fixtures/Regression/CompileTimeChoicesRfc/integer-value-match.firmamentnew file mode 100644index 00000000..c6e92470--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/integer-value-match.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: Int>+Struct Plate {+ Box Stock { Size: [Match choice {+ 4 => 40mm+ 6 => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: 4>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/lowercase-match.firmament b/fixtures/Regression/CompileTimeChoicesRfc/lowercase-match.firmamentnew file mode 100644index 00000000..a26dc5e4--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/lowercase-match.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [match choice {+ Compact => 40mm+ Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/match-call-compatibility.firmament b/fixtures/Regression/CompileTimeChoicesRfc/match-call-compatibility.firmamentnew file mode 100644index 00000000..cc5cc8b9--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/match-call-compatibility.firmament@@ -0,0 +1,8 @@+Model Result {+ units: mm+ Feature match(diameter: Length) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: diameter end: ThroughAll }+ }+ Box Stock { size: [40mm, 20mm, 5mm] }+ Modify Stock { Feature mount = match(diameter: 6mm) }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/match-cycle.firmament b/fixtures/Regression/CompileTimeChoicesRfc/match-cycle.firmamentnew file mode 100644index 00000000..b0dd5f52--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/match-cycle.firmament@@ -0,0 +1,6 @@+Model Result {+ units: mm+ Options SizeChoice { Compact Standard }+ Static a: SizeChoice = match a { Compact => Compact; Standard => Standard }+ Box Stock { size: [40mm, 20mm, 5mm] }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/missing-selected.firmament b/fixtures/Regression/CompileTimeChoicesRfc/missing-selected.firmamentnew file mode 100644index 00000000..30e5b49b--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/missing-selected.firmament@@ -0,0 +1,8 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/missing-unselected.firmament b/fixtures/Regression/CompileTimeChoicesRfc/missing-unselected.firmamentnew file mode 100644index 00000000..072e1be9--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/missing-unselected.firmament@@ -0,0 +1,8 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/nested-match.firmament b/fixtures/Regression/CompileTimeChoicesRfc/nested-match.firmamentnew file mode 100644index 00000000..a6e1d78a--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/nested-match.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => match true { true => 40mm; false => 50mm }+ Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/nominal-confusion.firmament b/fixtures/Regression/CompileTimeChoicesRfc/nominal-confusion.firmamentnew file mode 100644index 00000000..4df1d84e--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/nominal-confusion.firmament@@ -0,0 +1,8 @@+Model Result {+ units: mm+ Options LeftChoice { Compact Standard }+ Options RightChoice { Compact Standard }+ Static left: LeftChoice = Compact+ Static right: RightChoice = left+ Box Stock { size: [40mm, 20mm, 5mm] }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/nominal-record-result.firmament b/fixtures/Regression/CompileTimeChoicesRfc/nominal-record-result.firmamentnew file mode 100644index 00000000..a044f90a--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/nominal-record-result.firmament@@ -0,0 +1,13 @@+Model Result {+ units: mm+ Options SizeChoice { Compact Standard }+ Record PlateSpec { width: Length }+ Static small: PlateSpec = PlateSpec { width: 40mm }+ Static large: PlateSpec = PlateSpec { width: 80mm }+ Static choice: SizeChoice = Compact+ Record OtherSpec { width: Length }+ Static other: OtherSpec = OtherSpec { width: 80mm }+ Static selected: PlateSpec = match choice { Compact => small; Standard => other }+ Template<spec: PlateSpec> Struct Plate { Box Stock { size: [spec.width, 20mm, 5mm] } }+ Struct Result = Plate<spec: selected>+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/options-alias.firmament b/fixtures/Regression/CompileTimeChoicesRfc/options-alias.firmamentnew file mode 100644index 00000000..ba130516--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/options-alias.firmament@@ -0,0 +1,9 @@+Options SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/parenthesized-condition.firmament b/fixtures/Regression/CompileTimeChoicesRfc/parenthesized-condition.firmamentnew file mode 100644index 00000000..7e5821bb--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/parenthesized-condition.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [match (3mm > 2mm) {+ true => 40mm+ false => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/pmi-reference.firmament b/fixtures/Regression/CompileTimeChoicesRfc/pmi-reference.firmamentnew file mode 100644index 00000000..46be63e8--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/pmi-reference.firmament@@ -0,0 +1,29 @@+// One engineering requirement crosses data, specialization and recipe boundaries.+Record BoreSpec {+ diameter: Length+ width: Length+}+Static standardBore: BoreSpec = BoreSpec {+ diameter: 8mm tol +0.10mm -0.05mm+ width: 40mm+}++Template<spec: BoreSpec>+Model PlateFamily {+ units: mm+ Feature Drill(diameter: Length) -> Hole<Shaft> {+ let inspection: Length = diameter+ return Hole<Shaft> {+ on: +Z+ center: Point2(0mm, 0mm)+ diameter: inspection+ end: ThroughAll+ }+ }+ Box Body { size: [spec.width, 30mm, 8mm] }+ Modify Body { Feature Mount = Drill(diameter: spec.diameter) }+ Pmi {+ HoleDiameter MountSize { target: Mount dimension: spec.diameter }+ }+}+Model TolerancedProduct = PlateFamily<spec: standardBore>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/pmi-selected-record.firmament b/fixtures/Regression/CompileTimeChoicesRfc/pmi-selected-record.firmamentnew file mode 100644index 00000000..84d8a3f8--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/pmi-selected-record.firmament@@ -0,0 +1,34 @@+// One engineering requirement crosses data, specialization and recipe boundaries.+Record BoreSpec {+ diameter: Length+ width: Length+}+Static standardBore: BoreSpec = BoreSpec {+ diameter: 8mm tol +0.10mm -0.05mm+ width: 40mm+}++Options BoreChoice { Compact Standard }+Static largeBore: BoreSpec = BoreSpec { diameter: 10mm tol 0.2mm width: 80mm }+Static choice: BoreChoice = Compact+Static selectedBore: BoreSpec = match choice { Compact => standardBore; Standard => largeBore }++Template<spec: BoreSpec>+Model PlateFamily {+ units: mm+ Feature Drill(diameter: Length) -> Hole<Shaft> {+ let inspection: Length = diameter+ return Hole<Shaft> {+ on: +Z+ center: Point2(0mm, 0mm)+ diameter: inspection+ end: ThroughAll+ }+ }+ Box Body { size: [spec.width, 30mm, 8mm] }+ Modify Body { Feature Mount = Drill(diameter: spec.diameter) }+ Pmi {+ HoleDiameter MountSize { target: Mount dimension: spec.diameter }+ }+}+Model TolerancedProduct = PlateFamily<spec: selectedBore>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/private-template-values.firmament b/fixtures/Regression/CompileTimeChoicesRfc/private-template-values.firmamentnew file mode 100644index 00000000..1ca041f5--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/private-template-values.firmament@@ -0,0 +1,10 @@+Template<width: Length>+Model Family {+ units: mm+ Options SizeChoice { Compact Standard }+ Record LocalSpec { kind: SizeChoice }+ Static config: LocalSpec = LocalSpec { kind: Compact }+ Static thickness: Length = match config.kind { Compact => 5mm; Standard => 10mm }+ Box Stock { size: [width, 20mm, thickness] }+}+Model Result = Family<width: 40mm>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/qualified-cases.firmament b/fixtures/Regression/CompileTimeChoicesRfc/qualified-cases.firmamentnew file mode 100644index 00000000..20f6f38a--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/qualified-cases.firmament@@ -0,0 +1,9 @@+Options SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ SizeChoice.Compact => 40mm+ SizeChoice.Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/record-choice.firmament b/fixtures/Regression/CompileTimeChoicesRfc/record-choice.firmamentnew file mode 100644index 00000000..2685dfc9--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/record-choice.firmament@@ -0,0 +1,11 @@+Enum SizeChoice { Compact Standard }+Record PlateSpec { choice: SizeChoice }+Static compact: PlateSpec = PlateSpec { choice: Compact }+Template<spec: PlateSpec>+Struct Plate {+ Box Stock { Size: [Match spec.choice {+ Compact => 40mm+ Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<spec: compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/record-result.firmament b/fixtures/Regression/CompileTimeChoicesRfc/record-result.firmamentnew file mode 100644index 00000000..2ca1aa92--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/record-result.firmament@@ -0,0 +1,11 @@+Model Result {+ units: mm+ Options SizeChoice { Compact Standard }+ Record PlateSpec { width: Length }+ Static small: PlateSpec = PlateSpec { width: 40mm }+ Static large: PlateSpec = PlateSpec { width: 80mm }+ Static choice: SizeChoice = Compact+ Static selected: PlateSpec = match choice { Compact => small; Standard => large }+ Template<spec: PlateSpec> Struct Plate { Box Stock { size: [spec.width, 20mm, 5mm] } }+ Struct Result = Plate<spec: selected>+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/record-with-result.firmament b/fixtures/Regression/CompileTimeChoicesRfc/record-with-result.firmamentnew file mode 100644index 00000000..2fd7d139--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/record-with-result.firmament@@ -0,0 +1,11 @@+Model Result {+ units: mm+ Options SizeChoice { Compact Standard }+ Record PlateSpec { width: Length }+ Static small: PlateSpec = PlateSpec { width: 40mm }+ Static large: PlateSpec = PlateSpec { width: 80mm }+ Static choice: SizeChoice = Compact+ Static selected: PlateSpec = match choice { Compact => large with { width: 40mm }; Standard => large }+ Template<spec: PlateSpec> Struct Plate { Box Stock { size: [spec.width, 20mm, 5mm] } }+ Struct Result = Plate<spec: selected>+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/reordered-arms.firmament b/fixtures/Regression/CompileTimeChoicesRfc/reordered-arms.firmamentnew file mode 100644index 00000000..39303507--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/reordered-arms.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Standard => 80mm+ Compact => 40mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/run.py b/fixtures/Regression/CompileTimeChoicesRfc/run.pynew file mode 100644index 00000000..07d79a6f--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/run.py@@ -0,0 +1,87 @@+"""Evaluate the choices RFC against the production CLI; known RFC gaps fail.++No fixture is rewritten and no geometry reference is recorded automatically.+Run from any directory after building Aetheris.CLI in Release.+"""+import argparse+import hashlib+import json+from pathlib import Path+import subprocess+++def main():+ root = Path(__file__).resolve().parent+ repo = root.parents[2]+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--output", type=Path, default=repo / "artifacts/local/compile-time-choices")+ args = parser.parse_args()+ output = args.output.resolve()+ output.mkdir(parents=True, exist_ok=True)+ cli = repo / "Aetheris.CLI/bin/Release/net10.0/aetheris.dll"++ def invoke(*arguments):+ result = subprocess.run(["dotnet", str(cli), *map(str, arguments), "--json"],+ cwd=repo, capture_output=True, text=True, timeout=90)+ try:+ payload = json.loads(result.stdout)+ except ValueError as error:+ raise RuntimeError(f"CLI did not return JSON: {result.stdout}\n{result.stderr}") from error+ return result.returncode, payload++ cases = json.loads((root / "cases.json").read_text(encoding="utf-8"))+ results = []+ for case in cases:+ name = case["name"]+ source = root / (name + ".firmament")+ step = output / (name + ".step")+ validation_code, validation = invoke("validate", source)+ build_code, build = invoke("build", source, "--output", step)+ admitted = build_code == 0 and build.get("success") is True+ validated = validation_code == 0 and validation.get("firmamentV2Validation", {}).get("status") == "valid"+ row = dict(name=name, shouldBuild=case["shouldBuild"], validated=validated,+ built=admitted, agreement=validated == admitted,+ meetsRfc=admitted == case["shouldBuild"], reference=case["reference"])+ expected_code = case.get("diagnostic")+ if expected_code:+ def contains_code(payload):+ return any(isinstance(d, dict) and+ (d.get("code") == expected_code or+ str(d.get("code", "")).startswith(expected_code + ":"))+ for d in payload.get("diagnostics", []))+ row["diagnosticMatches"] = (contains_code(build) and+ contains_code(validation.get("firmamentV2Validation", {})))+ row["meetsRfc"] &= row["diagnosticMatches"]+ row["canonicalDiagnosticCodes"] = all(+ d["code"] == expected_code+ for payload in (build, validation.get("firmamentV2Validation", {}))+ for d in payload.get("diagnostics", [])+ if isinstance(d, dict) and str(d.get("code", "")).startswith(expected_code))+ if admitted:+ analysis_code, analysis = invoke("analyze", step)+ if analysis_code != 0:+ raise RuntimeError(f"STEP analysis failed for {name}: {analysis}")+ summary = analysis["summary"]+ row["geometry"] = {key: summary[key] for key in+ ("bodyCount", "shellCount", "faceCount", "edgeCount", "vertexCount", "boundingBox", "surfaceFamilies")}+ row["stepSha256"] = hashlib.sha256(step.read_bytes()).hexdigest()+ (output / (name + ".json")).write_text(json.dumps(dict(validation=validation, build=build), indent=2) + "\n")+ results.append(row)++ by_name = {row["name"]: row for row in results}+ for row in results:+ if row["built"] and row["reference"]:+ reference = by_name[row["reference"]]+ row["geometryMatchesReference"] = row["geometry"] == reference.get("geometry")+ row["stepMatchesReference"] = row["stepSha256"] == reference.get("stepSha256")+ row["meetsRfc"] &= row["geometryMatchesReference"]+ label = "PASS" if row["meetsRfc"] and row["agreement"] else "GAP"+ print(f"{label:4} {row['name']:30} validate={row['validated']} build={row['built']}")+ (output / "results.json").write_text(json.dumps(results, indent=2) + "\n")+ passed = sum(row["meetsRfc"] and row["agreement"] for row in results)+ print(f"RFC requirements met: {passed}/{len(results)}; evidence: {output}")+ return 0 if passed == len(results) else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/fixtures/Regression/CompileTimeChoicesRfc/scoped-choice.firmament b/fixtures/Regression/CompileTimeChoicesRfc/scoped-choice.firmamentnew file mode 100644index 00000000..8cf6d464--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/scoped-choice.firmament@@ -0,0 +1,9 @@+Options SizeChoice { Compact Standard }+Template<choice: SizeChoice> Struct Ignored { Box Unused { size: [1mm, 1mm, 1mm] } }+Model Result {+ units: mm+ Options SizeChoice { Small Large }+ Static choice: SizeChoice = Small+ Static width: Length = match choice { Small => 40mm; Large => 80mm }+ Box Stock { size: [width, 20mm, 5mm] }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/standard-reference.firmament b/fixtures/Regression/CompileTimeChoicesRfc/standard-reference.firmamentnew file mode 100644index 00000000..931ffb99--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/standard-reference.firmament@@ -0,0 +1 @@+Struct Result { Box Stock { Size: [80mm, 20mm, 5mm] } }diff --git a/fixtures/Regression/CompileTimeChoicesRfc/static-choice.firmament b/fixtures/Regression/CompileTimeChoicesRfc/static-choice.firmamentnew file mode 100644index 00000000..6a564a24--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/static-choice.firmament@@ -0,0 +1,7 @@+Model Result {+ units: mm+ Enum SizeChoice { Compact Standard }+ Static choice: SizeChoice = Compact+ Static width: Length = Match choice { Compact => 40mm; Standard => 80mm }+ Box Stock { Size: [width, 20mm, 5mm] }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/template-compact.firmament b/fixtures/Regression/CompileTimeChoicesRfc/template-compact.firmamentnew file mode 100644index 00000000..d5967063--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/template-compact.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/template-default.firmament b/fixtures/Regression/CompileTimeChoicesRfc/template-default.firmamentnew file mode 100644index 00000000..37e26b89--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/template-default.firmament@@ -0,0 +1,6 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice = Compact, width: Length = match choice { Compact => 40mm; Standard => 80mm }>+Struct Plate {+ Box Stock { Size: [width, 20mm, 5mm] }+}+Struct Result = Plate<>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/template-standard.firmament b/fixtures/Regression/CompileTimeChoicesRfc/template-standard.firmamentnew file mode 100644index 00000000..20136f5e--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/template-standard.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Standard>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/unknown-arm.firmament b/fixtures/Regression/CompileTimeChoicesRfc/unknown-arm.firmamentnew file mode 100644index 00000000..2948258d--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/unknown-arm.firmament@@ -0,0 +1,10 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ Standard => 80mm+ Imaginary => 90mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/unknown-choice.firmament b/fixtures/Regression/CompileTimeChoicesRfc/unknown-choice.firmamentnew file mode 100644index 00000000..270c7b8e--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/unknown-choice.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ Standard => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Imaginary>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/unresolved-unselected.firmament b/fixtures/Regression/CompileTimeChoicesRfc/unresolved-unselected.firmamentnew file mode 100644index 00000000..16a06023--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/unresolved-unselected.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ Standard => MissingLength+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/unselected-division.firmament b/fixtures/Regression/CompileTimeChoicesRfc/unselected-division.firmamentnew file mode 100644index 00000000..3ad4870d--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/unselected-division.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ Standard => (80mm / 0)+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/unselected-invalid-tolerance.firmament b/fixtures/Regression/CompileTimeChoicesRfc/unselected-invalid-tolerance.firmamentnew file mode 100644index 00000000..20a8a4a0--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/unselected-invalid-tolerance.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ Standard => 80mm tol 0.1deg+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/unselected-spatial-field.firmament b/fixtures/Regression/CompileTimeChoicesRfc/unselected-spatial-field.firmamentnew file mode 100644index 00000000..fec23d67--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/unselected-spatial-field.firmament@@ -0,0 +1,16 @@+Enum SizeChoice {+ Compact+ Standard+}+Concept Struct Design {+ choice: SizeChoice = Compact+ Bounds: Match choice {+ Compact => Box3 { Size: [40mm, 20mm, 5mm] }+ Standard => Box3 { size: [80mm, 20mm, 5mm] heigth: 7mm }+ }+ TopPlane: Bounds.Face(+Z)+}+Struct Result {+ Box Stock { Bounds: Design.Bounds }+ Modify Stock { EdgeFinish Break { Face: +Z; Target: Boundary; Kind: Chamfer; Distance: 1mm } }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/unselected-spatial-name.firmament b/fixtures/Regression/CompileTimeChoicesRfc/unselected-spatial-name.firmamentnew file mode 100644index 00000000..4ce6ad81--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/unselected-spatial-name.firmament@@ -0,0 +1,16 @@+Enum SizeChoice {+ Compact+ Standard+}+Concept Struct Design {+ choice: SizeChoice = Compact+ Bounds: Match choice {+ Compact => Box3 { Size: [40mm, 20mm, 5mm] }+ Standard => Box3 { Size: [MissingWidth, 20mm, 5mm] }+ }+ TopPlane: Bounds.Face(+Z)+}+Struct Result {+ Box Stock { Bounds: Design.Bounds }+ Modify Stock { EdgeFinish Break { Face: +Z; Target: Boundary; Kind: Chamfer; Distance: 1mm } }+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/unused-incomplete-feature.firmament b/fixtures/Regression/CompileTimeChoicesRfc/unused-incomplete-feature.firmamentnew file mode 100644index 00000000..e52661ca--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/unused-incomplete-feature.firmament@@ -0,0 +1,12 @@+Model Result {+ units: mm++ Enum SizeChoice { Compact Standard }+ Feature Bore(choice: SizeChoice) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: Match choice {+ Compact => 6mm+ } end: ThroughAll }+ }+ Box Stock { size: [40mm, 20mm, 5mm] }+ Modify Stock {}+}diff --git a/fixtures/Regression/CompileTimeChoicesRfc/unused-incomplete-template.firmament b/fixtures/Regression/CompileTimeChoicesRfc/unused-incomplete-template.firmamentnew file mode 100644index 00000000..077a4d5a--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/unused-incomplete-template.firmament@@ -0,0 +1,8 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ }, 20mm, 5mm] }+}+Struct Result { Box Stock { Size: [40mm, 20mm, 5mm] } }diff --git a/fixtures/Regression/CompileTimeChoicesRfc/wildcard.firmament b/fixtures/Regression/CompileTimeChoicesRfc/wildcard.firmamentnew file mode 100644index 00000000..c40fabb9--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/wildcard.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ _ => 80mm+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>diff --git a/fixtures/Regression/CompileTimeChoicesRfc/wrong-unselected-dimension.firmament b/fixtures/Regression/CompileTimeChoicesRfc/wrong-unselected-dimension.firmamentnew file mode 100644index 00000000..c9edfb89--- /dev/null+++ b/fixtures/Regression/CompileTimeChoicesRfc/wrong-unselected-dimension.firmament@@ -0,0 +1,9 @@+Enum SizeChoice { Compact Standard }+Template<choice: SizeChoice>+Struct Plate {+ Box Stock { Size: [Match choice {+ Compact => 40mm+ Standard => 80deg+ }, 20mm, 5mm] }+}+Struct Result = Plate<choice: Compact>