Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Complete exact prism mass properties and canonical static authoring

Yuechen Li2b4f235bb46a
diff --git a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs
index 701304a6..428961f3 100644
--- a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs
+++ b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs
@@ -92,16 +92,14 @@ public static class BrepMassProperties
return exact;
}
- // A normalized section stack is an exact Z-prism whose boundary is
- // composed only of horizontal planes and vertical planes/cylinders.
- // The display-tessellation M8 lane otherwise measures arc chord error
- // rather than the authoritative analytic boundary. This recognizer
- // consumes only the materialized B-rep graph and bindings: for every
- // constant-Z interval it integrates the oriented line/arc section
- // boundary exactly. It deliberately declines any non-prismatic face.
+ // The exact-Z-prism lane is authoritative for section volume. Its first
+ // implementation did not populate surface area or centroid, which made
+ // a WorldXY extrusion observably less complete than a rotated equivalent
+ // frame. Complete those public fields from the independent boundary
+ // evaluator while retaining the exact section-volume evidence.
if (TryEvaluateExactVerticalLineArcPrism(body, effective, topology, out exact))
{
- return exact;
+ return CompleteExactPrismResult(body, effective, exact);
}
var coarse = EvaluateAtResolution(body, effective, refinement: 1);
@@ -163,6 +161,28 @@ public static class BrepMassProperties
private static BrepMassPropertiesResult Unavailable(BrepMassPropertiesOptions options, BrepMassPropertiesTopologyDiagnostics topology, string reason)
=> new(BrepMassPropertiesStatus.Unavailable, 0d, 0d, 0d, null, topology.IsEnclosed, topology.IsOrientationConsistent, [], "DeterministicTrimmedFaceTriangulationBoundaryIntegral", null, options, topology, topology.Messages.Append(reason).ToArray());
+ private static BrepMassPropertiesResult CompleteExactPrismResult(BrepBody body, BrepMassPropertiesOptions options, BrepMassPropertiesResult exact)
+ {
+ var boundary = EvaluateAtResolution(body, options, refinement: 2);
+ if (boundary.Error is not null || System.Math.Abs(boundary.SignedVolume) <= 1e-18d)
+ return exact;
+
+ var centroid = new Point3D(
+ boundary.CentroidNumerator.X / boundary.SignedVolume,
+ boundary.CentroidNumerator.Y / boundary.SignedVolume,
+ boundary.CentroidNumerator.Z / boundary.SignedVolume);
+ var error = System.Math.Max(exact.ErrorBound ?? 0d, boundary.SurfaceArea * options.LinearTolerance * 4d);
+ return exact with
+ {
+ SurfaceArea = boundary.SurfaceArea,
+ Centroid = centroid,
+ FaceContributions = boundary.Contributions,
+ EvaluationMethod = "ExactVerticalLineArcPrismSectionIntegration+DeterministicTrimmedFaceTriangulationBoundaryIntegral",
+ ErrorBound = error,
+ Diagnostics = exact.Diagnostics.Append("Exact section volume was completed with deterministic boundary area and centroid evidence.").ToArray()
+ };
+ }
+
/// <summary>
/// Exact volume recognizer for a materialized line/arc prismatic shell.
/// It intentionally has no knowledge of Firmament section stacks: its only
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs
new file mode 100644
index 00000000..d9ebfb7c
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs
@@ -0,0 +1,288 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentV2CanonicalAdvancedGrammarTests
+{
+ [Fact]
+ public void CanonicalStaticRecordsArraysTemplatePatternAndRequire_ExpandToProductionHoles()
+ {
+ var parse = FirmamentV2Parser.Parse("""
+ Model GeneratedMounts {
+ Units: mm
+ Record MountSpec { Center: Point2 Diameter: Length }
+ Static Mounts: MountSpec[] = [
+ MountSpec { Center: Point2(-20mm, 0mm) Diameter: 8mm }
+ MountSpec { Center: Point2(20mm, 0mm) Diameter: 8mm }
+ ]
+ Require ValidDiameter => 8mm > 0mm
+ Template MountHole(MountSpec spec) {
+ Hole<Shaft> Mount {
+ On: +Z
+ Center: spec.Center
+ Diameter: spec.Diameter
+ End: ThroughAll
+ }
+ }
+ Box Base { Size: [80mm, 40mm, 10mm] }
+ Modify Base {
+ Pattern MountPattern Over Mounts { MountHole(Current) }
+ }
+ }
+ """);
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ Assert.Equal(2, parse.Document!.ModifyBlocks!.Single().SemanticHoles.Count);
+ var staticAuthoring = Assert.IsType<FirmamentV2StaticAuthoringDocument>(parse.Document.StaticAuthoring);
+ Assert.Equal("MountSpec", Assert.Single(staticAuthoring.RecordTypes).Name);
+ Assert.Equal(2, Assert.Single(staticAuthoring.Arrays).Elements.Count);
+ Assert.Equal(["MountPattern[0]", "MountPattern[1]"], Assert.Single(staticAuthoring.Patterns).GeneratedIds);
+ }
+
+ [Fact]
+ public void CanonicalStaticRequire_FailsBeforeMaterialLowering()
+ {
+ var parse = FirmamentV2Parser.Parse("""
+ Model InvalidRequire {
+ Units: mm
+ Require Dimensions => 0mm > 1mm
+ Box Base { Size: [10mm, 10mm, 10mm] }
+ }
+ """);
+
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(parse.Diagnostics, diagnostic => diagnostic == "firmament-v2-static-require-failed:Dimensions:0mm > 1mm");
+ }
+
+ [Fact]
+ public void CanonicalStaticPoint2Value_DrivesTypedProfileGuide()
+ {
+ var parse = FirmamentV2Parser.Parse("""
+ Model StaticProfile {
+ Units: mm
+ Record GuideSpec { Center: Point2 }
+ Static Guides: GuideSpec[] = [ GuideSpec { Center: Point2(0mm, 0mm) } ]
+ Concept Struct Layout On XY {
+ Rect2 Stock { Center: Guides[0].Center; Size: [20mm, 10mm] }
+ }
+ Profile Plate Using Layout { Loop Outer {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ } }
+ Struct Plate { Extrude Plate { Profile: Plate; From: -2mm; To: 2mm } }
+ }
+ """);
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ Assert.Equal("Plate", Assert.Single(parse.Document!.Profiles!).Name);
+ Assert.NotNull(parse.Document.StaticAuthoring);
+ }
+
+ [Fact]
+ public void CanonicalTemplate_EmitsSlotsForPatternAndProfileForDirectInvocation()
+ {
+ var slots = FirmamentV2Parser.Parse("""
+ Model GeneratedSlot {
+ Units: mm
+ Record SlotSpec { Center: Point2 Direction: Vector2 Length: Length Width: Length }
+ Static Vents: SlotSpec[] = [ SlotSpec { Center: Point2(0mm, 0mm) Direction: Vector2(1, 0) Length: 80mm Width: 40mm } ]
+ Template Vent(SlotSpec spec) { Slot<Capsule> Vent { Center: spec.Center Direction: spec.Direction Length: spec.Length Width: spec.Width Extent: ThroughAll Role: ThroughSlot } }
+ Concept Struct Layout On XY { Rect2 Stock { Center: Point2(0mm, 0mm); Size: [200mm, 100mm] } }
+ Profile Plate Using Layout { Loop Outer {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ } }
+ Struct Plate { Compose Body { Base Stock { Profile: Plate; From: -10mm; To: 10mm; Role: Stock } Pattern SlotPattern Over Vents { Vent(Current) } } }
+ }
+ """);
+ Assert.True(slots.IsSuccess, string.Join(Environment.NewLine, slots.Diagnostics));
+
+ var profile = FirmamentV2Parser.Parse("""
+ Model GeneratedProfile {
+ Units: mm
+ Record ProfileSpec { Center: Point2 }
+ Static Specs: ProfileSpec[] = [ ProfileSpec { Center: Point2(0mm, 0mm) } ]
+ Template PlateProfile(ProfileSpec spec) { Profile Plate Using Layout { Loop Outer {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ } } }
+ Concept Struct Layout On XY { Rect2 Stock { Center: Specs[0].Center; Size: [20mm, 10mm] } }
+ PlateProfile(Specs[0])
+ Struct PlateBody { Extrude Plate { Profile: Plate; From: -2mm; To: 2mm } }
+ }
+ """);
+ Assert.True(profile.IsSuccess, string.Join(Environment.NewLine, profile.Diagnostics));
+ Assert.Equal("Plate", Assert.Single(profile.Document!.Profiles!).Name);
+ }
+
+ [Theory]
+ [InlineData("record-array-pattern-slots.firmament", "CYLINDRICAL_SURFACE")]
+ [InlineData("record-array-template-profile.firmament", "MANIFOLD_SOLID_BREP")]
+ public void CanonicalStaticTemplateOutput_BuildsThroughTheProductionMaterializer(string fixtureName, string expectedStepEntity)
+ {
+ var source = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures/FirmamentV2/Canonical/valid", fixtureName));
+ var output = Path.Combine(Path.GetTempPath(), "aetheris-" + Guid.NewGuid().ToString("N") + ".step");
+ try
+ {
+ var build = FirmamentBuildAndExport.Run(source, output);
+
+ Assert.True(build.IsSuccess, string.Join(Environment.NewLine, build.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ Assert.Contains(expectedStepEntity, build.Value.Export.StepText, StringComparison.Ordinal);
+ }
+ finally
+ {
+ if (File.Exists(output)) File.Delete(output);
+ }
+ }
+
+ [Fact]
+ public void CanonicalSymbolTable_BindsSelectionsAcrossProfileComposeAndSlotFamilies()
+ {
+ var path = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures/FirmamentV2/Canonical/valid/semantic-slot-capsule.firmament"));
+ var parse = FirmamentV2Parser.Parse(File.ReadAllText(path));
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ var symbols = Assert.IsType<FirmamentV2CanonicalSymbolTable>(parse.Document!.SymbolTable);
+ Assert.Equal(FirmamentV2CanonicalSymbolKind.Profile, symbols.Resolve("Plate")!.Kind);
+ Assert.Equal(FirmamentV2CanonicalSymbolKind.Compose, symbols.Resolve("SlotBody")!.Kind);
+ Assert.Equal(FirmamentV2CanonicalSymbolKind.Slot, symbols.Resolve("Relief")!.Kind);
+ Assert.Contains(symbols.Bindings, binding => binding.OwnerCanonicalId == "Selection:ReliefEntry" && binding.TargetCanonicalId == "Slot:Relief");
+ Assert.Contains("firmament-v2-unified-canonical-symbols-bound", parse.Diagnostics);
+ }
+
+ [Fact]
+ public void CanonicalSymbolTable_RejectsCrossFamilyNameCollisions()
+ {
+ var parse = FirmamentV2Parser.Parse("""
+ Model Collision {
+ Units: mm
+ Concept Struct Layout On XY { Rect2 Stock { Center: [0mm, 0mm]; Size: [20mm, 10mm] } }
+ Profile Plate Using Layout { Loop Outer {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ } }
+ Struct PlateBody { Compose Plate { Base Stock { Profile: Plate; From: -2mm; To: 2mm; Role: Stock } } }
+ }
+ """);
+
+ Assert.False(parse.IsSuccess);
+ Assert.Contains("firmament-v2-symbol-duplicate:Plate:Profile:Compose", parse.Diagnostics);
+ }
+
+ [Theory]
+ [InlineData("semantic-slot-capsule.firmament", "ReliefEntry")]
+ [InlineData("semantic-slot-rounded-rectangle.firmament", "OpeningEntry")]
+ [InlineData("semantic-selection-chamfer.firmament", "OuterTopBoundary")]
+ public void CanonicalRoot_AdmitsSemanticSlotsAndSelections_WithoutACompatibilityDocumentRoot(string fixtureName, string selectionName)
+ {
+ var path = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures/FirmamentV2/Canonical/valid", fixtureName));
+ var parse = FirmamentV2Parser.Parse(File.ReadAllText(path));
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ var selection = Assert.Single(parse.Document!.Selections!);
+ Assert.Equal(selectionName, selection.Name);
+ Assert.Contains("firmament-v2-unified-canonical-advanced-parsed", parse.Diagnostics);
+ }
+
+ [Fact]
+ public void CanonicalSelection_ReportsSpecificBindingFailures()
+ {
+ var source = """
+ Model InvalidSelection {
+ Units: mm
+ Concept Struct Layout On XY { Rect2 Stock { Center: [0mm, 0mm]; Size: [20mm, 10mm] } }
+ Profile Plate Using Layout { Loop Outer {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ } }
+ Struct PlateBody { Extrude Plate { Profile: Plate; From: -2mm; To: 2mm } }
+ Selection Bad { Target: VertexSet Source: Missing.ProfileLoop(Outer) Require: ClosedLoop }
+ }
+ """;
+
+ var parse = FirmamentV2Parser.Parse(source);
+
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(parse.Diagnostics, diagnostic => diagnostic == FirmamentV2Parser.SelectionResultKindInvalid + ":Bad:VertexSet");
+ Assert.Contains(parse.Diagnostics, diagnostic => diagnostic == FirmamentV2Parser.SelectionUnknownSource + ":Bad:Missing");
+ }
+
+ [Fact]
+ public void CanonicalRoot_AdmitsConceptConstructionPlaneAndBlindHole_ThroughTheV2Route()
+ {
+ var parse = FirmamentV2Parser.Parse("""
+ Model SideHolePart {
+ Units: mm
+ Concept Struct SideLayout {
+ Datum: Plane { Origin: [-50mm, 0mm, 0mm]; Normal: [1, 0, 0]; Up: [0, 0, 1] }
+ }
+ Construction Plane PositiveXWorkplane { Trace: SideLayout.Datum }
+ Struct SideHoleBracket {
+ Box Base { Size: [100mm, 60mm, 12mm] }
+ Modify Base {
+ Hole<Shaft> SideMount {
+ From: PositiveXWorkplane
+ Center: Point2(10mm, 6mm)
+ Diameter: 8mm
+ End: ThroughAll
+ }
+ }
+ }
+ }
+ """);
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ Assert.Equal(FirmamentV2ParseDisposition.RecognizedValid, parse.Disposition);
+ Assert.Equal("SideHolePart", parse.Document!.ModelName);
+ Assert.Single(parse.Document.ModifyBlocks!.Single().SemanticHoles);
+ Assert.Contains("firmament-v2-unified-canonical-advanced-parsed", parse.Diagnostics);
+ }
+
+ [Fact]
+ public void CanonicalRoot_AdmitsProfileAndComposeDeclarations_IntoTheNormalizedDocument()
+ {
+ var profile = FirmamentV2Parser.Parse("""
+ Model ProfilePart {
+ Units: mm
+ Concept Struct Layout On XY {
+ Rect2 Stock { Center: [0mm, 0mm]; Size: [20mm, 10mm] }
+ }
+ Profile Plate Using Layout {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ }
+ Struct PlateBody { Extrude Plate { Profile: Plate; From: -2mm; To: 2mm } }
+ }
+ """);
+ Assert.True(profile.IsSuccess, string.Join(Environment.NewLine, profile.Diagnostics));
+ Assert.Equal("Plate", Assert.Single(profile.Document!.Profiles!).Name);
+
+ var compose = FirmamentV2Parser.Parse("""
+ Model ComposePart {
+ Units: mm
+ Concept Struct Layout On XY { Rect2 Stock { Center: [0mm, 0mm]; Size: [20mm, 10mm] } }
+ Profile Plate Using Layout { Loop Outer {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ } }
+ Struct PlateBody { Compose Body { Base Stock { Profile: Plate; From: -2mm; To: 2mm; Role: Stock } } }
+ }
+ """);
+ Assert.True(compose.IsSuccess, string.Join(Environment.NewLine, compose.Diagnostics));
+ Assert.Equal("Body", Assert.Single(compose.Document!.Composes!).Name);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2StaticLogicTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2StaticLogicTests.cs
index f39b0488..2f40a849 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2StaticLogicTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2StaticLogicTests.cs
@@ -140,5 +140,5 @@ public sealed class FirmamentV2StaticLogicTests
}
}
}
- """;
+ """.ReplaceLineEndings("\n");
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index f56d2c6e..033d8d68 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -58,9 +58,32 @@ public static class FirmamentBuildAndExport
private static KernelResult<FirmamentStepExportResult> ExportSource(string sourceText, string? sourceDirectory = null)
{
- if (PrismaticProfileCompositionParser.IsCompositionSource(sourceText))
+ // The V2 parser owns canonical-root admission. Profile/composition
+ // materializers consume only the extracted normalized declaration body,
+ // so their historical top-level spelling is no longer author-visible.
+ // Static authoring is intentionally erased before this boundary, too:
+ // parser admission alone is insufficient because the profile/composition
+ // materializers read source declarations directly.
+ var staticDiagnostics = new List<string>();
+ var staticExpansion = CanonicalStaticAuthoring.Expand(sourceText, staticDiagnostics);
+ if (staticExpansion is null)
+ {
+ return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics
+ .Distinct(StringComparer.Ordinal)
+ .Order(StringComparer.Ordinal)
+ .Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
+ Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
+ Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
+ diagnostic,
+ "FirmamentV2.StaticAuthoring"))
+ .ToArray());
+ }
+ var materializerInput = staticExpansion.Source;
+ var canonicalAdvanced = FirmamentV2Parser.TryGetCanonicalAdvancedBody(materializerInput, out var canonicalBody);
+ var materializerSource = canonicalAdvanced ? canonicalBody : materializerInput;
+ if (PrismaticProfileCompositionParser.IsCompositionSource(materializerSource))
{
- var parsed = PrismaticProfileCompositionParser.Parse(sourceText);
+ var parsed = PrismaticProfileCompositionParser.Parse(materializerSource);
var stack = PrismaticSectionStackCompiler.Normalize(parsed, out var diagnostics);
if (stack is null)
return KernelResult<FirmamentStepExportResult>.Failure(diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.ProfileComposition")).ToArray());
@@ -77,20 +100,25 @@ public static class FirmamentBuildAndExport
return KernelResult<FirmamentStepExportResult>.Failure(materialized.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.ProfileComposition.BlindDrill")).ToArray());
emitted = new PrismaticSectionStackEmissionResult(materialized.Body, finalPlan, emitted.Diagnostics.Concat(bridgeDiagnostics).ToArray(), finalPlan.Correspondence);
}
- if (sourceText.Contains("EdgeFinish", StringComparison.Ordinal))
- return ExportComposedSemanticTopBoundaryChamfer(sourceText, parsed, stack, emitted);
- var step = Step242Exporter.ExportBody(emitted.Body);
+ if (materializerSource.Contains("EdgeFinish", StringComparison.Ordinal))
+ return ExportComposedSemanticTopBoundaryChamfer(materializerSource, parsed, stack, emitted);
+ // The composition route either retained the checked body above or
+ // replaced it with a checked blind-drill materialization.
+ var completedBody = emitted.Body;
+ if (completedBody is null)
+ return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, "profile-composition-materialization-missing-body", "FirmamentV2.ProfileComposition")]);
+ var step = Step242Exporter.ExportBody(completedBody);
if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, stack.Feature.Name, 0, "prismatic-section-stack", "line-arc-profile-composition"));
}
- if (ProfileAuthoringParser.IsProfileSource(sourceText))
+ if (ProfileAuthoringParser.IsProfileSource(materializerSource))
{
- var parsed = ProfileAuthoringParser.Parse(sourceText);
+ var parsed = ProfileAuthoringParser.Parse(materializerSource);
if (parsed.Profile is null) return KernelResult<FirmamentStepExportResult>.Failure(parsed.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.Profile")).ToArray());
var emitted = ResolvedProfile2DValidator.Extrude(parsed.Profile, parsed.Height);
if (emitted.Status != LineArcProfileExtrudeStatus.Succeeded || emitted.Body is null) return KernelResult<FirmamentStepExportResult>.Failure(emitted.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.Profile")).ToArray());
- if (sourceText.Contains("EdgeFinish", StringComparison.Ordinal))
- return ExportProfileSemanticTopBoundaryChamfer(sourceText, parsed.Profile, parsed.Height, emitted);
+ if (materializerSource.Contains("EdgeFinish", StringComparison.Ordinal))
+ return ExportProfileSemanticTopBoundaryChamfer(materializerSource, parsed.Profile, parsed.Height, emitted);
var step = Step242Exporter.ExportBody(emitted.Body); if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, parsed.Profile.Name, 0, "profile-extrude", "line-arc-profile"));
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
new file mode 100644
index 00000000..906fb15f
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
@@ -0,0 +1,163 @@
+using System.Globalization;
+using System.Text.RegularExpressions;
+
+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>
+internal static class CanonicalStaticAuthoring
+{
+ internal const string Prefix = "firmament-v2-static-";
+ internal sealed record Result(string Source, FirmamentV2StaticAuthoringDocument? Document);
+ private sealed record Template(string Name, string Type, string Parameter, string Body, FirmamentV2SourceSpan Span);
+
+ public static Result? Expand(string source, List<string> diagnostics)
+ {
+ var canonicalRoot = Regex.IsMatch(source, @"^\s*Model\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant);
+ var staticDeclaration = Regex.IsMatch(source, @"\b(?:Record|Static|Template\s+[A-Za-z_]\w*\s*\(|Pattern\s+\w+\s+Over)\b", RegexOptions.CultureInvariant);
+ if (!staticDeclaration && !(canonicalRoot && Regex.IsMatch(source, @"\bRequire\s+[A-Za-z_]\w*\s*=>", RegexOptions.CultureInvariant))) return new(source, null);
+ var changes = new List<(int Start, int Length, string Text)>();
+ var names = new HashSet<string>(StringComparer.Ordinal);
+ var recordTypes = new List<FirmamentV2RecordTypeDecl>();
+ var arrays = new List<FirmamentV2StaticArrayDecl>();
+ var templates = new List<Template>();
+ var patterns = new List<FirmamentV2CanonicalPatternDecl>();
+ var requires = new List<FirmamentV2RequireDecl>();
+
+ foreach (Match header in Regex.Matches(source, @"\bRecord\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
+ {
+ 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));
+ }
+ var recordByName = recordTypes.ToDictionary(x => x.Name, 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*\[", RegexOptions.CultureInvariant))
+ {
+ var open = source.IndexOf('[', header.Index + header.Value.LastIndexOf('[')); var close = MatchPair(source, open, '[', ']');
+ var name = header.Groups["name"].Value; var type = header.Groups["type"].Value;
+ if (close < 0 || !recordByName.TryGetValue(type, out var record)) { diagnostics.Add(Prefix + "array-type-invalid:" + name); continue; }
+ if (!names.Add(name)) { diagnostics.Add(FirmamentV2Parser.DuplicateName + ":Static:" + name); continue; }
+ var elements = new List<IReadOnlyDictionary<string, string>>();
+ foreach (Match literal in Regex.Matches(source[(open + 1)..close], $@"\b{Regex.Escape(type)}\s*\{{", RegexOptions.CultureInvariant))
+ {
+ var literalOpen = open + 1 + literal.Index + literal.Value.LastIndexOf('{'); var literalClose = MatchPair(source, literalOpen, '{', '}');
+ if (literalClose < 0) { diagnostics.Add(Prefix + "record-literal-malformed:" + name); continue; }
+ var values = Fields(source[(literalOpen + 1)..literalClose]);
+ 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));
+ if (missing.Length == 0 && extra.Length == 0) elements.Add(values);
+ }
+ arrays.Add(new(name, type, elements, new(header.Index, close - header.Index + 1)));
+ changes.Add((header.Index, close - header.Index + 1, string.Empty));
+ }
+ var arrayByName = arrays.ToDictionary(x => x.Name, StringComparer.Ordinal);
+
+ foreach (Match header in Regex.Matches(source, @"\bTemplate\s+(?<name>[A-Za-z_]\w*)\s*\(\s*(?<type>[A-Za-z_]\w*)\s+(?<param>[A-Za-z_]\w*)\s*\)\s*\{", RegexOptions.CultureInvariant))
+ {
+ var close = MatchPair(source, source.IndexOf('{', header.Index), '{', '}');
+ var name = header.Groups["name"].Value;
+ if (close < 0 || !recordByName.ContainsKey(header.Groups["type"].Value)) { diagnostics.Add(Prefix + "template-malformed:" + name); continue; }
+ if (!names.Add(name)) { diagnostics.Add(FirmamentV2Parser.DuplicateName + ":Template:" + name); continue; }
+ var template = new Template(name, header.Groups["type"].Value, header.Groups["param"].Value, source[(source.IndexOf('{', header.Index) + 1)..close], new(header.Index, close - header.Index + 1));
+ templates.Add(template); changes.Add((header.Index, close - header.Index + 1, string.Empty));
+ }
+ var templateByName = templates.ToDictionary(x => x.Name, StringComparer.Ordinal);
+
+ // Static members are substituted through the common expression spelling before
+ // Profile/Compose adapters consume their already-resolved guide declarations.
+ foreach (var array in arrays)
+ {
+ for (var index = 0; index < array.Elements.Count; index++)
+ {
+ foreach (var field in array.Elements[index])
+ {
+ var reference = $@"\b{Regex.Escape(array.Name)}\s*\[\s*{index.ToString(CultureInfo.InvariantCulture)}\s*\]\s*\.\s*{Regex.Escape(field.Key)}\b";
+ foreach (Match referenceMatch in Regex.Matches(source, reference, RegexOptions.CultureInvariant))
+ changes.Add((referenceMatch.Index, referenceMatch.Length, field.Value));
+ }
+ }
+ }
+
+ 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 open = source.IndexOf('{', pattern.Index); var close = MatchPair(source, open, '{', '}');
+ if (close < 0 || !arrayByName.TryGetValue(pattern.Groups["array"].Value, 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*$", 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; }
+ 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 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)));
+ }
+
+ // A direct invocation is the same static expansion route as Pattern, with an
+ // explicit bounded element index. The declaration body is still erased before
+ // material AIR; it is not a runtime call.
+ foreach (Match invocation in Regex.Matches(source, @"\b(?<template>[A-Za-z_]\w*)\s*\(\s*(?<array>[A-Za-z_]\w*)\s*\[\s*(?<index>\d+)\s*\]\s*\)", RegexOptions.CultureInvariant))
+ {
+ if (!templateByName.TryGetValue(invocation.Groups["template"].Value, out var template)
+ || !arrayByName.TryGetValue(invocation.Groups["array"].Value, out var array)
+ || template.Type != array.ElementType) continue;
+ var index = int.Parse(invocation.Groups["index"].Value, CultureInfo.InvariantCulture);
+ if (index >= array.Elements.Count) { diagnostics.Add(Prefix + "array-index-out-of-range:" + array.Name); continue; }
+ var generatedId = template.Name + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
+ var declaration = Instantiate(template, array.Elements[index], generatedId, false, diagnostics);
+ if (declaration is not null) changes.Add((invocation.Index, invocation.Length, declaration));
+ }
+
+ foreach (Match require in Regex.Matches(source, @"\bRequire\s+(?<name>[A-Za-z_]\w*)\s*=>\s*(?<expr>[^\r\n}]+)", RegexOptions.CultureInvariant))
+ {
+ var expression = require.Groups["expr"].Value.Trim();
+ if (!TryRequire(expression, out var value)) { diagnostics.Add(Prefix + "require-non-bool:" + require.Groups["name"].Value); continue; }
+ requires.Add(new(require.Groups["name"].Value, expression, value, new(require.Index, require.Length)));
+ if (!value) diagnostics.Add(Prefix + "require-failed:" + require.Groups["name"].Value + ":" + expression);
+ changes.Add((require.Index, require.Length, string.Empty));
+ }
+ if (diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal) || d.StartsWith(FirmamentV2Parser.DuplicateName, StringComparison.Ordinal))) return null;
+ foreach (var change in changes.OrderByDescending(x => x.Start)) source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
+ return new(source, new(recordTypes, arrays, templates.Select(t => new FirmamentV2CanonicalTemplateDecl(t.Name, t.Type, t.Parameter, t.Body, t.Span)).ToArray(), patterns, requires));
+ }
+
+ 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\s*>|Slot\s*<\s*(?:Capsule|RoundedRectangle)\s*>|Profile)\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))
+ {
+ diagnostics.Add(Prefix + "pattern-output-unsupported:Profile");
+ return null;
+ }
+ 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}}}";
+ }
+ private static Dictionary<string, string> Fields(string body) => Regex.Matches(body, @"\b(?<name>[A-Za-z_]\w*)\s*:\s*(?<value>(?:Point2|Vector2)\s*\([^)]*\)|[-+]?\d+(?:\.\d+)?(?:mm|deg)?)", RegexOptions.CultureInvariant)
+ .Cast<Match>().ToDictionary(m => m.Groups["name"].Value, m => m.Groups["value"].Value, StringComparer.Ordinal);
+ private static bool TryRequire(string expression, out bool value)
+ {
+ value = false; var m = Regex.Match(expression, @"^(?<a>[-+]?\d+(?:\.\d+)?)(?<u>mm|deg)?\s*(?<op>>=|<=|==|>|<)\s*(?<b>[-+]?\d+(?:\.\d+)?)(?<v>mm|deg)?$", RegexOptions.CultureInvariant);
+ if (!m.Success || m.Groups["u"].Value != m.Groups["v"].Value) return false;
+ var a = double.Parse(m.Groups["a"].Value, CultureInfo.InvariantCulture); var b = double.Parse(m.Groups["b"].Value, CultureInfo.InvariantCulture);
+ value = m.Groups["op"].Value switch { ">" => a > b, ">=" => a >= b, "<" => a < b, "<=" => a <= b, "==" => a == b, _ => false }; return true;
+ }
+ private static int MatchPair(string text, int open, char left, char right) { var depth = 0; for (var i = open; i < text.Length; i++) { if (text[i] == left) depth++; else if (text[i] == right && --depth == 0) return i; } return -1; }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs
new file mode 100644
index 00000000..fca72d26
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs
@@ -0,0 +1,118 @@
+using System.Text.RegularExpressions;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>One canonical namespace for declarations that can participate in
+/// author-visible cross-family references. It is deliberately independent of
+/// materializer implementation types.</summary>
+public enum FirmamentV2CanonicalSymbolKind
+{
+ Record,
+ StaticArray,
+ Template,
+ Pattern,
+ Require,
+ Profile,
+ Compose,
+ Hole,
+ Slot,
+ Selection
+}
+
+public sealed record FirmamentV2CanonicalSymbol(
+ string Name,
+ FirmamentV2CanonicalSymbolKind Kind,
+ FirmamentV2SourceSpan SourceSpan)
+{
+ public string CanonicalId => $"{Kind}:{Name}";
+}
+
+/// <summary>A checked source reference, retained independently of the adapter
+/// that supplied its eventual material geometry.</summary>
+public sealed record FirmamentV2CanonicalSymbolBinding(
+ string OwnerCanonicalId,
+ string Relation,
+ string TargetCanonicalId,
+ FirmamentV2SourceSpan SourceSpan);
+
+public sealed record FirmamentV2CanonicalSymbolTable(
+ IReadOnlyList<FirmamentV2CanonicalSymbol> Symbols,
+ IReadOnlyList<FirmamentV2CanonicalSymbolBinding> Bindings)
+{
+ public FirmamentV2CanonicalSymbol? Resolve(string name) =>
+ Symbols.SingleOrDefault(symbol => string.Equals(symbol.Name, name, StringComparison.Ordinal));
+}
+
+internal static class FirmamentV2CanonicalSymbolBinder
+{
+ internal const string Duplicate = "firmament-v2-symbol-duplicate";
+ internal const string KindMismatch = "firmament-v2-symbol-kind-mismatch";
+
+ internal sealed record Result(FirmamentV2CanonicalSymbolTable Table, IReadOnlyList<string> Diagnostics);
+
+ public static Result Bind(FirmamentV2Document document, string source)
+ {
+ var symbols = new List<FirmamentV2CanonicalSymbol>();
+ var byName = new Dictionary<string, FirmamentV2CanonicalSymbol>(StringComparer.Ordinal);
+ var diagnostics = new List<string>();
+
+ void Add(string name, FirmamentV2CanonicalSymbolKind kind, FirmamentV2SourceSpan span)
+ {
+ if (byName.TryGetValue(name, out var previous))
+ {
+ diagnostics.Add($"{Duplicate}:{name}:{previous.Kind}:{kind}");
+ return;
+ }
+ var symbol = new FirmamentV2CanonicalSymbol(name, kind, span);
+ byName.Add(name, symbol);
+ symbols.Add(symbol);
+ }
+
+ if (document.StaticAuthoring is { } staticAuthoring)
+ {
+ foreach (var record in staticAuthoring.RecordTypes) Add(record.Name, FirmamentV2CanonicalSymbolKind.Record, record.SourceSpan);
+ foreach (var array in staticAuthoring.Arrays) Add(array.Name, FirmamentV2CanonicalSymbolKind.StaticArray, array.SourceSpan);
+ foreach (var template in staticAuthoring.Templates) Add(template.Name, FirmamentV2CanonicalSymbolKind.Template, template.SourceSpan);
+ foreach (var pattern in staticAuthoring.Patterns) Add(pattern.Name, FirmamentV2CanonicalSymbolKind.Pattern, pattern.SourceSpan);
+ foreach (var require in staticAuthoring.Requires) Add(require.Name, FirmamentV2CanonicalSymbolKind.Require, require.SourceSpan);
+ }
+
+ foreach (var profile in document.Profiles ?? []) Add(profile.Name, FirmamentV2CanonicalSymbolKind.Profile, profile.SourceSpan);
+ foreach (var compose in document.Composes ?? []) Add(compose.Name, FirmamentV2CanonicalSymbolKind.Compose, compose.SourceSpan);
+ foreach (Match feature in Regex.Matches(source, @"\b(?<kind>Hole|Slot)\s*<[^>]+>\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
+ {
+ Add(feature.Groups["name"].Value,
+ string.Equals(feature.Groups["kind"].Value, "Hole", StringComparison.Ordinal)
+ ? FirmamentV2CanonicalSymbolKind.Hole
+ : FirmamentV2CanonicalSymbolKind.Slot,
+ new(feature.Index, feature.Length));
+ }
+ foreach (var selection in document.Selections ?? []) Add(selection.Name, FirmamentV2CanonicalSymbolKind.Selection, selection.SourceSpan);
+
+ var bindings = new List<FirmamentV2CanonicalSymbolBinding>();
+ foreach (var selection in document.Selections ?? [])
+ {
+ var reference = ParseSelectionReference(selection.Source);
+ if (reference is null) continue; // Syntax and unknown-source diagnostics belong to the selection parser.
+ if (!byName.TryGetValue(reference.Value.Name, out var target)) continue;
+ if (target.Kind != reference.Value.Kind)
+ {
+ diagnostics.Add($"{KindMismatch}:{selection.Name}:{reference.Value.Kind}:{reference.Value.Name}:{target.Kind}");
+ continue;
+ }
+ bindings.Add(new($"{FirmamentV2CanonicalSymbolKind.Selection}:{selection.Name}", "Source", target.CanonicalId, selection.SourceSpan));
+ }
+
+ return new(new(symbols, bindings), diagnostics.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray());
+ }
+
+ private static (string Name, FirmamentV2CanonicalSymbolKind Kind)? ParseSelectionReference(string source)
+ {
+ var profile = Regex.Match(source, @"^(?<name>[A-Za-z_]\w*)\.Profile(?:Segments|Loop)\s*\(", RegexOptions.CultureInvariant);
+ if (profile.Success) return (profile.Groups["name"].Value, FirmamentV2CanonicalSymbolKind.Profile);
+ var slot = Regex.Match(source, @"^Slot\s*\(\s*(?<name>[A-Za-z_]\w*)\s*\)$", RegexOptions.CultureInvariant);
+ if (slot.Success) return (slot.Groups["name"].Value, FirmamentV2CanonicalSymbolKind.Slot);
+ var hole = Regex.Match(source, @"^Hole\s*\(\s*(?<name>[A-Za-z_]\w*)\s*\)$", RegexOptions.CultureInvariant);
+ return hole.Success ? (hole.Groups["name"].Value, FirmamentV2CanonicalSymbolKind.Hole) : null;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
index 59de04e3..78bc81ba 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
@@ -178,8 +178,9 @@ internal static class ConceptIrResolver
public static ConceptPhase3Resolution? Resolve(string source, List<string> diagnostics)
{
- // Match roles are compile-time conformance metadata. They deliberately do not lower to AIR.
- source = StripMatchBlocks(source);
+ // Match roles are compile-time conformance metadata. They deliberately do not lower to AIR,
+ // but they must remain available to the static evaluator so invalid domains and selected-arm
+ // failures are diagnosed before feature lowering.
var enums = ParseEnums(source, diagnostics);
var definitions = ParseDefinitions(source, diagnostics);
var materializedMatches = MaterializedHeader.Matches(source).Cast<Match>()
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 9cfcffad..f68c75e6 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -2,7 +2,7 @@ using Aetheris.Kernel.Firmament.Materializer;
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)
+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)
{
public FirmamentV2SolidBinding Solid => Solids[^1];
public FirmamentV2SideHoleIntent? SideHoleIntent => ModifyBlocks?.SelectMany(m => m.Regions.Select(r =>
@@ -69,6 +69,8 @@ public sealed record FirmamentV2TorusRecord(double MajorRadius, double MinorRadi
public sealed record FirmamentV2RoundedBoxRecord(IReadOnlyList<double> Size, double CornerRadius) : FirmamentV2PrimitiveRecord;
/// <summary>Exact conical-frustum primitive identity; unlike Cone it cannot silently collapse into a generic primitive name.</summary>
public sealed record FirmamentV2FrustumRecord(double BottomRadius, double TopRadius, double Height) : FirmamentV2PrimitiveRecord;
+/// <summary>Resolved by the profile/composition materialization routes rather than primitive lowering.</summary>
+public sealed record FirmamentV2AdvancedMaterialRecord(string Kind) : FirmamentV2PrimitiveRecord;
public sealed record FirmamentV2InlineStepRecord(string SourcePath, string NormalizedPath, string ContentHash, bool CanonicalInput, string CanonicalEvidence, ImportedStepTopologyMap TopologyMap) : FirmamentV2PrimitiveRecord;
public sealed record ImportedStepTopologyMap(IReadOnlyDictionary<string, string> FaceEntityToFaceId, IReadOnlyDictionary<string, string> FaceIdToFaceEntity)
{
@@ -188,6 +190,18 @@ public sealed record FirmamentV2BoundPmiRecord(FirmamentV2PmiKind Kind, string N
public sealed record FirmamentV2ConceptDecl(string Name, string RawValue, double NumericValue, string? Unit);
public sealed record FirmamentV2TemplateDecl(string Process, string Name, IReadOnlyList<FirmamentV2ConceptDecl> Concepts);
public sealed record FirmamentV2FillRegionDecl(string Name, IReadOnlyList<double> Size, IReadOnlyList<double> Center, FirmamentV2SourceSpan SourceSpan);
+/// <summary>Parser-owned normalized declaration evidence for the advanced material routes.
+/// The materializers consume the same resolved profile/composition semantics regardless of source origin.</summary>
+public sealed record FirmamentV2ProfileDecl(string Name, string Frame, double From, double To, FirmamentV2SourceSpan SourceSpan);
+public sealed record FirmamentV2ComposeDecl(string Name, IReadOnlyList<string> Operations, FirmamentV2SourceSpan SourceSpan);
+public sealed record FirmamentV2SelectionDecl(string Name, string Target, string Source, string Requirement, FirmamentV2SourceSpan SourceSpan);
+/// <summary>Normalized, erased-before-materialization evidence for canonical static authoring.</summary>
+public sealed record FirmamentV2StaticAuthoringDocument(IReadOnlyList<FirmamentV2RecordTypeDecl> RecordTypes, IReadOnlyList<FirmamentV2StaticArrayDecl> Arrays, IReadOnlyList<FirmamentV2CanonicalTemplateDecl> Templates, IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, IReadOnlyList<FirmamentV2RequireDecl> Requires);
+public sealed record FirmamentV2RecordTypeDecl(string Name, IReadOnlyDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);
+public sealed record FirmamentV2StaticArrayDecl(string Name, string ElementType, IReadOnlyList<IReadOnlyDictionary<string, string>> Elements, FirmamentV2SourceSpan SourceSpan);
+public sealed record FirmamentV2CanonicalTemplateDecl(string Name, string ParameterType, string ParameterName, string Body, FirmamentV2SourceSpan SourceSpan);
+public sealed record FirmamentV2CanonicalPatternDecl(string Name, string Source, string Template, int GeneratedCount, IReadOnlyList<string> GeneratedIds, FirmamentV2SourceSpan SourceSpan);
+public sealed record FirmamentV2RequireDecl(string Name, string Expression, bool Value, FirmamentV2SourceSpan SourceSpan, string? Provenance = null);
public sealed record FirmamentV2LatticeFillDecl(string Name, string Host, FirmamentV2FillRegionDecl Region, string Pattern, double CellSize, double StrutRadius, string BoundaryPolicy, FirmamentV2SourceSpan SourceSpan);
/// <summary>M9R's admitted standalone material body. It is intentionally distinct from the deferred host-replacement Fill.</summary>
public sealed record FirmamentV2StandaloneLatticeFillDecl(string Name, FirmamentV2FillRegionDecl Region, string Pattern, int CellsX, int CellsY, int CellsZ, double CellSize, double StrutRadius, double NodeRadius, string Placement, FirmamentV2SourceSpan SourceSpan);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index d93b9415..323423bf 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -3,6 +3,7 @@ using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Air;
+using Aetheris.Kernel.Firmament.Materializer;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
@@ -66,6 +67,10 @@ public static class FirmamentV2Parser
public const string CanonicalPrimitiveMalformed = "firmament-v2-canonical-primitive-malformed";
public const string CanonicalPoint2Invalid = "firmament-v2-canonical-point2-invalid";
public const string CanonicalModifyMalformed = "firmament-v2-canonical-modify-malformed";
+ public const string SelectionMalformed = "firmament-v2-selection-malformed";
+ public const string SelectionDuplicateName = "firmament-v2-selection-duplicate-name";
+ public const string SelectionUnknownSource = "firmament-v2-selection-unknown-source";
+ public const string SelectionResultKindInvalid = "firmament-v2-selection-result-kind-invalid";
public const string ConceptUnknownFamily = "firmament-v2-concept-unknown-family";
public const string ConceptUnknownConcept = "firmament-v2-concept-unknown-concept";
@@ -273,6 +278,15 @@ public static class FirmamentV2Parser
var v2AdmissionCandidate = IsV2AdmissionCandidate(source);
conceptCatalog ??= FirmamentV2ForgeConceptRegistry.Catalog;
+ var canonicalStaticExpansion = CanonicalStaticAuthoring.Expand(source, diagnostics);
+ if (canonicalStaticExpansion is null)
+ {
+ diagnostics.Add("firmament-v2-parse-failed");
+ return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray(),
+ v2AdmissionCandidate ? FirmamentV2ParseDisposition.RecognizedInvalid : FirmamentV2ParseDisposition.NotRecognized);
+ }
+ source = canonicalStaticExpansion.Source;
+
var templateExpansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics);
if (templateExpansion is null)
{
@@ -288,7 +302,27 @@ public static class FirmamentV2Parser
// adapters below remain only for old fixtures and no longer define the language
// an author must select for ordinary mechanical work.
if (CanonicalModelRegex.IsMatch(source))
- return Recognized(ParseCanonicalDocument(source, diagnostics));
+ {
+ var parsed = Recognized(ContainsCanonicalAdvancedDeclaration(source)
+ ? ParseCanonicalAdvancedDocument(source, diagnostics, templateExpansion.Instantiations)
+ : ParseCanonicalDocument(source, diagnostics));
+ if (parsed.Document is null) return parsed;
+
+ var normalized = parsed.Document with { StaticAuthoring = canonicalStaticExpansion.Document };
+ var symbolBinding = FirmamentV2CanonicalSymbolBinder.Bind(normalized, source);
+ if (symbolBinding.Diagnostics.Count > 0)
+ {
+ return FirmamentV2ParseResult.Failure(
+ parsed.Diagnostics.Concat(symbolBinding.Diagnostics).Distinct(StringComparer.Ordinal).Order().ToArray(),
+ FirmamentV2ParseDisposition.RecognizedInvalid);
+ }
+
+ return parsed with
+ {
+ Document = normalized with { SymbolTable = symbolBinding.Table },
+ Diagnostics = parsed.Diagnostics.Append("firmament-v2-unified-canonical-symbols-bound").Distinct(StringComparer.Ordinal).Order().ToArray()
+ };
+ }
if (Regex.IsMatch(source, @"\b(?:RoundedBox|Frustum|Box)\s*<\s*[A-Za-z_][A-Za-z0-9_]*\s*>\s+[A-Za-z_]", RegexOptions.CultureInvariant))
return Recognized(ParsePrimitiveConstructionPolicyDocument(source, diagnostics));
@@ -812,6 +846,194 @@ public static class FirmamentV2Parser
/// document as all compatibility forms: materializer selection sees primitive
/// and feature semantics, never the spelling that introduced them.
/// </summary>
+ private static bool ContainsCanonicalAdvancedDeclaration(string source) =>
+ Regex.IsMatch(source, @"\b(?:Concept|Struct|Construction\s+Plane|Profile|Compose|Selection|Template|Enum|Pattern|Require|Match)\b", RegexOptions.CultureInvariant);
+
+ /// <summary>
+ /// Parser-owned canonical admission for advanced declarations. The existing
+ /// production profile and section-stack readers remain semantic adapters; this
+ /// method owns the root, units, disposition, and normalized declaration list.
+ /// </summary>
+ private static FirmamentV2ParseResult ParseCanonicalAdvancedDocument(string source, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations)
+ {
+ var model = CanonicalModelRegex.Match(source);
+ var rootOpen = model.Success ? source.IndexOf('{', model.Index) : -1;
+ var rootClose = rootOpen >= 0 ? FindMatchingBrace(source, rootOpen) : -1;
+ if (!model.Success || rootClose < 0 || !string.IsNullOrWhiteSpace(source[(rootClose + 1)..]))
+ return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
+
+ var body = source[(rootOpen + 1)..rootClose];
+ var units = Regex.Match(body, @"\bUnits\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)\b", RegexOptions.CultureInvariant);
+ if (!units.Success || units.Groups["value"].Value != "mm")
+ return CanonicalFailure(diagnostics, CanonicalUnitsInvalid);
+ var adapterSource = Regex.Replace(body, @"(?m)^\s*Units\s*:\s*mm\s*$", string.Empty, RegexOptions.CultureInvariant);
+
+ if (PrismaticProfileCompositionParser.IsCompositionSource(adapterSource))
+ {
+ var composition = PrismaticProfileCompositionParser.Parse(adapterSource);
+ if (composition.Feature is null)
+ {
+ diagnostics.AddRange(composition.Diagnostics);
+ return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
+ }
+ var feature = composition.Feature;
+ var compositionSelectionDiagnostics = new List<string>();
+ var compositionSelections = ParseCanonicalSelections(body, rootOpen + 1, compositionSelectionDiagnostics);
+ ValidateCanonicalSelectionSources(body, compositionSelections, composition.Profiles.Keys, compositionSelectionDiagnostics);
+ if (compositionSelectionDiagnostics.Count > 0)
+ {
+ diagnostics.AddRange(compositionSelectionDiagnostics);
+ return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
+ }
+ var document = new FirmamentV2Document(
+ model.Groups["name"].Value,
+ "mm",
+ [new FirmamentV2SolidBinding(feature.Name, "Compose", new FirmamentV2AdvancedMaterialRecord("Compose"))],
+ Profiles: composition.Profiles.Values.Select(profile => new FirmamentV2ProfileDecl(profile.Name, profile.EffectiveConstructionPlane.StableId, profile.LocalStartDepth ?? 0d, profile.LocalEndDepth ?? 0d, new(0, 0))).ToArray(),
+ Composes: [new FirmamentV2ComposeDecl(feature.Name, feature.Operations.Select(operation => operation.Name).ToArray(), new(0, body.Length))],
+ Selections: compositionSelections);
+ diagnostics.Add("firmament-v2-unified-canonical-advanced-parsed");
+ diagnostics.Add("firmament-v2-profile-compose-adapted");
+ diagnostics.Add("firmament-v2-parse-succeeded");
+ diagnostics.Sort(StringComparer.Ordinal);
+ return FirmamentV2ParseResult.Success(document, diagnostics.Distinct(StringComparer.Ordinal).ToArray());
+ }
+
+ if (ProfileAuthoringParser.IsProfileSource(adapterSource))
+ {
+ var profile = ProfileAuthoringParser.Parse(adapterSource);
+ if (profile.Profile is null)
+ {
+ diagnostics.AddRange(profile.Diagnostics);
+ return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
+ }
+ var resolved = profile.Profile;
+ var profileSelectionDiagnostics = new List<string>();
+ var profileSelections = ParseCanonicalSelections(body, rootOpen + 1, profileSelectionDiagnostics);
+ ValidateCanonicalSelectionSources(body, profileSelections, [resolved.Name], profileSelectionDiagnostics);
+ if (profileSelectionDiagnostics.Count > 0)
+ {
+ diagnostics.AddRange(profileSelectionDiagnostics);
+ return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
+ }
+ var document = new FirmamentV2Document(
+ model.Groups["name"].Value,
+ "mm",
+ [new FirmamentV2SolidBinding(resolved.Name, "Profile", new FirmamentV2AdvancedMaterialRecord("Profile"))],
+ Profiles: [new FirmamentV2ProfileDecl(resolved.Name, resolved.EffectiveConstructionPlane.StableId, resolved.LocalStartDepth ?? 0d, resolved.LocalEndDepth ?? profile.Height, new(0, body.Length))],
+ Selections: profileSelections);
+ diagnostics.Add("firmament-v2-unified-canonical-advanced-parsed");
+ diagnostics.Add("firmament-v2-profile-adapted");
+ diagnostics.Add("firmament-v2-parse-succeeded");
+ diagnostics.Sort(StringComparer.Ordinal);
+ return FirmamentV2ParseResult.Success(document, diagnostics.Distinct(StringComparer.Ordinal).ToArray());
+ }
+
+ var concept = ParseConceptModelingDocument(adapterSource, diagnostics, templateInstantiations);
+ if (!concept.IsSuccess || concept.Document is null) return concept;
+ var conceptSelectionDiagnostics = new List<string>();
+ var conceptSelections = ParseCanonicalSelections(body, rootOpen + 1, conceptSelectionDiagnostics);
+ ValidateCanonicalSelectionSources(body, conceptSelections, [], conceptSelectionDiagnostics);
+ if (conceptSelectionDiagnostics.Count > 0)
+ {
+ diagnostics.AddRange(conceptSelectionDiagnostics);
+ return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
+ }
+ var normalized = concept.Document with
+ {
+ ModelName = model.Groups["name"].Value,
+ Selections = conceptSelections
+ };
+ diagnostics.Add("firmament-v2-unified-canonical-advanced-parsed");
+ diagnostics.Sort(StringComparer.Ordinal);
+ return FirmamentV2ParseResult.Success(normalized, diagnostics.Distinct(StringComparer.Ordinal).ToArray());
+ }
+
+ private static IReadOnlyList<FirmamentV2SelectionDecl> ParseCanonicalSelections(string body, int offset, List<string> diagnostics)
+ {
+ var selections = new List<FirmamentV2SelectionDecl>();
+ var names = new HashSet<string>(StringComparer.Ordinal);
+ foreach (Match header in Regex.Matches(body, @"\bSelection\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant))
+ {
+ var name = header.Groups["name"].Value;
+ var open = body.IndexOf('{', header.Index);
+ var close = FindMatchingBrace(body, open);
+ if (close < 0)
+ {
+ diagnostics.Add($"{SelectionMalformed}:{name}");
+ continue;
+ }
+
+ if (!names.Add(name))
+ {
+ diagnostics.Add($"{SelectionDuplicateName}:{name}");
+ continue;
+ }
+
+ var content = body[(open + 1)..close];
+ string Field(string field) => Regex.Match(content, $@"\b{Regex.Escape(field)}\s*:\s*(?<value>[\s\S]*?)(?=\s+(?:Target|Source|Require)\s*:|\z)", RegexOptions.CultureInvariant).Groups["value"].Value.Trim();
+ var target = Field("Target");
+ var source = Field("Source");
+ var requirement = Field("Require");
+ if (string.IsNullOrWhiteSpace(target) || string.IsNullOrWhiteSpace(source) || string.IsNullOrWhiteSpace(requirement))
+ {
+ diagnostics.Add($"{SelectionMalformed}:{name}");
+ continue;
+ }
+
+ selections.Add(new(name, target, source, requirement, new(offset + header.Index, close - header.Index + 1)));
+ }
+
+ return selections;
+ }
+
+ private static void ValidateCanonicalSelectionSources(
+ string body,
+ IReadOnlyList<FirmamentV2SelectionDecl> selections,
+ IEnumerable<string> profileNames,
+ List<string> diagnostics)
+ {
+ var profiles = profileNames.ToHashSet(StringComparer.Ordinal);
+ var slots = Regex.Matches(body, @"\bSlot\s*<[^>]+>\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant)
+ .Select(match => match.Groups["name"].Value)
+ .ToHashSet(StringComparer.Ordinal);
+ var holes = Regex.Matches(body, @"\bHole\s*<[^>]+>\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant)
+ .Select(match => match.Groups["name"].Value)
+ .ToHashSet(StringComparer.Ordinal);
+ var allowedTargets = new HashSet<string>(StringComparer.Ordinal)
+ {
+ "TopBoundary", "BottomBoundary", "SideBoundary", "HoleEntry", "HoleExit", "HoleWall", "ShaftToDrillPoint", "DrillPoint", "Tip",
+ "SlotEntry", "SlotExit", "SlotWall", "SlotStraightWall", "SlotEndWall"
+ };
+
+ foreach (var selection in selections)
+ {
+ if (!allowedTargets.Contains(selection.Target)) diagnostics.Add($"{SelectionResultKindInvalid}:{selection.Name}:{selection.Target}");
+ var profile = Regex.Match(selection.Source, @"^(?<profile>[A-Za-z_][A-Za-z0-9_]*)\.Profile(?:Segments|Loop)\s*\(", RegexOptions.CultureInvariant);
+ var slot = Regex.Match(selection.Source, @"^Slot\s*\(\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\)$", RegexOptions.CultureInvariant);
+ var hole = Regex.Match(selection.Source, @"^Hole\s*\(\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\)$", RegexOptions.CultureInvariant);
+ if (profile.Success && !profiles.Contains(profile.Groups["profile"].Value)) diagnostics.Add($"{SelectionUnknownSource}:{selection.Name}:{profile.Groups["profile"].Value}");
+ else if (slot.Success && !slots.Contains(slot.Groups["name"].Value)) diagnostics.Add($"{SelectionUnknownSource}:{selection.Name}:{slot.Groups["name"].Value}");
+ else if (hole.Success && !holes.Contains(hole.Groups["name"].Value)) diagnostics.Add($"{SelectionUnknownSource}:{selection.Name}:{hole.Groups["name"].Value}");
+ else if (!profile.Success && !slot.Success && !hole.Success) diagnostics.Add($"{SelectionUnknownSource}:{selection.Name}");
+ }
+ }
+
+ /// <summary>Extracts an already admitted canonical advanced body for the
+ /// production materializer boundary. It is intentionally not a second parser.</summary>
+ public static bool TryGetCanonicalAdvancedBody(string source, out string body)
+ {
+ body = string.Empty;
+ var model = CanonicalModelRegex.Match(source);
+ if (!model.Success || !ContainsCanonicalAdvancedDeclaration(source)) return false;
+ var open = source.IndexOf('{', model.Index); var close = FindMatchingBrace(source, open);
+ if (open < 0 || close < 0 || !string.IsNullOrWhiteSpace(source[(close + 1)..])) return false;
+ var candidate = source[(open + 1)..close];
+ if (!Regex.IsMatch(candidate, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant)) return false;
+ body = Regex.Replace(candidate, @"(?m)^\s*Units\s*:\s*mm\s*$", string.Empty, RegexOptions.CultureInvariant);
+ return true;
+ }
+
private static FirmamentV2ParseResult ParseCanonicalDocument(string source, List<string> diagnostics)
{
var model = CanonicalModelRegex.Match(source);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
index 90b066b3..f15e3301 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
@@ -7,10 +7,10 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;
/// <summary>Bounded parser for the first scaffold-referenced profile source route.</summary>
public static class ProfileAuthoringParser
{
- private static readonly Regex Point = new(@"\bPoint2\s+(?<n>\w+)\s*\{\s*Position\s*:\s*\[(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\]", RegexOptions.Singleline);
+ private static readonly Regex Point = new(@"\bPoint2\s+(?<n>\w+)\s*\{\s*Position\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\s*(?:\]|\))", RegexOptions.Singleline);
private static readonly Regex Line = new(@"\bLine2\s+(?<n>\w+)\s*\{\s*From\s*:\s*(?<a>\w+)\s*;?\s*To\s*:\s*(?<b>\w+)", RegexOptions.Singleline);
private static readonly Regex Circle = new(@"\bCircle2\s+(?<n>\w+)\s*\{\s*Center\s*:\s*(?<c>\w+)\s*;?\s*Radius\s*:\s*(?<r>[-+.\d]+)mm", RegexOptions.Singleline);
- private static readonly Regex Rect = new(@"\bRect2\s+(?<n>\w+)\s*\{\s*Center\s*:\s*\[(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\]\s*;?\s*Size\s*:\s*\[(?<w>[-+.\d]+)mm\s*,\s*(?<h>[-+.\d]+)mm\]", RegexOptions.Singleline);
+ private static readonly Regex Rect = new(@"\bRect2\s+(?<n>\w+)\s*\{\s*Center\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\s*(?:\]|\))\s*;?\s*Size\s*:\s*\[(?<w>[-+.\d]+)mm\s*,\s*(?<h>[-+.\d]+)mm\]", RegexOptions.Singleline);
private static readonly Regex Header = new(@"\bProfile\s+(?<n>\w+)\s+Using\s+(?<layout>\w+)\s*\{(?<body>[\s\S]*)", RegexOptions.CultureInvariant);
private static readonly Regex ConstructionPlaneDeclaration = new(@"\bConstruction\s+Plane\s+(?<name>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*\}", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex Segment = new(@"\bSegment\s+(?<n>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*From\s*:\s*(?<from>[\w.]+)\s*;?\s*To\s*:\s*(?<to>[\w.]+)(?:\s*;?\s*Sweep\s*:\s*(?<sweep>Clockwise|CounterClockwise))?", RegexOptions.Singleline);
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
index 8654c9ba..7ef901f3 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
@@ -72,10 +72,10 @@ public sealed record PrismaticProfileCompositionParseResult(
/// </summary>
public static class PrismaticProfileCompositionParser
{
- private static readonly Regex Point = new(@"\bPoint2\s+(?<n>\w+)\s*\{\s*Position\s*:\s*\[(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\]", RegexOptions.Singleline | RegexOptions.CultureInvariant);
+ private static readonly Regex Point = new(@"\bPoint2\s+(?<n>\w+)\s*\{\s*Position\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\s*(?:\]|\))", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex Line = new(@"\bLine2\s+(?<n>\w+)\s*\{\s*From\s*:\s*(?<a>\w+)\s*;?\s*To\s*:\s*(?<b>\w+)", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex Circle = new(@"\bCircle2\s+(?<n>\w+)\s*\{\s*Center\s*:\s*(?<c>\w+)\s*;?\s*Radius\s*:\s*(?<r>[-+.\d]+)mm", RegexOptions.Singleline | RegexOptions.CultureInvariant);
- private static readonly Regex Rect = new(@"\bRect2\s+(?<n>\w+)\s*\{\s*Center\s*:\s*\[(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\]\s*;?\s*Size\s*:\s*\[(?<w>[-+.\d]+)mm\s*,\s*(?<h>[-+.\d]+)mm\]", RegexOptions.Singleline | RegexOptions.CultureInvariant);
+ private static readonly Regex Rect = new(@"\bRect2\s+(?<n>\w+)\s*\{\s*Center\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\s*(?:\]|\))\s*;?\s*Size\s*:\s*\[(?<w>[-+.\d]+)mm\s*,\s*(?<h>[-+.\d]+)mm\]", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex ProfileHead = new(@"\bProfile\s+(?<n>\w+)\s+Using\s+(?<layout>\w+)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex Segment = new(@"\bSegment\s+(?<n>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*From\s*:\s*(?<from>[\w.]+)\s*;?\s*To\s*:\s*(?<to>[\w.]+)(?:\s*;?\s*Sweep\s*:\s*(?<sweep>Clockwise|CounterClockwise))?", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex ComposeHead = new(@"\bCompose\s+(?<n>\w+)\s*\{", RegexOptions.CultureInvariant);
diff --git a/Aetheris.Kernel.Firmament/Materializer/SectionStackBlindDrillCavityPlan.cs b/Aetheris.Kernel.Firmament/Materializer/SectionStackBlindDrillCavityPlan.cs
index d756f4c8..a6fb0786 100644
--- a/Aetheris.Kernel.Firmament/Materializer/SectionStackBlindDrillCavityPlan.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/SectionStackBlindDrillCavityPlan.cs
@@ -169,18 +169,19 @@ internal static class SectionStackBlindDrillCavityPlanner
if (point is null || input.Hole.EndCondition is AirHoleEndCondition.ThroughAll) d.Add("SectionStackBlindDrillRequiresBlindDrillPoint");
if (source is null) d.Add("SectionStackBlindDrillMissingAuthoritativeHostPlan");
if (d.Count != 0) { diagnostics = d; return null; }
+ if (source is null) { diagnostics = ["SectionStackBlindDrillMissingAuthoritativeHostPlan"]; return null; }
var faceIds = input.MouthHostFaceIds.Distinct().OrderBy(x => x.Value).ToArray();
if (faceIds.Length != 2) { diagnostics = ["SectionStackMouthArcOwnershipAmbiguous"]; return null; }
- var mappings = faceIds.Select(id => source!.FaceMappings.SingleOrDefault(x => x.FaceId == id && x.Kind == "PrismaticSide")).ToArray();
+ var mappings = faceIds.Select(id => source.FaceMappings.SingleOrDefault(x => x.FaceId == id && x.Kind == "PrismaticSide")).ToArray();
if (mappings.Any(x => x is null)) d.Add("SectionStackBlindDrillMouthFaceProvenanceMissing");
- var faces = faceIds.Select(id => source!.Topology.TryGetFace(id, out var face) ? face : null).ToArray();
+ var faces = faceIds.Select(id => source.Topology.TryGetFace(id, out var face) ? face : null).ToArray();
if (faces.Any(x => x is null)) d.Add("SectionStackBlindDrillMouthFaceMissing");
var bindings = new FaceGeometryBinding?[2];
var surfaces = new SurfaceGeometry?[2];
for (var index = 0; index < faceIds.Length; index++)
{
- if (source!.Bindings.TryGetFaceBinding(faceIds[index], out var binding))
+ if (source.Bindings.TryGetFaceBinding(faceIds[index], out var binding))
{
bindings[index] = binding;
if (source.Geometry.TryGetSurface(binding.SurfaceGeometryId, out var surface)) surfaces[index] = surface;
@@ -204,12 +205,15 @@ internal static class SectionStackBlindDrillCavityPlanner
d.Add("SectionStackMouthSeamPhysicalBoundary");
if (d.Count != 0) { diagnostics = d; return null; }
- var loops = faces.Select(face => source!.Topology.Loops.Single(loop => loop.Id == face!.LoopIds.Single())).ToArray();
- var edgeSets = loops.Select(loop => loop.CoedgeIds.Select(id => source!.Topology.Coedges.Single(c => c.Id == id).EdgeId).ToHashSet()).ToArray();
+ var loops = faces.Select(face => source.Topology.Loops.Single(loop => loop.Id == face!.LoopIds.Single())).ToArray();
+ var edgeSets = loops.Select(loop => loop.CoedgeIds.Select(id => source.Topology.Coedges.Single(c => c.Id == id).EdgeId).ToHashSet()).ToArray();
var common = edgeSets[0].Intersect(edgeSets[1]).OrderBy(id => id.Value).ToArray();
if (common.Length != 1) { diagnostics = ["SectionStackMouthSeamPhysicalBoundary"]; return null; }
- var seamId = common[0]; var seam = source!.Topology.Edges.Single(edge => edge.Id == seamId);
- if (!source.Bindings.TryGetEdgeBinding(seamId, out var seamBinding) || !source.Geometry.TryGetCurve(seamBinding.CurveGeometryId, out var seamCurve) || seamCurve.Kind != CurveGeometryKind.Line3)
+ var seamId = common[0]; var seam = source.Topology.Edges.Single(edge => edge.Id == seamId);
+ if (!source.Bindings.TryGetEdgeBinding(seamId, out var seamBinding)
+ || !source.Geometry.TryGetCurve(seamBinding.CurveGeometryId, out var seamCurve)
+ || seamCurve is null
+ || seamCurve.Kind != CurveGeometryKind.Line3)
{ diagnostics = ["SectionStackMouthSeamPhysicalBoundary"]; return null; }
var seamStart = source.VertexPoints[seam.StartVertexId]; var seamEnd = source.VertexPoints[seam.EndVertexId];
var seamVector = seamEnd - seamStart; var seamLength = seamVector.Length;
@@ -371,10 +375,10 @@ public static class SectionStackBlindDrillComposeBridge
var mouth = placement.WorldMouthCenter; var axis = placement.AxisZ.ToVector();
var compatible = plan.FaceMappings.Where(x => x.Kind == "PrismaticSide")
.Where(x => plan.Bindings.TryGetFaceBinding(x.FaceId, out var binding)
- && plan.Geometry.TryGetSurface(binding.SurfaceGeometryId, out var surface)
- && surface.Kind == SurfaceGeometryKind.Plane
- && Math.Abs(Math.Abs(surface.Plane!.Value.Normal.ToVector().Dot(axis)) - 1d) <= Tol
- && Math.Abs((mouth - surface.Plane.Value.Origin).Dot(surface.Plane.Value.Normal.ToVector())) <= Tol)
+ && plan.Geometry.TryGetSurface(binding.SurfaceGeometryId, out var surface)
+ && surface is { Kind: SurfaceGeometryKind.Plane, Plane: { } plane }
+ && Math.Abs(Math.Abs(plane.Normal.ToVector().Dot(axis)) - 1d) <= Tol
+ && Math.Abs((mouth - plane.Origin).Dot(plane.Normal.ToVector())) <= Tol)
.ToArray();
var candidates = compatible.Where(x => x.SlabFrom is { } from && x.SlabTo is { } to && mouth.Z - radius >= from - Tol && mouth.Z + radius <= to + Tol).ToArray();
if (candidates.Length == 1)
diff --git a/docs/firmament/v2-advanced-grammar-moonshot-x2.md b/docs/firmament/v2-advanced-grammar-moonshot-x2.md
new file mode 100644
index 00000000..43860c68
--- /dev/null
+++ b/docs/firmament/v2-advanced-grammar-moonshot-x2.md
@@ -0,0 +1,55 @@
+# Firmament V2 advanced grammar — X2 progress
+
+## Canonical root and adapter boundary
+
+Firmament V2 admits canonical advanced documents through one root:
+
+```firmament
+Model Name {
+ Units: mm
+ // Concept, Struct, Construction Plane, Profile, Compose, Selection
+}
+```
+
+`FirmamentV2Parser` owns root recognition, unit validation, parse disposition,
+and the normalized V2 document. Existing Concept IR, profile, and section-stack
+readers are semantic adapters behind that boundary. Build extracts a body only
+after canonical admission; it does not use the first source keyword to choose a
+user-visible dialect.
+
+## Normalized declarations
+
+`FirmamentV2Document` now carries parser-owned `Profiles`, `Composes`, and
+`Selections` alongside existing primitive, Modify, Concept IR, template, and
+static value fields. Advanced material records are deliberately distinct from
+primitive records so primitive lowering cannot accidentally treat a profile or
+section stack as a box.
+
+## Current semantic policy
+
+- The canonical root is PascalCase and requires `Units: mm`.
+- Ordinary dimensions use `mm`; angles use `deg`; ordinary feature points use
+ `Point2(xmm, ymm)`.
+- `Concept Struct` supplies immutable compile-time geometry. `Struct` supplies
+ material construction. `Construction Plane` traces Concept-plane provenance.
+- Profile and Compose preserve their resolved local frame, profile identities,
+ operation roles, intervals, and selection declarations through the adapter.
+- Compatibility inputs remain accepted at the boundary while their migration is
+ completed.
+
+## Verified corpus
+
+`profile-line-extrusion.firmament` and `profile-compose-base.firmament` build,
+export STEP, and reimport as enclosed one-body solids from their canonical
+roots. Construction-plane holes and static `Match` diagnostics are covered by
+V2 parser tests.
+
+## Remaining work before Preview 1
+
+This is not yet the complete moonshot. Slot/Selection consumers, Template
+syntax, typed profile guide literals, record/array syntax, and complete
+duplicate-name resolution still retain compatibility-era implementation seams.
+They need to be lowered into the same document model rather than represented
+only as adapter metadata. No claim of full dialect retirement should be made
+until those routes, their invalid fixtures, and all end-to-end exports are
+covered.
diff --git a/docs/firmament/v2-canonical-authoring.md b/docs/firmament/v2-canonical-authoring.md
index cecbb8ca..87c0c9bc 100644
--- a/docs/firmament/v2-canonical-authoring.md
+++ b/docs/firmament/v2-canonical-authoring.md
@@ -43,7 +43,98 @@ Model Bracket {
The currently proven low-ceremony production shape is one Box, one top-face ThroughAll shaft Hole, and one disjoint `+Z Boundary Chamfer`. It routes to `CombinedHoleEdgeFinish`, then authoritative STEP export and STEP reimport verification.
-Concept-first authoring remains available for construction planes, profiles, composition, templates, semantic selections, and spatial contracts. It is an escalation for spatial complexity, not a prerequisite for a primitive or ordinary host-relative Hole.
+## Advanced declarations in the same document
+
+Advanced source uses the same `Model { Units: mm }` root. Declarations may be
+ordered before their material `Struct`; the parser resolves the bounded static
+graph before materialization.
+
+```firmament
+Model SideHolePart {
+ Units: mm
+
+ Concept Struct SideLayout {
+ Datum: Plane { Origin: [-50mm, 0mm, 0mm]; Normal: [1, 0, 0]; Up: [0, 0, 1] }
+ }
+ Construction Plane PositiveXWorkplane { Trace: SideLayout.Datum }
+
+ Struct Bracket {
+ Box Base { Size: [100mm, 60mm, 12mm] }
+ Modify Base {
+ Hole<Shaft> SideMount {
+ From: PositiveXWorkplane
+ Center: Point2(10mm, 6mm)
+ Diameter: 8mm
+ End: ThroughAll
+ }
+ }
+ }
+}
+```
+
+Profiles and `Compose` use that same root and retain their production
+materializers. `Profile`, `Compose`, and `Selection` are recorded in the
+normalized V2 document; the build route consumes the parser-admitted body,
+not a raw leading-token dialect choice. See the canonical fixtures below.
+
+### Semantic Slots and Selections
+
+Slots are compiler-owned semantic removals inside an admitted `Compose`. Their
+geometry still lowers through the established exact profile route; the
+canonical root is the only document entry point.
+
+```firmament
+Slot<Capsule> Relief {
+ Center: Point2(0mm, 0mm)
+ Direction: Vector2(1, 0)
+ Length: 80mm
+ Width: 40mm
+ Extent: ThroughAll
+}
+Selection ReliefEntry {
+ Target: SlotEntry
+ Source: Slot(Relief)
+ Require: ClosedLoop
+}
+```
+
+`Slot<RoundedRectangle>` additionally requires `CornerRadius`. A selection is
+source-grounded: use `ProfileSegments(...)`, `ProfileLoop(...)`, `Hole(...)`,
+or `Slot(...)`, never a B-rep identifier. The canonical parser rejects a
+missing field, duplicate selection name, unknown source, or an incompatible
+selection result kind before materialization.
+
+### Bounded static authoring
+
+The current canonical static route admits typed records, static record arrays,
+one typed Template parameter, Pattern expansion, and static Require checks.
+They erase to ordinary admitted declarations before material lowering.
+
+```firmament
+Record MountSpec { Center: Point2 Diameter: Length }
+Static Mounts: MountSpec[] = [
+ MountSpec { Center: Point2(-20mm, 0mm) Diameter: 8mm }
+ MountSpec { Center: Point2(20mm, 0mm) Diameter: 8mm }
+]
+Require ValidDiameter => 8mm > 0mm
+Template MountHole(MountSpec spec) { /* Hole<Shaft> using spec.Center/spec.Diameter */ }
+Pattern MountPattern Over Mounts { MountHole(Current) }
+```
+
+The bounded route emits `Hole<Shaft>` and `Slot<Capsule>` or
+`Slot<RoundedRectangle>` from a `Pattern`. Generated feature names are stable:
+`PatternName_0`, `PatternName_1`, and so on. A template may also emit a
+`Profile`, but that form is deliberately a direct indexed invocation such as
+`PlateProfile(Specs[0])`: a generated profile needs a declared identity, so a
+profile is not admitted as Pattern output.
+
+Its normalized static AST preserves record schemas, values, template source,
+Pattern-generated IDs, and Require results; unsupported output kinds diagnose
+rather than silently falling back to a compatibility parser.
+
+Profile-guide `Point2` and `Rect2` declarations accept typed `Point2(x, y)`
+literals, including values substituted from a static record. Bracket
+coordinates remain accepted for existing fixtures during migration.
## Canonical examples
@@ -53,6 +144,14 @@ Concept-first authoring remains available for construction planes, profiles, com
- `fixtures/FirmamentV2/Canonical/valid/bare-frustum.firmament`
- `fixtures/FirmamentV2/Canonical/valid/box-through-hole.firmament`
- `fixtures/FirmamentV2/Canonical/valid/box-hole-chamfer.firmament`
+- `fixtures/FirmamentV2/Canonical/valid/profile-line-extrusion.firmament`
+- `fixtures/FirmamentV2/Canonical/valid/profile-compose-base.firmament`
+- `fixtures/FirmamentV2/Canonical/valid/semantic-slot-capsule.firmament`
+- `fixtures/FirmamentV2/Canonical/valid/semantic-slot-rounded-rectangle.firmament`
+- `fixtures/FirmamentV2/Canonical/valid/semantic-selection-chamfer.firmament`
+- `fixtures/FirmamentV2/Canonical/valid/record-array-pattern-holes.firmament`
+- `fixtures/FirmamentV2/Canonical/valid/record-array-pattern-slots.firmament`
+- `fixtures/FirmamentV2/Canonical/valid/record-array-template-profile.firmament`
## Common diagnostics
@@ -60,5 +159,9 @@ Concept-first authoring remains available for construction planes, profiles, com
- `firmament-v2-canonical-primitive-malformed`: a primitive is missing a required canonical field or has an invalid dimension.
- `firmament-v2-canonical-point2-invalid`: use `Point2(xmm, ymm)`, not `[x, y]`.
- `firmament-v2-canonical-modify-malformed`: a Hole or EdgeFinish declaration is missing a required canonical field.
+- `firmament-v2-selection-malformed`: provide `Target`, `Source`, and `Require`.
+- `firmament-v2-selection-unknown-source`: the named Profile, Hole, or Slot does not exist in the canonical document.
+- `firmament-v2-selection-result-kind-invalid`: choose an admitted semantic topology role.
-Legacy lowercase, phase-style, and Concept/Struct sources remain compatibility inputs during migration. New authoring should use the form above.
+Legacy lowercase and phase-style inputs remain compatibility inputs during
+migration. New authoring should use the canonical root shown above.
diff --git a/docs/firmament/v2-static-authoring-closure-x3.md b/docs/firmament/v2-static-authoring-closure-x3.md
new file mode 100644
index 00000000..d8aca4eb
--- /dev/null
+++ b/docs/firmament/v2-static-authoring-closure-x3.md
@@ -0,0 +1,54 @@
+# Firmament V2 static-authoring closure — X3 status
+
+This document is an evidence log, not a claim that every X3 objective is
+complete. Firmament V2 now has one canonical document root for ordinary parts,
+Concept/Struct work, Profile/Compose, semantic Slots, and source-grounded
+Selections:
+
+```firmament
+Model Name {
+ Units: mm
+ // all currently admitted declarations
+}
+```
+
+The parser owns root recognition, units, parse disposition, and a normalized
+document. Profile and section-stack readers are bounded semantic adapters
+behind that root; they do not decide the author-visible document dialect.
+
+## Current normalized and binding evidence
+
+- `FirmamentV2Document` carries Profile, Compose, Selection, static-authoring,
+ and canonical-symbol evidence.
+- Semantic Slot lowering remains the existing exact Profile lowering, with
+ source-to-topology correspondence and stable Slot descendant roles.
+- Canonical selection binding now diagnoses malformed declarations, duplicate
+ selection names, invalid result roles, and unknown Profile/Hole/Slot sources.
+- `Match`, bounded Concept `Pattern`, and the existing typed-template expansion
+ remain compile-time only and preserve static selection/template provenance.
+- Canonical `Record`, `Static T[]`, a typed one-parameter `Template`,
+ `Pattern ... Over`, and scalar `Require` normalize to a static AST then erase
+ before material lowering. Pattern output admits Shaft Holes and Capsule or
+ RoundedRectangle Slots; a Profile template is a direct indexed invocation.
+- The canonical symbol table has one namespace for Record, Static array,
+ Template, Pattern, Require, Profile, Compose, Hole, Slot, and Selection.
+ It rejects collisions across families and records the checked target of each
+ Profile/Hole/Slot Selection source.
+- Canonical Profile/Compose/Slot fixtures are parser-admitted then built through
+ production materializers; no build route relies on the old top-level root.
+
+## Deliberate bounds
+
+This closure is intentionally static: templates take one typed record
+parameter, direct invocation is an indexed static-array element, and Profile
+templates are direct-only because a generated Profile requires a declared
+identity. Runtime loops, dynamic collections, and generic cross-document
+linking remain outside the canonical grammar.
+
+## Verification
+
+The canonical corpus currently includes Profile extrusion, Compose, Capsule
+Slot, RoundedRectangle Slot, Selection-driven chamfer, record-array generated
+holes and slots, and direct Profile-template fixtures. Focused parser tests
+prove canonical-root admission, deterministic typed Selection diagnostics, and
+cross-family binding. The full Firmament suite remains the release gate.
diff --git a/docs/v2/firmament-v2-concept-template-syntax-reconciliation.md b/docs/v2/firmament-v2-concept-template-syntax-reconciliation.md
index a90b184e..5b628294 100644
--- a/docs/v2/firmament-v2-concept-template-syntax-reconciliation.md
+++ b/docs/v2/firmament-v2-concept-template-syntax-reconciliation.md
@@ -1,5 +1,15 @@
# Firmament V2 concept/template syntax reconciliation
+## X3 canonical-root update
+
+Advanced Profile/Compose, semantic Slots, and source-grounded Selections are
+now admitted under `Model { Units: mm }`. Their production readers are
+adapter-only; the canonical parser records normalized declarations first.
+Selection names are unique in the canonical Selection namespace and bind only
+to authored Profile/Hole/Slot provenance, never raw topology IDs. Templates,
+records, arrays, and general Pattern syntax still retain separate migration
+work; see [`../firmament/v2-static-authoring-closure-x3.md`](../firmament/v2-static-authoring-closure-x3.md).
+
Milestone: **V2-FIRMAMENT-SYNTAX-RECONCILE-A0**
This note is the Phase 1 reference for how `let`, Forge-backed concepts, and future templates relate in Firmament V2. It is intentionally narrow: it reconciles source syntax and fixture doctrine without adding language/runtime behavior.
diff --git a/fixtures/FirmamentV2/Canonical/valid/profile-compose-base.firmament b/fixtures/FirmamentV2/Canonical/valid/profile-compose-base.firmament
new file mode 100644
index 00000000..b8ac256b
--- /dev/null
+++ b/fixtures/FirmamentV2/Canonical/valid/profile-compose-base.firmament
@@ -0,0 +1,20 @@
+Model ComposePlate {
+ Units: mm
+
+ Concept Struct Layout On XY {
+ Rect2 Stock { Center: [0mm, 0mm]; Size: [20mm, 10mm] }
+ }
+
+ Profile Plate Using Layout { Loop Outer {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ } }
+
+ Struct PlateBody {
+ Compose Body {
+ Base Stock { Profile: Plate; From: -2mm; To: 2mm; Role: Stock }
+ }
+ }
+}
diff --git a/fixtures/FirmamentV2/Canonical/valid/profile-line-extrusion.firmament b/fixtures/FirmamentV2/Canonical/valid/profile-line-extrusion.firmament
new file mode 100644
index 00000000..48d0961f
--- /dev/null
+++ b/fixtures/FirmamentV2/Canonical/valid/profile-line-extrusion.firmament
@@ -0,0 +1,18 @@
+Model ProfilePlate {
+ Units: mm
+
+ Concept Struct Layout On XY {
+ Rect2 Stock { Center: [0mm, 0mm]; Size: [20mm, 10mm] }
+ }
+
+ Profile Plate Using Layout {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ }
+
+ Struct PlateBody {
+ Extrude Plate { Profile: Plate; From: -2mm; To: 2mm }
+ }
+}
diff --git a/fixtures/FirmamentV2/Canonical/valid/record-array-pattern-holes.firmament b/fixtures/FirmamentV2/Canonical/valid/record-array-pattern-holes.firmament
new file mode 100644
index 00000000..cf7af3db
--- /dev/null
+++ b/fixtures/FirmamentV2/Canonical/valid/record-array-pattern-holes.firmament
@@ -0,0 +1,21 @@
+Model GeneratedMounts {
+ Units: mm
+ Record MountSpec { Center: Point2 Diameter: Length }
+ Static Mounts: MountSpec[] = [
+ MountSpec { Center: Point2(-20mm, 0mm) Diameter: 8mm }
+ MountSpec { Center: Point2(20mm, 0mm) Diameter: 8mm }
+ ]
+ Require ValidDiameter => 8mm > 0mm
+ Template MountHole(MountSpec spec) {
+ Hole<Shaft> Mount {
+ On: +Z
+ Center: spec.Center
+ Diameter: spec.Diameter
+ End: ThroughAll
+ }
+ }
+ Box Base { Size: [80mm, 40mm, 10mm] }
+ Modify Base {
+ Pattern MountPattern Over Mounts { MountHole(Current) }
+ }
+}
diff --git a/fixtures/FirmamentV2/Canonical/valid/record-array-pattern-slots.firmament b/fixtures/FirmamentV2/Canonical/valid/record-array-pattern-slots.firmament
new file mode 100644
index 00000000..fc7ae42a
--- /dev/null
+++ b/fixtures/FirmamentV2/Canonical/valid/record-array-pattern-slots.firmament
@@ -0,0 +1,42 @@
+Model GeneratedSlots {
+ Units: mm
+
+ Record SlotSpec { Center: Point2 Direction: Vector2 Length: Length Width: Length }
+ Static Vents: SlotSpec[] = [
+ SlotSpec {
+ Center: Point2(0mm, 0mm)
+ Direction: Vector2(1, 0)
+ Length: 80mm
+ Width: 40mm
+ }
+ ]
+
+ Template Vent(SlotSpec spec) {
+ Slot<Capsule> Vent {
+ Center: spec.Center
+ Direction: spec.Direction
+ Length: spec.Length
+ Width: spec.Width
+ Extent: ThroughAll
+ Role: ThroughSlot
+ }
+ }
+
+ Concept Struct Layout On XY {
+ Rect2 Stock { Center: Point2(0mm, 0mm); Size: [200mm, 100mm] }
+ }
+ Profile Plate Using Layout {
+ Loop Outer {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ }
+ }
+ Struct Plate {
+ Compose Body {
+ Base Stock { Profile: Plate; From: -10mm; To: 10mm; Role: Stock }
+ Pattern SlotPattern Over Vents { Vent(Current) }
+ }
+ }
+}
diff --git a/fixtures/FirmamentV2/Canonical/valid/record-array-template-profile.firmament b/fixtures/FirmamentV2/Canonical/valid/record-array-template-profile.firmament
new file mode 100644
index 00000000..d9ece9c5
--- /dev/null
+++ b/fixtures/FirmamentV2/Canonical/valid/record-array-template-profile.firmament
@@ -0,0 +1,23 @@
+Model GeneratedProfile {
+ Units: mm
+
+ Record ProfileSpec { Center: Point2 }
+ Static Specs: ProfileSpec[] = [ ProfileSpec { Center: Point2(0mm, 0mm) } ]
+
+ Template PlateProfile(ProfileSpec spec) {
+ Profile Plate Using Layout {
+ Loop Outer {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ }
+ }
+ }
+
+ Concept Struct Layout On XY {
+ Rect2 Stock { Center: Specs[0].Center; Size: [20mm, 10mm] }
+ }
+ PlateProfile(Specs[0])
+ Struct PlateBody { Extrude Plate { Profile: Plate; From: -2mm; To: 2mm } }
+}
diff --git a/fixtures/FirmamentV2/Canonical/valid/semantic-selection-chamfer.firmament b/fixtures/FirmamentV2/Canonical/valid/semantic-selection-chamfer.firmament
new file mode 100644
index 00000000..e1252287
--- /dev/null
+++ b/fixtures/FirmamentV2/Canonical/valid/semantic-selection-chamfer.firmament
@@ -0,0 +1,26 @@
+Model SelectionChamferPart {
+ Units: mm
+ Concept Struct RectangleLayout On XY {
+ Point2 SouthWest { Position: [-10mm, -5mm] }
+ Point2 SouthEast { Position: [10mm, -5mm] }
+ Point2 NorthEast { Position: [10mm, 5mm] }
+ Point2 NorthWest { Position: [-10mm, 5mm] }
+ Line2 South { From: SouthWest; To: SouthEast }
+ Line2 East { From: SouthEast; To: NorthEast }
+ Line2 North { From: NorthEast; To: NorthWest }
+ Line2 West { From: NorthWest; To: SouthWest }
+ }
+ Profile MainPlate Using RectangleLayout { Loop Outer {
+ Segment SouthEdge { Trace: South; From: SouthWest; To: SouthEast }
+ Segment EastEdge { Trace: East; From: SouthEast; To: NorthEast }
+ Segment NorthEdge { Trace: North; From: NorthEast; To: NorthWest }
+ Segment WestEdge { Trace: West; From: NorthWest; To: SouthWest }
+ } }
+ Struct Plate { Extrude MainPlate { Profile: MainPlate; From: -2mm; To: 0mm } }
+ Selection OuterTopBoundary {
+ Target: TopBoundary
+ Source: MainPlate.ProfileSegments([SouthEdge, EastEdge, NorthEdge, WestEdge])
+ Require: ClosedLoop
+ }
+ EdgeFinish TopEdgeBreak { Target: OuterTopBoundary Kind: Chamfer Distance: 1mm }
+}
diff --git a/fixtures/FirmamentV2/Canonical/valid/semantic-slot-capsule.firmament b/fixtures/FirmamentV2/Canonical/valid/semantic-slot-capsule.firmament
new file mode 100644
index 00000000..18e1f790
--- /dev/null
+++ b/fixtures/FirmamentV2/Canonical/valid/semantic-slot-capsule.firmament
@@ -0,0 +1,17 @@
+Model CapsuleSlotPart {
+ Units: mm
+ Concept Struct SlotLayout On XY {
+ Rect2 Stock { Center: [0mm, 0mm]; Size: [200mm, 100mm] }
+ }
+ Profile Plate Using SlotLayout { Loop Outer {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ } }
+ Struct SlotFixture { Compose SlotBody {
+ Base Stock { Profile: Plate; From: -10mm; To: 10mm; Role: Stock }
+ Slot<Capsule> Relief { Center: Point2(0mm, 0mm); Direction: Vector2(1, 0); Length: 80mm; Width: 40mm; Extent: ThroughAll; Role: ThroughSlot }
+ } }
+ Selection ReliefEntry { Target: SlotEntry Source: Slot(Relief) Require: ClosedLoop }
+}
diff --git a/fixtures/FirmamentV2/Canonical/valid/semantic-slot-rounded-rectangle.firmament b/fixtures/FirmamentV2/Canonical/valid/semantic-slot-rounded-rectangle.firmament
new file mode 100644
index 00000000..5a39c07f
--- /dev/null
+++ b/fixtures/FirmamentV2/Canonical/valid/semantic-slot-rounded-rectangle.firmament
@@ -0,0 +1,17 @@
+Model RoundedRectangleSlotPart {
+ Units: mm
+ Concept Struct SlotLayout On XY {
+ Rect2 Stock { Center: [0mm, 0mm]; Size: [200mm, 100mm] }
+ }
+ Profile Plate Using SlotLayout { Loop Outer {
+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }
+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }
+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }
+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }
+ } }
+ Struct SlotFixture { Compose SlotBody {
+ Base Stock { Profile: Plate; From: -10mm; To: 10mm; Role: Stock }
+ Slot<RoundedRectangle> Opening { Center: Point2(0mm, 0mm); Direction: Vector2(1, 0); Length: 100mm; Width: 50mm; CornerRadius: 8mm; Extent: ThroughAll; Role: ThroughSlot }
+ } }
+ Selection OpeningEntry { Target: SlotEntry Source: Slot(Opening) Require: ClosedLoop }
+}