Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Improve Firmament modeling and assembly workflows

Yuechen Li263f01282f36
diff --git a/Aetheris.CLI.Tests/FirmamentFrontendX2CliTests.cs b/Aetheris.CLI.Tests/FirmamentFrontendX2CliTests.cs
new file mode 100644
index 00000000..52079bb3
--- /dev/null
+++ b/Aetheris.CLI.Tests/FirmamentFrontendX2CliTests.cs
@@ -0,0 +1,78 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class FirmamentFrontendX2CliTests
+{
+ [Fact]
+ public void ExplainReportsTheActualFeatureScopeAndExpansionWithoutClaimingCompleteMaps()
+ {
+ var path = Fixture("scoped-drill.firmament"); var stdout = new StringWriter();
+ Assert.Equal(0, CliRunner.Run(["validate", path, "--json", "--explain"], stdout, new StringWriter()));
+ using var json = JsonDocument.Parse(stdout.ToString());
+ Assert.Equal("valid", json.RootElement.GetProperty("firmamentV2Validation").GetProperty("status").GetString());
+ var semantics = json.RootElement.GetProperty("frontendSemantics");
+ Assert.Equal("UnifiedAstFeature", semantics.GetProperty("featureOwner").GetString());
+ var invocation = Assert.Single(semantics.GetProperty("featureInvocations").EnumerateArray());
+ Assert.Equal("document/Model ScopedPlate", invocation.GetProperty("bindingScope").GetString());
+ Assert.Equal("Drill", invocation.GetProperty("definitionOrigin").GetProperty("binding").GetString());
+ Assert.Equal("inline", invocation.GetProperty("invocationOrigin").GetProperty("sourceFile").GetString());
+ Assert.Contains("pending", semantics.GetProperty("sourceProvenance").GetString());
+ }
+
+ [Theory]
+ [InlineData("sibling-feature.invalid.firmament", "firmament-feature-unknown:Local", 8)]
+ [InlineData("sibling-data.invalid.firmament", "firmament-binding-name-not-visible:secret", 6)]
+ public void UnresolvedSiblingIsRejectedByValidateAndBuildWithTheAuthoredLocation(string fixture, string code, int line)
+ {
+ var path = Fixture(fixture); var validation = new StringWriter();
+ Assert.Equal(1, CliRunner.Run(["validate", path, "--json"], validation, new StringWriter()));
+ using var json = JsonDocument.Parse(validation.ToString());
+ var diagnostic = Assert.Single(json.RootElement.GetProperty("firmamentV2Validation").GetProperty("diagnostics").EnumerateArray(),
+ d => d.GetProperty("code").GetString()!.StartsWith(code, StringComparison.Ordinal));
+ Assert.Equal(code, diagnostic.GetProperty("code").GetString());
+ Assert.Equal(line, diagnostic.GetProperty("line").GetInt32());
+ Assert.Contains("not visible", diagnostic.GetProperty("message").GetString());
+ var directory = Path.Combine(Path.GetTempPath(), "aetheris-x2-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(directory);
+ try
+ {
+ var output = Path.Combine(directory, "part.step"); var stdout = new StringWriter();
+ Assert.Equal(1, CliRunner.Run(["build", path, "--output", output, "--json"], stdout, new StringWriter()));
+ Assert.False(File.Exists(output));
+ Assert.Contains(code, stdout.ToString());
+ }
+ finally { Directory.Delete(directory, true); }
+ }
+
+ [Fact]
+ public void TemplateShadowingAndSiblingRejectionUseTheNormalAdmissionPath()
+ {
+ var stdout = new StringWriter();
+ Assert.Equal(0, CliRunner.Run(["validate", Fixture("template-shadowing.firmament"), "--json", "--explain"], stdout, new StringWriter()));
+ using var positive = JsonDocument.Parse(stdout.ToString());
+ var semantics = positive.RootElement.GetProperty("frontendSemantics");
+ Assert.Contains("UnifiedAstTemplate", semantics.GetProperty("templateOwner").GetString());
+ var receipt = Assert.Single(semantics.GetProperty("templateInstantiations").EnumerateArray());
+ Assert.Equal("30mm", receipt.GetProperty("valueArguments").GetProperty("width").GetString());
+ Assert.StartsWith("document/Model LocalFamily", receipt.GetProperty("definitionScope").GetString());
+ stdout = new StringWriter();
+ var path = Fixture("sibling-template.invalid.firmament");
+ Assert.Equal(1, CliRunner.Run(["validate", path, "--json"], stdout, new StringWriter()));
+ using var negative = JsonDocument.Parse(stdout.ToString());
+ var diagnostic = Assert.Single(negative.RootElement.GetProperty("firmamentV2Validation").GetProperty("diagnostics").EnumerateArray(),
+ d => d.GetProperty("code").GetString() == "firmament-template-not-found:Family");
+ Assert.Equal(8, diagnostic.GetProperty("line").GetInt32());
+ Assert.Contains("not visible", diagnostic.GetProperty("message").GetString());
+ var directory = Path.Combine(Path.GetTempPath(), "aetheris-x2-template-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(directory);
+ try
+ {
+ var output = Path.Combine(directory, "part.step");
+ Assert.Equal(1, CliRunner.Run(["build", path, "--output", output, "--json"], new StringWriter(), new StringWriter()));
+ Assert.False(File.Exists(output));
+ }
+ finally { Directory.Delete(directory, true); }
+ }
+ private static string Fixture(string file) => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,
+ "../../../../fixtures/Regression/FrontendX2", file));
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 3d511246..010f233b 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -1760,6 +1760,10 @@ Model CanonicalPanel {
invocation.ExpandedSemanticKind,
invocation.GeneratedByFeature,
invocation.ResultIdentity,
+ invocation.BindingScope,
+ invocation.DefinitionOrigin,
+ invocation.InvocationOrigin,
+ invocation.ExpansionChain,
invocation.Status
}).ToArray() ?? [],
featureExpansion = document?.FeatureExpansion,
@@ -2519,11 +2523,32 @@ Model CanonicalPanel {
if (report.Status != "invalid") report = report with { Status = "parsed-not-built" };
}
else report = FirmamentBuildAdmissionValidation.Admit(report, authoredValidationSource, Path.GetDirectoryName(Path.GetFullPath(sourcePath)));
- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = report }, JsonOptions));
+ if (json && explain) stdout.WriteLine(JsonSerializer.Serialize(new
+ {
+ firmamentV2Validation = report,
+ frontendSemantics = new
+ {
+ featureOwner = "UnifiedAstFeature",
+ featureExpansion = parse.Document?.FeatureExpansion,
+ featureDefinitions = parse.Document?.FeatureDefinitions,
+ featureInvocations = parse.Document?.FeatureInvocations,
+ patternOwner = "CanonicalStaticAuthoring (AST mapping; source catalog adapter)",
+ patterns = parse.Document?.StaticAuthoring?.Patterns,
+ templateOwner = "UnifiedAstTemplate (lexical binding; Record/Match/body source adapters)",
+ templateInstantiations = parse.Document?.TemplateInstantiations,
+ dataOwner = "UnifiedAstData (lexical identities; shared typed catalog)",
+ dataBindings = parse.Document?.DataBindings,
+ sourceProvenance = "Original Feature definition/use anchors where retained; complete include/Template maps pending",
+ rejectionStage = report.Diagnostics.FirstOrDefault(d => d.Severity is "error" or "fatal")?.Stage
+ }
+ }, JsonOptions));
+ else if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = report }, JsonOptions));
else stdout.WriteLine($"Firmament V2 validation: {report.Status} ({report.Summary.FatalDiagnosticCount} fatal, {report.Summary.WarningDiagnosticCount} warning)");
if (!json)
{
if (explain) stdout.WriteLine($"Language: {report.LanguageVersion}; parser route: {report.ParserRoute ?? "Expansion/Unselected"}; admission: {report.ValidationLevel}; templates: {parse.Document?.TemplateInstantiations?.Count ?? 0}; solids: {parse.Document?.Solids.Count ?? 0}");
+ if (explain && parse.Document?.FeatureExpansion is { } expansion)
+ stdout.WriteLine($"Feature owner: UnifiedAstFeature; definitions: {expansion.DefinitionCount}; invocations: {expansion.InvocationCount}; expanded declarations: {expansion.ExpandedSemanticNodeCount}");
foreach (var diagnostic in report.Diagnostics)
stderr.WriteLine($"{sourcePath}({diagnostic.Line},{diagnostic.Column}): {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");
}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentCompileTimeValueBindingTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentCompileTimeValueBindingTests.cs
index c0ce66f3..54d0a624 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentCompileTimeValueBindingTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentCompileTimeValueBindingTests.cs
@@ -161,6 +161,10 @@ public sealed class FirmamentCompileTimeValueBindingTests
Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
Assert.Contains(parsed.Document!.BoundLets!, v => v.Origins.Any(o => o.Binding == "Template PlateFamily.spec.diameter")
&& v.Origins.Any(o => o.Binding == "Feature Drill.spec.diameter") && v.Tolerance?.Plus == 0.1);
+ var arguments = Assert.Single(parsed.Document.FeatureInvocations!).Arguments;
+ Assert.Contains("spec", arguments.Keys);
+ Assert.Contains("spec.diameter", arguments.Keys);
+ Assert.Contains("spec.width", arguments.Keys);
Assert.True(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
var wrongType = source.Replace("Feature Drill(spec: BoreSpec)", "Record OtherSpec { diameter: Length }\nFeature Drill(spec: OtherSpec)");
Assert.False(FirmamentBuildAndExport.CompileSource(wrongType, null).IsSuccess);
@@ -308,6 +312,9 @@ public sealed class FirmamentCompileTimeValueBindingTests
Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
Assert.Contains(parsed.Document!.BoundLets!, v => v.Origins.Any(o => o.Binding == "Template PlateFamily.spec.bore.diameter")
&& v.Origins.Any(o => o.Binding == "Feature Drill.spec.bore.diameter") && v.Tolerance?.Plus == 0.10);
+ var arguments = Assert.Single(parsed.Document.FeatureInvocations!).Arguments;
+ Assert.Contains("spec.bore.diameter", arguments.Keys);
+ Assert.Contains("spec.bore.width", arguments.Keys);
Assert.True(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
}
}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX2Tests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX2Tests.cs
new file mode 100644
index 00000000..abd1f959
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX2Tests.cs
@@ -0,0 +1,515 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentFrontendX2Tests
+{
+ [Fact]
+ public void ExistingPanelRadianAdmissionPreservesSurfaceCoordinates()
+ {
+ var source = File.ReadAllText(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,
+ "../../../../fixtures/Regression/FrontendX2/panel-radians.firmament")));
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.True(parse.IsSuccess, string.Join("\n", parse.Diagnostics));
+ var panel = Assert.Single(parse.Document!.Panels!);
+ var start = panel.SurfaceConstruction.Evaluate(0, 0);
+ var end = panel.SurfaceConstruction.Evaluate(1, 1);
+ Assert.Equal(10 * Math.Cos(0.25), start.X, 10); Assert.Equal(10 * Math.Sin(0.25), start.Y, 10); Assert.Equal(0, start.Z, 10);
+ Assert.Equal(10 * Math.Cos(0.75), end.X, 10); Assert.Equal(10 * Math.Sin(0.75), end.Y, 10); Assert.Equal(5, end.Z, 10);
+ var build = FirmamentBuildAndExport.CompileSource(source);
+ Assert.False(build.IsSuccess);
+ Assert.Contains(build.Diagnostics, d => d.Message.Contains("firmament-panel-only-step-materialization-unsupported"));
+ }
+
+ [Fact]
+ public void NamedInvocationCannotDiscardPlacementFromAnOtherwiseBuildablePart()
+ {
+ const string source = """
+ Model Plate {
+ units: mm
+ Feature Drill() -> Hole<Shaft> {
+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: 6mm end: ThroughAll }
+ }
+ Box stock { size: [30mm, 20mm, 8mm] }
+ Modify stock { Feature bore = Drill() }
+ }
+ """;
+ var ordinary = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(ordinary.IsSuccess, string.Join("\n", ordinary.Diagnostics));
+ var unsupported = source.Replace("Feature bore =", "Feature bore on XZ =");
+ var parse = FirmamentV2Parser.Parse(unsupported);
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(parse.SyntaxDiagnostics, d => d.Code == "firmament-feature-body-unsupported:invocation-header"
+ && d.Message.Contains("placement") && d.SourceSpan is not null);
+ Assert.False(FirmamentBuildAndExport.CompileSource(unsupported).IsSuccess);
+ }
+
+ [Theory]
+ [InlineData("Feature<> Make() -> Hole<Shaft> { return Hole<Shaft> { diameter: 6mm } } Make()")]
+ [InlineData("Feature Make(p: \"Profile\") -> Boss { return Boss { Profile: p Height: 2mm } } Make(Shape)")]
+ [InlineData("Feature Make() -> Hole<Shaft> { let p: \"Length\" = 6mm; return Hole<Shaft> { diameter: p } } Make()")]
+ [InlineData("Feature Make() -> Hole<Shaft> { return Hole<Shaft> Named { diameter: 6mm } } Make()")]
+ [InlineData("Feature Make() -> Hole<Shaft> { return Hole<Shaft> { diameter: 6mm } } Feature result on XZ = Make()")]
+ [InlineData("Feature Make() -> Hole<Shaft> { return Hole<Shaft> { diameter: 6mm } } Feature result() = Make()")]
+ [InlineData("Feature Make() -> Hole<Shaft> { Circle2 Outline() { radius: 2mm } return Hole<Shaft> { diameter: 6mm } } Make()")]
+ public void MalformedFeatureTypeHeadersCannotBecomeIgnoredIntent(string body)
+ {
+ var source = "Model P { units: mm " + body + " }";
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.False(parse.IsSuccess);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ Assert.Contains(parse.Diagnostics, d => d.StartsWith("firmament-feature-"));
+ }
+
+ [Fact]
+ public void TemplateShadowingBindsTheNearestDefinitionAndPreservesConcreteGeometry()
+ {
+ var source = File.ReadAllText(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,
+ "../../../../fixtures/Regression/FrontendX2/template-shadowing.firmament")));
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var instance = Assert.Single(parsed.Document!.TemplateInstantiations!);
+ Assert.Equal("30mm", instance.ValueArguments["width"]);
+ Assert.StartsWith("document/Model LocalFamily", instance.DefinitionScope);
+ Assert.Equal(instance.DefinitionScope, instance.BindingScope);
+ Assert.Equal(source.LastIndexOf("Template<", StringComparison.Ordinal), instance.TemplateSourceSpan.Start);
+ var actual = FirmamentBuildAndExport.CompileSource(source);
+ var concrete = FirmamentBuildAndExport.CompileSource("Model LocalFamily { units: mm Struct product { Box stock { size: [30mm, 20mm, 6mm] } } }");
+ Assert.True(actual.IsSuccess, string.Join("\n", actual.Diagnostics));
+ Assert.True(concrete.IsSuccess, string.Join("\n", concrete.Diagnostics));
+ Assert.Equal(concrete.Value!.StepText, actual.Value!.StepText);
+ }
+
+ [Fact]
+ public void NestedTemplateCallsResolveAtDefinitionScopeRatherThanCallerScope()
+ {
+ const string source = """
+ Template<> Struct Family { Box stock { size: [10mm, 20mm, 6mm] } }
+ Template<> Struct Outer { Struct nested = Family<> }
+ Model Plate {
+ units: mm
+ Template<> Struct Family { Box stock { size: [30mm, 20mm, 6mm] } }
+ Struct product = Outer<>
+ }
+ """;
+ var actual = FirmamentBuildAndExport.CompileSource(source);
+ var concrete = FirmamentBuildAndExport.CompileSource("Model Plate { units: mm Struct product { Box stock { size: [10mm, 20mm, 6mm] } } }");
+ Assert.True(actual.IsSuccess, string.Join("\n", actual.Diagnostics));
+ Assert.True(concrete.IsSuccess, string.Join("\n", concrete.Diagnostics));
+ Assert.Equal(concrete.Value!.StepText, actual.Value!.StepText);
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.Equal(["Outer", "Family"], parse.Document!.TemplateInstantiations!.Select(i => i.Template));
+ }
+
+ [Fact]
+ public void TemplateSiblingVisibilityAndSameScopeDuplicatesRejectInProduction()
+ {
+ const string sibling = """
+ Model Other { Template<> Struct Family { Box stock { size: [10mm, 20mm, 6mm] } } }
+ Model Plate { units: mm Struct product = Family<> }
+ """;
+ var parsed = FirmamentV2Parser.Parse(sibling);
+ Assert.False(parsed.IsSuccess);
+ Assert.Contains("firmament-template-not-found:Family", parsed.Diagnostics);
+ var located = Assert.Single(parsed.SyntaxDiagnostics, d => d.Code == "firmament-template-not-found:Family");
+ Assert.Equal("Template binding", located.Stage);
+ Assert.True(located.IsOriginalSource);
+ Assert.Equal(sibling.IndexOf("Struct product", StringComparison.Ordinal), located.SourceSpan!.Start);
+ Assert.False(FirmamentBuildAndExport.CompileSource(sibling).IsSuccess);
+ const string duplicate = "Template<> Struct Family {} Template<> Struct Family {} Struct product = Family<>";
+ Assert.Contains("firmament-template-duplicate-name:Family", FirmamentV2Parser.Parse(duplicate).Diagnostics);
+ Assert.False(FirmamentBuildAndExport.CompileSource(duplicate).IsSuccess);
+ }
+
+ [Fact]
+ public void TemplateCycleDetectionUsesLexicalDeclarationsNotUnqualifiedNames()
+ {
+ const string source = """
+ Template<> Struct Family { Box stock { size: [10mm, 20mm, 6mm] } }
+ Template<> Struct Outer {
+ Template<> Struct Family { Struct next = Outer<> }
+ Struct nested = Family<>
+ }
+ Model Plate { units: mm Struct product = Outer<> }
+ """;
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(parse.Diagnostics, d => d.StartsWith("firmament-template-recursive-specialization:"));
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Theory]
+ [InlineData("Template<> Struct Family on XZ { Box stock { size: [10mm, 20mm, 6mm] } } Struct product = Family<>")]
+ [InlineData("Template<> Struct Family { Box stock { size: [10mm, 20mm, 6mm] } } Struct product on XZ = Family<>")]
+ [InlineData("Template<> Template<> Struct Family {} Struct product = Family<>")]
+ [InlineData("Template<> Struct<> Family {} Struct product = Family<>")]
+ public void TemplateHeadersCannotDiscardPlacement(string source)
+ {
+ Assert.False(FirmamentV2Parser.Parse(source).IsSuccess);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Fact]
+ public void ScopedRecordSchemasDoNotCaptureAnUnrelatedOuterValue()
+ {
+ var source = File.ReadAllText(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,
+ "../../../../fixtures/Regression/FrontendX2/record-shadowing.firmament")));
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.True(parse.IsSuccess, string.Join("\n", parse.Diagnostics));
+ var actual = FirmamentBuildAndExport.CompileSource(source);
+ var concrete = FirmamentBuildAndExport.CompileSource("Model LocalRecord { units: mm Struct product { Box stock { size: [30mm, 20mm, 6mm] } } }");
+ Assert.True(actual.IsSuccess, string.Join("\n", actual.Diagnostics));
+ Assert.True(concrete.IsSuccess, string.Join("\n", concrete.Diagnostics));
+ Assert.Equal(concrete.Value!.StepText, actual.Value!.StepText);
+ }
+
+ [Fact]
+ public void HostTemplateExportsAreDocumentScopedAndUseTheSameLexicalBinder()
+ {
+ const string source = """
+ Template<width: Length = 10mm> Struct Family { Box stock { size: [width, 20mm, 6mm] } }
+ Model Other { Template<width: Length = 30mm> Struct Family { Box stock { size: [width, 20mm, 6mm] } } }
+ """;
+ var exported = FirmamentTemplateHostBridge.Inspect(source, out var diagnostics);
+ Assert.Empty(diagnostics);
+ Assert.Equal("10mm", Assert.Single(Assert.Single(exported).Parameters).DefaultExpression);
+ var expanded = FirmamentTemplateHostBridge.Expand(source, "Family", "product", new Dictionary<string, FirmamentHostArgument>(), out diagnostics);
+ Assert.NotNull(expanded);
+ Assert.Empty(diagnostics);
+ Assert.Contains("10mm", expanded.ExpandedSource);
+ Assert.DoesNotContain("30mm", expanded.ExpandedSource);
+ }
+
+ [Fact]
+ public void AstTemplateParametersPreserveQuotedCommasAndIgnoreCommentDeclarations()
+ {
+ const string source = """
+ // Template<> Struct Family { misleading { braces }
+ Template<label: String = "left, right", width: Length = 10mm> Struct Family {
+ Box stock { size: [width, 20mm, 6mm] }
+ }
+ Model Plate { units: mm Struct product = Family<> }
+ """;
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\\n", parsed.Diagnostics));
+ Assert.Equal("\"left, right\"", Assert.Single(parsed.Document!.TemplateInstantiations!).ValueArguments["label"]);
+ var actual = FirmamentBuildAndExport.CompileSource(source);
+ var concrete = FirmamentBuildAndExport.CompileSource("Model Plate { units: mm Struct product { Box stock { size: [10mm, 20mm, 6mm] } } }");
+ Assert.True(actual.IsSuccess, string.Join("\\n", actual.Diagnostics));
+ Assert.True(concrete.IsSuccess, string.Join("\\n", concrete.Diagnostics));
+ Assert.Equal(concrete.Value!.StepText, actual.Value!.StepText);
+ }
+
+ [Fact]
+ public void SameNamedTemplatesInDifferentScopesHaveDistinctDeterministicIdentities()
+ {
+ const string source = """
+ Template<> Struct Family { Box stock { size: [10mm, 20mm, 6mm] } }
+ Struct product = Family<>
+ Model Plate {
+ Template<> Struct Family { Box stock { size: [10mm, 20mm, 7mm] } }
+ Struct product = Family<>
+ }
+ """;
+ var first = FirmamentTemplateSourceCompiler.Expand(source, out var diagnostics);
+ Assert.Empty(diagnostics); Assert.NotNull(first);
+ var identities = first.Instantiations.Select(i => i.SpecializationIdentity).ToArray();
+ Assert.Equal(2, identities.Distinct().Count());
+ var second = FirmamentTemplateSourceCompiler.Expand(source, out diagnostics);
+ Assert.Empty(diagnostics); Assert.NotNull(second);
+ Assert.Equal(identities, second.Instantiations.Select(i => i.SpecializationIdentity));
+ }
+
+ [Theory]
+ [InlineData("Template<> Struct Product { Construct Company.Geometry.Part body { width: 10mm } }")]
+ [InlineData("Template<force: float> Model Product { units mm analysis LinearElastic Study { force Load { vector: [force N, 0N, 0N] } } }")]
+ public void SharedSyntaxRepresentsExistingHostCapabilityAndAnalysisProductions(string source)
+ {
+ var syntax = FirmamentSyntaxParser.Parse(source);
+ Assert.True(syntax.IsSuccess, string.Join("\n", syntax.Diagnostics));
+ Assert.Single(FirmamentTemplateHostBridge.Inspect(source, out var diagnostics));
+ Assert.Empty(diagnostics);
+ }
+
+ [Fact]
+ public void MalformedTemplatePrefixCannotDisappearWhenStructuralRecoveryLosesItsDeclaration()
+ {
+ const string source = "Template<width: Length Struct Family {} Struct product = Family<>";
+ Assert.False(FirmamentSyntaxParser.Parse(source).IsSuccess);
+ Assert.Null(FirmamentTemplateSourceCompiler.Expand(source, out var diagnostics));
+ Assert.Contains(diagnostics, d => d.StartsWith("firmament-template-syntax:"));
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Fact]
+ public void PatternSymbolCannotRewriteFieldLabelsOrGeneratedIdentity()
+ {
+ var source = File.ReadAllText(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,
+ "../../../../fixtures/Regression/FrontendX2/pattern-symbol-collision.firmament")));
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.True(parse.IsSuccess, string.Join("\n", parse.Diagnostics));
+ var pattern = Assert.Single(parse.Document!.StaticAuthoring!.Patterns);
+ Assert.Equal(["holes.left", "holes.right"], pattern.GeneratedIds);
+ var holes = Assert.Single(parse.Document.ModifyBlocks!).SemanticHoles;
+ Assert.Equal(["holes_left", "holes_right"], holes.Select(h => h.Name));
+ Assert.All(holes, h => Assert.Equal(6, h.ShaftDiameter));
+ var build = FirmamentBuildAndExport.CompileSource(source);
+ var renamed = FirmamentBuildAndExport.CompileSource(source.Replace("Diameter => Hole<Shaft> Diameter", "point => Hole<Shaft> seed")
+ .Replace("center: Diameter", "center: point"));
+ Assert.True(build.IsSuccess, string.Join("\n", build.Diagnostics));
+ Assert.True(renamed.IsSuccess, string.Join("\n", renamed.Diagnostics));
+ Assert.Equal(renamed.Value!.StepText, build.Value!.StepText);
+ var variantCollision = FirmamentBuildAndExport.CompileSource(source.Replace("Diameter => Hole<Shaft> Diameter", "Shaft => Hole<Shaft> seed")
+ .Replace("center: Diameter", "center: Shaft"));
+ Assert.True(variantCollision.IsSuccess, string.Join("\n", variantCollision.Diagnostics));
+ Assert.Equal(build.Value.StepText, variantCollision.Value!.StepText);
+ }
+
+ [Fact]
+ public void SemanticPointPatternSymbolCannotRewriteDiameterField()
+ {
+ const string source = """
+ Concept Struct Layout {
+ Bounds: Box3 { Size: [60mm, 40mm, 10mm] }
+ Points: Grid {
+ Within: Bounds.Face(+Z).Inset(8mm)
+ Columns: 2
+ Rows: 2
+ }
+ }
+ Struct Product {
+ Box Base { Bounds: Layout.Bounds }
+ Modify Base {
+ Pattern Mounts {
+ Source: Layout.Points
+ Hole<Shaft> Diameter { On: Base.Top Center: Diameter Diameter: 6mm End: ThroughAll }
+ }
+ }
+ }
+ """;
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var holes = Assert.Single(parsed.Document!.ModifyBlocks!).SemanticHoles;
+ Assert.Equal(4, holes.Count); Assert.All(holes, h => Assert.Equal(6, h.ShaftDiameter));
+ var actual = FirmamentBuildAndExport.CompileSource(source);
+ var renamed = FirmamentBuildAndExport.CompileSource(source.Replace("Hole<Shaft> Diameter", "Hole<Shaft> Item").Replace("Center: Diameter", "Center: Item"));
+ Assert.True(actual.IsSuccess, string.Join("\n", actual.Diagnostics)); Assert.True(renamed.IsSuccess);
+ Assert.Equal(renamed.Value!.StepText, actual.Value!.StepText);
+ }
+
+ [Fact]
+ public void FeatureLookupUsesNearestLexicalDefinitionAndPreservesConcreteGeometry()
+ {
+ var source = """
+ Feature Drill(diameter: Length = 2mm) -> Hole<Shaft> {
+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: diameter end: ThroughAll }
+ }
+ Model Plate {
+ units: mm
+ Feature Drill(diameter: Length = 6mm) -> Hole<Shaft> {
+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: diameter end: ThroughAll }
+ }
+ Box stock { size: [30mm, 20mm, 8mm] }
+ Modify stock { Drill() }
+ }
+ """;
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.True(parse.IsSuccess, string.Join("\n", parse.Diagnostics));
+ var call = Assert.Single(parse.Document!.FeatureInvocations!);
+ Assert.Equal("document/Model Plate", call.BindingScope);
+ Assert.Equal(6, Assert.Single(Assert.Single(parse.Document.ModifyBlocks!).SemanticHoles).ShaftDiameter);
+ var build = FirmamentBuildAndExport.CompileSource(source);
+ var concrete = FirmamentBuildAndExport.CompileSource("""
+ Model Plate { units: mm
+ Box stock { size: [30mm, 20mm, 8mm] }
+ Modify stock { Hole<Shaft> Drill__0 { on: +Z center: Point2(0mm, 0mm) diameter: 6mm end: ThroughAll } }
+ }
+ """);
+ Assert.True(build.IsSuccess, string.Join("\n", build.Diagnostics.Select(d => d.Message)));
+ Assert.True(concrete.IsSuccess);
+ Assert.Equal(concrete.Value!.StepText, build.Value!.StepText);
+ }
+
+ [Fact]
+ public void FeatureInSiblingScopeCannotCaptureAnUnresolvedCall()
+ {
+ const string source = """
+ Struct Other { Feature Local() -> Hole<Shaft> { return Hole<Shaft> { diameter: 9mm } } }
+ Model Plate { units: mm Box stock { size: [20mm, 20mm, 5mm] } Modify stock { Local() } }
+ """;
+ var codes = new List<string>();
+ Assert.Null(FirmamentV2FeatureExpansion.Expand(source, codes));
+ Assert.Contains("firmament-feature-unknown:Local", codes);
+ var parsed = FirmamentV2Parser.Parse(source);
+ var build = FirmamentBuildAndExport.CompileSource(source);
+ Assert.False(parsed.IsSuccess); Assert.False(build.IsSuccess);
+ Assert.Contains(parsed.SyntaxDiagnostics, d => d.Message.Contains("not visible") && d.SourceSpan is not null);
+ }
+
+ [Fact]
+ public void DeclarationLabelsMembersStringsAndSimilarIdentifiersAreNotVariableReferences()
+ {
+ var parsed = FirmamentSyntaxParser.Parse("""
+ Circle2 Ring { radius: size center: [size, 0mm] }
+ Profile Outline { Loop Outer { Ring |> TraceLoop } }
+ Other Unrelated { size: size sizeExtra: sizeExtra path: Other.size text: "size Ring Outline" }
+ Feature Nested(size: Length) -> Hole<Shaft> { return Hole<Shaft> { diameter: size } }
+ Pattern P over Items { size => Hole<Shaft> Item { diameter: size } }
+ """);
+ Assert.True(parsed.IsSuccess);
+ var value = FirmamentSyntaxParser.ParseExpression("8mm").Expression!;
+ var rewrite = new FirmamentSyntaxSubstitution(new Dictionary<string, ExpressionSyntax> { ["size"] = value },
+ new Dictionary<string, string> { ["Ring"] = "Call__Ring", ["Outline"] = "Call__Outline" });
+ var statements = parsed.Document.Statements.Select(rewrite.Statement).ToArray();
+ var circle = Assert.IsType<DeclarationSyntax>(statements[0]);
+ Assert.Equal("Call__Ring", circle.Name!.Text);
+ Assert.Equal("8mm", FirmamentSyntaxWriter.Expression(Assert.IsType<FieldSyntax>(circle.Body!.Statements[0]).Value));
+ var unrelated = Assert.IsType<DeclarationSyntax>(statements[2]);
+ var fields = unrelated.Body!.Statements.Cast<FieldSyntax>().ToDictionary(f => f.Name.Text, f => f.Value);
+ Assert.Equal("sizeExtra", Assert.IsType<ReferenceSyntax>(fields["sizeExtra"]).Name.Text);
+ Assert.Equal("Other.size", FirmamentSyntaxWriter.Expression(fields["path"]));
+ Assert.Equal("\"size Ring Outline\"", Assert.IsType<LiteralSyntax>(fields["text"]).Raw);
+ var nested = Assert.IsType<DeclarationSyntax>(statements[3]);
+ var returned = Assert.IsType<ObjectSyntax>(Assert.IsType<ReturnSyntax>(Assert.Single(nested.Body!.Statements)).Value);
+ Assert.Equal("size", Assert.IsType<ReferenceSyntax>(Assert.IsType<FieldSyntax>(Assert.Single(returned.Body.Statements)).Value).Name.Text);
+ var pattern = Assert.IsType<DeclarationSyntax>(statements[4]);
+ var mapping = Assert.IsType<MappingSyntax>(Assert.Single(pattern.Body!.Statements));
+ var hole = Assert.IsType<DeclarationSyntax>(mapping.Value);
+ Assert.Equal("Item", hole.Name!.Text);
+ Assert.Equal("size", Assert.IsType<ReferenceSyntax>(Assert.IsType<FieldSyntax>(Assert.Single(hole.Body!.Statements)).Value).Name.Text);
+ }
+
+ [Theory]
+ [InlineData("(20mm + 4mm) / 3", "mm", 8)]
+ [InlineData("(90deg - 30deg) * 2", "deg", 120)]
+ [InlineData("12mm / 3mm + 2", "", 6)]
+ [InlineData("2 + 3 * 4", "", 14)]
+ [InlineData("1e-2mm * 100", "mm", 1)]
+ [InlineData("0.25rad * 2", "rad", 0.5)]
+ public void SharedNumericEvaluationHasOnePrecedenceAndUnitPolicy(string expression, string unit, double expected)
+ {
+ var ast = FirmamentSyntaxParser.ParseExpression(expression).Expression!;
+ Assert.True(FirmamentNumericEvaluation.TryEvaluate(ast, out var result));
+ Assert.Equal(unit, result.Unit); Assert.Equal(expected, result.Number, 10);
+ Assert.True(FirmamentSyntaxValues.TryMeasure(ast, unit, out var field));
+ Assert.Equal(expected, field, 10);
+ Assert.True(FirmamentNumericEvaluation.TryEvaluateScalar(expression, out var adapter, out var adapterUnit));
+ Assert.Equal(result.Number, adapter); Assert.Equal(unit, adapterUnit);
+ }
+
+ [Theory]
+ [InlineData("1mm + 1deg")]
+ [InlineData("1deg + 1rad")]
+ [InlineData("1mm * 1mm")]
+ [InlineData("1 / 1mm")]
+ [InlineData("1mm / 0")]
+ [InlineData("missing + 1mm")]
+ [InlineData("Pow(1mm, 2)")]
+ [InlineData("1e999")]
+ [InlineData("(width: 1mm)")]
+ public void SharedNumericEvaluationRejectsInvalidValues(string expression) => Assert.False(FirmamentNumericEvaluation.TryEvaluate(expression, out _));
+
+ [Fact]
+ public void DefaultsResolveTypedDependenciesAndRejectCycles()
+ {
+ const string source = """
+ Feature Drill(diameter: Length = base * 2, base: Length = 3mm) -> Hole<Shaft> {
+ return Hole<Shaft> { diameter: diameter }
+ }
+ Model P { Modify stock { Drill() } }
+ """;
+ var codes = new List<string>();
+ var result = FirmamentV2FeatureExpansion.Expand(source, codes);
+ Assert.NotNull(result); Assert.Empty(codes);
+ Assert.Equal("6mm", Assert.Single(result.Invocations).Arguments["diameter"]);
+ codes.Clear();
+ Assert.Null(FirmamentV2FeatureExpansion.Expand(source.Replace("base: Length = 3mm", "base: Length = diameter"), codes));
+ Assert.Contains(codes, c => c.StartsWith("firmament-feature-default-cycle:"));
+ }
+
+ [Fact]
+ public void QuotedCommentBracesCannotChangeTerminalReturnOrConstructionNames()
+ {
+ var codes = new List<string>();
+ var expanded = FirmamentV2FeatureExpansion.Expand("""
+ Feature Drill() -> Hole<Shaft> {
+ // "}" return Missing() { fake
+ return Hole<Shaft> { diameter: 6mm }
+ }
+ Model P { Modify stock { Drill() } }
+ """, codes);
+ Assert.NotNull(expanded); Assert.Empty(codes);
+ Assert.Single(expanded.Invocations);
+ Assert.DoesNotContain(FirmamentSyntaxTraversal.Declarations(expanded.Document!), d => d.Type.Name.Text == "Feature");
+ }
+
+ [Fact]
+ public void ValueParameterCannotRenameAConstructionTypeOrReturnConstructor()
+ {
+ const string source = """
+ Feature Make(Profile: Profile, Boss: Plane) -> Boss {
+ Circle2 Outline { Center: [0mm, 0mm] Radius: 2mm }
+ Profile Section { Loop Outer { Outline |> TraceLoop } }
+ return Boss { On: Boss Profile: Profile Height: 2mm }
+ }
+ Model P { Compose Body { Make(Profile: ExternalProfile, Boss: Top) } }
+ """;
+ var codes = new List<string>();
+ var expanded = FirmamentV2FeatureExpansion.Expand(source, codes);
+ Assert.NotNull(expanded); Assert.Empty(codes);
+ var nodes = FirmamentSyntaxTraversal.Declarations(expanded.Document!).ToArray();
+ Assert.Contains(nodes, d => d.Type.Name.Text == "Profile" && d.Name?.Text == "Make__0__Section");
+ var boss = Assert.Single(nodes, d => d.Type.Name.Text == "Boss");
+ var fields = boss.Body!.Statements.Cast<FieldSyntax>().ToDictionary(f => f.Name.Text, f => f.Value);
+ Assert.Equal("Top", Assert.IsType<ReferenceSyntax>(fields["On"]).Name.Text);
+ Assert.Equal("ExternalProfile", Assert.IsType<ReferenceSyntax>(fields["Profile"]).Name.Text);
+ }
+
+ [Fact]
+ public void TransportSerializationPreservesIdentityBearingApplicationSpelling()
+ {
+ const string source = "<Part fret = Panel<L:site.Width,W:1.2mm,H:1mm,R:0.5mm>> Placement { From: Origin; To: World; } </Part>";
+ var parsed = FirmamentSyntaxParser.Parse(source);
+ Assert.True(parsed.IsSuccess);
+ var width = FirmamentSyntaxParser.ParseExpression("43.697597898337534mm").Expression!;
+ var transform = new FirmamentSyntaxSubstitution(new Dictionary<string, ExpressionSyntax> { ["site.Width"] = width });
+ var part = (DeclarationSyntax)transform.Statement(Assert.Single(parsed.Document.Statements));
+ var serialized = FirmamentSyntaxWriter.Statement(part, source);
+ var rebound = (DeclarationSyntax)Assert.Single(FirmamentSyntaxParser.Parse(serialized).Document.Statements);
+ var application = rebound.Initializer!;
+ Assert.Equal("Panel<L:43.697597898337534mm,W:1.2mm,H:1mm,R:0.5mm>", serialized.Substring(application.Span.Start, application.Span.Length));
+ }
+
+ [Fact]
+ public void ExpansionLimitsRejectRatherThanTruncateAndRetainLocatedDiagnostics()
+ {
+ var source = "Feature Drill() -> Hole<Shaft> { return Hole<Shaft> { diameter: 6mm } }\nModel P { Modify stock {\n"
+ + string.Join("\n", Enumerable.Repeat("Drill()", FirmamentV2FeatureExpansion.MaximumInvocations + 1)) + "\n} }";
+ var codes = new List<string>(); var values = new FirmamentCompileTimeValues(source);
+ Assert.Null(FirmamentV2FeatureExpansion.Expand(source, codes, values));
+ Assert.Contains("firmament-feature-expansion-limit", codes);
+ Assert.Contains(values.Diagnostics, d => d.Code == "firmament-feature-expansion-limit" && d.SourceSpan is not null && d.Severity == "fatal");
+ }
+
+ [Fact]
+ public void InvocationReceiptsAreDeterministicAndSeparateDefinitionFromUse()
+ {
+ const string source = """
+ Feature Drill(diameter: Length = 6mm) -> Hole<Shaft> { return Hole<Shaft> { diameter: diameter } }
+ Model P { Modify stock { Drill() Drill(8mm) } }
+ """;
+ var first = FirmamentV2FeatureExpansion.Expand(source, []);
+ var second = FirmamentV2FeatureExpansion.Expand(source, []);
+ Assert.NotNull(first); Assert.NotNull(second);
+ Assert.Equal(first.Source, second.Source);
+ Assert.Equal([0, 1], first.Invocations.Select(i => i.Ordinal));
+ foreach (var invocation in first.Invocations)
+ {
+ Assert.Equal("Drill", invocation.DefinitionOrigin!.Binding);
+ Assert.StartsWith("Feature Drill", source.Substring(invocation.DefinitionOrigin.SourceSpan.Start, invocation.DefinitionOrigin.SourceSpan.Length));
+ Assert.StartsWith("Drill(", source.Substring(invocation.InvocationOrigin!.SourceSpan.Start, invocation.InvocationOrigin.SourceSpan.Length));
+ Assert.Equal(["Drill"], invocation.ExpansionChain);
+ }
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentScopedDataBindingTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentScopedDataBindingTests.cs
new file mode 100644
index 00000000..77aff9ef
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentScopedDataBindingTests.cs
@@ -0,0 +1,236 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentScopedDataBindingTests
+{
+ [Fact]
+ public void LocalTypedToleranceRetainsGeometryPmiAndAuthoredRequirementLocation()
+ {
+ var source = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/FrontendX2/scoped-record-pmi.firmament"));
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.Equal(8, Assert.Single(Assert.Single(parsed.Document!.ModifyBlocks!).SemanticHoles).ShaftDiameter);
+ var dimension = Assert.Single(parsed.Document.BoundPmi!.Dimensions);
+ Assert.Contains(dimension.DimensionOrigins, o => source.Substring(o.SourceSpan.Start, o.SourceSpan.Length).Contains("8mm tol +0.10mm -0.05mm"));
+ var compiled = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics));
+ var item = Assert.Single(Step242SemanticPmiInspector.Inspect(compiled.Value!.StepText).Items, i => i.Kind == "Diameter");
+ Assert.Equal(8, item.Value); Assert.Equal(0.10, item.TolerancePlus); Assert.Equal(0.05, item.ToleranceMinus);
+ Assert.NotEmpty(item.GeometricFaceEntityIds);
+ }
+ [Theory]
+ [InlineData("Static width: Length = 30mm", "width")]
+ [InlineData("Record Spec { width: Length } Static spec: Spec = Spec { width: 30mm }", "spec.width")]
+ [InlineData("Record Spec { width: Length } Static Table choices: Spec { width: [30mm] } Static spec: Spec = choices[0]", "spec.width")]
+ [InlineData("Record Spec { width: Length } Static base: Spec = Spec { width: 12mm } Static spec: Spec = base with { width: 30mm }", "spec.width")]
+ public void ModelLocalDataShadowsOuterNamesWithoutChangingConcreteGeometry(string declarations, string value)
+ {
+ var source = $$"""
+ Static width: Length = 10mm
+ Record Spec { width: Length thickness: Length }
+ Static spec: Spec = Spec { width: 10mm thickness: 3mm }
+ Static Table choices: Spec { width: [10mm] thickness: [3mm] }
+ Model Plate {
+ units: mm
+ {{declarations}}
+ Box stock { size: [{{value}}, 20mm, 6mm] }
+ }
+ """;
+ EqualConcrete(source, 30);
+ }
+
+ [Fact]
+ public void TemplateDefaultsResolveAtDefinitionAndExplicitArgumentsAtInvocation()
+ {
+ const string source = """
+ Static width: Length = 10mm
+ Template<size: Length = width> Struct Family { Box stock { size: [size, 20mm, 6mm] } }
+ Model Plate { units: mm Static width: Length = 30mm Struct product = Family<> }
+ """;
+ EqualConcrete(source, 10, nested: true);
+ EqualConcrete(source.Replace("Family<>", "Family<size: width>"), 30, nested: true);
+ }
+
+ [Fact]
+ public void TypedNestedRecordAliasesRetainTheirMemberBindings()
+ {
+ const string source = """
+ Record Leaf { width: Length }
+ Static leaf: Leaf = Leaf { width: 10mm }
+ Model Plate {
+ units: mm
+ Record Leaf { width: Length }
+ Record Config { leaf: Leaf }
+ Static leaf: Leaf = Leaf { width: 30mm }
+ Static config: Config = Config { leaf: leaf }
+ Static selected: Config = config
+ Box stock { size: [selected.leaf.width, 20mm, 6mm] }
+ }
+ """;
+ EqualConcrete(source, 30);
+ }
+
+ [Theory]
+ [InlineData("Record Spec() { width: Length }")]
+ [InlineData("Static width on XZ: Length = 30mm")]
+ [InlineData("Record Spec { width: Length } Static Table choices: Spec on XZ { width: [30mm] }")]
+ public void DataHeadersCannotDiscardUnsupportedClauses(string declaration)
+ {
+ var source = "Model Plate { units: mm " + declaration + " Box stock { size: [30mm, 20mm, 6mm] } }";
+ Assert.False(FirmamentV2Parser.Parse(source).IsSuccess);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Theory]
+ [InlineData("Record Spec { width: Length }", "Static value: Spec = Spec { width: 30mm }")]
+ [InlineData("Static secret: Length = 30mm", "Static value: Length = secret")]
+ [InlineData("Record Spec { width: Length } Static Table choices: Spec { width: [30mm] }", "Static value: Length = choices[0].width")]
+ public void SiblingDataIsNotVisibleToAConsumer(string declarations, string consumer)
+ {
+ var source = "Model Other { " + declarations + " } Model Plate { units: mm " + consumer + " Box stock { size: [30mm, 20mm, 6mm] } }";
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.False(parse.IsSuccess);
+ var errors = parse.SyntaxDiagnostics.Where(d => d.Code.StartsWith("firmament-binding-name-not-visible:")).ToArray();
+ Assert.NotEmpty(errors);
+ Assert.All(errors, diagnostic =>
+ {
+ Assert.NotNull(diagnostic.SourceSpan);
+ Assert.True(diagnostic.IsOriginalSource);
+ Assert.Contains("not visible", diagnostic.Message);
+ });
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Theory]
+ [InlineData("Record Spec { width: Length } Record Spec { height: Length }")]
+ [InlineData("Static width: Length = 10mm Static width: Length = 30mm")]
+ [InlineData("Record Spec { width: Length } Static Table choices: Spec { width: [10mm] } Static Table choices: Spec { width: [30mm] }")]
+ public void DuplicateDataInOneScopeRejectsWithoutAReaderException(string declarations)
+ {
+ var source = "Model Plate { units: mm " + declarations + " Box stock { size: [30mm, 20mm, 6mm] } }";
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(parse.SyntaxDiagnostics, d => d.Code.StartsWith("firmament-binding-duplicate-name:") && d.SourceSpan is not null);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Fact]
+ public void SameSpellingAndShapeDoNotMakeDifferentScopedRecordTypesInterchangeable()
+ {
+ const string source = """
+ Record Spec { width: Length }
+ Static outer: Spec = Spec { width: 30mm }
+ Model Plate {
+ units: mm
+ Record Spec { width: Length }
+ Template<p: Spec> Struct Family { Box stock { size: [p.width, 20mm, 6mm] } }
+ Struct product = Family<p: outer>
+ }
+ """;
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(parse.Diagnostics, d => d.StartsWith("firmament-template-record-argument-type-mismatch:"));
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Fact]
+ public void FeatureParametersAndPatternBindersDoNotCaptureAStaticOfTheSameName()
+ {
+ const string source = """
+ Static diameter: Length = 12mm
+ Model Plate {
+ units: mm
+ Static diameter: Length = 6mm
+ Feature Drill(diameter: Length) -> Hole<Shaft> {
+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: diameter end: ThroughAll }
+ }
+ Box stock { size: [30mm, 20mm, 6mm] }
+ Modify stock { Feature bore = Drill(diameter) }
+ }
+ """;
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.Equal(6, Assert.Single(Assert.Single(parsed.Document!.ModifyBlocks!).SemanticHoles).ShaftDiameter);
+ Assert.True(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Fact]
+ public void SpecializedRecordAndStaticDeclarationsAreBoundBeforeFeatureArguments()
+ {
+ const string source = """
+ Template<diameter: Length = 6mm> Struct Family {
+ Record Spec { diameter: Length }
+ Static selected: Spec = Spec { diameter: diameter }
+ Feature Drill(p: Spec) -> Hole<Shaft> {
+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: p.diameter end: ThroughAll }
+ }
+ Box stock { size: [30mm, 20mm, 6mm] }
+ Modify stock { Feature bore = Drill(selected) }
+ }
+ Model Plate { units: mm Struct product = Family<> }
+ """;
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.True(parse.IsSuccess, string.Join("\n", parse.Diagnostics));
+ Assert.Equal(6, Assert.Single(Assert.Single(parse.Document!.ModifyBlocks!).SemanticHoles).ShaftDiameter);
+ Assert.True(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Fact]
+ public void HostInspectionAndInvocationUseTheVisibleRecordSchema()
+ {
+ const string source = """
+ Record Spec { width: Length }
+ Static outer: Spec = Spec { width: 10mm }
+ Model Library {
+ units: mm
+ Record Spec { width: Length thickness: Length }
+ Static selected: Spec = Spec { width: 30mm thickness: 6mm }
+ Template<p: Spec = selected> Struct Family { Box stock { size: [p.width, 20mm, p.thickness] } }
+ }
+ """;
+ var metadata = FirmamentTemplateHostBridge.InspectModule(source, out var diagnostics);
+ Assert.Empty(diagnostics);
+ var schema = Assert.Single(metadata.Records);
+ Assert.Equal("Spec", schema.Name);
+ Assert.Equal(["thickness", "width"], schema.Fields.Select(f => f.Name).OrderBy(n => n));
+ var expansion = FirmamentTemplateHostBridge.Expand(source, "Family", "product",
+ new Dictionary<string, FirmamentHostArgument> { ["p"] = new("", "Spec", new Dictionary<string, string> { ["width"] = "30mm", ["thickness"] = "6mm" }) }, out diagnostics);
+ Assert.NotNull(expansion); Assert.Empty(diagnostics);
+ var built = FirmamentBuildAndExport.CompileSource(expansion.ExpandedSource);
+ Assert.True(built.IsSuccess, expansion.ExpandedSource + "\n" + string.Join("\n", built.Diagnostics));
+ }
+
+ [Fact]
+ public void HostNestedRecordMarkersResolveTheDeclaredScopedType()
+ {
+ const string source = """
+ Record Leaf { unused: Length }
+ Model Library {
+ units: mm
+ Record Leaf { width: Length }
+ Record Spec { leaf: Leaf }
+ Template<p: Spec> Struct Family { Box stock { size: [p.leaf.width, 20mm, 6mm] } }
+ }
+ """;
+ var expanded = FirmamentTemplateHostBridge.Expand(source, "Family", "product",
+ new Dictionary<string, FirmamentHostArgument> { ["p"] = new("", "Spec", new Dictionary<string, string> { ["leaf"] = "Leaf", ["leaf.width"] = "30mm" }) }, out var diagnostics);
+ Assert.NotNull(expanded); Assert.Empty(diagnostics);
+ var built = FirmamentBuildAndExport.CompileSource(expanded.ExpandedSource);
+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics));
+ }
+
+ private static void EqualConcrete(string source, double width, bool nested = false)
+ {
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.True(parse.IsSuccess, string.Join("\n", parse.Diagnostics));
+ var actual = FirmamentBuildAndExport.CompileSource(source);
+ var box = $"Box stock {{ size: [{width}mm, 20mm, 6mm] }}";
+ var concrete = FirmamentBuildAndExport.CompileSource("Model Plate { units: mm " + (nested ? "Struct product { " + box + " }" : box) + " }");
+ Assert.True(actual.IsSuccess, string.Join("\n", actual.Diagnostics));
+ Assert.True(concrete.IsSuccess, string.Join("\n", concrete.Diagnostics));
+ Assert.Equal(concrete.Value!.StepText, actual.Value!.StepText);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2FeatureFunctionTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2FeatureFunctionTests.cs
index 000b69e0..cdfb29f4 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2FeatureFunctionTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2FeatureFunctionTests.cs
@@ -163,8 +163,8 @@ public sealed class FirmamentV2FeatureFunctionTests
[InlineData("wrong-return-type.firmament", "firmament-feature-return-type")]
[InlineData("direct-recursion.firmament", "firmament-feature-recursion")]
[InlineData("indirect-recursion.firmament", "firmament-feature-recursion")]
- [InlineData("unsupported-conditional.firmament", "firmament-feature-control-flow-unsupported")]
- [InlineData("unsupported-loop.firmament", "firmament-feature-control-flow-unsupported")]
+ [InlineData("unsupported-conditional.firmament", "firmament-syntax-control-flow-unsupported")]
+ [InlineData("unsupported-loop.firmament", "firmament-syntax-control-flow-unsupported")]
public void InvalidFeatureFixtures_ProduceSpecificTypedDiagnostics(string file, string diagnostic)
{
var source = File.ReadAllText(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,
diff --git a/Aetheris.Kernel.Firmament.Tests/FunctionalPickupTests.cs b/Aetheris.Kernel.Firmament.Tests/FunctionalPickupTests.cs
index f6d6c1ef..79945420 100644
--- a/Aetheris.Kernel.Firmament.Tests/FunctionalPickupTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FunctionalPickupTests.cs
@@ -70,7 +70,8 @@ public sealed class FunctionalPickupTests
Assert.Empty(diagnostics);
Assert.Contains("Profile Pad__Section", expansion.Source);
Assert.Contains("Profile Pad__Call1__Section", expansion.Source);
- Assert.Contains("Boss Pad ", expansion.Source);
+ Assert.Contains(Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxTraversal.Declarations(expansion.Document!),
+ d => d.Type.Name.Text == "Boss" && d.Name?.Text == "Pad");
}
[Theory]
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyFrameAuthoring.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyFrameAuthoring.cs
index 4a4af002..2375e524 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyFrameAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyFrameAuthoring.cs
@@ -1,3 +1,4 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using System.Globalization;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Math;
@@ -48,7 +49,7 @@ internal static class AssemblyFrameAuthoring
var text = values[i];
if (lengths)
{
- if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(text,out result[i],out var unit) || unit != "mm" || !double.IsFinite(result[i]))
+ if (!FirmamentNumericEvaluation.TryEvaluateScalar(text,out result[i],out var unit) || unit != "mm" || !double.IsFinite(result[i]))
diagnostics.Add(new("assembly-frame-invalid-unit", $"Frame '{name}' translation components require finite mm length expressions."));
continue;
}
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs
index 50f1e0e7..24dd01ab 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs
@@ -1,3 +1,4 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using System.Globalization;
using System.Text.RegularExpressions;
using Aetheris.Semantics;
@@ -184,7 +185,7 @@ internal static class AssemblyPublishedPorts
var components = match.Groups["origin"].Value.Split(',');
var values = new double[3];
if (components.Length != 3 || components.Where((component, index) =>
- !FirmamentV2FeatureExpansion.TryEvaluateScalar(component.Trim(), out values[index], out var unit)
+ !FirmamentNumericEvaluation.TryEvaluateScalar(component.Trim(), out values[index], out var unit)
|| (unit != "mm" && !(unit.Length == 0 && double.TryParse(component.Trim(), NumberStyles.Float,
CultureInfo.InvariantCulture, out _))) || !double.IsFinite(values[index])).Any())
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 1351863a..5c3e709f 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -282,6 +282,13 @@ public static class FirmamentBuildAndExport
if (!v2Parse.IsSuccess) return V2ParseFailure(v2Parse);
materializerSource = v2Parse.BoundSource!;
}
+ else if (v2Parse.Disposition == FirmamentV2ParseDisposition.NotRecognized)
+ {
+ // The explicit versioned V1 reader below owns compatibility. Do not
+ // interpret serialized data as a second V2 expansion input. The later
+ // allowV1Compatibility/version checks remain mandatory.
+ materializerSource = sourceText;
+ }
else
{
var staticDiagnostics = new List<string>();
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
index 6a7ab662..39e56141 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
@@ -4,8 +4,9 @@ using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
-/// <summary>Small, bounded canonical static frontend. It normalizes records, arrays, templates,
-/// patterns, and Require into erased concrete declarations before the material frontend runs.</summary>
+/// <summary>Finite static authoring owner. Pattern headers/mappings and finite feature
+/// Template output bind AST nodes; the remaining Record/Set catalog and source adapters
+/// are explicit migration boundaries before domain AIR.</summary>
internal static class CanonicalStaticAuthoring
{
internal const string Prefix = "firmament-v2-static-";
@@ -16,26 +17,29 @@ internal static class CanonicalStaticAuthoring
/// <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)
{
+ var binding = new FirmamentDataBinding(source);
+ diagnostics.AddRange(binding.Diagnostics.Select(d => d.Code + ": " + d.Message));
+ if (binding.Diagnostics.Count > 0) return null;
+ source = binding.Source;
var points = ConceptPointAuthoring.Expand(source, diagnostics);
if (points is null) return null;
source = points.Source;
var sites = AssemblySiteAuthoring.Expand(source, diagnostics);
if (sites is null) return null;
source = sites.Source;
- var headers = Regex.Matches(source,@"\bPattern\s+(?<name>[A-Za-z_]\w*)\s+Over\s+(?<set>[A-Za-z_]\w*)\s*\{").Cast<Match>()
- .Where(h => Regex.IsMatch(source[(h.Index+h.Length)..],@"^\s*[A-Za-z_]\w*\s*=>\s*<(?:Part|Assembly)\b")).ToArray();
+ var syntax = FirmamentSyntaxParser.Parse(source);
+ var headers = FirmamentSyntaxTraversal.Declarations(syntax.Document)
+ .Where(d => d.Type.Name.Text == "Pattern" && d.Clauses.Any(c => c.Kind == ClauseKind.Over)
+ && d.Body?.Statements.FirstOrDefault() is MappingSyntax { Value: DeclarationSyntax { Occurrence: true, Type.Name.Text: "Part" or "Assembly" } }).ToArray();
if (headers.Length == 0)
{
source = points.Math.Normalize(source, diagnostics);
return diagnostics.Count > 0 ? null : new(source, points.Points.Count == 0 ? null : new([],[],[],[],[], ConceptPoints: points.Points));
}
var catalog = source.Select(c => c is '\r' or '\n' ? c : ' ').ToArray();
- foreach (Match header in Regex.Matches(source,@"\b(?:Record\s+[A-Za-z_]\w*|Static\s+[A-Za-z_]\w*\s*:\s*Set\s*<\s*[A-Za-z_]\w*\s*>)\s*\{"))
- {
- var open=source.IndexOf('{',header.Index); var close=MatchPair(source,open,'{','}');
- if (close<0) { diagnostics.Add(Prefix+"assembly-pattern-catalog-malformed"); return null; }
- source.CopyTo(header.Index,catalog,header.Index,close-header.Index+1);
- }
+ foreach (var declaration in FirmamentSyntaxTraversal.Declarations(syntax.Document)
+ .Where(d => d.Type.Name.Text == "Record" || d.Type.Name.Text == "Static" && d.Annotation is SpecializationSyntax { Target: ReferenceSyntax { Name.Text: "Set" } }))
+ source.CopyTo(declaration.Span.Start, catalog, declaration.Span.Start, declaration.Span.Length);
var catalogSource = new string(catalog);
if (spatial)
{
@@ -55,27 +59,36 @@ internal static class CanonicalStaticAuthoring
var patterns=new List<FirmamentV2CanonicalPatternDecl>(); var names=new HashSet<string>(); var total=0;
foreach (var header in headers)
{
- var name=header.Groups["name"].Value; var open=source.IndexOf('{',header.Index); var close=MatchPair(source,open,'{','}');
- if (!names.Add(name)) { diagnostics.Add(Prefix+"assembly-pattern-duplicate:"+name); continue; }
- if (close<0 || !sets.TryGetValue(header.Groups["set"].Value,out var set)) { diagnostics.Add(Prefix+"pattern-source-invalid:"+name); continue; }
- var body=source[(open+1)..close].Trim();
- var arrow=Regex.Match(body,@"^(?<binder>[A-Za-z_]\w*)\s*=>\s*(?<mapping>[\s\S]+)$");
- if (!arrow.Success || !Regex.IsMatch(arrow.Groups["mapping"].Value,@"^\s*<(?:Part|Assembly)\b") || Regex.IsMatch(body,@"\bPattern\s+"))
- { diagnostics.Add(Prefix+"assembly-pattern-body-invalid:"+name); continue; }
+ var name = header.Name?.Text ?? "<unnamed>";
+ if (!names.Add(name)) { diagnostics.Add(Prefix + "assembly-pattern-duplicate:" + name); continue; }
+ var sourceName = header.Clauses.Count == 1 ? FirmamentSyntaxValues.Reference(header.Clauses[0].Value) : null;
+ if (sourceName is null || !sets.TryGetValue(sourceName, out var set))
+ { diagnostics.Add(Prefix + "pattern-source-invalid:" + name); continue; }
+ var mapping = (MappingSyntax)header.Body!.Statements[0];
+ var mappedStatements = new[] { mapping.Value }.Concat(header.Body.Statements.Skip(1)).ToArray();
+ if (mappedStatements.Any(s => s is not DeclarationSyntax { Occurrence: true, Type.Name.Text: "Part" or "Assembly" })
+ || header.Parameters.Count > 0 || header.Modifiers.Count > 0 || header.Initializer is not null || header.Annotation is not null || header.ResultType is not null
+ || header.Type.Span.Length > header.Type.Name.Span.Length || header.Occurrence || header.HasParameterList)
+ { diagnostics.Add(Prefix + "assembly-pattern-body-invalid:" + name); continue; }
total+=set.Entries.Count;
if (set.Entries.Count>MaxPatternExpansion || total>4096) { diagnostics.Add(Prefix+"pattern-expansion-limit:"+name); continue; }
var output=new List<string>(); var associations=new List<FirmamentV2PatternAssociation>();
const string identity="Placement LegacyExplicit = [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];";
foreach (var entry in set.Entries)
{
- var mapping=SubstituteSetMapping(arrow.Groups["mapping"].Value,arrow.Groups["binder"].Value,entry);
- if (Regex.IsMatch(mapping,$@"\b{Regex.Escape(arrow.Groups["binder"].Value)}\."))
- { diagnostics.Add(Prefix+"assembly-pattern-member-unresolved:"+name+"."+entry.Name); continue; }
- output.Add(spatial ? $"<Group {entry.Name}>\n{mapping}\n</Group>" : $"<Assembly {entry.Name}> {identity}\n{mapping}\n</Assembly>");
+ var substitution = BindSetElement(mapping.Key.Text, entry, diagnostics);
+ if (substitution is null) continue;
+ var bound = mappedStatements.Select(substitution.Statement).ToArray();
+ var mappedText = FirmamentSyntaxWriter.Statements(bound, source);
+ var mappedSyntax = new DocumentSyntax("expanded-pattern", bound, [], header.Span);
+ if (FirmamentSyntaxTraversal.Expressions(mappedSyntax).OfType<MemberSyntax>()
+ .Any(m => FirmamentSyntaxValues.Reference(m.Target) == mapping.Key.Text))
+ { diagnostics.Add(Prefix + "assembly-pattern-member-unresolved:" + name + "." + entry.Name); continue; }
+ output.Add(spatial ? $"<Group {entry.Name}>\n{mappedText}\n</Group>" : $"<Assembly {entry.Name}> {identity}\n{mappedText}\n</Assembly>");
associations.Add(new(name+"."+entry.Name,set.Name,entry.Name,entry.Value,entry.SourceOrder,entry.Provenance));
}
- changes.Add((header.Index,close-header.Index+1,spatial ? $"<Group {name}>\n{string.Join(Environment.NewLine,output)}\n</Group>" : $"<Assembly {name}> {identity}\n{string.Join(Environment.NewLine,output)}\n</Assembly>"));
- patterns.Add(new(name,set.Name,"Assembly",set.Entries.Count,associations.Select(a=>a.GeneratedId).ToArray(),new(header.Index,close-header.Index+1),associations,
+ changes.Add((header.Span.Start,header.Span.Length,spatial ? $"<Group {name}>\n{string.Join(Environment.NewLine,output)}\n</Group>" : $"<Assembly {name}> {identity}\n{string.Join(Environment.NewLine,output)}\n</Assembly>"));
+ patterns.Add(new(name,set.Name,"Assembly",set.Entries.Count,associations.Select(a=>a.GeneratedId).ToArray(),header.Span,associations,
sites.Recipes.GetValueOrDefault(set.Name)));
}
foreach (var change in changes.OrderByDescending(c=>c.Start)) source=source.Remove(change.Start,change.Length).Insert(change.Start,change.Text);
@@ -86,28 +99,45 @@ internal static class CanonicalStaticAuthoring
return diagnostics.Count > 0 ? null : new(source,data.Document with { Patterns=patterns, ConceptPoints=points.Points });
}
- private static string SubstituteSetMapping(string mapping,string binder,FirmamentV2StaticSetEntry entry)
+ private static FirmamentSyntaxSubstitution? BindSetElement(string binder, FirmamentV2StaticSetEntry entry, List<string> diagnostics)
{
+ var values = new Dictionary<string, ExpressionSyntax>(StringComparer.Ordinal);
+ bool Add(string name, string value)
+ {
+ var parsed = FirmamentSyntaxParser.ParseExpression(value);
+ if (parsed.Expression is null || parsed.Diagnostics.Count > 0)
+ { diagnostics.Add(Prefix + "pattern-value-invalid:" + entry.Name + ":" + name); return false; }
+ values[name] = parsed.Expression; return true;
+ }
if (entry.RecordFields is not null)
+ {
foreach (var field in entry.RecordFields)
- mapping=Regex.Replace(mapping,$@"\b{Regex.Escape(binder)}\s*\.\s*{Regex.Escape(field.Key)}\b",field.Value,RegexOptions.CultureInvariant);
+ if (!Add(binder + "." + field.Key, field.Value)) return null;
+ }
else
{
- var point = Regex.Match(entry.Value, @"^Point(?<dim>[23])\((?<values>[^()]+)\)$");
- if (point.Success)
+ if (!Add(binder, entry.Value)) return null;
+ if (values[binder] is CallSyntax { Target: ReferenceSyntax { Name.Text: "Point2" or "Point3" } } point)
{
- var coordinates = point.Groups["values"].Value.Split(',', StringSplitOptions.TrimEntries);
- for (var i = 0; i < coordinates.Length; i++)
- mapping = Regex.Replace(mapping, $@"\b{Regex.Escape(binder)}(?:\s*\.\s*Position)?\s*\.\s*{"XYZ"[i]}\b", coordinates[i]);
- mapping = Regex.Replace(mapping, $@"\b{Regex.Escape(binder)}\s*\.\s*Position\b", entry.Value);
+ for (var i = 0; i < point.Arguments.Count; i++)
+ {
+ values[binder + "." + "XYZ"[i]] = point.Arguments[i].Value;
+ values[binder + ".Position." + "XYZ"[i]] = point.Arguments[i].Value;
+ }
+ values[binder + ".Position"] = point;
}
- mapping=Regex.Replace(mapping,$@"\b{Regex.Escape(binder)}\b",entry.Value,RegexOptions.CultureInvariant);
}
- return mapping;
+ return new(values);
}
public static Result? Expand(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null)
{
+ var binding = new FirmamentDataBinding(source);
+ diagnostics.AddRange(binding.Diagnostics.Select(d => scalars is null ? d.Code + ": " + d.Message : d.Code));
+ scalars?.AddExpansionDiagnostics(binding.Diagnostics);
+ if (binding.Diagnostics.Count > 0) return null;
+ scalars?.UseDataBinding(binding);
+ source = binding.Source;
var points = ConceptPointAuthoring.Expand(source, diagnostics);
if (points is null) return null;
source = points.Source;
@@ -144,16 +174,13 @@ internal static class CanonicalStaticAuthoring
if (close >= 0) changes.Add((header.Index, close - header.Index + 1, string.Empty));
}
- foreach (Match header in Regex.Matches(source, @"\bRecord\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
+ var catalog = FirmamentV2TemplateExpansion.ReadDataCatalog(source, diagnostics, scalars);
+ foreach (var record in catalog.Types.Values)
{
- var close = MatchPair(source, source.IndexOf('{', header.Index), '{', '}');
- if (close < 0) { diagnostics.Add(Prefix + "record-malformed"); continue; }
- var name = header.Groups["name"].Value; if (!names.Add(name)) { diagnostics.Add(FirmamentV2Parser.DuplicateName + ":Record:" + name); continue; }
- var fields = Regex.Matches(source[(source.IndexOf('{', header.Index) + 1)..close], @"\b(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)", RegexOptions.CultureInvariant)
- .Cast<Match>().ToDictionary(m => m.Groups["name"].Value, m => m.Groups["type"].Value, StringComparer.Ordinal);
- if (fields.Count == 0) diagnostics.Add(Prefix + "record-empty:" + name);
- recordTypes.Add(new(name, fields, new(header.Index, close - header.Index + 1)));
- changes.Add((header.Index, close - header.Index + 1, string.Empty));
+ if (record.Fields.Count == 0) diagnostics.Add(Prefix + "record-empty:" + record.Name);
+ recordTypes.Add(new(record.Name, record.Fields, record.SourceSpan));
+ changes.Add((record.SourceSpan.Start, record.SourceSpan.Length, string.Empty));
+ names.Add(record.Name);
}
var recordByName = recordTypes.ToDictionary(x => x.Name, StringComparer.Ordinal);
@@ -178,42 +205,17 @@ internal static class CanonicalStaticAuthoring
// Tables share Record typing with Static values, but intentionally preserve their
// columnar spelling for source inspection. The template binder has already checked
// cells and lookups before this phase erases the compile-time declaration.
- foreach (Match header in Regex.Matches(source, @"\bStatic\s+Table\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)(?:\s+Key\s*:\s*(?<key>[A-Za-z_]\w*))?\s*\{", RegexOptions.CultureInvariant))
- {
- var open = source.IndexOf('{', header.Index); var close = MatchPair(source, open, '{', '}');
- if (close < 0) { diagnostics.Add(Prefix + "table-malformed:" + header.Groups["name"].Value); continue; }
- var columns = TableColumns(source, open + 1, close);
- var rowCount = columns.Count == 0 ? 0 : columns.First().Value.Count;
- tables.Add(new(header.Groups["name"].Value, header.Groups["type"].Value, header.Groups["key"].Success ? header.Groups["key"].Value : null, columns, rowCount, new(header.Index, close - header.Index + 1)));
- changes.Add((header.Index, close - header.Index + 1, string.Empty));
- }
-
- foreach (Match header in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)(?:\s*=\s*(?<literal>[A-Za-z_]\w*))?\s*\{", RegexOptions.CultureInvariant))
+ foreach (var table in catalog.Tables.Values)
{
- var open = source.IndexOf('{', header.Index); var close = MatchPair(source, open, '{', '}');
- var name = header.Groups["name"].Value; var type = header.Groups["type"].Value; var literalType = header.Groups["literal"].Success ? header.Groups["literal"].Value : type;
- if (close < 0 || !recordByName.TryGetValue(type, out var record)) { diagnostics.Add(Prefix + "record-type-invalid:" + name); continue; }
- if (!string.Equals(type, literalType, StringComparison.Ordinal)) { diagnostics.Add(Prefix + "record-literal-type-mismatch:" + name); continue; }
- if (!names.Add(name)) { diagnostics.Add(FirmamentV2Parser.DuplicateName + ":Static:" + name); continue; }
- var values = Fields(source[(open + 1)..close]);
- var missing = record.Fields.Keys.Where(field => !values.ContainsKey(field)).ToArray();
- var extra = values.Keys.Where(field => !record.Fields.ContainsKey(field)).ToArray();
- if (missing.Length > 0) diagnostics.Add(Prefix + "record-missing-field:" + name + ":" + string.Join(",", missing));
- if (extra.Length > 0) diagnostics.Add(Prefix + "record-extra-field:" + name + ":" + string.Join(",", extra));
- staticRecords.Add(new(name, type, values, new(header.Index, close - header.Index + 1)));
- changes.Add((header.Index, close - header.Index + 1, string.Empty));
+ var columns = table.Columns.ToDictionary(c => c.Key, c => (IReadOnlyList<string>)c.Value, StringComparer.Ordinal);
+ tables.Add(new(table.Name, table.RowType, table.KeyField, columns, columns.Count == 0 ? 0 : columns.First().Value.Count, table.SourceSpan));
+ changes.Add((table.SourceSpan.Start, table.SourceSpan.Length, string.Empty));
}
-
- // `with` and Table row selection are compile-time Record expressions. Their actual
- // member maps are owned by the common template binder; this phase retains no runtime
- // representation and simply ensures source is erased before material parsing.
- foreach (Match declaration in Regex.Matches(source, @"\bStatic\s+[A-Za-z_]\w*\s*(?::\s*[A-Za-z_]\w*)?\s*=\s*[A-Za-z_]\w*\s+with\s*\{", RegexOptions.CultureInvariant))
+ foreach (var record in catalog.Records.Values)
{
- var open = source.IndexOf('{', declaration.Index); var close = MatchPair(source, open, '{', '}');
- if (close >= 0) changes.Add((declaration.Index, close - declaration.Index + 1, string.Empty));
+ staticRecords.Add(new(record.Name, record.TypeName, record.Fields, record.SourceSpan));
+ changes.Add((record.SourceSpan.Start, record.SourceSpan.Length, string.Empty));
}
- foreach (Match declaration in Regex.Matches(source, @"\bStatic\s+[A-Za-z_]\w*\s*(?::\s*[A-Za-z_]\w*)?\s*=\s*[A-Za-z_]\w*\s*\[[^\]]+\]", RegexOptions.CultureInvariant))
- changes.Add((declaration.Index, declaration.Length, string.Empty));
foreach (Match header in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\[\]\s*=\s*\[", RegexOptions.CultureInvariant))
{
@@ -288,37 +290,42 @@ internal static class CanonicalStaticAuthoring
}
}
- foreach (Match pattern in Regex.Matches(source, @"\bPattern\s+(?<name>[A-Za-z_]\w*)\s+Over\s+(?<array>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
+ var patternSyntax = FirmamentSyntaxParser.Parse(source);
+ foreach (var pattern in FirmamentSyntaxTraversal.Declarations(patternSyntax.Document)
+ .Where(d => d.Type.Name.Text == "Pattern" && d.Clauses.Any(c => c.Kind == ClauseKind.Over)))
{
- var open = source.IndexOf('{', pattern.Index); var close = MatchPair(source, open, '{', '}');
- var sourceName = pattern.Groups["array"].Value;
- if (close >= 0 && setByName.TryGetValue(sourceName, out var set))
+ var patternName = pattern.Name?.Text ?? "<unnamed>";
+ var sourceName = pattern.Clauses.Count == 1 ? FirmamentSyntaxValues.Reference(pattern.Clauses[0].Value) : null;
+ if (pattern.Body is null || sourceName is null || pattern.Name is null || pattern.Parameters.Count > 0 || pattern.Annotation is not null
+ || pattern.Initializer is not null || pattern.ResultType is not null || pattern.Type.Span.Length > pattern.Type.Name.Span.Length || pattern.Modifiers.Count > 0 || pattern.Occurrence || pattern.HasParameterList)
+ { diagnostics.Add(Prefix + "pattern-source-invalid:" + patternName); continue; }
+ if (setByName.TryGetValue(sourceName, out var set))
{
- ExpandSetPattern(source, pattern, open, close, set, templateByName, changes, patterns, diagnostics);
+ ExpandSetPattern(pattern, set, templateByName, changes, patterns, diagnostics);
continue;
}
- if (close < 0 || !arrayByName.TryGetValue(sourceName, out var array)) { diagnostics.Add(Prefix + "pattern-source-invalid:" + pattern.Groups["name"].Value); continue; }
- var invocation = Regex.Match(source[(open + 1)..close], @"^(?:\s)*(?<template>[A-Za-z_]\w*)\s*(?:<\s*Current\s*>|\(\s*Current\s*\))\s*$", RegexOptions.CultureInvariant);
- if (!invocation.Success || !templateByName.TryGetValue(invocation.Groups["template"].Value, out var template) || template.Type != array.ElementType) { diagnostics.Add(Prefix + "pattern-body-invalid:" + pattern.Groups["name"].Value); continue; }
+ if (!arrayByName.TryGetValue(sourceName, out var array))
+ { diagnostics.Add(Prefix + "pattern-source-invalid:" + patternName); continue; }
+ var invocation = pattern.Body.Statements.Count == 1 ? TemplateInvocation(pattern.Body.Statements[0]) : null;
+ if (invocation is null || !templateByName.TryGetValue(invocation, out var template) || template.Type != array.ElementType)
+ { diagnostics.Add(Prefix + "pattern-body-invalid:" + patternName); continue; }
+ if (array.Elements.Count > MaxPatternExpansion)
+ { diagnostics.Add(Prefix + "pattern-expansion-limit:" + patternName); continue; }
var generated = new List<string>(); var output = new List<string>();
for (var index = 0; index < array.Elements.Count; index++)
{
- var id = pattern.Groups["name"].Value + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
+ var id = patternName + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
var declaration = Instantiate(template, array.Elements[index], id, true, diagnostics);
if (declaration is not null) { output.Add(declaration); generated.Add(id); }
}
- patterns.Add(new(pattern.Groups["name"].Value, array.Name, template.Name, generated.Count, generated, new(pattern.Index, close - pattern.Index + 1)));
- changes.Add((pattern.Index, close - pattern.Index + 1, string.Join(Environment.NewLine, output)));
- // PMI may target a semantic Pattern instance. Resolve that declaration identity
- // through the same deterministic materialization map used for generated features.
- for (var index = 0; index < generated.Count; index++)
+ patterns.Add(new(patternName, array.Name, template.Name, generated.Count, generated, pattern.Span));
+ changes.Add((pattern.Span.Start, pattern.Span.Length, string.Join(Environment.NewLine, output)));
+ foreach (var target in FirmamentSyntaxTraversal.Statements(patternSyntax.Document).OfType<FieldSyntax>()
+ .Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Target")))
{
- var semanticId = generated[index];
- var materializedId = semanticId.Replace("[", "_", StringComparison.Ordinal).Replace("]", string.Empty, StringComparison.Ordinal);
- foreach (Match target in Regex.Matches(source,
- $@"\bTarget\s*:\s*(?<id>{Regex.Escape(semanticId)})\b",
- RegexOptions.CultureInvariant))
- changes.Add((target.Groups["id"].Index, target.Groups["id"].Length, materializedId));
+ var id = FirmamentSyntaxWriter.Expression(target.Value);
+ if (generated.Contains(id, StringComparer.Ordinal))
+ changes.Add((target.Value.Span.Start, target.Value.Span.Length, id.Replace("[", "_", StringComparison.Ordinal).Replace("]", "", StringComparison.Ordinal)));
}
}
@@ -439,54 +446,59 @@ internal static class CanonicalStaticAuthoring
return result;
}
- private static void ExpandSetPattern(string source, Match pattern, int open, int close, FirmamentV2StaticSetDecl set,
+ private static string? TemplateInvocation(StatementSyntax statement)
+ {
+ var expression = (statement as ExpressionStatementSyntax)?.Value;
+ var (target, args) = expression switch
+ {
+ CallSyntax call => (call.Target as ReferenceSyntax, call.Arguments),
+ SpecializationSyntax specialization => (specialization.Target as ReferenceSyntax, specialization.Arguments),
+ _ => ((ReferenceSyntax?)null, (IReadOnlyList<ArgumentSyntax>)[])
+ };
+ return target is not null && args.Count == 1 && args[0].Name is null && args[0].Value is ReferenceSyntax { Name.Text: "Current" }
+ ? target.Name.Text : null;
+ }
+
+ private static void ExpandSetPattern(DeclarationSyntax pattern, FirmamentV2StaticSetDecl set,
IReadOnlyDictionary<string, Template> templates, List<(int Start, int Length, string Text)> changes,
List<FirmamentV2CanonicalPatternDecl> patterns, List<string> diagnostics)
{
- var patternName = pattern.Groups["name"].Value;
+ var patternName = pattern.Name!.Text;
if (set.Entries.Count > MaxPatternExpansion) { diagnostics.Add(Prefix + "pattern-expansion-limit:" + patternName + ":" + set.Entries.Count); return; }
- var body = source[(open + 1)..close].Trim();
- var arrow = Regex.Match(body, @"^(?<binder>[A-Za-z_]\w*)\s*=>\s*(?<mapping>[\s\S]+)$", RegexOptions.CultureInvariant);
- if (!arrow.Success) { diagnostics.Add(Prefix + "pattern-body-invalid:" + patternName); return; }
- var binder = arrow.Groups["binder"].Value; var mapping = arrow.Groups["mapping"].Value.Trim();
+ if (pattern.Body!.Statements.Count != 1 || pattern.Body.Statements[0] is not MappingSyntax mapping)
+ { diagnostics.Add(Prefix + "pattern-body-invalid:" + patternName); return; }
var output = new List<string>(); var generated = new List<string>(); var associations = new List<FirmamentV2PatternAssociation>();
+ var invocation = TemplateInvocation(mapping.Value);
foreach (var entry in set.Entries)
{
var semanticId = patternName + "." + entry.Name;
var materializedId = patternName + "_" + entry.Name;
- string? declaration;
- var templateCall = Regex.Match(mapping, @"^(?<template>[A-Za-z_]\w*)\s*(?:<\s*Current\s*>|\(\s*Current\s*\))$", RegexOptions.CultureInvariant);
- if (templateCall.Success && templates.TryGetValue(templateCall.Groups["template"].Value, out var template) && entry.RecordFields is not null && template.Type == set.ElementType)
- declaration = Instantiate(template, entry.RecordFields, materializedId, true, diagnostics);
+ string? text;
+ if (invocation is not null && templates.TryGetValue(invocation, out var template) && entry.RecordFields is not null && template.Type == set.ElementType)
+ text = Instantiate(template, entry.RecordFields, materializedId, true, diagnostics);
else
{
- declaration = mapping;
- declaration = SubstituteSetMapping(declaration,binder,entry);
- if (Regex.IsMatch(declaration, @"^Section\s+[A-Za-z_]\w*\s*\{"))
+ if (mapping.Value is not DeclarationSyntax declaration || declaration.Body is null || declaration.Name is null
+ || declaration.Type.Name.Text is not ("Hole" or "Slot" or "Boss" or "Pocket" or "EdgeFinish" or "Panel" or "Section"))
+ { diagnostics.Add(Prefix + "pattern-body-invalid:" + patternName); return; }
+ var substitution = BindSetElement(mapping.Key.Text, entry, diagnostics);
+ if (substitution is null) continue;
+ var bound = (DeclarationSyntax)substitution.Statement(declaration);
+ bound = bound with { Name = bound.Name! with { Text = materializedId } };
+ if (bound.Type.Name.Text != "Section")
{
- var sectionOpen = declaration.IndexOf('{');
- var sectionClose = MatchPair(declaration, sectionOpen, '{', '}');
- if (sectionClose != declaration.Length - 1 || Regex.Matches(declaration, @"\b(?:Pattern|Section)\s+", RegexOptions.CultureInvariant).Count != 1)
- { diagnostics.Add(Prefix + "pattern-body-invalid:" + patternName); return; }
- var sectionName = Regex.Match(declaration, @"^Section\s+(?<name>[A-Za-z_]\w*)").Groups["name"];
- declaration = declaration.Remove(sectionName.Index, sectionName.Length).Insert(sectionName.Index, materializedId);
- output.Add(declaration); generated.Add(semanticId);
- associations.Add(new(semanticId, set.Name, entry.Name, entry.Value, entry.SourceOrder, entry.Provenance));
- continue;
+ var value = FirmamentSyntaxParser.ParseExpression(semanticId).Expression!;
+ bound = bound with { Body = bound.Body! with { Statements = new StatementSyntax[] { new FieldSyntax(new("PatternIdentity", pattern.Span), value, pattern.Span) }.Concat(bound.Body.Statements).ToArray() } };
}
- var construction = Regex.Match(declaration, @"\b(?:Hole\s*<\s*(?:Shaft|Counterbore|Countersink)\s*>|Slot\s*<\s*(?:Capsule|RoundedRectangle)\s*>|Boss|Pocket|EdgeFinish|Panel)\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
- if (!construction.Success) { diagnostics.Add(Prefix + "pattern-body-invalid:" + patternName); return; }
- declaration = declaration.Remove(construction.Groups["name"].Index, construction.Groups["name"].Length).Insert(construction.Groups["name"].Index, materializedId);
- var openingBrace = declaration.IndexOf('{', construction.Index);
- declaration = declaration.Insert(openingBrace + 1, " PatternIdentity: " + semanticId + " ");
+ text = FirmamentSyntaxWriter.Statement(bound);
}
- if (declaration is null) continue;
- output.Add(declaration); generated.Add(semanticId);
+ if (text is null) continue;
+ output.Add(text); generated.Add(semanticId);
associations.Add(new(semanticId, set.Name, entry.Name, entry.Value, entry.SourceOrder, entry.Provenance));
}
- patterns.Add(new(patternName, set.Name, Regex.Match(mapping, @"^[A-Za-z_]\w*").Value, generated.Count, generated,
- new(pattern.Index, close - pattern.Index + 1), associations));
- changes.Add((pattern.Index, close - pattern.Index + 1, string.Join(Environment.NewLine, output)));
+ patterns.Add(new(patternName, set.Name, invocation ?? (mapping.Value as DeclarationSyntax)?.Type.Name.Text ?? "mapping",
+ generated.Count, generated, pattern.Span, associations));
+ changes.Add((pattern.Span.Start, pattern.Span.Length, string.Join(Environment.NewLine, output)));
}
private static bool IsSupportedSetElementType(string type, IReadOnlyDictionary<string, FirmamentV2RecordTypeDecl> records) =>
@@ -551,36 +563,27 @@ internal static class CanonicalStaticAuthoring
private static string? Instantiate(Template template, IReadOnlyDictionary<string, string> values, string id, bool patterned, List<string> diagnostics)
{
- var declaration = Regex.Match(template.Body, @"\b(?<kind>Hole\s*<\s*(?:Shaft|Counterbore)\s*>|Slot\s*<\s*(?:Capsule|RoundedRectangle)\s*>|Profile|StandardPart)\s+(?<name>[A-Za-z_]\w*)(?<tail>\s+Using\s+[A-Za-z_]\w*)?\s*\{", RegexOptions.CultureInvariant);
- if (!declaration.Success) { diagnostics.Add(Prefix + "template-output-unsupported:" + template.Name); return null; }
- var kind = declaration.Groups["kind"].Value;
- if (patterned && string.Equals(kind, "Profile", StringComparison.Ordinal))
+ var syntax = FirmamentSyntaxParser.Parse(template.Body);
+ if (!syntax.IsSuccess || syntax.Document.Statements.Count != 1 || syntax.Document.Statements[0] is not DeclarationSyntax declaration
+ || declaration.Body is null || declaration.Name is null || declaration.Type.Name.Text is not ("Hole" or "Slot" or "Profile" or "StandardPart"))
+ { diagnostics.Add(Prefix + "template-output-unsupported:" + template.Name); return null; }
+ if (patterned && declaration.Type.Name.Text == "Profile")
+ { diagnostics.Add(Prefix + "pattern-output-unsupported:Profile"); return null; }
+ var bound = new Dictionary<string, ExpressionSyntax>(StringComparer.Ordinal);
+ foreach (var value in values)
{
- diagnostics.Add(Prefix + "pattern-output-unsupported:Profile");
- return null;
+ var parsed = FirmamentSyntaxParser.ParseExpression(value.Value);
+ if (parsed.Expression is null || parsed.Diagnostics.Count > 0)
+ { diagnostics.Add(Prefix + "template-value-invalid:" + template.Name + ":" + value.Key); return null; }
+ bound[template.Parameter + "." + value.Key] = parsed.Expression;
}
- var open = template.Body.IndexOf('{', declaration.Index); var close = MatchPair(template.Body, open, '{', '}');
- if (close < 0) { diagnostics.Add(Prefix + "template-output-unsupported:" + template.Name); return null; }
- var body = template.Body[(open + 1)..close];
- foreach (var value in values) body = Regex.Replace(body, $@"\b{Regex.Escape(template.Parameter)}\.{Regex.Escape(value.Key)}\b", value.Value);
- var outputName = string.Equals(kind, "Profile", StringComparison.Ordinal)
- ? declaration.Groups["name"].Value
- : id.Replace("[", "_", StringComparison.Ordinal).Replace("]", string.Empty, StringComparison.Ordinal);
- return $"{kind} {outputName}{declaration.Groups["tail"].Value} {{{body}}}";
+ declaration = (DeclarationSyntax)new FirmamentSyntaxSubstitution(bound).Statement(declaration);
+ if (declaration.Type.Name.Text != "Profile") declaration = declaration with
+ { Name = declaration.Name! with { Text = id.Replace("[", "_", StringComparison.Ordinal).Replace("]", "", StringComparison.Ordinal) } };
+ return FirmamentSyntaxWriter.Statement(declaration);
}
private static Dictionary<string, string> Fields(string body) => Regex.Matches(body, "\\b(?<name>[A-Za-z_]\\w*)\\s*:\\s*(?<value>\"[^\"]*\"|(?:Point2|Point3|Vector2|PlusMinus)\\s*\\([^)]*\\)|\\d+\\.\\d+\\.\\d+|\\d{4}-\\d{2}-\\d{2}|[A-Za-z_]\\w*|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?)", RegexOptions.CultureInvariant)
.Cast<Match>().ToDictionary(m => m.Groups["name"].Value, m => m.Groups["value"].Value, StringComparer.Ordinal);
- private static IReadOnlyDictionary<string, IReadOnlyList<string>> TableColumns(string source, int start, int end)
- {
- var columns = new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal);
- foreach (Match column in Regex.Matches(source[start..end], @"\b(?<name>[A-Za-z_]\w*)\s*:\s*\[", RegexOptions.CultureInvariant))
- {
- var open = start + column.Index + column.Value.LastIndexOf('['); var close = MatchPair(source, open, '[', ']');
- if (close < 0 || close > end) continue;
- columns[column.Groups["name"].Value] = Regex.Matches(source[(open + 1)..close], "\"[^\"]*\"|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?|[A-Za-z_]\\w*", RegexOptions.CultureInvariant).Cast<Match>().Select(match => match.Value).ToArray();
- }
- return columns;
- }
private static Dictionary<string, string> RequireFields(string body) => Regex.Matches(body, @"(?<name>[A-Za-z_]\w*)\s*:\s*(?<value>.*?)(?=\s+[A-Za-z_]\w*\s*:|$)", RegexOptions.CultureInvariant | RegexOptions.Singleline)
.Cast<Match>().ToDictionary(m => m.Groups["name"].Value, m => m.Groups["value"].Value.Trim(), StringComparer.Ordinal);
private static bool TrySubject(string text, out string subject, out string property)
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
index d6903be3..b79ff72f 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
@@ -135,7 +135,11 @@ public sealed record ConceptIrTemplateInstantiation(
string Status = "ExpandedBeforeFeatureAir",
IReadOnlyDictionary<string, string>? SelectedMatchArms = null,
IReadOnlyDictionary<string, ConceptIrTemplateRecordArgument>? RecordArguments = null,
- IReadOnlyDictionary<string, string>? RequireResults = null);
+ IReadOnlyDictionary<string, string>? RequireResults = null)
+{
+ public string? DefinitionScope { get; init; }
+ public string? BindingScope { get; init; }
+}
public sealed record ConceptIrDocument(
IReadOnlyList<ConceptIrDefinition> Concepts,
IReadOnlyList<ConceptIrStructInstance> Structs,
@@ -500,7 +504,11 @@ internal static class ConceptIrResolver
for (var index = 0; index < points.Points.Count; index++)
{
var generatedName = pattern.Groups["name"].Value + "_" + index.ToString(CultureInfo.InvariantCulture);
- var concreteBody = Regex.Replace(featureBody, $@"\b{Regex.Escape(item)}\b", source + "[" + index.ToString(CultureInfo.InvariantCulture) + "]");
+ var featureSyntax = FirmamentSyntaxParser.Parse(featureBody);
+ var element = FirmamentSyntaxParser.ParseExpression(source + "[" + index.ToString(CultureInfo.InvariantCulture) + "]").Expression;
+ if (!featureSyntax.IsSuccess || element is null) { diagnostics.Add("firmament-pattern-element-type-mismatch"); continue; }
+ var substitution = new FirmamentSyntaxSubstitution(new Dictionary<string, ExpressionSyntax>(StringComparer.Ordinal) { [item] = element });
+ var concreteBody = FirmamentSyntaxWriter.Statements(featureSyntax.Document.Statements.Select(substitution.Statement));
var concrete = $"hole<Shaft> {generatedName} {{{concreteBody}}}";
var one = ParseConceptHoles(concrete, bodyOffset + open + featureOpen, boxName, bounds, instances, materializedName, bindings, diagnostics);
if (one.Count != 1) continue;
@@ -862,7 +870,7 @@ internal static class ConceptIrResolver
{
return false;
}
- var components = FirmamentV2FeatureExpansion.SplitTopLevel(match.Groups["values"].Value);
+ var components = FirmamentSyntaxValues.Components(match.Groups["values"].Value);
if (components.Count != 3)
{
return false;
@@ -870,7 +878,7 @@ internal static class ConceptIrResolver
var values = new double[3];
for (int index = 0; index < components.Count; index++)
{
- if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(components[index].Text, out values[index], out string unit)
+ if (!FirmamentNumericEvaluation.TryEvaluateScalar(components[index].Text, out values[index], out string unit)
|| !double.IsFinite(values[index]) || (unit != "" && (name != "Origin" || unit != "mm")))
{
return false;
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs
index 96e16b06..df22b5ad 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs
@@ -1,3 +1,4 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using System.Globalization;
using System.Text.RegularExpressions;
@@ -42,7 +43,7 @@ internal static class ConceptPointAuthoring
{
var variables=function.Parameters.ToDictionary(p=>p.Name,p=>(1d,Unit(p.Type)),StringComparer.Ordinal);
var dependencies = Regex.Matches(function.Body,@"\b(?<name>[A-Za-z_]\w*)\s*\(").Select(m=>m.Groups["name"].Value).ToArray();
- if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(function.Body,variables,(name,args)=>Call(name,args,true,[]),true,out _,out var unit)
+ if (!FirmamentNumericEvaluation.TryEvaluateScalar(function.Body,variables,(name,args)=>Call(name,args,true,[]),true,out _,out var unit)
|| unit!=Unit(function.ReturnType)) diagnostics.Add(Prefix+"function-body-invalid:"+function.Name);
bool Cycle(string name,HashSet<string> visiting)
{
@@ -70,7 +71,7 @@ internal static class ConceptPointAuthoring
if(args[i].Unit!=Unit(function.Parameters[i].Type) || (!typeOnly && function.Parameters[i].Type=="Int" && !ValidInt(args[i].Value))) throw new FormatException();
if(typeOnly) return (1,Unit(function.ReturnType));
var variables=function.Parameters.Select((p,i)=>(p.Name,args[i])).ToDictionary(p=>p.Name,p=>p.Item2,StringComparer.Ordinal);
- if(!FirmamentV2FeatureExpansion.TryEvaluateScalar(function.Body,variables,(n,a)=>Call(n,a,false,active),false,out var value,out var unit)
+ if(!FirmamentNumericEvaluation.TryEvaluateScalar(function.Body,variables,(n,a)=>Call(n,a,false,active),false,out var value,out var unit)
|| unit!=Unit(function.ReturnType) || (function.ReturnType=="Int" && !ValidInt(value))) throw new FormatException();
return (value,unit);
}
@@ -80,7 +81,7 @@ internal static class ConceptPointAuthoring
internal bool Evaluate(string expression,IReadOnlyDictionary<string,(double Value,string Unit)> variables,out double value,out string unit)
{
_remainingCalls = 10000;
- return FirmamentV2FeatureExpansion.TryEvaluateScalar(expression,variables,(n,a)=>Call(n,a,false,[]),false,out value,out unit);
+ return FirmamentNumericEvaluation.TryEvaluateScalar(expression,variables,(n,a)=>Call(n,a,false,[]),false,out value,out unit);
}
// Only scalar consumer fields are normalized. No source code is executed.
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs
index 8a4d37b4..03f2a1e2 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs
@@ -19,9 +19,25 @@ internal sealed class FirmamentCompileTimeValues(string source)
private int nextIdentity;
private IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes = new Dictionary<string, TemplateRecordTypeIr>();
private readonly Dictionary<string, TemplateStaticRecordIr> recordValues = new(StringComparer.Ordinal);
- private readonly IReadOnlyDictionary<string, FirmamentV2SourceSpan> originalScopes = OriginalScopes(source);
+ private IReadOnlyDictionary<string, FirmamentV2SourceSpan> originalScopes = OriginalScopes(source);
+ private FirmamentDataBinding? dataBinding;
+
+ internal void UseDataBinding(FirmamentDataBinding binding)
+ {
+ dataBinding ??= binding;
+ if (!binding.IsChanged) return;
+ dataBinding = binding;
+ source = binding.Source;
+ originalSyntax = null;
+ originalScopes = OriginalScopes(source).ToDictionary(p => p.Key, p => binding.OriginalSpan(p.Value), StringComparer.Ordinal);
+ identifiers.UnionWith(FirmamentLanguageAnalysisService.Lex(source).Where(t => t.Shape == "identifier").Select(t => t.Text));
+ }
internal IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics => diagnostics;
+ internal IReadOnlyList<FirmamentV2DataSymbolBinding> DataBindings => dataBinding?.Symbols.Select(s =>
+ new FirmamentV2DataSymbolBinding(s.Name, s.Declaration.Type.Name.Text, s.Scope, s.Identity, s.Declaration.Span)).ToArray() ?? [];
+
+ internal void AddExpansionDiagnostics(IEnumerable<FirmamentV2ValidationDiagnostic> reported) => diagnostics.AddRange(reported);
internal void AddConceptDiagnostics(IEnumerable<FirmamentV2ValidationDiagnostic> reported, bool original = true, string? producerSource = null)
{
@@ -48,7 +64,7 @@ internal sealed class FirmamentCompileTimeValues(string source)
originalSyntax ??= FirmamentSyntaxParser.Parse(source).Document;
var matches = FirmamentSyntaxTraversal.Declarations(originalSyntax)
.Where(d => d.Type.Name.Text == type && d.Name?.Text == name && (modifier is null || d.Modifiers.Any(m => m.Name.Text == modifier))).ToArray();
- return matches.Length == 1 ? matches[0].Span : null;
+ return matches.Length == 1 ? dataBinding?.OriginalSpan(matches[0].Span) ?? matches[0].Span : null;
}
internal void BindExpandedScalars(string expanded, List<string> codes)
@@ -151,7 +167,8 @@ internal sealed class FirmamentCompileTimeValues(string source)
}
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);
- diagnostics.AddRange(bound.Diagnostics.Select(d => d with { IsOriginalSource = true }));
+ 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)
{
var definition = definitions[value.Name];
@@ -162,7 +179,8 @@ internal sealed class FirmamentCompileTimeValues(string source)
if (definition.Name.Text != value.Name) origins.Add(new("inline", definition.Span, value.Name));
if (definition.Initializer is ToleranceSyntax)
origins = origins.OrderByDescending(o => o.Binding == definition.Name.Text).ToList();
- values[value.Name] = value with { Origins = origins.Distinct().ToArray() };
+ values[value.Name] = value with { Origins = origins.Distinct().Select(o => dataBinding is null ? o
+ : o with { SourceSpan = dataBinding.OriginalSpan(o.SourceSpan), Binding = dataBinding.DisplayName(o.Binding) }).ToArray() };
}
void Add(string name, DeclarationSyntax declaration) => definitions[name] = declaration;
}
@@ -248,6 +266,50 @@ internal sealed class FirmamentCompileTimeValues(string source)
{
recordTypes = types;
foreach (var record in records) recordValues[record.Key] = record.Value;
+ // 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)
+ {
+ if (!types.ContainsKey(record.TypeName)) continue;
+ var flattenCodes = new List<string>();
+ var leaves = FirmamentV2TemplateExpansion.FlattenRecordFields(record, types, recordValues, flattenCodes);
+ foreach (var field in leaves)
+ {
+ var name = record.Name + "." + field.Key;
+ var type = RecordFieldType(record.TypeName, field.Key);
+ if (values.ContainsKey(name) || type is null || !IsScalar(type)) continue;
+ if (values.TryGetValue(field.Value, out var existing)) { values[name] = existing with { Name = name }; continue; }
+ var parsed = FirmamentSyntaxParser.ParseExpression(field.Value);
+ if (parsed.Expression is not { } expression || parsed.Diagnostics.Any(d => d.Severity is "error" or "fatal") || LegacyWideInteger(type, field.Value)) continue;
+ var codes = new List<string>();
+ var bound = FirmamentV2Parser.BindCompileTimeScalars([Scalar(name, type, expression, expression.Span)],
+ field.Value, "inline", codes, values.Values.ToArray());
+ var span = OriginalDeclaration("Static", record.Name);
+ diagnostics.AddRange(bound.Diagnostics.Select(d => d with { SourceSpan = span, IsOriginalSource = span is not null,
+ LocationNote = "Location identifies the enclosing Static value selected from Record/Table data." }));
+ if (bound.Values.FirstOrDefault(v => v.Name == name) is { } value)
+ values[name] = value with { SourceSpan = span ?? record.SourceSpan,
+ Origins = [new("inline", span ?? record.SourceSpan, DisplayDataName(name), record.Provenance)] };
+ }
+ }
+ }
+
+ internal string DisplayDataName(string name)
+ {
+ var dot = name.IndexOf('.');
+ return dot < 0 ? dataBinding?.DisplayName(name) ?? name
+ : (dataBinding?.DisplayName(name[..dot]) ?? name[..dot]) + name[dot..];
+ }
+
+ private string? RecordFieldType(string type, string path)
+ {
+ string? fieldType = null;
+ foreach (var part in path.Split('.'))
+ {
+ if (!recordTypes.TryGetValue(type, out var schema) || !schema.Fields.TryGetValue(part, out fieldType)) return null;
+ type = fieldType;
+ }
+ return fieldType;
}
internal bool IsRecordType(string type) => recordTypes.ContainsKey(type);
@@ -280,13 +342,7 @@ internal sealed class FirmamentCompileTimeValues(string source)
}
foreach (var field in result.ToArray())
{
- var schema = recordTypes[type];
- string? fieldType = null;
- foreach (var part in field.Key.Split('.'))
- {
- if (!schema.Fields.TryGetValue(part, out fieldType)) break;
- if (recordTypes.TryGetValue(fieldType, out var nested)) schema = nested;
- }
+ var fieldType = RecordFieldType(type, field.Key);
if (fieldType is not null && IsScalar(fieldType)
&& TryTransfer(field.Value, fieldType, binding + "." + field.Key, span, codes, out var transported))
result[field.Key] = transported;
@@ -353,7 +409,7 @@ internal sealed class FirmamentCompileTimeValues(string source)
{
if (d.Modifiers.Any(m => m.Name.Text is "Template" or "Concept") || d.Type.Name.Text is "Feature" or "Template") continue;
yield return d;
- if (d.Type.Name.Text == "Model" && d.Body is not null)
+ if (d.Type.Name.Text is not ("Record" or "Static" or "Enum" or "Table") && d.Body is not null)
foreach (var child in Scope(d.Body.Statements)) yield return child;
}
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs
index 30dee533..93c709c3 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs
@@ -1,3 +1,5 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
namespace Aetheris.Kernel.Firmament.FirmamentV2;
/// <summary>Stable compiler metadata consumed by Forge and generated host bindings.</summary>
@@ -109,6 +111,12 @@ public static class FirmamentTemplateHostBridge
{
ArgumentNullException.ThrowIfNull(moduleSource);
var collected = new List<string>();
+ var dataBinding = new FirmamentDataBinding(moduleSource);
+ collected.AddRange(dataBinding.Diagnostics.Select(d => d.Code + ": " + d.Message));
+ moduleSource = dataBinding.Source;
+ var export = new FirmamentTemplateSyntax(moduleSource, collected);
+ var position = dataBinding.OriginalSpan(new(export.ExportPosition, 0)).Start;
+ bool Visible(string space, string identity) => dataBinding.ResolveIdentity(space, dataBinding.DisplayName(identity), position) == identity;
var templates = FirmamentV2TemplateExpansion.Inspect(moduleSource, collected)
.Select(template => new FirmamentTemplateMetadata(
template.Name,
@@ -116,23 +124,26 @@ public static class FirmamentTemplateHostBridge
template.Parameters.Select(parameter => new FirmamentTemplateParameterMetadata(
parameter.Name,
parameter.Kind == "Type" ? FirmamentTemplateParameterKind.Type : FirmamentTemplateParameterKind.Value,
- parameter.TypeName,
- parameter.DefaultExpression,
+ dataBinding.DisplayName(parameter.TypeName),
+ parameter.DefaultExpression is null ? null : dataBinding.DisplayName(parameter.DefaultExpression),
parameter.ConstraintConcept)).ToArray(),
template.Constraints.Select(constraint => new FirmamentTemplateConstraintMetadata(
constraint.Name,
constraint.Expression)).ToArray()))
.ToArray();
var records = FirmamentV2TemplateExpansion.InspectRecords(moduleSource, collected)
- .Select(record => new FirmamentTemplateRecordMetadata(record.Name,
- record.Fields.Select(field => new FirmamentTemplateRecordFieldMetadata(field.Key, field.Value)).ToArray()))
+ .Where(record => Visible("type", record.Name))
+ .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)
- .Select(item => new FirmamentTemplateEnumMetadata(item.Key, item.Value.ToArray()))
+ .Where(item => Visible("type", item.Key))
+ .Select(item => new FirmamentTemplateEnumMetadata(dataBinding.DisplayName(item.Key), item.Value.ToArray()))
.ToArray();
var staticRecords = FirmamentV2TemplateExpansion.InspectStaticRecords(moduleSource, collected)
+ .Where(record => Visible("value", record.Name))
.Select(record => new FirmamentTemplateStaticRecordMetadata(
- record.Name, record.TypeName, record.Fields, record.Provenance))
+ dataBinding.DisplayName(record.Name), dataBinding.DisplayName(record.TypeName), record.Fields, record.Provenance))
.ToArray();
diagnostics = collected.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();
return new(templates, records, enums, staticRecords);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 31a62422..2c6f1284 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -5,6 +5,7 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;
public sealed record FirmamentV2Document(string ModelName, string Units, IReadOnlyList<FirmamentV2SolidBinding> Solids, IReadOnlyList<FirmamentV2ModifyBlock>? ModifyBlocks = null, IReadOnlyList<FirmamentV2TemplateDecl>? Templates = null, IReadOnlyList<FirmamentV2PmiDecl>? Pmi = null, IReadOnlyList<FirmamentV2RecognizedRegion>? RecognizedRegions = null, IReadOnlyList<FirmamentV2ReplacementDecl>? Replacements = null, IReadOnlyList<FirmamentV2LetDeclaration>? Lets = null, IReadOnlyList<FirmamentV2BoundLet>? BoundLets = null, IReadOnlyList<FirmamentV2LetRecordDeclaration>? LetRecords = null, IReadOnlyList<FirmamentV2BoundLetRecord>? BoundLetRecords = null, IReadOnlyList<FirmamentV2ManufacturingConceptDeclaration>? ManufacturingConcepts = null, IReadOnlyList<FirmamentV2FeatureConceptDeclaration>? FeatureConcepts = null, FirmamentV2PmiBlock? PmiBlock = null, FirmamentV2BoundPmiBlock? BoundPmi = null, ConceptIrDocument? ConceptIr = null, IReadOnlyList<FirmamentV2LatticeFillDecl>? LatticeFills = null, IReadOnlyList<FirmamentV2StandaloneLatticeFillDecl>? StandaloneLatticeFills = null, IReadOnlyList<FirmamentV2ProfileDecl>? Profiles = null, IReadOnlyList<FirmamentV2ComposeDecl>? Composes = null, IReadOnlyList<FirmamentV2SelectionDecl>? Selections = null, FirmamentV2StaticAuthoringDocument? StaticAuthoring = null, FirmamentV2CanonicalSymbolTable? SymbolTable = null, IReadOnlyList<FirmamentV2VolumeAssertion>? VolumeAssertions = null, IReadOnlyList<ConceptIrTemplateInstantiation>? TemplateInstantiations = null, IReadOnlyList<PanelIr>? Panels = null, IReadOnlyList<FirmamentV2BossDecl>? Bosses = null, IReadOnlyList<FirmamentV2PocketDecl>? Pockets = null, IReadOnlyList<FirmamentV2FeatureDefinition>? FeatureDefinitions = null, IReadOnlyList<FirmamentV2FeatureInvocation>? FeatureInvocations = null, FirmamentV2FeatureExpansionMetrics? FeatureExpansion = null, IReadOnlyList<FirmamentV2Polygon2Decl>? Polygons = null, IReadOnlyList<FirmamentV2ClosedBoundary2Decl>? Boundaries = null, IReadOnlyList<FirmamentV2ThreadDecl>? Threads = null)
{
+ public IReadOnlyList<FirmamentV2DataSymbolBinding> DataBindings { get; init; } = [];
public FirmamentV2SolidBinding Solid => Solids[^1];
public FirmamentV2SideHoleIntent? SideHoleIntent => ModifyBlocks?.SelectMany(m => m.Regions.Select(r =>
{
@@ -15,6 +16,7 @@ public sealed record FirmamentV2Document(string ModelName, string Units, IReadOn
}
public sealed record FirmamentV2SourceSpan(int Start, int Length);
+public sealed record FirmamentV2DataSymbolBinding(string Name, string Kind, string Scope, string Identity, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2ThreadDecl(string Name, string SupportSolid, string SupportRole,
double MajorDiameterMm, double PitchMm, double LengthMm, double? StartOffsetMm,
string Hand, FirmamentV2SourceSpan SourceSpan);
@@ -149,6 +151,10 @@ public sealed record FirmamentV2FeatureInvocation(string Feature, int Ordinal, s
string ExpandedSemanticKind, string Status, string? ResultIdentity = null)
{
public string GeneratedByFeature => Feature;
+ public string? BindingScope { get; init; }
+ public FirmamentV2ValueOrigin? DefinitionOrigin { get; init; }
+ public FirmamentV2ValueOrigin? InvocationOrigin { get; init; }
+ public IReadOnlyList<string> ExpansionChain { get; init; } = [];
}
public sealed record FirmamentV2FeatureExpansionMetrics(int DefinitionCount, int InvocationCount,
int ExpandedSemanticNodeCount, string ExpansionOrder);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs
index 3d8bef95..00518653 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs
@@ -1,14 +1,11 @@
using System.Collections.Immutable;
using System.Globalization;
-using System.Text.RegularExpressions;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
-/// <summary>
-/// Bounded, pure expansion for Firmament's function-like Feature declarations.
-/// Feature bodies contain immutable local derivations/construction declarations and one
-/// terminal return. Expansion produces ordinary semantic declarations before Feature AIR.
-/// </summary>
+/// <summary>Scoped, finite AST specialization of pure terminal-return Features.
+/// Source serialization is the boundary to domain adapters not yet migrated to AST inputs.</summary>
internal static class FirmamentV2FeatureExpansion
{
internal const string Prefix = "firmament-feature-";
@@ -28,470 +25,336 @@ internal static class FirmamentV2FeatureExpansion
internal const string LocalType = Prefix + "local-type";
internal const string LocalDuplicate = Prefix + "local-duplicate";
internal const string UnsupportedBody = Prefix + "body-unsupported";
+ internal const int MaximumDepth = 64;
+ internal const int MaximumInvocations = 4096;
+ internal const int MaximumOutputCharacters = 4 * 1024 * 1024;
- private sealed record Parameter(string Name, string Type, string? DefaultExpression, FirmamentV2SourceSpan Span);
- private sealed record Declaration(string Name, ImmutableArray<Parameter> Parameters, string ReturnTypeName,
- string ReturnExpression, ImmutableArray<Local> Locals, string Construction, ImmutableArray<string> ConstructionNames, FirmamentV2SourceSpan Span);
- private sealed record Local(string Name, string Type, string Expression);
-
- internal sealed record Result(
- string Source,
- IReadOnlyList<FirmamentV2FeatureDefinition> Definitions,
- IReadOnlyList<FirmamentV2FeatureInvocation> Invocations,
- FirmamentV2FeatureExpansionMetrics Metrics);
+ private sealed record Definition(DeclarationSyntax Syntax, FirmamentBindingScope Scope, string ResultType,
+ ReturnSyntax Return, IReadOnlyList<DeclarationSyntax> Locals, IReadOnlyList<DeclarationSyntax> Construction);
+ internal sealed record Result(string Source, IReadOnlyList<FirmamentV2FeatureDefinition> Definitions,
+ IReadOnlyList<FirmamentV2FeatureInvocation> Invocations, FirmamentV2FeatureExpansionMetrics Metrics)
+ {
+ internal DocumentSyntax? Document { get; init; }
+ internal IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics { get; init; } = [];
+ }
- public static Result? Expand(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null)
+ internal static Result? Expand(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null,
+ string? originalSource = null)
{
- var declarations = ParseDeclarations(source, diagnostics);
- var byName = declarations.ToDictionary(item => item.Name, StringComparer.Ordinal);
- DetectCycles(declarations, byName, diagnostics);
- if (declarations.Length > 0)
+ var parsed = FirmamentSyntaxParser.Parse(source);
+ var declarations = FirmamentSyntaxTraversal.Declarations(parsed.Document)
+ .Where(d => d.Type.Name.Text == "Feature" && d.ResultType is not null).ToArray();
+ if (declarations.Length == 0) return new(source, [], [], new(0, 0, 0, "BoundedSourceOrder")) { Document = parsed.Document };
+ var located = new List<FirmamentV2ValidationDiagnostic>();
+ var original = FirmamentSyntaxParser.Parse(originalSource ?? source).Document;
+ var origins = new FirmamentSyntaxOrigins(original, parsed.Document);
+ FirmamentV2SourceSpan? OriginalDefinition(DeclarationSyntax d)
{
- foreach (Match possibleCall in Regex.Matches(source, @"(?m)^\s*(?<name>[A-Za-z_]\w*)\s*\(", RegexOptions.CultureInvariant))
- {
- if (declarations.Any(item => possibleCall.Index >= item.Span.Start && possibleCall.Index < item.Span.Start + item.Span.Length)) continue;
- var name = possibleCall.Groups["name"].Value;
- if (!byName.ContainsKey(name)) diagnostics.Add(Unknown + ":" + name);
- }
+ if (originalSource is null || originalSource == source) return d.Span;
+ return origins.Find(d.Span);
}
- if (HasErrors(diagnostics)) return null;
-
- var invocations = new List<FirmamentV2FeatureInvocation>();
- var ordinal = 0;
- string ExpandCall(Declaration declaration, string argumentText, FirmamentV2SourceSpan span,
- IReadOnlyList<string> stack, bool patternContext, string? resultName = null)
+ void Error(string code, string message, FirmamentV2SourceSpan span, DeclarationSyntax? definition = null)
{
- var bound = Bind(declaration, argumentText, span.Start, diagnostics, source, scalars);
- if (bound is null) return string.Empty;
- var invocationOrdinal = ordinal++;
- var environment = new Dictionary<string, string>(bound, StringComparer.Ordinal);
- foreach (var local in declaration.Locals)
- {
- if (environment.ContainsKey(local.Name))
- {
- diagnostics.Add(LocalDuplicate + $":{declaration.Name}:{local.Name}");
- return string.Empty;
- }
- var expression = Substitute(local.Expression, environment);
- if (scalars?.IsScalar(local.Type) == true && scalars.TryTransfer(expression, local.Type,
- $"Feature {declaration.Name}.{local.Name}", span, diagnostics, out var checkedValue))
- environment[local.Name] = NormalizeExpression(checkedValue, local.Type);
- else if (!TypeMatches(expression, local.Type))
- {
- diagnostics.Add(LocalType + $":{declaration.Name}:{local.Name}:expected-{local.Type}:actual-{DescribeType(expression)}");
- return string.Empty;
- }
- else environment[local.Name] = NormalizeExpression(expression, local.Type);
- }
-
- var construction = Substitute(declaration.Construction, environment);
- var returned = Substitute(declaration.ReturnExpression, environment).Trim();
- var prefix = resultName is null ? declaration.Name + "__" + invocationOrdinal.ToString(CultureInfo.InvariantCulture)
- : stack.Count == 1 ? resultName : resultName + "__Call" + invocationOrdinal.ToString(CultureInfo.InvariantCulture);
- foreach (var localName in declaration.ConstructionNames)
- {
- var generated = prefix + "__" + localName;
- construction = Regex.Replace(construction, $@"\b{Regex.Escape(localName)}\b(?!\s*:)", generated);
- returned = Regex.Replace(returned, $@"\b{Regex.Escape(localName)}\b(?!\s*:)", generated);
- }
- var nested = Regex.Match(returned, @"^(?<name>[A-Za-z_]\w*)\s*\((?<args>[\s\S]*)\)$", RegexOptions.CultureInvariant);
- string expanded;
- string expandedKind;
- if (nested.Success && byName.TryGetValue(nested.Groups["name"].Value, out var nestedDeclaration))
- {
- if (stack.Contains(nestedDeclaration.Name, StringComparer.Ordinal))
- {
- diagnostics.Add(Recursion + ":" + string.Join(":", stack.Append(nestedDeclaration.Name)));
- return string.Empty;
- }
- if (!SameType(declaration.ReturnTypeName, nestedDeclaration.ReturnTypeName))
- {
- diagnostics.Add(ReturnType + $":{declaration.Name}:expected-{declaration.ReturnTypeName}:actual-{nestedDeclaration.ReturnTypeName}");
- return string.Empty;
- }
- expanded = ExpandCall(nestedDeclaration, nested.Groups["args"].Value, span,
- stack.Append(nestedDeclaration.Name).ToArray(), patternContext, resultName);
- expandedKind = nestedDeclaration.ReturnTypeName;
- }
- else
+ diagnostics.Add(code);
+ var invocation = origins.Find(span);
+ var anchor = invocation ?? (definition is null ? null : OriginalDefinition(definition));
+ var unchanged = originalSource is null || originalSource == source;
+ located.Add(new(code, "fatal", message, Target: definition?.Name?.Text)
{
- var constructor = Regex.Match(returned,
- @"^(?<kind>Hole\s*<\s*(?:Shaft|Counterbore|Countersink)\s*>|Boss|Pocket|EdgeFinish|Profile)\s*\{",
- RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
- if (!constructor.Success)
- {
- diagnostics.Add(UnsupportedBody + ":" + declaration.Name);
- return string.Empty;
- }
- var constructorOpen = returned.IndexOf('{', constructor.Index);
- var constructorClose = Matching(returned, constructorOpen, '{', '}');
- if (constructorClose < 0 || !string.IsNullOrWhiteSpace(returned[(constructorClose + 1)..]))
- {
- diagnostics.Add(UnsupportedBody + ":" + declaration.Name + ":return-must-be-terminal");
- return string.Empty;
- }
- expandedKind = Regex.Replace(constructor.Groups["kind"].Value, @"\s+", string.Empty, RegexOptions.CultureInvariant);
- if (!SameType(declaration.ReturnTypeName, expandedKind))
- {
- diagnostics.Add(ReturnType + $":{declaration.Name}:expected-{declaration.ReturnTypeName}:actual-{expandedKind}");
- return string.Empty;
- }
- var generatedName = resultName ?? (patternContext
- ? PatternItemName(returned, declaration.Name, invocationOrdinal)
- : declaration.Name + "__" + invocationOrdinal.ToString(CultureInfo.InvariantCulture));
- expanded = returned.Insert(constructor.Index + constructor.Length - 1, " " + generatedName + " ");
- }
-
- invocations.Add(new(declaration.Name, invocationOrdinal, declaration.ReturnTypeName,
- bound, span, expandedKind, "ExpandedBeforeFeatureAir", resultName));
- return construction + "\n" + expanded;
+ SourceFile = unchanged || anchor is not null ? "inline" : "inline#pre-feature-expansion",
+ SourceSpan = unchanged ? span : anchor ?? span, IsOriginalSource = unchanged || anchor is not null, Stage = "Feature binding",
+ LocationNote = anchor is not null && !unchanged ? invocation is not null ? "Location identifies the original Feature use." : "Location identifies the original Feature definition; its invocation is in expanded source."
+ : unchanged ? null : "Location is in the input to Feature expansion; original-file mapping is unavailable."
+ });
}
-
- var changes = declarations.Select(item => (item.Span.Start, item.Span.Length, Text: string.Empty)).ToList();
- var callSites = declarations.SelectMany(declaration =>
+ Result? Failure()
{
- var callRegex = new Regex($@"\b{Regex.Escape(declaration.Name)}\s*\(", RegexOptions.CultureInvariant);
- return callRegex.Matches(source).Cast<Match>()
- .Where(call => !declarations.Any(item => call.Index >= item.Span.Start && call.Index < item.Span.Start + item.Span.Length))
- .Select(call => (Declaration: declaration, Call: call));
- }).OrderBy(item => item.Call.Index).ToArray();
- foreach (var site in callSites)
+ scalars?.AddExpansionDiagnostics(located);
+ return null;
+ }
+ bool Failed() => located.Count > 0 || diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal));
+ if (!parsed.IsSuccess)
{
- var open = source.IndexOf('(', site.Call.Index); var close = Matching(source, open, '(', ')');
- if (close < 0) { diagnostics.Add(ArgumentCount + ":" + site.Declaration.Name); continue; }
- var span = new FirmamentV2SourceSpan(site.Call.Index, close - site.Call.Index + 1);
- var named = Regex.Match(source[..site.Call.Index], @"\bFeature\s+(?<name>[A-Za-z_]\w*)\s*=\s*$");
- var patternContext = IsInsideBlock(source, site.Call.Index, "Pattern");
- var expansion = ExpandCall(site.Declaration, source[(open + 1)..close], span, [site.Declaration.Name], patternContext, named.Success ? named.Groups["name"].Value : null);
- if (expansion.Length > 0) changes.Add((named.Success ? named.Index : span.Start, close - (named.Success ? named.Index : span.Start) + 1, expansion));
+ foreach (var d in parsed.Diagnostics) { diagnostics.Add(d.Code); located.Add(d); }
+ return Failure();
}
- if (HasErrors(diagnostics)) return null;
- foreach (var change in changes.OrderByDescending(item => item.Start))
- source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
-
- var definitions = declarations.Select(item => new FirmamentV2FeatureDefinition(item.Name,
- item.Parameters.Select(parameter => new FirmamentV2FeatureParameter(parameter.Name, parameter.Type, parameter.DefaultExpression)).ToArray(),
- item.ReturnTypeName, item.Span, "FileLocal", "PureTerminalReturn")).ToArray();
- var orderedInvocations = invocations.OrderBy(item => item.Ordinal).ToArray();
- return new(source, definitions, orderedInvocations,
- new(definitions.Length, invocations.Count, invocations.Count, "BoundedSourceOrder"));
- }
-
- private static ImmutableArray<Declaration> ParseDeclarations(string source, List<string> diagnostics)
- {
- var result = ImmutableArray.CreateBuilder<Declaration>();
- var names = new HashSet<string>(StringComparer.Ordinal);
- foreach (Match header in Regex.Matches(source,
- @"\bFeature\s+(?<name>[A-Za-z_]\w*)\s*\([^()]*\)\s*->\s*(?<return>[A-Za-z_]\w*(?:\s*<\s*[A-Za-z_]\w*\s*>)?)\s*\{",
- RegexOptions.CultureInvariant))
+ var scopes = new Dictionary<DeclarationSyntax, FirmamentBindingScope>(ReferenceEqualityComparer.Instance);
+ var bodies = new Dictionary<BlockSyntax, FirmamentBindingScope>(ReferenceEqualityComparer.Instance);
+ var definitions = new Dictionary<DeclarationSyntax, Definition>(ReferenceEqualityComparer.Instance);
+ var root = new FirmamentBindingScope(null, "document");
+ void Collect(IReadOnlyList<StatementSyntax> statements, FirmamentBindingScope scope)
{
- var returnType = NormalizeType(header.Groups["return"].Value);
- if (!Regex.IsMatch(returnType, @"^(?:Hole<(?:Shaft|Counterbore|Countersink)>|Boss|Pocket|EdgeFinish|Profile)$", RegexOptions.CultureInvariant))
- diagnostics.Add(ReturnType + $":{header.Groups["name"].Value}:unsupported-{returnType}");
+ foreach (var mapping in statements.OfType<MappingSyntax>()) Collect([mapping.Value], scope);
+ foreach (var d in statements.OfType<DeclarationSyntax>())
+ {
+ scopes[d] = scope;
+ var kind = d.Type.Name.Text == "Feature" && d.ResultType is not null ? "Feature" : d.Type.Name.Text;
+ if (d.Name is not null && !scope.Declare(kind, d) && kind == "Feature")
+ Error(DuplicateName + ":" + d.Name.Text, $"Duplicate Feature '{d.Name.Text}' in {scope.Identity}.", d.Span, d);
+ }
+ foreach (var d in statements.OfType<DeclarationSyntax>().Where(d => d.Body is not null))
+ {
+ var child = new FirmamentBindingScope(scope, scope.Identity + "/" + d.Type.Name.Text + " " + d.Name?.Text);
+ bodies[d.Body!] = child; Collect(d.Body!.Statements, child);
+ }
}
- foreach (Match header in Regex.Matches(source,
- @"\bFeature\s+(?<name>[A-Za-z_]\w*)\s*\((?<parameters>[^()]*)\)\s*->\s*(?<return>Hole\s*<\s*[A-Za-z_]\w*\s*>|Boss|Pocket|EdgeFinish|Profile)\s*\{",
- RegexOptions.CultureInvariant))
+ Collect(parsed.Document.Statements, root);
+ foreach (var d in declarations)
{
- var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}');
- var name = header.Groups["name"].Value;
- if (close < 0) { diagnostics.Add(MissingReturn + ":" + name); continue; }
- if (!names.Add(name)) { diagnostics.Add(DuplicateName + ":" + name); continue; }
- var parameters = ParseParameters(header.Groups["parameters"].Value, header.Groups["parameters"].Index, name, diagnostics);
- var body = source[(open + 1)..close];
- foreach (Match keyword in Regex.Matches(body, @"\b(if|else|while|for|foreach|switch|match|goto|throw|try|catch|var)\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
- diagnostics.Add(ControlFlowUnsupported + ":" + keyword.Value.ToLowerInvariant());
- var returns = Regex.Matches(body, @"\breturn\b", RegexOptions.CultureInvariant);
- if (returns.Count == 0) { diagnostics.Add(MissingReturn + ":" + name); continue; }
- if (returns.Count != 1) { diagnostics.Add(MultipleReturns + ":" + name); continue; }
- var returnMatch = returns[0];
- var returnExpression = body[(returnMatch.Index + returnMatch.Length)..].Trim();
- if (returnExpression.EndsWith(';')) returnExpression = returnExpression[..^1].TrimEnd();
- var beforeReturn = body[..returnMatch.Index];
- var locals = ImmutableArray.CreateBuilder<Local>();
- var consumed = new List<(int Start, int Length)>();
- foreach (Match local in Regex.Matches(beforeReturn,
- @"\blet\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\s*=\s*(?<expression>[^;\r\n]+)\s*;?",
- RegexOptions.CultureInvariant))
+ var name = d.Name?.Text ?? "<unnamed>"; var resultType = TypeName(d.ResultType!);
+ if (!AllowedResult(resultType)) Error(ReturnType + $":{name}:unsupported-{resultType}", $"Feature '{name}' cannot return {resultType}; expected a supported Hole variant, Boss, Pocket, EdgeFinish or Profile.", d.Span, d);
+ var names = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var p in d.Parameters)
+ if (p.Name is null || p.Value is not ReferenceSyntax)
+ Error(InvalidParameter + ":" + name, $"Feature '{name}' expects named typed parameters.", p.Span, d);
+ else if (!names.Add(p.Name.Text)) Error(DuplicateParameter + $":{name}:{p.Name.Text}", $"Duplicate parameter '{p.Name.Text}' in Feature '{name}'.", p.Span, d);
+ if (d.Body is null || d.Name is null || d.Annotation is not null || d.Clauses.Count > 0 || d.Modifiers.Count > 0 || d.Initializer is not null
+ || d.Type.Span.Length > d.Type.Name.Span.Length || d.Occurrence || d.Target is not null || !d.HasParameterList)
+ { Error(UnsupportedBody + ":" + name, $"Feature '{name}' expects a non-generic name(parameters) definition, a body and terminal return; header placement and initialization clauses are not admitted.", d.Span, d); continue; }
+ var returns = d.Body.Statements.OfType<ReturnSyntax>().ToArray();
+ if (returns.Length != 1)
+ { Error((returns.Length == 0 ? MissingReturn : MultipleReturns) + ":" + name, $"Feature '{name}' must have exactly one terminal return.", d.Span, d); continue; }
+ if (!ReferenceEquals(returns[0], d.Body.Statements.Last()))
+ Error(UnsupportedBody + ":" + name + ":return-must-be-terminal", $"Feature '{name}' has statements after its return.", returns[0].Span, d);
+ var locals = new List<DeclarationSyntax>(); var construction = new List<DeclarationSyntax>();
+ foreach (var statement in d.Body.Statements.Where(s => s is not ReturnSyntax))
{
- locals.Add(new(local.Groups["name"].Value, local.Groups["type"].Value, local.Groups["expression"].Value.Trim()));
- consumed.Add((local.Index, local.Length));
+ if (statement is DeclarationSyntax { Type.Name.Text: "let", Name: not null, Annotation: ReferenceSyntax, Initializer: not null, Body: null,
+ Parameters.Count: 0, Modifiers.Count: 0, Clauses.Count: 0, ResultType: null, Occurrence: false, HasParameterList: false } local
+ && local.Type.Span.Length == local.Type.Name.Span.Length) locals.Add(local);
+ else if (statement is DeclarationSyntax { Body: not null, Name: not null, HasParameterList: false } c && c.Type.Name.Text is "Point2" or "Line2" or "CubicBezier2" or "Circle2" or "RoundedRect2" or "Rect2" or "Profile") construction.Add(c);
+ else { Error(UnsupportedBody + ":" + name, $"Unsupported statement in Feature '{name}'; use typed immutable let values and admitted private construction before return.", statement.Span, d); continue; }
+ var localName = ((DeclarationSyntax)statement).Name!.Text;
+ if (!names.Add(localName)) Error(LocalDuplicate + $":{name}:{localName}", $"Duplicate local name '{localName}' in Feature '{name}'.", statement.Span, d);
}
- var constructionNames = ImmutableArray.CreateBuilder<string>();
- var constructions = new List<string>();
- foreach (Match local in Regex.Matches(beforeReturn, @"\b(?:Point2|Line2|CubicBezier2|Circle2|RoundedRect2|Rect2|Profile)\s+(?<name>[A-Za-z_]\w*)\s*\{"))
+ definitions[d] = new(d, scopes[d], resultType, returns[0], locals, construction);
+ }
+ foreach (var definition in definitions.Values)
+ {
+ var returned = definition.Return.Value;
+ 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 })
{
- var localClose = Matching(beforeReturn, beforeReturn.IndexOf('{', local.Index), '{', '}');
- if (localClose < 0) { diagnostics.Add(UnsupportedBody + ":" + name); continue; }
- var localName = local.Groups["name"].Value;
- if (constructionNames.Contains(localName) || parameters.Any(p => p.Name == localName) || locals.Any(l => l.Name == localName))
- diagnostics.Add(LocalDuplicate + $":{name}:{localName}");
- constructionNames.Add(localName);
- constructions.Add(beforeReturn[local.Index..(localClose + 1)]);
- consumed.Add((local.Index, localClose - local.Index + 1));
+ if (definition.Scope.Resolve("Feature", call.Name.Text) is not { } target || !definitions.TryGetValue(target, out var nested))
+ Error(Unknown + ":" + call.Name.Text, $"Feature '{call.Name.Text}' is not visible from definition '{definition.Syntax.Name!.Text}'.", returned.Span, definition.Syntax);
+ else if (!SameType(definition.ResultType, nested.ResultType))
+ Error(ReturnType + $":{definition.Syntax.Name!.Text}:expected-{definition.ResultType}:actual-{nested.ResultType}", "Delegated Feature result does not match the declared return type.", returned.Span, definition.Syntax);
}
- var residue = beforeReturn;
- foreach (var item in consumed.OrderByDescending(item => item.Start)) residue = residue.Remove(item.Start, item.Length);
- if (!string.IsNullOrWhiteSpace(residue)) diagnostics.Add(UnsupportedBody + ":" + name);
- result.Add(new(name, parameters, NormalizeType(header.Groups["return"].Value),
- returnExpression, locals.ToImmutable(), string.Join("\n", constructions), constructionNames.ToImmutable(), new(header.Index, close - header.Index + 1)));
+ else if (returned is not ObjectSyntax { Type: not null, Name: null } obj || !SameType(definition.ResultType, TypeName(obj.Type)))
+ Error(ReturnType + $":{definition.Syntax.Name!.Text}:expected-{definition.ResultType}", $"Feature '{definition.Syntax.Name!.Text}' must return {definition.ResultType} construction or a Feature with that result type.", returned.Span, definition.Syntax);
}
- return result.ToImmutable();
- }
-
- private static ImmutableArray<Parameter> ParseParameters(string text, int offset, string feature, List<string> diagnostics)
- {
- var result = ImmutableArray.CreateBuilder<Parameter>(); var names = new HashSet<string>(StringComparer.Ordinal);
- foreach (var (raw, start) in SplitTopLevel(text))
+ var checkedDefinitions = new HashSet<DeclarationSyntax>(ReferenceEqualityComparer.Instance);
+ void CheckCycles(Definition definition, List<Definition> stack)
{
- var match = Regex.Match(raw.Trim(), @"^(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)(?:\s*=\s*(?<default>.+))?$", RegexOptions.CultureInvariant);
- if (!match.Success) { diagnostics.Add(InvalidParameter + ":" + feature + ":" + raw.Trim()); continue; }
- var name = match.Groups["name"].Value;
- if (!names.Add(name)) { diagnostics.Add(DuplicateParameter + ":" + feature + ":" + name); continue; }
- result.Add(new(name, match.Groups["type"].Value,
- match.Groups["default"].Success ? match.Groups["default"].Value.Trim() : null,
- new(offset + start, raw.Length)));
+ if (stack.Contains(definition))
+ { Error(Recursion + ":" + string.Join(":", stack.SkipWhile(d => d != definition).Append(definition).Select(d => d.Syntax.Name!.Text)), "Feature calls contain a recursive dependency. Use a finite, acyclic recipe.", definition.Return.Span, definition.Syntax); return; }
+ if (stack.Count >= MaximumDepth)
+ { Error(Prefix + "depth-limit", $"Feature specialization exceeds depth {MaximumDepth}.", definition.Syntax.Span, definition.Syntax); return; }
+ if (!checkedDefinitions.Add(definition.Syntax)) return;
+ if (definition.Return.Value is CallSyntax { Target: ReferenceSyntax r }
+ && definition.Scope.Resolve("Feature", r.Name.Text) is { } target && definitions.TryGetValue(target, out var nested)) CheckCycles(nested, [.. stack, definition]);
}
- return result.ToImmutable();
- }
+ foreach (var definition in definitions.Values) CheckCycles(definition, []);
+ if (Failed()) return Failure();
+ var invocations = new List<FirmamentV2FeatureInvocation>(); var ordinal = 0;
+ long emittedCharacters = 0;
+ var emittedDeclarations = 0;
+ var changes = new List<(FirmamentV2SourceSpan Span, string Text)>();
+ var replacements = new Dictionary<StatementSyntax, IReadOnlyList<StatementSyntax>>(ReferenceEqualityComparer.Instance);
- private static ImmutableDictionary<string, string>? Bind(Declaration declaration, string argumentText, int offset, List<string> diagnostics, string source,
- FirmamentCompileTimeValues? scalars = null)
- {
- var supplied = new Dictionary<string, string>(StringComparer.Ordinal); var position = 0;
- foreach (var (raw, _) in SplitTopLevel(argumentText))
+ IReadOnlyList<StatementSyntax> ExpandCall(Definition definition, CallSyntax call, FirmamentBindingScope callScope,
+ IReadOnlyList<Definition> stack, bool pattern, string? resultName = null)
{
- var colon = TopLevelColon(raw); string name; string expression;
- if (colon >= 0) { name = raw[..colon].Trim(); expression = raw[(colon + 1)..].Trim(); }
- else
+ if (stack.Contains(definition)) { Error(Recursion + ":" + string.Join(":", stack.Append(definition).Select(d => d.Syntax.Name!.Text)), "Recursive Feature invocation is not admitted.", call.Span, definition.Syntax); return []; }
+ if (stack.Count >= MaximumDepth || ordinal >= MaximumInvocations)
+ { Error(Prefix + "expansion-limit", $"Feature expansion is limited to depth {MaximumDepth} and {MaximumInvocations} invocations; no output was truncated.", call.Span, definition.Syntax); return []; }
+ var invocationOrdinal = ordinal++;
+ var environment = new Dictionary<string, ExpressionSyntax>(StringComparer.Ordinal);
+ var bindings = new Dictionary<string, string>(StringComparer.Ordinal);
+ var supplied = new Dictionary<string, ExpressionSyntax>(StringComparer.Ordinal); var position = 0;
+ foreach (var arg in call.Arguments)
{
- if (position >= declaration.Parameters.Length) { diagnostics.Add(ArgumentCount + ":" + declaration.Name); continue; }
- name = declaration.Parameters[position++].Name; expression = raw.Trim();
+ var name = arg.Name?.Text ?? (position < definition.Syntax.Parameters.Count ? definition.Syntax.Parameters[position++].Name!.Text : null);
+ if (name is null) { Error(ArgumentCount + ":" + definition.Syntax.Name!.Text, "Too many positional Feature arguments.", arg.Span, definition.Syntax); continue; }
+ if (!definition.Syntax.Parameters.Any(p => p.Name?.Text == name)) { Error(UnknownArgument + $":{definition.Syntax.Name!.Text}:{name}", $"Unknown Feature argument '{name}'.", arg.Span, definition.Syntax); continue; }
+ if (!supplied.TryAdd(name, arg.Value)) Error(DuplicateArgument + $":{definition.Syntax.Name!.Text}:{name}", $"Duplicate Feature argument '{name}'.", arg.Span, definition.Syntax);
}
- if (!declaration.Parameters.Any(parameter => parameter.Name == name)) { diagnostics.Add(UnknownArgument + $":{declaration.Name}:{name}"); continue; }
- if (!supplied.TryAdd(name, expression)) diagnostics.Add(DuplicateArgument + $":{declaration.Name}:{name}");
- }
- foreach (var parameter in declaration.Parameters)
- if (!supplied.ContainsKey(parameter.Name))
+ bool BindValue(ExpressionSyntax expression, string type, string name, FirmamentV2SourceSpan span, out ExpressionSyntax bound)
{
- if (parameter.DefaultExpression is null) diagnostics.Add(ArgumentCount + $":{declaration.Name}:missing-{parameter.Name}");
- else supplied[parameter.Name] = Substitute(parameter.DefaultExpression, supplied);
+ bound = expression; var text = FirmamentSyntaxWriter.Expression(expression);
+ if (scalars?.IsRecordType(type) == true)
+ {
+ if (!scalars.TryRecordTransfer(text, type, $"Feature {definition.Syntax.Name!.Text}.{name}", call.Span, diagnostics, out var fields))
+ { Error(ArgumentType + $":{definition.Syntax.Name!.Text}:{name}:expected-{type}", $"Feature input '{name}' requires Record {type}.", span, definition.Syntax); return false; }
+ foreach (var field in fields)
+ {
+ environment[name + "." + field.Key] = ParseValue(field.Value);
+ bindings[name + "." + field.Key] = field.Value;
+ }
+ return true;
+ }
+ if (scalars?.IsScalar(type) == true && scalars.TryTransfer(text, type, $"Feature {definition.Syntax.Name!.Text}.{name}", call.Span, diagnostics, out var transferred))
+ { bound = ParseValue(transferred); return true; }
+ if (!Matches(expression, type))
+ { Error(ArgumentType + $":{definition.Syntax.Name!.Text}:{name}:expected-{type}", $"Feature input '{name}' requires {type}; supplied {text}.", span, definition.Syntax); return false; }
+ bound = Normalize(expression, type); return true;
}
- foreach (var parameter in declaration.Parameters)
- if (supplied.TryGetValue(parameter.Name, out var expression))
+ var resolving = new HashSet<string>(StringComparer.Ordinal);
+ void BindParameter(ArgumentSyntax p)
{
- if (scalars?.IsRecordType(parameter.Type) == true)
+ var name = p.Name!.Text;
+ if (environment.ContainsKey(name)) return;
+ if (resolving.Count >= MaximumDepth)
+ { Error(Prefix + "default-depth-limit:" + name, $"Feature defaults exceed dependency depth {MaximumDepth}.", p.Span, definition.Syntax); return; }
+ if (!resolving.Add(name)) { Error(Prefix + "default-cycle:" + name, $"Feature default for '{name}' contains a dependency cycle.", p.Span, definition.Syntax); return; }
+ var explicitArgument = supplied.TryGetValue(name, out var value);
+ if (!explicitArgument)
{
- if (!scalars.TryRecordTransfer(expression, parameter.Type, $"Feature {declaration.Name}.{parameter.Name}",
- declaration.Span, diagnostics, out var fields))
- diagnostics.Add(ArgumentType + $":{declaration.Name}:{parameter.Name}:expected-{parameter.Type}:actual-{expression}:at-{offset}");
- else foreach (var field in fields) supplied[parameter.Name + "." + field.Key] = field.Value;
- continue;
+ if (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);
}
- if (parameter.Type == "Point2") expression = ResolvePointArgument(source, expression);
- if (scalars?.IsScalar(parameter.Type) == true && scalars.TryTransfer(expression, parameter.Type,
- $"Feature {declaration.Name}.{parameter.Name}", declaration.Span, diagnostics, out var checkedValue))
- supplied[parameter.Name] = NormalizeExpression(checkedValue, parameter.Type);
- else if (!TypeMatches(expression, parameter.Type))
- diagnostics.Add(ArgumentType + $":{declaration.Name}:{parameter.Name}:expected-{parameter.Type}:actual-{DescribeType(expression)}:at-{offset}");
- else supplied[parameter.Name] = NormalizeExpression(expression, parameter.Type);
+ var type = TypeName(p.Value);
+ if (type is "Point2" or "Point3") value = ResolvePoint(value!, explicitArgument ? callScope : definition.Scope);
+ if (BindValue(value!, type, name, p.Span, out var bound)) { environment[name] = bound; bindings[name] = FirmamentSyntaxWriter.Expression(bound); }
+ resolving.Remove(name);
}
- return HasErrors(diagnostics) ? null : supplied.ToImmutableDictionary(StringComparer.Ordinal);
- }
-
- private static string ResolvePointArgument(string source, string expression)
- {
- var reference = expression.Trim().Split('.');
- if (reference.Length is < 1 or > 2 || reference.Any(r => !Regex.IsMatch(r, @"^[A-Za-z_]\w*$"))) return expression;
- var scope = source;
- if (reference.Length == 2)
- {
- var owner = Regex.Match(source, $@"\bConcept\s+Struct\s+{Regex.Escape(reference[0])}\s+On\s+XY\s*\{{");
- var close = owner.Success ? Matching(source, source.IndexOf('{', owner.Index), '{', '}') : -1;
- if (close < 0) return expression;
- scope = source[owner.Index..(close + 1)];
- }
- var point = Regex.Match(scope, $@"\bPoint2\s+{Regex.Escape(reference[^1])}\s*\{{\s*Position\s*:\s*\[(?<value>[^]]+)\]");
- if (!point.Success) return expression;
- var values = point.Groups["value"].Value.Split(',');
- if (values.Length != 2 || !TryEvaluateScalar(values[0], out var x, out var xu) || xu != "mm"
- || !TryEvaluateScalar(values[1], out var y, out var yu) || yu != "mm") return expression;
- return $"Point2({x.ToString("R", CultureInfo.InvariantCulture)}mm,{y.ToString("R", CultureInfo.InvariantCulture)}mm)";
- }
-
- private static void DetectCycles(IEnumerable<Declaration> declarations, IReadOnlyDictionary<string, Declaration> byName, List<string> diagnostics)
- {
- foreach (var declaration in declarations)
- {
- var stack = new List<string>(); var complete = new HashSet<string>(StringComparer.Ordinal);
- bool Visit(string name)
+ foreach (var p in definition.Syntax.Parameters) BindParameter(p);
+ foreach (var local in definition.Locals)
{
- var at = stack.IndexOf(name);
- if (at >= 0) { diagnostics.Add(Recursion + ":" + string.Join(":", stack.Skip(at).Append(name))); return true; }
- if (!complete.Add(name)) return false;
- stack.Add(name);
- foreach (var target in byName.Keys.Where(candidate => Regex.IsMatch(byName[name].ReturnExpression, $@"^\s*{Regex.Escape(candidate)}\s*\(", RegexOptions.CultureInvariant)))
- if (Visit(target)) return true;
- stack.RemoveAt(stack.Count - 1); return false;
+ 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;
+ else Error(LocalType + $":{definition.Syntax.Name!.Text}:{local.Name.Text}:expected-{type}", $"Feature local '{local.Name.Text}' requires {type}.", local.Span, definition.Syntax);
}
- _ = Visit(declaration.Name);
- }
- }
-
- private static string Substitute(string expression, IReadOnlyDictionary<string, string> values)
- => FirmamentValueSubstitution.Apply(expression, values);
-
- private static bool TypeMatches(string expression, string type)
- {
- expression = expression.Trim(); type = NormalizeType(type);
- if (type is "FaceId" or "EdgeId" or "Body") return false;
- if (type == "Length") return TryEvaluateScalar(expression, out _, out var unit) && unit == "mm";
- if (type == "Angle") return TryEvaluateScalar(expression, out _, out var unit) && unit == "deg";
- if (type == "Int") return TryEvaluateScalar(expression, out var integer, out var intUnit) && intUnit.Length == 0 && integer == Math.Truncate(integer);
- if (type == "Float") return TryEvaluateScalar(expression, out _, out var floatUnit) && floatUnit.Length == 0;
- if (type == "Bool") return bool.TryParse(expression, out _);
- if (type is "Point2" or "Point3")
- {
- var arity = type == "Point2" ? 2 : 3;
- var match = Regex.Match(expression, @"^(?:Point[23]\s*\()?\s*\[?(?<body>[^\]\)]+)\]?\s*\)?$", RegexOptions.CultureInvariant);
- return (match.Success && SplitTopLevel(match.Groups["body"].Value).Count == arity
- && SplitTopLevel(match.Groups["body"].Value).All(item => TypeMatches(item.Text, "Length")))
- || Regex.IsMatch(expression, @"^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?(?:\[\d+\])?$", RegexOptions.CultureInvariant);
- }
- // Semantic references and Concept-bound values retain their typed spelling for the owning frontend.
- return Regex.IsMatch(expression, @"^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?(?:\[\d+\])?$", RegexOptions.CultureInvariant);
- }
-
- private static string NormalizeExpression(string expression, string type)
- {
- if (NormalizeType(type) is "Length" or "Angle" && TryEvaluateScalar(expression, out var value, out var unit))
- return value.ToString("R", CultureInfo.InvariantCulture) + unit;
- if (NormalizeType(type) is "Int" or "Float" && TryEvaluateScalar(expression, out value, out unit) && unit.Length == 0)
- return value.ToString("R", CultureInfo.InvariantCulture);
- if (NormalizeType(type) is "Point2" or "Point3")
- {
- var match = Regex.Match(expression.Trim(), @"^(?<prefix>Point[23]\s*\()?\s*(?<open>\[)?(?<body>[^\]\)]+)(?:\])?\s*(?:\))?$", RegexOptions.CultureInvariant);
- if (match.Success)
+ if (Failed()) return [];
+ var prefix = resultName is null ? definition.Syntax.Name!.Text + "__" + invocationOrdinal.ToString(CultureInfo.InvariantCulture)
+ : stack.Count == 0 ? resultName : resultName + "__Call" + invocationOrdinal.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);
+ if (returned is CallSyntax { Target: ReferenceSyntax nestedName } nestedCall
+ && definition.Scope.Resolve("Feature", nestedName.Name.Text) is { } nestedSyntax && definitions.TryGetValue(nestedSyntax, out var nested))
{
- var values = SplitTopLevel(match.Groups["body"].Value)
- .Select(item => TryEvaluateScalar(item.Text, out var component, out var componentUnit)
- ? component.ToString("R", CultureInfo.InvariantCulture) + componentUnit
- : item.Text.Trim()).ToArray();
- if (match.Groups["prefix"].Success) return NormalizeType(type) + "(" + string.Join(", ", values) + ")";
- if (match.Groups["open"].Success) return "[" + string.Join(", ", values) + "]";
+ if (!SameType(definition.ResultType, nested.ResultType)) Error(ReturnType + $":{definition.Syntax.Name!.Text}:expected-{definition.ResultType}:actual-{nested.ResultType}", "Delegated Feature result does not match the declared return type.", definition.Return.Span, definition.Syntax);
+ else output.AddRange(ExpandCall(nested, nestedCall, definition.Scope, stack.Append(definition).ToArray(), pattern, resultName));
}
- }
- return expression.Trim();
- }
-
- internal static bool TryEvaluateScalar(string expression, out double value, out string unit)
- {
- var parser = new ScalarParser(expression); return parser.TryParse(out value, out unit);
- }
-
- internal static bool TryEvaluateScalar(string expression, IReadOnlyDictionary<string, (double Value, string Unit)> variables,
- Func<string, IReadOnlyList<(double Value, string Unit)>, (double Value, string Unit)> functions,
- bool typeOnly, out double value, out string unit)
- => new ScalarParser(expression, variables, functions, typeOnly).TryParse(out value, out unit);
-
- private sealed class ScalarParser(string text,
- IReadOnlyDictionary<string, (double Value, string Unit)>? variables = null,
- Func<string, IReadOnlyList<(double Value, string Unit)>, (double Value, string Unit)>? functions = null,
- bool typeOnly = false)
- {
- private int _at;
- private int _depth;
- public bool TryParse(out double value, out string unit)
- {
- try { if (text.Length > 8192) throw new FormatException(); var result = Add(); White(); if (_at != text.Length || (!typeOnly && !double.IsFinite(result.Value))) throw new FormatException(); value = result.Value; unit = result.Unit; return true; }
- catch { value = 0; unit = string.Empty; return false; }
- }
- private (double Value, string Unit) Add()
- {
- var left = Multiply();
- while (true) { White(); if (!Take('+') && !Take('-')) return left; var op = text[_at - 1]; var right = Multiply(); if (left.Unit != right.Unit) throw new FormatException(); left = (op == '+' ? left.Value + right.Value : left.Value - right.Value, left.Unit); }
- }
- private (double Value, string Unit) Multiply()
- {
- var left = Atom();
- while (true)
+ else if (returned is ObjectSyntax { Type: not null, Name: null } obj && SameType(definition.ResultType, TypeName(obj.Type)))
{
- White(); if (!Take('*') && !Take('/')) return left; var op = text[_at - 1]; var right = Atom();
- if (op == '*') { if (left.Unit.Length > 0 && right.Unit.Length > 0) throw new FormatException(); left = (left.Value * right.Value, left.Unit.Length > 0 ? left.Unit : right.Unit); }
- else { if ((!typeOnly && right.Value == 0) || (right.Unit.Length > 0 && right.Unit != left.Unit)) throw new FormatException(); left = (typeOnly ? 1 : left.Value / right.Value, right.Unit.Length > 0 ? string.Empty : left.Unit); }
+ var generated = resultName ?? (pattern ? PatternItemName(obj, definition.Syntax.Name!.Text, invocationOrdinal) : definition.Syntax.Name!.Text + "__" + invocationOrdinal.ToString(CultureInfo.InvariantCulture));
+ output.Add(new DeclarationSyntax(ToType(obj.Type), new(generated, call.Span), [], [], null, null, [], null, obj.Body, false, definition.Return.Span));
}
+ else Error(ReturnType + $":{definition.Syntax.Name!.Text}:expected-{definition.ResultType}", $"Feature '{definition.Syntax.Name!.Text}' must return {definition.ResultType} construction or a Feature with that result type.", definition.Return.Span, definition.Syntax);
+ invocations.Add(new(definition.Syntax.Name!.Text, invocationOrdinal, definition.ResultType, bindings.ToImmutableDictionary(StringComparer.Ordinal), call.Span, definition.ResultType, "ExpandedBeforeFeatureAir", resultName)
+ {
+ BindingScope = definition.Scope.Identity,
+ DefinitionOrigin = new(OriginalDefinition(definition.Syntax) is null ? "inline#pre-feature-expansion" : "inline", OriginalDefinition(definition.Syntax) ?? definition.Syntax.Span, definition.Syntax.Name.Text,
+ OriginalDefinition(definition.Syntax) is null ? "Definition is in expanded input; original-file mapping unavailable." : null),
+ InvocationOrigin = new(origins.Find(call.Span) is null ? "inline#pre-feature-expansion" : "inline", origins.Find(call.Span) ?? call.Span, definition.Syntax.Name.Text,
+ origins.Find(call.Span) is null ? "Invocation offsets refer to the AST input of Feature expansion; original include/Template mapping is not yet available." : null),
+ ExpansionChain = stack.Select(d => d.Syntax.Name!.Text).Append(definition.Syntax.Name.Text).ToArray()
+ });
+ // Account only this invocation's own nodes; delegated nodes were already
+ // charged by their owner. Reject before retaining another large expansion.
+ foreach (var node in output.Take(definition.Construction.Count).Concat(returned is ObjectSyntax ? output.TakeLast(1) : []))
+ {
+ emittedCharacters += FirmamentSyntaxWriter.Statement(node).Length;
+ emittedDeclarations += FirmamentSyntaxTraversal.Declarations(node).Count();
+ if (emittedCharacters > MaximumOutputCharacters || emittedDeclarations > 65536)
+ { Error(Prefix + "output-limit", "Feature expansion exceeds 4 MiB or 65,536 declarations; no construction was truncated.", call.Span, definition.Syntax); return []; }
+ }
+ return output;
}
- private (double Value, string Unit) Atom()
- {
- if (++_depth > 128) throw new FormatException();
- try { return AtomCore(); }
- finally { _depth--; }
- }
- private (double Value, string Unit) AtomCore()
+ void Visit(IReadOnlyList<StatementSyntax> statements, FirmamentBindingScope scope, bool pattern)
{
- White(); if (Take('+')) return Atom(); if (Take('-')) { var negative = Atom(); return (-negative.Value, negative.Unit); }
- if (Take('(')) { var value = Add(); White(); if (!Take(')')) throw new FormatException(); return value; }
- if (_at < text.Length && (char.IsLetter(text[_at]) || text[_at] == '_'))
+ foreach (var statement in statements)
{
- var begin = _at++;
- while (_at < text.Length && (char.IsLetterOrDigit(text[_at]) || text[_at] == '_')) _at++;
- var name = text[begin.._at]; White();
- if (!Take('(')) return variables is not null && variables.TryGetValue(name, out var variable) ? variable : throw new FormatException();
- var arguments = new List<(double Value, string Unit)>(); White();
- if (!Take(')'))
+ if (statement is DeclarationSyntax d && definitions.ContainsKey(d)) { changes.Add((d.Span, "")); replacements[d] = []; continue; }
+ var call = statement switch { ExpressionStatementSyntax { Value: CallSyntax c } => c,
+ DeclarationSyntax { Type.Name.Text: "Feature", Initializer: CallSyntax c, ResultType: null } => c, _ => null };
+ if (call?.Target is ReferenceSyntax target)
{
- do { arguments.Add(Add()); White(); } while (Take(','));
- if (!Take(')')) throw new FormatException();
+ if (statement is DeclarationSyntax named && (named.Name is null || named.HasParameterList || named.Type.Span.Length > named.Type.Name.Span.Length
+ || named.Modifiers.Count > 0 || named.Clauses.Count > 0 || named.Annotation is not null || named.Body is not null || named.Occurrence))
+ { Error(UnsupportedBody + ":invocation-header", "A named invocation is Feature name = Recipe(arguments), without parameter, type, placement or body clauses.", named.Span); continue; }
+ if (scope.Resolve("Feature", target.Name.Text) is { } declaration && definitions.TryGetValue(declaration, out var definition))
+ {
+ var nodes = ExpandCall(definition, call, scope, [], pattern, (statement as DeclarationSyntax)?.Name?.Text);
+ changes.Add((statement.Span, FirmamentSyntaxWriter.Statements(nodes))); replacements[statement] = nodes;
+ }
+ else Error(Unknown + ":" + target.Name.Text, $"Feature '{target.Name.Text}' is not visible in {scope.Identity}.", call.Span);
}
- if (name == "Pow" && arguments.Count == 2 && arguments.All(a => a.Unit.Length == 0))
- return (typeOnly ? 1 : Math.Pow(arguments[0].Value, arguments[1].Value), string.Empty);
- return functions?.Invoke(name, arguments) ?? throw new FormatException();
+ // Static mappings contain values (Point2 constructors, for example),
+ // not statements invoking a Feature. Their owner binds those values.
+ else if (statement is DeclarationSyntax { Type.Name.Text: "Static" or "Table" or "Record" or "Enum" }) continue;
+ else if (statement is DeclarationSyntax { Body: not null } owner) Visit(owner.Body.Statements, bodies[owner.Body], pattern || owner.Type.Name.Text == "Pattern");
+ else if (statement is MappingSyntax mapping) Visit([mapping.Value], scope, true);
}
- var start = _at;
- while (_at < text.Length && (char.IsDigit(text[_at]) || text[_at] == '.')) _at++;
- if (_at < text.Length && text[_at] is 'e' or 'E')
- { _at++; if (_at < text.Length && text[_at] is '+' or '-') _at++; while (_at < text.Length && char.IsDigit(text[_at])) _at++; }
- if (start == _at || !double.TryParse(text[start.._at], NumberStyles.Float, CultureInfo.InvariantCulture, out var number)) throw new FormatException();
- var unit = text.AsSpan(_at).StartsWith("mm") ? "mm" : text.AsSpan(_at).StartsWith("deg") ? "deg" : string.Empty; _at += unit.Length; return (number, unit);
}
- private void White() { while (_at < text.Length && char.IsWhiteSpace(text[_at])) _at++; }
- private bool Take(char token) { if (_at >= text.Length || text[_at] != token) return false; _at++; return true; }
+ Visit(parsed.Document.Statements, root, false);
+ if (Failed()) return Failure();
+ if (source.Length + changes.Sum(c => (long)c.Text.Length - c.Span.Length) > MaximumOutputCharacters)
+ { Error(Prefix + "output-limit", $"Feature output exceeds {MaximumOutputCharacters} characters; no construction was truncated.", parsed.Document.Span); return Failure(); }
+ var projected = new ExpansionProjection(replacements).Rewrite(parsed.Document);
+ foreach (var change in changes.OrderByDescending(c => c.Span.Start)) source = source.Remove(change.Span.Start, change.Span.Length).Insert(change.Span.Start, change.Text);
+ var summaries = definitions.Values.Select(d => new FirmamentV2FeatureDefinition(d.Syntax.Name!.Text,
+ d.Syntax.Parameters.Select(p => new FirmamentV2FeatureParameter(p.Name!.Text, TypeName(p.Value), p.Default is null ? null : FirmamentSyntaxWriter.Expression(p.Default))).ToArray(),
+ d.ResultType, d.Syntax.Span, d.Scope.Identity, "PureTerminalReturn")).ToArray();
+ return new(source, summaries, invocations.OrderBy(i => i.Ordinal).ToArray(), new(summaries.Length, invocations.Count, emittedDeclarations, "BoundedSourceOrder")) { Document = projected, Diagnostics = located };
}
- private static string DescribeType(string expression)
+ private sealed class ExpansionProjection(IReadOnlyDictionary<StatementSyntax, IReadOnlyList<StatementSyntax>> replacements) : FirmamentSyntaxRewriter
{
- foreach (var type in new[] { "Length", "Angle", "Int", "Float", "Bool", "Point2", "Point3" }) if (TypeMatches(expression, type)) return type;
- return "Unknown";
+ internal DocumentSyntax Rewrite(DocumentSyntax document) => document with { Statements = Project(document.Statements) };
+ private StatementSyntax[] Project(IReadOnlyList<StatementSyntax> statements) => statements.SelectMany(s => replacements.TryGetValue(s, out var r) ? r : [Statement(s)]).ToArray();
+ internal override BlockSyntax Block(BlockSyntax block) => block with { Statements = Project(block.Statements) };
+ internal override StatementSyntax Statement(StatementSyntax statement) => statement is MappingSyntax m && replacements.TryGetValue(m.Value, out var nodes) && nodes.Count == 1
+ ? m with { Value = nodes[0] } : base.Statement(statement);
}
- private static string NormalizeType(string type) => Regex.Replace(type, @"\s+", string.Empty, RegexOptions.CultureInvariant);
- private static bool SameType(string left, string right) => string.Equals(NormalizeType(left), NormalizeType(right), StringComparison.OrdinalIgnoreCase);
- private static bool HasErrors(IEnumerable<string> diagnostics) => diagnostics.Any(item => item.StartsWith(Prefix, StringComparison.Ordinal));
- private static string PatternItemName(string returned, string feature, int ordinal)
+ private static TypeSyntax ToType(ExpressionSyntax e) => e switch
{
- var center = Regex.Match(returned, @"\bCenter\s*:\s*(?<item>[A-Za-z_]\w*)\b", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
- return center.Success ? center.Groups["item"].Value : feature + "__" + ordinal.ToString(CultureInfo.InvariantCulture);
+ ReferenceSyntax r => new(r.Name, [], r.Span),
+ SpecializationSyntax { Target: ReferenceSyntax r } s => new(r.Name, s.Arguments, s.Span),
+ _ => throw new InvalidOperationException("A checked Feature return must have a constructor type.")
+ };
+ private static string TypeName(ExpressionSyntax e) => FirmamentSyntaxWriter.Expression(e).Replace(" ", "", StringComparison.Ordinal);
+ private static bool SameType(string a, string b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
+ private static bool AllowedResult(string type) => type is "Hole<Shaft>" or "Hole<Counterbore>" or "Hole<Countersink>" or "Boss" or "Pocket" or "EdgeFinish" or "Profile";
+ private static ExpressionSyntax ParseValue(string source) => FirmamentSyntaxParser.ParseExpression(source).Expression ?? throw new InvalidOperationException("A checked compile-time value did not serialize as a Firmament expression.");
+ private static ExpressionSyntax ResolvePoint(ExpressionSyntax expression, FirmamentBindingScope scope)
+ {
+ DeclarationSyntax? point = expression switch
+ {
+ ReferenceSyntax r => scope.Resolve("Point2", r.Name.Text) ?? scope.Resolve("Point3", r.Name.Text),
+ MemberSyntax { Target: ReferenceSyntax owner } member when scope.Resolve("Struct", owner.Name.Text)?.Body is { } body
+ => body.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d => d.Name?.Text == member.Member.Text && d.Type.Name.Text is "Point2" or "Point3"),
+ _ => null
+ };
+ if (point?.Body?.Statements.OfType<FieldSyntax>().FirstOrDefault(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Position"))?.Value is not SequenceSyntax position) return expression;
+ return new CallSyntax(new ReferenceSyntax(point.Type.Name, point.Type.Span), position.Items, expression.Span);
}
- private static int TopLevelColon(string text)
+ private static bool Matches(ExpressionSyntax e, string type)
{
- var round = 0; var square = 0; var curly = 0;
- for (var i = 0; i < text.Length; i++) { switch (text[i]) { case '(': round++; break; case ')': round--; break; case '[': square++; break; case ']': square--; break; case '{': curly++; break; case '}': curly--; break; case ':' when round == 0 && square == 0 && curly == 0: return i; } }
- return -1;
+ if (type is "FaceId" or "EdgeId" or "Body") return false;
+ if (type is "Length" or "Angle" or "Int" or "Float") return FirmamentNumericEvaluation.TryEvaluate(e, out var n)
+ && n.Unit == (type == "Length" ? "mm" : type == "Angle" ? "deg" : "") && (type != "Int" || n.Number == Math.Truncate(n.Number));
+ if (type == "Bool") return e is LiteralSyntax { Kind: LiteralKind.Boolean };
+ if (type == "String") return e is LiteralSyntax { Kind: LiteralKind.String };
+ if (type is "Point2" or "Point3") return FirmamentSyntaxValues.Vector(e, "mm", out var components) && components.Length == (type == "Point2" ? 2 : 3) || e is ReferenceSyntax or MemberSyntax or IndexSyntax;
+ return e is ReferenceSyntax or MemberSyntax or IndexSyntax;
}
- internal static List<(string Text, int Start)> SplitTopLevel(string text)
+ private static ExpressionSyntax Normalize(ExpressionSyntax e, string type)
{
- var result = new List<(string, int)>(); var start = 0; var round = 0; var square = 0; var curly = 0;
- for (var i = 0; i < text.Length; i++)
+ if (type is "Length" or "Angle" or "Int" or "Float" && FirmamentNumericEvaluation.TryEvaluate(e, out var n)) return ParseValue(n.Number.ToString("R", CultureInfo.InvariantCulture) + n.Unit);
+ if (type is "Point2" or "Point3" && FirmamentSyntaxValues.Vector(e, "mm", out var components))
{
- switch (text[i]) { case '(': round++; break; case ')': round--; break; case '[': square++; break; case ']': square--; break; case '{': curly++; break; case '}': curly--; break; case ',' when round == 0 && square == 0 && curly == 0: result.Add((text[start..i], start)); start = i + 1; break; }
+ var args = components.Select(n => new ArgumentSyntax(null, ParseValue(n.ToString("R", CultureInfo.InvariantCulture) + "mm"), null, e.Span)).ToArray();
+ return e is CallSyntax c ? c with { Arguments = args } : new SequenceSyntax(SequenceKind.List, args, e.Span);
}
- if (!string.IsNullOrWhiteSpace(text[start..])) result.Add((text[start..], start));
- return result;
- }
- private static int Matching(string source, int open, char begin, char end) { var depth = 0; for (var i = open; i < source.Length; i++) { if (source[i] == begin) depth++; else if (source[i] == end && --depth == 0) return i; } return -1; }
- private static bool IsInsideBlock(string source, int index, string kind)
- {
- foreach (Match header in Regex.Matches(source, $@"\b{Regex.Escape(kind)}\s+[A-Za-z_]\w*\s*\{{", RegexOptions.CultureInvariant))
- { var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}'); if (header.Index < index && index < close) return true; }
- return false;
+ return e;
}
+ private static string PatternItemName(ObjectSyntax obj, string feature, int ordinal) => obj.Body.Statements.OfType<FieldSyntax>()
+ .FirstOrDefault(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Center"))?.Value is ReferenceSyntax r ? r.Name.Text : feature + "__" + ordinal.ToString(CultureInfo.InvariantCulture);
+
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 1f06c3b5..4949e92e 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -393,6 +393,7 @@ public static partial class FirmamentV2Parser
if (leading.Length == 2 && (leading[0].Text is "firmament" or "model" && leading[1].Text == ":"
|| leading[0].Text == "{" && leading[1].Shape == "string"))
return FirmamentV2ParseResult.Failure([], FirmamentV2ParseDisposition.NotRecognized) with { ParserRoute = "LegacySerialization" };
+ var authoredSourceText = sourceText;
sourceText = FirmamentSourceSpelling.Normalize(sourceText);
var valueSource = MaskCommentTrivia(sourceText);
sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);
@@ -438,7 +439,7 @@ public static partial class FirmamentV2Parser
// Record and scalar Static declarations still exist, then let canonical
// static authoring erase those compile-time declarations before AIR.
var compileTime = new FirmamentCompileTimeValues(valueSource);
- var templateExpansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics, compileTime);
+ var templateExpansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics, compileTime, authoredSourceText);
if (templateExpansion is null || compileTime.Diagnostics.Any(d => d.Severity is "error" or "fatal"))
{
diagnostics.Add("firmament-v2-parse-failed");
@@ -453,7 +454,7 @@ public static partial class FirmamentV2Parser
// Feature is Firmament's bounded function-like abstraction. It is expanded once,
// after typed Template specialization and before static pattern lowering, so every command consumes the
// same concrete semantic declarations and no geometry callback can bypass AIR.
- var featureExpansion = FirmamentV2FeatureExpansion.Expand(source, diagnostics, compileTime);
+ var featureExpansion = FirmamentV2FeatureExpansion.Expand(source, diagnostics, compileTime, authoredSourceText);
if (featureExpansion is null || compileTime.Diagnostics.Any(d => d.Severity is "error" or "fatal"))
{
diagnostics.Add("firmament-v2-parse-failed");
@@ -589,14 +590,14 @@ public static partial class FirmamentV2Parser
if (standaloneConstruction) parsed = parsed with { Document = parsed.Document with { ModelName = parsed.BoundProfile?.Name ?? parsed.BoundComposition?.Feature?.Name ?? parsed.Document.ModelName } };
return WithFeatureMetadata(
AttachVolumeAssertionsAndSymbols(WithPolygonMetadata(parsed, polygonExpansion), source, canonicalStaticExpansion.Document, diagnostics),
- featureExpansion) with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true, BoundSchema = FirmamentFrontendSchema.Mechanical, BoundSource = parsed.BoundSource ?? source };
+ featureExpansion, compileTime) with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true, BoundSchema = FirmamentFrontendSchema.Mechanical, BoundSource = parsed.BoundSource ?? source };
}
if (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),
- featureExpansion)) with { ParserRoute = "ConceptModeling" };
+ featureExpansion, compileTime)) with { ParserRoute = "ConceptModeling" };
if (ContainsRawBackendId(source)) diagnostics.Add(RawBackendIdReferenceForbidden);
if (ContainsUnsupportedConstruct(source)) diagnostics.Add(UnsupportedConstruct);
@@ -659,7 +660,8 @@ public static partial class FirmamentV2Parser
private static FirmamentV2ParseResult WithFeatureMetadata(
FirmamentV2ParseResult result,
- FirmamentV2FeatureExpansion.Result expansion) =>
+ FirmamentV2FeatureExpansion.Result expansion,
+ FirmamentCompileTimeValues? values = null) =>
result.Document is null
? result
: result with
@@ -668,7 +670,8 @@ public static partial class FirmamentV2Parser
{
FeatureDefinitions = expansion.Definitions,
FeatureInvocations = expansion.Invocations,
- FeatureExpansion = expansion.Metrics
+ FeatureExpansion = expansion.Metrics,
+ DataBindings = values?.DataBindings ?? []
}
};
@@ -987,24 +990,15 @@ public static partial class FirmamentV2Parser
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);
}
private static bool IsZero(FirmamentV2LiteralValue v) => v.NumericValue is double d && d == 0d;
- internal static FirmamentV2PrimitiveType? ResultType(FirmamentV2PrimitiveType a, string op, FirmamentV2PrimitiveType b) => op switch
- {
- "+" or "-" when a == b && a is FirmamentV2PrimitiveType.Int or FirmamentV2PrimitiveType.Float or FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle => a,
- "+" or "-" when IsNumeric(a) && IsNumeric(b) => FirmamentV2PrimitiveType.Float,
- "*" when IsNumeric(a) && IsNumeric(b) => a == FirmamentV2PrimitiveType.Int && b == FirmamentV2PrimitiveType.Int ? FirmamentV2PrimitiveType.Int : FirmamentV2PrimitiveType.Float,
- "*" when IsDim(a) && IsNumeric(b) => a,
- "*" when IsNumeric(a) && IsDim(b) => b,
- "/" when IsNumeric(a) && IsNumeric(b) => FirmamentV2PrimitiveType.Float,
- "/" when IsDim(a) && IsNumeric(b) => a,
- "/" when IsDim(a) && a == b => FirmamentV2PrimitiveType.Float,
- _ => null
- };
- private static bool IsNumeric(FirmamentV2PrimitiveType t) => t is FirmamentV2PrimitiveType.Int or FirmamentV2PrimitiveType.Float;
- private static bool IsDim(FirmamentV2PrimitiveType t) => t is FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle;
+ internal static FirmamentV2PrimitiveType? ResultType(FirmamentV2PrimitiveType a, string op, FirmamentV2PrimitiveType b) =>
+ FirmamentNumericEvaluation.ResultType(a, op, b);
private static FirmamentV2LiteralValue Compute(FirmamentV2PrimitiveType type, FirmamentV2LiteralValue l, string op, FirmamentV2LiteralValue r, string raw)
{
var a = Convert.ToDouble(l.NumericValue, CultureInfo.InvariantCulture); var b = Convert.ToDouble(r.NumericValue, CultureInfo.InvariantCulture);
- var d = op switch { "+" => a + b, "-" => a - b, "*" => a * b, "/" => a / b, _ => 0 };
+ 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))
+ return new(type, double.NaN, double.NaN, Raw: raw);
+ var d = computed.Number;
object value = type == FirmamentV2PrimitiveType.Int ? (object)(int)d : d;
return new(type, value, d, type == FirmamentV2PrimitiveType.Length ? "mm" : type == FirmamentV2PrimitiveType.Angle ? "deg" : null, raw);
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
index 50b39775..435d6c51 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
@@ -7,13 +7,23 @@ using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
-// Immutable parser/binder IR. Source text is payload for the already-established declaration parser;
-// it is never an authority for parameter meaning after TemplateIrParser has built these nodes.
-internal sealed record TemplateDeclarationIr(string Name, string TargetKind, string HeaderTail, ImmutableArray<TemplateParameterIr> Parameters, string Body, FirmamentV2SourceSpan SourceSpan);
+// AST-owned declaration/application binding. Body slices remain an explicit transport
+// boundary to the existing Record/Match/PMI specialization lowerers.
+internal sealed record TemplateDeclarationIr(string Name, string TargetKind, string HeaderTail, ImmutableArray<TemplateParameterIr> Parameters, string Body, FirmamentV2SourceSpan SourceSpan)
+{
+ internal FirmamentTemplateSyntax.Scope? DefinitionScope { get; init; }
+ internal FirmamentTemplateSyntax.Scope? BodyScope { get; init; }
+ internal List<TemplateApplicationIr> BodyApplications { get; } = [];
+ internal string? IdentityNamespace { get; set; }
+}
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 TemplateApplicationIr(string TargetKind, string InstanceName, string TemplateName, ImmutableArray<TemplateArgumentIr> Arguments, FirmamentV2SourceSpan SourceSpan);
+internal sealed record TemplateApplicationIr(string TargetKind, string InstanceName, string TemplateName, ImmutableArray<TemplateArgumentIr> Arguments, FirmamentV2SourceSpan SourceSpan)
+{
+ internal TemplateDeclarationIr? BoundTemplate { get; init; }
+ internal string? BindingScope { get; init; }
+}
internal sealed record TemplateArgumentIr(string Name, string Expression, FirmamentV2SourceSpan SourceSpan);
internal sealed record TemplateRecordTypeIr(string Name, ImmutableDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);
internal sealed record TemplateStaticRecordIr(string Name, string TypeName, ImmutableDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan, string Provenance = "StaticRecord")
@@ -101,7 +111,7 @@ internal static class FirmamentV2TemplateExpansion
string Provenance);
internal static IReadOnlyList<HostTemplate> Inspect(string source, List<string> diagnostics) =>
- ParseDeclarations(source, diagnostics)
+ ExportedDeclarations(source, diagnostics)
.Select(template => new HostTemplate(
template.Name,
template.TargetKind,
@@ -167,10 +177,15 @@ internal static class FirmamentV2TemplateExpansion
ArgumentException.ThrowIfNullOrWhiteSpace(instanceName);
ArgumentNullException.ThrowIfNull(hostArguments);
- var declarations = ParseDeclarations(source, diagnostics);
- var byName = declarations.ToDictionary(declaration => declaration.Name, StringComparer.Ordinal);
- DetectTemplateCycles(declarations, byName, diagnostics);
- if (!byName.TryGetValue(templateName, out var template))
+ var dataBinding = new FirmamentDataBinding(source);
+ diagnostics.AddRange(dataBinding.Diagnostics.Select(d => d.Code + ": " + d.Message));
+ if (dataBinding.Diagnostics.Count > 0) return null;
+ source = dataBinding.Source;
+ var syntax = new FirmamentTemplateSyntax(source, diagnostics);
+ var declarations = syntax.RemovableDeclarations;
+ DetectTemplateCycles(syntax.Declarations, diagnostics);
+ var template = syntax.ExportScope.Resolve(templateName);
+ if (template is null)
{
diagnostics.Add(Prefix + "not-found:" + templateName);
return null;
@@ -189,21 +204,22 @@ internal static class FirmamentV2TemplateExpansion
var arguments = ImmutableArray.CreateBuilder<TemplateArgumentIr>();
foreach (var pair in hostArguments.OrderBy(pair => pair.Key, StringComparer.Ordinal))
{
- var expression = pair.Value.Expression;
+ var expression = dataBinding.ResolveIdentity("value", pair.Value.Expression, dataBinding.OriginalSpan(template.SourceSpan).Start);
if (pair.Value.RecordFields is not null)
{
var recordName = $"__forge_{instanceName}_{pair.Key}";
- var recordType = pair.Value.RecordType ?? string.Empty;
+ var recordType = dataBinding.ResolveIdentity("type", pair.Value.RecordType ?? string.Empty, dataBinding.OriginalSpan(template.SourceSpan).Start);
if (!recordTypes.TryGetValue(recordType, out var recordDefinition))
{
diagnostics.Add(UnknownRecordType + $":{pair.Key}:{recordType}");
continue;
}
- ValidateSyntheticRecord(recordName, recordDefinition, pair.Value.RecordFields, string.Empty);
+ var recordFields = pair.Value.RecordFields.ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal);
+ ValidateSyntheticRecord(recordName, recordDefinition, recordFields, string.Empty);
staticRecords[recordName] = new TemplateStaticRecordIr(
recordName,
recordType,
- pair.Value.RecordFields.ToImmutableDictionary(StringComparer.Ordinal),
+ recordFields.ToImmutableDictionary(StringComparer.Ordinal),
new FirmamentV2SourceSpan(source.Length, 0),
"ForgeHostRecord");
expression = recordName;
@@ -256,10 +272,11 @@ internal static class FirmamentV2TemplateExpansion
application.SourceSpan,
SelectedMatchArms: selectedMatches,
RecordArguments: recordArguments,
- RequireResults: requireResults);
+ RequireResults: requireResults)
+ { DefinitionScope = template.DefinitionScope?.Identity, BindingScope = "host/document" };
var nestedInstantiations = new List<ConceptIrTemplateInstantiation>();
- body = ExpandNestedApplications(body, byName, source, enums, recordTypes, staticRecords,
- diagnostics, nestedInstantiations, [template.Name]);
+ body = ExpandNestedApplications(body, template, source, enums, recordTypes, staticRecords,
+ diagnostics, nestedInstantiations, [template]);
if (HasErrors(diagnostics)) return null;
var liftedPmi = LiftPmi(body, out body);
@@ -267,7 +284,7 @@ internal static class FirmamentV2TemplateExpansion
.Select(declaration => (
Start: declaration.SourceSpan.Start,
Length: declaration.SourceSpan.Length,
- Text: string.Equals(declaration.Name, template.Name, StringComparison.Ordinal)
+ Text: ReferenceEquals(declaration, template)
? RenderOutput(template.TargetKind, instanceName, template.HeaderTail, body) + liftedPmi
: string.Empty))
.OrderByDescending(change => change.Start)
@@ -277,7 +294,7 @@ internal static class FirmamentV2TemplateExpansion
return HasErrors(diagnostics) ? null : new Result(source, new[] { instantiation }.Concat(nestedInstantiations).ToArray());
void ValidateSyntheticRecord(string recordName, TemplateRecordTypeIr definition,
- IReadOnlyDictionary<string, string> fields, string prefix)
+ IDictionary<string, string> fields, string prefix)
{
foreach (var expected in definition.Fields)
{
@@ -289,6 +306,7 @@ internal static class FirmamentV2TemplateExpansion
}
if (recordTypes.TryGetValue(expected.Value, out var nested))
{
+ if (value == dataBinding.DisplayName(expected.Value)) { fields[path] = expected.Value; value = expected.Value; }
if (!string.Equals(value, expected.Value, StringComparison.Ordinal))
diagnostics.Add(RecordFieldTypeMismatch + $":{recordName}.{path}:expected-{expected.Value}:actual-{value}");
else ValidateSyntheticRecord(recordName, nested, fields, path + ".");
@@ -304,24 +322,37 @@ internal static class FirmamentV2TemplateExpansion
}
}
- public static Result? Expand(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null)
+ public static Result? Expand(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null, string? originalSource = null)
{
- var declarations = ParseDeclarations(source, diagnostics);
- var byName = declarations.ToDictionary(d => d.Name, StringComparer.Ordinal);
- DetectTemplateCycles(declarations, byName, diagnostics);
- var applications = ParseApplications(source, byName, diagnostics)
- .Where(application => !declarations.Any(declaration =>
- application.SourceSpan.Start > declaration.SourceSpan.Start
- && application.SourceSpan.Start < declaration.SourceSpan.Start + declaration.SourceSpan.Length))
- .ToImmutableArray();
+ var dataBinding = new FirmamentDataBinding(source);
+ diagnostics.AddRange(dataBinding.Diagnostics.Select(d => scalars is null ? d.Code + ": " + d.Message : d.Code));
+ scalars?.AddExpansionDiagnostics(dataBinding.Diagnostics);
+ if (dataBinding.Diagnostics.Count > 0) return null;
+ scalars?.UseDataBinding(dataBinding);
+ source = dataBinding.Source;
+ var syntax = new FirmamentTemplateSyntax(source, diagnostics);
+ if (scalars is not null && syntax.Diagnostics.Count > 0)
+ {
+ var origins = new FirmamentSyntaxOrigins(FirmamentSyntaxParser.Parse(originalSource ?? source).Document,
+ FirmamentSyntaxParser.Parse(source).Document);
+ scalars.AddExpansionDiagnostics(syntax.Diagnostics.Select(d =>
+ {
+ var anchor = d.SourceSpan is { } span ? origins.Find(span) : null;
+ return d with { SourceSpan = anchor ?? d.SourceSpan, IsOriginalSource = anchor is not null,
+ SourceFile = anchor is null ? d.SourceFile : "inline",
+ LocationNote = anchor is null ? d.LocationNote : "Location identifies the original enclosing Template declaration or application." };
+ }));
+ }
+ var declarations = syntax.RemovableDeclarations;
+ DetectTemplateCycles(syntax.Declarations, diagnostics);
+ var applications = syntax.Applications;
if (HasErrors(diagnostics)) return null;
- var enums = ParseEnums(source);
- var recordTypes = ParseRecordTypes(source, diagnostics);
- scalars?.Initialize(recordTypes, diagnostics);
- var tables = ParseStaticTables(source, recordTypes, enums, diagnostics);
- var staticRecords = ParseStaticRecords(source, recordTypes, enums, tables, diagnostics, scalars);
- scalars?.SetRecords(recordTypes, staticRecords);
+ var catalog = ReadDataCatalog(source, diagnostics, scalars, initialize: true);
+ var enums = catalog.Enums;
+ var recordTypes = catalog.Types;
+ var tables = catalog.Tables;
+ var staticRecords = catalog.Records;
var concepts = new FirmamentConcepts(source, scalars);
diagnostics.AddRange(concepts.Diagnostics.Select(d => d.Code + ": " + d.Message));
scalars?.AddConceptDiagnostics(concepts.Diagnostics, producerSource: source);
@@ -330,7 +361,7 @@ internal static class FirmamentV2TemplateExpansion
var instantiations = new List<ConceptIrTemplateInstantiation>();
foreach (var application in applications)
{
- var template = byName[application.TemplateName];
+ var template = application.BoundTemplate!;
if (!string.Equals(application.TargetKind, template.TargetKind, StringComparison.Ordinal)) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); continue; }
var bound = Bind(template, application, source, enums, recordTypes, staticRecords, diagnostics, scalars);
if (bound is null) continue;
@@ -346,39 +377,43 @@ internal static class FirmamentV2TemplateExpansion
pair.Value.TypeName, pair.Value.StaticName, pair.Value.Fields, pair.Value.SourceSpan, pair.Value.Provenance), StringComparer.Ordinal);
instantiations.Add(new(template.Name, application.InstanceName, bound.TypeArguments, bound.ValueArguments, bound.DefaultedArguments,
specialization.SpecializationIdentity, specialization.GeneratedDeclarationPaths, template.SourceSpan, application.SourceSpan,
- SelectedMatchArms: selectedMatches, RecordArguments: recordArguments, RequireResults: requireResults));
- body = ExpandNestedApplications(body, byName, source, enums, recordTypes, staticRecords,
- diagnostics, instantiations, [template.Name], scalars);
+ SelectedMatchArms: selectedMatches, RecordArguments: recordArguments, RequireResults: requireResults)
+ { DefinitionScope = template.DefinitionScope?.Identity, BindingScope = application.BindingScope });
+ body = ExpandNestedApplications(body, template, source, enums, recordTypes, staticRecords,
+ diagnostics, instantiations, [template], scalars);
var liftedPmi = LiftPmi(body, out body);
changes.Add((application.SourceSpan.Start, application.SourceSpan.Length, RenderOutput(template.TargetKind, application.InstanceName, template.HeaderTail, body) + liftedPmi));
}
if (HasErrors(diagnostics)) return null;
foreach (var change in changes.OrderByDescending(c => c.Start)) source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
+ if (instantiations.Count > 0)
+ {
+ // Concrete instances introduce their own Record/Static/Table scopes.
+ // 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,
+ 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);
+ _ = ReadDataCatalog(source, diagnostics, scalars);
+ }
+ if (HasErrors(diagnostics)) return null;
return new(source, instantiations);
}
internal static IReadOnlyList<FirmamentV2SourceSpan> DeclarationSpans(string source, List<string> diagnostics)
- => ParseDeclarations(source, diagnostics).Select(item => item.SourceSpan).ToArray();
+ // Boundary owners only need shielding spans. Binding here would discard
+ // structured errors before the specialization owner can present them.
+ => FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)
+ .Where(d => d.Modifiers.Any(m => m.Name.Text == "Template")).Select(d => d.Span).ToArray();
- private static ImmutableArray<TemplateDeclarationIr> ParseDeclarations(string source, List<string> diagnostics)
+ private static IEnumerable<TemplateDeclarationIr> ExportedDeclarations(string source, List<string> diagnostics)
{
- var result = ImmutableArray.CreateBuilder<TemplateDeclarationIr>(); var names = new HashSet<string>(StringComparer.Ordinal);
- foreach (Match start in Regex.Matches(source, @"\bTemplate\s*<", RegexOptions.CultureInvariant))
- {
- var open = source.IndexOf('<', start.Index); var close = Matching(source, open, '<', '>');
- var header = close < 0 ? Match.Empty : Regex.Match(source[(close + 1)..], @"^\s*(?<kind>Concept\s+Struct|Struct|Model|Panel|SheetMetal|ProfileDelta|Profile)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)(?<tail>\s*:\s*[A-Za-z_][A-Za-z0-9_]*)?\s*\{", RegexOptions.CultureInvariant);
- if (close >= 0 && !header.Success
- && Regex.IsMatch(source[(close + 1)..], @"^\s*[A-Za-z_][A-Za-z0-9_]*\s*\{", RegexOptions.CultureInvariant))
- continue; // finite feature Template; CanonicalStaticAuthoring owns this bounded form.
- if (close < 0 || !header.Success) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); continue; }
- var brace = close + 1 + header.Index + header.Value.LastIndexOf('{'); var end = Matching(source, brace, '{', '}');
- if (end < 0) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); continue; }
- var name = header.Groups["name"].Value;
- if (!names.Add(name)) { diagnostics.Add(DuplicateName + ":" + name); continue; }
- var parameters = ParseParameters(source[(open + 1)..close], open + 1, diagnostics);
- result.Add(new(name, header.Groups["kind"].Value, header.Groups["tail"].Value, parameters, source[(brace + 1)..end], new(start.Index, end - start.Index + 1)));
- }
- return result.ToImmutable();
+ var syntax = new FirmamentTemplateSyntax(source, diagnostics);
+ return syntax.Declarations.Where(d => ReferenceEquals(d.DefinitionScope, syntax.ExportScope));
}
private static string RenderOutput(string kind, string instance, string tail, string body)
@@ -407,45 +442,6 @@ internal static class FirmamentV2TemplateExpansion
return prelude + $"{kind} {instance}{tail} {{{body}}}";
}
- private static ImmutableArray<TemplateParameterIr> ParseParameters(string text, int offset, List<string> diagnostics)
- {
- var result = ImmutableArray.CreateBuilder<TemplateParameterIr>(); var names = new HashSet<string>(StringComparer.Ordinal);
- var cursor = 0;
- foreach (var raw in text.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
- {
- var span = new FirmamentV2SourceSpan(offset + cursor, raw.Length); cursor += raw.Length + 1;
- var type = Regex.Match(raw, @"^type\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s+satisfies\s+(?<concept>[A-Za-z_][A-Za-z0-9_]*)$", RegexOptions.CultureInvariant);
- var value = Regex.Match(raw, @"^(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<type>[A-Za-z_][A-Za-z0-9_]*)(?:\s*=\s*(?<default>.+))?$", RegexOptions.CultureInvariant);
- if (!type.Success && !value.Success) { diagnostics.Add(InvalidParameter + ":" + raw); continue; }
- var name = type.Success ? type.Groups["name"].Value : value.Groups["name"].Value;
- if (!names.Add(name)) { diagnostics.Add(DuplicateParameter + ":" + name); continue; }
- result.Add(type.Success ? new TemplateTypeParameterIr(name, type.Groups["concept"].Value, span) : new TemplateValueParameterIr(name, value.Groups["type"].Value, value.Groups["default"].Success ? value.Groups["default"].Value.Trim() : null, span));
- }
- return result.ToImmutable();
- }
-
- private static ImmutableArray<TemplateApplicationIr> ParseApplications(string source, IReadOnlyDictionary<string, TemplateDeclarationIr> templates, List<string> diagnostics)
- {
- var result = ImmutableArray.CreateBuilder<TemplateApplicationIr>();
- foreach (Match start in Regex.Matches(source, @"\b(?<kind>Concept\s+Struct|Struct|Model|Panel|SheetMetal|ProfileDelta|Profile)\s+(?<instance>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?<template>[A-Za-z_][A-Za-z0-9_]*)\s*<", RegexOptions.CultureInvariant))
- {
- if (!templates.ContainsKey(start.Groups["template"].Value)) continue;
- var open = source.IndexOf('<', start.Index); var close = Matching(source, open, '<', '>');
- if (close < 0) { diagnostics.Add(MissingArgument); continue; }
- var args = ImmutableArray.CreateBuilder<TemplateArgumentIr>(); var seen = new HashSet<string>(StringComparer.Ordinal);
- foreach (var raw in ConceptPointAuthoring.Components(source[(open + 1)..close]).Select(value => value.Trim()).Where(value => value.Length > 0))
- {
- var parsed = Regex.Match(raw, @"^(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<value>.+)$", RegexOptions.CultureInvariant);
- if (!parsed.Success) { diagnostics.Add(UnknownArgument + ":" + raw); continue; }
- var name = parsed.Groups["name"].Value;
- if (!seen.Add(name)) { diagnostics.Add(DuplicateArgument + ":" + name); continue; }
- args.Add(new(name, parsed.Groups["value"].Value.Trim(), new(start.Index, close - start.Index + 1)));
- }
- result.Add(new(start.Groups["kind"].Value, start.Groups["instance"].Value, start.Groups["template"].Value, args.ToImmutable(), new(start.Index, close - start.Index + 1)));
- }
- return result.ToImmutable();
- }
-
private static BoundTemplateArguments? Bind(TemplateDeclarationIr template, TemplateApplicationIr application, string source, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums,
IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes, IReadOnlyDictionary<string, TemplateStaticRecordIr> staticRecords, List<string> diagnostics,
FirmamentCompileTimeValues? scalars = null)
@@ -525,7 +521,9 @@ internal static class FirmamentV2TemplateExpansion
fields = checkedFields.ToImmutableDictionary(StringComparer.Ordinal);
}
else fields = FlattenRecordFields(staticRecord, recordTypes, staticRecords, diagnostics);
- records[parameter.Name] = new(parameter.Name, recordType.Name, staticRecord.AuthoredName ?? staticRecord.Name, fields, staticRecord.SourceSpan, staticRecord.Provenance);
+ records[parameter.Name] = new(parameter.Name, scalars?.DisplayDataName(recordType.Name) ?? recordType.Name,
+ scalars?.DisplayDataName(staticRecord.AuthoredName ?? staticRecord.Name) ?? staticRecord.AuthoredName ?? staticRecord.Name,
+ fields, staticRecord.SourceSpan, staticRecord.Provenance);
values[parameter.Name] = scalars?.RecordReference(staticRecord, fields) ?? staticRecord.Name;
return;
}
@@ -587,45 +585,80 @@ internal static class FirmamentV2TemplateExpansion
private static bool IsBuiltInValueType(string type, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums) =>
type is "Point3" or "Length" or "Angle" or "String" or "Version" or "Date" or "ImportedStep" or "ProfilePath" or "Int" or "Float" or "Bool" or "int" or "float" or "bool" || enums.ContainsKey(type);
+ internal sealed record DataCatalog(IReadOnlyDictionary<string, TemplateRecordTypeIr> Types,
+ IReadOnlyDictionary<string, TemplateStaticTableIr> Tables, IReadOnlyDictionary<string, TemplateStaticRecordIr> Records,
+ IReadOnlyDictionary<string, ImmutableHashSet<string>> Enums);
+
+ internal static DataCatalog ReadDataCatalog(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null, bool initialize = false)
+ {
+ var enums = ParseEnums(source);
+ var types = ParseRecordTypes(source, diagnostics);
+ if (initialize) scalars?.Initialize(types, diagnostics);
+ var tables = ParseStaticTables(source, types, enums, diagnostics, scalars);
+ if (HasErrors(diagnostics)) return new(types, tables, new Dictionary<string, TemplateStaticRecordIr>(), enums);
+ var records = ParseStaticRecords(source, types, enums, tables, diagnostics, scalars);
+ scalars?.SetRecords(types, records);
+ return new(types, tables, records, enums);
+ }
+
+ internal static IEnumerable<DeclarationSyntax> DataDeclarations(string source)
+ {
+ IEnumerable<DeclarationSyntax> Visit(IEnumerable<StatementSyntax> statements)
+ {
+ foreach (var declaration in statements.OfType<DeclarationSyntax>())
+ {
+ if (declaration.Modifiers.Any(m => m.Name.Text == "Template") || declaration.Type.Name.Text is "Template" or "Feature") continue;
+ yield return declaration;
+ if (declaration.Body is not null && declaration.Type.Name.Text is not ("Record" or "Enum" or "Static" or "Table"))
+ foreach (var nested in Visit(declaration.Body.Statements)) yield return nested;
+ }
+ }
+ return Visit(FirmamentSyntaxParser.Parse(source).Document.Statements);
+ }
+
private static IReadOnlyDictionary<string, TemplateRecordTypeIr> ParseRecordTypes(string source, List<string> diagnostics)
{
var result = new Dictionary<string, TemplateRecordTypeIr>(StringComparer.Ordinal);
- foreach (Match header in Regex.Matches(source, @"\bRecord\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
+ foreach (var declaration in DataDeclarations(source).Where(d => d.Type.Name.Text == "Record" && d.Name is not null && d.Body is not null))
{
- var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}');
- if (close < 0) continue;
var fields = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
- foreach (Match field in Regex.Matches(source[(open + 1)..close], @"\b(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)", RegexOptions.CultureInvariant))
- fields[field.Groups["name"].Value] = field.Groups["type"].Value;
- result[header.Groups["name"].Value] = new(header.Groups["name"].Value, fields.ToImmutable(), new(header.Index, close - header.Index + 1));
+ foreach (var statement in declaration.Body!.Statements)
+ {
+ if (statement is not FieldSyntax field) { diagnostics.Add(Prefix + "record-field-declaration:" + declaration.Name!.Text); continue; }
+ var type = FirmamentSyntaxValues.Reference(field.Value) ?? source.Substring(field.Value.Span.Start, field.Value.Span.Length);
+ if (!fields.TryAdd(field.Name.Text, type)) diagnostics.Add(Prefix + "record-duplicate-field:" + field.Name.Text);
+ }
+ if (!result.TryAdd(declaration.Name!.Text, new(declaration.Name.Text, fields.ToImmutable(), declaration.Span)))
+ diagnostics.Add(Prefix + "record-duplicate-name:" + declaration.Name.Text);
}
return result;
}
private static IReadOnlyDictionary<string, TemplateStaticTableIr> ParseStaticTables(string source, IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes,
- IReadOnlyDictionary<string, ImmutableHashSet<string>> enums, List<string> diagnostics)
+ IReadOnlyDictionary<string, ImmutableHashSet<string>> enums, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null)
{
var tables = new Dictionary<string, TemplateStaticTableIr>(StringComparer.Ordinal);
- foreach (Match header in Regex.Matches(source, @"\bStatic\s+Table\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)(?:\s+Key\s*:\s*(?<key>[A-Za-z_]\w*))?\s*\{", RegexOptions.CultureInvariant))
+ foreach (var declaration in DataDeclarations(source).Where(d => d.Type.Name.Text == "Table" && d.Modifiers.Any(m => m.Name.Text == "Static") && d.Name is not null))
{
- var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}');
- var name = header.Groups["name"].Value; var type = header.Groups["type"].Value; var key = header.Groups["key"].Success ? header.Groups["key"].Value : null;
- if (close < 0 || !recordTypes.TryGetValue(type, out var rowType)) { diagnostics.Add(TableUnknownRowType + ":" + name + ":" + type); continue; }
+ var name = declaration.Name!.Text;
+ var type = FirmamentSyntaxValues.Reference(declaration.Annotation) ?? "";
+ var key = declaration.Clauses.FirstOrDefault(c => c.Kind == ClauseKind.Key) is { } clause ? FirmamentSyntaxValues.Reference(clause.Value) : null;
+ if (declaration.Body is null || !recordTypes.TryGetValue(type, out var rowType)) { diagnostics.Add(TableUnknownRowType + ":" + name + ":" + type); continue; }
var columns = ImmutableDictionary.CreateBuilder<string, ImmutableArray<string>>(StringComparer.Ordinal);
- var body = source[(open + 1)..close];
- foreach (Match column in Regex.Matches(body, @"\b(?<name>[A-Za-z_]\w*)\s*:\s*\[", RegexOptions.CultureInvariant))
+ foreach (var statement in declaration.Body.Statements)
{
- var columnOpen = open + 1 + column.Index + column.Value.LastIndexOf('['); var columnClose = Matching(source, columnOpen, '[', ']');
- if (columnClose < 0 || columnClose > close) { diagnostics.Add(TableUnequalColumns + ":" + name + ":malformed-" + column.Groups["name"].Value); continue; }
- var columnName = column.Groups["name"].Value;
- if (columns.ContainsKey(columnName)) { diagnostics.Add(TableDuplicateKey + ":" + name + ":duplicate-column-" + columnName); continue; }
- columns[columnName] = SplitValues(source[(columnOpen + 1)..columnClose]).ToImmutableArray();
+ if (statement is not FieldSyntax { Value: SequenceSyntax { Kind: SequenceKind.List } values } column)
+ { diagnostics.Add(TableUnknownColumn + ":" + name + ":invalid-column"); continue; }
+ if (columns.ContainsKey(column.Name.Text)) { diagnostics.Add(TableDuplicateKey + ":" + name + ":duplicate-column-" + column.Name.Text); continue; }
+ if (values.Items.Any(a => FirmamentSyntaxTraversal.Expressions(a.Value).OfType<ToleranceSyntax>().Any()))
+ diagnostics.Add(FirmamentV2Parser.ToleranceUnsupported + ":Table:" + name + "." + column.Name.Text);
+ columns[column.Name.Text] = values.Items.Select(a => source.Substring(a.Value.Span.Start, a.Value.Span.Length)).ToImmutableArray();
}
foreach (var field in rowType.Fields.Keys.Where(field => !columns.ContainsKey(field))) diagnostics.Add(TableMissingColumn + ":" + name + ":" + field);
foreach (var column in columns.Keys.Where(column => !rowType.Fields.ContainsKey(column))) diagnostics.Add(TableUnknownColumn + ":" + name + ":" + column);
foreach (var column in columns)
if (rowType.Fields.TryGetValue(column.Key, out var expected))
- foreach (var value in column.Value.Where(value => !TypeMatches(value, expected, enums, recordTypes, null))) diagnostics.Add(TableColumnTypeMismatch + ":" + name + "." + column.Key + ":expected-" + expected + ":actual-" + value);
+ foreach (var value in column.Value.Where(value => !TypeMatches(value, expected, enums, recordTypes, null, scalars))) diagnostics.Add(TableColumnTypeMismatch + ":" + name + "." + column.Key + ":expected-" + expected + ":actual-" + value);
var lengths = columns.Values.Select(values => values.Length).Distinct().ToArray();
if (lengths.Length > 1) diagnostics.Add(TableUnequalColumns + ":" + name);
if (key is not null)
@@ -634,7 +667,7 @@ internal static class FirmamentV2TemplateExpansion
else if (keyType is not ("String" or "int") && !enums.ContainsKey(keyType)) diagnostics.Add(TableInvalidKey + ":" + name + ":" + keyType);
else if (columns[key].Distinct(StringComparer.Ordinal).Count() != columns[key].Length) diagnostics.Add(TableDuplicateKey + ":" + name + ":" + key);
}
- tables[name] = new(name, type, key, columns.ToImmutable(), new(header.Index, close - header.Index + 1));
+ tables[name] = new(name, type, key, columns.ToImmutable(), declaration.Span);
}
return tables;
}
@@ -644,112 +677,128 @@ internal static class FirmamentV2TemplateExpansion
FirmamentCompileTimeValues? scalars = null)
{
var result = new Dictionary<string, TemplateStaticRecordIr>(StringComparer.Ordinal);
- foreach (Match header in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)(?:\s*=\s*(?<literal>[A-Za-z_]\w*))?\s*\{", RegexOptions.CultureInvariant))
- {
- var name = header.Groups["name"].Value; var typeName = header.Groups["type"].Value; var literalType = header.Groups["literal"].Success ? header.Groups["literal"].Value : typeName;
- var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}');
- if (close < 0 || !recordTypes.TryGetValue(typeName, out var recordType)) continue;
- if (!string.Equals(typeName, literalType, StringComparison.Ordinal)) { diagnostics.Add(WrongRecordType + $":{name}:expected-{typeName}:actual-{literalType}"); continue; }
- var fields = ParseRecordFields(source[(open + 1)..close], recordType.Fields, diagnostics, scalars, name);
- foreach (var field in fields.ToArray())
- if (recordType.Fields.TryGetValue(field.Key, out var fieldType) && scalars is not null)
- fields[field.Key] = scalars.Field(name, field.Key, field.Value, fieldType, new(header.Index, close - header.Index + 1), diagnostics);
- foreach (var missing in recordType.Fields.Keys.Where(field => !fields.ContainsKey(field))) diagnostics.Add(RecordMissingField + ":" + name + ":" + missing);
- foreach (var extra in fields.Keys.Where(field => !recordType.Fields.ContainsKey(field))) diagnostics.Add(RecordExtraField + ":" + name + ":" + extra);
- foreach (var field in fields.Where(field => recordType.Fields.TryGetValue(field.Key, out var expected) && !recordTypes.ContainsKey(expected) && !TypeMatches(field.Value, expected, enums, recordTypes, result, scalars)))
- diagnostics.Add(RecordFieldTypeMismatch + ":" + name + "." + field.Key + ":expected-" + recordType.Fields[field.Key] + ":actual-" + field.Value);
- result[name] = new(name, typeName, fields.ToImmutableDictionary(StringComparer.Ordinal), new(header.Index, close - header.Index + 1));
- }
- foreach (Match declaration in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*(?::\s*(?<type>[A-Za-z_]\w*))?\s*=\s*(?<table>[A-Za-z_]\w*)\s*\[\s*(?<lookup>[^\]]+)\s*\]", RegexOptions.CultureInvariant))
- {
- if (!tables.TryGetValue(declaration.Groups["table"].Value, out var table)) continue;
- var lookup = declaration.Groups["lookup"].Value.Trim(); var index = -1;
- if (int.TryParse(lookup, NumberStyles.Integer, CultureInfo.InvariantCulture, out var numeric)) index = numeric;
- else if (table.KeyField is null) diagnostics.Add(TableLookupTypeMismatch + ":" + table.Name + ":index-required");
- else
- {
- var keyType = recordTypes[table.RowType].Fields[table.KeyField];
- if (!TypeMatches(lookup, keyType, enums, recordTypes, result)) diagnostics.Add(TableLookupTypeMismatch + ":" + table.Name + ":expected-" + keyType + ":actual-" + lookup);
- else index = table.Columns[table.KeyField].IndexOf(lookup);
- if (index < 0) diagnostics.Add(TableKeyNotFound + ":" + table.Name + ":" + lookup);
- }
- var rowCount = table.Columns.Count == 0 ? 0 : table.Columns.First().Value.Length;
- if (index < 0 || index >= rowCount) { if (int.TryParse(lookup, out _)) diagnostics.Add(TableIndexOutOfRange + ":" + table.Name + ":" + lookup); continue; }
- var requestedType = declaration.Groups["type"].Success ? declaration.Groups["type"].Value : table.RowType;
- if (!string.Equals(requestedType, table.RowType, StringComparison.Ordinal)) { diagnostics.Add(WrongRecordType + ":" + declaration.Groups["name"].Value + ":expected-" + requestedType + ":actual-" + table.RowType); continue; }
- var fields = table.Columns.ToImmutableDictionary(column => column.Key, column => column.Value[index], StringComparer.Ordinal);
- var keyDetail = table.KeyField is null ? string.Empty : " key:" + table.Columns[table.KeyField][index];
- result[declaration.Groups["name"].Value] = new(declaration.Groups["name"].Value, table.RowType, fields, new(declaration.Index, declaration.Length), "Table:" + table.Name + " row:" + index + keyDetail);
- }
- // Derived records are resolved in source order. This gives Static declarations the same
- // acyclic dependency discipline as existing template defaults without runtime values.
- var pending = Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*(?::\s*(?<type>[A-Za-z_]\w*))?\s*=\s*(?<base>[A-Za-z_]\w*)\s+with\s*\{", RegexOptions.CultureInvariant).Cast<Match>().ToArray();
- while (pending.Length > 0)
+ var 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 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;
- var remaining = new List<Match>();
- foreach (var declaration in pending)
- {
- var open = source.IndexOf('{', declaration.Index); var close = Matching(source, open, '{', '}');
- var name = declaration.Groups["name"].Value; var baseName = declaration.Groups["base"].Value;
- if (close < 0) { diagnostics.Add(WithBaseNotRecord + ":" + name + ":malformed"); continue; }
- if (!result.TryGetValue(baseName, out var baseRecord)) { remaining.Add(declaration); continue; }
- var type = declaration.Groups["type"].Success ? declaration.Groups["type"].Value : baseRecord.TypeName;
- if (!string.Equals(type, baseRecord.TypeName, StringComparison.Ordinal)) { diagnostics.Add(WrongRecordType + ":" + name + ":expected-" + type + ":actual-" + baseRecord.TypeName); continue; }
- var overrides = ParseRecordFields(source[(open + 1)..close], recordTypes[baseRecord.TypeName].Fields, diagnostics, scalars, name);
- foreach (var field in overrides.ToArray())
- if (recordTypes[baseRecord.TypeName].Fields.TryGetValue(field.Key, out var fieldType) && scalars is not null)
- overrides[field.Key] = scalars.Field(name, field.Key, field.Value, fieldType, new(declaration.Index, close - declaration.Index + 1), diagnostics);
- var overrideNames = Regex.Matches(source[(open + 1)..close], @"\b(?<name>[A-Za-z_]\w*)\s*:", RegexOptions.CultureInvariant).Cast<Match>().Select(match => match.Groups["name"].Value).ToArray();
- foreach (var duplicate in overrideNames.GroupBy(value => value, StringComparer.Ordinal).Where(group => group.Count() > 1)) diagnostics.Add(WithDuplicateField + ":" + name + ":" + duplicate.Key);
- foreach (var field in overrides.Keys.Where(field => !recordTypes[baseRecord.TypeName].Fields.ContainsKey(field))) diagnostics.Add(WithUnknownField + ":" + name + ":" + field);
- foreach (var field in overrideNames.Where(field => recordTypes[baseRecord.TypeName].Fields.ContainsKey(field) && !overrides.ContainsKey(field))) diagnostics.Add(WithTypeMismatch + ":" + name + "." + field + ":collection-or-unsupported-value");
- foreach (var field in overrides.Where(field => recordTypes[baseRecord.TypeName].Fields.TryGetValue(field.Key, out var expected) && !TypeMatches(field.Value, expected, enums, recordTypes, result, scalars))) diagnostics.Add(WithTypeMismatch + ":" + name + "." + field.Key + ":expected-" + recordTypes[baseRecord.TypeName].Fields[field.Key] + ":actual-" + field.Value);
- var fields = baseRecord.Fields.SetItems(overrides);
- var inherited = baseRecord.Fields.Values.Concat(overrides.Values).Where(result.ContainsKey).Select(value => result[value].Provenance).Distinct(StringComparer.Ordinal).ToArray();
- result[name] = new(name, type, fields, new(declaration.Index, close - declaration.Index + 1), baseRecord.Provenance + "; derivedFrom:" + baseName + (inherited.Length == 0 ? string.Empty : "; origin:" + string.Join("|", inherited)) + "; overrides:" + string.Join(",", overrides.Keys.OrderBy(value => value, StringComparer.Ordinal)));
- progressed = true;
- }
- if (!progressed)
- {
- foreach (var declaration in remaining) diagnostics.Add(WithBaseNotRecord + ":" + declaration.Groups["name"].Value + ":" + declaration.Groups["base"].Value);
- break;
- }
- pending = remaining.ToArray();
- }
- foreach (Match declaration in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*(?::\s*(?<type>[A-Za-z_]\w*))?\s*=\s*(?<table>[A-Za-z_]\w*)\s*\[\s*(?<lookup>[^\]]+)\s*\]", RegexOptions.CultureInvariant))
- {
- if (!tables.TryGetValue(declaration.Groups["table"].Value, out var table)) continue;
- var lookup = declaration.Groups["lookup"].Value.Trim(); var index = -1;
- if (int.TryParse(lookup, NumberStyles.Integer, CultureInfo.InvariantCulture, out var numeric)) index = numeric;
- else if (table.KeyField is null) diagnostics.Add(TableLookupTypeMismatch + ":" + table.Name + ":index-required");
- else
+ foreach (var declaration in pending.ToArray())
{
- var keyType = recordTypes[table.RowType].Fields[table.KeyField];
- if (!TypeMatches(lookup, keyType, enums, recordTypes, result)) diagnostics.Add(TableLookupTypeMismatch + ":" + table.Name + ":expected-" + keyType + ":actual-" + lookup);
- else index = table.Columns[table.KeyField].IndexOf(lookup);
- if (index < 0) diagnostics.Add(TableKeyNotFound + ":" + table.Name + ":" + lookup);
+ var name = declaration.Name!.Text;
+ var annotatedType = FirmamentSyntaxValues.Reference(declaration.Annotation);
+ if (declaration.Initializer is WithSyntax with)
+ {
+ var baseName = FirmamentSyntaxValues.Reference(with.Target) ?? "";
+ if (!result.TryGetValue(baseName, out var parent)) continue;
+ var type = annotatedType ?? parent.TypeName;
+ if (type != parent.TypeName) diagnostics.Add(WrongRecordType + ":" + name + ":expected-" + type + ":actual-" + parent.TypeName);
+ else
+ {
+ var schema = recordTypes[type];
+ foreach (var duplicate in with.Body.Statements.OfType<FieldSyntax>().GroupBy(f => f.Name.Text).Where(g => g.Count() > 1))
+ diagnostics.Add(WithDuplicateField + ":" + name + ":" + duplicate.Key);
+ var fields = Fields(with.Body, schema, name);
+ foreach (var extra in fields.Keys.Where(f => !schema.Fields.ContainsKey(f))) diagnostics.Add(WithUnknownField + ":" + name + ":" + extra);
+ Check(fields, schema, name, WithTypeMismatch);
+ result[name] = new(name, type, parent.Fields.SetItems(fields), declaration.Span,
+ parent.Provenance + "; derivedFrom:" + baseName + "; overrides:" + string.Join(",", fields.Keys.OrderBy(k => k, StringComparer.Ordinal)));
+ }
+ }
+ else if (declaration.Initializer is IndexSyntax index)
+ {
+ var tableName = FirmamentSyntaxValues.Reference(index.Target) ?? "";
+ if (!tables.TryGetValue(tableName, out var table)) continue;
+ var lookup = index.Index is null ? "" : Text(index.Index.Span);
+ if (scalars is not null && scalars.TryValue(lookup, out var lookupValue)) lookup = scalars.NominalExpression(lookupValue.Name);
+ var row = -1;
+ if (int.TryParse(lookup, NumberStyles.Integer, CultureInfo.InvariantCulture, out var number)) row = number;
+ else if (table.KeyField is null) diagnostics.Add(TableLookupTypeMismatch + ":" + table.Name + ":index-required");
+ else
+ {
+ var keyType = recordTypes[table.RowType].Fields[table.KeyField];
+ if (!TypeMatches(lookup, keyType, enums, recordTypes, result, scalars)) diagnostics.Add(TableLookupTypeMismatch + ":" + table.Name + ":expected-" + keyType + ":actual-" + lookup);
+ else row = table.Columns[table.KeyField].IndexOf(lookup);
+ if (row < 0) diagnostics.Add(TableKeyNotFound + ":" + table.Name + ":" + lookup);
+ }
+ var rowCount = table.Columns.Count == 0 ? 0 : table.Columns.First().Value.Length;
+ if (row < 0 || row >= rowCount)
+ {
+ if (int.TryParse(lookup, out _)) diagnostics.Add(TableIndexOutOfRange + ":" + table.Name + ":" + lookup);
+ }
+ else if (annotatedType is not null && annotatedType != table.RowType)
+ diagnostics.Add(WrongRecordType + ":" + name + ":expected-" + annotatedType + ":actual-" + table.RowType);
+ else
+ {
+ var fields = table.Columns.ToDictionary(c => c.Key, c => c.Value[row], StringComparer.Ordinal);
+ foreach (var field in fields.ToArray())
+ if (scalars is not null && recordTypes[table.RowType].Fields.TryGetValue(field.Key, out var fieldType))
+ fields[field.Key] = scalars.Field(name, field.Key, field.Value, fieldType, declaration.Span, diagnostics);
+ var keyDetail = table.KeyField is null ? "" : " key:" + table.Columns[table.KeyField][row];
+ result[name] = new(name, table.RowType, fields.ToImmutableDictionary(StringComparer.Ordinal), declaration.Span, "Table:" + table.Name + " row:" + row + keyDetail);
+ }
+ }
+ else if (declaration.Initializer is ReferenceSyntax reference)
+ {
+ if (!result.TryGetValue(reference.Name.Text, out var parent)) continue;
+ if (annotatedType != parent.TypeName) diagnostics.Add(WrongRecordType + ":" + name + ":expected-" + annotatedType + ":actual-" + parent.TypeName);
+ else result[name] = parent with { Name = name, SourceSpan = declaration.Span, Provenance = parent.Provenance + "; derivedFrom:" + parent.Name };
+ }
+ else
+ {
+ 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; }
+ var literalType = FirmamentSyntaxValues.Reference(literal?.Type) ?? type;
+ if (literalType != type) diagnostics.Add(WrongRecordType + ":" + name + ":expected-" + type + ":actual-" + literalType);
+ var body = literal?.Body ?? declaration.Body!;
+ var fields = Fields(body, schema, name);
+ foreach (var missing in schema.Fields.Keys.Where(f => !fields.ContainsKey(f))) diagnostics.Add(RecordMissingField + ":" + name + ":" + missing);
+ foreach (var extra in fields.Keys.Where(f => !schema.Fields.ContainsKey(f))) diagnostics.Add(RecordExtraField + ":" + name + ":" + extra);
+ Check(fields, schema, name, RecordFieldTypeMismatch, scalarOnly: true);
+ result[name] = new(name, type, fields.ToImmutableDictionary(StringComparer.Ordinal), declaration.Span);
+ }
+ pending.Remove(declaration); progressed = true;
}
- var rowCount = table.Columns.Count == 0 ? 0 : table.Columns.First().Value.Length;
- if (index < 0 || index >= rowCount) { if (int.TryParse(lookup, out _)) diagnostics.Add(TableIndexOutOfRange + ":" + table.Name + ":" + lookup); continue; }
- var requestedType = declaration.Groups["type"].Success ? declaration.Groups["type"].Value : table.RowType;
- if (!string.Equals(requestedType, table.RowType, StringComparison.Ordinal)) { diagnostics.Add(WrongRecordType + ":" + declaration.Groups["name"].Value + ":expected-" + requestedType + ":actual-" + table.RowType); continue; }
- var fields = table.Columns.ToImmutableDictionary(column => column.Key, column => column.Value[index], StringComparer.Ordinal);
- var keyDetail = table.KeyField is null ? string.Empty : " key:" + table.Columns[table.KeyField][index];
- result[declaration.Groups["name"].Value] = new(declaration.Groups["name"].Value, table.RowType, fields, new(declaration.Index, declaration.Length), "Table:" + table.Name + " row:" + index + keyDetail);
+ if (progressed) continue;
+ foreach (var declaration in pending)
+ diagnostics.Add(WithBaseNotRecord + ":" + declaration.Name!.Text + ":" + (declaration.Initializer is WithSyntax w ? FirmamentSyntaxValues.Reference(w.Target) : FirmamentSyntaxValues.Reference(declaration.Initializer)));
+ break;
}
foreach (var record in result.Values.ToArray())
{
- var origins = record.Fields.Values.Where(result.ContainsKey).Select(value => result[value].Provenance).Where(value => value != record.Provenance).Distinct(StringComparer.Ordinal).ToArray();
+ var origins = record.Fields.Values.Where(result.ContainsKey).Select(v => result[v].Provenance).Where(v => v != record.Provenance).Distinct(StringComparer.Ordinal).ToArray();
if (origins.Length > 0 && !record.Provenance.Contains("origin:", StringComparison.Ordinal)) result[record.Name] = record with { Provenance = record.Provenance + "; origin:" + string.Join("|", origins) };
}
foreach (var record in result.Values)
- foreach (var field in record.Fields.Where(field => recordTypes[record.TypeName].Fields.TryGetValue(field.Key, out var expected) && !TypeMatches(field.Value, expected, enums, recordTypes, result, scalars)))
- diagnostics.Add(Prefix + "record-field-type-mismatch:" + record.Name + "." + field.Key + ":expected-" + recordTypes[record.TypeName].Fields[field.Key] + ":actual-" + field.Value);
+ {
+ Check(record.Fields, recordTypes[record.TypeName], record.Name, RecordFieldTypeMismatch);
+ var before = diagnostics.Count;
+ _ = FlattenRecordFields(record, recordTypes, result, diagnostics);
+ foreach (var code in diagnostics.Skip(before).ToArray()) scalars?.RecordError(record.Name, "", code,
+ $"Record '{record.Name}' contains a cyclic reference or exceeds the supported nesting depth of 128. Use finite, acyclic Record data.");
+ }
return result;
- }
- private static IReadOnlyList<string> SplitValues(string text) => Regex.Matches(text, "\"[^\"]*\"|\\d+\\.\\d+\\.\\d+|\\d{4}-\\d{2}-\\d{2}|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?|[A-Za-z_]\\w*", RegexOptions.CultureInvariant).Cast<Match>().Select(match => match.Value).ToArray();
+ string Text(FirmamentV2SourceSpan span) => source.Substring(span.Start, span.Length);
+ Dictionary<string, string> Fields(BlockSyntax body, TemplateRecordTypeIr schema, string name)
+ {
+ var fields = ParseRecordFields(Text(body.ContentSpan), schema.Fields, diagnostics, scalars, name);
+ foreach (var field in fields.ToArray())
+ if (schema.Fields.TryGetValue(field.Key, out var type) && scalars is not null)
+ fields[field.Key] = scalars.Field(name, field.Key, field.Value, type, body.Span, diagnostics);
+ return fields;
+ }
+ void Check(IReadOnlyDictionary<string, string> fields, TemplateRecordTypeIr schema, string name, string code, bool scalarOnly = false)
+ {
+ foreach (var field in fields)
+ if (schema.Fields.TryGetValue(field.Key, out var type) && (!scalarOnly || !recordTypes.ContainsKey(type))
+ && !TypeMatches(field.Value, type, enums, recordTypes, result, scalars))
+ diagnostics.Add(code + ":" + name + "." + field.Key + ":expected-" + type + ":actual-" + field.Value);
+ }
+ }
private static Dictionary<string, string> ParseRecordFields(string body, IReadOnlyDictionary<string, string> schema, List<string> diagnostics,
FirmamentCompileTimeValues? scalars, string recordName)
@@ -758,6 +807,8 @@ internal static class FirmamentV2TemplateExpansion
var text = prefix + body + "\n}";
var syntax = FirmamentSyntaxParser.Parse(text);
var fields = syntax.Document.Statements.OfType<DeclarationSyntax>().SelectMany(d => d.Body?.Statements ?? []).OfType<FieldSyntax>().ToArray();
+ if (syntax.Document.Statements.OfType<DeclarationSyntax>().SelectMany(d => d.Body?.Statements ?? []).Any(s => s is not FieldSyntax))
+ diagnostics.Add(Prefix + "record-field-declaration:" + recordName);
foreach (var duplicate in fields.GroupBy(f => f.Name.Text, StringComparer.Ordinal).Where(g => g.Count() > 1))
{
var code = Prefix + "record-duplicate-field:" + duplicate.Key;
@@ -875,26 +926,32 @@ internal static class FirmamentV2TemplateExpansion
results = evidence;
return !HasErrors(diagnostics);
}
- private static void DetectTemplateCycles(IEnumerable<TemplateDeclarationIr> templates, IReadOnlyDictionary<string, TemplateDeclarationIr> byName, List<string> diagnostics)
+ private static void DetectTemplateCycles(IEnumerable<TemplateDeclarationIr> templates, List<string> diagnostics)
{
- foreach (var template in templates)
+ var complete = new HashSet<TemplateDeclarationIr>(ReferenceEqualityComparer.Instance);
+ var stack = new List<TemplateDeclarationIr>();
+ void Visit(TemplateDeclarationIr template)
{
- var stack = new List<string>(); var seen = new HashSet<string>(StringComparer.Ordinal);
- bool Visit(string name)
+ var at = stack.FindIndex(item => ReferenceEquals(item, template));
+ if (at >= 0)
{
- var at = stack.IndexOf(name); if (at >= 0) { diagnostics.Add(Recursive + ":" + string.Join(" -> ", stack.Skip(at).Append(name))); return true; }
- if (!seen.Add(name)) return false; stack.Add(name);
- foreach (Match call in Regex.Matches(byName[name].Body, @"=\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*<", RegexOptions.CultureInvariant)) if (byName.ContainsKey(call.Groups["name"].Value) && Visit(call.Groups["name"].Value)) return true;
- stack.RemoveAt(stack.Count - 1); return false;
+ diagnostics.Add(Recursive + ":" + string.Join(" -> ", stack.Skip(at).Append(template).Select(item => item.Name)));
+ return;
}
- _ = Visit(template.Name);
+ if (complete.Contains(template)) return;
+ if (stack.Count >= 64) { diagnostics.Add(Prefix + "depth-limit:" + template.Name); return; }
+ stack.Add(template);
+ foreach (var application in template.BodyApplications) Visit(application.BoundTemplate!);
+ stack.RemoveAt(stack.Count - 1);
+ complete.Add(template);
}
+ foreach (var template in templates) Visit(template);
}
private static string Identity(TemplateDeclarationIr template, TemplateApplicationIr application, BoundTemplateArguments args, FirmamentCompileTimeValues? scalars = null)
{
string Value(string value) => scalars?.NominalExpression(value) ?? value;
var recordInput = args.RecordArguments.OrderBy(x => x.Key).SelectMany(x => x.Value.Fields.OrderBy(f => f.Key).Select(f => x.Key + "." + f.Key + "=" + Value(f.Value)));
- var input = template.Name + "|" + application.InstanceName + "|" + string.Join("|", args.TypeArguments.Concat(args.ValueArguments).OrderBy(x => x.Key).Select(x => x.Key + "=" + Value(x.Value)).Concat(recordInput));
+ var input = (template.IdentityNamespace is null ? template.Name : template.IdentityNamespace + "/" + template.Name) + "|" + application.InstanceName + "|" + string.Join("|", args.TypeArguments.Concat(args.ValueArguments).OrderBy(x => x.Key).Select(x => x.Key + "=" + Value(x.Value)).Concat(recordInput));
return "template:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(input))).ToLowerInvariant()[..16];
}
private static string DisplaySignature(TemplateDeclarationIr template) => template.Name + "<" + string.Join(", ", template.Parameters.Select(parameter => parameter switch
@@ -929,23 +986,25 @@ internal static class FirmamentV2TemplateExpansion
private static string ExpandNestedApplications(
string body,
- IReadOnlyDictionary<string, TemplateDeclarationIr> templates,
+ TemplateDeclarationIr enclosingTemplate,
string moduleSource,
IReadOnlyDictionary<string, ImmutableHashSet<string>> enums,
IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes,
IReadOnlyDictionary<string, TemplateStaticRecordIr> staticRecords,
List<string> diagnostics,
ICollection<ConceptIrTemplateInstantiation> instantiations,
- IReadOnlyList<string> stack, FirmamentCompileTimeValues? scalars = null)
+ IReadOnlyList<TemplateDeclarationIr> stack, FirmamentCompileTimeValues? scalars = null)
{
- var applications = ParseApplications(body, templates, diagnostics);
- var changes = new List<(int Start, int Length, string Text)>();
+ if (stack.Count > 64) { diagnostics.Add(Prefix + "depth-limit:" + enclosingTemplate.Name); return body; }
+ var syntax = new FirmamentTemplateSyntax(body, diagnostics, enclosingTemplate.BodyScope);
+ var applications = syntax.Applications;
+ var changes = syntax.RemovableDeclarations.Select(d => (Start: d.SourceSpan.Start, Length: d.SourceSpan.Length, Text: string.Empty)).ToList();
foreach (var application in applications)
{
- var template = templates[application.TemplateName];
- if (stack.Contains(template.Name, StringComparer.Ordinal))
+ var template = application.BoundTemplate!;
+ if (stack.Any(item => ReferenceEquals(item, template)))
{
- diagnostics.Add(Recursive + ":" + string.Join(" -> ", stack.Append(template.Name)));
+ diagnostics.Add(Recursive + ":" + string.Join(" -> ", stack.Append(template).Select(item => item.Name)));
continue;
}
var bound = Bind(template, application, moduleSource, enums, recordTypes, staticRecords, diagnostics, scalars);
@@ -964,9 +1023,10 @@ internal static class FirmamentV2TemplateExpansion
instantiations.Add(new(template.Name, application.InstanceName, bound.TypeArguments, bound.ValueArguments,
bound.DefaultedArguments, specialization.SpecializationIdentity, specialization.GeneratedDeclarationPaths,
template.SourceSpan, application.SourceSpan, SelectedMatchArms: selectedMatches,
- RecordArguments: recordArguments, RequireResults: requireResults));
- specializedBody = ExpandNestedApplications(specializedBody, templates, moduleSource, enums, recordTypes,
- staticRecords, diagnostics, instantiations, stack.Append(template.Name).ToArray(), scalars);
+ RecordArguments: recordArguments, RequireResults: requireResults)
+ { DefinitionScope = template.DefinitionScope?.Identity, BindingScope = application.BindingScope });
+ specializedBody = ExpandNestedApplications(specializedBody, template, moduleSource, enums, recordTypes,
+ staticRecords, diagnostics, instantiations, stack.Append(template).ToArray(), scalars);
var liftedPmi = LiftPmi(specializedBody, out specializedBody);
// Nested finite specializations flatten into the containing declaration before
// Feature AIR. The instantiation record above preserves the semantic boundary;
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/LinearFeatureAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/LinearFeatureAuthoring.cs
index ec94fca7..58a65669 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/LinearFeatureAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/LinearFeatureAuthoring.cs
@@ -1,3 +1,4 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using System.Globalization;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Firmament.Materializer;
@@ -24,10 +25,10 @@ internal static class LinearFeatureAuthoring
var origin = Regex.Match(fields, @"\bOrigin\s*:\s*\[(?<x>[^,]+),(?<y>[^]]+)\]");
var vector = Regex.Match(fields, @"\bDirection\s*:\s*\[(?<x>[^,]+),(?<y>[^]]+)\]");
if (!origin.Success || !vector.Success
- || !FirmamentV2FeatureExpansion.TryEvaluateScalar(origin.Groups["x"].Value, out var x, out var xu) || xu != "mm"
- || !FirmamentV2FeatureExpansion.TryEvaluateScalar(origin.Groups["y"].Value, out var y, out var yu) || yu != "mm"
- || !FirmamentV2FeatureExpansion.TryEvaluateScalar(vector.Groups["x"].Value, out var vx, out var vxu) || vxu.Length != 0
- || !FirmamentV2FeatureExpansion.TryEvaluateScalar(vector.Groups["y"].Value, out var vy, out var vyu) || vyu.Length != 0
+ || !FirmamentNumericEvaluation.TryEvaluateScalar(origin.Groups["x"].Value, out var x, out var xu) || xu != "mm"
+ || !FirmamentNumericEvaluation.TryEvaluateScalar(origin.Groups["y"].Value, out var y, out var yu) || yu != "mm"
+ || !FirmamentNumericEvaluation.TryEvaluateScalar(vector.Groups["x"].Value, out var vx, out var vxu) || vxu.Length != 0
+ || !FirmamentNumericEvaluation.TryEvaluateScalar(vector.Groups["y"].Value, out var vy, out var vyu) || vyu.Length != 0
|| !double.IsFinite(vx * vx + vy * vy) || vx * vx + vy * vy < 1e-24)
{ Error("axis-invalid", identity); continue; }
var norm = Math.Sqrt(vx * vx + vy * vy);
@@ -50,7 +51,7 @@ internal static class LinearFeatureAuthoring
var seed = Field(body, "Source"); var direction = Field(body, "Direction");
if (!int.TryParse(Field(body, "Count"), out var count) || count is < 1 or > 1024)
{ Error("count-invalid", name); continue; }
- if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(Field(body, "Spacing"), out var spacing, out var unit) || unit != "mm" || spacing <= 0)
+ if (!FirmamentNumericEvaluation.TryEvaluateScalar(Field(body, "Spacing"), out var spacing, out var unit) || unit != "mm" || spacing <= 0)
{ Error("spacing-invalid", name); continue; }
if (direction.EndsWith(".Direction", StringComparison.Ordinal))
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentBindingScope.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentBindingScope.cs
new file mode 100644
index 00000000..eeb7ee95
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentBindingScope.cs
@@ -0,0 +1,12 @@
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+/// <summary>Finite lexical declaration ownership. Callable and construction names have
+/// distinct namespaces (a Feature and its Profile may legitimately share a name).</summary>
+internal sealed class FirmamentBindingScope(FirmamentBindingScope? parent, string identity)
+{
+ private readonly Dictionary<(string Kind, string Name), DeclarationSyntax> symbols = new();
+ internal string Identity => identity;
+ internal bool Declare(string kind, DeclarationSyntax declaration) => declaration.Name is { } name
+ && symbols.TryAdd((kind, name.Text), declaration);
+ internal DeclarationSyntax? Resolve(string kind, string name) => symbols.GetValueOrDefault((kind, name)) ?? parent?.Resolve(kind, name);
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs
new file mode 100644
index 00000000..391cb352
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs
@@ -0,0 +1,225 @@
+using System.Security.Cryptography;
+using System.Text;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+/// <summary>Lexical identities for compile-time data. Identifier spans are lowered
+/// only after AST lookup, at the existing source boundary to domain adapters.</summary>
+internal sealed class FirmamentDataBinding
+{
+ internal sealed record Symbol(string Name, string Identity, string Namespace, string Scope, DeclarationSyntax Declaration);
+ private sealed class Scope(Scope? parent, string identity)
+ {
+ internal string Identity => identity;
+ internal readonly Dictionary<(string Namespace, string Name), Symbol> Symbols = new();
+ internal readonly HashSet<string> Values = new(StringComparer.Ordinal);
+ internal readonly HashSet<string> Types = new(StringComparer.Ordinal);
+ internal Symbol? Resolve(string space, string name) => Symbols.GetValueOrDefault((space, name))
+ ?? (space == "value" && Values.Contains(name) || space == "type" && Types.Contains(name) ? null : parent?.Resolve(space, name));
+ internal bool HasValueShadow(string name) => Values.Contains(name) || parent?.HasValueShadow(name) == true;
+ internal bool HasTypeShadow(string name) => Types.Contains(name) || parent?.HasTypeShadow(name) == true;
+ }
+ private sealed record Edit(FirmamentV2SourceSpan Span, string Text);
+ private readonly List<Edit> edits = [];
+ private readonly Dictionary<string, Symbol> identities = new(StringComparer.Ordinal);
+ private readonly List<(FirmamentV2SourceSpan Span, Scope Scope)> scopeSpans = [];
+ internal string OriginalSource { get; }
+ internal string Source { get; }
+ internal IReadOnlyList<Symbol> Symbols { get; }
+ internal IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics { get; }
+ internal bool IsChanged => edits.Count != 0;
+
+ internal FirmamentDataBinding(string source)
+ {
+ OriginalSource = source;
+ Source = source;
+ var syntax = FirmamentSyntaxParser.Parse(source);
+ if (!syntax.IsSuccess) { Symbols = []; Diagnostics = []; return; } // syntax owner presents recovery failures
+ var errors = new List<FirmamentV2ValidationDiagnostic>();
+ var symbols = new List<Symbol>();
+ var scopes = new Dictionary<StatementSyntax, Scope>(ReferenceEqualityComparer.Instance);
+ var definitions = new Dictionary<DeclarationSyntax, Symbol>(ReferenceEqualityComparer.Instance);
+ var headers = new Dictionary<DeclarationSyntax, Scope>(ReferenceEqualityComparer.Instance);
+ var root = new Scope(null, "document");
+ scopeSpans.Add((new(0, source.Length), root));
+ var occupied = syntax.Document.Tokens.Where(t => t.Kind == SyntaxTokenKind.Identifier).Select(t => t.Text).ToHashSet(StringComparer.Ordinal);
+ Collect(syntax.Document.Statements, root);
+ // Preserve all established unique spellings, including root declarations.
+ foreach (var group in symbols.GroupBy(s => (s.Namespace, s.Name)))
+ {
+ var ordered = group.OrderBy(s => s.Scope == "document" ? 0 : 1).ThenBy(s => s.Declaration.Span.Start).ToArray();
+ for (var i = 0; i < ordered.Length; i++)
+ {
+ var symbol = ordered[i];
+ var identity = symbol.Name;
+ if (i > 0)
+ {
+ var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(symbol.Scope + "/" + symbol.Namespace + "/" + symbol.Name)))[..12];
+ identity = "__firmamentData_" + hash + "_" + symbol.Name;
+ while (!occupied.Add(identity)) identity += "_";
+ }
+ var bound = symbol with { Identity = identity };
+ scopes[symbol.Declaration].Symbols[(symbol.Namespace, symbol.Name)] = bound;
+ definitions[symbol.Declaration] = bound;
+ identities[identity] = bound;
+ }
+ }
+ Rewrite(syntax.Document.Statements);
+ Symbols = definitions.Values.OrderBy(s => s.Declaration.Span.Start).ToArray();
+ Diagnostics = errors;
+ edits.Sort((a, b) => a.Span.Start.CompareTo(b.Span.Start));
+ for (var i = edits.Count - 1; i >= 0; i--)
+ Source = Source.Remove(edits[i].Span.Start, edits[i].Span.Length).Insert(edits[i].Span.Start, edits[i].Text);
+
+ void Collect(IReadOnlyList<StatementSyntax> statements, Scope scope)
+ {
+ foreach (var statement in statements)
+ {
+ scopes[statement] = scope;
+ if (statement is not DeclarationSyntax { Name: { } name } d) continue;
+ var space = d.Type.Name.Text is "Record" or "Enum" ? "type"
+ : d.Type.Name.Text == "Static" || d.Type.Name.Text == "Table" && d.Modifiers.Any(m => m.Name.Text == "Static") ? "value" : null;
+ if (space is null) { scope.Values.Add(name.Text); continue; }
+ var table = d.Type.Name.Text == "Table";
+ if (d.HasParameterList || d.Type.Span.Length != d.Type.Name.Span.Length || d.Occurrence
+ || d.ResultType is not null || d.Clauses.Any(c => !table || c.Kind != ClauseKind.Key)
+ || d.Clauses.Count(c => c.Kind == ClauseKind.Key) > 1
+ || d.Modifiers.Any(m => !table || m.Name.Text != "Static"))
+ {
+ Error("firmament-binding-invalid-data-header:" + name.Text, $"{d.Type.Name.Text} '{name.Text}' cannot carry ignored parameters, placement, generic or result clauses.", d.Span, name.Text);
+ continue;
+ }
+ var symbol = new Symbol(name.Text, name.Text, space, scope.Identity, d);
+ if (!scope.Symbols.TryAdd((space, name.Text), symbol))
+ Error("firmament-binding-duplicate-name:" + name.Text, $"Compile-time {space} '{name.Text}' is declared more than once in scope '{scope.Identity}'.", d.Span, name.Text);
+ else { symbols.Add(symbol); definitions[d] = symbol; }
+ }
+ var ordinals = new Dictionary<string, int>(StringComparer.Ordinal);
+ foreach (var statement in statements)
+ {
+ if (statement is MappingSyntax m)
+ {
+ var child = new Scope(scope, scope.Identity + "/mapping " + m.Key.Text); child.Values.Add(m.Key.Text);
+ Collect([m.Value], child); continue;
+ }
+ if (statement is not DeclarationSyntax d || d.Body is null) continue;
+ var label = d.Type.Name.Text + " " + d.Name?.Text;
+ var ordinal = ordinals.GetValueOrDefault(label); ordinals[label] = ordinal + 1;
+ var header = new Scope(scope, scope.Identity + "/parameters " + label + "#" + ordinal);
+ 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)
+ {
+ if (p.Value is TypeParameterSyntax) header.Types.Add(p.Name.Text);
+ else header.Values.Add(p.Name.Text);
+ }
+ headers[d] = header;
+ var body = new Scope(header, scope.Identity + "/" + label + "#" + ordinal);
+ scopeSpans.Add((d.Body.ContentSpan, body));
+ Collect(d.Body.Statements, body);
+ }
+ }
+ void Rewrite(IEnumerable<StatementSyntax> statements)
+ {
+ foreach (var statement in statements)
+ {
+ var scope = scopes[statement];
+ if (statement is MappingSyntax m) { Rewrite([m.Value]); continue; }
+ if (statement is FieldSyntax f) { Expression(f.Value, scope, false); continue; }
+ if (statement is ExpressionStatementSyntax e) { Expression(e.Value, scope, false); continue; }
+ if (statement is ReturnSyntax r) { Expression(r.Value, scope, false); continue; }
+ if (statement is not DeclarationSyntax d) continue;
+ if (definitions.TryGetValue(d, out var symbol)) Rename(d.Name!, symbol.Identity);
+ var parameters = d.Parameters.Concat(d.Modifiers.Where(m => m.Name.Text == "Template").SelectMany(m => m.Arguments)).ToArray();
+ foreach (var p in parameters)
+ {
+ Expression(p.Value, headers.GetValueOrDefault(d) ?? scope, true);
+ if (p.Default is not null) Expression(p.Default, headers.GetValueOrDefault(d) ?? scope, false);
+ }
+ if (d.Annotation is not null) Expression(d.Annotation, scope, true);
+ if (d.ResultType is not null) Expression(d.ResultType, headers.GetValueOrDefault(d) ?? scope, true);
+ if (d.Initializer is not null) Expression(d.Initializer, scope, false);
+ foreach (var clause in d.Clauses.Where(c => c.Kind != ClauseKind.Key)) Expression(clause.Value, scope, false);
+ if (d.Body is not null)
+ {
+ if (d.Type.Name.Text == "Record")
+ foreach (var field in d.Body.Statements.OfType<FieldSyntax>()) Expression(field.Value, scope, true);
+ else Rewrite(d.Body.Statements);
+ }
+ }
+ }
+ void Expression(ExpressionSyntax expression, Scope scope, bool type)
+ {
+ switch (expression)
+ {
+ case ReferenceSyntax r:
+ var space = type ? "type" : "value";
+ var symbol = scope.Resolve(space, r.Name.Text);
+ if (symbol is not null) Rename(r.Name, symbol.Identity);
+ else if (!(space == "value" ? scope.HasValueShadow(r.Name.Text) : scope.HasTypeShadow(r.Name.Text)) && symbols.Any(s => s.Namespace == space && s.Name == r.Name.Text))
+ Error("firmament-binding-name-not-visible:" + r.Name.Text, $"Compile-time {space} '{r.Name.Text}' is not visible from scope '{scope.Identity}'.", r.Span, r.Name.Text);
+ return;
+ case ObjectSyntax o:
+ if (o.Type is not null) Expression(o.Type, scope, true);
+ foreach (var f in o.Body.Statements.OfType<FieldSyntax>()) Expression(f.Value, scope, false);
+ return;
+ case SpecializationSyntax s:
+ foreach (var a in s.Arguments) Expression(a.Value, scope, type);
+ return;
+ case CallSyntax c:
+ foreach (var a in c.Arguments) Expression(a.Value, scope, false);
+ if (c.Target is not ReferenceSyntax) Expression(c.Target, scope, false);
+ return;
+ case MemberSyntax m: Expression(m.Target, scope, type); return;
+ case WithSyntax w:
+ Expression(w.Target, scope, false);
+ foreach (var f in w.Body.Statements.OfType<FieldSyntax>()) Expression(f.Value, scope, false);
+ return;
+ case SequenceSyntax s: foreach (var a in s.Items) Expression(a.Value, scope, type); return;
+ case TypeParameterSyntax: return;
+ case UnarySyntax u: Expression(u.Operand, scope, type); return;
+ case BinarySyntax b: Expression(b.Left, scope, type); Expression(b.Right, scope, type); return;
+ case QuantitySyntax q: Expression(q.Value, scope, false); return;
+ case IndexSyntax i: Expression(i.Target, scope, type); if (i.Index is not null) Expression(i.Index, scope, false); return;
+ case 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 AliasSyntax a: Expression(a.Value, scope, type); return;
+ case ProvenanceSyntax p: Expression(p.Value, scope, type); return;
+ case FrameSyntax f:
+ Expression(f.Origin, scope, false); foreach (var a in f.Axes) Expression(a.Value, scope, false); return;
+ case MemberSetSyntax m:
+ Expression(m.Target, scope, false); foreach (var a in m.Members) Expression(a.Value, scope, false); return;
+ case TraceSyntax t:
+ Expression(t.Source, scope, false); if (t.From is not null) Expression(t.From, scope, false); if (t.To is not null) Expression(t.To, scope, false); return;
+ }
+ }
+ void Rename(IdentifierSyntax name, string text)
+ {
+ if (name.Text != text && !edits.Any(e => e.Span == name.Span)) edits.Add(new(name.Span, text));
+ }
+ void Error(string code, string message, FirmamentV2SourceSpan span, string name) => errors.Add(new(code, "fatal", message, Target: name)
+ { SourceSpan = span, IsOriginalSource = true, Stage = "Data binding" });
+ }
+
+ internal string DisplayName(string identity) => identities.TryGetValue(identity, out var symbol) ? symbol.Name : identity;
+ internal string ResolveIdentity(string space, string name, int position) => scopeSpans
+ .Where(s => position >= s.Span.Start && position < s.Span.Start + s.Span.Length).OrderBy(s => s.Span.Length)
+ .FirstOrDefault().Scope?.Resolve(space, name)?.Identity ?? name;
+ internal FirmamentV2SourceSpan OriginalSpan(FirmamentV2SourceSpan span)
+ {
+ int Position(int position)
+ {
+ var delta = 0;
+ foreach (var edit in edits)
+ {
+ var start = edit.Span.Start + delta;
+ if (position < start) break;
+ if (position <= start + edit.Text.Length) return edit.Span.Start + Math.Min(position - start, edit.Span.Length);
+ delta += edit.Text.Length - edit.Span.Length;
+ }
+ return position - delta;
+ }
+ var start = Position(span.Start); return new(start, Math.Max(0, Position(span.Start + span.Length) - start));
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericEvaluation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericEvaluation.cs
new file mode 100644
index 00000000..7cbac94d
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericEvaluation.cs
@@ -0,0 +1,117 @@
+using System.Globalization;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+/// <summary>Finite numeric evaluation over the shared expression grammar. Domain callers
+/// supply their expected unit and, where admitted, bounded intrinsic functions.</summary>
+internal static class FirmamentNumericEvaluation
+{
+ internal readonly record struct Value(double Number, string Unit);
+
+ internal static bool TryEvaluate(string source, out Value value,
+ IReadOnlyDictionary<string, Value>? variables = null,
+ Func<string, IReadOnlyList<Value>, Value>? functions = null, bool typeOnly = false)
+ {
+ value = default;
+ if (source.Length > 8192) return false;
+ var parsed = FirmamentSyntaxParser.ParseExpression(source);
+ return parsed.Expression is not null && parsed.Diagnostics.Count == 0
+ && TryEvaluate(parsed.Expression, out value, variables, functions, typeOnly);
+ }
+
+ internal static bool TryEvaluate(ExpressionSyntax? expression, out Value value,
+ IReadOnlyDictionary<string, Value>? variables = null,
+ Func<string, IReadOnlyList<Value>, Value>? functions = null, bool typeOnly = false)
+ {
+ var remaining = 8192;
+ bool Evaluate(ExpressionSyntax? node, int depth, out Value result)
+ {
+ result = default;
+ if (depth > 128 || --remaining < 0) return false;
+ switch (node)
+ {
+ case LiteralSyntax { Kind: LiteralKind.Number } n:
+ if (!double.TryParse(n.Raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var number)
+ || !double.IsFinite(number)) return false;
+ result = new(number, ""); return true;
+ case ReferenceSyntax r:
+ return variables is not null && variables.TryGetValue(r.Name.Text, out result);
+ case MemberSyntax m when FirmamentSyntaxValues.Reference(m) is { } name:
+ return variables is not null && variables.TryGetValue(name, out result);
+ case QuantitySyntax q when q.Unit.Text is "mm" or "deg" or "rad":
+ if (!Evaluate(q.Value, depth + 1, out var quantity) || quantity.Unit.Length != 0) return false;
+ result = quantity with { Unit = q.Unit.Text }; return true;
+ case UnarySyntax { Operator: UnaryOperator.Positive or UnaryOperator.Negative } u:
+ if (!Evaluate(u.Operand, depth + 1, out result)) return false;
+ if (u.Operator == UnaryOperator.Negative) result = result with { Number = -result.Number };
+ return true;
+ case SequenceSyntax { Kind: SequenceKind.Tuple, Items.Count: 1 } group when group.Items[0].Name is null && group.Items[0].Default is null:
+ return Evaluate(group.Items[0].Value, depth + 1, out result);
+ case BinarySyntax b:
+ return Evaluate(b.Left, depth + 1, out var left) && Evaluate(b.Right, depth + 1, out var right)
+ && TryBinary(left, b.Operator, right, out result, typeOnly);
+ case CallSyntax { Target: ReferenceSyntax target } call:
+ var args = new List<Value>();
+ foreach (var argument in call.Arguments)
+ {
+ if (argument.Name is not null || argument.Default is not null
+ || !Evaluate(argument.Value, depth + 1, out var arg)) return false;
+ args.Add(arg);
+ }
+ if (target.Name.Text == "Pow" && args.Count == 2 && args.All(a => a.Unit.Length == 0))
+ result = new(typeOnly ? 1 : Math.Pow(args[0].Number, args[1].Number), "");
+ else if (functions is not null) result = functions(target.Name.Text, args);
+ else return false;
+ return (result.Unit is "" or "mm" or "deg" or "rad") && (typeOnly || double.IsFinite(result.Number));
+ default: return false;
+ }
+ }
+ try { return Evaluate(expression, 0, out value); }
+ catch (FormatException) { value = default; return false; }
+ }
+
+ internal static bool TryBinary(Value left, BinaryOperator op, Value right, out Value result, bool typeOnly = false)
+ {
+ result = default;
+ static FirmamentV2PrimitiveType? Type(string unit) => unit switch
+ { "" => FirmamentV2PrimitiveType.Float, "mm" => FirmamentV2PrimitiveType.Length, "deg" or "rad" => FirmamentV2PrimitiveType.Angle, _ => null };
+ var symbol = op switch { BinaryOperator.Add => "+", BinaryOperator.Subtract => "-", BinaryOperator.Multiply => "*", BinaryOperator.Divide => "/", _ => "" };
+ if (Type(left.Unit) is not { } lt || Type(right.Unit) is not { } rt || ResultType(lt, symbol, rt) is not { } type
+ || left.Unit.Length > 0 && right.Unit.Length > 0 && left.Unit != right.Unit
+ || op == BinaryOperator.Divide && !typeOnly && right.Number == 0) return false;
+ var number = typeOnly ? 1 : op switch
+ { BinaryOperator.Add => left.Number + right.Number, BinaryOperator.Subtract => left.Number - right.Number,
+ BinaryOperator.Multiply => left.Number * right.Number, _ => left.Number / right.Number };
+ result = new(number, type is FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle
+ ? left.Unit.Length > 0 ? left.Unit : right.Unit : "");
+ return typeOnly || double.IsFinite(result.Number);
+ }
+
+ internal static FirmamentV2PrimitiveType? ResultType(FirmamentV2PrimitiveType a, string op, FirmamentV2PrimitiveType b) => op switch
+ {
+ "+" or "-" when a == b && a is FirmamentV2PrimitiveType.Int or FirmamentV2PrimitiveType.Float or FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle => a,
+ "+" or "-" when IsNumeric(a) && IsNumeric(b) => FirmamentV2PrimitiveType.Float,
+ "*" when IsNumeric(a) && IsNumeric(b) => a == FirmamentV2PrimitiveType.Int && b == FirmamentV2PrimitiveType.Int ? FirmamentV2PrimitiveType.Int : FirmamentV2PrimitiveType.Float,
+ "*" when IsDim(a) && IsNumeric(b) => a,
+ "*" when IsNumeric(a) && IsDim(b) => b,
+ "/" when IsNumeric(a) && IsNumeric(b) => FirmamentV2PrimitiveType.Float,
+ "/" when IsDim(a) && IsNumeric(b) => a,
+ "/" when IsDim(a) && a == b => FirmamentV2PrimitiveType.Float,
+ _ => null
+ };
+ private static bool IsNumeric(FirmamentV2PrimitiveType t) => t is FirmamentV2PrimitiveType.Int or FirmamentV2PrimitiveType.Float;
+ private static bool IsDim(FirmamentV2PrimitiveType t) => t is FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle;
+
+ internal static bool TryEvaluateScalar(string expression, out double value, out string unit)
+ {
+ var success = FirmamentNumericEvaluation.TryEvaluate(expression, out var result); value = result.Number; unit = result.Unit ?? ""; return success;
+ }
+ internal static bool TryEvaluateScalar(string expression, IReadOnlyDictionary<string, (double Value, string Unit)> variables,
+ Func<string, IReadOnlyList<(double Value, string Unit)>, (double Value, string Unit)> functions, bool typeOnly, out double value, out string unit)
+ {
+ var success = FirmamentNumericEvaluation.TryEvaluate(expression, out var result,
+ variables.ToDictionary(p => p.Key, p => new FirmamentNumericEvaluation.Value(p.Value.Value, p.Value.Unit), StringComparer.Ordinal),
+ (name, args) => { var result = functions(name, args.Select(a => (a.Number, a.Unit)).ToArray()); return new(result.Value, result.Unit); }, typeOnly);
+ value = result.Number; unit = result.Unit ?? ""; return success;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs
index 2c91ee95..1c8689f9 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs
@@ -28,7 +28,13 @@ public enum BinaryOperator { Pipeline, Direction, Or, And, Equal, NotEqual, Less
[JsonDerivedType(typeof(ReplacementSyntax), "replacement")]
public abstract record StatementSyntax(FirmamentV2SourceSpan Span);
public sealed record IdentifierSyntax(string Text, FirmamentV2SourceSpan Span);
-public sealed record ArgumentSyntax(IdentifierSyntax? Name, ExpressionSyntax Value, ExpressionSyntax? Default, FirmamentV2SourceSpan Span);
+public sealed record ArgumentSyntax(IdentifierSyntax? Name, ExpressionSyntax Value, ExpressionSyntax? Default, FirmamentV2SourceSpan Span)
+{
+ // Retain the authored value boundary when a binder replaces Value. Transport
+ // serializers can preserve identity-bearing application spelling without
+ // interpreting the source or guessing the extent of an expression.
+ [JsonIgnore] public FirmamentV2SourceSpan AuthoredValueSpan { get; init; } = Value.Span;
+}
public sealed record TypeSyntax(IdentifierSyntax Name, IReadOnlyList<ArgumentSyntax> Arguments, FirmamentV2SourceSpan Span);
public sealed record ClauseSyntax(ClauseKind Kind, ExpressionSyntax Value, FirmamentV2SourceSpan Span);
public sealed record BlockSyntax(IReadOnlyList<StatementSyntax> Statements, FirmamentV2SourceSpan Span)
@@ -44,6 +50,7 @@ public sealed record DeclarationSyntax(TypeSyntax Type, IdentifierSyntax? Name,
{
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public ExpressionSyntax? Target { get; init; }
+ [JsonIgnore] public bool HasParameterList { get; init; }
}
public sealed record FieldSyntax(IdentifierSyntax Name, ExpressionSyntax Value, FirmamentV2SourceSpan Span) : StatementSyntax(Span);
public sealed record DirectiveSyntax(DirectiveKind Kind, ExpressionSyntax Value, FirmamentV2SourceSpan Span) : StatementSyntax(Span);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxOrigins.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxOrigins.cs
new file mode 100644
index 00000000..971dbfaa
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxOrigins.cs
@@ -0,0 +1,47 @@
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+/// <summary>Matches retained syntax by lexical declaration/mapping ownership, never by
+/// concatenated offsets. Generated nodes with no authored counterpart remain unmapped.</summary>
+internal sealed class FirmamentSyntaxOrigins(DocumentSyntax original, DocumentSyntax input)
+{
+ private readonly IReadOnlyDictionary<string, FirmamentV2SourceSpan> authored = Index(original);
+ private readonly IReadOnlyDictionary<string, FirmamentV2SourceSpan> incoming = Index(input);
+ private Dictionary<FirmamentV2SourceSpan, FirmamentV2SourceSpan>? locations;
+ internal FirmamentV2SourceSpan? Find(FirmamentV2SourceSpan span)
+ {
+ locations ??= incoming.Where(p => authored.ContainsKey(p.Key)).GroupBy(p => p.Value)
+ .Where(g => g.Select(p => authored[p.Key]).Distinct().Count() == 1)
+ .ToDictionary(g => g.Key, g => authored[g.First().Key]);
+ return locations.GetValueOrDefault(span);
+ }
+ private static IReadOnlyDictionary<string, FirmamentV2SourceSpan> Index(DocumentSyntax syntax)
+ {
+ var result = new Dictionary<string, FirmamentV2SourceSpan>(StringComparer.Ordinal);
+ void Scope(IReadOnlyList<StatementSyntax> statements, string path)
+ {
+ var counts = new Dictionary<string, int>(StringComparer.Ordinal);
+ foreach (var statement in statements)
+ {
+ var label = statement switch
+ {
+ DeclarationSyntax declaration => declaration.Type.Name.Text + " " + declaration.Name?.Text,
+ MappingSyntax mapping => "mapping " + mapping.Key.Text,
+ FieldSyntax f => "field " + f.Name.Text,
+ ExpressionStatementSyntax { Value: CallSyntax { Target: ReferenceSyntax r } } => "call " + r.Name.Text,
+ _ => statement.GetType().Name
+ };
+ var ordinal = counts.GetValueOrDefault(label); counts[label] = ordinal + 1;
+ var identity = path + "/" + label + "#" + ordinal;
+ result[identity] = statement.Span;
+ if (statement is DeclarationSyntax d)
+ {
+ if (d.Body is not null) Scope(d.Body.Statements, identity);
+ if (d.Initializer is CallSyntax call) result[identity + "/invocation"] = call.Span;
+ }
+ if (statement is ExpressionStatementSyntax { Value: CallSyntax c }) result[identity + "/invocation"] = c.Span;
+ if (statement is MappingSyntax m) Scope([m.Value], identity);
+ }
+ }
+ Scope(syntax.Statements, "document"); return result;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
index ad9f7f57..612fbb28 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
@@ -168,9 +168,9 @@ public static class FirmamentSyntaxParser
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 == "<"))
|| type.Name.Text == "Static" && Is("Table")
- || type.Name.Text is "Assert" or "Analysis" or "Extend" or "Comptime" or "proposes" or "manufacturing" && Current.Kind == SyntaxTokenKind.Identifier)
+ || type.Name.Text is "Assert" or "Analysis" or "analysis" or "Construct" or "Extend" or "Comptime" or "proposes" or "manufacturing" && Current.Kind == SyntaxTokenKind.Identifier)
{
- modifiers.Add(type); type = Type();
+ modifiers.Add(type); type = Type(qualified: type.Name.Text == "Construct");
}
IdentifierSyntax? name = null;
// Lowercase from was already a legal authored name. It becomes a link
@@ -199,7 +199,8 @@ public static class FirmamentSyntaxParser
IdentifierSyntax? headerUnit = null;
if (type.Name.Text is "Model" or "Struct" && name is not null && Current.Kind == SyntaxTokenKind.Identifier
&& !LineBreak && !IsClause(Current.Text)) headerUnit = Identifier();
- var parameters = Take("(") ? Arguments(")", declarationParameters: true) : [];
+ var hasParameterList = Take("(");
+ var parameters = hasParameterList ? Arguments(")", declarationParameters: true) : [];
if (type.Name.Text == "Replace" && Take("."))
{
var member = Identifier();
@@ -263,12 +264,18 @@ public static class FirmamentSyntaxParser
var field = new FieldSyntax(new("Units", headerUnit.Span), unit, headerUnit.Span);
body = body is null ? new([field], headerUnit.Span) : body with { Statements = new StatementSyntax[] { field }.Concat(body.Statements).ToArray() };
}
- return new(type, name, modifiers.ToArray(), parameters, annotation, result, clauses.ToArray(), initializer, body, occurrence, Span(start)) { Target = target };
+ return new(type, name, modifiers.ToArray(), parameters, annotation, result, clauses.ToArray(), initializer, body, occurrence, Span(start)) { Target = target, HasParameterList = hasParameterList };
}
- private TypeSyntax Type()
+ private TypeSyntax Type(bool qualified = false)
{
var name = Identifier();
+ if (qualified)
+ while (Take("."))
+ {
+ var segment = Identifier();
+ name = new(name.Text + "." + segment.Text, new(name.Span.Start, segment.Span.Start + segment.Span.Length - name.Span.Start));
+ }
var args = Take("<") ? Arguments(">") : [];
return new(name, args, Span(name.Span.Start));
}
@@ -474,9 +481,9 @@ public static class FirmamentSyntaxParser
{ left = new ObjectSyntax(left, Block(), Span(start)); continue; }
if (allowObject && Take("with")) { left = new WithSyntax(left, Block(), Span(start)); continue; }
if (Current.Kind == SyntaxTokenKind.Identifier && !LineBreak &&
- (Current.Text is "mm" or "cm" or "m" or "deg" or "rad"
+ (Current.Text is "mm" or "cm" or "m" or "deg" or "rad" or "N" or "kN" or "MN" or "Pa" or "kPa" or "MPa" or "GPa"
|| left is LiteralSyntax { Kind: LiteralKind.Number } && Current.Span.Start == left.Span.Start + left.Span.Length)
- && left is LiteralSyntax or SequenceSyntax)
+ && left is LiteralSyntax or SequenceSyntax or ReferenceSyntax)
{ left = new QuantitySyntax(left, Identifier(), Span(start)); continue; }
if (!Operator(out var binary, out var precedence, out var width) || precedence < minimum || stopGreater && Is(">")) break;
at += width;
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxRewriter.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxRewriter.cs
new file mode 100644
index 00000000..38ff63b2
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxRewriter.cs
@@ -0,0 +1,97 @@
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+/// <summary>Immutable syntax transformation. Identifier declarations, field labels and
+/// member labels are distinct from references; none are inferred from source substrings.</summary>
+internal class FirmamentSyntaxRewriter
+{
+ internal virtual BlockSyntax Block(BlockSyntax block) => block with { Statements = block.Statements.Select(Statement).ToArray() };
+ internal virtual ArgumentSyntax Argument(ArgumentSyntax a) => a with { Value = Expression(a.Value), Default = a.Default is null ? null : Expression(a.Default) };
+ internal virtual TypeSyntax Type(TypeSyntax t) => t with { Arguments = t.Arguments.Select(Argument).ToArray() };
+ internal virtual StatementSyntax Statement(StatementSyntax s) => s switch
+ {
+ DeclarationSyntax d => d with { Type = Type(d.Type), Modifiers = d.Modifiers.Select(Type).ToArray(),
+ Parameters = d.Parameters.Select(Argument).ToArray(), Annotation = Optional(d.Annotation), ResultType = Optional(d.ResultType),
+ Target = Optional(d.Target), Clauses = d.Clauses.Select(c => c with { Value = Expression(c.Value) }).ToArray(),
+ Initializer = Optional(d.Initializer), Body = d.Body is null ? null : Block(d.Body) },
+ FieldSyntax f => f with { Value = Expression(f.Value) },
+ DirectiveSyntax d => d with { Value = Expression(d.Value) },
+ ExpressionStatementSyntax e => e with { Value = Expression(e.Value) },
+ ReturnSyntax r => r with { Value = Expression(r.Value) },
+ MappingSyntax m => m with { Value = Statement(m.Value) },
+ InterfaceRelationSyntax r => r with { First = Expression(r.First), Second = Expression(r.Second), Option = Optional(r.Option) },
+ InterfaceFitSyntax f => f with { Shaft = Expression(f.Shaft), Bore = Expression(f.Bore) },
+ InterfacePolicySyntax p => p with { Values = p.Values.Select(Argument).ToArray() },
+ ReplacementSyntax r => r with { Target = Expression(r.Target), Replacement = (DeclarationSyntax)Statement(r.Replacement) },
+ RoleRequirementSyntax or InterfaceMotionSyntax => s,
+ _ => throw new InvalidOperationException($"Unowned syntax transformation: {s.GetType().Name}.")
+ };
+ protected ExpressionSyntax? Optional(ExpressionSyntax? e) => e is null ? null : Expression(e);
+ internal virtual ExpressionSyntax Expression(ExpressionSyntax e) => e switch
+ {
+ UnarySyntax u => u with { Operand = Expression(u.Operand) },
+ BinarySyntax b => b with { Left = Expression(b.Left), Right = Expression(b.Right) },
+ QuantitySyntax q => q with { Value = Expression(q.Value) },
+ ToleranceSyntax t => t with { Nominal = Expression(t.Nominal), Plus = Expression(t.Plus), Minus = Optional(t.Minus) },
+ SequenceSyntax s => s with { Items = s.Items.Select(Argument).ToArray() },
+ MemberSyntax m => m with { Target = Expression(m.Target) },
+ IndexSyntax i => i with { Target = Expression(i.Target), Index = Optional(i.Index) },
+ CallSyntax c => c with { Target = Expression(c.Target), Arguments = c.Arguments.Select(Argument).ToArray() },
+ SpecializationSyntax s => s with { Target = Expression(s.Target), Arguments = s.Arguments.Select(Argument).ToArray() },
+ ObjectSyntax o => o with { Type = Optional(o.Type), Body = Block(o.Body) },
+ WithSyntax w => w with { Target = Expression(w.Target), Body = Block(w.Body) },
+ FrameSyntax f => f with { Origin = Expression(f.Origin), Axes = f.Axes.Select(Argument).ToArray() },
+ AliasSyntax a => a with { Value = Expression(a.Value) },
+ TraceSyntax t => t with { Source = Expression(t.Source), From = Optional(t.From), To = Optional(t.To) },
+ MemberSetSyntax m => m with { Target = Expression(m.Target), Members = m.Members.Select(Argument).ToArray() },
+ TypedValueSyntax t => t with { Type = Expression(t.Type), Value = Expression(t.Value) },
+ ProvenanceSyntax p => p with { Value = Expression(p.Value) },
+ TypeParameterSyntax p => p with { Constraint = Optional(p.Constraint) },
+ MatchSyntax m => m with { Scrutinee = Expression(m.Scrutinee), Arms = m.Arms.Select(a => a with { Pattern = Expression(a.Pattern), Value = Expression(a.Value) }).ToArray() },
+ ReferenceSyntax or LiteralSyntax => e,
+ _ => throw new InvalidOperationException($"Unowned expression transformation: {e.GetType().Name}.")
+ };
+}
+
+/// <summary>Substitutes already-bound AST values. Nested parameters and mapping binders
+/// shadow their enclosing environment. Declaration renaming is explicit and separate.</summary>
+internal sealed class FirmamentSyntaxSubstitution(IReadOnlyDictionary<string, ExpressionSyntax> values,
+ IReadOnlyDictionary<string, string>? renames = null) : FirmamentSyntaxRewriter
+{
+ private readonly Stack<HashSet<string>> shadows = new();
+ private bool Shadowed(string name) => shadows.Any(s => s.Contains(name.Split('.')[0]));
+ internal override StatementSyntax Statement(StatementSyntax statement)
+ {
+ var names = statement switch
+ {
+ DeclarationSyntax d => d.Parameters.Select(p => p.Name?.Text).OfType<string>()
+ .Concat(d.Modifiers.Where(m => m.Name.Text == "Template").SelectMany(m => m.Arguments).Select(p => p.Name?.Text).OfType<string>())
+ .Concat(d.Type.Name.Text == "Feature" ? d.Body?.Statements.OfType<DeclarationSyntax>().Where(l => l.Type.Name.Text == "let").Select(l => l.Name?.Text).OfType<string>() ?? [] : []),
+ MappingSyntax m => [m.Key.Text],
+ _ => []
+ };
+ shadows.Push(names.ToHashSet(StringComparer.Ordinal));
+ var rewritten = base.Statement(statement);
+ shadows.Pop();
+ if (rewritten is DeclarationSyntax { Name: { } name } declaration && renames?.TryGetValue(name.Text, out var replacement) == true)
+ return declaration with { Name = name with { Text = replacement } };
+ return rewritten;
+ }
+ internal override ExpressionSyntax Expression(ExpressionSyntax expression)
+ {
+ // A constructor's type is not a value reference, even when a parameter
+ // happens to have the same spelling (Profile: Profile, for example).
+ if (expression is ObjectSyntax obj) return obj with { Body = Block(obj.Body) };
+ if (expression is TypedValueSyntax typed) return typed with { Value = Expression(typed.Value) };
+ if (expression is SpecializationSyntax specialization) return specialization with { Arguments = specialization.Arguments.Select(Argument).ToArray() };
+ if (expression is CallSyntax { Target: ReferenceSyntax } call) return call with { Arguments = call.Arguments.Select(Argument).ToArray() };
+ if (FirmamentSyntaxValues.Reference(expression) is { } name && expression is ReferenceSyntax or MemberSyntax && !Shadowed(name))
+ {
+ if (values.TryGetValue(name, out var value)) return value;
+ if (renames?.TryGetValue(name, out var replacement) == true) return new ReferenceSyntax(new(replacement, expression.Span), expression.Span);
+ }
+ return base.Expression(expression);
+ }
+ // This is value substitution. Declaration type/variant names occupy the type
+ // namespace; product Template type specialization has its separate owner.
+ internal override TypeSyntax Type(TypeSyntax type) => type;
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxTraversal.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxTraversal.cs
index 724966b5..e41fae3d 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxTraversal.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxTraversal.cs
@@ -18,13 +18,21 @@ public static class FirmamentSyntaxTraversal
InterfaceFitSyntax f => Expressions(f.Shaft).Concat(Expressions(f.Bore)),
InterfacePolicySyntax p => p.Values.SelectMany(v => Expressions(v.Value)),
ReplacementSyntax r => Expressions(r.Target),
- DeclarationSyntax d => (d.Annotation is null ? [] : Expressions(d.Annotation))
+ DirectiveSyntax d => Expressions(d.Value),
+ DeclarationSyntax d => Arguments(d.Type.Arguments)
+ .Concat(d.Modifiers.SelectMany(m => Arguments(m.Arguments)))
+ .Concat(Arguments(d.Parameters))
+ .Concat(d.ResultType is null ? [] : Expressions(d.ResultType))
+ .Concat(d.Annotation is null ? [] : Expressions(d.Annotation))
.Concat(d.Initializer is null ? [] : Expressions(d.Initializer))
.Concat(d.Target is null ? [] : Expressions(d.Target))
.Concat(d.Clauses.SelectMany(c => Expressions(c.Value))),
_ => []
});
+ private static IEnumerable<ExpressionSyntax> Arguments(IEnumerable<ArgumentSyntax> arguments) =>
+ arguments.SelectMany(a => Expressions(a.Value).Concat(a.Default is null ? [] : Expressions(a.Default)));
+
public static IEnumerable<ExpressionSyntax> Expressions(ExpressionSyntax expression)
{
yield return expression;
@@ -35,9 +43,9 @@ public static class FirmamentSyntaxTraversal
UnarySyntax u => [u.Operand],
QuantitySyntax q => [q.Value],
ToleranceSyntax t => new[] { t.Nominal, t.Plus, t.Minus }.OfType<ExpressionSyntax>(),
- SequenceSyntax s => s.Items.Select(a => a.Value),
- CallSyntax c => new[] { c.Target }.Concat(c.Arguments.Select(a => a.Value)),
- SpecializationSyntax s => new[] { s.Target }.Concat(s.Arguments.Select(a => a.Value)),
+ SequenceSyntax s => s.Items.SelectMany(a => new[] { a.Value, a.Default }.OfType<ExpressionSyntax>()),
+ CallSyntax c => new[] { c.Target }.Concat(c.Arguments.SelectMany(a => new[] { a.Value, a.Default }.OfType<ExpressionSyntax>())),
+ SpecializationSyntax s => new[] { s.Target }.Concat(s.Arguments.SelectMany(a => new[] { a.Value, a.Default }.OfType<ExpressionSyntax>())),
MemberSyntax m => [m.Target],
IndexSyntax i => i.Index is null ? [i.Target] : [i.Target, i.Index],
WithSyntax w => [w.Target],
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs
index f6e29ed4..bb99e3eb 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs
@@ -1,5 +1,3 @@
-using System.Globalization;
-
namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
/// <summary>Literal and bounded dimensional binding over syntax. This preserves the
@@ -19,41 +17,9 @@ internal static class FirmamentSyntaxValues
public static bool TryMeasure(ExpressionSyntax? expression, string unit, out double value, string? implicitUnit = null)
{
value = double.NaN;
- if (!Evaluate(expression, unit, out var result, out var dimension) || dimension != (unit.Length == 0 ? 0 : 1) && !(dimension == 0 && unit == implicitUnit)) return false;
- value = result; return double.IsFinite(value);
- }
-
- private static bool Evaluate(ExpressionSyntax? expression, string unit, out double value, out int dimension)
- {
- value = double.NaN; dimension = 0;
- switch (expression)
- {
- case LiteralSyntax { Kind: LiteralKind.Number } literal:
- return double.TryParse(literal.Raw, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);
- case QuantitySyntax quantity when quantity.Unit.Text == unit:
- if (!Evaluate(quantity.Value, unit, out value, out dimension) || dimension != 0) return false;
- dimension = 1; return true;
- case UnarySyntax { Operator: UnaryOperator.Positive or UnaryOperator.Negative } unary:
- if (!Evaluate(unary.Operand, unit, out value, out dimension)) return false;
- if (unary.Operator == UnaryOperator.Negative) value = -value;
- return true;
- case SequenceSyntax { Kind: SequenceKind.Tuple, Items.Count: 1 } group:
- return Evaluate(group.Items[0].Value, unit, out value, out dimension);
- case BinarySyntax binary:
- if (!Evaluate(binary.Left, unit, out var left, out var ld) || !Evaluate(binary.Right, unit, out var right, out var rd)) return false;
- switch (binary.Operator)
- {
- case BinaryOperator.Add or BinaryOperator.Subtract when ld == rd:
- dimension = ld; value = binary.Operator == BinaryOperator.Add ? left + right : left - right; break;
- case BinaryOperator.Multiply:
- dimension = ld + rd; value = left * right; break;
- case BinaryOperator.Divide when Math.Abs(right) > double.Epsilon:
- dimension = ld - rd; value = left / right; break;
- default: return false;
- }
- return dimension is >= 0 and <= 1 && double.IsFinite(value);
- default: return false;
- }
+ if (!FirmamentNumericEvaluation.TryEvaluate(expression, out var result)
+ || result.Unit != unit && !(result.Unit.Length == 0 && unit == implicitUnit)) return false;
+ value = result.Number; return true;
}
public static bool Vector(ExpressionSyntax? expression, string unit, out double[] values, string? implicitUnit = null)
@@ -77,6 +43,12 @@ internal static class FirmamentSyntaxValues
}
values = result; return true;
}
+ internal static List<(string Text, int Start)> Components(string text)
+ {
+ var parsed = FirmamentSyntaxParser.ParseExpression("[" + text + "]");
+ return parsed.Expression is SequenceSyntax s ? s.Items.Select(a => (text.Substring(a.Value.Span.Start - 1, a.Value.Span.Length), a.Value.Span.Start - 1)).ToList() : [];
+ }
+
}
/// <summary>Each semantic owner consumes its actual fields, then closes its scope.
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs
new file mode 100644
index 00000000..c845ad3e
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs
@@ -0,0 +1,100 @@
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+/// <summary>Serialization boundary for existing domain adapters. This writes structured
+/// syntax; it performs no name resolution, expression evaluation or source parsing.</summary>
+internal sealed class FirmamentSyntaxWriter(string? source = null)
+{
+ internal static string Statements(IEnumerable<StatementSyntax> statements, string? source = null) => new FirmamentSyntaxWriter(source).WriteStatements(statements);
+ internal static string Statement(StatementSyntax statement, string? source = null) => new FirmamentSyntaxWriter(source).WriteStatement(statement);
+ internal static string Expression(ExpressionSyntax expression, string? source = null) => new FirmamentSyntaxWriter(source).WriteExpression(expression);
+ internal static string Type(TypeSyntax type) => new FirmamentSyntaxWriter().WriteType(type);
+
+ private string WriteStatements(IEnumerable<StatementSyntax> statements) => string.Join("\n", statements.Select(WriteStatement));
+ private string WriteBlock(BlockSyntax block) => "{\n" + WriteStatements(block.Statements) + "\n}";
+ private string WriteType(TypeSyntax type) => type.Name.Text + (type.Arguments.Count == 0 && type.Span.Length <= type.Name.Span.Length ? "" : "<" + WriteArguments(type.Arguments) + ">");
+ private string WriteArguments(IEnumerable<ArgumentSyntax> args) => string.Join(", ", args.Select(a =>
+ (a.Name is null ? "" : a.Name.Text + ": ") + WriteExpression(a.Value) + (a.Default is null ? "" : " = " + WriteExpression(a.Default))));
+ private string WriteStatement(StatementSyntax s) => s switch
+ {
+ DeclarationSyntax d => WriteDeclaration(d),
+ FieldSyntax f => f.Name.Text + ": " + WriteExpression(f.Value) + ";",
+ DirectiveSyntax d => d.Kind.ToString().ToLowerInvariant() + " " + WriteExpression(d.Value),
+ ExpressionStatementSyntax e => WriteExpression(e.Value),
+ ReturnSyntax r => "return " + WriteExpression(r.Value),
+ MappingSyntax m => m.Key.Text + " => " + WriteStatement(m.Value),
+ RoleRequirementSyntax r => "Role " + r.Name.Text + " requires " + string.Join(", ", r.Capabilities.Select(c => c.Text)),
+ InterfaceRelationSyntax r => "Lower " + r.Kind.Text + " " + WriteExpression(r.First) + " " + WriteExpression(r.Second) + (r.Option is null ? "" : " " + WriteExpression(r.Option)),
+ InterfaceFitSyntax f => "Fit " + WriteExpression(f.Shaft) + " inside " + WriteExpression(f.Bore) + (f.PerSide ? " per-side" : ""),
+ InterfaceMotionSyntax m => "Allow " + m.Kind.Text + ": " + m.Axis.Text,
+ InterfacePolicySyntax p => p.Kind.Text + " " + string.Join(" ", p.Values.Select(a => a.Name!.Text + " " + WriteExpression(a.Value))),
+ ReplacementSyntax r => "replace " + WriteExpression(r.Target) + " with " + WriteDeclaration(r.Replacement),
+ _ => throw new InvalidOperationException($"Unowned syntax serialization: {s.GetType().Name}.")
+ };
+ private string WriteDeclaration(DeclarationSyntax d)
+ {
+ var head = string.Join(" ", d.Modifiers.Select(WriteType).Append(WriteType(d.Type)))
+ + (d.Target is not null ? " " + WriteExpression(d.Target) : d.Name is null ? "" : " " + d.Name.Text)
+ + (!d.HasParameterList && d.Parameters.Count == 0 && d.ResultType is null ? "" : "(" + WriteArguments(d.Parameters) + ")")
+ + (d.Annotation is null ? "" : ": " + WriteExpression(d.Annotation))
+ + (d.ResultType is null ? "" : " -> " + WriteExpression(d.ResultType))
+ + string.Concat(d.Clauses.Select(c => " " + c.Kind + (c.Kind == ClauseKind.Key ? ":" : "") + " " + WriteExpression(c.Value)))
+ + (d.Initializer is null ? "" : " = " + WriteExpression(d.Initializer));
+ if (d.Occurrence) return "<" + head + ">\n" + WriteStatements(d.Body?.Statements ?? []) + "\n</" + WriteType(d.Type) + ">";
+ return head + (d.Body is null ? ";" : " " + WriteBlock(d.Body));
+ }
+ private string WriteExpression(ExpressionSyntax e) => e switch
+ {
+ ReferenceSyntax r => r.Name.Text,
+ LiteralSyntax l => l.Raw,
+ UnarySyntax u => (u.Operator switch { UnaryOperator.Positive => "+", UnaryOperator.Negative => "-", UnaryOperator.Not => "!", _ => "Reverse " }) + WriteExpression(u.Operand),
+ BinarySyntax { Operator: BinaryOperator.Pipeline or BinaryOperator.Direction } b => WriteExpression(b.Left) + " " + Operator(b.Operator) + " " + WriteExpression(b.Right),
+ BinarySyntax b => "(" + WriteExpression(b.Left) + " " + Operator(b.Operator) + " " + WriteExpression(b.Right) + ")",
+ QuantitySyntax q => WriteExpression(q.Value) + q.Unit.Text,
+ SequenceSyntax s => (s.Kind == SequenceKind.List ? "[" : "(") + WriteArguments(s.Items) + (s.Kind == SequenceKind.List ? "]" : ")"),
+ MemberSyntax m => WriteExpression(m.Target) + "." + m.Member.Text,
+ IndexSyntax i => WriteExpression(i.Target) + "[" + (i.Index is null ? "" : WriteExpression(i.Index)) + "]",
+ CallSyntax c => WriteExpression(c.Target) + "(" + WriteArguments(c.Arguments) + ")",
+ SpecializationSyntax s => WriteSpecialization(s),
+ ObjectSyntax o => (o.Type is null ? "" : WriteExpression(o.Type) + " ") + (o.Name is null ? "" : o.Name.Text + " ") + WriteBlock(o.Body),
+ WithSyntax w => WriteExpression(w.Target) + " with " + WriteBlock(w.Body),
+ FrameSyntax f => WriteExpression(f.Origin) + " " + string.Join(" ", f.Axes.Select(a => a.Name!.Text + WriteExpression(a.Value))),
+ AliasSyntax a => WriteExpression(a.Value) + " as " + a.Name.Text,
+ TraceSyntax t => WriteExpression(t.Source) + (t.From is null ? "" : " from " + WriteExpression(t.From)) + (t.To is null ? "" : " to " + WriteExpression(t.To)),
+ MemberSetSyntax m => WriteExpression(m.Target) + ".[" + WriteArguments(m.Members) + "]",
+ TypedValueSyntax t => WriteExpression(t.Type) + " = " + WriteExpression(t.Value),
+ ProvenanceSyntax p => WriteExpression(p.Value) + " from " + p.Source.Raw,
+ TypeParameterSyntax p => "type " + p.Name.Text + (p.Constraint is null ? "" : " satisfies " + WriteExpression(p.Constraint)),
+ MatchSyntax m => "Match " + WriteExpression(m.Scrutinee) + " { " + string.Join("; ", m.Arms.Select(a => WriteExpression(a.Pattern) + " => " + WriteExpression(a.Value))) + " }",
+ ToleranceSyntax t => WriteExpression(t.Nominal) + " tol " + WriteExpression(t.Plus) + (t.Minus is null ? "" : " -" + WriteExpression(t.Minus)),
+ _ => throw new InvalidOperationException($"Unowned expression serialization: {e.GetType().Name}.")
+ };
+ private string WriteSpecialization(SpecializationSyntax specialization)
+ {
+ var span = specialization.Span;
+ var target = specialization.Target;
+ var arguments = specialization.Arguments;
+ // Assembly definition identities historically include the application spelling.
+ // Preserve its punctuation/trivia while writing already-bound argument ASTs.
+ // No identifier replacement or semantic interpretation occurs here.
+ if (source is null || span.Start < 0 || span.Start + span.Length > source.Length
+ || target.Span.Start < span.Start || target.Span.Start + target.Span.Length > span.Start + span.Length
+ || source.Substring(target.Span.Start, target.Span.Length) != WriteExpression(target)
+ || arguments.Any(a => a.Default is not null || a.AuthoredValueSpan.Start < target.Span.Start + target.Span.Length
+ || a.AuthoredValueSpan.Start + a.AuthoredValueSpan.Length > span.Start + span.Length))
+ return WriteExpression(target) + "<" + WriteArguments(arguments) + ">";
+ var text = source.Substring(span.Start, span.Length);
+ foreach (var argument in arguments.OrderByDescending(a => a.AuthoredValueSpan.Start))
+ text = text.Remove(argument.AuthoredValueSpan.Start - span.Start, argument.AuthoredValueSpan.Length)
+ .Insert(argument.AuthoredValueSpan.Start - span.Start, WriteExpression(argument.Value));
+ return text;
+ }
+
+ private static string Operator(BinaryOperator op) => op switch
+ {
+ BinaryOperator.Pipeline => "|>", BinaryOperator.Direction => "->", BinaryOperator.Or => "||", BinaryOperator.And => "&&",
+ BinaryOperator.Equal => "==", BinaryOperator.NotEqual => "!=", BinaryOperator.Less => "<", BinaryOperator.LessEqual => "<=",
+ BinaryOperator.Greater => ">", BinaryOperator.GreaterEqual => ">=", BinaryOperator.Add => "+", BinaryOperator.Subtract => "-",
+ BinaryOperator.Multiply => "*", BinaryOperator.Divide => "/", BinaryOperator.Remainder => "%", BinaryOperator.Power => "^",
+ _ => throw new ArgumentOutOfRangeException(nameof(op))
+ };
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentTemplateSyntax.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentTemplateSyntax.cs
new file mode 100644
index 00000000..20b2b868
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentTemplateSyntax.cs
@@ -0,0 +1,179 @@
+using System.Collections.Immutable;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+/// <summary>Lexical Template declarations and applications from the production AST.
+/// Text slices only transport checked nodes into the existing specialization lowerer.</summary>
+internal sealed class FirmamentTemplateSyntax
+{
+ internal sealed class Scope(Scope? parent, string identity)
+ {
+ private readonly FirmamentBindingScope symbols = new(parent?.symbols, identity);
+ private readonly Dictionary<DeclarationSyntax, TemplateDeclarationIr> declarations = parent?.declarations ?? new();
+ internal string Identity => symbols.Identity;
+ internal bool Declare(DeclarationSyntax syntax, TemplateDeclarationIr template)
+ {
+ declarations[syntax] = template;
+ return symbols.Declare("Template", syntax);
+ }
+ internal TemplateDeclarationIr? Resolve(string name) => symbols.Resolve("Template", name) is { } syntax
+ ? declarations[syntax] : null;
+ }
+
+ internal Scope Root { get; }
+ internal Scope ExportScope { get; }
+ internal int ExportPosition { get; }
+ internal List<TemplateDeclarationIr> Declarations { get; } = [];
+ internal List<TemplateDeclarationIr> RemovableDeclarations { get; } = [];
+ internal List<TemplateApplicationIr> Applications { get; } = [];
+ internal List<FirmamentV2ValidationDiagnostic> Diagnostics { get; } = [];
+
+ internal FirmamentTemplateSyntax(string source, List<string> diagnostics, Scope? parent = null)
+ {
+ Root = new(parent, parent is null ? "document" : parent.Identity + "/specialization");
+ ExportScope = Root;
+ var bodyScopes = new Dictionary<DeclarationSyntax, Scope>();
+ var parsed = FirmamentSyntaxParser.Parse(source);
+ if (!parsed.IsSuccess)
+ {
+ // This owner cannot relabel another construct's syntax failure as a
+ // Template error. The normal frontend/owning expander presents it.
+ var tokens = parsed.Document.Tokens.Where(t => t.Kind is not (SyntaxTokenKind.Whitespace or SyntaxTokenKind.Comment)).ToArray();
+ var hasProductPrefix = tokens.Zip(tokens.Skip(1)).Any(pair => pair.First.Kind == SyntaxTokenKind.Identifier
+ && pair.First.Text == "Template" && pair.Second.Text == "<");
+ if (hasProductPrefix || FirmamentSyntaxTraversal.Declarations(parsed.Document).Any(d => d.Modifiers.Any(m => m.Name.Text == "Template")))
+ diagnostics.AddRange(parsed.Diagnostics.Where(d => d.Severity is "fatal" or "error")
+ .Select(d => FirmamentV2TemplateExpansion.Prefix + "syntax: " + d.Code + ": " + d.Message));
+ return;
+ }
+ Visit(parsed.Document.Statements, Root, null);
+ // Existing host libraries use one Model as their module container. Keep
+ // that explicit compatibility form; never pool declarations from siblings.
+ var models = parsed.Document.Statements.OfType<DeclarationSyntax>()
+ .Where(d => d.Type.Name.Text == "Model" && d.Body is not null && d.Modifiers.Count == 0).ToArray();
+ if (!Declarations.Any(d => ReferenceEquals(d.DefinitionScope, Root)) && models.Length == 1
+ && bodyScopes.TryGetValue(models[0], out var moduleScope))
+ { ExportScope = moduleScope; ExportPosition = models[0].Body!.ContentSpan.Start; }
+ foreach (var group in Declarations.GroupBy(d => d.Name).Where(g => g.Count() > 1))
+ foreach (var template in group) template.IdentityNamespace = template.DefinitionScope!.Identity;
+
+ void Visit(IReadOnlyList<StatementSyntax> statements, Scope scope, TemplateDeclarationIr? owner)
+ {
+ var definitions = new Dictionary<DeclarationSyntax, TemplateDeclarationIr>();
+ // Register all siblings before resolving any application (forward references).
+ foreach (var declaration in statements.OfType<DeclarationSyntax>())
+ {
+ var modifier = declaration.Modifiers.FirstOrDefault(m => m.Name.Text == "Template");
+ if (modifier is null) continue; // finite feature Templates have their existing owner
+ var kind = Kind(declaration);
+ if (kind is null || declaration.Name is null || declaration.Body is null
+ || declaration.HasParameterList || declaration.Initializer is not null
+ || declaration.ResultType is not null || declaration.Clauses.Count != 0
+ || declaration.Type.Span.Length != declaration.Type.Name.Span.Length || declaration.Occurrence
+ || modifier.Span.Length == modifier.Name.Span.Length
+ || declaration.Modifiers.Count(m => m.Name.Text == "Template") != 1
+ || declaration.Modifiers.Count(m => m.Name.Text == "Concept") > 1
+ || declaration.Modifiers.Any(m => m.Name.Text is not ("Template" or "Concept")))
+ {
+ Error(FirmamentV2TemplateExpansion.Prefix + "invalid-declaration-header", "A product Template requires a named body and cannot carry ignored parameters, placement or initializer clauses.", declaration);
+ continue;
+ }
+ var parameters = ImmutableArray.CreateBuilder<TemplateParameterIr>();
+ var names = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var parameter in modifier.Arguments)
+ {
+ if (parameter.Name is null || !names.Add(parameter.Name.Text))
+ {
+ diagnostics.Add((parameter.Name is null ? FirmamentV2TemplateExpansion.InvalidParameter
+ : FirmamentV2TemplateExpansion.DuplicateParameter) + ":" + parameter.Name?.Text);
+ continue;
+ }
+ if (parameter.Value is TypeParameterSyntax { Constraint: ReferenceSyntax constraint } type && parameter.Default is null)
+ parameters.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));
+ else diagnostics.Add(FirmamentV2TemplateExpansion.InvalidParameter + ":" + parameter.Name.Text);
+ }
+ var template = new TemplateDeclarationIr(declaration.Name.Text, kind,
+ declaration.Annotation is null ? "" : ": " + Text(declaration.Annotation.Span),
+ parameters.ToImmutable(), Text(declaration.Body.ContentSpan), declaration.Span)
+ {
+ DefinitionScope = scope,
+ 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);
+ definitions[declaration] = template;
+ Declarations.Add(template);
+ if (owner is null) RemovableDeclarations.Add(template);
+ }
+ foreach (var statement in statements)
+ {
+ if (statement is MappingSyntax mapping)
+ {
+ Visit([mapping.Value], new(scope, scope.Identity + "/mapping " + mapping.Key.Text), owner);
+ continue;
+ }
+ if (statement is not DeclarationSyntax declaration) continue;
+ if (definitions.TryGetValue(declaration, out var definition))
+ {
+ Visit(declaration.Body!.Statements, definition.BodyScope!, definition);
+ continue;
+ }
+ if (Kind(declaration) is { } kind && declaration.Name is not null
+ && declaration.Initializer is SpecializationSyntax { Target: ReferenceSyntax target } application)
+ {
+ var template = scope.Resolve(target.Name.Text);
+ if (template is null)
+ {
+ Error(FirmamentV2TemplateExpansion.Prefix + "not-found:" + target.Name.Text, $"Template '{target.Name.Text}' is not visible from scope '{scope.Identity}'. Declare it in this scope or an enclosing scope.", declaration);
+ continue;
+ }
+ if (declaration.HasParameterList || declaration.Annotation is not null || declaration.ResultType is not null
+ || declaration.Body is not null || declaration.Clauses.Count != 0 || declaration.Modifiers.Any(m => m.Name.Text != "Concept"))
+ {
+ Error(FirmamentV2TemplateExpansion.Prefix + "invalid-application-header:" + declaration.Name.Text, "A Template application cannot carry ignored placement, parameter, annotation or body clauses. Put supported placement in the resulting construction.", declaration);
+ continue;
+ }
+ var arguments = ImmutableArray.CreateBuilder<TemplateArgumentIr>();
+ var seen = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var argument in application.Arguments)
+ {
+ if (argument.Name is null || argument.Default is not null)
+ diagnostics.Add(FirmamentV2TemplateExpansion.UnknownArgument + ":" + Text(argument.Span));
+ else if (!seen.Add(argument.Name.Text)) diagnostics.Add(FirmamentV2TemplateExpansion.DuplicateArgument + ":" + argument.Name.Text);
+ else arguments.Add(new(argument.Name.Text, Text(argument.Value.Span), argument.Span));
+ }
+ var bound = new TemplateApplicationIr(kind, declaration.Name.Text, target.Name.Text, arguments.ToImmutable(), declaration.Span)
+ { BoundTemplate = template, BindingScope = scope.Identity };
+ if (owner is null) Applications.Add(bound);
+ else owner.BodyApplications.Add(bound);
+ }
+ if (declaration.Body is { } body)
+ {
+ var child = new Scope(scope, scope.Identity + "/" + declaration.Type.Name.Text + " " + declaration.Name?.Text + "@" + declaration.Span.Start);
+ bodyScopes[declaration] = child;
+ Visit(body.Statements, child, owner);
+ }
+ }
+ }
+ void Error(string code, string message, DeclarationSyntax declaration)
+ {
+ diagnostics.Add(code);
+ Diagnostics.Add(new(code, "fatal", message, declaration.Name?.Text, declaration.Type.Name.Text)
+ {
+ SourceFile = "inline#pre-template-expansion", SourceSpan = declaration.Span,
+ IsOriginalSource = false, Stage = "Template binding",
+ LocationNote = "Location identifies the enclosing declaration before Template specialization; original-source mapping is applied by the frontend where available.",
+ });
+ }
+ string Text(FirmamentV2SourceSpan span) => source.Substring(span.Start, span.Length);
+ }
+
+ private static string? Kind(DeclarationSyntax declaration) => declaration.Type.Name.Text switch
+ {
+ "Struct" when declaration.Modifiers.Any(m => m.Name.Text == "Concept") => "Concept Struct",
+ "Struct" or "Model" or "Panel" or "SheetMetal" or "ProfileDelta" or "Profile" => declaration.Type.Name.Text,
+ _ => null,
+ };
+}
diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentAuthoring.cs b/Aetheris.Kernel.Firmament/Garment/GarmentAuthoring.cs
index e82eb2ca..1ece75b8 100644
--- a/Aetheris.Kernel.Firmament/Garment/GarmentAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/Garment/GarmentAuthoring.cs
@@ -1,3 +1,4 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using System.Collections.Immutable;
using System.Globalization;
using System.Numerics;
@@ -412,7 +413,7 @@ public static class GarmentAuthoring
private static float Scalar(string value)
{
- if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(value, out double evaluated, out string unit) || unit.Length != 0)
+ if (!FirmamentNumericEvaluation.TryEvaluateScalar(value, out double evaluated, out string unit) || unit.Length != 0)
{
Fail("garment-scalar-invalid", "Expected a dimensionless scalar: " + value);
}
@@ -426,7 +427,7 @@ public static class GarmentAuthoring
private static float Length(string value)
{
- if (FirmamentV2FeatureExpansion.TryEvaluateScalar(value, out double evaluated, out string unit) && unit == "mm")
+ if (FirmamentNumericEvaluation.TryEvaluateScalar(value, out double evaluated, out string unit) && unit == "mm")
{
if (!double.IsFinite(evaluated) || !float.IsFinite((float)evaluated))
{
diff --git a/Aetheris.Kernel.Firmament/Garment/GarmentFigureAuthoring.cs b/Aetheris.Kernel.Firmament/Garment/GarmentFigureAuthoring.cs
index f3bccf57..91530874 100644
--- a/Aetheris.Kernel.Firmament/Garment/GarmentFigureAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/Garment/GarmentFigureAuthoring.cs
@@ -1,3 +1,4 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using System.Globalization;
using System.Text.RegularExpressions;
using Aetheris.Humanoid;
@@ -151,7 +152,7 @@ internal static class GarmentFigureAuthoring
private static double Length(string text)
{
- if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(text, out double value, out string unit) || unit != "mm")
+ if (!FirmamentNumericEvaluation.TryEvaluateScalar(text, out double value, out string unit) || unit != "mm")
{
GarmentAuthoring.Fail("garment-fit-unit-invalid", "Section height must be a Length: " + text);
}
diff --git a/Aetheris.Kernel.Firmament/Humanoid/HumanoidPoseAuthoring.cs b/Aetheris.Kernel.Firmament/Humanoid/HumanoidPoseAuthoring.cs
index b26d0af7..660b5f7f 100644
--- a/Aetheris.Kernel.Firmament/Humanoid/HumanoidPoseAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/Humanoid/HumanoidPoseAuthoring.cs
@@ -1,3 +1,4 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using System.Globalization;
using System.Text.RegularExpressions;
using Aetheris.Humanoid;
@@ -277,7 +278,7 @@ public static class HumanoidPoseAuthoring
private static double Angle(string text)
{
- if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(text, out double value, out string unit)
+ if (!FirmamentNumericEvaluation.TryEvaluateScalar(text, out double value, out string unit)
|| unit != "deg" || !double.IsFinite(value))
{
Fail("humanoid-pose-angle", "Anatomical angles require finite degree-valued expressions: " + text);
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
index b4639760..c1ee681f 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
@@ -873,9 +873,9 @@ public static class PrismaticProfileCompositionParser
var normal = plane.Groups["normal"].Value.Split(',');
var up = plane.Groups["up"].Success ? plane.Groups["up"].Value.Split(',').Select(v => v.Trim()).ToArray() : new[] { "0", "1", "0" };
if (!up.SequenceEqual(new[] { "0", "1", "0" }) || origin.Length != 3 || normal.Length != 3
- || !FirmamentV2FeatureExpansion.TryEvaluateScalar(origin[0], out var x, out var xu) || xu != "mm" || Math.Abs(x) > 1e-9
- || !FirmamentV2FeatureExpansion.TryEvaluateScalar(origin[1], out var y, out var yu) || yu != "mm" || Math.Abs(y) > 1e-9
- || !FirmamentV2FeatureExpansion.TryEvaluateScalar(origin[2], out var z, out var zu) || zu != "mm"
+ || !FirmamentNumericEvaluation.TryEvaluateScalar(origin[0], out var x, out var xu) || xu != "mm" || Math.Abs(x) > 1e-9
+ || !FirmamentNumericEvaluation.TryEvaluateScalar(origin[1], out var y, out var yu) || yu != "mm" || Math.Abs(y) > 1e-9
+ || !FirmamentNumericEvaluation.TryEvaluateScalar(origin[2], out var z, out var zu) || zu != "mm"
|| !double.TryParse(normal[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var nx) || nx != 0
|| !double.TryParse(normal[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var ny) || ny != 0
|| !double.TryParse(normal[2], NumberStyles.Float, CultureInfo.InvariantCulture, out var nz) || nz != 1)
diff --git a/Aetheris.Kernel.Firmament/Scene/SceneAuthoring.cs b/Aetheris.Kernel.Firmament/Scene/SceneAuthoring.cs
index 576c6090..0e47ae65 100644
--- a/Aetheris.Kernel.Firmament/Scene/SceneAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/Scene/SceneAuthoring.cs
@@ -1,3 +1,4 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using System.Globalization;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Math;
@@ -316,7 +317,7 @@ public static class SceneAuthoring
// dimension-checked scalar evaluator. No separate Scene arithmetic engine.
var expression = Regex.Replace(value, @"(?<![\w.])(?<n>(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)m\b", m =>
(double.Parse(m.Groups["n"].Value,CultureInfo.InvariantCulture)*1000).ToString("R",CultureInfo.InvariantCulture)+"mm");
- if (!FirmamentV2FeatureExpansion.TryEvaluateScalar(expression,out var n,out var unit) || unit != "mm" || !double.IsFinite(n))
+ if (!FirmamentNumericEvaluation.TryEvaluateScalar(expression,out var n,out var unit) || unit != "mm" || !double.IsFinite(n))
Fail("scene-length-unit-required", $"Expected a finite length expression with m or mm suffix, got '{value}'.");
return n;
}
diff --git a/Aetheris.Server.Tests/PaperclipDemoIntegrationTests.cs b/Aetheris.Server.Tests/PaperclipDemoIntegrationTests.cs
index 2ea3079e..b13e6a67 100644
--- a/Aetheris.Server.Tests/PaperclipDemoIntegrationTests.cs
+++ b/Aetheris.Server.Tests/PaperclipDemoIntegrationTests.cs
@@ -16,7 +16,7 @@ public sealed class PaperclipDemoIntegrationTests : IClassFixture<WebApplication
{
var response = await _client.PostAsJsonAsync("/api/v1/demos/maximum-paperclips",
new PaperclipDemoRequest(1, 17.25, 16.1, 5, 3, "Standard.Materials.StainlessSteel.304_Annealed"));
- response.EnsureSuccessStatusCode();
+ Assert.True(response.IsSuccessStatusCode, await response.Content.ReadAsStringAsync());
var envelope = await response.Content.ReadFromJsonAsync<ApiResponseDto<PaperclipDemoResponse>>();
Assert.NotNull(envelope?.Data);
diff --git a/Aetheris.Server/Api/PaperclipDemoEndpoints.cs b/Aetheris.Server/Api/PaperclipDemoEndpoints.cs
index 04a06d0d..206adb21 100644
--- a/Aetheris.Server/Api/PaperclipDemoEndpoints.cs
+++ b/Aetheris.Server/Api/PaperclipDemoEndpoints.cs
@@ -23,7 +23,8 @@ public static class PaperclipDemoEndpoints
["InnerBendRadius"] = Mm(request.InnerBendRadius),
["Material"] = System.Text.Json.JsonSerializer.Serialize(request.Material ?? "Standard.Materials.StainlessSteel.304_Annealed"),
};
- var expansion = FirmamentTemplateHostBridge.Expand(PaperclipTemplateLibrary.Source, "PaperclipTemplate", "InteractivePaperclip",
+ var module = StandardProductTemplateLibrary.GetTemplateSource("PaperclipTemplate", "PaperclipPolicy");
+ var expansion = FirmamentTemplateHostBridge.Expand(module, "PaperclipTemplate", "InteractivePaperclip",
new Dictionary<string, FirmamentHostArgument>(StringComparer.Ordinal) { ["P"] = new(string.Empty, "PaperclipPolicy", fields) }, out var diagnostics);
if (expansion is null) return ApiMappings.BadRequestFromMessage(string.Join("; ", diagnostics), "maximum-paperclips.bind");
var compiled = FirmamentBuildAndExport.CompileSource(expansion.ExpandedSource);
diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
index 1c2c3d0c..cee10943 100644
--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
@@ -1,5 +1,20 @@
# October 2026 Firmament language decision register
+X2 production binding amendment (2026-10-15):
+[current semantic migration report](../release/FIRMAMENT-FRONTEND-X2.md) migrates
+Feature definitions/calls, private construction renaming and defaults to lexical
+AST binding. Shared numeric AST evaluation replaces Feature's private arithmetic
+parser and the separate syntax-field arithmetic implementation. Static scalar
+binding and Concept arithmetic share the numerical operator/type policy. Keyed
+Set, record-array and Assembly/Scene occurrence Pattern headers/mappings use AST
+nodes; semantic point Pattern references no longer replace field labels.
+Product Template lookup and Record/Static/Table lexical data ownership now use
+the AST. The shared typed data catalog replaces independent canonical readers.
+Set/array collections, Template body transport, several domain readers and complete
+include/expansion provenance remain unfinished. X2 is **Meaningful progression**,
+not Accepted; the original findings/rationale and all 24 recommendations below
+remain tracked.
+
Concept/2D amendment (2026-10-14):
[production qualification](../release/FIRMAMENT-CONCEPTS-AND-2D.md) adds named
scalar predicates and record-shaped labeled requirement bundles. Structural
@@ -199,3 +214,78 @@ and records 4,943 passing full-suite tests plus 26 byte-identical STEP baselines
This closes the structural migration gate, not X2 semantic consolidation or the
remaining domain source adapters. The nine explicit canonical admission limits
and downstream-only negative expectations remain visible in the closeout ledger.
+
+
+## X2 current owner and handoff matrix
+
+This supplements the original recommendation/rationale table; it does not replace
+its history. “Retained” means the existing admitted semantics remain, not that the
+complete language surface is reconciled. X2 remains Meaningful progression.
+
+| # | Current implementation / semantic owner | Compatibility impact | X3 decision / X4 evidence still needed |
+| --- | --- | --- | --- |
+| 1 | Shared production admission; Feature/Template/data binding failures reach validate/build | Existing valid sources retained; lexical sibling capture rejects | X4 repeat all twelve sources through both commands. |
+| 2 | Shared V2 disposition/severity and explicit serialized V1 boundary retained | Feature fatal severity retained; shared syntax owns control-flow rejection | X4 ensure every failure remains V2 and actionable. |
+| 3 | Mechanical AST field/statement owners; Feature/Pattern bodies and Record/Table fields consumed | Labels cannot be rewritten as iteration references; other domains still pending | Complete domain source consumption in X2, then X4 omission witnesses. |
+| 4 | Compiler diagnostic records; original Feature definition/use anchors added | Existing codes/severity/report retained; explain adds receipts | Complete module/Template maps in X2; X4 diagnostic repair effort. |
+| 5 | Existing placement/frame admission retained | No new plane fallback or kernel placement behavior | X4 asymmetric XZ and attachment witnesses. |
+| 6 | Existing document summary/Pocket capability messages retained | No semantic change | X4 check model identity and through-cut guidance. |
+| 7 | X1 lexer/recursive-descent AST remains structural authority | No replacement parser or new dispatch | X3 root/scope teaching; X4 documented first-try paths. |
+| 8 | Feature AST expansion, Template lexical lookup, scoped data identities and Pattern mapping hygiene migrated | Stable names/keys retained; product Template body/value adapters remain X2 | Finish module/Template AST handoff before X3 syntax changes. |
+| 9 | Shared numeric AST evaluator/type policy used by fields, scalar graph, Feature and Concept arithmetic | Units preserved; Record/Static/Table scope and nominal schemas migrated; collection/domain value ownership remains partial | Finish typed value consolidation in X2; X4 arithmetic in ordinary parts. |
+| 10 | Existing point/vector owners retained; Feature components use shared numeric AST values | Both established point spellings retained where admitted | X3 choose canonical literal and alias policy; X4 point ergonomics. |
+| 11 | Existing Hole/EdgeFinish variant owners retained | No new generic EdgeFinish form | X3 reconcile variants; X4 exact repair diagnostic. |
+| 12 | Set/array/occurrence AST mappings; semantic point substitution fixed | Human spellings unchanged; radial/mirror/linear owners still separate | X3 unify surface forms after remaining X2 semantics; X4 Pattern authoring. |
+| 13 | Existing Compose and materializer authority retained | ThroughCut versus Pocket unchanged | X3 termination vocabulary; X4 enclosure/slot tasks. |
+| 14 | Existing document/domain root contracts retained | No new optional-root rule | X3 decide and document root policy; X4 wrapping stability. |
+| 15 | Public syntax updated for actual Feature and product Template scope/defaults | No speculative syntax published as admitted | X4 repeat complete public examples and original corpus. |
+| 16 | Existing separators retained; serializer meets Assembly adapter requirements | No broad terminator grammar change | X3 reconcile separators, including Grid derivation friction. |
+| 17 | Existing spelling metadata/AST normalization retained | Pascal/camel aliases preserved; user symbols retain case | X3 remaining owner exceptions and PMI spelling; X4 examples. |
+| 18 | Existing one-off geometry owners retained | No deletion based on frequency | X3 justify library/construct boundaries after semantic qualification. |
+| 19 | Feature defaults plus Record/Static/Table references use lexical AST identities and the common typed catalog | No general Let or runtime variables | Finish lexical value ownership in X2; X3 surface choice; X4 parameterization effort. |
+| 20 | Existing named outline/profile construction retained | No new inline polygon/revolve grammar | X3 vertex-list policy; X4 L-bracket/revolve friction. |
+| 21 | Existing typed face/selection owners retained | No global face alias expansion | X2 typed selector binding; X3 canonical spelling; X4 selection repairs. |
+| 22 | Existing inspect and validate --explain expose Feature/Template scopes/arguments; validate also exposes data identities and available origins | Ordinary report shape unchanged; developer metadata additive | Complete Template/Pattern/module explanation in X2; X4 diagnosis usefulness. |
+| 23 | AST remains incomplete as an authoritative semantic grammar generator | No aspirational grammar publication | Finish source owner migration, then X3 generated reference and X4 doc qualification. |
+| 24 | Existing kernel/material/capability owners retained | No Fillet+Hole, shell or general plane implementation | Separate engineering capability work; X4 accurate unsupported diagnostics. |
+
+
+### X2 continuation: lexical product Templates
+
+Product Template declarations, parameters, applications and dependency edges now
+come from the shared AST. Local shadowing, sibling privacy and definition-scope
+nested lookup are qualified through production compilation. Host exports retain
+document and single-Model module-container compatibility. Qualified Construct
+capability names and historical lowercase analysis headers have explicit shared
+parser productions. Existing unique-name specialization identities are preserved.
+
+Recommendations 3, 4, 8, 15, 19 and 22 advance with closed application headers,
+source-located lookup errors, lexical receipts and the promoted Family witness.
+At that pass they remained partial for scoped Record/Static/Table binding,
+complete module maps and source-based body/domain lowerers. The following data
+continuation closes the demonstrated schema-capture defect; module maps and
+remaining body/domain adapters stay open. No syntax or kernel-policy decision is
+waiting for the user. All 24 original dispositions/rationales above remain tracked.
+
+
+### X2 continuation: scoped Record, Static and Table data
+
+Record/type and Static/Table value references bind lexical AST identities before
+typed evaluation. Same-named Records in different scopes remain nominally
+distinct. Same-scope duplicates and sibling-private references reject; parameter
+and mapping binders protect their own names. Existing unambiguous spellings,
+field keys and Table key labels are retained. Internal collision identities are
+compiler metadata, not new authoring syntax.
+
+The Record/Table/with/row/alias catalog is shared by specialization and canonical
+static erasure. Its declarations and field values come from the shared AST;
+ordinary scalar evaluation still belongs to the existing typed graph. Table row
+leaves and nested typed aliases enter that graph rather than a second evaluator.
+The former Spec schema-capture witness is promoted to a positive geometry test.
+A scoped requirement witness checks explicit AP242 PMI and authored tolerance
+provenance. Recommendations 3, 4, 8, 9, 15, 19 and 22 advance accordingly.
+
+Complete include-file/module provenance and remaining collection/domain source
+adapters remain X2 work. No general Let, runtime scripting, new units doctrine or
+geometry capability was introduced. All 24 original recommendations and rationale
+remain in the register above; no syntax policy decision is awaiting the user.
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index 086c37a2..86c03b32 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -138,7 +138,10 @@ Follow the consuming guide; there is no uniform statement-termination rule yet.
Write dimensions explicitly in new mechanical source: `8mm`, `90deg`,
`Point2(12mm, -4mm)`. Use bare numbers for dimensionless counts and vector
components. `units: mm` belongs in an ordinary mechanical Model; it does not
-make dimensions optional in every native field.
+make dimensions optional in every native field. Existing Panel arc boundary
+angles also admit `rad`; this does not make radians a universal alias in every
+Angle field. Mixed degree/radian arithmetic requires an explicit owning-domain
+conversion rather than silently adding the raw numbers.
Points and lists overlap without being universal aliases. The direct Hole above
requires `Point2(...)`; a Rect2's `center` accepts `[x, y]`. A semantic Grid may
@@ -519,6 +522,19 @@ defaults. A body may contain typed immutable `let` derivations and admitted
private construction, followed by one terminal `return`. Calls may delegate to
another Feature with the same result type; recursion is rejected.
+Feature names resolve lexically. A Feature declared inside a Model shadows an
+enclosing Feature with the same name; a Feature inside another Struct is not
+visible outside that Struct. Two definitions in the same scope are an error.
+Calls delegated by a Feature resolve in its definition's scope. A Feature and
+a construction Profile may share a name because calls and construction references
+have different roles.
+
+Defaults may use other typed parameters, including dimensional arithmetic;
+cyclic defaults are errors. Expansion is finite: at most 64 nested calls or
+default dependencies, 4,096 invocations, 65,536 expanded declarations and 4 MiB
+of generated construction per Feature expansion phase. Exceeding a limit rejects
+the program; it never yields a partially generated part.
+
Return kinds include Hole variants, Boss, Pocket, EdgeFinish and Profile. A
definition does not grant those results new support in an unsupported consumer.
Feature-local Profile construction is also used by Garment; WireForm, Sweep and
@@ -578,6 +594,11 @@ These are context-specific forms, not interchangeable spellings of one loop.
A named Feature invocation may use `Feature result = Recipe(...)`; it differs
from a Feature definition and from a Pattern.
+In the admitted Set and semantic point Patterns, an iteration symbol substitutes
+value references. It does not rename field labels, declaration names, string
+contents or a similarly spelled identifier. Generated instance identities still
+come from the Pattern and its keys or ordered elements.
+
### Template: specialize a product
**Complete file — one sized member of a product family:**
@@ -598,6 +619,14 @@ specialization admissibility. Typed Record values may carry a configuration;
`Static` binds them and `with` derives checked immutable values. A separate
finite feature-Template form is used by record-array Patterns.
+Product Template names resolve in their lexical scope. A Model-local Template
+can shadow a document Template; a sibling Model's private Template is invisible.
+Nested applications resolve from the Template definition, so a caller-local
+Template does not capture them. Duplicate Template names in the same scope
+reject. Host discovery and invocation expose document-level product Templates;
+existing single-Model module containers also export their immediate Templates.
+Application headers cannot silently discard placement or other clauses.
+
`<...>` therefore means several things: a built-in Hole variant, a Set element
type, or Template parameters/arguments. It does not make every construct a
general generic. See [Templates](templates.md) for constraints, finite Tables,
@@ -607,6 +636,43 @@ Feature, Template and Pattern describe deterministic finite construction. They
do not add mutable state, exceptions, arbitrary recursion, `for`/`while`, or
general `if`/`else` control flow. Use domain-specific forms only where admitted.
+### Compile-time data scope
+
+Record schemas, Static values and Static Tables belong to their lexical scope.
+A local declaration shadows the same name in an enclosing scope; sibling scopes
+remain private. Record types are nominal: declaring another `Record Spec` does
+not make values of the outer Spec instances of the local Spec. Both field names
+and user symbols retain their authored casing.
+
+```firmament
+Record Spec { width: Length }
+Static outer: Spec = Spec { width: 10mm }
+Model Plate {
+ units: mm
+ Record Spec { width: Length thickness: Length }
+ Static Table choices: Spec {
+ width: [30mm]
+ thickness: [6mm]
+ }
+ Static selected: Spec = choices[0]
+ Box stock { size: [selected.width, 20mm, selected.thickness] }
+}
+```
+
+The local Table uses the local schema. The unused outer value keeps its own
+schema and does not acquire a `thickness` requirement. Table rows, checked `with`
+derivations and Record aliases use the same typed data binding as literal
+Records. Product Template defaults resolve where the Template is defined;
+explicit arguments resolve at the invocation. Specialized data is admitted before
+Feature arguments. Unknown fields, inaccessible names, duplicate declarations,
+cycles and unsupported data-header clauses reject.
+
+Typed tolerances on Record/scalar values retain their requirement provenance
+through specialization, geometry and explicit Pmi. Table/collection tolerance
+propagation remains unsupported and rejects; a Table is not a way to bypass that
+boundary. See [the scoped Record witness](../../../fixtures/Regression/FrontendX2/record-shadowing.firmament)
+and [explicit scoped PMI](../../../fixtures/Regression/FrontendX2/scoped-record-pmi.firmament).
+
## Mirror and radial symmetry
Symmetry transforms semantic construction before materialization. It does not
@@ -748,3 +814,13 @@ preserves the original authoring audit and later migration dispositions.
Use [supported features](../reference/supported-features.md) for capability
boundaries and the linked domain guides for detailed syntax. Proposals and
migration reports explain design/history; they do not grant source admission.
+
+Feature, product Template, Record, Static and Table names use lexical lookup.
+Same-named Records in different scopes are distinct nominal types, even when their
+fields match. Values resolve in their declaration scope; callers bind explicit
+arguments in the caller scope. Duplicate names in one namespace/scope reject,
+and sibling-private data cannot be referenced. Complete include/Template
+expansion source maps remain unfinished. `validate --json --explain` exposes
+the implemented Feature and Template owners, lexical scopes, bound arguments and
+available definition/use receipts, plus compile-time data symbol scopes and
+identities, with these limits stated.
diff --git a/docs/public/firmament/templates.md b/docs/public/firmament/templates.md
index be1f3aae..dbe80cb0 100644
--- a/docs/public/firmament/templates.md
+++ b/docs/public/firmament/templates.md
@@ -22,6 +22,17 @@ The complete build-qualified version is [`generic-mounting-plate.firmament`](../
The explicit output keyword is significant: current Templates specialize `Struct`, `Model`, `Concept Struct`, `Panel`, `SheetMetal`, `Profile`, or `ProfileDelta` declarations. It is not inferred from the body.
+Product Template names have lexical scope. A Model-local definition shadows a
+document definition, sibling scopes remain private, and duplicate names in one
+scope reject. Nested applications resolve where the Template was defined.
+Host metadata and host invocation expose document-level product Templates, or
+Templates in the single Model used as a module container by existing libraries.
+They do not merge private definitions from sibling Models.
+Record, Static and Table declarations now use the same lexical ownership. A local
+Record shadows its enclosing name while retaining a distinct nominal type;
+sibling-private data is invisible. Defaults resolve in the definition scope and
+explicit arguments in the caller scope. The geometry operations remain unchanged.
+
A finite feature Template used by `Pattern ... Over` has the same generic visual form:
```text
diff --git a/docs/release/FIRMAMENT-FRONTEND-X2.evidence.json b/docs/release/FIRMAMENT-FRONTEND-X2.evidence.json
new file mode 100644
index 00000000..bef7c6df
--- /dev/null
+++ b/docs/release/FIRMAMENT-FRONTEND-X2.evidence.json
@@ -0,0 +1,1231 @@
+{
+ "schemaVersion": 1,
+ "implementationBase": "e6468b03c6bd4a6b2bfd40329de1381c16968512",
+ "verdict": "Meaningful progression",
+ "acceptedX2": false,
+ "baselineLedger": {
+ "path": "docs/release/FIRMAMENT-FRONTEND-X1-CLOSEOUT.evidence.json",
+ "sha256": "9AE7B4820FCE6F855DE457548BF753BBF3DF26F5A25215E0C3947C388C294228",
+ "sourceCount": 1266
+ },
+ "corpus": {
+ "schemaVersion": 1,
+ "sourceCount": 1276,
+ "canonicalSourceCount": 327,
+ "canonicalStructurallyParsed": 327,
+ "structurallyParsed": 912,
+ "standaloneProductionAccepted": 510,
+ "inventorySha256": "3FE41317FF888DC74EB9A1FF6A95761E4950B7F88301976B5EB4BC8960F24CF0",
+ "unresolvedMismatchCount": 0,
+ "universalSemanticParityQualified": false,
+ "classifications": {
+ "Admitted": 493,
+ "AdmittedGeometryWithDfmFindings": 1,
+ "AdmittedInConsumerContext": 34,
+ "DeclarationModuleRequiresConsumer": 5,
+ "ExpectedNegativeRejection": 285,
+ "ExperimentalAdmitted": 9,
+ "ExperimentalRejected": 31,
+ "LegacySerializationAdmitted": 5,
+ "LegacySerializationRejected": 324,
+ "MalformedOrUnsupportedSourceRejected": 6,
+ "MisfiledPositiveFixture": 1,
+ "RejectedAtSolveStage": 1,
+ "SourceAdmissionRejected": 81
+ },
+ "canonicalClassifications": {
+ "Admitted": 285,
+ "AdmittedInConsumerContext": 33,
+ "SourceAdmissionRejected": 9
+ }
+ },
+ "inheritedSourceVerification": {
+ "sourcesCompared": 1266,
+ "sourceHashOwnerAdmissionDifferences": [],
+ "meaning": "All inherited source hashes, structural outcomes, production owners/levels/exits and fingerprints compared to the pre-X2 collection. Any measured differences are listed explicitly; universal semantic parity is not claimed.",
+ "classificationDifferences": [],
+ "syntaxFingerprintDifferences": [
+ {
+ "source": "Speculative/RecordDerivation/valid/material-with-property-variant-v2.valid.firmfixture",
+ "differences": {
+ "syntaxFingerprint": {
+ "before": "4CC3D552D61DD8A936D8B45E292BEC219509B43BDFD3152A166A57FF55416891",
+ "after": "60DABFD429EC0B6ABAC34EE9A695DE4163D5191D2780C0D5A2D542536F0492F9"
+ }
+ },
+ "reviewedDisposition": "Spaced GPa literals are represented as quantities; speculative material/density syntax remains rejected with unchanged source, owner, admission and classification."
+ }
+ ],
+ "diagnosticFamilyDifferences": [
+ {
+ "source": "Invalid/Feature/unsupported-conditional.firmament",
+ "before": [
+ "firmament-feature-body-unsupported",
+ "firmament-feature-control-flow-unsupported",
+ "firmament-v2-parse-failed"
+ ],
+ "after": [
+ "firmament-syntax-control-flow-unsupported",
+ "firmament-v2-parse-failed"
+ ]
+ },
+ {
+ "source": "Invalid/Feature/unsupported-loop.firmament",
+ "before": [
+ "firmament-feature-body-unsupported",
+ "firmament-feature-control-flow-unsupported",
+ "firmament-v2-parse-failed"
+ ],
+ "after": [
+ "firmament-syntax-control-flow-unsupported",
+ "firmament-v2-parse-failed"
+ ]
+ },
+ {
+ "source": "Regression/FrontendX1/nested-generics.firmament",
+ "before": [
+ "firmament-template-invalid-parameter-name",
+ "firmament-v2-parse-failed"
+ ],
+ "after": [
+ "firmament-template-invalid-parameter-name",
+ "firmament-template-not-found",
+ "firmament-v2-parse-failed"
+ ],
+ "reviewedDisposition": "Structural-only X1 witness remains semantically rejected: unsupported nested Set parameter T and undeclared Product are reported separately."
+ }
+ ],
+ "diagnosticCodeDifferences": [
+ {
+ "source": "Invalid/Feature/indirect-recursion.firmament",
+ "differences": {
+ "productionDiagnosticCodes": {
+ "before": [
+ "firmament-feature-recursion:A:B:A",
+ "firmament-feature-recursion:B:A:B",
+ "firmament-v2-parse-failed"
+ ],
+ "after": [
+ "firmament-feature-recursion:A:B:A",
+ "firmament-v2-parse-failed"
+ ]
+ }
+ }
+ },
+ {
+ "source": "Invalid/Feature/unsupported-conditional.firmament",
+ "differences": {
+ "productionDiagnosticCodes": {
+ "before": [
+ "firmament-feature-body-unsupported:Broken",
+ "firmament-feature-control-flow-unsupported:if",
+ "firmament-v2-parse-failed"
+ ],
+ "after": [
+ "firmament-syntax-control-flow-unsupported",
+ "firmament-v2-parse-failed"
+ ]
+ }
+ }
+ },
+ {
+ "source": "Invalid/Feature/unsupported-loop.firmament",
+ "differences": {
+ "productionDiagnosticCodes": {
+ "before": [
+ "firmament-feature-body-unsupported:Broken",
+ "firmament-feature-control-flow-unsupported:for",
+ "firmament-v2-parse-failed"
+ ],
+ "after": [
+ "firmament-syntax-control-flow-unsupported",
+ "firmament-v2-parse-failed"
+ ]
+ }
+ }
+ },
+ {
+ "source": "Invalid/Feature/wrong-argument-type.firmament",
+ "differences": {
+ "productionDiagnosticCodes": {
+ "before": [
+ "firmament-feature-argument-type:MountHole:Center:expected-Point2:actual-Length:at-213",
+ "firmament-v2-parse-failed"
+ ],
+ "after": [
+ "firmament-feature-argument-type:MountHole:Center:expected-Point2",
+ "firmament-v2-parse-failed"
+ ]
+ }
+ }
+ },
+ {
+ "source": "Invalid/Feature/wrong-return-type.firmament",
+ "differences": {
+ "productionDiagnosticCodes": {
+ "before": [
+ "firmament-feature-return-type:Broken:expected-Hole<Counterbore>:actual-Hole<Shaft>",
+ "firmament-v2-parse-failed"
+ ],
+ "after": [
+ "firmament-feature-return-type:Broken:expected-Hole<Counterbore>",
+ "firmament-v2-parse-failed"
+ ]
+ }
+ }
+ },
+ {
+ "source": "Regression/FrontendX1/nested-generics.firmament",
+ "differences": {
+ "productionDiagnosticCodes": {
+ "before": [
+ "firmament-template-invalid-parameter-name:T: Set<Set<Point2>>",
+ "firmament-v2-parse-failed"
+ ],
+ "after": [
+ "firmament-template-invalid-parameter-name:T",
+ "firmament-template-not-found:Product",
+ "firmament-v2-parse-failed"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "sourceAdditions": [
+ {
+ "source": "Regression/FrontendX2/panel-radians.firmament",
+ "sha256": "24339C2B8CD72F8DD48A643E2E06965E34DF3F97A2293F8D1D9B7B224211DEE2",
+ "structuralSuccess": true,
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "standaloneProductionExit": 1,
+ "classification": "SourceAdmissionRejected",
+ "productionDiagnosticCodes": [
+ "firmament-panel-only-step-materialization-unsupported"
+ ],
+ "expansionOwner": "PreviouslyQualifiedX2Owner",
+ "provenanceStatus": "AvailableAuthoredAnchors_CompleteIncludeExpansionMapsPending"
+ },
+ {
+ "source": "Regression/FrontendX2/pattern-symbol-collision.firmament",
+ "sha256": "526AEB3BA9CC466B1686C484C9B45A310048ABE8F05A57A4025D5F99491FD0E3",
+ "structuralSuccess": true,
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "standaloneProductionExit": 0,
+ "classification": "Admitted",
+ "productionDiagnosticCodes": [],
+ "expansionOwner": "PreviouslyQualifiedX2Owner",
+ "provenanceStatus": "AvailableAuthoredAnchors_CompleteIncludeExpansionMapsPending"
+ },
+ {
+ "source": "Regression/FrontendX2/record-shadowing.firmament",
+ "sha256": "F2A221AF5F2AA873758CD2299215F9DA4E40CA2FD578DCC08618A4C36A9B4C9D",
+ "structuralSuccess": true,
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "standaloneProductionExit": 0,
+ "classification": "Admitted",
+ "productionDiagnosticCodes": [],
+ "expansionOwner": "UnifiedAstScopedData",
+ "provenanceStatus": "AvailableAuthoredAnchors_CompleteIncludeExpansionMapsPending"
+ },
+ {
+ "source": "Regression/FrontendX2/scoped-drill.firmament",
+ "sha256": "E9E7611398FA7A12504F3713A405D2AC931D244659D3C470B4E4A770EF2D23EB",
+ "structuralSuccess": true,
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "standaloneProductionExit": 0,
+ "classification": "Admitted",
+ "productionDiagnosticCodes": [],
+ "expansionOwner": "PreviouslyQualifiedX2Owner",
+ "provenanceStatus": "AvailableAuthoredAnchors_CompleteIncludeExpansionMapsPending"
+ },
+ {
+ "source": "Regression/FrontendX2/scoped-record-pmi.firmament",
+ "sha256": "11AF24E14B595F714939CB389E9AD82207EADEE68BE28E4035E4CC12F13FDDA2",
+ "structuralSuccess": true,
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "standaloneProductionExit": 0,
+ "classification": "Admitted",
+ "productionDiagnosticCodes": [],
+ "expansionOwner": "UnifiedAstScopedData",
+ "provenanceStatus": "AvailableAuthoredAnchors_CompleteIncludeExpansionMapsPending"
+ },
+ {
+ "source": "Regression/FrontendX2/scoped-table.firmament",
+ "sha256": "099403730BB31221D936BA23842FE5709416791A649B729C9603EB11815852D3",
+ "structuralSuccess": true,
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "standaloneProductionExit": 0,
+ "classification": "Admitted",
+ "productionDiagnosticCodes": [],
+ "expansionOwner": "UnifiedAstScopedData",
+ "provenanceStatus": "AvailableAuthoredAnchors_CompleteIncludeExpansionMapsPending"
+ },
+ {
+ "source": "Regression/FrontendX2/sibling-data.invalid.firmament",
+ "sha256": "2584C8449E345361DCBDE8D8DD1BEB1907602E3E3767A9F6B1A2C8B731F0FA0B",
+ "structuralSuccess": true,
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "standaloneProductionExit": 1,
+ "classification": "ExpectedNegativeRejection",
+ "productionDiagnosticCodes": [
+ "firmament-binding-name-not-visible:secret",
+ "firmament-v2-parse-failed"
+ ],
+ "expansionOwner": "UnifiedAstScopedData",
+ "provenanceStatus": "AvailableAuthoredAnchors_CompleteIncludeExpansionMapsPending"
+ },
+ {
+ "source": "Regression/FrontendX2/sibling-feature.invalid.firmament",
+ "sha256": "77F9E13949E472FDDE6F2229C5E55281698DDE69B71C72C5BB7F5F3182D7E26C",
+ "structuralSuccess": true,
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "standaloneProductionExit": 1,
+ "classification": "ExpectedNegativeRejection",
+ "productionDiagnosticCodes": [
+ "firmament-feature-unknown:Local",
+ "firmament-v2-parse-failed"
+ ],
+ "expansionOwner": "PreviouslyQualifiedX2Owner",
+ "provenanceStatus": "AvailableAuthoredAnchors_CompleteIncludeExpansionMapsPending"
+ },
+ {
+ "source": "Regression/FrontendX2/sibling-template.invalid.firmament",
+ "sha256": "8C50B7AE867AF1BFAEA76F6ED05FD82752ECF388350F134DF30C6891BB15CA37",
+ "structuralSuccess": true,
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "standaloneProductionExit": 1,
+ "classification": "ExpectedNegativeRejection",
+ "productionDiagnosticCodes": [
+ "firmament-template-not-found:Family",
+ "firmament-v2-parse-failed"
+ ],
+ "expansionOwner": "PreviouslyQualifiedX2Owner",
+ "provenanceStatus": "AvailableAuthoredAnchors_CompleteIncludeExpansionMapsPending"
+ },
+ {
+ "source": "Regression/FrontendX2/template-shadowing.firmament",
+ "sha256": "4B9BCF681615E0B92CACC2B803885BCF638C0629AEFECF078E582EA5DD033E14",
+ "structuralSuccess": true,
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "standaloneProductionExit": 0,
+ "classification": "Admitted",
+ "productionDiagnosticCodes": [],
+ "expansionOwner": "PreviouslyQualifiedX2Owner",
+ "provenanceStatus": "AvailableAuthoredAnchors_CompleteIncludeExpansionMapsPending"
+ }
+ ],
+ "tests": {
+ "failed": 0,
+ "passed": 5018,
+ "skipped": 0,
+ "total": 5018,
+ "executingAssemblies": 20
+ },
+ "stepComparisons": 26,
+ "stepByteIdentical": 26,
+ "geometryParity": [
+ {
+ "source": "fixtures/Canonical/Symmetry/radial-bolt-circle.firmament",
+ "sourceSha256": "19DAA47DC20CA092A6DDA1CC49AF0B74E7E016F5E4A143AA4C00B7230B81C3CE",
+ "expectedSha256": "4B4F8FD69D10E73BB403F1538C6FC13995F895E4C1C17E0605A3E4A008E5356E",
+ "actualSha256": "4B4F8FD69D10E73BB403F1538C6FC13995F895E4C1C17E0605A3E4A008E5356E",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Symmetry/partial-radial-pattern.firmament",
+ "sourceSha256": "258427029AA0882653801833109AD9FE04542C7448DE1D126291215FC016DE7D",
+ "expectedSha256": "7D708B30209B6A03010D9C647F762E453C705BC8F656882BE4F18785B2F08D87",
+ "actualSha256": "7D708B30209B6A03010D9C647F762E453C705BC8F656882BE4F18785B2F08D87",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Symmetry/mirrored-revolve.firmament",
+ "sourceSha256": "B955033028F838A3A3D7D265BD4EB04A9AAD89E83D95D5EA1C640ECB0953FA6C",
+ "expectedSha256": "C44AE2A5B6CFC978AFB24041F0B5C43A4554161FE5880FC6E2D59ADB1B7CAB4A",
+ "actualSha256": "C44AE2A5B6CFC978AFB24041F0B5C43A4554161FE5880FC6E2D59ADB1B7CAB4A",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Symmetry/mirrored-profile.firmament",
+ "sourceSha256": "1F41E7EBE426306205E01226C36410261798418C385E5E284BD0A4216CAF98BF",
+ "expectedSha256": "30D1F927A7295A5B553453BA2D6E936564140839E4497B0C5B46A1682A18F6A1",
+ "actualSha256": "30D1F927A7295A5B553453BA2D6E936564140839E4497B0C5B46A1682A18F6A1",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Symmetry/mirrored-hole.firmament",
+ "sourceSha256": "39B62FB47C0C42BDF7CD3DE7FCA2E78E785BCD693412FC052628F470F3261EB0",
+ "expectedSha256": "4A0DA2E67DA153B38DD7E6389CB329B4BBB6939FEC88541936DF705F49BE62FE",
+ "actualSha256": "4A0DA2E67DA153B38DD7E6389CB329B4BBB6939FEC88541936DF705F49BE62FE",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Symmetry/mirrored-feature-with-override.firmament",
+ "sourceSha256": "DEBDCE6974743DCBCED725B9FF6B8ED833EF64DBE69A4B94256515E6CDF24B4E",
+ "expectedSha256": "052F9FC96919130FA11D2FDE5BEF302BCBE42BA6441A61F7164D43E25EAF8FBB",
+ "actualSha256": "052F9FC96919130FA11D2FDE5BEF302BCBE42BA6441A61F7164D43E25EAF8FBB",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Regression/FrontendMigration/preferred-profile-links.firmament",
+ "sourceSha256": "41ACDC508CDB714BC0409C864708FD968BB812A83E4FD406B7AA0818670C6C4B",
+ "expectedSha256": "E43449262ECDD3DD05EFB73DB821D2E09226637EC1FB1EAF73E07821CD46AA57",
+ "actualSha256": "E43449262ECDD3DD05EFB73DB821D2E09226637EC1FB1EAF73E07821CD46AA57",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Features/Holes/through-hole.firmament",
+ "sourceSha256": "38E8188DB1BB7C75406570BBCEC9A09DAFA9D4D33A0EDEB746A6C04A973B265C",
+ "expectedSha256": "5999F127E5A1477E5825AFA656DCEB7F89241D8F85312B0E6BCD793639A0F548",
+ "actualSha256": "5999F127E5A1477E5825AFA656DCEB7F89241D8F85312B0E6BCD793639A0F548",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Templates/generic-mounting-plate.firmament",
+ "sourceSha256": "91B69697F5E777438F688FA2D1F0330FEF5C430D064FCA0A7FFF886252567C92",
+ "expectedSha256": "B0FF1D05D82135A3630C5E165C09B6C2C467B3FAF98A0825A9AF86B2E1CE76A3",
+ "actualSha256": "B0FF1D05D82135A3630C5E165C09B6C2C467B3FAF98A0825A9AF86B2E1CE76A3",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Set/pattern-feature-map.firmament",
+ "sourceSha256": "7BF1BA1E508CAE2548EC429724A895F2E50FFDAD057084F17B506C4362A34E40",
+ "expectedSha256": "08D4EA1F1336C06A380E30806C02AEE3F08535CAD1592929470EBD64B9882FC2",
+ "actualSha256": "08D4EA1F1336C06A380E30806C02AEE3F08535CAD1592929470EBD64B9882FC2",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/PMI/hole-diameter-and-datum.firmament",
+ "sourceSha256": "B105A5535F53189938CBA6C9E8644FC9D8C6683F8BB97B04167FA48C411ABBFD",
+ "expectedSha256": "9F2F24975267BF425D16A2ECDF863F4A94C0FAD172C932F9868BBB836BD46F5D",
+ "actualSha256": "9F2F24975267BF425D16A2ECDF863F4A94C0FAD172C932F9868BBB836BD46F5D",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/PMI/typed-tolerance.firmament",
+ "sourceSha256": "7C928F862D443904E87EAD137DB7D55E4D69E03A12F918F3319ECED947245EC9",
+ "expectedSha256": "098B515124D46220AAB85F6DBE1568E6B5969FEB55B537BA91AD3DDA587509A5",
+ "actualSha256": "098B515124D46220AAB85F6DBE1568E6B5969FEB55B537BA91AD3DDA587509A5",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/PMI/record-template-feature-tolerance.firmament",
+ "sourceSha256": "6F88543F7E0D544F460709EE85521620101DCB053CF3C5C7C90F05A96CA63B8D",
+ "expectedSha256": "300023D4A6CC156F9224F4937F990926523372C8BF0AB11D8C15851FA256BB18",
+ "actualSha256": "300023D4A6CC156F9224F4937F990926523372C8BF0AB11D8C15851FA256BB18",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/AssemblyInterfaces/executable-machine.firmament",
+ "sourceSha256": "9CEDEDC63C8EEF28A51F58E0E1E0D85E70104C9014C94508C44F1E9320B42F72",
+ "expectedSha256": "912FCCCDF607E0EB9437423BEA0D2E6EB74D9BEDE4D4758D9DF6BF5364C66391",
+ "actualSha256": "912FCCCDF607E0EB9437423BEA0D2E6EB74D9BEDE4D4758D9DF6BF5364C66391",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Assembly/template-block-pair.firmament",
+ "sourceSha256": "3530A14F1156C588EA5747EE65B338162AEC803243FBBB379D7C11D5265EF211",
+ "expectedSha256": "17E1DABEA787334BE13DA18E9771B69927CE46D754CA35783693C2FD76847B24",
+ "actualSha256": "17E1DABEA787334BE13DA18E9771B69927CE46D754CA35783693C2FD76847B24",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Assembly/coil-on-stem.firmament",
+ "sourceSha256": "056E6354C85B0E54AC6B4E1B79C1E9ED5CBE7A97648748F1C55923B76C85E485",
+ "expectedSha256": "9C21BE66AA885DF21DE349169C4E3D14282C2384E661372EC4034E627A5E0A1A",
+ "actualSha256": "9C21BE66AA885DF21DE349169C4E3D14282C2384E661372EC4034E627A5E0A1A",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm",
+ "sourceSha256": "10C11DD2FA4361C87D14E22D318348CE18BE0925119496184E846A603B1CA2DB",
+ "expectedSha256": "469E42D07EC1BB3FFDB88D5B0149DA50C21F39631EDC7441C2B3DCF11C41681C",
+ "actualSha256": "469E42D07EC1BB3FFDB88D5B0149DA50C21F39631EDC7441C2B3DCF11C41681C",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Sculpting/sculpt-branch-variants.firmament",
+ "sourceSha256": "CEFCA8936656C4947A5D434FD75EF6AA23B94D8A3DBB808B340DD376842B9240",
+ "expectedSha256": "DDC7B5C388058035E1B6A5FC8D5AC6701FBA3057508448EF00351312D766EF07",
+ "actualSha256": "DDC7B5C388058035E1B6A5FC8D5AC6701FBA3057508448EF00351312D766EF07",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Sculpting/sculpt-offset-region.firmament",
+ "sourceSha256": "2FB5300A60902B01916B7D2D0C72A83156E365674BA0A5F249BC5D0B7EF00EE7",
+ "expectedSha256": "EB310460850C1153C5C1813F2863DCD16595755359E8545558140BBA5F632F05",
+ "actualSha256": "EB310460850C1153C5C1813F2863DCD16595755359E8545558140BBA5F632F05",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Sculpting/sculpt-preserve-interface.firmament",
+ "sourceSha256": "C2310DAB5E3F591E1260EDA82852F53EE7842B284914D030231C15DA72D50AF4",
+ "expectedSha256": "67D5F7D6316FA53F63CEE95C08F45AFEC71E2AA2B89060A41F7F88D29319AD79",
+ "actualSha256": "67D5F7D6316FA53F63CEE95C08F45AFEC71E2AA2B89060A41F7F88D29319AD79",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Sculpting/sculpted-housing.firmament",
+ "sourceSha256": "CD6647031A073A140C93CE7DBC14C08D801B84C24F0C15816D3C446464CF1D48",
+ "expectedSha256": "27136BC65CACE501B84E6EC81BCC186F1F48262ABB2CC9F76D2208951092396F",
+ "actualSha256": "27136BC65CACE501B84E6EC81BCC186F1F48262ABB2CC9F76D2208951092396F",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Sculpting/surf-x1-freeform-housing.firmament",
+ "sourceSha256": "36CCD4855AC3F8574854AA2499CB7B5BFFE4A892852AE9DDC452714962457B38",
+ "expectedSha256": "F509AA95D3B223F876790A755DF0052900E07598A1CB8266D63EA2408EF2DB07",
+ "actualSha256": "F509AA95D3B223F876790A755DF0052900E07598A1CB8266D63EA2408EF2DB07",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Sculpting/surf-x1a-trimmed-freeform-housing.firmament",
+ "sourceSha256": "990DC7389DBCB4E330B2A316AF4946297B5CA8F13C5BD9A693497792852ABD46",
+ "expectedSha256": "5717FD937D9FE93EACF3B49190BB967028C574121AE8850F2D82EA8FC7C1B9B4",
+ "actualSha256": "5717FD937D9FE93EACF3B49190BB967028C574121AE8850F2D82EA8FC7C1B9B4",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Sculpting/surf-x2-g1-blend.firmament",
+ "sourceSha256": "1BB2EE58823B87D5CF65D227CC7163D36D92E670B43D33B8D6A9DCDB9F6288F9",
+ "expectedSha256": "73C2D486D3CED015EBEFA984C41063C54D86BF81E5A575179CA9098EBE23EF22",
+ "actualSha256": "73C2D486D3CED015EBEFA984C41063C54D86BF81E5A575179CA9098EBE23EF22",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Sculpting/surf-x2-judged-housing.firmament",
+ "sourceSha256": "96BEDCA540DD454F27DA530E9B58E3E4C3DA21F4AEE0CA5422E56372D32EDE8C",
+ "expectedSha256": "0BC71E45EE37D7B523063A59E5060610048FBE7DAC227D82CB24B4A8186FDB2A",
+ "actualSha256": "0BC71E45EE37D7B523063A59E5060610048FBE7DAC227D82CB24B4A8186FDB2A",
+ "exitCode": 0,
+ "byteIdentical": true
+ },
+ {
+ "source": "fixtures/Canonical/Sculpting/surf-x2-manual-candidate.firmament",
+ "sourceSha256": "CFBA24141D578B8049C61FA491B5978D40E873DA149373D287F5DB5488F40056",
+ "expectedSha256": "1B32DB8AFF518EAA86ADBEC212047641B48C5CCD9F57736F9C807D897AFA70B2",
+ "actualSha256": "1B32DB8AFF518EAA86ADBEC212047641B48C5CCD9F57736F9C807D897AFA70B2",
+ "exitCode": 0,
+ "byteIdentical": true
+ }
+ ],
+ "dogfood": [
+ {
+ "source": "fixtures/Regression/FrontendX2/scoped-drill.firmament",
+ "sourceSha256": "E9E7611398FA7A12504F3713A405D2AC931D244659D3C470B4E4A770EF2D23EB",
+ "validationExit": 0,
+ "buildExit": 0,
+ "artifactExists": true,
+ "expectedAccepted": true,
+ "physicalWitness": {
+ "bodyCount": 1,
+ "shellCount": 1,
+ "faceCount": 7,
+ "edgeCount": 15,
+ "vertexCount": 12,
+ "boundingBox": {
+ "min": {
+ "x": -15,
+ "y": -10,
+ "z": 0
+ },
+ "max": {
+ "x": 15,
+ "y": 10,
+ "z": 8
+ }
+ },
+ "structuralAssessment": "enclosed-manifold",
+ "lengthUnit": "mm"
+ }
+ },
+ {
+ "source": "fixtures/Regression/FrontendX2/pattern-symbol-collision.firmament",
+ "sourceSha256": "526AEB3BA9CC466B1686C484C9B45A310048ABE8F05A57A4025D5F99491FD0E3",
+ "validationExit": 0,
+ "buildExit": 0,
+ "artifactExists": true,
+ "expectedAccepted": true,
+ "physicalWitness": {
+ "bodyCount": 1,
+ "shellCount": 1,
+ "faceCount": 8,
+ "edgeCount": 18,
+ "vertexCount": 16,
+ "boundingBox": {
+ "min": {
+ "x": -20,
+ "y": -12,
+ "z": 0
+ },
+ "max": {
+ "x": 20,
+ "y": 12,
+ "z": 6
+ }
+ },
+ "structuralAssessment": "enclosed-manifold",
+ "lengthUnit": "mm"
+ }
+ },
+ {
+ "source": "fixtures/Regression/FrontendX2/sibling-feature.invalid.firmament",
+ "sourceSha256": "77F9E13949E472FDDE6F2229C5E55281698DDE69B71C72C5BB7F5F3182D7E26C",
+ "validationExit": 1,
+ "buildExit": 1,
+ "artifactExists": false,
+ "expectedAccepted": false
+ },
+ {
+ "source": "fixtures/Regression/FrontendX2/template-shadowing.firmament",
+ "sourceSha256": "4B9BCF681615E0B92CACC2B803885BCF638C0629AEFECF078E582EA5DD033E14",
+ "validationExit": 0,
+ "buildExit": 0,
+ "artifactExists": true,
+ "expectedAccepted": true,
+ "physicalWitness": {
+ "bodyCount": 1,
+ "shellCount": 1,
+ "faceCount": 6,
+ "edgeCount": 12,
+ "vertexCount": 8,
+ "boundingBox": {
+ "min": {
+ "x": -15,
+ "y": -10,
+ "z": 0
+ },
+ "max": {
+ "x": 15,
+ "y": 10,
+ "z": 6
+ }
+ },
+ "structuralAssessment": "enclosed-manifold",
+ "lengthUnit": "mm"
+ }
+ },
+ {
+ "source": "fixtures/Regression/FrontendX2/sibling-template.invalid.firmament",
+ "sourceSha256": "8C50B7AE867AF1BFAEA76F6ED05FD82752ECF388350F134DF30C6891BB15CA37",
+ "validationExit": 1,
+ "buildExit": 1,
+ "artifactExists": false,
+ "expectedAccepted": false
+ },
+ {
+ "source": "fixtures/Regression/FrontendX2/record-shadowing.firmament",
+ "sourceSha256": "F2A221AF5F2AA873758CD2299215F9DA4E40CA2FD578DCC08618A4C36A9B4C9D",
+ "validationExit": 0,
+ "buildExit": 0,
+ "artifactExists": true,
+ "expectedAccepted": true,
+ "physicalWitness": {
+ "bodyCount": 1,
+ "shellCount": 1,
+ "faceCount": 6,
+ "edgeCount": 12,
+ "vertexCount": 8,
+ "boundingBox": {
+ "min": {
+ "x": -15,
+ "y": -10,
+ "z": 0
+ },
+ "max": {
+ "x": 15,
+ "y": 10,
+ "z": 6
+ }
+ },
+ "structuralAssessment": "enclosed-manifold",
+ "lengthUnit": "mm"
+ }
+ },
+ {
+ "source": "fixtures/Regression/FrontendX2/scoped-record-pmi.firmament",
+ "sourceSha256": "11AF24E14B595F714939CB389E9AD82207EADEE68BE28E4035E4CC12F13FDDA2",
+ "validationExit": 0,
+ "buildExit": 0,
+ "artifactExists": true,
+ "expectedAccepted": true,
+ "physicalWitness": {
+ "bodyCount": 1,
+ "shellCount": 1,
+ "faceCount": 7,
+ "edgeCount": 15,
+ "vertexCount": 12,
+ "boundingBox": {
+ "min": {
+ "x": -20,
+ "y": -15,
+ "z": 0
+ },
+ "max": {
+ "x": 20,
+ "y": 15,
+ "z": 8
+ }
+ },
+ "structuralAssessment": "enclosed-manifold",
+ "lengthUnit": "mm"
+ }
+ },
+ {
+ "source": "fixtures/Regression/FrontendX2/scoped-table.firmament",
+ "sourceSha256": "099403730BB31221D936BA23842FE5709416791A649B729C9603EB11815852D3",
+ "validationExit": 0,
+ "buildExit": 0,
+ "artifactExists": true,
+ "expectedAccepted": true,
+ "physicalWitness": {
+ "bodyCount": 1,
+ "shellCount": 1,
+ "faceCount": 6,
+ "edgeCount": 12,
+ "vertexCount": 8,
+ "boundingBox": {
+ "min": {
+ "x": -15,
+ "y": -10,
+ "z": 0
+ },
+ "max": {
+ "x": 15,
+ "y": 10,
+ "z": 6
+ }
+ },
+ "structuralAssessment": "enclosed-manifold",
+ "lengthUnit": "mm"
+ }
+ },
+ {
+ "source": "fixtures/Regression/FrontendX2/sibling-data.invalid.firmament",
+ "sourceSha256": "2584C8449E345361DCBDE8D8DD1BEB1907602E3E3767A9F6B1A2C8B731F0FA0B",
+ "validationExit": 1,
+ "buildExit": 1,
+ "artifactExists": false,
+ "expectedAccepted": false
+ }
+ ],
+ "performance": [
+ {
+ "name": "small-mechanical",
+ "source": "fixtures/Regression/FrontendX2/scoped-drill.firmament",
+ "owner": "validate",
+ "commandMilliseconds": 512.0336,
+ "exitCode": 0,
+ "measurement": "End-to-end CLI including process startup; Assembly requests two retained-session compiles",
+ "phaseTimingQualification": "Not a complete lex/bind/expand/lower phase benchmark"
+ },
+ {
+ "name": "template-record",
+ "source": "fixtures/Canonical/Templates/table-driven-mounting-plate.firmament",
+ "owner": "validate",
+ "commandMilliseconds": 450.1476,
+ "exitCode": 0,
+ "measurement": "End-to-end CLI including process startup; Assembly requests two retained-session compiles",
+ "phaseTimingQualification": "Not a complete lex/bind/expand/lower phase benchmark"
+ },
+ {
+ "name": "keyed-pattern",
+ "source": "fixtures/Canonical/Set/pattern-feature-map.firmament",
+ "owner": "validate",
+ "commandMilliseconds": 546.2391,
+ "exitCode": 0,
+ "measurement": "End-to-end CLI including process startup; Assembly requests two retained-session compiles",
+ "phaseTimingQualification": "Not a complete lex/bind/expand/lower phase benchmark"
+ },
+ {
+ "name": "guitar",
+ "source": "fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm",
+ "owner": "assembly",
+ "commandMilliseconds": 10384.4752,
+ "exitCode": 0,
+ "measurement": "End-to-end CLI including process startup; Assembly requests two retained-session compiles",
+ "phaseTimingQualification": "Not a complete lex/bind/expand/lower phase benchmark"
+ },
+ {
+ "name": "assembly",
+ "source": "fixtures/Regression/FrontendX1/assembly-modern-contract.firmament",
+ "owner": "assembly",
+ "commandMilliseconds": 595.0742,
+ "exitCode": 0,
+ "measurement": "End-to-end CLI including process startup; Assembly requests two retained-session compiles",
+ "phaseTimingQualification": "Not a complete lex/bind/expand/lower phase benchmark"
+ },
+ {
+ "name": "house",
+ "source": "fixtures/Canonical/Scene/WarmModernHouse/house.firmament",
+ "owner": "scene",
+ "commandMilliseconds": 2274.1356,
+ "exitCode": 0,
+ "measurement": "End-to-end CLI including process startup; Assembly requests two retained-session compiles",
+ "phaseTimingQualification": "Not a complete lex/bind/expand/lower phase benchmark"
+ }
+ ],
+ "provenanceQualification": "Scoped Record/scalar tolerance and explicit AP242 PMI retain authored requirement anchors; module/include and complete generated-source maps remain unqualified.",
+ "runtimeSnapshot": {
+ "remainingHosts": 0,
+ "freePhysicalMemoryGiB": 13.19,
+ "freeDiskGiB": 91.82,
+ "qualification": "Post-run snapshot; no long-duration soak claim",
+ "taskOwnedHostsReaped": 0,
+ "measuredAtUtc": "2026-10-15T16:42:08.7728994Z"
+ },
+ "surfaceCompatibilityWitness": {
+ "source": "fixtures/Regression/FrontendX2/panel-radians.firmament",
+ "semanticAdmission": "Panel AIR admitted and sampled by FirmamentFrontendX2Tests.ExistingPanelRadianAdmissionPreservesSurfaceCoordinates",
+ "startPointMm": [
+ "10*cos(0.25)",
+ "10*sin(0.25)",
+ 0
+ ],
+ "endPointMm": [
+ "10*cos(0.75)",
+ "10*sin(0.75)",
+ 5
+ ],
+ "solidBuild": "Explicit existing panel-only STEP materialization rejection"
+ },
+ "retainedCompilations": {
+ "guitar": [
+ {
+ "index": 0,
+ "elapsedMilliseconds": 9330.4041,
+ "success": true,
+ "reusedDefinitions": 0,
+ "rebuiltDefinitions": 56,
+ "domainPhaseMeasurements": {
+ "parseMilliseconds": 1218.6151,
+ "bindMilliseconds": 3.9119,
+ "mateValidationMilliseconds": 0.7047,
+ "placementMilliseconds": 2.2181,
+ "dimensionalGraphMilliseconds": 0.2918,
+ "toleranceAnalysisMilliseconds": 0.1929,
+ "definitionMaterializationMilliseconds": 6274.746,
+ "geometryExecutionMilliseconds": 1804.9446,
+ "routeBindingMilliseconds": 12.6791
+ }
+ },
+ {
+ "index": 1,
+ "elapsedMilliseconds": 106.8128,
+ "success": true,
+ "reusedDefinitions": 56,
+ "rebuiltDefinitions": 0,
+ "domainPhaseMeasurements": {
+ "parseMilliseconds": 62.2165,
+ "bindMilliseconds": 1.066,
+ "mateValidationMilliseconds": 0.1963,
+ "placementMilliseconds": 0.9371,
+ "dimensionalGraphMilliseconds": 0.0885,
+ "toleranceAnalysisMilliseconds": 0.0562,
+ "definitionMaterializationMilliseconds": 3.3194,
+ "geometryExecutionMilliseconds": 28.1709,
+ "routeBindingMilliseconds": 3.3562
+ }
+ }
+ ],
+ "assembly": [
+ {
+ "index": 0,
+ "elapsedMilliseconds": 447.1969,
+ "success": true,
+ "reusedDefinitions": 0,
+ "rebuiltDefinitions": 1,
+ "domainPhaseMeasurements": {
+ "parseMilliseconds": 58.9015,
+ "bindMilliseconds": 8.2055,
+ "mateValidationMilliseconds": 4.5347,
+ "placementMilliseconds": 11.8434,
+ "dimensionalGraphMilliseconds": 1.4081,
+ "toleranceAnalysisMilliseconds": 1.4955,
+ "definitionMaterializationMilliseconds": 323.5362,
+ "geometryExecutionMilliseconds": 24.4896,
+ "routeBindingMilliseconds": 0.8273
+ }
+ },
+ {
+ "index": 1,
+ "elapsedMilliseconds": 2.5054,
+ "success": true,
+ "reusedDefinitions": 1,
+ "rebuiltDefinitions": 0,
+ "domainPhaseMeasurements": {
+ "parseMilliseconds": 1.3847,
+ "bindMilliseconds": 0.0772,
+ "mateValidationMilliseconds": 0.053,
+ "placementMilliseconds": 0.1376,
+ "dimensionalGraphMilliseconds": 0.0182,
+ "toleranceAnalysisMilliseconds": 0.006,
+ "definitionMaterializationMilliseconds": 0.1733,
+ "geometryExecutionMilliseconds": 0.2286,
+ "routeBindingMilliseconds": 0.0043
+ }
+ }
+ ]
+ },
+ "buildWarnings": 19,
+ "focusedTests": 117,
+ "templateContinuation": {
+ "status": "ProductionAstLexicalLookup",
+ "priorSourceCount": 1271,
+ "commonSourcesCompared": 1270,
+ "sourceChanges": [
+ {
+ "source": "Speculative/RecordDerivation/valid/material-with-property-variant-v2.valid.firmfixture",
+ "differences": {
+ "syntaxFingerprint": {
+ "before": "4CC3D552D61DD8A936D8B45E292BEC219509B43BDFD3152A166A57FF55416891",
+ "after": "60DABFD429EC0B6ABAC34EE9A695DE4163D5191D2780C0D5A2D542536F0492F9"
+ }
+ },
+ "reviewedDisposition": "Spaced GPa literals are represented as quantities; speculative material/density syntax remains rejected with unchanged source, owner, admission and classification."
+ }
+ ],
+ "diagnosticCodeChanges": [
+ {
+ "source": "Regression/FrontendX1/nested-generics.firmament",
+ "differences": {
+ "productionDiagnosticCodes": {
+ "before": [
+ "firmament-template-invalid-parameter-name:T: Set<Set<Point2>>",
+ "firmament-v2-parse-failed"
+ ],
+ "after": [
+ "firmament-template-invalid-parameter-name:T",
+ "firmament-template-not-found:Product",
+ "firmament-v2-parse-failed"
+ ]
+ }
+ }
+ }
+ ],
+ "promotedWitness": {
+ "before": "fixtures/Regression/FrontendX2/template-shadowing.pending.firmament",
+ "after": "fixtures/Regression/FrontendX2/template-shadowing.firmament",
+ "qualification": "Normal validate/build admit the local 30mm family; component tests compare byte-identical concrete STEP."
+ },
+ "nextBlocker": {
+ "source": "fixtures/Regression/FrontendX2/record-shadowing.pending.firmament",
+ "observedCode": "firmament-template-record-missing-field:outerSpec:thickness",
+ "cause": "The global Record catalog applies the local Spec schema to the unrelated outerSpec declaration.",
+ "status": "Closed by dataContinuation; historical reproduction retained."
+ },
+ "requiredFastLane": {
+ "failed": 0,
+ "passed": 1068,
+ "skipped": 0,
+ "total": 1068,
+ "executingAssemblies": 1
+ },
+ "hostCompatibility": "Document exports and existing single-Model module containers; qualified Construct capability names, lowercase analysis headers and parameterized force quantities have explicit AST productions."
+ },
+ "implementationSourceAndBinaryHashes": [
+ {
+ "path": "Aetheris.CLI.Tests/FirmamentFrontendX2CliTests.cs",
+ "sha256": "29B1C274E153A8A7DB2E3BC5DC67795A59A80A22119FC087FB78B19C04C9A3CE"
+ },
+ {
+ "path": "Aetheris.CLI/CliRunner.cs",
+ "sha256": "6CBA72D0D3DB19815D47D659C3B12ECC9C059F0870F5CB7F3FB9879E87A3C8DC"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament.Tests/FirmamentCompileTimeValueBindingTests.cs",
+ "sha256": "6E48CC163D6DC3CB32ACD9022A403CF098B808E4D15C838576B52B414B4C0CF9"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX2Tests.cs",
+ "sha256": "DBEE665D7A2142965BDC912516D08B1CEBE4B9F9BE43FB5E0489B1ACC8DC295D"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament.Tests/FirmamentScopedDataBindingTests.cs",
+ "sha256": "79CFE314A4BC0D89FE1DA45B7B47A852117B01D216E0A1AB5DA0A7E28E9BE375"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament.Tests/FirmamentV2FeatureFunctionTests.cs",
+ "sha256": "8182F99414C6F49E4DA13A944BED93B237AAC510D5FD366FA387D8F499B3E20F"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament.Tests/FunctionalPickupTests.cs",
+ "sha256": "3451F0CDC63095771661B1CE8DCD1F42E9AE0A1000F8D4B592FF11DAE7BB6CBB"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/Assembly/AssemblyFrameAuthoring.cs",
+ "sha256": "0C4887F2DAF89B771A357B56D75387B92C48FC2CC43A7EFFA5905F009236BA3D"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs",
+ "sha256": "CFE2D863BCA611220335E57D7C488BBAB085FF5E79689D285DE2F6E233EA278D"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs",
+ "sha256": "423ECE1CB4B29B2AEFACE30B1F0AEB38C235BB018E4CE4B1C7E8F19B75199D42"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs",
+ "sha256": "967F0ED04B6DC1EC09F889978281AEC9BA3DB707C795985EFD8E4B7BC96E497C"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs",
+ "sha256": "A414D12C0F63505D31AF10F150A68EDCEE33FF0F546F4245EBAD369BA35C9C94"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs",
+ "sha256": "B2908B4F63F027285565321FF65725632EDAF69C4285945F6E1DD874FCF7D3B8"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs",
+ "sha256": "D90FE887D905490C804304A6ED396D6A274DA1A2E7AD60FB247D105D4D40C06D"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs",
+ "sha256": "C0302C5C05CA326BDB7D99BCD1651D815FCF03EE7E02424635F710667A05C1A0"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs",
+ "sha256": "77CA511CE2A8DA7A78CF14882B27C0FD86BE51E4B144BF88BB5E023862CB9885"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs",
+ "sha256": "9933973C206F62061E393BE2C52A59CDCBA92EDF8A780F6DF04D235503A70A0B"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs",
+ "sha256": "114B4F82ACC99843B1EC0C3D08EE9B61EF0FE369CB556CE3F008B48C2AB69940"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs",
+ "sha256": "B8F126AC0097F3299AB930FB8359CAEA4F960AE5ED7E6D249F59503DFAB54DC5"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/LinearFeatureAuthoring.cs",
+ "sha256": "B65BF34783463FA913DA6C5FFB66D8F93CC90CC70879FDF716AF68AEEA0EEDBB"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentBindingScope.cs",
+ "sha256": "BA6B1119B6C3D3F35D0AE5F566C0AE30C489093E3E56CFA9BB1BAF62843E034F"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs",
+ "sha256": "3911D82ECADC192B671869B055104C1ADFB193BB408C0B40CED09D1D009F70B2"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericEvaluation.cs",
+ "sha256": "4291026F543ECA6C0B2A06FEEDF2D2F6A2B48DFEE9EA4ADB9CA75AEE32BCEC8C"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs",
+ "sha256": "2ADDDD88A6CC673842E9904EA696C7100507BFADDEB4466388F15504E5A7BEB6"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxOrigins.cs",
+ "sha256": "A74A7D12D02FB94D73F14D70278D0AFAADD5A06229CE2CD37915AF2263459EE3"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs",
+ "sha256": "2C9E108D51A190BF23B9FA7BB7C5F5B323B56FBC1B8696C2E3D37132B8244688"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxRewriter.cs",
+ "sha256": "DD4B7F759B12E92CBD387FE9BA796764DA9B2B8087F61BCFDCC6DEE0E05DDD40"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxTraversal.cs",
+ "sha256": "5035A669E603A131446246B39BCA0C52FE11C40756EAE45CD7AF9ECD678060EF"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs",
+ "sha256": "72541944ADF221D5C0DD29A6AAB0685B0C1A500E8AAEC4DE3ECE48672FB3707B"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxWriter.cs",
+ "sha256": "9A68F9156EAB06FF1A9BD05CB8D10F362218D2562F8D8214DB183DB7E709089E"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentTemplateSyntax.cs",
+ "sha256": "1988ED3074AABAA71FC23743C0469284A22C902904CCAC865A7C514D2593EC88"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/Garment/GarmentAuthoring.cs",
+ "sha256": "19EEAED5EF83B97A6C13A5A18820DF6F05C00D9CBDC76755F23649188CE0D82B"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/Garment/GarmentFigureAuthoring.cs",
+ "sha256": "0313064C0692C5B2D5F4B1A727D76F911DEA4E77F5237AA56261EBF2F478C69C"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/Humanoid/HumanoidPoseAuthoring.cs",
+ "sha256": "B08994903676E07C947A13412AB17C7C6592571040228B353824C9CA351E5255"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs",
+ "sha256": "D582F2B969B8DFA9A1F5DFFD325AB522C7A90477EC0850B01D39C67300F361E9"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/Scene/SceneAuthoring.cs",
+ "sha256": "EB776ADE721646AD4AC5BA032B3C8E9779780968368B5A99AD89E22E8CF34436"
+ },
+ {
+ "path": "Aetheris.Server.Tests/PaperclipDemoIntegrationTests.cs",
+ "sha256": "736E7BCA4C5908E02297EFD90DB1B03AD7DD268662C0EDC9C68754B147CD6CEA"
+ },
+ {
+ "path": "Aetheris.Server/Api/PaperclipDemoEndpoints.cs",
+ "sha256": "EC3BF6E850820E76CFA36484563365FB606D53CC94E6B4C0966D6D1D153A411C"
+ },
+ {
+ "path": "Aetheris.CLI/bin/Release/net10.0/aetheris.dll",
+ "sha256": "77B87FB5A8F77C8511DCC8F5F1596CC6277263EBF51059A6B68FA29E80FD1D23"
+ },
+ {
+ "path": "Aetheris.Kernel.Firmament/bin/Release/net10.0/Aetheris.Kernel.Firmament.dll",
+ "sha256": "A900E68BB8483E42CAE1EC350E3219D93234D713910118C613CD1320C486A197"
+ }
+ ],
+ "dataContinuation": {
+ "status": "ProductionAstScopedData",
+ "requestedPassVerdict": "Success",
+ "commonSourcesCompared": 1272,
+ "sourceDeltas": [],
+ "classificationOrDiagnosticDeltas": [],
+ "reviewedDispositions": [
+ {
+ "kind": "PromotedReproduction",
+ "before": {
+ "source": "Regression/FrontendX2/record-shadowing.pending.firmament",
+ "sha256": "513CA4D8DF88F1BACD17A30E1CE9FA8A5D9FFE0BEDCD34259253214CF446BE78",
+ "structuralSuccess": true,
+ "syntaxFingerprint": "4AD527B468B427A2DA148C373924C29A4D956B1B51556D51995312F44921BD76",
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "productionExit": 1,
+ "classification": "SourceAdmissionRejected",
+ "standaloneProductionExit": 1,
+ "productionDiagnosticCodes": [
+ "firmament-template-record-missing-field:outerSpec:thickness",
+ "firmament-v2-parse-failed"
+ ]
+ },
+ "after": {
+ "source": "Regression/FrontendX2/record-shadowing.firmament",
+ "sha256": "F2A221AF5F2AA873758CD2299215F9DA4E40CA2FD578DCC08618A4C36A9B4C9D",
+ "structuralSuccess": true,
+ "syntaxFingerprint": "4AD527B468B427A2DA148C373924C29A4D956B1B51556D51995312F44921BD76",
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "classification": "Admitted",
+ "productionDiagnosticCodes": [],
+ "standaloneProductionExit": 0
+ },
+ "reason": "The preserved Spec schema-capture program now binds the outer value to the outer schema and the local product to the local schema. Only its explanatory comment changed; component/native STEP equals the concrete 30 x 20 x 6 mm product."
+ },
+ {
+ "kind": "AddedWitness",
+ "after": {
+ "source": "Regression/FrontendX2/scoped-record-pmi.firmament",
+ "sha256": "11AF24E14B595F714939CB389E9AD82207EADEE68BE28E4035E4CC12F13FDDA2",
+ "structuralSuccess": true,
+ "syntaxFingerprint": "FD4B777C595CE9E1C07EEC7F46FAAD7D0EDA3993C01F5991F4FFB42FE62C83EE",
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "classification": "Admitted",
+ "productionDiagnosticCodes": [],
+ "standaloneProductionExit": 0
+ },
+ "reason": "Positive: same-named outer/local Record and Static declarations retain the local 8mm tolerance, through Template/Feature into AP242 plus 0.10/minus 0.05 and authored requirement span."
+ },
+ {
+ "kind": "AddedWitness",
+ "after": {
+ "source": "Regression/FrontendX2/scoped-table.firmament",
+ "sha256": "099403730BB31221D936BA23842FE5709416791A649B729C9603EB11815852D3",
+ "structuralSuccess": true,
+ "syntaxFingerprint": "299FC325A081430B7066C600ED094759AB24D2F2193A35699406ABE4505FD4C0",
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "classification": "Admitted",
+ "productionDiagnosticCodes": [],
+ "standaloneProductionExit": 0
+ },
+ "reason": "Positive: root and local schema/Table/value names bind separately; the checked local row produces 30 x 20 x 6 mm geometry."
+ },
+ {
+ "kind": "AddedWitness",
+ "after": {
+ "source": "Regression/FrontendX2/sibling-data.invalid.firmament",
+ "sha256": "2584C8449E345361DCBDE8D8DD1BEB1907602E3E3767A9F6B1A2C8B731F0FA0B",
+ "structuralSuccess": true,
+ "syntaxFingerprint": "948272C43EAD3460A73D594811FF2644AFBBAD77F5C3E68A33FDFEFD845472B3",
+ "owner": "ValidateDomainDispatch",
+ "productionLevel": "OwnerReported",
+ "classification": "ExpectedNegativeRejection",
+ "productionDiagnosticCodes": [
+ "firmament-binding-name-not-visible:secret",
+ "firmament-v2-parse-failed"
+ ],
+ "standaloneProductionExit": 1
+ },
+ "reason": "Negative: a sibling-private scalar cannot leak into a consumer. Both validate/build reject at the authored reference and no STEP is produced."
+ }
+ ],
+ "promotedWitness": {
+ "before": "fixtures/Regression/FrontendX2/record-shadowing.pending.firmament",
+ "after": "fixtures/Regression/FrontendX2/record-shadowing.firmament"
+ },
+ "remainingX2": "Complete module/include original-source provenance; remaining collection, expansion and domain source adapters.",
+ "sourceBoundary": "AST-resolved symbol identities; only collisions lower private identifiers at the existing source boundary. No regex reference substitution or new expression engine.",
+ "fastLane": {
+ "failed": 0,
+ "passed": 1068,
+ "skipped": 0,
+ "total": 1068,
+ "executingAssemblies": 1
+ },
+ "focusedCliTests": {
+ "failed": 0,
+ "passed": 4,
+ "skipped": 0,
+ "total": 4,
+ "executingAssemblies": 1
+ }
+ },
+ "documentationTests": 13
+}
diff --git a/docs/release/FIRMAMENT-FRONTEND-X2.md b/docs/release/FIRMAMENT-FRONTEND-X2.md
new file mode 100644
index 00000000..9bf68e60
--- /dev/null
+++ b/docs/release/FIRMAMENT-FRONTEND-X2.md
@@ -0,0 +1,492 @@
+# Firmament frontend X2 — production semantic migration
+
+Date: 2026-10-15. Base: `e6468b03c6bd4a6b2bfd40329de1381c16968512`.
+
+**Verdict: Meaningful progression. X2 is not Accepted.**
+
+Latest continuation: Record, Static and Table names now bind through lexical
+production AST identities and a shared typed data catalog. The Spec schema-capture
+witness builds its intended 30 × 20 × 6 mm geometry. Final gates: **5,018 tests**,
+**1,276 classified sources**, **26/26 byte-identical STEP baselines**. Complete
+include-file provenance and remaining collection/domain body readers remain X2 work.
+
+## Baseline and inherited guarantees
+
+The X1 closeout, its complete evidence ledger, earlier handoff, October authoring
+audit, language audits/register and current public authoring guide were checked
+against the implementation. A fresh owner-aware production sweep reproduced
+the X1 baseline before edits: **1,266 sources**, **327/327 canonical sources
+structurally parsed**, 902 total structural successes, 504 standalone owner
+admissions, and zero unresolved classification mismatches. The source inventory
+hash remained `7CC4BFD666557BFA58F182FEF8042BFF51B576244A2E85C1CF09EF4D45B25D41`.
+X1's 4,943 passing tests and 26 STEP hashes are inherited evidence, not newly
+measured X2 results. Fresh qualification is recorded separately below.
+
+The nine explicit canonical domain rejections remain inherited boundaries:
+four figure-dependent Garments, one profile identity collision and four
+SurfaceCoil material-owner combinations. Analysis compilation is distinct from
+solving. Deliberately invalid, experimental, legacy serialization and consuming
+modules retain their dispositions.
+
+## Architecture and migrated owners
+
+The existing shared lexer and recursive-descent parser remain the source grammar.
+AST metadata retains explicit parameter-list presence and authored argument-value
+boundaries so admission and serialization cannot lose those distinctions.
+No shadow compiler, whole-document dispatch mechanism, alternate engineering IR
+or geometry operation was introduced.
+
+Feature definitions, parameters, local derivations, construction and terminal
+returns now bind AST nodes. `FirmamentBindingScope` resolves Features through
+finite lexical parents, using a separate callable namespace from construction
+types. A Model-local Feature can shadow a document Feature; sibling declarations
+cannot capture a call. Duplicate definitions in one scope reject. Delegated
+calls resolve in the definition's scope. Unused definitions still have their
+return kind/delegation and dependency cycles checked.
+
+`FirmamentSyntaxSubstitution` transforms references and member paths. Declaration
+names, labels and strings are separate syntax roles. Explicit private-construction
+renaming replaces Feature's regex alpha-renaming. Nested parameters and mapping
+binders shadow enclosing substitutions. Defaults bind typed dependencies;
+cycles and excessive depth reject. Existing scalar/Record transport continues
+to carry tolerances and explicit PMI receipts through the existing typed owner.
+Invocation metadata retains both the original whole-Record argument and its
+checked flattened member bindings, including nested Record tolerance receipts.
+
+Feature expansion produces concrete AST declarations and a retained AST result.
+The only production Feature implementation uses these nodes. The old regex
+definition/call/return/local readers and private character-based arithmetic
+parser were removed. Existing consumers still take serialized declarations:
+`FirmamentSyntaxWriter` is an explicit adapter boundary, not a second parser or
+evaluator. Subsequent legacy expansion stages still prevent handing one bound
+document directly to every lowerer. This is a remaining X2 gap, not full pipeline
+acceptance merely because an AST result exists.
+
+Finite bounds reject rather than truncate: 64 nested calls/default dependencies,
+4,096 Feature invocations, 65,536 generated declarations and 4 MiB of output.
+Output is charged during expansion, before accumulating another large result.
+No mutable compiler-global environment or specialization cache was added.
+
+## Expressions and values
+
+`FirmamentNumericEvaluation` evaluates the shared expression AST. It replaces
+both the former Feature arithmetic parser and the duplicate syntax-field numeric
+interpreter. Scalar dependency binding and Concept arithmetic use its operator
+type policy; scalar computation delegates numeric operations to that service.
+Panel arc radians retain their original numeric unit without degree conversion.
+Mixed degree/radian arithmetic is not silently admitted. Existing Assembly
+frames/ports, Scene dimensions, Garment dimensions, bounded
+Concept point math, linear features and relevant profile materializer adapters
+call the same service instead of reaching into Feature expansion.
+
+Lengths and angles remain distinct; invalid dimensional products, mismatched
+addition, unknown references, division by zero and nonfinite results reject.
+Existing compile-time tolerance semantics remain: nominal arithmetic does not
+implicitly propagate a tolerance. Explicit requirements and PMI retain their
+own existing authority. This is numeric consolidation, not completion of typed
+Records, Sets, Tables, enum values, selectors and structural predicates in one
+scoped value environment.
+
+## Patterns and finite feature Templates
+
+Keyed Set and record-array Pattern headers and mapping bodies now use AST nodes.
+The existing finite feature-Template output form specializes a checked declaration
+through AST member substitution. Assembly/Scene occurrence Patterns also consume
+AST headers and mapping bodies, including the legitimate form where one item
+maps to several occurrences. Existing generated wrappers, keys, source order,
+instance identities and per-family limits are preserved.
+
+The historical semantic point Pattern adapter now substitutes expression nodes
+instead of replacing every occurrence of the item spelling in its body. A binder
+named `Diameter` cannot overwrite the `Diameter:` label. The new keyed Pattern
+witness deliberately gives the binder and Hole declaration the same name and
+compares real STEP output with a differently named binder/declaration.
+
+This does not complete Pattern consolidation: Set/array collection interpretation,
+point recipes, radial/mirror/linear expansion and several shared source adapters
+remain. No new Pattern spelling or unsupported nesting was added.
+
+## Includes, provenance and the next concrete blocker
+
+Feature receipts distinguish definition and invocation, retain the lexical scope
+and ordered delegation chain, and expose their actual available spans. Retained
+nodes are matched to authored AST locations by lexical declaration/mapping
+ownership and occurrence identity; offsets are not reused after spelling changes.
+Generated nodes without an authored counterpart remain explicitly unmapped.
+Virtual input locations carry a limitation note rather than claiming to be
+original include-file positions.
+
+The product Template registry has now moved to the production AST. Declaration
+and application recognition, parameter lists/default spans, forward registration,
+nearest-scope lookup and cycle dependencies use structured nodes. A Model-local
+Template shadows its document counterpart; sibling-private Templates reject.
+Nested specialization resolves from the definition scope. Same-scope duplicates,
+unknown applications and ignored header/placement clauses reject. Scope receipts
+are additive debug metadata. Original unambiguous specialization identities are
+retained; newly admitted same-named lexical families receive distinct identities.
+
+The former pending
+[`template-shadowing.firmament`](../../fixtures/Regression/FrontendX2/template-shadowing.firmament)
+is now an admitted positive: the local default produces a 30 × 20 × 6 mm body,
+and its STEP matches concrete source. A nested definition-scope witness matches
+the 10 mm outer family despite a 30 mm caller-local family. The sibling-negative
+fixture retains the authored application span and actionable message in CLI JSON.
+
+Host discovery/invocation uses the same lexical index. Document exports and the
+established single-Model module container remain admitted; private definitions
+from sibling Models are never pooled. Qualification exposed two genuine structural
+productions used by host clients outside the fixture inventory: qualified
+`Construct Company.Capability name` and lowercase `analysis Kind name` headers.
+They now have explicit productions in the existing recursive-descent parser.
+Parameterized force quantities such as `AppliedForce N` are also represented
+before specialization; unit/capability meaning remains with the existing owner.
+The file-build path also avoids re-expanding serialized V1 data as V2: the existing
+NotRecognized boundary delegates to the original explicit version-1 reader and
+retains its version and in-memory compatibility checks.
+
+The server Paperclip demo previously passed the X0 example facade, which includes
+a default application, into host specialization. After removing the Template
+definition, that left a dangling default application that old discovery skipped.
+The stricter binder rejects it. The endpoint now uses the existing declaration-only
+library API; its real HTTP/STEP integration test remains the acceptance path.
+Malformed Template prefixes cannot disappear if syntax recovery fails to produce
+a declaration node: the existing lexer/token stream retains the failed prefix.
+
+Complete provenance and value scoping still have concrete blockers.
+`AssemblyM0Parser.LoadProjectSource` and `LoadSourceGraph` return concatenated
+strings without per-declaration file identity. Template bodies still cross the
+existing Match/PMI and domain lowerers as source slices. No claim is made
+that the Template body substitution or every domain reader has migrated.
+
+The Spec schema-capture witness is now repaired:
+[`record-shadowing.firmament`](../../fixtures/Regression/FrontendX2/record-shadowing.firmament)
+is an admitted positive whose local 30 × 20 × 6 mm product matches concrete STEP.
+The outer Spec(width) and local Spec(width, thickness) have distinct nominal type
+identities. The outer value is checked against its own schema and cannot be
+passed as an instance of the local type merely because their names match.
+
+`FirmamentDataBinding` registers Record/Enum types and Static/Table values in
+lexical AST scopes. Parameters, mapping binders and type parameters protect their
+own namespaces. It binds type/value references before typed evaluation. Existing
+unique spellings are preserved; collisions lower to deterministic private symbol
+identities only at the established source boundary. This is AST identifier
+lowering, not a new source-text macro, expression engine or parser route. Strings,
+field labels, member labels and Table key fields are never renamed as references.
+Explain metadata exposes original names, scopes, identities and available spans.
+
+Record schemas, Static Record literals, checked with derivation, Table rows and
+typed aliases now use one AST-derived catalog. `CanonicalStaticAuthoring` consumes
+that catalog rather than reinterpreting another set of Record/Table declarations.
+Their fields and scalar leaves use the established typed dependency graph.
+Specialized data is admitted before Feature arguments. Duplicate data declarations,
+private sibling references, nominal mismatches, cycles, unknown fields and ignored
+headers reject. Typed tolerances retain their explicit PMI projection and authored
+requirement locations; toleranced Table/collection cells still reject.
+
+Host discovery selects visible schemas from its existing export scope, preserving
+document and single-Model container compatibility. Public Record/type names remain
+authored names; nested host Record markers resolve the selected nominal schema.
+Unambiguous existing engineering identities remain unchanged.
+
+The next X2 boundary is complete module/original-file provenance and the remaining
+collection, expansion and domain source adapters. Included documents are still
+concatenated by the Assembly source loader. Record/data lexical lookup no longer
+requires that handoff to be flattened into an unqualified registry, but this pass
+does not claim that all original include locations or domain bodies have migrated.
+
+## Domain reader inventory
+
+Classification is per source owner, not a claim that a structural gate migrates
+all downstream semantics.
+
+| Family / current owner | Current classification | Remaining source responsibility |
+| --- | --- | --- |
+| Feature / `FirmamentV2FeatureExpansion` | AST-owned binding/expansion with explicit serialization boundary | Downstream consumers still require text; complete per-node include/Template maps remain. |
+| Product Template / `FirmamentTemplateSyntax`, `FirmamentV2TemplateExpansion` | AST-owned declarations, parameters, lexical lookup and dependency edges | Body substitution, Match/Require/PMI and domain transport remain explicit adapters; typed data uses the shared AST catalog. |
+| Record/Static/Table / `FirmamentDataBinding`, shared `ReadDataCatalog` | AST lexical identities and one checked data catalog | Existing downstream source transport remains; Set/array interpretation and complete module maps are separate. |
+| Gear / `GearAuthoring.Bind` | AST-owned source fields | Generic product specialization remains upstream. |
+| Mechanical / unified binders | AST admission with bounded semantic adapters | Profile, Compose, selection/PMI and compatibility readers remain in parts of the lowerer chain. |
+| Panel, Plateau, Revolve, Loft/SectionChain | AST admission with bounded semantic adapters | Profile resolution, preprocessing and specialized source projections remain. |
+| Assembly contracts / `AssemblyInterfaceSyntax` | AST-owned migrated contracts/mates | Existing engineering placement and relationship lowerers preserved. |
+| Assembly tree / `AssemblyM0Parser` | Legacy source reader still authoritative after structural admission | Includes, product tree, parts, frames, appearances, ports and source specialization. |
+| Scene / `SceneAuthoring.Reader` | Legacy source reader still authoritative | Room/opening/camera/placement binding and module interpretation; numeric service and occurrence mapping now shared. |
+| SheetMetal / SheetMetalFirmament, AuthoredSheetMetalCompiler | Legacy source reader still authoritative after structural admission | Manufacturing source fields and expansion remain to migrate. |
+| WireForm / `WireFormAuthoring` | Legacy source reader still authoritative | Field/route interpretation and source-based specialization remain. |
+| Drawing / `FirmamentDrawingCompiler` | Legacy source reader still authoritative | Drawing Templates, metadata and drawing fields remain independent source readers. |
+| Analysis / `FirmamentAnalysisCompiler` | Legacy source reader still authoritative | Analysis fields, native/import references and geometry adapters remain; solving is separate. |
+| Garment / `GarmentAuthoring` | Legacy block reader after structural admission | Garment fields and figure/posing/surface source adapters; Feature specialization now shares AST owner. |
+| Sculpting / Aetheris.Surfacing.SculptingAuthoring | Existing source adapter retained | Source interpretation and artifact capability remain separate from this migrated Feature family. |
+| STEP/AP242, JSON serialization | Intentional external/import-format parser | Not Firmament V2 source semantics; not candidates for deleting external format readers. |
+
+A parity run caught a concrete transport failure: adding spaces to a guitar
+Panel specialization changed its Assembly definition identity and STEP ordering,
+even though the Cartesian-coordinate multiset matched. The serializer now retains
+authored argument-value spans and preserves application punctuation/trivia while
+emitting the bound AST values. A focused source/AST test and the original guitar
+STEP hash qualify that repair. No numerical tolerance or reordered-geometry excuse
+was used to waive byte identity. The removal criterion for this transport adapter
+is the typed module/specialization handoff described above, with explicit stable
+identity compatibility; a general source rewrite is not the replacement.
+
+Feature definition/invocation headers are closed, including empty generic/parameter
+lists, quoted type names, named return constructors and unsupported invocation
+placements. An otherwise buildable drilled plate rejects when `on XZ` is added
+to its named Feature invocation. Value parameters cannot capture type/variant
+names such as `Profile`, `Boss` or `Shaft`.
+
+No obsolete Feature implementation remains as a competing authority. Unmigrated
+Template body/value and domain readers are explicitly outstanding, not justified as
+permanent alternate semantic frontends.
+
+## Diagnostics, tooling and compatibility
+
+Feature binding preserves the established blocking `fatal` severity, stable
+diagnostic families, human messages, stage and available authored locations.
+Unsupported general control flow now comes from the shared structural parser's
+located diagnostic. Two component expectations were updated for that earlier
+owner. A whitespace-only generated-source assertion was replaced with an AST
+result assertion while retaining its real build/private-identity checks.
+
+`validate --json --explain` exposes Feature ownership, definitions, actual bound
+invocations, scopes, expansion counts and definition/use receipts. It explicitly
+also exposes product Template owner, bound arguments and definition/application
+scopes. Data metadata adds original names, lexical scopes and lowered identities
+under `dataOwner` / `dataBindings`, while labeling remaining body/provenance adapters. Ordinary JSON retains
+its existing report shape. `inspect --json` adds the same Feature receipt fields.
+Normal validate/build still use the same production admission, not explain data.
+No Helios parser or validator was introduced. Existing language-service compiler
+diagnostics/navigation tests are part of the full gate; no fresh browser session
+or universal domain marker/source-map qualification is claimed.
+
+PascalCase constructs/types, camelCase built-in fields, lowercase links and
+preserved user/domain symbols remain the spelling decision. Legitimate aliases,
+typed Interface families/named Mates, multi-occurrence Pattern mappings, material
+overrides and rotation fields are preserved. Assembly adapters still require
+semicolons in some generated forms; the serializer supplies them rather than
+changing accepted source meaning or rewriting that grammar during this pass.
+
+## Dogfood and X3 handoff
+
+Two fresh ordinary parts were authored from the current guide: a small drilled
+plate using a typed/defaulted local Feature and a two-hole keyed mounting plate.
+The latter intentionally collides the element name with a field/declaration name.
+Their real validation/build and STEP inspection receipts are retained locally.
+A separate Panel arc witness checks retained radian surface coordinates and
+explicitly retains the existing panel-only STEP capability rejection.
+Invalid sibling calls/data references are explicit rejection witnesses; the former
+Record scope boundary is now a positive geometry and nominal-type qualification.
+
+Observed friction: semantic Grid derivations still require the existing field
+separators; the initial compact test spelling was invalid in that owner and was
+corrected to documented multiline fields. This did not justify adding another
+Grid grammar. Pattern families retain different human-facing binders, point
+aliases and material/domain scopes. X3 owns their eventual surface reconciliation;
+X4 still owns the independent original twelve-part authoring retest.
+
+The October decision register retains all original recommendations and rationale,
+with current owner/compatibility/X3/X4 dispositions appended. No syntax decision
+is being withheld for user approval. The outstanding work is implementation and
+qualification of the module/Template semantic contract described above.
+
+
+## Final qualification
+
+The final code gate is `closeout-build.log` / `closeout-full.log`, not the intermediate
+runs that exposed severity, serializer identity and header-consumption issues.
+Final qualification commands ran serially with build-node reuse/shared compilation disabled.
+The last CLI review removed a duplicate data error caused by appending its message
+to the code string. Structured callers now retain one stable, source-located
+binding diagnostic; string-only compatibility APIs retain readable explanations.
+
+| Check | Final result |
+| --- | --- |
+| Release solution build | Zero errors; 19 existing warnings in the final gate build. |
+| Focused scoped-data/frontend/Template/Record tests | 117 passed in the final focused gate; Feature, CLI and Paperclip HTTP tests also pass in the full gate. |
+| Public documentation qualification | 13 passed; relative links and real CLI examples qualified. |
+| Required Core fast lane | 1,068 passed. |
+| Complete serial solution suite, including SlowCorpus | **5,018 passed across 20 executing assemblies; zero failures/skips.** Firmament: 2,548; CLI: 518; Core: 1,201. |
+| Complete current source corpus | **1,276 sources**, all classified; **327/327 canonical sources structurally parsed**; zero unresolved classification mismatches. |
+| Inherited source comparison | All 1,266 original source hashes, structural outcomes, production owners/levels/exits and final classifications match the fresh baseline. One speculative AST fingerprint change is reviewed below. |
+| Diagnostic family changes | Two control-flow negatives use the shared structural parser; a structural-only nested-generics witness reports its unsupported parameter and undeclared Product separately. All remain rejected. Data-only diagnostic-code differences are retained explicitly. |
+| STEP/AP242 parity | **26/26 byte-identical**, including guitar, assemblies, symmetry, Sculpting, typed tolerances and Record/Template/Feature explicit PMI. |
+| Fresh valid sources | Six real CLI validate/build successes, with STEP reimport inspection; three sibling negatives reject in both commands and emit no STEP. |
+| Panel radian compatibility | Real production parse produces Panel AIR and the expected sampled surface coordinates; solid build retains its explicit preexisting Panel-only capability rejection. |
+| Runtime snapshot | **0 remaining dotnet/test/build hosts**, 13.19 GiB free RAM and 91.82 GiB free disk. |
+
+The existing FrictionLab project discovers no tests and is not counted as an
+executing test assembly. Focused/fast totals are not added to the full total.
+There is no remote CI or new live Helios/browser claim. The runtime result is a
+post-run snapshot plus bounded retained-session checks, not a long-duration soak.
+
+### Corpus dispositions
+
+| Disposition | Sources |
+| --- | ---: |
+| Admitted | 493 |
+| AdmittedGeometryWithDfmFindings | 1 |
+| AdmittedInConsumerContext | 34 |
+| DeclarationModuleRequiresConsumer | 5 |
+| ExpectedNegativeRejection | 285 |
+| ExperimentalAdmitted | 9 |
+| ExperimentalRejected | 31 |
+| LegacySerializationAdmitted | 5 |
+| LegacySerializationRejected | 324 |
+| MalformedOrUnsupportedSourceRejected | 6 |
+| MisfiledPositiveFixture | 1 |
+| RejectedAtSolveStage | 1 |
+| SourceAdmissionRejected | 81 |
+
+Raw structural outcomes: 912 parsed / 364 rejected. Raw standalone/domain owner
+outcomes: 510 accepted / 766 rejected. These totals are not a V2 success rate.
+Canonical dispositions remain 285 direct admissions, 33 actual consumer contexts
+and nine explicit domain admission limits. No previously admitted fixture was
+reclassified to conceal a regression. The Panel-only witness remains an existing
+capability rejection. The former pending Record is explicitly promoted to a positive.
+
+The current inventory hash is
+`3FE41317FF888DC74EB9A1FF6A95761E4950B7F88301976B5EB4BC8960F24CF0`.
+The compact evidence record references the exact X1 complete ledger by hash,
+records verification of every inherited source, adds all ten current new source rows
+and all observed diagnostic/fingerprint differences, and retains all 26 artifact comparisons.
+Detailed current owner outputs/messages remain in the ignored complete report.
+Universal semantic parity remains explicitly false.
+
+### Reviewed continuation differences
+
+All **1,272** source paths common to the preceding 1,273-source X2 pass retain
+exact hashes, AST fingerprints, structural outcomes, production owners/levels/exits,
+diagnostic codes and dispositions. The pending Record file is promoted/renamed to
+`record-shadowing.firmament`: its former missing-thickness rejection is replaced
+by a correctly admitted local product. Three fixtures are added: scoped Table
+selection, scoped Record tolerance/PMI and a sibling-private data rejection.
+These changes account for the complete current 1,276-source inventory.
+
+The original 1,266-source comparison remains unchanged. Earlier Template-pass
+history is retained in the compact evidence rather than reported as a new data-pass
+difference. No invalid/speculative fixture was reclassified to hide a regression.
+
+One speculative material fixture changes AST fingerprint: spaced `200 GPa` and
+`180 GPa` now form Quantity nodes. Its unsupported material/density syntax still
+rejects structurally and in production; its disposition is unchanged. This is
+neither an admitted material capability nor a geometry regression.
+
+`Regression/FrontendX1/nested-generics.firmament` is explicitly structural-only:
+its nested Set parameter and undeclared `Product` remain semantically rejected.
+The parameter diagnostic names `T`, and lookup reports `Product` separately.
+Compared with the pre-X2 baseline, two control-flow fixtures changed diagnostic
+owner, one Feature cycle no longer repeats the same cycle from a second starting
+node, and two Feature type errors carry shorter code suffixes. All six complete
+code differences are retained in evidence; no accepted/rejected status changes.
+
+### Physical and identity witnesses
+
+| Witness | Measured result |
+| --- | --- |
+| Scoped drilled plate | One enclosed manifold body, seven faces, bounds `(-15,-10,0)..(15,10,8)` mm; the local recipe produces the checked 6 mm hole. STEP matches the equivalent concrete program in the component test. |
+| Keyed mounting plate | One enclosed manifold body, eight faces, bounds `(-20,-12,0)..(20,12,6)` mm; two 6 mm holes retain `holes.left/right` identities. STEP matches the renamed-binder form, including a binder named Shaft. |
+| Semantic point Pattern | Four checked 6 mm holes; a binder named Diameter retains the same STEP as the Item spelling. |
+| Local product Template | One enclosed manifold body, six faces, bounds `(-15,-10,0)..(15,10,6)` mm; local width is 30 mm and STEP matches concrete source. |
+| Scoped schema capture / Table row | Each is one enclosed manifold six-face body, bounds `(-15,-10,0)..(15,10,6)` mm. Component tests compare local Record, scalar, Table and with derivation against concrete STEP. |
+| Scoped Record tolerance / explicit PMI | One seven-face body, bounds `(-20,-15,0)..(20,15,8)` mm; 8 mm hole with +0.10/-0.05 mm requirement, AP242 face associations and the authored tolerance span checked in the component test. |
+| Guitar | Original STEP hash `469E42D07EC1BB3FFDB88D5B0149DA50C21F39631EDC7441C2B3DCF11C41681C`; 170 occurrences / 66 definitions. |
+| Radian Panel | Sampled endpoints `(10*cos(0.25),10*sin(0.25),0)` and `(10*cos(0.75),10*sin(0.75),5)` mm, with no round-trip unit conversion. |
+
+Representative real ATLAS, house/factory Scene, sheet-metal, WireForm, Sweep,
+Revolve and PMI cases also run through their proper corpus owners and regression
+paths. Exact pre/post artifact equivalence is claimed for the measured STEP
+baselines and explicit equivalent-program witnesses, not every conceivable
+Scene/GLB export or every specialization.
+
+## Performance evidence
+
+Single-run end-to-end CLI measurements include process startup and the existing
+engineering execution, not just AST evaluation:
+
+| Case | Elapsed |
+| --- | ---: |
+| Small mechanical / scoped Feature | 512 ms |
+| Record/Table Template | 450 ms |
+| Keyed Pattern | 546 ms |
+| Guitar, two retained-session compiles | 10,384 ms |
+| Small Assembly, two retained-session compiles | 595 ms |
+| House Scene inspection | 2,274 ms |
+
+The compact record retains the Assembly owners' actual per-build phase timings
+and reuse counts. The second guitar compile reuses all 56 definitions tracked by the ordinary
+definition reuse counter; exported definition count remains 66. The second
+small Assembly compile reuses its definition. These checks preserve retained
+compilation behavior. They are neither a speedup claim against an old binary
+nor a complete lex/bind/expand/lower phase benchmark. Dedicated uniform frontend
+phase measurements remain part of unfinished X2 qualification.
+
+## Code-quality closeout
+
+The modified frontend was checked for competing Feature readers, duplicated
+numeric interpretation, duplicate Record/Table readers, textual identifier
+replacement, diagnostic construction,
+header consumption, type/value namespace capture, provenance loss, mutable global
+state, expansion growth and ordering. Obsolete Feature readers and arithmetic
+code are removed, together with the independent canonical Record/Table readers
+and their unused Table-column helper. Existing unmigrated readers are identified above; no new
+fatal-code allowlist, whole-document parser route, generic source-reparse adapter
+or kernel feature was added. Serializer source spans preserve transport spelling
+only after AST binding; they do not select symbols or engineering meaning.
+
+The build, focused/full tests, complete corpus disposition and STEP hashes verify
+the final implementation. Public syntax and the 24-item decision register are
+updated. Test expectations changed only for earlier control-flow ownership and
+a whitespace-only assertion replaced by an AST identity assertion, plus the
+promoted pending Template and Record witnesses; real build,
+geometry and identity assertions remain. Generated logs, STEP and full reports
+stay under ignored `artifacts/local/firmament-x2/` and the continuation directory
+`artifacts/local/firmament-x2-scoped/`, with this pass in
+`artifacts/local/firmament-x2-data/`. Earlier evidence remains intact; this pass
+does not remove prior generated runs. Runtime hosts are checked after qualification.
+
+## Replay and evidence
+
+```powershell
+dotnet build Aetheris.slnx -c Release -m:1 -nr:false -p:UseSharedCompilation=false
+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter "Category!=SlowCorpus"
+dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll frontend-shadow --corpus fixtures --production --output-dir artifacts/local/firmament-x2/replay-corpus
+python scripts/classify-firmament-frontend-x1.py --report artifacts/local/firmament-x2/replay-corpus/report.json --downstream-evidence docs/release/FIRMAMENT-FRONTEND-X1-DOWNSTREAM.evidence.json --output artifacts/local/firmament-x2/replay-classified.json
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll validate fixtures/Regression/FrontendX2/scoped-drill.firmament --json --explain
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll asm inspect fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm --json --profile --repeat 2
+```
+
+The inventory command retains its historical `frontend-shadow` name; it calls
+the current structural parser and production domain owners. It does not provide
+a shadow-only admission path.
+
+Artifact replay: the adjacent evidence JSON's `geometryParity` entries contain
+source hashes and expected STEP hashes. Build each ordinary source with
+`build <source> --output <ignored-output.step> --json`; use
+`asm export-ap242 <source> --out <ignored-output.step> --json` for Assembly sources.
+Compare SHA-256 only after a successful command. The source hash must still match;
+a changed source is not the same baseline.
+
+Local final logs in `artifacts/local/firmament-x2-data/`: `closeout-build.log`,
+`closeout-focused.log`, `closeout-cli.log`, `closeout-docs.log`, `closeout-fast.log`, `closeout-full.log`,
+`corpus/report.json`, `classified.json`, `parity.log`, `geometry-parity.json`,
+`dogfood.json`, `performance.json`, `reviewed-dispositions.json` and
+`runtime-summary.json`. Earlier failed runs remain reproduction evidence; no
+failed intermediate run is used as the final gate.
+
+Portable record: [X2 compact evidence](FIRMAMENT-FRONTEND-X2.evidence.json).
+Baseline: [X1 closeout](FIRMAMENT-FRONTEND-X1-CLOSEOUT.md) and its complete ledger.
+Current language: [syntax](../public/firmament/syntax.md) and
+[decision register](../development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md).
+
+## Executive verdict
+
+**Success for the requested scoped-data binding pass. Meaningful progression
+for X2 overall.** Record, Static and Table lookup and schema ownership now
+use production AST identities and the common typed catalog. The schema-capture
+witness builds its intended geometry, inaccessible/incorrect data rejects, and
+scoped tolerance requirements project through the real AP242 path.
+
+X2 remains open for complete include-file/module provenance and remaining
+collection, expansion and domain readers. No language-policy decision is awaiting
+the user. The next work is the module syntax/provenance handoff and removal of
+those remaining source owners as each family is qualified.
diff --git a/fixtures/Regression/FrontendX2/README.md b/fixtures/Regression/FrontendX2/README.md
new file mode 100644
index 00000000..d99721f9
--- /dev/null
+++ b/fixtures/Regression/FrontendX2/README.md
@@ -0,0 +1,24 @@
+# X2 semantic migration witnesses
+
+| Source | Intent and current expected outcome |
+| --- | --- |
+| `scoped-drill.firmament` | Accepted: Model-local Drill shadows document Drill; dependent defaults produce a 6 mm hole in 30 × 20 × 8 mm stock. |
+| `pattern-symbol-collision.firmament` | Accepted: a binder and Hole named Diameter do not rewrite field labels. Two stable keyed holes have 6 mm diameter. |
+| `sibling-feature.invalid.firmament` | Rejected: Other.Local is not visible to Plate. Validate/build fail; no STEP is emitted. |
+| `template-shadowing.firmament` | Accepted: Model-local Family shadows document Family; the 30 × 20 × 6 mm product matches its concrete STEP equivalent. Promoted from the original pending specimen. |
+| `sibling-template.invalid.firmament` | Rejected: Other.Family is invisible to Plate; both validate/build reject with the authored application location. |
+| `record-shadowing.firmament` | Accepted: the outer and Model-local Spec schemas retain distinct nominal identities; the local product is 30 × 20 × 6 mm and matches concrete STEP. |
+| `scoped-record-pmi.firmament` | Accepted: a local tolerance survives same-named outer schema/value declarations, Template and Feature binding into explicit AP242 PMI. |
+| `scoped-table.firmament` | Accepted: local Table/schema/value names shadow outer declarations; a selected row produces 30 × 20 × 6 mm stock. |
+| `sibling-data.invalid.firmament` | Rejected: the sibling Static secret is invisible; validate/build reject at its authored reference. |
+| `panel-radians.firmament` | Existing radian-valued Panel arc admission retains exact sampled surface coordinates. Normal solid STEP export still reports its existing panel-only capability limitation. |
+
+The component tests compare accepted geometry to concrete/renamed equivalents,
+check generated identities, and retain source-located private-name rejection explicitly.
+The release report records real CLI outcomes and the complete corpus disposition.
+These fixtures do not extend permitted Pattern nesting or geometry capabilities.
+
+```powershell
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll validate fixtures/Regression/FrontendX2/scoped-drill.firmament --json --explain
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build fixtures/Regression/FrontendX2/pattern-symbol-collision.firmament --output artifacts/local/firmament-x2/mounting-plate.step --json
+```
diff --git a/fixtures/Regression/FrontendX2/panel-radians.firmament b/fixtures/Regression/FrontendX2/panel-radians.firmament
new file mode 100644
index 00000000..fed1c66b
--- /dev/null
+++ b/fixtures/Regression/FrontendX2/panel-radians.firmament
@@ -0,0 +1,25 @@
+// Compatibility surface witness. Panel admission succeeds; the existing
+// panel-only STEP materialization capability remains a separate limitation.
+Model RadianSurface {
+ units: mm
+ Panel patch {
+ surface: RuledSurface {
+ boundaryA: Arc {
+ center: [0mm, 0mm, 0mm]
+ normal: [0, 0, 1]
+ radius: 10mm
+ referenceAxis: [1, 0, 0]
+ startAngle: 0.25rad
+ sweepAngle: 0.5rad
+ }
+ boundaryB: Arc {
+ center: [0mm, 0mm, 5mm]
+ normal: [0, 0, 1]
+ radius: 10mm
+ referenceAxis: [1, 0, 0]
+ startAngle: 0.25rad
+ sweepAngle: 0.5rad
+ }
+ }
+ }
+}
diff --git a/fixtures/Regression/FrontendX2/pattern-symbol-collision.firmament b/fixtures/Regression/FrontendX2/pattern-symbol-collision.firmament
new file mode 100644
index 00000000..436c50e0
--- /dev/null
+++ b/fixtures/Regression/FrontendX2/pattern-symbol-collision.firmament
@@ -0,0 +1,19 @@
+schema Mechanical
+Model MountingPlate {
+ units: mm
+ Static points: Set<Point2> {
+ left => Point2(-10mm, 0mm)
+ right => Point2(10mm, 0mm)
+ }
+ Box stock { size: [40mm, 24mm, 6mm] }
+ Modify stock {
+ Pattern holes over points {
+ Diameter => Hole<Shaft> Diameter {
+ on: +Z
+ center: Diameter
+ diameter: 6mm
+ end: ThroughAll
+ }
+ }
+ }
+}
diff --git a/fixtures/Regression/FrontendX2/record-shadowing.firmament b/fixtures/Regression/FrontendX2/record-shadowing.firmament
new file mode 100644
index 00000000..3ffa9898
--- /dev/null
+++ b/fixtures/Regression/FrontendX2/record-shadowing.firmament
@@ -0,0 +1,12 @@
+// The outer Spec(width) and local Spec(width, thickness) retain distinct lexical identities.
+Record Spec { width: Length }
+Static outerSpec: Spec = Spec { width: 10mm }
+Model LocalRecord {
+ units: mm
+ Record Spec { width: Length thickness: Length }
+ Static localSpec: Spec = Spec { width: 30mm thickness: 6mm }
+ Template<spec: Spec = localSpec> Struct Family {
+ Box stock { size: [spec.width, 20mm, spec.thickness] }
+ }
+ Struct product = Family<>
+}
diff --git a/fixtures/Regression/FrontendX2/scoped-drill.firmament b/fixtures/Regression/FrontendX2/scoped-drill.firmament
new file mode 100644
index 00000000..ced066fa
--- /dev/null
+++ b/fixtures/Regression/FrontendX2/scoped-drill.firmament
@@ -0,0 +1,12 @@
+schema Mechanical
+Feature Drill(diameter: Length = 2mm) -> Hole<Shaft> {
+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: diameter end: ThroughAll }
+}
+Model ScopedPlate {
+ units: mm
+ Feature Drill(diameter: Length = nominal * 2, nominal: Length = 3mm) -> Hole<Shaft> {
+ return Hole<Shaft> { on: +Z center: Point2(0mm, 0mm) diameter: diameter end: ThroughAll }
+ }
+ Box stock { size: [30mm, 20mm, 8mm] }
+ Modify stock { Drill() }
+}
diff --git a/fixtures/Regression/FrontendX2/scoped-record-pmi.firmament b/fixtures/Regression/FrontendX2/scoped-record-pmi.firmament
new file mode 100644
index 00000000..fa667516
--- /dev/null
+++ b/fixtures/Regression/FrontendX2/scoped-record-pmi.firmament
@@ -0,0 +1,26 @@
+// These outer names must not capture the local engineering requirement.
+Record BoreSpec { unused: Length }
+Static standardBore: BoreSpec = BoreSpec { unused: 100mm }
+Model ScopedRequirements {
+ units: mm
+ Record BoreSpec { diameter: Length width: Length }
+ Static standardBore: BoreSpec = BoreSpec {
+ diameter: 8mm tol +0.10mm -0.05mm
+ width: 40mm
+ }
+ Template<spec: BoreSpec> Struct Family {
+ 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 } }
+ }
+ Struct product = Family<spec: standardBore>
+}
diff --git a/fixtures/Regression/FrontendX2/scoped-table.firmament b/fixtures/Regression/FrontendX2/scoped-table.firmament
new file mode 100644
index 00000000..769a328c
--- /dev/null
+++ b/fixtures/Regression/FrontendX2/scoped-table.firmament
@@ -0,0 +1,14 @@
+Record Spec { width: Length }
+Static Table choices: Spec { width: [10mm] }
+Static selected: Spec = choices[0]
+Model ScopedTable {
+ units: mm
+ Record Spec { width: Length thickness: Length }
+ Static width: Length = 30mm
+ Static Table choices: Spec {
+ width: [width]
+ thickness: [6mm]
+ }
+ Static selected: Spec = choices[0]
+ Box stock { size: [selected.width, 20mm, selected.thickness] }
+}
diff --git a/fixtures/Regression/FrontendX2/sibling-data.invalid.firmament b/fixtures/Regression/FrontendX2/sibling-data.invalid.firmament
new file mode 100644
index 00000000..3f0415f4
--- /dev/null
+++ b/fixtures/Regression/FrontendX2/sibling-data.invalid.firmament
@@ -0,0 +1,8 @@
+Model Other {
+ Static secret: Length = 30mm
+}
+Model Plate {
+ units: mm
+ Static width: Length = secret
+ Box stock { size: [width, 20mm, 6mm] }
+}
diff --git a/fixtures/Regression/FrontendX2/sibling-feature.invalid.firmament b/fixtures/Regression/FrontendX2/sibling-feature.invalid.firmament
new file mode 100644
index 00000000..db3bb1e4
--- /dev/null
+++ b/fixtures/Regression/FrontendX2/sibling-feature.invalid.firmament
@@ -0,0 +1,9 @@
+schema Mechanical
+Struct Other {
+ Feature Local() -> Hole<Shaft> { return Hole<Shaft> { diameter: 9mm } }
+}
+Model Plate {
+ units: mm
+ Box stock { size: [20mm, 20mm, 5mm] }
+ Modify stock { Local() }
+}
diff --git a/fixtures/Regression/FrontendX2/sibling-template.invalid.firmament b/fixtures/Regression/FrontendX2/sibling-template.invalid.firmament
new file mode 100644
index 00000000..b15c8bf6
--- /dev/null
+++ b/fixtures/Regression/FrontendX2/sibling-template.invalid.firmament
@@ -0,0 +1,9 @@
+// Template names are private to their lexical declaration scope.
+Model Other {
+ Template<> Struct Family {
+ Box stock { size: [10mm, 20mm, 6mm] }
+ }
+}
+Model Plate {
+ Struct product = Family<>
+}
diff --git a/fixtures/Regression/FrontendX2/template-shadowing.firmament b/fixtures/Regression/FrontendX2/template-shadowing.firmament
new file mode 100644
index 00000000..5d6e0f1d
--- /dev/null
+++ b/fixtures/Regression/FrontendX2/template-shadowing.firmament
@@ -0,0 +1,11 @@
+// Model-local Family shadows the document Template; product must be 30 x 20 x 6 mm.
+Template<width: Length = 10mm> Struct Family {
+ Box stock { size: [width, 20mm, 6mm] }
+}
+Model LocalFamily {
+ units: mm
+ Template<width: Length = 30mm> Struct Family {
+ Box stock { size: [width, 20mm, 6mm] }
+ }
+ Struct product = Family<>
+}