Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Implement tiny Firmament V2 Box parser
Yuechen Li6ad7f0a99de9
diff --git a/Aetheris.CLI.Tests/AirTraceCommandTests.cs b/Aetheris.CLI.Tests/AirTraceCommandTests.csindex 376c4bac..bcaff5f8 100644--- a/Aetheris.CLI.Tests/AirTraceCommandTests.cs+++ b/Aetheris.CLI.Tests/AirTraceCommandTests.cs@@ -909,9 +909,71 @@ public sealed class AirTraceCommandTestsAssert.Contains("STEP smoke: succeeded", File.ReadAllText(Path.Combine(firstDir, "side-hole.trace.txt")), StringComparison.Ordinal);}++ [Fact]+ public void FirmamentV2Parser_Box_TraceReportsFeatureAir()+ {+ var (exitCode, output, error) = Run("trace", "--fixture", FirmamentV2Fixture("Primitive/valid/box-v2.valid.firmfixture"));+ Assert.Equal(0, exitCode);+ Assert.True(string.IsNullOrWhiteSpace(error));+ Assert.Contains("Firmament V2", output);+ Assert.Contains("Stage: feature-air", output);+ Assert.Contains("Model: BoxExample", output);+ Assert.Contains("Units: mm", output);+ Assert.Contains("Solid: base", output);+ Assert.Contains("Record: Box", output);+ Assert.Contains("Size: [10, 8, 6]", output);+ Assert.Contains("Feature AIR: CreateBox", output);+ }++ [Fact]+ public void FirmamentV2Parser_Box_JsonIncludesStableFields()+ {+ var (exitCode, output, _) = Run("trace", "--fixture", FirmamentV2Fixture("Primitive/valid/box-v2.valid.firmfixture"), "--json");+ Assert.Equal(0, exitCode);+ using var doc = JsonDocument.Parse(output);+ var root = doc.RootElement;+ Assert.Equal("AIR-FIRMAMENT-X1", root.GetProperty("milestone").GetString());+ Assert.Equal("feature-air", root.GetProperty("actualStageReached").GetString());+ Assert.Equal("CreateBox", root.GetProperty("featureAir").GetProperty("nodeKind").GetString());+ var v2 = root.GetProperty("firmamentV2");+ Assert.Equal("FirmamentV2", v2.GetProperty("syntaxVersion").GetString());+ Assert.Equal("BoxExample", v2.GetProperty("modelName").GetString());+ Assert.Equal("mm", v2.GetProperty("units").GetString());+ Assert.Equal("base", v2.GetProperty("solidName").GetString());+ Assert.Equal("Box", v2.GetProperty("recordType").GetString());+ Assert.Equal(3, v2.GetProperty("size").GetArrayLength());+ Assert.Contains("firmament-v2-no-v1-parser", output);+ }++ [Fact]+ public void FirmamentV2Parser_MissingUnits_TraceReportsDiagnostic()+ {+ var (exitCode, output, _) = Run("trace", "--fixture", FirmamentV2Fixture("Primitive/invalid/box-v2-missing-units.invalid.firmfixture"), "--json");+ Assert.Equal(0, exitCode);+ Assert.Contains("firmament-v2-missing-units", output);+ }++ [Fact]+ public void FirmamentV2Parser_NegativeSize_TraceReportsDegenerateDimension()+ {+ var (exitCode, output, _) = Run("trace", "--fixture", FirmamentV2Fixture("Primitive/invalid/box-v2-negative-size.invalid.firmfixture"), "--json");+ Assert.Equal(0, exitCode);+ Assert.Contains("firmament-degenerate-dimension", output);+ }++ [Fact]+ public void FirmamentV2Parser_UnknownRecord_TraceReportsDiagnostic()+ {+ var (exitCode, output, _) = Run("trace", "--fixture", FirmamentV2Fixture("Primitive/invalid/box-v2-unknown-record.invalid.firmfixture"), "--json");+ Assert.Equal(0, exitCode);+ Assert.Contains("firmament-v2-unknown-record-type", output);+ }+private static string Fixture(string relative) => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures/Firmament/Chamfer", relative));private static string PrimitiveFixture(string relative) => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures/Firmament/Primitive", relative));private static string RegionFixture(string relative) => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures/Firmament/Region", relative));+ private static string FirmamentV2Fixture(string relative) => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures/FirmamentV2", relative));private static (int ExitCode, string Stdout, string Stderr) Run(params string[] args){diff --git a/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs b/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.csindex 74c2a5db..78b9e05d 100644--- a/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs+++ b/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs@@ -133,8 +133,8 @@ public sealed class FirmamentFixtureCorpusTestsforeach (var key in RequiredMetadata) Assert.True(fixture.ContainsKey(key), $"{path} missing {key}");Assert.Equal("FirmamentV2", fixture["syntax-version"]);Assert.Contains(fixture["validity"], new[] { "valid", "invalid" });- Assert.Contains(fixture["implementation"], new[] { "not-implemented", "rejected" });- Assert.True(fixture.ContainsKey("expected-diagnostic"), $"{path} missing expected-diagnostic");+ Assert.Contains(fixture["implementation"], new[] { "not-implemented", "rejected", "parser-backed" });+ if (fixture["implementation"] != "parser-backed") Assert.True(fixture.ContainsKey("expected-diagnostic"), $"{path} missing expected-diagnostic");}}@@ -146,11 +146,12 @@ public sealed class FirmamentFixtureCorpusTestsusing var doc = Trace(path);var root = doc.RootElement;var metadata = LoadMetadata(path);- Assert.False(root.GetProperty("fixture").GetProperty("parserBacked").GetBoolean());+ var isParserBacked = metadata["implementation"] == "parser-backed";+ Assert.Equal(isParserBacked, root.GetProperty("fixture").GetProperty("parserBacked").GetBoolean());Assert.True(root.GetProperty("fixture").GetProperty("expectationSatisfied").GetBoolean(), path);Assert.Equal(metadata["expected-stage"], root.GetProperty("actualStageReached").GetString());var diagnostics = root.GetProperty("diagnostics").EnumerateArray().Select(x => x.GetString()).ToArray();- Assert.Contains(metadata["expected-diagnostic"], diagnostics);+ if (metadata.TryGetValue("expected-diagnostic", out var expectedDiagnostic)) Assert.Contains(expectedDiagnostic, diagnostics);Assert.DoesNotContain("air-x11-firmament-parse-failed", diagnostics);}}diff --git a/Aetheris.CLI/AirTrace.cs b/Aetheris.CLI/AirTrace.csindex c96308c8..1823099a 100644--- a/Aetheris.CLI/AirTrace.cs+++ b/Aetheris.CLI/AirTrace.cs@@ -41,6 +41,7 @@ internal sealed record AirTraceReport(AirTraceFeatureAirSummary? FeatureAir = null,AirTraceConstructiveAirSummary? ConstructiveAir = null,AirTraceProfileEmissionSummary? ProfileEmission = null,+ AirTraceFirmamentV2Summary? FirmamentV2 = null,[property: JsonPropertyName("regions")] AirRegionTraceSummary? Regions = null,AirTraceArtifactsSummary? Artifacts = null);@@ -50,6 +51,7 @@ internal sealed record AirTraceFeatureAirSummary(bool ParserBacked, string Sourcinternal sealed record AirTraceConstructiveAirSummary(string NodeKind, string CanonicalForm, string SourceFeatureAirNodeKind, string ProfileKind, double Width, double Depth, double Height, string ExtrusionAxis, string ConstructionIntent, string RouteKind, string StageReached, IReadOnlyList<string> Diagnostics, IReadOnlyList<string> Guarantees);internal sealed record AirTraceProfileEmissionSummary(bool WrapperInvoked, string EmitterName, bool Succeeded, double Width, double Depth, double Height, string StageReached, AirTraceProfileEmissionTopologySummary? TopologySummary, AirTraceProfileEmissionStepSmokeSummary StepSmoke, IReadOnlyList<string> Diagnostics, IReadOnlyList<string> Guarantees);internal sealed record AirTraceProfileEmissionTopologySummary(int Vertices, int Edges, int Faces, int PlanarFaces, int CylindricalFaces, int Loops, int Coedges, int? CapFaces, int? SideFaces, string? Bounds);+internal sealed record AirTraceFirmamentV2Summary(string SyntaxVersion, string ModelName, string Units, string SolidName, string RecordType, IReadOnlyList<double> Size, string Stage);internal sealed record AirTraceProfileEmissionStepSmokeSummary(bool WasChecked, bool Succeeded, bool RequiredMarkersPresent, bool ForbiddenMarkersAbsent, IReadOnlyList<string> Diagnostics);internal sealed record AirTraceDimensionsSummary(double Width, double Depth, double Height);internal sealed record AirTraceAirSummary(string Node, string Route, string SelectionClass, string Rule, string ConstructionHistory, string FeatureName, string FeatureId, string ProvenanceMilestone);@@ -116,14 +118,15 @@ internal static class AirTraceReportBuilderprivate static AirTraceReport BuildParserBackedFixture(FirmFixture fixture){- var frontend = FirmamentFrontendTraceProbe.ParseOnly(fixture.SourceBody);+ var isFirmamentV2 = string.Equals(fixture.Metadata.GetValueOrDefault("syntax-version"), "FirmamentV2", StringComparison.Ordinal);+ var frontend = isFirmamentV2 ? FirmamentFrontendTraceProbe.ParseV2Only(fixture.SourceBody) : FirmamentFrontendTraceProbe.ParseOnly(fixture.SourceBody);var profileEmissionProbe = frontend.ConstructiveAir is null ? null : BoxConstructiveAirToProfileEmissionTraceProbe.Invoke(frontend.ConstructiveAir);var actualStage = profileEmissionProbe?.StageReached ?? frontend.FrontendStageReached ?? "frontend-unavailable";var expectedStageSatisfied = string.IsNullOrWhiteSpace(fixture.ExpectedStage) || string.Equals(actualStage, fixture.ExpectedStage, StringComparison.Ordinal);var expectationSatisfied = fixture.Expectation == "valid"? frontend.ParseSucceeded && expectedStageSatisfied && (profileEmissionProbe?.Succeeded ?? true): !frontend.ParseSucceeded && expectedStageSatisfied;- var fxDiagnostics = Stable([.. fixture.Diagnostics, .. frontend.Diagnostics, .. profileEmissionProbe?.Diagnostics ?? [], "air-x8-parser-backed-fixture-trace-created", "air-x11-parser-backed-fixture-loaded", "air-x11-firmament-parser-invoked", frontend.ParseSucceeded ? "air-x11-firmament-parse-succeeded" : "air-x11-firmament-parse-failed", expectationSatisfied ? "air-x11-parser-backed-expectation-satisfied" : "air-x11-profile-emission-expectation-not-satisfied"]).ToArray();+ var fxDiagnostics = Stable([.. fixture.Diagnostics, .. frontend.Diagnostics, .. profileEmissionProbe?.Diagnostics ?? [], "air-x8-parser-backed-fixture-trace-created", "air-x11-parser-backed-fixture-loaded", isFirmamentV2 ? "firmament-v2-parser-invoked" : "air-x11-firmament-parser-invoked", frontend.ParseSucceeded ? (isFirmamentV2 ? "firmament-v2-parse-succeeded" : "air-x11-firmament-parse-succeeded") : (isFirmamentV2 ? "firmament-v2-parse-failed" : "air-x11-firmament-parse-failed"), expectationSatisfied ? "air-x11-parser-backed-expectation-satisfied" : "air-x11-profile-emission-expectation-not-satisfied"]).ToArray();var featureAir = frontend.FeatureAir is null? null@@ -155,7 +158,9 @@ internal static class AirTraceReportBuilderprofileEmissionProbe.Diagnostics,profileEmissionProbe.Guarantees);- return new("AIR-X11", "trace", "lowering", "firmfixture", fixture.CaseName, expectationSatisfied, frontend.FrontendSummary,+ var v2 = frontend.FirmamentV2 is null ? null : new AirTraceFirmamentV2Summary(frontend.FirmamentV2.SyntaxVersion, frontend.FirmamentV2.ModelName, frontend.FirmamentV2.Units, frontend.FirmamentV2.SolidName, frontend.FirmamentV2.RecordType, frontend.FirmamentV2.Size, frontend.FirmamentV2.StageReached);++ return new(isFirmamentV2 ? "AIR-FIRMAMENT-X1" : "AIR-X11", "trace", "lowering", "firmfixture", fixture.CaseName, expectationSatisfied, frontend.FrontendSummary,new(constructiveAir?.NodeKind ?? featureAir?.NodeKind ?? "FirmamentPrimitive", constructiveAir?.RouteKind ?? "none", "none", "none", "parser-backed-source-fixture", fixture.CaseName, fixture.CaseName, "AIR-X11"),new("none", null, false, "Route selection and BRepPlan are deferred for parser-backed box fixtures in AIR-X11; profile emission is reported separately.", "none", "none", []),new("none", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "none", "none", null, []),@@ -163,12 +168,14 @@ internal static class AirTraceReportBuildernew(profileEmission?.StepSmoke.WasChecked ?? false, profileEmission?.StepSmoke.Succeeded ?? false, profileEmission?.StepSmoke.RequiredMarkersPresent ?? false, profileEmission?.StepSmoke.ForbiddenMarkersAbsent ?? false, profileEmission?.StepSmoke.Diagnostics ?? []),new("not-requested", "none", "none", "FirmamentPrimitive", "none", "none", "none", [], [], [], []),[], ["BRepPlan/CIR deferred for parser-backed box fixture", "STEP smoke unavailable for parser-backed box fixture"], fxDiagnostics,- ["real Firmament parser invoked", "parser-backed fixture reaches Feature AIR summary", "parser-backed fixture reaches Constructive AIR summary", "ProfileExtrude wrapper invoked", "no production grammar expansion", "no production route replacement", "no new geometry", "no profile emitter rewrite"],+ (isFirmamentV2+ ? ["real Firmament V2 parser invoked", "parser-backed fixture reaches Feature AIR summary", "no V1 parser route", "no production route replacement", "no new geometry"]+ : ["real Firmament parser invoked", "parser-backed fixture reaches Feature AIR summary", "parser-backed fixture reaches Constructive AIR summary", "ProfileExtrude wrapper invoked", "no production grammar expansion", "no production route replacement", "no new geometry", "no profile emitter rewrite"]),["no production Firmament grammar expansion", "no production route replacement", "no production analyzer behavior change", "no STEP exporter/importer change", "no BRep topology behavior change", "no route-selection/JudgmentUtility behavior change", "no CIR evaluator/tape behavior change", "no Boolean behavior change", "no AirEdgeSweep behavior change", "no BrepBoundedChamfer/BrepBoundedFillet behavior change", "no chamfer/fillet/shell geometry change", "no new geometry"],new(fixture.Path, fixture.Expectation, fixture.CaseName, fixture.ExpectedStage, actualStage!, fixture.ExpectedRoute, fixture.ExpectedReason, expectationSatisfied, true, fxDiagnostics),fixture.Path, fixture.Expectation, fixture.CaseName, fixture.ExpectedStage, actualStage!, fixture.ExpectedRoute, fixture.ExpectedReason, expectationSatisfied, fxDiagnostics,new(true, frontend.ParserName, frontend.ParseSucceeded, frontend.Diagnostics, actualStage!, frontend.FrontendSummary),- featureAir, constructiveAir, profileEmission, regions);+ featureAir, constructiveAir, profileEmission, v2, regions);}@@ -309,6 +316,18 @@ internal static class AirTraceTextRenderer{b.AppendLine("Frontend"); b.AppendLine($" Parser-backed: {r.Frontend.ParserBacked.ToString().ToLowerInvariant()}"); b.AppendLine($" Parser name: {r.Frontend.ParserName}"); b.AppendLine($" Parse succeeded: {r.Frontend.ParseSucceeded?.ToString().ToLowerInvariant()}"); b.AppendLine($" Frontend stage reached: {r.Frontend.FrontendStageReached}"); b.AppendLine(" Diagnostics:"); foreach (var d in r.Frontend.ParseDiagnostics) b.AppendLine($" - {d}"); b.AppendLine();}+ if (r.FirmamentV2 is not null)+ {+ b.AppendLine("Firmament V2");+ b.AppendLine($" Stage: {r.FirmamentV2.Stage}");+ b.AppendLine($" Model: {r.FirmamentV2.ModelName}");+ b.AppendLine($" Units: {r.FirmamentV2.Units}");+ b.AppendLine($" Solid: {r.FirmamentV2.SolidName}");+ b.AppendLine($" Record: {r.FirmamentV2.RecordType}");+ b.AppendLine($" Size: [{string.Join(", ", r.FirmamentV2.Size.Select(v => v.ToString("g", System.Globalization.CultureInfo.InvariantCulture)))}]");+ if (r.FeatureAir is not null) b.AppendLine($" Feature AIR: {r.FeatureAir.NodeKind}");+ b.AppendLine();+ }if (r.FeatureAir is not null){b.AppendLine("Feature AIR"); b.AppendLine($" Source op: {r.FeatureAir.SourceOpKind}"); b.AppendLine($" Node: {r.FeatureAir.NodeKind}");diff --git a/Aetheris.CLI/FirmFixture.cs b/Aetheris.CLI/FirmFixture.csindex f6619b4c..76329ff6 100644--- a/Aetheris.CLI/FirmFixture.cs+++ b/Aetheris.CLI/FirmFixture.cs@@ -44,6 +44,7 @@ internal static class FirmFixtureLoadervar sourceBody = ExtractSourceBody(lines);var parserBacked = metadata.TryGetValue("parser-backed", out var parserBackedValue) && string.Equals(parserBackedValue, "true", StringComparison.OrdinalIgnoreCase);+ if (!parserBacked && string.Equals(metadata.GetValueOrDefault("syntax-version"), "FirmamentV2", StringComparison.Ordinal) && string.Equals(metadata.GetValueOrDefault("implementation"), "parser-backed", StringComparison.Ordinal)) parserBacked = true;var diagnostics = new[]{"air-x7-firmfixture-loaded",diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.csnew file mode 100644index 00000000..d01db45e--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs@@ -0,0 +1,82 @@+using Aetheris.Kernel.Firmament;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentV2ParserTests+{+ [Fact]+ public void FirmamentV2Parser_Box_ParsesModelUnitsAndSolid()+ {+ var result = FirmamentV2Parser.Parse(Source("Primitive/valid/box-v2.valid.firmfixture"));+ Assert.True(result.IsSuccess, string.Join(", ", result.Diagnostics));+ Assert.NotNull(result.Document);+ var document = result.Document!;+ Assert.Equal("BoxExample", document.ModelName);+ Assert.Equal("mm", document.Units);+ Assert.Equal("base", document.Solid.Name);+ Assert.Equal("Box", document.Solid.RecordType);+ Assert.Equal([10, 8, 6], document.Solid.Box.Size);+ }++ [Fact]+ public void FirmamentV2Parser_Box_LowersToFeatureAir()+ {+ var result = FirmamentFrontendTraceProbe.ParseV2Only(Source("Primitive/valid/box-v2.valid.firmfixture"));+ Assert.True(result.ParseSucceeded, string.Join(", ", result.Diagnostics));+ Assert.Equal("FirmamentV2Parser", result.ParserName);+ Assert.Equal("feature-air", result.FrontendStageReached);+ Assert.NotNull(result.FeatureAir);+ Assert.Equal("CreateBox", result.FeatureAir!.FeatureAirNodeKind);+ Assert.Null(result.ConstructiveAir);+ }++ [Fact]+ public void FirmamentV2Parser_MissingUnits_IsDiagnostic()+ {+ var result = FirmamentV2Parser.Parse(Source("Primitive/invalid/box-v2-missing-units.invalid.firmfixture"));+ Assert.False(result.IsSuccess);+ Assert.Contains(FirmamentV2Parser.MissingUnits, result.Diagnostics);+ }++ [Fact]+ public void FirmamentV2Parser_NegativeSize_IsDegenerateDimension()+ {+ var result = FirmamentV2Parser.Parse(Source("Primitive/invalid/box-v2-negative-size.invalid.firmfixture"));+ Assert.False(result.IsSuccess);+ Assert.Contains(FirmamentV2Parser.DegenerateDimension, result.Diagnostics);+ }++ [Fact]+ public void FirmamentV2Parser_UnknownRecord_IsDiagnostic()+ {+ var result = FirmamentV2Parser.Parse(Source("Primitive/invalid/box-v2-unknown-record.invalid.firmfixture"));+ Assert.False(result.IsSuccess);+ Assert.Contains(FirmamentV2Parser.UnknownRecordType, result.Diagnostics);+ }++ [Fact]+ public void FirmamentV2Parser_DoesNotUseV1Parser()+ {+ var result = FirmamentFrontendTraceProbe.ParseV2Only(Source("Primitive/valid/box-v2.valid.firmfixture"));+ Assert.Equal("FirmamentV2Parser", result.ParserName);+ Assert.Contains("firmament-v2-no-v1-parser", result.Diagnostics);+ Assert.DoesNotContain(result.Diagnostics, d => d.Contains("FirmamentTopLevelParser", StringComparison.Ordinal));+ }++ [Fact]+ public void FirmamentV2Parser_UnsupportedConstruct_RemainsMetadataClassified()+ {+ var result = FirmamentV2Parser.Parse(Source("RecordDerivation/valid/box-with-size-variant-v2.valid.firmfixture"));+ Assert.False(result.IsSuccess);+ Assert.Contains(FirmamentV2Parser.UnsupportedConstruct, result.Diagnostics);+ }++ private static string Source(string relative)+ {+ var path = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures/FirmamentV2", relative));+ var lines = File.ReadAllLines(path);+ var bodyStart = Array.FindIndex(lines, line => !string.IsNullOrWhiteSpace(line) && !line.TrimStart().StartsWith("//", StringComparison.Ordinal));+ return string.Join(Environment.NewLine, lines.Skip(Math.Max(0, bodyStart)));+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentFrontendTraceProbe.cs b/Aetheris.Kernel.Firmament/FirmamentFrontendTraceProbe.csindex e60f75b7..526c8985 100644--- a/Aetheris.Kernel.Firmament/FirmamentFrontendTraceProbe.cs+++ b/Aetheris.Kernel.Firmament/FirmamentFrontendTraceProbe.cs@@ -2,6 +2,7 @@ using System.Globalization;using System.Text.RegularExpressions;using Aetheris.Kernel.Firmament.ParsedModel;using Aetheris.Kernel.Firmament.Parsing;+using Aetheris.Kernel.Firmament.FirmamentV2;namespace Aetheris.Kernel.Firmament;@@ -12,7 +13,10 @@ public sealed record FirmamentFrontendTraceProbeResult(string FrontendSummary,IReadOnlyList<string> Diagnostics,FirmamentPrimitiveAirTraceSummary? FeatureAir = null,- FirmamentConstructiveAirTraceSummary? ConstructiveAir = null);+ FirmamentConstructiveAirTraceSummary? ConstructiveAir = null,+ FirmamentV2TraceSummary? FirmamentV2 = null);++public sealed record FirmamentV2TraceSummary(string SyntaxVersion, string ModelName, string Units, string SolidName, string RecordType, IReadOnlyList<double> Size, string StageReached);public sealed record FirmamentPrimitiveAirTraceSummary(bool ParserBacked,@@ -41,6 +45,63 @@ public sealed record FirmamentTraceDimensions(double Width, double Depth, doublepublic static class FirmamentFrontendTraceProbe{++ public static FirmamentFrontendTraceProbeResult ParseV2Only(string sourceText)+ {+ ArgumentNullException.ThrowIfNull(sourceText);++ var parseResult = FirmamentV2Parser.Parse(sourceText);+ if (!parseResult.IsSuccess || parseResult.Document is null)+ {+ return new(+ "FirmamentV2Parser",+ false,+ "parsed",+ "Firmament V2 parser rejected the fixture source body.",+ parseResult.Diagnostics);+ }++ var document = parseResult.Document;+ var dimensions = new FirmamentTraceDimensions(document.Solid.Box.Size[0], document.Solid.Box.Size[1], document.Solid.Box.Size[2]);+ var featureDiagnostics = new[]+ {+ "firmament-v2-box-record-recognized",+ "firmament-v2-feature-air-create-box-created",+ "firmament-v2-inherited-model-units",+ "firmament-v2-no-v1-parser",+ "firmament-v2-parser-backed-fixture-loaded"+ }.Concat(parseResult.Diagnostics).Order(StringComparer.Ordinal).ToArray();++ var featureAir = new FirmamentPrimitiveAirTraceSummary(+ ParserBacked: true,+ SourceOpKind: document.Solid.RecordType,+ FeatureAirNodeKind: "CreateBox",+ SourceDimensions: dimensions,+ ConstructionIntent: "Box",+ StageReached: "feature-air",+ Diagnostics: featureDiagnostics,+ Guarantees:+ [+ "Firmament V2 parser invoked",+ "typed record solid binding",+ "model units inherited by Box size",+ "Feature AIR CreateBox summary",+ "no V1 parser route",+ "no production route replacement",+ "no new geometry emitted"+ ]);++ return new(+ "FirmamentV2Parser",+ true,+ "feature-air",+ $"Firmament V2 parsed model '{document.ModelName}' with units '{document.Units}', solid '{document.Solid.Name}: {document.Solid.RecordType}', and created Feature AIR CreateBox summary.",+ featureDiagnostics,+ featureAir,+ null,+ new FirmamentV2TraceSummary("FirmamentV2", document.ModelName, document.Units, document.Solid.Name, document.Solid.RecordType, document.Solid.Box.Size, "feature-air"));+ }+public static FirmamentFrontendTraceProbeResult ParseOnly(string sourceText){ArgumentNullException.ThrowIfNull(sourceText);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csnew file mode 100644index 00000000..df9c1c09--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -0,0 +1,10 @@+namespace Aetheris.Kernel.Firmament.FirmamentV2;++public sealed record FirmamentV2Document(string ModelName, string Units, FirmamentV2SolidBinding Solid);+public sealed record FirmamentV2SolidBinding(string Name, string RecordType, FirmamentV2BoxRecord Box);+public sealed record FirmamentV2BoxRecord(IReadOnlyList<double> Size);+public sealed record FirmamentV2ParseResult(bool IsSuccess, FirmamentV2Document? Document, IReadOnlyList<string> Diagnostics)+{+ public static FirmamentV2ParseResult Success(FirmamentV2Document document, IReadOnlyList<string> diagnostics) => new(true, document, diagnostics);+ public static FirmamentV2ParseResult Failure(IReadOnlyList<string> diagnostics) => new(false, null, diagnostics);+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csnew file mode 100644index 00000000..6805b284--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -0,0 +1,105 @@+using System.Globalization;+using System.Text.RegularExpressions;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public static class FirmamentV2Parser+{+ public const string MissingModel = "firmament-v2-missing-model";+ public const string MissingUnits = "firmament-v2-missing-units";+ public const string MissingSolid = "firmament-v2-missing-solid";+ public const string UnsupportedConstruct = "firmament-v2-unsupported-construct";+ public const string UnknownRecordType = "firmament-v2-unknown-record-type";+ public const string BoxMissingSize = "firmament-v2-box-missing-size";+ public const string BoxSizeArity = "firmament-v2-box-size-arity";+ public const string DegenerateDimension = "firmament-degenerate-dimension";++ private static readonly Regex ModelRegex = new(@"\bmodel\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);+ private static readonly Regex UnitsRegex = new(@"\bunits\s+(?<units>[A-Za-z_][A-Za-z0-9_]*)\b", RegexOptions.CultureInvariant);+ private static readonly Regex SolidRegex = new(@"\bsolid\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<type>[A-Za-z_][A-Za-z0-9_]*)\s*\{(?<body>.*?)\}", RegexOptions.CultureInvariant | RegexOptions.Singleline);+ private static readonly Regex SizeRegex = new(@"\bsize\s*:\s*\[(?<values>[^\]]*)\]", RegexOptions.CultureInvariant | RegexOptions.Singleline);++ public static FirmamentV2ParseResult Parse(string sourceText)+ {+ ArgumentNullException.ThrowIfNull(sourceText);+ var diagnostics = new List<string> { "firmament-v2-parser-invoked" };+ var source = StripLineComments(sourceText);++ if (ContainsUnsupportedConstruct(source)) diagnostics.Add(UnsupportedConstruct);++ var modelMatch = ModelRegex.Match(source);+ if (!modelMatch.Success) diagnostics.Add(MissingModel);++ var unitsMatch = UnitsRegex.Match(source);+ if (!unitsMatch.Success) diagnostics.Add(MissingUnits);+ else if (!string.Equals(unitsMatch.Groups["units"].Value, "mm", StringComparison.Ordinal)) diagnostics.Add(UnsupportedConstruct);++ var solidMatches = SolidRegex.Matches(source);+ if (solidMatches.Count == 0) diagnostics.Add(MissingSolid);+ if (solidMatches.Count > 1) diagnostics.Add(UnsupportedConstruct);++ FirmamentV2Document? document = null;+ if (modelMatch.Success && unitsMatch.Success && solidMatches.Count > 0)+ {+ var solid = solidMatches[0];+ var recordType = solid.Groups["type"].Value;+ if (!string.Equals(recordType, "Box", StringComparison.Ordinal)) diagnostics.Add(UnknownRecordType);++ var sizeMatch = SizeRegex.Match(solid.Groups["body"].Value);+ IReadOnlyList<double>? values = null;+ if (!sizeMatch.Success) diagnostics.Add(BoxMissingSize);+ else+ {+ values = ParseSizeValues(sizeMatch.Groups["values"].Value, diagnostics);+ }++ if (string.Equals(recordType, "Box", StringComparison.Ordinal) && values is not null && !diagnostics.Any(IsFatalDiagnostic))+ {+ document = new FirmamentV2Document(+ modelMatch.Groups["name"].Value,+ unitsMatch.Groups["units"].Value,+ new FirmamentV2SolidBinding(solid.Groups["name"].Value, recordType, new FirmamentV2BoxRecord(values)));+ }+ }++ diagnostics.Add(document is null ? "firmament-v2-parse-failed" : "firmament-v2-parse-succeeded");+ diagnostics.Sort(StringComparer.Ordinal);+ return document is null ? FirmamentV2ParseResult.Failure(diagnostics) : FirmamentV2ParseResult.Success(document, diagnostics);+ }++ private static bool IsFatalDiagnostic(string code) => code is MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension;++ private static IReadOnlyList<double>? ParseSizeValues(string raw, List<string> diagnostics)+ {+ var parts = raw.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);+ if (parts.Length != 3)+ {+ diagnostics.Add(BoxSizeArity);+ return null;+ }++ var values = new List<double>(3);+ foreach (var part in parts)+ {+ if (!double.TryParse(part, NumberStyles.Float, CultureInfo.InvariantCulture, out var value))+ {+ diagnostics.Add(UnsupportedConstruct);+ return null;+ }++ if (value <= 0) diagnostics.Add(DegenerateDimension);+ values.Add(value);+ }++ return diagnostics.Contains(DegenerateDimension) ? null : values;+ }++ private static bool ContainsUnsupportedConstruct(string source) =>+ Regex.IsMatch(source, @"\b(with|concept|PMI|where|template|cut|add|shell|fillet|chamfer|region|regions|profile|material|pattern)\b|=>|<\s*Process\s*>", RegexOptions.CultureInvariant);++ private static string StripLineComments(string sourceText) => string.Join('\n', sourceText.Split('\n').Select(line =>+ {+ var index = line.IndexOf("//", StringComparison.Ordinal);+ return index >= 0 ? line[..index] : line;+ }));+}diff --git a/docs/air-firmament-a1-firmament-fixture-corpus.md b/docs/air-firmament-a1-firmament-fixture-corpus.mdindex e1dd1bf6..cf723f28 100644--- a/docs/air-firmament-a1-firmament-fixture-corpus.md+++ b/docs/air-firmament-a1-firmament-fixture-corpus.md@@ -136,7 +136,7 @@ Next milestones should pick one narrow future fixture and lower it part-by-part:Firmament V2 is the canonical future human-facing source language. Firmament V1 remains valid where already supported, but it is legacy TOON/YAML structured syntax, mostly frozen, and primarily useful for the existing corpus, interchange, and historical regression evidence.-A2 introduces metadata-only V2 design fixtures under `fixtures/FirmamentV2/`. These fixtures use record/block-style construction-intent snippets and declare `syntax-version: FirmamentV2`. Until a V2 parser lands, they are deliberately classified by metadata as `not-implemented` or `rejected`; they must not be surfaced as random V1 parser failures.+A2 introduces metadata-only V2 design fixtures under `fixtures/FirmamentV2/`. These fixtures use record/block-style construction-intent snippets and declare `syntax-version: FirmamentV2`. AIR-FIRMAMENT-X1 promotes only `fixtures/FirmamentV2/Primitive/valid/box-v2.valid.firmfixture` and its small invalid primitive pilots to parser-backed V2 fixtures. The rest remain deliberately classified by metadata as `not-implemented` or `rejected`; they must not be surfaced as random V1 parser failures.The intended V2 fixture tree is:@@ -159,7 +159,7 @@ fixtures/FirmamentV2/Invalid/```-Future features should be written in V2 syntax first, marked not implemented/future-design, and then advanced through parser, semantic intent, Feature AIR, Constructive/Compositional AIR, BRepPlan, BRep, STEP/artifact, and trace stages in narrow milestones. Existing V1 fixtures remain valid in `fixtures/Firmament/` and do not require migration.+Future features should be written in V2 syntax first, marked not implemented/future-design, and then advanced through parser, semantic intent, Feature AIR, Constructive/Compositional AIR, BRepPlan, BRep, STEP/artifact, and trace stages in narrow milestones. X1 establishes the first such narrow promotion at Feature AIR for typed-record Box only. Existing V1 fixtures remain valid in `fixtures/Firmament/` and do not require migration.## A2.1 semantic-reference and admissibility fixture expansiondiff --git a/docs/air-firmament-a2-firmament-v2-source-language-design.md b/docs/air-firmament-a2-firmament-v2-source-language-design.mdindex 1d66b363..9ca7f24d 100644--- a/docs/air-firmament-a2-firmament-v2-source-language-design.md+++ b/docs/air-firmament-a2-firmament-v2-source-language-design.md@@ -356,9 +356,9 @@ A2 explicitly does not introduce:Recommended next milestones:-1. Define a tiny V2 lexer/parser spike for model/units/basic named constructors without geometry expansion.-2. Add source diagnostics for missing units, duplicate names, and unsupported V2 constructs.-3. Lower one V2 parser-backed box fixture to existing Feature AIR without changing backend topology.+1. AIR-FIRMAMENT-X1 now provides the first parser-backed slice for `model`, `units`, and typed-record `solid base: Box { size: [...] }`; see `docs/air-firmament-x1-v2-parser-box.md`.+2. Add source diagnostics for duplicate names and keep unsupported V2 constructs metadata-classified until explicitly promoted.+3. Extend the V2 parser only through narrow frontend slices without changing backend topology.4. Lower one profile extrusion fixture through Feature AIR and existing Constructive AIR/profile emission evidence.5. Promote side-hole V2 region syntax from design fixture to semantic intent only, then to AIR Region only, before any materialization expansion.6. Keep fillet, shell, surfacing, and material fixtures as future-design until their compiler stages are separately admitted.diff --git a/docs/air-firmament-x1-v2-parser-box.md b/docs/air-firmament-x1-v2-parser-box.mdnew file mode 100644index 00000000..514006a3--- /dev/null+++ b/docs/air-firmament-x1-v2-parser-box.md@@ -0,0 +1,80 @@+# AIR-FIRMAMENT-X1 — Tiny Firmament V2 parser for Box++## Purpose and scope++AIR-FIRMAMENT-X1 implements the first parser-backed Firmament V2 slice: `model`, inherited `units`, one typed `solid` binding, the `Box` record, and a `size` field with three positive numeric components. The milestone intentionally stops at Feature AIR `CreateBox` trace evidence; it does not add BRep, STEP, topology, Boolean, shell, fillet, chamfer, surfacing, pattern, material, FEA, or PMI behavior.++## V2 parser organization++The V2 frontend is isolated under `Aetheris.Kernel.Firmament/FirmamentV2/`. `FirmamentV2Parser` and `FirmamentV2Ast` are separate from the legacy `Parsing/FirmamentTopLevelParser` path. Trace dispatch uses fixture metadata (`syntax-version: FirmamentV2`, `implementation: parser-backed`) to invoke the V2 parser directly.++## V1 legacy separation policy++Firmament V1 remains the existing TOON/YAML-style compatibility surface in `fixtures/Firmament/` and continues through `FirmamentTopLevelParser`. X1 does not expand V1 syntax, migrate the V1 corpus, or treat V2 as a V1 compatibility mode. Unsupported V2 design fixtures from A2/A2.1/A2.2/A2.3 remain metadata-classified unless explicitly promoted.++## Supported X1 grammar++Canonical X1 syntax is typed-record style:++```firmament+model BoxExample {+ units mm++ solid base: Box {+ size: [10, 8, 6]+ }+}+```++Supported constructs are limited to:++- `model Name { ... }`;+- `units mm`;+- `solid name: Box { size: [x, y, z] }`;+- numeric size literals;+- inherited model units;+- one solid binding.++## Unsupported constructs++X1 rejects or leaves metadata-only all broader V2 constructs, including `with`, `=>`, `template<Process>`, `concept`, `PMI`, `where`, selectors, regions, cut/add, shell, fillet, chamfer, ruled surfaces, profiles, materials, patterns, multiple solids, expressions, arbitrary units, and parser recovery beyond basic diagnostics.++## Lowering path++The implemented path is:++```text+FirmamentV2 source+ -> FirmamentV2Ast+ -> FirmamentFrontendTraceProbe.ParseV2Only+ -> Feature AIR CreateBox trace summary+```++X1 intentionally stops at Feature AIR for V2. Existing V1 box trace behavior still reaches its established profile-emission evidence separately.++## Fixture changes++`fixtures/FirmamentV2/Primitive/valid/box-v2.valid.firmfixture` is promoted from metadata-only `not-implemented` design intent to `implementation: parser-backed`, `expected-stage: feature-air`, `expected-feature-air: CreateBox`, `dimensions: 10, 8, 6`, and `units: mm`.++New invalid parser-backed pilot fixtures cover missing units, negative size, wrong size arity, and unknown record type under `fixtures/FirmamentV2/Primitive/invalid/`.++## Diagnostics++Stable X1 diagnostics include:++- `firmament-v2-missing-model`;+- `firmament-v2-missing-units`;+- `firmament-v2-missing-solid`;+- `firmament-v2-unsupported-construct`;+- `firmament-v2-unknown-record-type`;+- `firmament-v2-box-missing-size`;+- `firmament-v2-box-size-arity`;+- `firmament-degenerate-dimension`.++## Tests run++Validation for this milestone includes CLI build/help, V2 text and JSON traces, one invalid V2 trace, V1 box and side-hole trace smoke, and focused CLI/kernel/friction-lab filtered test suites. See the PR summary for exact commands and results.++## Next milestone recommendation++Recommended AIR-FIRMAMENT-X2: add a small token/lexer layer and semantic-name checks for V2 while preserving the X1 Feature AIR boundary. Do not broaden into regions, selectors, record derivation, or geometry materialization until the tiny parser contract remains stable across the fixture corpus.diff --git a/fixtures/FirmamentV2/Primitive/invalid/box-v2-missing-units.invalid.firmfixture b/fixtures/FirmamentV2/Primitive/invalid/box-v2-missing-units.invalid.firmfixturenew file mode 100644index 00000000..c2331699--- /dev/null+++ b/fixtures/FirmamentV2/Primitive/invalid/box-v2-missing-units.invalid.firmfixture@@ -0,0 +1,16 @@+// fixture-id: box-v2-missing-units+// case: firmament-v2-box-missing-units+// category: Primitive+// syntax-version: FirmamentV2+// validity: invalid+// implementation: parser-backed+// expected: invalid+// expected-stage: parsed+// expected-diagnostic: firmament-v2-missing-units+// parser-backed: true++model BoxExample {+ solid base: Box {+ size: [10, 8, 6]+ }+}diff --git a/fixtures/FirmamentV2/Primitive/invalid/box-v2-negative-size.invalid.firmfixture b/fixtures/FirmamentV2/Primitive/invalid/box-v2-negative-size.invalid.firmfixturenew file mode 100644index 00000000..15dc2218--- /dev/null+++ b/fixtures/FirmamentV2/Primitive/invalid/box-v2-negative-size.invalid.firmfixture@@ -0,0 +1,18 @@+// fixture-id: box-v2-negative-size+// case: firmament-v2-box-negative-size+// category: Primitive+// syntax-version: FirmamentV2+// validity: invalid+// implementation: parser-backed+// expected: invalid+// expected-stage: parsed+// expected-diagnostic: firmament-degenerate-dimension+// parser-backed: true++model BoxExample {+ units mm++ solid base: Box {+ size: [10, -8, 6]+ }+}diff --git a/fixtures/FirmamentV2/Primitive/invalid/box-v2-size-arity.invalid.firmfixture b/fixtures/FirmamentV2/Primitive/invalid/box-v2-size-arity.invalid.firmfixturenew file mode 100644index 00000000..c38d9b9e--- /dev/null+++ b/fixtures/FirmamentV2/Primitive/invalid/box-v2-size-arity.invalid.firmfixture@@ -0,0 +1,18 @@+// fixture-id: box-v2-size-arity+// case: firmament-v2-box-size-arity+// category: Primitive+// syntax-version: FirmamentV2+// validity: invalid+// implementation: parser-backed+// expected: invalid+// expected-stage: parsed+// expected-diagnostic: firmament-v2-box-size-arity+// parser-backed: true++model BoxExample {+ units mm++ solid base: Box {+ size: [10, 8]+ }+}diff --git a/fixtures/FirmamentV2/Primitive/invalid/box-v2-unknown-record.invalid.firmfixture b/fixtures/FirmamentV2/Primitive/invalid/box-v2-unknown-record.invalid.firmfixturenew file mode 100644index 00000000..0f80370b--- /dev/null+++ b/fixtures/FirmamentV2/Primitive/invalid/box-v2-unknown-record.invalid.firmfixture@@ -0,0 +1,18 @@+// fixture-id: box-v2-unknown-record+// case: firmament-v2-box-unknown-record+// category: Primitive+// syntax-version: FirmamentV2+// validity: invalid+// implementation: parser-backed+// expected: invalid+// expected-stage: parsed+// expected-diagnostic: firmament-v2-unknown-record-type+// parser-backed: true++model BoxExample {+ units mm++ solid base: Cylinder {+ size: [10, 8, 6]+ }+}diff --git a/fixtures/FirmamentV2/Primitive/valid/box-v2.valid.firmfixture b/fixtures/FirmamentV2/Primitive/valid/box-v2.valid.firmfixtureindex 04d033a7..c8c7a9d6 100644--- a/fixtures/FirmamentV2/Primitive/valid/box-v2.valid.firmfixture+++ b/fixtures/FirmamentV2/Primitive/valid/box-v2.valid.firmfixture@@ -3,16 +3,19 @@// category: Primitive// syntax-version: FirmamentV2// validity: valid-// implementation: not-implemented+// implementation: parser-backed// expected: valid-// expected-stage: not-implemented-// expected-diagnostic: firmament-v2-parser-not-ready-// notes: AIR-FIRMAMENT-A2 metadata-only V2 design fixture; source snippet is canonical-shape design, not parser-backed.+// expected-stage: feature-air+// expected-feature-air: CreateBox+// dimensions: 10, 8, 6+// units: mm+// parser-backed: true+// notes: AIR-FIRMAMENT-X1 canonical typed-record V2 Box parser fixture.model BoxExample {units mm- solid base = box {+ solid base: Box {size: [10, 8, 6]}}