Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Refactor STEP body import and topology handling
Yuechen Lifa816fde4d6d
diff --git a/Aetheris.CLI.Tests/FirmamentDomainFrontendCliTests.cs b/Aetheris.CLI.Tests/FirmamentDomainFrontendCliTests.csnew file mode 100644index 00000000..7cd0d092--- /dev/null+++ b/Aetheris.CLI.Tests/FirmamentDomainFrontendCliTests.cs@@ -0,0 +1,44 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class FirmamentDomainFrontendCliTests+{+ [Theory]+ [InlineData("Canonical/Gears/spur-basic.firmament", "UnifiedGear")]+ [InlineData("Canonical/Revolve/partial-quarter.firmament", "UnifiedRevolve")]+ [InlineData("Canonical/SectionChain/two-section-ruled.firmament", "UnifiedSectionChain")]+ public void NormalValidationReportsActualAdmissionAndStructuredDiagnostics(string relative, string route)+ {+ var output = new StringWriter(); var error = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["validate", Fixture(relative), "--explain", "--json"], output, error));+ Assert.Empty(error.ToString());+ using var json = JsonDocument.Parse(output.ToString());+ var report = json.RootElement.GetProperty("firmamentV2Validation");+ Assert.Equal("valid", report.GetProperty("status").GetString());+ Assert.Equal("Built", report.GetProperty("validationLevel").GetString());+ Assert.Equal(route, report.GetProperty("parserRoute").GetString());+ Assert.All(report.GetProperty("diagnostics").EnumerateArray(), item => Assert.Equal(JsonValueKind.Object, item.ValueKind));+ }++ [Fact]+ public void GearTrainCannotClaimNormalSingleBodyBuildAdmission()+ {+ var output = new StringWriter();+ Assert.Equal(1, CliRunner.Run(["validate", Fixture("Canonical/GearInterfaces/spur-pair.firmament"), "--json"], output, new StringWriter()));+ using var json = JsonDocument.Parse(output.ToString());+ var report = json.RootElement.GetProperty("firmamentV2Validation");+ Assert.Equal("invalid", report.GetProperty("status").GetString());+ Assert.Equal("BuildRejected", report.GetProperty("validationLevel").GetString());+ Assert.Contains(report.GetProperty("diagnostics").EnumerateArray(), item =>+ item.GetProperty("code").GetString() == "firmament-gear-build-body-count-invalid"+ && item.GetProperty("message").GetString()!.Contains("use-Assembly", StringComparison.Ordinal));+ }++ private static string Fixture(string relative)+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ return Path.Combine(directory?.FullName ?? throw new DirectoryNotFoundException(), "fixtures", relative);+ }+}diff --git a/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs b/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.csindex c5a5b2f9..b1822397 100644--- a/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs+++ b/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs@@ -163,7 +163,7 @@ public sealed class FirmamentFixtureCorpusTestsif (metadata.TryGetValue("expected-diagnostic", out var expectedValidationDiagnostic)) Assert.Contains(expectedValidationDiagnostic, diagnostics);// The public report itself proves V2 routing. Successful parser trace events// are intentionally filtered from user-facing diagnostics.- Assert.All(diagnostics, code => Assert.StartsWith("firmament-v2-", code, StringComparison.Ordinal));+ Assert.Equal("V2", validation.GetProperty("languageVersion").GetString());Assert.DoesNotContain("air-x11-firmament-parse-failed", diagnostics);continue;}@@ -302,7 +302,7 @@ public sealed class FirmamentFixtureCorpusTestsvar expected = new[]{(Path: "Compatibility/LegacyAliases/Invalid/RecordDerivation/with-degenerate-box-v2.invalid.firmfixture", Diagnostic: "firmament-degenerate-dimension"),- (Path: "Compatibility/LegacyAliases/Invalid/RecordDerivation/with-selector-target-v2.invalid.firmfixture", Diagnostic: "firmament-v2-with-requires-record"),+ (Path: "Compatibility/LegacyAliases/Invalid/RecordDerivation/with-selector-target-v2.invalid.firmfixture", Diagnostic: "firmament-syntax-statement"),(Path: "Compatibility/LegacyAliases/Invalid/RecordDerivation/with-unknown-field-v2.invalid.firmfixture", Diagnostic: "firmament-v2-with-field-not-found")};diff --git a/Aetheris.CLI.Tests/RevolveCliTests.cs b/Aetheris.CLI.Tests/RevolveCliTests.csindex ea282d9b..48becfe1 100644--- a/Aetheris.CLI.Tests/RevolveCliTests.cs+++ b/Aetheris.CLI.Tests/RevolveCliTests.cs@@ -31,7 +31,7 @@ public sealed class RevolveCliTestsusing var json = JsonDocument.Parse(output.ToString());var validation = json.RootElement.GetProperty("firmamentV2Validation");Assert.Equal("invalid", validation.GetProperty("status").GetString());- Assert.Contains(validation.GetProperty("diagnostics").EnumerateArray(), item => item.GetString() == "firmament-revolve-zero-angle:Bad");+ Assert.Contains(validation.GetProperty("diagnostics").EnumerateArray(), item => item.GetProperty("code").GetString() == "firmament-revolve-zero-angle:Bad");}private static string Fixture(string relative) => Path.Combine(Repo, "fixtures", relative.Replace('/', Path.DirectorySeparatorChar));diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 01ab78ce..2ffcd444 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -2416,34 +2416,16 @@ Model CanonicalPanel {}if (frontend.Schema == FirmamentFrontendSchema.SectionChain){- var section = SectionChainAuthoringParser.CompileFile(sourcePath);- var payload = new { source = sourcePath, status = section.IsSuccess ? "valid" : "invalid", domain = "SectionChain", summary = new { fatalDiagnosticCount = section.Diagnostics.Count, warningDiagnosticCount = 0, sections = section.Chain?.Sections.Count ?? 0 }, diagnostics = section.Diagnostics };+ var section = SectionChainAuthoringParser.CompileFile(sourcePath, materialize: !parseOnly);+ var diagnostics = section.Diagnostics.Select(message => FirmamentBuildAdmissionValidation.Present(new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, "Firmament.SectionChain"), sourcePath, validationSource)).ToArray();+ var payload = new { source = sourcePath, status = section.IsSuccess ? (parseOnly ? "parsed-not-built" : "valid") : "invalid", domain = "SectionChain",+ validationLevel = section.IsSuccess ? (parseOnly ? "ParsedNotBuilt" : "Built") : "BuildRejected", parserRoute = "UnifiedSectionChain",+ summary = new { fatalDiagnosticCount = diagnostics.Length, warningDiagnosticCount = 0, sections = section.Chain?.Sections.Count ?? 0 }, diagnostics };if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));else stdout.WriteLine($"Firmament V2 SectionChain validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");return section.IsSuccess ? 0 : 1;}- if (GearAuthoring.IsGearSource(validationSource))- {- var gear = GearAuthoring.Parse(validationSource);- var payload = new { source = sourcePath, status = gear.IsSuccess ? "valid" : "invalid", domain = "GearLibrary",- summary = new { fatalDiagnosticCount = gear.Diagnostics.Count, warningDiagnosticCount = 0, gears = gear.Gears.Count, interfaces = gear.Interfaces.Count },- gears = gear.Gears, interfaces = gear.Interfaces, diagnostics = gear.Diagnostics };- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));- else stdout.WriteLine($"Firmament Gear validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");- return gear.IsSuccess ? 0 : 1;- }- if (RevolveAuthoringParser.IsRevolveSource(validationSource))- {- var revolve = RevolveAuthoringParser.Parse(validationSource, out var bindDiagnostics);- var materializationDiagnostics = revolve is null ? [] : ResolvedProfileRevolveEmitter.TryEmit(revolve).Diagnostics;- var diagnostics = bindDiagnostics.Concat(materializationDiagnostics.Where(message => message.StartsWith(RevolveAuthoringParser.Prefix, StringComparison.Ordinal))).Distinct(StringComparer.Ordinal).ToArray();- var valid = revolve is not null && diagnostics.Length == 0;- var payload = new { source = sourcePath, status = valid ? "valid" : "invalid", domain = "Revolve",- summary = new { fatalDiagnosticCount = diagnostics.Length, warningDiagnosticCount = 0 }, diagnostics };- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));- else stdout.WriteLine($"Firmament V2 Revolve validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");- return valid ? 0 : 1;- }if (WireFormAuthoring.IsWireFormSource(validationSource)){var wireSource = ExpandSweepInspectionSource(validationSource, out var expansionDiagnostics);diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentCompatibilityAstMigrationTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentCompatibilityAstMigrationTests.csnew file mode 100644index 00000000..10390cf3--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentCompatibilityAstMigrationTests.cs@@ -0,0 +1,147 @@+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentCompatibilityAstMigrationTests+{+ [Theory]+ [InlineData("Box", "size: [30,24,12]", "size: [30mm,24mm,12mm]")]+ [InlineData("Cylinder", "radius: 4 height: 12", "radius: 4mm height: 12mm")]+ [InlineData("Cone", "bottomRadius: 4 topRadius: 2 height: 12", "bottomRadius: 4mm topRadius: 2mm height: 12mm")]+ [InlineData("Sphere", "radius: 4", "radius: 4mm")]+ [InlineData("Torus", "majorRadius: 8 minorRadius: 2", "majorRadius: 8mm minorRadius: 2mm")]+ public void CompatibilitySolids_UseNativeBindingAndPreserveStep(string type, string legacyFields, string fields)+ {+ var legacy = $"model Witness {{ units mm solid stock: {type} {{ {legacyFields} }} }}";+ var native = $"Model Witness {{ units: mm {type} stock {{ {fields} }} }}";+ var syntax = FirmamentSyntaxParser.Parse(legacy);+ Assert.True(syntax.IsSuccess);+ var parsed = FirmamentV2Parser.Parse(legacy);+ Assert.True(parsed.IsSuccess, string.Join("; ", parsed.Diagnostics));+ Assert.Equal("UnifiedCompatibility", parsed.ParserRoute);+ var built = FirmamentBuildAndExport.CompileSource(legacy);+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ Assert.Equal(FirmamentBuildAndExport.CompileSource(native).Value.StepText, built.Value.StepText);+ Assert.Equal("valid", FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(parsed), legacy).Status);+ }++ [Theory]+ [InlineData("solid stock: Box { size: [30,24,12] } Use Ignored.Module;", "Use")]+ [InlineData("solid stock: Box { size: [30,24,12] heigth: 20 }", "heigth")]+ [InlineData("solid stock: Box { size: [30,24,12] Fillet lost { radius: 1 } }", "Fillet")]+ [InlineData("solid stock: Box { size: [30,24,12] } Fillet lost { radius: 1 }", "Fillet")]+ [InlineData("solid stock: Box { size: [30,24,12] } modify stock { Fillet lost { radius: 1 } }", "Fillet")]+ [InlineData("solid stock: Box { size: [30,24,12] } modify stock { hole<shaft> bore { on: face(+Z) center: [0,0] diameter: 4 end: throughAll heigth: 2 } }", "heigth")]+ public void UnknownIntent_FailsBothPathsWithOriginalLocation(string body, string token)+ {+ var source = "model Witness { units mm " + body + " }";+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.False(parsed.IsSuccess);+ Assert.Equal("UnifiedCompatibility", parsed.ParserRoute);+ var report = FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(parsed, "compat.firmament"), source);+ Assert.Equal("invalid", report.Status);+ Assert.Contains(report.Diagnostics, d => d.SourceSpan is { } span && source.Substring(span.Start, span.Length) == token);+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);+ }++ [Theory]+ [InlineData("modify stock = 4 { }")]+ [InlineData("modify stock -> Box { }")]+ [InlineData("modify stock { hole<kind: Shaft> bore { on: face(+Z) center: [0,0] diameter: 4 end: throughAll } }")]+ public void UnsupportedHeaders_CannotBeDiscarded(string modification)+ {+ var source = "model Witness { units mm solid stock: Box { size: [30,24,12] } " + modification + " }";+ Assert.False(FirmamentV2Parser.Parse(source).IsSuccess);+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);+ }++ [Theory]+ [InlineData("radius: 1 center: [0,0] through: face(-X) heigth: 20")]+ [InlineData("radius: 1 center: [0,0] through: face(-X) Fillet lost { radius: 1 }")]+ public void RegionCut_ClosesItsActualFields(string body)+ {+ var source = "model Witness { units mm solid stock: Box { size: [30,24,12] } modify stock { region sideHole on face(+X) { cut Cylinder { " + body + " } } } }";+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.False(parsed.IsSuccess);+ Assert.Equal("UnifiedCompatibility", parsed.ParserRoute);+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);+ }++ [Fact]+ public void IncidentalConceptText_CannotChooseAnotherFrontend()+ {+ const string source = "model Witness { units mm solid stock: Box { size: [30,24,12] } note: \"Concept Struct Ghost\" }";+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.False(parsed.IsSuccess);+ Assert.Equal("UnifiedCompatibility", parsed.ParserRoute);+ Assert.Contains(parsed.Diagnostics, d => d.EndsWith(":Model:note", StringComparison.Ordinal));+ }++ [Fact]+ public void DerivedRecords_RemainImmutableAndCloseTheirFields()+ {+ const string source = "model Witness { units mm solid stock: Box { size: [10,8,6] } solid tall: stock with { size: [10,8,12] } }";+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.True(parsed.IsSuccess, string.Join("; ", parsed.Diagnostics));+ Assert.Equal([10d, 8d, 6d], parsed.Document!.Solids[0].Box!.Size);+ Assert.Equal([10d, 8d, 12d], parsed.Document.Solids[1].Box!.Size);+ Assert.Equal("stock", parsed.Document.Solids[1].DerivedFrom);+ Assert.False(FirmamentV2Parser.Parse(source.Replace("size: [10,8,12]", "size: [10,8,12] heigth: 20")).IsSuccess);+ }++ [Fact]+ public void LowercaseAlias_PreservesProfileIdentityAndGeometry()+ {+ const string source = """+ Model Witness {+ units: mm+ Rect2 guide { center: [0mm,0mm]; size: [12mm,8mm] }+ Profile outline { guide.Bottom as south |> guide.Right as east |> guide.Top as north |> guide.Left as west |> Close }+ Extrude stock { profile: outline; from: 0mm; to: 4mm }+ }+ """;+ var syntax = FirmamentSyntaxParser.Parse(source);+ Assert.True(syntax.IsSuccess);+ Assert.Equal(["south", "east", "north", "west"], FirmamentSyntaxTraversal.Expressions(syntax.Document).OfType<AliasSyntax>().Select(a => a.Name.Text));+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.True(parsed.IsSuccess, string.Join("; ", parsed.Diagnostics));+ var lower = FirmamentBuildAndExport.CompileSource(source);+ var upper = FirmamentBuildAndExport.CompileSource(source.Replace(" as ", " As "));+ Assert.True(lower.IsSuccess, string.Join("; ", lower.Diagnostics.Select(d => d.Message)));+ Assert.Equal(upper.Value.StepText, lower.Value.StepText);+ Assert.Equal(source, FirmamentSourceSpelling.Prefer(source.Replace(" as ", " As ")));+ Assert.Equal(FirmamentSourceSpelling.Normalize(source), FirmamentSourceSpelling.Normalize(FirmamentSourceSpelling.Prefer(source)));+ }++ [Fact]+ public void DepthParameter_RemainsAnOrdinaryValueOutsideLegacyEnd()+ {+ const string source = "Feature Make(depth: Length) -> Boss { return Boss { size: [10mm, depth]; height: depth - 1mm } }";+ var syntax = FirmamentSyntaxParser.Parse(source);+ Assert.True(syntax.IsSuccess, string.Join("; ", syntax.Diagnostics.Select(d => d.Message)));+ var values = FirmamentSyntaxTraversal.Expressions(syntax.Document).OfType<ReferenceSyntax>().Where(r => r.Name.Text == "depth").ToArray();+ Assert.Equal(2, values.Length);+ Assert.DoesNotContain(FirmamentSyntaxTraversal.Expressions(syntax.Document), e => e is CallSyntax { Target: ReferenceSyntax { Name.Text: "depth" } });+ }++ [Fact]+ public void AliasFormatting_NeverRenamesAuthoredAsSymbols()+ {+ const string source = "Model As { units: mm Box as { size: [10mm,8mm,6mm] } }\nRecord Spec { As: Length }\nStatic data: Spec { As: 2mm }\n// guide As alias\n";+ Assert.Equal(source, FirmamentSourceSpelling.Prefer(source));+ }++ [Theory]+ [InlineData("=>")]+ [InlineData("as")]+ public void ExposureAliases_PreserveFaceAndHoleIntent(string link)+ {+ var source = $"model Witness {{ units mm solid stock: Box {{ size: [30,24,12] expose {{ face(+Z) {link} top }} }} modify stock {{ hole<shaft> bore {{ on: top center: [0,0] diameter: 4 end: throughAll }} }} }}";+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.True(parsed.IsSuccess, string.Join("; ", parsed.Diagnostics));+ Assert.Equal("top", Assert.Single(parsed.Document!.Solid.Box!.Exposures).Alias);+ Assert.Equal("+Z", Assert.Single(Assert.Single(parsed.Document.ModifyBlocks!).SemanticHoles).EntryFace.Axis);+ Assert.True(FirmamentBuildAndExport.CompileSource(source).IsSuccess);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentDomainFrontendMigrationTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentDomainFrontendMigrationTests.csnew file mode 100644index 00000000..e27b1208--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentDomainFrontendMigrationTests.cs@@ -0,0 +1,206 @@+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentDomainFrontendMigrationTests+{+ [Theory]+ [InlineData("Gear", "heigth: 10mm")]+ [InlineData("Gear", "Module: 2mm")]+ [InlineData("Gear", "Fillet Lost { Radius: 1mm }")]+ [InlineData("Revolve", "heigth: 10mm")]+ [InlineData("Revolve", "Angle: half")]+ [InlineData("Revolve", "Fillet Lost { Radius: 1mm }")]+ [InlineData("Panel", "heigth: 10mm")]+ [InlineData("Panel", "Thickness: 2mm; Thickness: 3mm")]+ [InlineData("Panel", "Fillet Lost { Radius: 1mm }")]+ public void UnconsumedDomainIntentRejectsParsingValidationAndBuild(string kind, string intent)+ {+ var source = Source(kind).Replace("// intent", intent, StringComparison.Ordinal);+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.False(parsed.IsSuccess);+ Assert.StartsWith("Unified", parsed.ParserRoute);+ var build = FirmamentBuildAndExport.CompileSource(source);+ Assert.False(build.IsSuccess);+ var validation = FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(parsed, sourceText: source), source);+ Assert.Equal("invalid", validation.Status);+ Assert.Contains(validation.Diagnostics, d => d.Severity == "fatal" && d.SourceSpan is not null);+ }++ [Theory]+ [InlineData("Gear", "Module: 2mm", "Module: 2mm + 1")]+ [InlineData("Gear", "Axis: [0,0,1]", "Axis: Unknown")]+ [InlineData("Gear", "Teeth: 24", "Teeth: 24.5")]+ [InlineData("Revolve", "Angle: full", "Angle: full + 1mm")]+ [InlineData("Revolve", "Revolve Turn", "Revolve Turn On XZ")]+ [InlineData("Revolve", "Direction: [0,1,0]", "Direction: [0,1,0]; rotaton: 90deg")]+ [InlineData("Panel", "Rise: 6mm", "Rise: 6mm; heigth: 1mm")]+ [InlineData("Panel", "// intent", "Orientation: 2mm")]+ public void DomainValuesAndFramesCannotSilentlyDefault(string kind, string before, string after)+ {+ var source = Source(kind).Replace(before, after, StringComparison.Ordinal);+ Assert.False(FirmamentV2Parser.Parse(source).IsSuccess);+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);+ }++ [Fact]+ public void WrapperFreeRevolveRetainsAdmissionAndIdenticalGeometry()+ {+ var wrapped = Source("Revolve");+ var standalone = wrapped.Replace("Model Ring { Units: mm;", "", StringComparison.Ordinal);+ standalone = standalone[..standalone.LastIndexOf('}')];+ var first = FirmamentBuildAndExport.CompileSource(wrapped);+ var second = FirmamentBuildAndExport.CompileSource(standalone);+ Assert.True(first.IsSuccess, string.Join("\n", first.Diagnostics));+ Assert.True(second.IsSuccess, string.Join("\n", second.Diagnostics));+ Assert.Equal(first.Value.StepText, second.Value.StepText);+ Assert.True(second.Value.Revolve!.StepReimportedManifold);+ Assert.Equal("UnifiedRevolve", FirmamentV2Parser.Parse(standalone).ParserRoute);+ Assert.False(FirmamentBuildAndExport.CompileSource(standalone + "\nRevolve Other { Profile: Section; About: Axis; Angle: half }").IsSuccess);+ }++ [Fact]+ public void GearDimensionalExpressionsAndFieldAliasesRetainGeometry()+ {+ var source = Source("Gear");+ var equivalent = source.Replace("Module: 2mm", "module: 1mm * 2", StringComparison.Ordinal);+ var first = FirmamentBuildAndExport.CompileSource(source); var second = FirmamentBuildAndExport.CompileSource(equivalent);+ Assert.True(first.IsSuccess); Assert.True(second.IsSuccess);+ Assert.Equal(first.Value.StepText, second.Value.StepText);+ Assert.Equal("UnifiedGear", FirmamentV2Parser.Parse(equivalent).ParserRoute);+ }++ [Fact]+ public void MultipleGearDefinitionsAreInspectableButNormalValidationDoesNotPromiseSingleBodyBuild()+ {+ var source = FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/GearInterfaces/spur-pair.firmament");+ Assert.True(GearAuthoring.Parse(source).IsSuccess);+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.True(parsed.IsSuccess);+ var report = FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(parsed, sourceText: source), source);+ Assert.Equal("invalid", report.Status); Assert.Equal("BuildRejected", report.ValidationLevel);+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);+ Assert.Contains(report.Diagnostics, d => d.Message.Contains("use-Assembly", StringComparison.Ordinal));+ }++ [Theory]+ [InlineData("solid-loft-common-ray.firmament", "Reference: [1, 0, 0]", "Reference: [1, 0, 0]; heigth: 1mm")]+ [InlineData("solid-loft-common-ray.firmament", "Reference: [1, 0, 0]", "Reference: [1, 0, 0]; Fillet Lost { Radius: 1mm }")]+ [InlineData("solid-loft-common-ray.firmament", "Rule: Ruled", "Rule: Ruled; Rule: Other")]+ [InlineData("solid-loft-common-ray.firmament", "Loft Body", "Loft<policy: Hollow> Body")]+ [InlineData("two-section-ruled.firmament", "Transition: Ruled", "Transition: Ruled; heigth: 1mm")]+ [InlineData("two-section-ruled.firmament", "Transition: Ruled", "Transition: 1mm")]+ [InlineData("two-section-ruled.firmament", "Start: Cap", "Start: 1mm")]+ [InlineData("two-section-ruled.firmament", "Seam: Bottom", "Seam: 1mm")]+ [InlineData("two-section-ruled.firmament", "Seam: Bottom", "Seam: Bottom; heigth: 1mm")]+ [InlineData("two-section-ruled.firmament", "Seam: Bottom", "Seam: Bottom; Fillet Lost { Radius: 1mm }")]+ public void SectionOwnersConsumeAllFieldsAndStatements(string file, string before, string after)+ {+ var source = FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/SectionChain/" + file).Replace(before, after, StringComparison.Ordinal);+ Assert.False(SectionChainAuthoringParser.Compile(source, materialize: false).IsSuccess);+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.False(parsed.IsSuccess); Assert.Equal("UnifiedSectionChain", parsed.ParserRoute);+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);+ }++ [Fact]+ public void LegacyUnitHeaderUsesMechanicalAstAndRetainsExactStep()+ {+ var header = FirmamentCorpusHarness.ReadFixtureText("fixtures/Regression/FrontendMigration/legacy-unit-header.firmament");+ var explicitBody = "Model Old { Units: mm; " + header[(header.IndexOf('\n') + 1)..] + " }";+ var first = FirmamentBuildAndExport.CompileSource(header); var second = FirmamentBuildAndExport.CompileSource(explicitBody);+ Assert.True(first.IsSuccess); Assert.True(second.IsSuccess);+ Assert.Equal(first.Value.StepText, second.Value.StepText);+ Assert.Equal("UnifiedMechanical", FirmamentV2Parser.Parse(header).ParserRoute);+ Assert.False(FirmamentBuildAndExport.CompileSource(header + "\nFillet Lost { Radius: 1mm }").IsSuccess);+ }++ [Fact]+ public void NamedSurfaceSectionSyntaxPreservesIdentityWithoutCapturingWith()+ {+ var syntax = FirmamentSyntaxParser.Parse(FirmamentCorpusHarness.ReadFixtureText("fixtures/Regression/FrontendMigration/named-surface-section-syntax.firmament"));+ Assert.True(syntax.IsSuccess, string.Join("\n", syntax.Diagnostics));+ var items = Assert.IsType<SequenceSyntax>(Assert.Single(syntax.Document.Statements.OfType<DeclarationSyntax>()).Initializer).Items;+ Assert.Equal(["S0", "S1"], items.Select(i => Assert.IsType<ObjectSyntax>(i.Value).Name!.Text));+ Assert.IsType<WithSyntax>(FirmamentSyntaxParser.ParseExpression("Base with { Size: [1mm,2mm,3mm] }").Expression);+ }++ [Fact]+ public void SurfaceExpressionMigrationPreservesWorldPointsAndBoundaryIdentities()+ {+ var parsed = FirmamentV2Parser.Parse(FirmamentCorpusHarness.ReadFixtureText("fixtures/Regression/FrontendMigration/panel-parametric.firmament"));+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));+ var panel = Assert.Single(parsed.Document!.Panels!);+ Assert.Equal("panel:Saddle", panel.StableId);+ Assert.Equal("Back", panel.Orientation.MaterialSide.ToString());+ Assert.Equal(["West", "North", "East", "South"], panel.BoundaryEdges.Select(edge => edge.Name));+ foreach (var u in new[] { -1d, 0d, 1d })+ foreach (var v in new[] { -1d, 0d, 1d })+ {+ var point = panel.AuthoredPatch.EvaluatePoint(u, v);+ Assert.Equal(point, panel.SurfaceConstruction.Evaluate((u + 1) / 2, (v + 1) / 2));+ Assert.Equal(20 * u, point.X, 9);+ Assert.Equal(15 * v, point.Y, 9);+ Assert.Equal(6 * u * v, point.Z, 9);+ }+ }++ [Fact]+ public void GearDefinitionExtractionLeavesAssemblyRequirementsWithTheirOwner()+ {+ var source = FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/AssemblyInterfaces/gear-with-ordinary-part.firmament")+ + "\nInterface<Axial> OptionalCapability { Role A requires AxisCapable; Role B requires AxisCapable; }";+ var definitions = GearAuthoring.ParseDefinitions(source);+ Assert.True(definitions.IsSuccess, string.Join("\n", definitions.Diagnostics));+ Assert.Single(definitions.Gears);+ var assembly = new Aetheris.Kernel.Firmament.Assembly.AssemblyM0Parser().Parse(source);+ Assert.True(assembly.IsSuccess, string.Join("\n", assembly.Diagnostics));+ Assert.False(GearAuthoring.Parse(source).IsSuccess);+ }++ [Theory]+ [InlineData("Gear", "GearModel")]+ [InlineData("Panel", "PanelModel")]+ public void CompileTimeDefinitionsDoNotBecomeTheDisplayedModelOwner(string kind, string owner)+ {+ var source = "Concept Struct ConstructionData { Origin: Point3(0mm,0mm,0mm) }\n" + Source(kind);+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));+ Assert.Equal(owner, parsed.Document!.ModelName);+ if (kind == "Gear")+ {+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics));+ Assert.Equal(FirmamentBuildAndExport.CompileSource(Source(kind)).Value.StepText, built.Value.StepText);+ }+ }++ [Theory]+ [InlineData("WireForm")]+ [InlineData("Sweep")]+ [InlineData("Plateau")]+ public void AdmittedAstCannotBeReroutedByConstructTextInComments(string domain)+ {+ var source = FirmamentCorpusHarness.ReadFixtureText("fixtures/Regression/FrontendMigration/incidental-domain-text.firmament").Replace("$domain", domain, StringComparison.Ordinal);+ var plain = source[..source.IndexOf("/*", StringComparison.Ordinal)];+ var first = FirmamentBuildAndExport.CompileSource(plain); var second = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(first.IsSuccess, string.Join("\n", first.Diagnostics));+ Assert.True(second.IsSuccess, string.Join("\n", second.Diagnostics));+ Assert.Equal("UnifiedMechanical", FirmamentV2Parser.Parse(source).ParserRoute);+ Assert.Equal(first.Value.StepText, second.Value.StepText);+ }++ [Theory]+ [InlineData("Width: 2mm", "Width: 2mm; heigth: 1mm")]+ [InlineData("Width: 2mm", "Width: 2mm; Fillet Lost { Radius: 1mm }")]+ [InlineData("Plateau Raised", "Plateau Raised On XZ")]+ public void PlateauIntentIsBoundBeforeItsAdmittedBaseCanExecute(string before, string after)+ {+ var source = FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/Surfacing/g2-planar-plateau.firmament").Replace(before, after, StringComparison.Ordinal);+ Assert.False(FirmamentV2Parser.Parse(source).IsSuccess);+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);+ }++ private static string Source(string kind) => FirmamentCorpusHarness.ReadFixtureText("fixtures/Regression/FrontendMigration/" + kind.ToLowerInvariant() + ".firmament");+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2DiagnosticRoutingBuildTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2DiagnosticRoutingBuildTests.csindex 0a3adaee..f562b0a8 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2DiagnosticRoutingBuildTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2DiagnosticRoutingBuildTests.cs@@ -27,7 +27,7 @@ model Broken {Model Broken mmBox Base { Size: [10mm, 10mm] }Modify Base { EdgeFinish Break { Face: +Z Target: Boundary Kind: Chamfer Distance: 1mm } }-""", FirmamentV2Parser.Phase3EdgeFinishSyntaxInvalid)]+""", FirmamentV2Parser.CanonicalPrimitiveMalformed)]public void Build_RecognizedMalformedLowercaseAndPascalCaseModel_ReturnsV2Diagnostics(string source, string expectedDiagnostic){var path = Path.Combine(Path.GetTempPath(), $"aetheris-v2-diagnostic-routing-{Guid.NewGuid():N}.firmament");diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 0211fbc3..5f0516b7 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -268,30 +268,16 @@ public static class FirmamentBuildAndExportbool allowV1Compatibility = false,FirmamentFrontendSchema? explicitSchema = null){- if (GearAuthoring.IsGearSource(sourceText))- {- return ExportGearSource(sourceText);- }- if (explicitSchema == FirmamentFrontendSchema.SectionChain)- {- var authored = SectionChainAuthoringParser.Compile(sourceText);- if (!authored.IsSuccess || authored.Materialization?.Body is null)- return KernelResult<FirmamentStepExportResult>.Failure(authored.Diagnostics.Select(SchemaDiagnostic).ToArray());- var step = Step242Exporter.ExportBody(authored.Materialization.Body, new Step242ExportOptions { ProductName = authored.Chain!.StableId });- return step.IsSuccess- ? KernelResult<FirmamentStepExportResult>.Success(new(step.Value, authored.Chain!.StableId, 0, "section-chain", "section-chain"))- : KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);- }// Production mechanical execution consumes the result of AST admission.- // Its expansion pipeline runs once in the frontend. Other domain owners keep- // their existing expansion boundary until their own mechanical migration.+ // Its expansion pipeline runs once in the frontend. Unmigrated domain owners+ // retain their existing expansion boundary until their own cutover.sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);var canonicalParseWatch = System.Diagnostics.Stopwatch.StartNew();var v2Parse = FirmamentV2Parser.Parse(sourceText, sourceDirectory);canonicalParseWatch.Stop();var templateBindWatch = new System.Diagnostics.Stopwatch();string materializerSource;- if (v2Parse.ParserRoute == "UnifiedMechanical")+ if (v2Parse.OwnsUnifiedAdmission){if (!v2Parse.IsSuccess) return V2ParseFailure(v2Parse);materializerSource = v2Parse.BoundSource!;@@ -338,17 +324,25 @@ public static class FirmamentBuildAndExportvar materializerInput = staticExpansion.Source;materializerSource = FirmamentV2Parser.TryGetCanonicalAdvancedBody(materializerInput, out var canonicalBody) ? canonicalBody : materializerInput;}- if (PlateauAuthoring.IsSource(materializerSource))+ if (v2Parse.BoundSectionChain?.Chain is { } chain)+ {+ var materialized = Aetheris.Surfacing.SectionChainMaterializer.Materialize(chain);+ if (!materialized.IsSuccess || materialized.Body is null)+ return KernelResult<FirmamentStepExportResult>.Failure(materialized.Diagnostics.Select(d => SchemaDiagnostic(d.Code + ":" + d.Message)).ToArray());+ var step = Step242Exporter.ExportBody(materialized.Body, new Step242ExportOptions { ProductName = chain.StableId });+ return step.IsSuccess+ ? KernelResult<FirmamentStepExportResult>.Success(new(step.Value, chain.StableId, 0, "section-chain", "section-chain"))+ : KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);+ }+ if (v2Parse.BoundGear is { } gear) return ExportGear(gear);+ if (v2Parse.BoundPlateau is not null || !v2Parse.OwnsUnifiedAdmission && PlateauAuthoring.IsSource(materializerSource)){if (!v2Parse.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(v2Parse.Diagnostics.Select(SchemaDiagnostic).ToArray());- return PlateauAuthoring.Compile(materializerSource);+ return PlateauAuthoring.Compile(materializerSource, v2Parse.BoundPlateau, v2Parse.BoundProfile, v2Parse.ExtrusionHeight);}- if (RevolveAuthoringParser.IsRevolveSource(materializerSource))+ if (v2Parse.BoundRevolve is { } boundRevolve){- var authored = RevolveAuthoringParser.Parse(materializerSource, out var revolveDiagnostics);- if (authored is null)- return KernelResult<FirmamentStepExportResult>.Failure(revolveDiagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(- Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "FirmamentV2.Revolve")).ToArray());+ var authored = boundRevolve;var built = ResolvedProfileRevolveEmitter.TryEmit(authored);if (!built.Succeeded || built.Body is null || built.Plan is null)return KernelResult<FirmamentStepExportResult>.Failure(built.Diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(@@ -376,7 +370,7 @@ public static class FirmamentBuildAndExportEngineeringFeatures: [new(authored.Name, "Revolve", authored.StableId, authored.Name, authored.Axis.StableId, authored.Profile.Name,authored.SweepRadians, "SweepRadians", "Base", PolicySource: "ResolvedProfileRevolveEmitter", MaterializationRoute: "RevolveBRepPlan")]));}- if (explicitSchema == FirmamentFrontendSchema.WireForm || WireFormAuthoring.IsWireFormSource(materializerSource))+ if (explicitSchema == FirmamentFrontendSchema.WireForm || !v2Parse.OwnsUnifiedAdmission && WireFormAuthoring.IsWireFormSource(materializerSource)){var parsePhase = BuildPerfTrace.Phase("firmament.wire-parse-and-bind");var authored = WireFormAuthoring.Parse(materializerSource);@@ -410,7 +404,7 @@ public static class FirmamentBuildAndExportPolicySource: "WireFormFeatureAir", MaterializationRoute: "WireFormCenterlineAir->CircularSweepBRepPlan")).ToArray()){ RuntimeBody = reimport.Value }, []);}- if (explicitSchema == FirmamentFrontendSchema.Sweep || CircularSweepAuthoring.IsSweepSource(materializerSource))+ if (explicitSchema == FirmamentFrontendSchema.Sweep || !v2Parse.OwnsUnifiedAdmission && CircularSweepAuthoring.IsSweepSource(materializerSource)){var airWatch = System.Diagnostics.Stopwatch.StartNew();var authored = CircularSweepAuthoring.Parse(materializerSource);@@ -451,7 +445,7 @@ public static class FirmamentBuildAndExportauthored.Value.Path.StableId, "Circle", authored.Value.Diameter, "Diameter", "Add", PolicySource: "CircularSweepFeatureAir", MaterializationRoute: "CircularSweepBRepPlan")]),[]);}- if (v2Parse.BoundComposition is not null || (v2Parse.ParserRoute != "UnifiedMechanical" && PrismaticProfileCompositionParser.IsCompositionSource(materializerSource)))+ if (v2Parse.BoundComposition is not null || (!v2Parse.OwnsUnifiedAdmission && PrismaticProfileCompositionParser.IsCompositionSource(materializerSource))){var parsed = v2Parse.BoundComposition ?? PrismaticProfileCompositionParser.Parse(materializerSource);var stack = PrismaticSectionStackCompiler.Normalize(parsed, out var diagnostics);@@ -494,7 +488,7 @@ public static class FirmamentBuildAndExportFeatures: CompositionHoleReports(stack.Feature),EngineeringFeatures: EngineeringFeatureReports(stack.Feature)));}- if (v2Parse.BoundProfile is not null || (v2Parse.ParserRoute != "UnifiedMechanical" && ProfileAuthoringParser.IsProfileSource(materializerSource)))+ if (v2Parse.BoundProfile is not null || (!v2Parse.OwnsUnifiedAdmission && ProfileAuthoringParser.IsProfileSource(materializerSource))){var parsed = v2Parse.BoundProfile is { } boundProfile? (Profile: (ResolvedProfile2D?)boundProfile, Height: v2Parse.ExtrusionHeight, Diagnostics: (IReadOnlyList<string>)[])@@ -675,9 +669,8 @@ public static class FirmamentBuildAndExportreturn ExportV1CompatibilitySource(sourceText);}- private static KernelResult<FirmamentStepExportResult> ExportGearSource(string sourceText)+ private static KernelResult<FirmamentStepExportResult> ExportGear(GearAuthoringDocument authored){- var authored = GearAuthoring.Parse(sourceText);if (!authored.IsSuccess)return KernelResult<FirmamentStepExportResult>.Failure(authored.Diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.csindex 56cf3849..6a3fccde 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs@@ -98,7 +98,7 @@ internal static class ClosedBoundary2Authoring}private static IEnumerable<DeclarationSyntax> BoundaryDeclarations(DocumentSyntax syntax) =>- FirmamentSyntaxEvidence.Declarations(syntax)+ FirmamentSyntaxTraversal.Declarations(syntax).Where(d => d.Name is not null && d.Body is not null && !d.Modifiers.Any(m => m.Name.Text == "Concept")&& d.Type.Name.Text is "Rect2" or "Square2" or "Circle2" or "Ellipse2" or "Slot2" or "RoundedRect2" or "SmoothRoundedRect2" or "Triangle2" or "Polygon2" or "RegularPolygon2");diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.csindex 2ae4f742..35992499 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs@@ -252,7 +252,7 @@ internal static class ConceptIrResolvervar allInstances = instanceList.ToDictionary(i => i.Name, StringComparer.Ordinal);var boxBody = source[(boxOpen + 1)..boxClose];- var syntaxDeclarations = FirmamentSyntaxEvidence.Declarations(FirmamentSyntaxParser.Parse(source).Document).ToArray();+ var syntaxDeclarations = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).ToArray();var boxSyntax = syntaxDeclarations.FirstOrDefault(d => d.Type.Name.Text == "Box" && d.Body?.Span.Start == boxOpen);if (boxSyntax is null) { diagnostics.Add(FirmamentV2Parser.CanonicalPrimitiveMalformed); return null; }var boxFields = new FirmamentSyntaxFields(boxSyntax, diagnostics);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.csindex 2d4b7534..f62c666a 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs@@ -20,7 +20,7 @@ public sealed record FirmamentLanguageFormat(string Document, string Revision, spublic static class FirmamentLanguageAnalysisService{internal sealed record Lexeme(int Start, int Length, string Text, string Shape, string? Error = null);- private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "With", "with", "Expose", "Include", "Subassembly", "Assembly", "Part", "Template", "Function", "Record", "Pattern", "Over", "Using", "Output"];+ private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "With", "with", "Expose", "Include", "Subassembly", "Assembly", "Part", "Template", "Function", "Record", "Pattern", "Over", "Using", "As", "as", "Output"];private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Function", "Pattern", "Section", "SectionChain", "FrameTransform", "Points"];private static readonly HashSet<string> Types = ["Length", "Angle", "Float", "Int", "Bool", "Box3", "Plane", "Point2", "Point3"];private static readonly HashSet<string> Choices = FirmamentSemanticSchemas.Alldiff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentPanelCompiler.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentPanelCompiler.csindex de095df7..b3bdf2b8 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentPanelCompiler.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentPanelCompiler.cs@@ -1,6 +1,5 @@using System.Diagnostics;-using System.Globalization;-using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.Core.Math;using Aetheris.Geometry;using Aetheris.Surfacing;@@ -23,146 +22,191 @@ public static class FirmamentPanelCompilerpublic const string MissingSurface = "firmament-panel-surface-missing";public static FirmamentPanelCompilation Compile(string source,+ IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations = null) =>+ Bind(FirmamentSyntaxParser.Parse(source), templateInstantiations);++ internal static FirmamentPanelCompilation Bind(SyntaxParseResult syntax,IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations = null){- ArgumentNullException.ThrowIfNull(source);- var parseWatch = Stopwatch.StartNew(); var diagnostics = new List<string>();- var model = Regex.Match(source, @"\bModel\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- if (!model.Success) diagnostics.Add(FirmamentV2Parser.MissingModel);- var units = Regex.Match(source, @"\bUnits\s*:\s*(?<unit>[A-Za-z]+)", RegexOptions.CultureInvariant);- if (!units.Success || units.Groups["unit"].Value != "mm") diagnostics.Add(FirmamentV2Parser.MissingUnits);- var declarations = Blocks(source, @"\bPanel\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{").ToArray();+ var parseWatch = Stopwatch.StartNew();+ var diagnostics = syntax.Diagnostics.Select(d => d.Code + ": " + d.Message).ToList();+ var roots = syntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => !d.Modifiers.Any(m => m.Name.Text is "Concept" or "Template")).ToArray();+ var model = roots.FirstOrDefault(d => d.Type.Name.Text == "Model") ?? roots.FirstOrDefault(d => d.Type.Name.Text == "Struct");+ if (model is null) diagnostics.Add(FirmamentV2Parser.MissingModel);+ var units = model?.Body?.Statements.OfType<FieldSyntax>().Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Units")).ToArray() ?? [];+ if (units.Length == 0 || units.Any(f => FirmamentSyntaxValues.Reference(f.Value) != "mm")) diagnostics.Add(FirmamentV2Parser.MissingUnits);+ var declarations = FirmamentV2Parser.MechanicalDeclarations(syntax.Document.Statements).Where(d => d.Type.Name.Text == "Panel").ToArray();if (declarations.Length == 0) diagnostics.Add("firmament-panel-missing");+ CloseScope(syntax.Document.Statements, diagnostics);+ foreach (var duplicate in declarations.GroupBy(d => d.Name?.Text).Where(g => g.Count() > 1))+ diagnostics.Add($"{InvalidPanel}:{duplicate.Key}:duplicate-name");parseWatch.Stop();-var constructionWatch = Stopwatch.StartNew(); var panels = new List<PanelIr>();foreach (var declaration in declarations){try{- var panel = CompilePanel(declaration.Name, declaration.Body, diagnostics);+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);+ var panel = CompilePanel(fields, diagnostics);+ fields.Complete();if (panel is not null) panels.Add(panel);}catch (Exception exception) when (exception is ArgumentException or InvalidOperationException or NotSupportedException)- {- diagnostics.Add($"{InvalidPanel}:{declaration.Name}:{exception.Message}");- }+ { diagnostics.Add($"{InvalidPanel}:{declaration.Name?.Text}:{exception.Message}"); }}constructionWatch.Stop();- return new(model.Success ? model.Groups["name"].Value : "InvalidPanelModel", panels,+ return new(model?.Name?.Text ?? "InvalidPanelModel", panels,diagnostics.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(),new(parseWatch.Elapsed.TotalMilliseconds, constructionWatch.Elapsed.TotalMilliseconds), templateInstantiations);}- private static PanelIr? CompilePanel(string name, string body, ICollection<string> diagnostics)+ private static void CloseScope(IEnumerable<StatementSyntax> statements, List<string> diagnostics)+ {+ foreach (var statement in statements)+ {+ if (statement is DirectiveSyntax) continue;+ if (statement is FieldSyntax f && FirmamentSyntaxFields.SameField(f.Name.Text, "Units")) continue;+ if (statement is DeclarationSyntax d)+ {+ if (d.Type.Name.Text == "Panel") continue;+ // Uninstantiated templates are definitions, never material panels.+ if (d.Modifiers.Any(m => m.Name.Text is "Concept" or "Template")) continue;+ if (d.Type.Name.Text is "Model" or "Struct" && d.Body is not null)+ {+ if (d.Type.Arguments.Count > 0 || d.Parameters.Count > 0 || d.Clauses.Count > 0 || d.Annotation is not null || d.Initializer is not null)+ diagnostics.Add($"firmament-v2-domain-root-header-unsupported:{d.Type.Name.Text}:{d.Name?.Text}");+ CloseScope(d.Body.Statements, diagnostics); continue;+ }+ }+ diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:Panel:{(statement as DeclarationSyntax)?.Type.Name.Text ?? (statement as FieldSyntax)?.Name.Text ?? "expression"}");+ }+ }++ private static PanelIr? CompilePanel(FirmamentSyntaxFields fields, List<string> diagnostics){- var surface = Regex.Match(body, @"\bSurface\s*:\s*(?<kind>ParametricSurface|HyperbolicParaboloid|ParabolicCylinder|EllipticParaboloid|Helicoid|RuledSurface|RuledTransition|BoundaryPatch|SectionSurface)\s*\{", RegexOptions.CultureInvariant);- if (!surface.Success) { diagnostics.Add($"{MissingSurface}:{name}"); return null; }- var open = body.IndexOf('{', surface.Index); var close = Matching(body, open, '{', '}');- if (close < 0) { diagnostics.Add($"{InvalidPanel}:{name}:surface-block"); return null; }- var surfaceBody = body[(open + 1)..close];- var orientation = string.Equals(Field(body, "Orientation"), "Back", StringComparison.Ordinal)+ var declaration = fields.Declaration;+ var name = declaration.Name?.Text ?? "";+ if (declaration.Type.Arguments.Count > 0 || declaration.Modifiers.Count > 0 || name.Length == 0)+ diagnostics.Add($"{InvalidPanel}:{name}:header");+ if (fields.Take("Surface") is not ObjectSyntax surface)+ { diagnostics.Add($"{MissingSurface}:{name}"); return null; }+ var values = FirmamentSyntaxFields.Object(surface, name, diagnostics);+ var orientationExpression = fields.Take("Orientation");+ var orientationText = orientationExpression is null ? "Front" : FirmamentSyntaxValues.Reference(orientationExpression);+ if (orientationText is not ("Front" or "Back")) fields.Invalid("Orientation");+ var orientation = orientationText == "Back"? new PanelOrientation(PanelNormalOrientation.ReversedSupportNormal, PanelMaterialSide.Back) : PanelOrientation.Front;- var thicknessText = Field(body, "Thickness");- double? thickness = thicknessText is null ? null : Length(thicknessText);- var material = Field(body, "Material")?.Trim('"');- PanelResult result = surface.Groups["kind"].Value switch+ var thicknessExpression = fields.Take("Thickness");+ double? thickness = thicknessExpression is null ? null : Measure(thicknessExpression, "mm", "Thickness");+ var materialExpression = fields.Take("Material");+ var material = FirmamentSyntaxValues.Reference(materialExpression);+ if (materialExpression is not null && material is null) fields.Invalid("Material");+ double Length(string field) => Required(values, field, "mm");+ PanelResult result = values.Declaration.Type.Name.Text switch{- "HyperbolicParaboloid" => PanelFactory.FromParametric(MathematicalSurfaces.HyperbolicParaboloid(name, LengthRequired(surfaceBody,"Width")/2, LengthRequired(surfaceBody,"Depth")/2, LengthRequired(surfaceBody,"Rise")),orientation,thickness,material),- "ParabolicCylinder" => PanelFactory.FromParametric(MathematicalSurfaces.ParabolicCylinder(name, LengthRequired(surfaceBody,"Width")/2, LengthRequired(surfaceBody,"Depth")/2, LengthRequired(surfaceBody,"Rise")),orientation,thickness,material),- "EllipticParaboloid" => PanelFactory.FromParametric(MathematicalSurfaces.EllipticParaboloid(name, LengthRequired(surfaceBody,"Width")/2, LengthRequired(surfaceBody,"Depth")/2, LengthRequired(surfaceBody,"Rise")),orientation,thickness,material),- "Helicoid" => PanelFactory.FromParametric(MathematicalSurfaces.Helicoid(name,LengthRequired(surfaceBody,"Radius"),LengthRequired(surfaceBody,"Rise"),Number(surfaceBody,"Turns",1)),orientation,thickness,material),- "ParametricSurface" => PanelFactory.FromParametric(Parametric(name,surfaceBody),orientation,thickness,material),- "RuledSurface" => PanelFactory.FromRuled(Ruled(name,surfaceBody,RuledConstructionKind.RuledSurface),orientation,thickness,material),- "RuledTransition" => PanelFactory.FromRuled(Ruled(name,surfaceBody,RuledConstructionKind.RuledTransition),orientation,thickness,material),- "BoundaryPatch" => PanelFactory.FromBoundaryPatch(Boundary(name,surfaceBody),orientation,thickness,material),- "SectionSurface" => PanelFactory.FromSectionSurface(Sections(name,surfaceBody),orientation,thickness,material),- _ => new(null,[new(UnsupportedSurface,$"Surface kind '{surface.Groups["kind"].Value}' is not admitted.")])+ "HyperbolicParaboloid" => PanelFactory.FromParametric(MathematicalSurfaces.HyperbolicParaboloid(name, Length("Width")/2, Length("Depth")/2, Length("Rise")), orientation, thickness, material),+ "ParabolicCylinder" => PanelFactory.FromParametric(MathematicalSurfaces.ParabolicCylinder(name, Length("Width")/2, Length("Depth")/2, Length("Rise")), orientation, thickness, material),+ "EllipticParaboloid" => PanelFactory.FromParametric(MathematicalSurfaces.EllipticParaboloid(name, Length("Width")/2, Length("Depth")/2, Length("Rise")), orientation, thickness, material),+ "Helicoid" => PanelFactory.FromParametric(MathematicalSurfaces.Helicoid(name, Length("Radius"), Length("Rise"), values.Number("Turns", "", 1)), orientation, thickness, material),+ "ParametricSurface" => PanelFactory.FromParametric(Parametric(name, values), orientation, thickness, material),+ "RuledSurface" => PanelFactory.FromRuled(Ruled(name, values, RuledConstructionKind.RuledSurface, diagnostics), orientation, thickness, material),+ "RuledTransition" => PanelFactory.FromRuled(Ruled(name, values, RuledConstructionKind.RuledTransition, diagnostics), orientation, thickness, material),+ "BoundaryPatch" => PanelFactory.FromBoundaryPatch(Boundary(name, values, diagnostics), orientation, thickness, material),+ "SectionSurface" => PanelFactory.FromSectionSurface(Sections(name, values, diagnostics), orientation, thickness, material),+ _ => new(null, [new(UnsupportedSurface, $"Surface kind '{values.Declaration.Type.Name.Text}' is not admitted.")])};+ values.Complete();foreach (var diagnostic in result.Diagnostics) diagnostics.Add($"{diagnostic.Code}:{name}:{diagnostic.Message}");return result.Panel;}- private static ParametricSurfaceIr Parametric(string name,string body)+ private static ParametricSurfaceIr Parametric(string name, FirmamentSyntaxFields values){- var u=Vector2(body,"DomainU");var v=Vector2(body,"DomainV");- var parserX=new ExpressionParser(FieldRequired(body,"X"));var parserY=new ExpressionParser(FieldRequired(body,"Y"));var parserZ=new ExpressionParser(FieldRequired(body,"Z"));- return new(name,SurfaceConstructionKind.ParametricSurface,new(new(u[0],u[1]),new(v[0],v[1])),new(parserX.Parse(),parserY.Parse(),parserZ.Parse()),$"firmament:Panel:{name}:ParametricSurface");+ var u = Vector(values, "DomainU", "", 2); var v = Vector(values, "DomainV", "", 2);+ return new(name, SurfaceConstructionKind.ParametricSurface, new(new(u[0], u[1]), new(v[0], v[1])),+ new(Expression(values.Take("X")), Expression(values.Take("Y")), Expression(values.Take("Z"))), $"firmament:Panel:{name}:ParametricSurface");}- private static RuledSurfaceIr Ruled(string name,string body,RuledConstructionKind kind)+ private static RuledSurfaceIr Ruled(string name, FirmamentSyntaxFields values, RuledConstructionKind kind, List<string> diagnostics){- var a=NamedBoundary(body,"BoundaryA");var b=NamedBoundary(body,"BoundaryB");- return new(name,kind,a,b,new(a.StableId,$"firmament:Panel:{name}","BoundaryA"),new(b.StableId,$"firmament:Panel:{name}","BoundaryB"));+ var a = NamedBoundary(values, "BoundaryA", diagnostics); var b = NamedBoundary(values, "BoundaryB", diagnostics);+ return new(name, kind, a, b, new(a.StableId, $"firmament:Panel:{name}", "BoundaryA"), new(b.StableId, $"firmament:Panel:{name}", "BoundaryB"));}- private static BoundaryPatchIr Boundary(string name,string body)+ private static BoundaryPatchIr Boundary(string name, FirmamentSyntaxFields values, List<string> diagnostics){- var south=NamedBoundary(body,"South");var north=NamedBoundary(body,"North");var west=NamedBoundary(body,"West");var east=NamedBoundary(body,"East");- var values=new[]{south,north,west,east};- return new(name,south,north,west,east,values.Select(item=>new BoundaryProvenance(item.StableId,$"firmament:Panel:{name}",item.StableId)).ToArray());+ var south = NamedBoundary(values, "South", diagnostics); var north = NamedBoundary(values, "North", diagnostics);+ var west = NamedBoundary(values, "West", diagnostics); var east = NamedBoundary(values, "East", diagnostics);+ return new(name, south, north, west, east, new[] { south, north, west, east }+ .Select(item => new BoundaryProvenance(item.StableId, $"firmament:Panel:{name}", item.StableId)).ToArray());}- private static SectionSurfaceIr Sections(string name,string body)+ private static SectionSurfaceIr Sections(string name, FirmamentSyntaxFields fields, List<string> diagnostics){- var match=Regex.Match(body,@"\bSections\s*:\s*\[",RegexOptions.CultureInvariant);if(!match.Success)throw new ArgumentException("SectionSurface requires Sections: [ ... ].");- var open=body.IndexOf('[',match.Index);var close=Matching(body,open,'[',']');if(close<0)throw new ArgumentException("SectionSurface Sections list is incomplete.");- var sectionBody=body[(open+1)..close];var sections=Blocks(sectionBody,@"\b(?<kind>Line|Arc|Circle)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{").Select(block=>BoundaryValue($"{name}:{block.Name}",block.Kind,block.Body)).ToArray();- if(sections.Length<2)throw new ArgumentException("SectionSurface requires at least two explicit sections.");- return new(name,sections,sections.Select((item,index)=>new BoundaryProvenance(item.StableId,$"firmament:Panel:{name}",$"section-{index}")).ToArray());+ if (fields.Take("Sections") is not SequenceSyntax { Kind: SequenceKind.List } list)+ throw new ArgumentException("SectionSurface requires Sections: [ ... ].");+ var sections = new List<RuledBoundary>();+ foreach (var item in list.Items)+ {+ if (item.Name is not null || item.Default is not null || item.Value is not ObjectSyntax { Name: not null } value)+ throw new ArgumentException("Each explicit section requires a named Line, Arc or Circle object.");+ sections.Add(BoundaryValue($"{name}:{value.Name.Text}", value, diagnostics));+ }+ if (sections.Count < 2) throw new ArgumentException("SectionSurface requires at least two explicit sections.");+ return new(name, sections, sections.Select((item, index) => new BoundaryProvenance(item.StableId, $"firmament:Panel:{name}", $"section-{index}")).ToArray());}- private static RuledBoundary NamedBoundary(string body,string field)- {- var match=Regex.Match(body,$@"\b{Regex.Escape(field)}\s*:\s*(?<kind>Line|Arc|Circle)\s*\{{",RegexOptions.CultureInvariant);- if(!match.Success)throw new ArgumentException($"Missing {field} boundary.");var open=body.IndexOf('{',match.Index);var close=Matching(body,open,'{','}');- if(close<0)throw new ArgumentException($"Incomplete {field} boundary.");return BoundaryValue(field,match.Groups["kind"].Value,body[(open+1)..close]);- }+ private static RuledBoundary NamedBoundary(FirmamentSyntaxFields fields, string name, List<string> diagnostics) =>+ fields.Take(name) is ObjectSyntax value ? BoundaryValue(name, value, diagnostics)+ : throw new ArgumentException($"Missing {name} boundary.");- private static RuledBoundary BoundaryValue(string id,string kind,string body) => kind switch+ private static RuledBoundary BoundaryValue(string id, ObjectSyntax value, List<string> diagnostics){- "Line"=>new RuledBoundary.Line(id,Point(body,"Start"),Point(body,"End")),- "Circle"=>new RuledBoundary.Circle(id,Point(body,"Center"),Direction(body,"Normal"),LengthRequired(body,"Radius"),Direction(body,"ReferenceAxis")),- "Arc"=>new RuledBoundary.Arc(id,Point(body,"Center"),Direction(body,"Normal"),LengthRequired(body,"Radius"),Direction(body,"ReferenceAxis"),Angle(body,"StartAngle"),Angle(body,"SweepAngle")),- _=>throw new NotSupportedException($"Boundary kind '{kind}' is not admitted.")- };+ var fields = FirmamentSyntaxFields.Object(value, id, diagnostics);+ Point3D Point(string field) { var v = Vector(fields, field, "mm", 3); return new(v[0], v[1], v[2]); }+ Direction3D Direction(string field) { var v = Vector(fields, field, "", 3); return Direction3D.Create(new(v[0], v[1], v[2])); }+ RuledBoundary result = fields.Declaration.Type.Name.Text switch+ {+ "Line" => new RuledBoundary.Line(id, Point("Start"), Point("End")),+ "Circle" => new RuledBoundary.Circle(id, Point("Center"), Direction("Normal"), Required(fields, "Radius", "mm"), Direction("ReferenceAxis")),+ "Arc" => new RuledBoundary.Arc(id, Point("Center"), Direction("Normal"), Required(fields, "Radius", "mm"), Direction("ReferenceAxis"), Angle(fields, "StartAngle"), Angle(fields, "SweepAngle")),+ _ => throw new NotSupportedException($"Boundary kind '{fields.Declaration.Type.Name.Text}' is not admitted.")+ };+ fields.Complete(); return result;+ }- private static string FieldRequired(string body,string name)=>Field(body,name)??throw new ArgumentException($"Missing field '{name}'.");- private static string? Field(string body,string name)+ private static double[] Vector(FirmamentSyntaxFields fields, string name, string unit, int count) =>+ fields.Vector(name, unit, out var values) && values.Length == count ? values+ : throw new ArgumentException($"Field '{name}' requires {count} { (unit.Length == 0 ? "dimensionless" : unit) } values.");+ private static double Required(FirmamentSyntaxFields fields, string name, string unit) => Measure(fields.Take(name), unit, name);+ private static double Measure(ExpressionSyntax? expression, string unit, string name) =>+ FirmamentSyntaxValues.TryMeasure(expression, unit, out var value) ? value : throw new ArgumentException($"Field '{name}' requires a finite {unit} measure.");+ private static double Angle(FirmamentSyntaxFields fields, string name){- var match=Regex.Match(body,$@"\b{Regex.Escape(name)}\s*:\s*(?<value>[^;\r\n}}]+)\s*;?",RegexOptions.CultureInvariant);- return match.Success?match.Groups["value"].Value.Trim():null;+ var value = fields.Take(name);+ return FirmamentSyntaxValues.TryMeasure(value, "deg", out var degrees) ? degrees * Math.PI / 180d : Measure(value, "rad", name);}- private static double LengthRequired(string body,string name)=>Length(FieldRequired(body,name));- private static double Length(string value)- {var match=Regex.Match(value,@"^(?<n>[-+0-9.eE]+)\s*mm$");return match.Success&&double.TryParse(match.Groups["n"].Value,NumberStyles.Float,CultureInfo.InvariantCulture,out var result)?result:throw new ArgumentException($"Expected millimetre length, received '{value}'.");}- private static double Number(string body,string name,double fallback)- {var value=Field(body,name);return value is null?fallback:double.Parse(value,CultureInfo.InvariantCulture);}- private static double Angle(string body,string name)- {var value=FieldRequired(body,name);var match=Regex.Match(value,@"^(?<n>[-+0-9.eE]+)\s*(?<u>deg|rad)$");if(!match.Success)throw new ArgumentException($"Expected angle for '{name}'.");var n=double.Parse(match.Groups["n"].Value,CultureInfo.InvariantCulture);return match.Groups["u"].Value=="deg"?n*Math.PI/180:n;}- private static double[] Vector2(string body,string name)=>Vector(body,name,2,false);- private static Point3D Point(string body,string name){var v=Vector(body,name,3,true);return new(v[0],v[1],v[2]);}- private static Direction3D Direction(string body,string name){var v=Vector(body,name,3,false);return Direction3D.Create(new(v[0],v[1],v[2]));}- private static double[] Vector(string body,string name,int count,bool lengths)- {var raw=FieldRequired(body,name);var match=Regex.Match(raw,@"^\[(?<v>[^]]+)\]$");if(!match.Success)throw new ArgumentException($"Field '{name}' requires a vector.");var values=match.Groups["v"].Value.Split(',',StringSplitOptions.TrimEntries);if(values.Length!=count)throw new ArgumentException($"Field '{name}' requires {count} values.");return values.Select(value=>lengths?Length(value):double.Parse(value,CultureInfo.InvariantCulture)).ToArray();}-- private static IEnumerable<(string Name,string Kind,string Body)> Blocks(string source,string pattern)- {foreach(Match match in Regex.Matches(source,pattern,RegexOptions.CultureInvariant)){var open=source.IndexOf('{',match.Index);var close=Matching(source,open,'{','}');if(close<0)continue;yield return(match.Groups["name"].Value,match.Groups["kind"].Success?match.Groups["kind"].Value:string.Empty,source[(open+1)..close]);}}- private static int Matching(string text,int open,char opening,char closing)- {var depth=0;for(var i=open;i<text.Length;i++){if(text[i]==opening)depth++;else if(text[i]==closing&&--depth==0)return i;}return -1;}- private sealed class ExpressionParser+ // The surface expression algebra still owns dimensional and mathematical admission.+ // The shared parser supplies syntax; there is no second character expression parser.+ private static SurfaceScalarExpression Expression(ExpressionSyntax? value) => value switch{- private readonly string text;private int position;- internal ExpressionParser(string text)=>this.text=text;- internal SurfaceScalarExpression Parse(){var result=Add();Skip();if(position!=text.Length)throw new ArgumentException($"Unexpected parametric expression token at '{text[position..]}'.");return result;}- private SurfaceScalarExpression Add(){var value=Multiply();while(true){Skip();if(Take('+'))value=SurfaceExpression.Add(value,Multiply());else if(Take('-'))value=SurfaceExpression.Subtract(value,Multiply());else return value;}}- private SurfaceScalarExpression Multiply(){var value=Power();while(true){Skip();if(Take('*'))value=SurfaceExpression.Multiply(value,Power());else if(Take('/'))value=SurfaceExpression.Divide(value,Power());else return value;}}- private SurfaceScalarExpression Power(){var value=Unary();Skip();if(Take('^')){Skip();var exponent=(int)ReadNumber(out var unit);if(unit)throw new ArgumentException("Expression exponent must be dimensionless.");value=SurfaceExpression.Power(value,exponent);}return value;}- private SurfaceScalarExpression Unary(){Skip();if(Take('-'))return SurfaceExpression.Multiply(SurfaceExpression.Number(-1),Unary());if(Take('+'))return Unary();return Primary();}- private SurfaceScalarExpression Primary(){Skip();if(Take('(')){var value=Add();Skip();if(!Take(')'))throw new ArgumentException("Parametric expression is missing ')'.");return value;}if(char.IsDigit(Peek())||Peek()=='.'){var n=ReadNumber(out var mm);return mm?SurfaceExpression.Length(n):SurfaceExpression.Number(n);}var id=ReadIdentifier();if(id=="u")return SurfaceExpression.U;if(id=="v")return SurfaceExpression.V;if(id is "sin" or "cos"){Skip();if(!Take('('))throw new ArgumentException($"{id} requires parentheses.");var value=Add();if(!Take(')'))throw new ArgumentException($"{id} is missing ')'.");return id=="sin"?SurfaceExpression.Sin(value):SurfaceExpression.Cos(value);}throw new ArgumentException($"Unknown parametric expression symbol '{id}'.");}- private double ReadNumber(out bool mm){Skip();var start=position;while(position<text.Length&&(char.IsDigit(text[position])||text[position] is '.' or 'e' or 'E' or '+' or '-'))position++;var n=double.Parse(text[start..position],CultureInfo.InvariantCulture);mm=text.AsSpan(position).StartsWith("mm",StringComparison.Ordinal);if(mm)position+=2;return n;}- private string ReadIdentifier(){Skip();var start=position;while(position<text.Length&&(char.IsLetterOrDigit(text[position])||text[position]=='_'))position++;return text[start..position];}- private char Peek(){Skip();return position<text.Length?text[position]:'\0';}private bool Take(char c){Skip();if(position<text.Length&&text[position]==c){position++;return true;}return false;}private void Skip(){while(position<text.Length&&char.IsWhiteSpace(text[position]))position++;}- }+ ReferenceSyntax { Name.Text: "u" } => SurfaceExpression.U,+ ReferenceSyntax { Name.Text: "v" } => SurfaceExpression.V,+ LiteralSyntax { Kind: LiteralKind.Number } => SurfaceExpression.Number(Measure(value, "", "expression")),+ QuantitySyntax => SurfaceExpression.Length(Measure(value, "mm", "expression")),+ SequenceSyntax { Kind: SequenceKind.Tuple, Items.Count: 1 } group => Expression(group.Items[0].Value),+ UnarySyntax { Operator: UnaryOperator.Positive } unary => Expression(unary.Operand),+ UnarySyntax { Operator: UnaryOperator.Negative } unary => SurfaceExpression.Multiply(SurfaceExpression.Number(-1), Expression(unary.Operand)),+ BinarySyntax { Operator: BinaryOperator.Add } binary => SurfaceExpression.Add(Expression(binary.Left), Expression(binary.Right)),+ BinarySyntax { Operator: BinaryOperator.Subtract } binary => SurfaceExpression.Subtract(Expression(binary.Left), Expression(binary.Right)),+ BinarySyntax { Operator: BinaryOperator.Multiply } binary => SurfaceExpression.Multiply(Expression(binary.Left), Expression(binary.Right)),+ BinarySyntax { Operator: BinaryOperator.Divide } binary => SurfaceExpression.Divide(Expression(binary.Left), Expression(binary.Right)),+ BinarySyntax { Operator: BinaryOperator.Power } binary when FirmamentSyntaxValues.TryMeasure(binary.Right, "", out var exponent)+ && exponent == Math.Truncate(exponent) && exponent is >= int.MinValue and <= int.MaxValue => SurfaceExpression.Power(Expression(binary.Left), (int)exponent),+ CallSyntax { Target: ReferenceSyntax { Name.Text: "sin" or "cos" } function, Arguments.Count: 1 } call+ when call.Arguments[0].Name is null && call.Arguments[0].Default is null =>+ function.Name.Text == "sin" ? SurfaceExpression.Sin(Expression(call.Arguments[0].Value)) : SurfaceExpression.Cos(Expression(call.Arguments[0].Value)),+ _ => throw new ArgumentException("Unsupported or missing parametric surface expression.")+ };}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.csindex 5b4609bb..3e881bf6 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs@@ -1,3 +1,4 @@+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using System.Text;namespace Aetheris.Kernel.Firmament.FirmamentV2;@@ -12,7 +13,7 @@ public static class FirmamentSourceSpellingprivate static readonly Dictionary<string, HashSet<string>> Fields = CreateFields();private static readonly Dictionary<string, string> Links = new(StringComparer.Ordinal){- ["Using"] = "using", ["On"] = "on", ["Over"] = "over",+ ["As"] = "as", ["Using"] = "using", ["On"] = "on", ["Over"] = "over",["Include"] = "include", ["Expose"] = "expose", ["Bind"] = "bind"};@@ -24,6 +25,11 @@ public static class FirmamentSourceSpelling{ArgumentNullException.ThrowIfNull(source);var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(t => t.Shape != "comment").ToArray();+ var aliasPositions = tokens.Any(t => t.Text is "As" or "as") ? FirmamentSyntaxTraversal+ .Expressions(FirmamentSyntaxParser.Parse(source).Document)+ .OfType<AliasSyntax>()+ .Select(alias => tokens.LastOrDefault(t => t.Start < alias.Name.Span.Start && t.Start >= alias.Value.Span.Start + alias.Value.Span.Length && t.Text is "As" or "as")?.Start)+ .Where(position => position.HasValue).Select(position => position!.Value).ToHashSet() : [];var output = new StringBuilder(source);var scopes = new Stack<Scope>();var parentheses = 0;@@ -80,7 +86,7 @@ public static class FirmamentSourceSpelling{// Positive linking positions only; never convert a value/reference.canonical = Links.FirstOrDefault(pair => (t.Text == pair.Key || t.Text == pair.Value) &&- IsLink(tokens, i, pair.Key)).Key;+ (pair.Key == "As" ? aliasPositions.Contains(t.Start) : IsLink(tokens, i, pair.Key))).Key;}if (canonical is null) continue;var spelling = preferred ? Links.GetValueOrDefault(canonical) ?? PreferredField(canonical) : canonical;diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex 4add9355..b224510b 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -325,6 +325,11 @@ public sealed record FirmamentV2ParseResult(// Bound engineering inputs are retained for execution; a successful AST admission// cannot be replaced by a different whole-document parser in the build path.internal PrismaticProfileCompositionParseResult? BoundComposition { get; init; }+ internal FirmamentPlateauRequest? BoundPlateau { get; init; }+ internal bool OwnsUnifiedAdmission { get; init; }+ internal SectionChainAuthoringResult? BoundSectionChain { get; init; }+ internal GearAuthoringDocument? BoundGear { get; init; }+ internal ResolvedRevolve? BoundRevolve { get; init; }internal ResolvedProfile2D? BoundProfile { get; init; }internal double ExtrusionHeight { get; init; }internal string? BoundSource { get; init; }diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2CompatibilityBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2CompatibilityBinding.csnew file mode 100644index 00000000..4b62f013--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2CompatibilityBinding.cs@@ -0,0 +1,207 @@+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public static partial class FirmamentV2Parser+{+ private static bool BindCompatibilityScope(DocumentSyntax syntax, DeclarationSyntax? model, List<string> diagnostics)+ {+ var core = true;+ if (model?.Body is null) return core;+ if (model.Clauses.Count > 0 || model.Type.Arguments.Count > 0 || model.Parameters.Count > 0 || model.Annotation is not null || model.Initializer is not null || model.ResultType is not null || model.Occurrence)+ diagnostics.Add(CanonicalDocumentMalformed);+ foreach (var statement in syntax.Statements.Where(s => !ReferenceEquals(s, model)).Concat(model.Body.Statements))+ {+ switch (statement)+ {+ case DirectiveSyntax { Kind: DirectiveKind.Schema }: break;+ case DirectiveSyntax directive: diagnostics.Add($"{CanonicalDeclarationUnknown}:Model:{directive.Kind}"); break;+ case FieldSyntax field when FirmamentSyntaxFields.SameField(field.Name.Text, "Units"): break;+ case DeclarationSyntax { Type.Name.Text: "solid" or "modify" or "Modify" or "MODIFY" }: break;+ // Explicit existing semantic owners. These are not qualified as+ // whole-document AST admission until their remaining grammar moves.+ case DeclarationSyntax { Type.Name.Text: "let" or "template" or "pmi" or "Pmi" or "recognize" or "replace" or "manufacturing" or "feature" or "region" or "fill" }:+ core = false; break;+ case FieldSyntax field: diagnostics.Add($"{CanonicalFieldUnknown}:Model:{field.Name.Text}"); break;+ default: diagnostics.Add($"{CanonicalDeclarationUnknown}:Model:{(statement as DeclarationSyntax)?.Type.Name.Text ?? "expression"}"); break;+ }+ }+ return core;+ }++ private static IReadOnlyList<FirmamentV2ModifyBlock> BindCompatibilityModifies(SyntaxParseResult syntax,+ DeclarationSyntax? model, Dictionary<string, FirmamentV2SolidBinding> solids, List<string> diagnostics)+ {+ var result = new List<FirmamentV2ModifyBlock>();+ foreach (var modify in model?.Body?.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text is "modify" or "Modify" or "MODIFY") ?? [])+ {+ if (modify.Name is null || !solids.TryGetValue(modify.Name.Text, out var stock)) { diagnostics.Add(ModifyTargetUnresolved); continue; }+ if (stock.Box is null) { diagnostics.Add(ModifyTargetNotSolid); continue; }+ var holes = new List<FirmamentV2SemanticHoleDecl>();+ var regions = new List<FirmamentV2RegionDecl>();+ foreach (var error in syntax.Diagnostics.Where(error => error.SourceSpan is { } span &&+ span.Start >= modify.Span.Start && span.Start <= modify.Span.Start + modify.Span.Length)) diagnostics.Add(error.Code);+ if (modify.Body is null || modify.Annotation is not null || modify.Clauses.Count > 0 || modify.Parameters.Count > 0 || modify.Type.Arguments.Count > 0 || modify.Initializer is not null || modify.ResultType is not null || modify.Modifiers.Count > 0 || modify.Occurrence)+ diagnostics.Add(CanonicalModifyMalformed);+ foreach (var statement in modify.Body?.Statements ?? [])+ {+ if (statement is DeclarationSyntax { Type.Name.Text: "hole" or "Hole" } hole)+ {+ var fields = new FirmamentSyntaxFields(hole, diagnostics, implicitUnit: "mm");+ if (BindMechanicalHole(fields, diagnostics, stock) is { } bound) holes.Add(bound);+ fields.Complete();+ }+ else if (statement is DeclarationSyntax { Type.Name.Text: "region" } region)+ {+ if (BindCompatibilityRegion(region, stock, diagnostics) is { } bound) regions.Add(bound);+ }+ else diagnostics.Add($"{CanonicalDeclarationUnknown}:Modify:{(statement as DeclarationSyntax)?.Type.Name.Text ?? "expression"}");+ }+ if (holes.Count > 0 || regions.Count > 0) result.Add(new(stock.Name, regions, holes));+ }+ return result;+ }++ private static FirmamentV2RegionDecl? BindCompatibilityRegion(DeclarationSyntax region, FirmamentV2SolidBinding stock, List<string> diagnostics)+ {+ if (region.Name?.Text != "sideHole" || region.Clauses.Count != 1 || region.Clauses[0].Kind != ClauseKind.On+ || region.Type.Arguments.Count > 0 || region.Parameters.Count > 0 || region.Annotation is not null || region.Initializer is not null || region.ResultType is not null || region.Modifiers.Count > 0 || region.Occurrence)+ { diagnostics.Add(RegionUnsupported); return null; }+ var attachment = BindCompatibilityFace(region.Clauses[0].Value, stock, RegionAttachmentSelectorUnsupported, diagnostics);+ var statements = region.Body?.Statements ?? [];+ if (statements.Count != 1 || statements[0] is not DeclarationSyntax { Type.Name.Text: "cut" } cut)+ { diagnostics.Add(CutUnsupported); return null; }+ if (cut.Name?.Text is not ("Cylinder" or "cylinder")) { diagnostics.Add(CutToolUnsupported); return null; }+ var fields = new FirmamentSyntaxFields(cut, diagnostics, implicitUnit: "mm");+ var radiusExpression = fields.Take("Radius");+ var validRadius = FirmamentSyntaxValues.TryMeasure(radiusExpression, "mm", out var radius, "mm");+ if (radiusExpression is null) diagnostics.Add(CylinderRadiusMissing);+ else if (!validRadius || radius <= 0) diagnostics.Add(CylinderRadiusInvalid);+ var centerExpression = fields.Take("Center");+ FirmamentV2FaceLocalPoint2D? center = null;+ if (centerExpression is not null)+ {+ if (!FirmamentSyntaxValues.Vector(centerExpression, "mm", out var coordinates, "mm")) diagnostics.Add(CylinderCenterInvalid);+ else if (coordinates.Length != 2) diagnostics.Add(CylinderCenterArityInvalid);+ else center = new(coordinates[0], coordinates[1], string.Empty);+ }+ var through = BindCompatibilityFace(fields.Take("Through"), stock, ThroughSelectorUnsupported, diagnostics);+ fields.Complete();+ if (cut.Type.Arguments.Count > 0 || cut.Modifiers.Count > 0) diagnostics.Add(CutUnsupported);+ if (attachment is null || through is null || !validRadius || radius <= 0) return null;+ var route = FirmamentV2SideHoleRoutePolicy.Resolve(attachment.Axis, through.Axis, stock.Box!.Size, radius, center?.U ?? 0, center?.V ?? 0);+ if (!route.IsSupported)+ {+ diagnostics.Add(route.Diagnostic!);+ if (route.Diagnostic is SideHoleRouteUnsupported && (attachment.Kind == "Alias" || through.Kind == "Alias")) diagnostics.Add(SideHoleAliasResolvesToUnsupportedFace);+ diagnostics.Add(SideHoleOnlyPlusXMinusXSupported);+ }+ return diagnostics.Any(IsFatalDiagnosticCode) ? null : new(region.Name.Text, "FaceAttachedRegion", attachment, new("Cut", new("Cylinder", radius, center, through)));+ }++ private static FirmamentV2FaceTarget? BindCompatibilityFace(ExpressionSyntax? expression, FirmamentV2SolidBinding stock, string diagnostic, List<string> diagnostics)+ {+ var reference = FirmamentSyntaxValues.Reference(expression);+ if (expression is CallSyntax { Target: ReferenceSyntax { Name.Text: "face" }, Arguments.Count: 1 } call+ && call.Arguments[0].Name is null && call.Arguments[0].Default is null)+ reference = "face(" + FirmamentSyntaxValues.Reference(call.Arguments[0].Value) + ")";+ if (reference is null) { diagnostics.Add(diagnostic); return null; }+ // Canonical axes and compatibility face() values share the existing+ // semantic resolver; authored aliases retain their exact identities.+ if (reference is "+X" or "-X" or "+Y" or "-Y" or "+Z" or "-Z") return FirmamentV2FaceTarget.Direct(reference);+ return ResolveFaceTarget(reference, stock, diagnostic, diagnostics);+ }++ // Historical solid declarations are an AST spelling adapter, not another+ // primitive grammar. Units remain implicit only within this admitted syntax.+ private static Dictionary<string, FirmamentV2SolidBinding> BindCompatibilitySolids(+ SyntaxParseResult syntax, DeclarationSyntax? model, string source, string? directory, List<string> diagnostics)+ {+ var solids = new Dictionary<string, FirmamentV2SolidBinding>(StringComparer.Ordinal);+ if (model?.Body is null) return solids;+ foreach (var declaration in model.Body.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "solid"))+ {+ foreach (var error in syntax.Diagnostics.Where(error => error.SourceSpan is { } span &&+ span.Start >= declaration.Span.Start && span.Start <= declaration.Span.Start + declaration.Span.Length))+ diagnostics.Add(error.Code);+ if (declaration.Type.Arguments.Count > 0 || declaration.Modifiers.Count > 0) diagnostics.Add(CanonicalPrimitiveMalformed);+ var target = declaration.Annotation is WithSyntax with ? with.Target : declaration.Annotation;+ var type = FirmamentSyntaxValues.Reference(target);+ if (type is null || declaration.Name is null || declaration.Body is null)+ { diagnostics.Add(UnknownRecordType); continue; }+ var derived = declaration.Annotation is WithSyntax;+ var body = declaration.Body;+ var exposures = body.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "expose").ToArray();+ if (exposures.Length > 1) diagnostics.Add(ExposeBlockUnsupported);+ var primitiveSyntax = declaration with+ {+ Type = new(new(type, target!.Span), [], target.Span), Annotation = null,+ Body = body with { Statements = body.Statements.Except(exposures).ToArray() }+ };+ var fields = new FirmamentSyntaxFields(primitiveSyntax, diagnostics, implicitUnit: "mm");+ FirmamentV2SolidBinding? binding = null;+ if (derived)+ {+ if (!solids.TryGetValue(type, out var stock)) { diagnostics.Add(NameUnresolved); diagnostics.Add(WithForwardReference); }+ else if (stock.Box is null) diagnostics.Add(WithRequiresBoxRecord);+ else if (!fields.Vector("Size", "mm", out var size) || size.Length != 3) diagnostics.Add(WithFieldTypeMismatch);+ else if (size.Any(v => v <= 0)) diagnostics.Add(DegenerateDimension);+ else binding = new(declaration.Name.Text, "Box", new FirmamentV2BoxRecord(size, []), type,+ new Dictionary<string, IReadOnlyList<double>>(StringComparer.Ordinal) { ["size"] = size });+ if (exposures.Length > 0) diagnostics.Add(ExposeBlockUnsupported);+ if (body.Statements.OfType<FieldSyntax>().Any(f => !FirmamentSyntaxFields.SameField(f.Name.Text, "Size"))) diagnostics.Add(WithFieldNotFound);+ }+ else if (type == "InlineStep")+ {+ if (exposures.Length > 0) diagnostics.Add(ExposeBlockUnsupported);+ _ = fields.Reference("Path");+ // The import owner retains canonical AP242 admission and topology+ // evidence; syntax and unknown-field admission are AST-owned.+ var span = body.ContentSpan;+ binding = ParseInlineStep(declaration.Name.Text, source.Substring(span.Start, span.Length), diagnostics, directory);+ }+ else if (type is "Box" or "Cylinder" or "Cone" or "Sphere" or "Torus")+ {+ var primitive = BindMechanicalPrimitive(fields, diagnostics);+ if (primitive is FirmamentV2BoxRecord box)+ primitive = box with { Exposures = exposures.SelectMany(e => BindCompatibilityExposures(e, diagnostics)).ToArray() };+ else if (exposures.Length > 0) diagnostics.Add(ExposeBlockUnsupported);+ if (primitive is null)+ {+ diagnostics.Add(CanonicalPrimitiveMalformed);++ }+ else binding = new(declaration.Name.Text, type, primitive, SourceSpan: declaration.Span, AuthoredFields: fields.AuthoredFields);+ }+ else diagnostics.Add(UnknownRecordType);+ if (body.Statements.OfType<ExpressionStatementSyntax>().Any(e => e.Value is AliasSyntax)) diagnostics.Add(FatArrowOutsideExpose);+ fields.Complete();+ if (binding is not null && !solids.TryAdd(binding.Name, binding)) diagnostics.Add(DuplicateName);+ }+ return solids;+ }++ private static IReadOnlyList<FirmamentV2Exposure> BindCompatibilityExposures(DeclarationSyntax expose, List<string> diagnostics)+ {+ var result = new List<FirmamentV2Exposure>();+ var names = new HashSet<string>(StringComparer.Ordinal);+ if (expose.Name is not null || expose.Type.Arguments.Count > 0 || expose.Parameters.Count > 0 || expose.Clauses.Count > 0 || expose.Annotation is not null || expose.Initializer is not null || expose.ResultType is not null || expose.Modifiers.Count > 0 || expose.Occurrence)+ diagnostics.Add(ExposeBlockUnsupported);+ foreach (var statement in expose.Body?.Statements ?? [])+ {+ if (statement is not ExpressionStatementSyntax { Value: AliasSyntax alias }) { diagnostics.Add(SelectorUnsupported); continue; }+ if (!names.Add(alias.Name.Text)) { diagnostics.Add(ExposeAliasDuplicate); continue; }+ var value = alias.Value;+ string? sub = null;+ if (value is MemberSyntax member) { sub = member.Member.Text; value = member.Target; }+ if (value is not CallSyntax { Target: ReferenceSyntax { Name.Text: "face" }, Arguments.Count: 1 } call)+ { diagnostics.Add(SelectorUnsupported); continue; }+ if (call.Arguments[0].Name is not null || call.Arguments[0].Default is not null) { diagnostics.Add(SelectorUnsupported); continue; }+ var axis = FirmamentSyntaxValues.Reference(call.Arguments[0].Value);+ if (axis is not ("+X" or "-X" or "+Y" or "-Y" or "+Z" or "-Z")) { diagnostics.Add(SelectorAxisInvalid); continue; }+ if (sub is not null and not "outerLoop") { diagnostics.Add(SelectorSubselectorUnsupported); continue; }+ result.Add(new(alias.Name.Text, "face", $"face({axis})" + (sub is null ? "" : "." + sub), sub is null ? "FaceRef" : "LoopRef", axis, sub));+ }+ return result;+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.csindex 3e78e8ca..be57a444 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs@@ -5,13 +5,13 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;public static partial class FirmamentV2Parser{- private static IEnumerable<DeclarationSyntax> MechanicalDeclarations(IEnumerable<StatementSyntax> statements)+ internal static IEnumerable<DeclarationSyntax> MechanicalDeclarations(IEnumerable<StatementSyntax> statements){foreach (var declaration in statements.OfType<DeclarationSyntax>()){if (declaration.Modifiers.Any(m => m.Name.Text == "Template") || declaration.Type.Name.Text == "Template") continue;yield return declaration;- if (declaration.Type.Name.Text == "Struct" && !declaration.Modifiers.Any(m => m.Name.Text == "Concept"))+ if (declaration.Type.Name.Text is "Model" or "Struct" && !declaration.Modifiers.Any(m => m.Name.Text == "Concept"))foreach (var child in MechanicalDeclarations(declaration.Body?.Statements ?? [])) yield return child;}}@@ -199,7 +199,13 @@ public static partial class FirmamentV2Parser{var type = f.Declaration.Type.Name.Text;double Length(string name) => f.Number(name, "mm");- double[]? Size() => f.Vector("Size", "mm", out var values) && values.Length == 3 && values.All(v => v > 0) ? values : null;+ double[]? Size()+ {+ if (!f.Vector("Size", "mm", out var values)) return null;+ if (values.Length != 3) { diagnostics.Add(BoxSizeArity); return null; }+ if (values.Any(v => v <= 0)) { diagnostics.Add(DegenerateDimension); return null; }+ return values;+ }switch (type){case "Box": return Size() is { } box ? new FirmamentV2BoxRecord(box, []) : null;@@ -247,26 +253,51 @@ public static partial class FirmamentV2Parserreturn result;}- private static FirmamentV2SemanticHoleDecl? BindMechanicalHole(FirmamentSyntaxFields f, List<string> diagnostics)+ private static FirmamentV2SemanticHoleDecl? BindMechanicalHole(FirmamentSyntaxFields f, List<string> diagnostics, FirmamentV2SolidBinding? compatibilityStock = null){var d = f.Declaration;+ if (d.Modifiers.Count > 0 || d.Type.Arguments.Any(a => a.Name is not null || a.Default is not null))+ { diagnostics.Add(HoleVariantUnknown); return null; }var variantName = d.Type.Arguments.Count == 1 ? FirmamentSyntaxValues.Reference(d.Type.Arguments[0].Value) : null;- if (!Enum.TryParse<FirmamentV2SemanticHoleVariant>(variantName, out var variant)) { diagnostics.Add(HoleVariantUnknown); return null; }- var axis = f.Word("On"); var point = f.Take("Center"); var diameter = f.Number("Diameter", "mm");+ if (!Enum.TryParse<FirmamentV2SemanticHoleVariant>(variantName, compatibilityStock is not null, out var variant)) { diagnostics.Add(HoleVariantUnknown); return null; }+ var on = f.Take("On"); var axis = FirmamentSyntaxValues.Reference(on);+ FirmamentV2FaceTarget? face = null;+ if (compatibilityStock is not null)+ {+ face = BindCompatibilityFace(on, compatibilityStock, HoleEntryFaceMissing, diagnostics);+ axis = face?.Axis;+ }+ var point = f.Take("Center");+ double Diameter(string canonical, string? legacyStem = null)+ {+ if (compatibilityStock is null) return f.Number(canonical, "mm");+ var names = legacyStem is null ? new[] { canonical } : new[] { canonical, legacyStem + "Diameter", legacyStem + "Radius" };+ if (canonical == "Diameter") names = ["Diameter", "ShaftDiameter", "Radius", "ShaftRadius"];+ var authored = names.Distinct().Select(name => (Name: name, Value: f.Take(name))).Where(pair => pair.Value is not null).ToArray();+ if (authored.Length != 1 || !FirmamentSyntaxValues.TryMeasure(authored.FirstOrDefault().Value, "mm", out var value, "mm"))+ { f.Invalid(canonical); return double.NaN; }+ return authored[0].Name.EndsWith("Radius", StringComparison.Ordinal) ? value * 2 : value;+ }+ var diameter = Diameter("Diameter");var endExpression = f.Take("End"); var end = FirmamentSyntaxValues.Reference(endExpression);f.Take("PatternIdentity");- FirmamentV2SemanticHoleEnd? termination = end == "ThroughAll" ? new(FirmamentV2SemanticHoleEndKind.ThroughAll) : null;- if (endExpression is CallSyntax { Target: ReferenceSyntax { Name.Text: "Blind" }, Arguments.Count: 1 } blind- && FirmamentSyntaxValues.TryMeasure(blind.Arguments[0].Value, "mm", out var depth) && depth > 0) termination = new(FirmamentV2SemanticHoleEndKind.Depth, depth);+ FirmamentV2SemanticHoleEnd? termination = (end == "ThroughAll" || compatibilityStock is not null && end == "throughAll") ? new(FirmamentV2SemanticHoleEndKind.ThroughAll) : null;+ if (endExpression is CallSyntax { Target: ReferenceSyntax { Name.Text: "Blind" or "depth" }, Arguments.Count: 1 } blind+ && (compatibilityStock is not null || blind.Target is ReferenceSyntax { Name.Text: "Blind" })+ && FirmamentSyntaxValues.TryMeasure(blind.Arguments[0].Value, "mm", out var depth, compatibilityStock is null ? null : "mm") && depth > 0) termination = new(FirmamentV2SemanticHoleEndKind.Depth, depth);+ if (compatibilityStock is not null && termination is null)+ diagnostics.Add(endExpression is CallSyntax { Target: ReferenceSyntax { Name.Text: "depth" } } ? HoleDepthInvalid : HoleEndMissing);double? cbDiameter = null, cbDepth = null, csDiameter = null, csAngle = null;- if (variant == FirmamentV2SemanticHoleVariant.Counterbore) { cbDiameter = f.Number("CounterboreDiameter", "mm"); cbDepth = f.Number("CounterboreDepth", "mm"); }- if (variant == FirmamentV2SemanticHoleVariant.Countersink) { csDiameter = f.Number("CountersinkDiameter", "mm"); csAngle = f.Number("CountersinkAngle", "deg"); }- if (point is not CallSyntax { Target: ReferenceSyntax { Name.Text: "Point2" } } || !FirmamentSyntaxValues.Vector(point, "mm", out var center) || center.Length != 2) { diagnostics.Add(CanonicalPoint2Invalid); return null; }+ if (variant == FirmamentV2SemanticHoleVariant.Counterbore) { cbDiameter = Diameter("CounterboreDiameter", "Counterbore"); cbDepth = f.Number("CounterboreDepth", "mm"); }+ if (variant == FirmamentV2SemanticHoleVariant.Countersink) { csDiameter = Diameter("CountersinkDiameter", "Countersink");+ var angle = f.Take("CountersinkAngle");+ csAngle = FirmamentSyntaxValues.TryMeasure(angle, "deg", out var degrees, compatibilityStock is null ? null : "deg") ? degrees : double.NaN; }+ if (compatibilityStock is null && point is not CallSyntax { Target: ReferenceSyntax { Name.Text: "Point2" } } || !FirmamentSyntaxValues.Vector(point, "mm", out var center, compatibilityStock is null ? null : "mm") || center.Length != 2) { diagnostics.Add(CanonicalPoint2Invalid); return null; }if (axis is not ("+X" or "-X" or "+Y" or "-Y" or "+Z" or "-Z") || termination is null || d.Name is null) { diagnostics.Add(CanonicalModifyMalformed); return null; }if (!(diameter > 0)) { diagnostics.Add(HoleDiameterInvalid); return null; }if (cbDiameter is not null && (!(cbDiameter > diameter) || !(cbDepth > 0))) { diagnostics.Add(HoleCounterboreInvalid); return null; }if (csDiameter is not null && (!(csDiameter > diameter) || !(csAngle > 0 && csAngle < 180))) { diagnostics.Add(HoleCountersinkInvalid); return null; }- var face = FirmamentV2FaceTarget.Direct(axis);+ face ??= FirmamentV2FaceTarget.Direct(axis);return new(d.Name.Text, variant, face, new(center[0], center[1], FirmamentV2FaceLocalPoint2D.ConventionFor(axis)), diameter, termination,cbDiameter, cbDepth, csDiameter, csAngle, SourceSpan: d.Span, AuthoredFields: f.AuthoredFields);}@@ -277,8 +308,10 @@ public static partial class FirmamentV2Parservar axis = f.Word("Face"); var target = f.Word("Target"); var kind = f.Word("Kind");var distance = f.Take("Distance"); var radius = f.Take("Radius");if ((distance is not null && radius is not null) || f.Declaration.Name is null || axis is null || target is null || kind is null- || !FirmamentSyntaxValues.TryMeasure(distance ?? radius, "mm", out var value) || value <= 0)+ || !FirmamentSyntaxValues.TryMeasure(distance ?? radius, "mm", out var value)){ diagnostics.Add(CanonicalModifyMalformed); return null; }+ // The selected feature admission owner diagnoses nonpositive distances and+ // radii with its existing capability-specific explanation during preflight.return new(f.Declaration.Name.Text, axis, target, kind, value, f.Declaration.Span);}@@ -296,6 +329,31 @@ public static partial class FirmamentV2Parserdouble.IsNaN(circumferential) ? null : circumferential, double.IsNaN(top) ? null : top, double.IsNaN(bottom) ? null : bottom, angle);}+ /// <summary>Dedicated material binders reuse construction-scope recognition and+ /// reject material operations that their engineering lowerer cannot consume.</summary>+ internal static void BindMaterialDomainScope(DocumentSyntax syntax, string materialKind, List<string> diagnostics)+ {+ void Bind(IReadOnlyList<StatementSyntax> statements)+ {+ foreach (var wrapper in statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text is "Model" or "Struct"+ && !d.Modifiers.Any(m => m.Name.Text is "Concept" or "Template") && d.Annotation is null))+ {+ if (wrapper.Type.Arguments.Count > 0 || wrapper.Clauses.Count > 0 || wrapper.Parameters.Count > 0 || wrapper.Initializer is not null)+ diagnostics.Add($"firmament-v2-domain-root-header-unsupported:{materialKind}:{wrapper.Name?.Text}");+ var units = wrapper.Body?.Statements.OfType<FieldSyntax>().Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Units")).ToArray() ?? [];+ if (wrapper.Type.Name.Text == "Model" && units.Length == 0 || units.Any(f => FirmamentSyntaxValues.Reference(f.Value) != "mm")) diagnostics.Add(CanonicalUnitsInvalid);+ Bind(wrapper.Body?.Statements ?? []);+ }+ var owned = statements.Where(s => s is not DeclarationSyntax d || !(d.Type.Name.Text == materialKind+ || d.Type.Name.Text is "Model" or "Struct" && !d.Modifiers.Any(m => m.Name.Text is "Concept" or "Template") && d.Annotation is null)).ToArray();+ BindMechanicalScope(owned, diagnostics);+ foreach (var declaration in owned.OfType<DeclarationSyntax>().Where(d => IsPrimitiveDeclaration(d)+ || d.Type.Name.Text is "Compose" or "Extrude" or "Revolve" or "WireForm" or "WireRoute" or "Sweep" or "SectionChain" or "Loft" or "Modify" or "Thread" or "EdgeFinish"))+ diagnostics.Add($"firmament-v2-domain-material-combination-unsupported:{materialKind}:{declaration.Type.Name.Text}: This material owner cannot consume the additional operation; use Assembly for separate parts.");+ }+ Bind(syntax.Statements);+ }+private static void BindMechanicalScope(IReadOnlyList<StatementSyntax> statements, List<string> diagnostics){foreach (var statement in statements)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex 55754125..c5d19724 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -229,28 +229,15 @@ public static partial class FirmamentV2Parserpublic const string SemanticProposalTargetUnresolved = "firmament-inline-step-semantic-proposal-target-unresolved";public const string SemanticProposalEndUnsupported = "firmament-inline-step-semantic-proposal-end-unsupported";- 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 HashSet<string> ReservedWords = new(StringComparer.Ordinal) { "let", "model", "units", "solid", "modify", "region", "cut", "template", "concept", "pmi", "recognize", "replace", "with", "manufacturing", "process", "feature", "true", "false", "int", "float", "length", "angle", "string", "bool", "tol" };private static readonly Regex LetRegex = new(@"\blet\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<type>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?<literal>[^\r\n{}]+)", RegexOptions.CultureInvariant);private static readonly Regex LetRecordHeaderRegex = new(@"^\s*let\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant | RegexOptions.Multiline);private static readonly Regex LetRecordFieldRegex = new(@"^\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<type>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?<literal>.+?)\s*$", RegexOptions.CultureInvariant);private static readonly Regex DottedReferenceRegex = new(@"^(?<record>[A-Za-z_][A-Za-z0-9_]*)\.(?<field>[A-Za-z_][A-Za-z0-9_]*)$", RegexOptions.CultureInvariant);- private static readonly Regex SolidHeaderRegex = new(@"\bsolid\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<target>[A-Za-z_][A-Za-z0-9_]*)(?<with>\s+with)?\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex LegacyEqualsSolidRegex = new(@"\bsolid\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?<target>[A-Za-z_][A-Za-z0-9_]*)(?<with>\s+with)?\s*\{(?<body>.*?)\}", RegexOptions.CultureInvariant | RegexOptions.Singleline);private static readonly Regex SizeRegex = new(@"\bsize\s*:\s*\[(?<values>[^\]]*)\]", RegexOptions.CultureInvariant | RegexOptions.Singleline);- private static readonly Regex ScalarFieldRegex = new(@"\b(?<field>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<value>[-+0-9.eE]+(?:mm)?)", RegexOptions.CultureInvariant);private static readonly Regex FieldRegex = new(@"(?<field>@[A-Za-z_][A-Za-z0-9_]*|[A-Za-z_][A-Za-z0-9_\.]*)\s*:", RegexOptions.CultureInvariant);- private static readonly Regex ExposeRegex = new(@"\bexpose\s*\{(?<body>.*?)\}", RegexOptions.CultureInvariant | RegexOptions.Singleline);- private static readonly Regex ExposureLineRegex = new(@"^\s*(?<selector>.+?)\s*=>\s*(?<alias>[A-Za-z_][A-Za-z0-9_]*)\s*$", RegexOptions.CultureInvariant);private static readonly Regex FaceSelectorRegex = new(@"^face\((?<axis>[+-][XYZ])\)(?<sub>\.[A-Za-z_][A-Za-z0-9_]*)?$", RegexOptions.CultureInvariant);- private static readonly Regex ModifyHeaderRegex = new(@"\bmodify\s+(?<target>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);- private static readonly Regex RegionHeaderRegex = new(@"\bregion\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s+on\s+(?<target>face\([^)]*\)|[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex CutHeaderRegex = new(@"\bcut\s+(?<tool>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex RadiusRegex = new(@"\bradius\s*:\s*(?<value>[^\s}]+)", RegexOptions.CultureInvariant);- private static readonly Regex ThroughRegex = new(@"\bthrough\s*:\s*(?<target>face\([^)]*\)|[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);private static readonly Regex CenterRegex = new(@"\bcenter\s*:\s*\[(?<values>[^\]]*)\]", RegexOptions.CultureInvariant | RegexOptions.Singleline);- private static readonly Regex SemanticHoleHeaderRegex = new(@"\bhole\s*<\s*(?<variant>[A-Za-z_][A-Za-z0-9_]*)\s*>\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);private static readonly Regex RecognizeHeaderRegex = new(@"\brecognize\s+(?<body>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);private static readonly Regex RecognitionRegionHeaderRegex = new(@"\bregion\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);private static readonly Regex KindRegex = new("\\bkind\\s*:\\s*(?<kind>\"[^\"]+\"|[A-Za-z_][A-Za-z0-9_]*(?:\\s*<\\s*[A-Za-z_][A-Za-z0-9_]*\\s*>)?)", RegexOptions.CultureInvariant);@@ -367,6 +354,21 @@ public static partial class FirmamentV2ParsersourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);var diagnostics = new List<string> { "firmament-v2-parser-invoked" };var source = StripLineComments(sourceText);+ var authoredSyntax = FirmamentSyntaxParser.Parse(source);+ if (MechanicalDeclarations(authoredSyntax.Document.Statements).Any(d => d.Type.Name.Text is "SectionChain" or "Loft"+ && !d.Modifiers.Any(m => m.Name.Text == "Template")))+ {+ var section = SectionChainAuthoringParser.Compile(source, materialize: false);+ diagnostics.AddRange(section.Diagnostics);+ var owner = authoredSyntax.Document.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d => d.Type.Name.Text is "Model" or "Struct"+ && !d.Modifiers.Any(m => m.Name.Text is "Concept" or "Template"))?.Name?.Text+ ?? section.Chain?.StableId ?? "SectionChain";+ return section.IsSuccess+ ? FirmamentV2ParseResult.Success(new(owner, "mm", []), diagnostics.Append("firmament-v2-parse-succeeded").ToArray())+ with { ParserRoute = "UnifiedSectionChain", OwnsUnifiedAdmission = true, BoundSectionChain = section, BoundSource = source }+ : FirmamentV2ParseResult.Failure(diagnostics.Append("firmament-v2-parse-failed").ToArray())+ with { ParserRoute = "UnifiedSectionChain", OwnsUnifiedAdmission = true, SyntaxDiagnostics = authoredSyntax.Diagnostics };+ }var polygonExpansion = ClosedBoundary2Authoring.Expand(source, diagnostics);if (polygonExpansion is null){@@ -436,111 +438,120 @@ public static partial class FirmamentV2Parsersource = canonicalStaticExpansion.Source;v2AdmissionCandidate |= IsV2AdmissionCandidate(source);- if (Regex.IsMatch(source, @"\bPanel\s+[A-Za-z_][A-Za-z0-9_]*\s*\{", RegexOptions.CultureInvariant))+ var syntax = FirmamentSyntaxParser.Parse(source);+ var domainDeclarations = MechanicalDeclarations(syntax.Document.Statements).ToArray();+ if (domainDeclarations.Any(d => Enum.TryParse<GearFamily>(d.Type.Name.Text, out _)))+ {+ var gear = GearAuthoring.Bind(syntax);+ diagnostics.AddRange(gear.Diagnostics);+ return gear.IsSuccess+ ? FirmamentV2ParseResult.Success(new(gear.ModelName, "mm", []), diagnostics.Append("firmament-v2-parse-succeeded").ToArray())+ with { ParserRoute = "UnifiedGear", OwnsUnifiedAdmission = true, BoundGear = gear, BoundSource = source, SyntaxDiagnostics = syntax.Diagnostics }+ : FirmamentV2ParseResult.Failure(diagnostics.Append("firmament-v2-parse-failed").ToArray())+ with { ParserRoute = "UnifiedGear", OwnsUnifiedAdmission = true, SyntaxDiagnostics = syntax.Diagnostics };+ }+ if (domainDeclarations.Any(d => d.Type.Name.Text == "Panel" && !d.Modifiers.Any(m => m.Name.Text == "Template"))){- var panelCompilation = FirmamentPanelCompiler.Compile(source, templateExpansion.Instantiations);+ var panelCompilation = FirmamentPanelCompiler.Bind(syntax, templateExpansion.Instantiations);diagnostics.AddRange(panelCompilation.Diagnostics);diagnostics.Add(panelCompilation.IsSuccess ? "firmament-v2-parse-succeeded" : "firmament-v2-parse-failed");if (!panelCompilation.IsSuccess)- return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray()) with { ParserRoute = "Panel" };+ return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray())+ with { ParserRoute = "UnifiedPanel", OwnsUnifiedAdmission = true, SyntaxDiagnostics = syntax.Diagnostics };var panelDocument = new FirmamentV2Document(panelCompilation.ModelName, "mm", [],TemplateInstantiations: templateExpansion.Instantiations, Panels: panelCompilation.Panels,FeatureDefinitions: featureExpansion.Definitions, FeatureInvocations: featureExpansion.Invocations,FeatureExpansion: featureExpansion.Metrics, Polygons: polygonExpansion.Polygons, Boundaries: polygonExpansion.Boundaries);- return FirmamentV2ParseResult.Success(panelDocument, diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray()) with { ParserRoute = "Panel" };+ return FirmamentV2ParseResult.Success(panelDocument, diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray())+ with { ParserRoute = "UnifiedPanel", OwnsUnifiedAdmission = true, BoundSource = source };}// Canonical V2 is parsed as one document, before compatibility adapters. The// adapters below remain only for old fixtures and no longer define the language// an author must select for ordinary mechanical work.- var syntax = FirmamentSyntaxParser.Parse(source);var modelSyntax = syntax.Document.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d =>d.Type.Name.Text is "Model" or "Struct" && !d.Modifiers.Any(m => m.Name.Text is "Template" or "Concept") && d.Body is not null- && (d.Type.Name.Text == "Model" || MechanicalDeclarations(d.Body.Statements).Any(n => IsPrimitiveDeclaration(n) || n.Type.Name.Text is "Compose" or "Extrude")));+ && (d.Type.Name.Text == "Model" || MechanicalDeclarations(d.Body.Statements).Any(n => IsPrimitiveDeclaration(n) || n.Type.Name.Text is "Compose" or "Extrude" or "Revolve" or "WireForm" or "WireRoute" or "Sweep" or "SectionChain")));+ var standaloneConstruction = modelSyntax is null && domainDeclarations.Any(d => d.Type.Name.Text is "Extrude" or "Compose");+ if (standaloneConstruction)+ {+ // A wrapper-free construction is the same lexical scope with implicit+ // millimetres. Project the existing statements; do not rewrite source.+ var owner = domainDeclarations.FirstOrDefault(d => d.Type.Name.Text is "Profile" or "Compose")?.Name+ ?? new IdentifierSyntax("StandaloneConstruction", syntax.Document.Span);+ modelSyntax = new(new(new("Struct", owner.Span), [], owner.Span), owner, [], [], null, null, [], null,+ new(syntax.Document.Statements, syntax.Document.Span) { Delimited = false }, false, syntax.Document.Span);+ syntax = syntax with { Document = syntax.Document with { Statements = [modelSyntax] } };+ }// Dedicated material domains retain their established semantic owners.// This is a decision over material declaration nodes, never a keyword// search that lets an unused guide choose the mechanical grammar.var rootMaterials = modelSyntax?.Body is null ? [] : MechanicalDeclarations(modelSyntax.Body.Statements).ToArray();var hasMechanicalMaterial = rootMaterials.Any(d => IsPrimitiveDeclaration(d) || d.Type.Name.Text is "Compose" or "Extrude");var dedicatedMaterialDomain = rootMaterials.Any(d => d.Type.Name.Text is "Revolve" or "WireForm" or "WireRoute" or "Sweep" or "SectionChain");+ if (domainDeclarations.Any(d => d.Type.Name.Text == "Revolve"))+ {+ if (!syntax.IsSuccess)+ return FirmamentV2ParseResult.Failure(diagnostics.Concat(syntax.Diagnostics.Select(d => d.Code)).ToArray())+ with { ParserRoute = "UnifiedRevolve", OwnsUnifiedAdmission = true, SyntaxDiagnostics = syntax.Diagnostics };+ var revolve = RevolveAuthoringParser.BindExpanded(source, syntax, out var revolveDiagnostics);+ diagnostics.AddRange(revolveDiagnostics);+ if (revolve is null || diagnostics.Any(IsFatalDiagnosticCode))+ return FirmamentV2ParseResult.Failure(diagnostics.Append("firmament-v2-parse-failed").ToArray()) with { ParserRoute = "UnifiedRevolve", OwnsUnifiedAdmission = true };+ return FirmamentV2ParseResult.Success(new(modelSyntax?.Name?.Text ?? revolve.Name, "mm", []), diagnostics.Append("firmament-v2-parse-succeeded").ToArray())+ with { ParserRoute = "UnifiedRevolve", OwnsUnifiedAdmission = true, BoundRevolve = revolve, BoundSource = source };+ }if (modelSyntax is not null && (hasMechanicalMaterial || !dedicatedMaterialDomain)){if (!syntax.IsSuccess)return FirmamentV2ParseResult.Failure(diagnostics.Concat(syntax.Diagnostics.Select(d => d.Code)).ToArray(), FirmamentV2ParseDisposition.RecognizedInvalid)- with { ParserRoute = "UnifiedMechanical", SyntaxDiagnostics = syntax.Diagnostics };+ with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true, SyntaxDiagnostics = syntax.Diagnostics };var parsed = Recognized(BindMechanicalModel(syntax.Document, modelSyntax, source, diagnostics, sourceDirectory, templateExpansion.Instantiations));- if (parsed.Document is null) return parsed with { ParserRoute = "UnifiedMechanical" };+ if (parsed.Document is null) return parsed with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true };+ if (domainDeclarations.Any(d => d.Type.Name.Text == "Plateau"))+ {+ var plateauDiagnostics = new List<string>();+ var plateau = PlateauAuthoring.Bind(source, plateauDiagnostics);+ if (plateau is null) return FirmamentV2ParseResult.Failure(diagnostics.Concat(plateauDiagnostics).Append("firmament-v2-parse-failed").ToArray())+ with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true };+ parsed = parsed with { BoundPlateau = plateau };+ }+ if (standaloneConstruction) parsed = parsed with { Document = parsed.Document with { ModelName = parsed.BoundProfile?.Name ?? parsed.BoundComposition?.Feature?.Name ?? parsed.Document.ModelName } };return WithFeatureMetadata(AttachVolumeAssertionsAndSymbols(WithPolygonMetadata(parsed, polygonExpansion), source, canonicalStaticExpansion.Document, diagnostics),- featureExpansion) with { ParserRoute = "UnifiedMechanical", BoundSource = parsed.BoundSource ?? source };+ featureExpansion) with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true, BoundSource = parsed.BoundSource ?? source };}- if (Regex.IsMatch(source, @"\b(?:RoundedBox|Frustum|Cylinder|Box)\s*<\s*[A-Za-z_][A-Za-z0-9_]*\s*>\s+[A-Za-z_]", RegexOptions.CultureInvariant))- return Recognized(ParsePrimitiveConstructionPolicyDocument(source, diagnostics)) with { ParserRoute = "PrimitiveConstructionPolicy" };-- if (Regex.IsMatch(source, @"\bRoundedBox\s+[A-Za-z_]", RegexOptions.CultureInvariant))- return Recognized(ParseRoundedBoxModelingDocument(source, diagnostics)) with { ParserRoute = "RoundedBox" };-- // Standalone Profile documents predate the canonical Model wrapper. Keep that- // bounded document form usable when its body uses the preferred pipeline surface,- // including inline guide declarations, instead of falling into an unrelated- // historical modeling parser merely because a Construction Plane has a Concept owner.- if (ProfileAuthoringParser.IsProfileSource(source) && Regex.IsMatch(source, @"\bExtrude\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant))- return Recognized(ParseStandaloneProfileDocument(source, diagnostics)) with { ParserRoute = "StandaloneProfile" };-- if (Regex.IsMatch(source, @"\bConcept\s+(?:Struct\s+)?[A-Za-z_]", RegexOptions.CultureInvariant)- || Regex.IsMatch(source, @"\b(?:Struct|Model)\s+[A-Za-z_][A-Za-z0-9_]*\s*(?::\s*[A-Za-z_][A-Za-z0-9_]*)?\s*\{", RegexOptions.CultureInvariant))+ if (syntax.Document.Statements.OfType<DeclarationSyntax>().Any(d => d.Type.Name.Text is "Model" or "Struct" or "Concept"+ || d.Modifiers.Any(m => m.Name.Text == "Concept")))return Recognized(WithFeatureMetadata(AttachVolumeAssertionsAndSymbols(WithPolygonMetadata(ParseConceptModelingDocument(RemoveCanonicalVolumeAssertions(source), diagnostics, templateExpansion.Instantiations), polygonExpansion), source, canonicalStaticExpansion.Document, diagnostics),featureExpansion)) with { ParserRoute = "ConceptModeling" };- if (Regex.IsMatch(source, @"^\s*Model\b", RegexOptions.CultureInvariant))- return Recognized(ParsePhase3ModelingDocument(source, diagnostics)) with { ParserRoute = "Phase3" };-if (ContainsRawBackendId(source)) diagnostics.Add(RawBackendIdReferenceForbidden);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 = FindSolids(source).ToArray();- if (solidMatches.Length == 0 && LegacyEqualsSolidRegex.IsMatch(source)) diagnostics.Add(UnsupportedConstruct);- var appearsStandaloneLattice = Regex.IsMatch(source, @"\bfill\s+[A-Za-z_][A-Za-z0-9_]*\s*\{[\s\S]*?\bpattern\s*:\s*CubicTruss\b", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);- if (solidMatches.Length == 0 && !appearsStandaloneLattice) diagnostics.Add(MissingSolid);-- var solids = new List<FirmamentV2SolidBinding>();- var byName = new Dictionary<string, FirmamentV2SolidBinding>(StringComparer.Ordinal);- if (modelMatch.Success && unitsMatch.Success)- {- foreach (var solid in solidMatches)- {- var name = solid.Name;- var target = solid.Target;- var body = solid.Body;- var isWith = solid.IsWith;- if (byName.ContainsKey(name)) { diagnostics.Add(DuplicateName); continue; }-- FirmamentV2SolidBinding? binding = isWith- ? ParseDerived(name, target, body, byName, diagnostics)- : ParseDirect(name, target, body, diagnostics, sourceDirectory);- if (binding is not null)- {- solids.Add(binding);- byName.Add(name, binding);- }- }- }+ var compatibilityModels = syntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "model").ToArray();+ var compatibilityModel = compatibilityModels.FirstOrDefault();+ if (compatibilityModel?.Body is null) diagnostics.Add(MissingModel);+ if (compatibilityModels.Length > 1) diagnostics.Add(DuplicateName);+ var units = compatibilityModel?.Body?.Statements.OfType<FieldSyntax>().Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Units")).ToArray() ?? [];+ if (units.Length == 0) diagnostics.Add(MissingUnits);+ else if (units.Length != 1 || FirmamentSyntaxValues.Reference(units[0].Value) != "mm") diagnostics.Add(CanonicalUnitsInvalid);+ var compatibilityCore = BindCompatibilityScope(syntax.Document, compatibilityModel, diagnostics);+ if (compatibilityCore) diagnostics.AddRange(syntax.Diagnostics.Select(d => d.Code));++ var byName = BindCompatibilitySolids(syntax, compatibilityModel, source, sourceDirectory, diagnostics);+ var solids = byName.Values.ToList();+ var appearsStandaloneLattice = compatibilityModel?.Body?.Statements.OfType<DeclarationSyntax>().Any(d => d.Type.Name.Text == "fill") == true;+ if (solids.Count == 0 && !appearsStandaloneLattice) diagnostics.Add(MissingSolid);var letRecords = ParseLetRecords(source, byName.Keys, diagnostics);var lets = ParseLets(source, byName.Keys.Concat(letRecords.Select(r => r.Name)), diagnostics);var boundLetRecords = BindLetRecords(letRecords);var boundLets = BindLets(lets, boundLetRecords, byName.Keys, diagnostics);- var modifyBlocks = ParseModifyBlocks(source, byName, diagnostics);+ var modifyBlocks = BindCompatibilityModifies(syntax, compatibilityModel, byName, diagnostics);var templates = ParseTemplates(source, diagnostics);var latticeFills = ParseLatticeFills(source, byName, diagnostics);var standaloneLatticeFills = ParseStandaloneLatticeFills(source, diagnostics);@@ -550,8 +561,8 @@ public static partial class FirmamentV2Parservar (manufacturingConcepts, featureConcepts) = ParseConceptApplications(source, boundLets, boundLetRecords, conceptCatalog, diagnostics);FirmamentV2Document? document = null;- if (modelMatch.Success && unitsMatch.Success && (solids.Count > 0 || standaloneLatticeFills.Count > 0) && !diagnostics.Any(d => d.StartsWith("firmament-v2-fill-", StringComparison.Ordinal)))- document = new FirmamentV2Document(modelMatch.Groups["name"].Value, unitsMatch.Groups["units"].Value, solids, modifyBlocks, templates, pmi, recognizedRegions, replacements, lets, boundLets, letRecords, boundLetRecords, manufacturingConcepts, featureConcepts, pmiBlock, boundPmi, null, latticeFills, standaloneLatticeFills);+ if (compatibilityModel?.Name is not null && units.Length == 1 && (solids.Count > 0 || standaloneLatticeFills.Count > 0) && !diagnostics.Any(d => d.StartsWith("firmament-v2-fill-", StringComparison.Ordinal)))+ document = new FirmamentV2Document(compatibilityModel.Name.Text, "mm", solids, modifyBlocks, templates, pmi, recognizedRegions, replacements, lets, boundLets, letRecords, boundLetRecords, manufacturingConcepts, featureConcepts, pmiBlock, boundPmi, null, latticeFills, standaloneLatticeFills);var hasFatalDiagnostics = diagnostics.Any(IsFatalDiagnosticCode);diagnostics.Add(document is null || hasFatalDiagnostics ? "firmament-v2-parse-failed" : "firmament-v2-parse-succeeded");@@ -560,12 +571,12 @@ public static partial class FirmamentV2Parserreturn FirmamentV2ParseResult.Failure(diagnostics, FirmamentV2ParseDisposition.NotRecognized);return document is null- ? FirmamentV2ParseResult.Failure(diagnostics) with { ParserRoute = "LegacyLowercase" }+ ? FirmamentV2ParseResult.Failure(diagnostics) with { ParserRoute = compatibilityCore ? "UnifiedCompatibility" : "CompatibilityExtensions", OwnsUnifiedAdmission = compatibilityCore, SyntaxDiagnostics = compatibilityCore ? syntax.Diagnostics : [] }: new FirmamentV2ParseResult(!hasFatalDiagnostics,document,diagnostics,- hasFatalDiagnostics ? FirmamentV2ParseDisposition.RecognizedInvalid : FirmamentV2ParseDisposition.RecognizedValid) { ParserRoute = "LegacyLowercase" };+ hasFatalDiagnostics ? FirmamentV2ParseDisposition.RecognizedInvalid : FirmamentV2ParseDisposition.RecognizedValid) { ParserRoute = compatibilityCore ? "UnifiedCompatibility" : "CompatibilityExtensions", OwnsUnifiedAdmission = compatibilityCore, SyntaxDiagnostics = compatibilityCore ? syntax.Diagnostics : [] };}private static FirmamentV2ParseResult Recognized(FirmamentV2ParseResult result) =>@@ -918,38 +929,6 @@ public static partial class FirmamentV2Parser}}- private static FirmamentV2SolidBinding? ParseDirect(string name, string recordType, string body, List<string> diagnostics, string? sourceDirectory)- {- if (string.Equals(recordType, "Box", StringComparison.Ordinal))- {- var values = ParseSizeField(body, diagnostics, BoxMissingSize);- var exposures = ParseExposures(body, diagnostics);- return values is null ? null : new(name, "Box", new FirmamentV2BoxRecord(values, exposures));- }-- if (string.Equals(recordType, "InlineStep", StringComparison.Ordinal))- {- return ParseInlineStep(name, body, diagnostics, sourceDirectory);- }-- if (recordType is not ("Cylinder" or "Cone" or "Sphere" or "Torus")) { diagnostics.Add(UnknownRecordType); return null; }-- var scalars = ParseScalarFields(body, diagnostics);- FirmamentV2PrimitiveRecord? primitive = recordType switch- {- "Cylinder" => RequireFields(scalars, diagnostics, "radius", "height") is null ? null : new FirmamentV2CylinderRecord(scalars["radius"], scalars["height"]),- "Cone" => RequireFields(scalars, diagnostics, "bottomRadius", "topRadius", "height") is null ? null : new FirmamentV2ConeRecord(scalars["bottomRadius"], scalars["topRadius"], scalars["height"]),- "Sphere" => RequireFields(scalars, diagnostics, "radius") is null ? null : new FirmamentV2SphereRecord(scalars["radius"]),- "Torus" => RequireFields(scalars, diagnostics, "majorRadius", "minorRadius") is null ? null : new FirmamentV2TorusRecord(scalars["majorRadius"], scalars["minorRadius"]),- _ => null- };- if (primitive is null) { return null; }- ValidatePrimitive(recordType, scalars, diagnostics);- return diagnostics.Contains(DegenerateDimension) || diagnostics.Contains(PrimitiveFieldInvalid) || diagnostics.Contains(PrimitiveFieldUnknown) || diagnostics.Contains(PrimitiveFieldMissing)- ? null- : new(name, recordType, primitive);- }-private static FirmamentV2SolidBinding? ParseInlineStep(string name, string body, List<string> diagnostics, string? sourceDirectory){var match = Regex.Match(body, "\\b(?:path|Path)\\s*:\\s*\\\"(?<path>[^\\\"]+)\\\"", RegexOptions.CultureInvariant);@@ -1011,20 +990,6 @@ public static partial class FirmamentV2Parserreturn false;}- private static FirmamentV2SolidBinding? ParseDerived(string name, string baseName, string body, Dictionary<string, FirmamentV2SolidBinding> byName, List<string> diagnostics)- {- if (!byName.TryGetValue(baseName, out var baseSolid)) { diagnostics.Add(NameUnresolved); if (Regex.IsMatch(body, @"\bsize\s*:", RegexOptions.CultureInvariant)) diagnostics.Add(WithForwardReference); return null; }- if (!string.Equals(baseSolid.RecordType, "Box", StringComparison.Ordinal)) { diagnostics.Add(WithRequiresBoxRecord); return null; }- var fields = FieldRegex.Matches(body).Select(m => m.Groups["field"].Value).ToArray();- if (fields.Length == 0) { diagnostics.Add(WithFieldNotFound); return null; }- if (fields.Any(f => f.StartsWith('@'))) { diagnostics.Add(WithRequiresRecord); return null; }- if (ExposeRegex.IsMatch(body)) { diagnostics.Add(ExposeBlockUnsupported); return null; }- if (fields.Any(f => !string.Equals(f, "size", StringComparison.Ordinal))) { diagnostics.Add(WithFieldNotFound); return null; }- var values = ParseSizeField(body, diagnostics, WithFieldTypeMismatch);- if (values is null) { diagnostics.Add(WithDerivedRecordInvalid); return null; }- return new(name, "Box", new FirmamentV2BoxRecord(values, []), baseName, new Dictionary<string, IReadOnlyList<double>>(StringComparer.Ordinal) { ["size"] = values });- }-/// <summary>/// Brace-depth extraction retained by legacy semantic adapters. Mechanical/// document and statement admission is owned by the unified syntax tree.@@ -1050,8 +1015,8 @@ public static partial class FirmamentV2Parser/// </summary>private static FirmamentV2ParseResult BindMechanicalConstruction(string source, DeclarationSyntax model, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations){- var rootOpen = model.Body!.Span.Start;- var body = source.Substring(rootOpen + 1, model.Body.Span.Length - 2);+ var bodySpan = model.Body!.ContentSpan;+ var body = source.Substring(bodySpan.Start, bodySpan.Length);var units = model.Body.Statements.OfType<FieldSyntax>().Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Units")).ToArray();if (units.Length == 0 && model.Type.Name.Text != "Struct" || units.Any(f => FirmamentSyntaxValues.Reference(f.Value) != "mm"))return CanonicalFailure(diagnostics, CanonicalUnitsInvalid);@@ -1070,7 +1035,7 @@ public static partial class FirmamentV2Parser}var feature = composition.Feature;var compositionSelectionDiagnostics = new List<string>();- var compositionSelections = ParseCanonicalSelections(body, rootOpen + 1, compositionSelectionDiagnostics);+ var compositionSelections = ParseCanonicalSelections(body, bodySpan.Start, compositionSelectionDiagnostics);ValidateCanonicalSelectionSources(body, compositionSelections, composition.Profiles.Keys, compositionSelectionDiagnostics);if (compositionSelectionDiagnostics.Count > 0){@@ -1122,7 +1087,7 @@ public static partial class FirmamentV2Parser}var resolved = profile.Profile;var profileSelectionDiagnostics = new List<string>();- var profileSelections = ParseCanonicalSelections(body, rootOpen + 1, profileSelectionDiagnostics);+ var profileSelections = ParseCanonicalSelections(body, bodySpan.Start, profileSelectionDiagnostics);ValidateCanonicalSelectionSources(body, profileSelections, [resolved.Name], profileSelectionDiagnostics);if (profileSelectionDiagnostics.Count > 0){@@ -1172,7 +1137,7 @@ public static partial class FirmamentV2Parserdiagnostics);if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);var conceptSelectionDiagnostics = new List<string>();- var conceptSelections = ParseCanonicalSelections(body, rootOpen + 1, conceptSelectionDiagnostics);+ var conceptSelections = ParseCanonicalSelections(body, bodySpan.Start, conceptSelectionDiagnostics);ValidateCanonicalSelectionSources(body, conceptSelections, [], conceptSelectionDiagnostics);if (conceptSelectionDiagnostics.Count > 0){@@ -1250,7 +1215,7 @@ public static partial class FirmamentV2Parservar selections = new List<FirmamentV2SelectionDecl>();var names = new HashSet<string>(StringComparer.Ordinal);var syntax = FirmamentSyntaxParser.Parse(body);- foreach (var declaration in FirmamentSyntaxEvidence.Declarations(syntax.Document).Where(d => d.Type.Name.Text == "Selection"))+ foreach (var declaration in FirmamentSyntaxTraversal.Declarations(syntax.Document).Where(d => d.Type.Name.Text == "Selection")){var name = declaration.Name?.Text ?? "";if (!names.Add(name)) { diagnostics.Add($"{SelectionDuplicateName}:{name}"); continue; }@@ -1407,7 +1372,7 @@ public static partial class FirmamentV2ParserIEnumerable<string> profileNames, List<string> diagnostics){var profiles = profileNames.ToHashSet(StringComparer.Ordinal);- var declarations = FirmamentSyntaxEvidence.Declarations(FirmamentSyntaxParser.Parse(body).Document).ToArray();+ var declarations = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(body).Document).ToArray();foreach (var selection in selections){// Result categories retain the existing semantic contract. Source syntax@@ -1438,7 +1403,7 @@ public static partial class FirmamentV2Parser{var syntax = FirmamentSyntaxParser.Parse(source);var model = syntax.Document.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d => d.Type.Name.Text == "Model" && !d.Modifiers.Any(m => m.Name.Text == "Template") && d.Body is not null);- body = model?.Body is { } block ? source[..model.Span.Start] + source.Substring(block.Span.Start + 1, block.Span.Length - 2) + source[(model.Span.Start + model.Span.Length)..] : string.Empty;+ body = model?.Body is { } block ? source[..model.Span.Start] + source.Substring(block.ContentSpan.Start, block.ContentSpan.Length) + source[(model.Span.Start + model.Span.Length)..] : string.Empty;return model?.Body is not null;}@@ -1751,279 +1716,6 @@ public static partial class FirmamentV2Parserreturn FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray());}- private static FirmamentV2ParseResult ParseStandaloneProfileDocument(string source, List<string> diagnostics)- {- var parsed = ProfileAuthoringParser.Parse(source);- diagnostics.AddRange(parsed.Diagnostics);- if (parsed.Profile is null || diagnostics.Any(IsFatalDiagnosticCode))- return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);-- var profile = parsed.Profile;- var extrude = Regex.Match(source, @"\bExtrude\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);- var solidName = extrude.Success ? extrude.Groups["name"].Value : profile.Name;- var document = new FirmamentV2Document(- profile.Name,- "mm",- [new FirmamentV2SolidBinding(solidName, "Profile", new FirmamentV2AdvancedMaterialRecord("Profile"))],- Profiles: [new FirmamentV2ProfileDecl(profile.Name, profile.EffectiveConstructionPlane.StableId, profile.LocalStartDepth ?? 0d, profile.LocalEndDepth ?? parsed.Height, new(0, source.Length))]);- diagnostics.Add("firmament-v2-standalone-profile-parsed");- diagnostics.Add("firmament-v2-parse-succeeded");- return FirmamentV2ParseResult.Success(document, diagnostics.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray());- }-- private static FirmamentV2ParseResult ParsePhase3ModelingDocument(string source, List<string> diagnostics)- {- var model = Regex.Match(source, @"^\s*Model\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s+(?<units>[A-Za-z_][A-Za-z0-9_]*)\b", RegexOptions.CultureInvariant);- var primitive = Regex.Match(source, @"\b(?<type>Box|Cylinder)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- var modify = Regex.Match(source, @"\bModify\s+(?<target>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- var edges = Regex.Matches(source, @"\bEdgeFinish\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant).Cast<Match>().ToArray();- var edge = edges.FirstOrDefault() ?? Match.Empty;- if (!model.Success || !primitive.Success || !modify.Success || !edge.Success || model.Groups["units"].Value != "mm"- || Regex.Matches(source, @"\b(?:Box|Cylinder)\s+[A-Za-z_]", RegexOptions.CultureInvariant).Count != 1- || Regex.Matches(source, @"\bModify\s+[A-Za-z_]", RegexOptions.CultureInvariant).Count != 1- || edges.Length is < 1 or > 3)- diagnostics.Add(Phase3EdgeFinishSyntaxInvalid);-- if (diagnostics.Contains(Phase3EdgeFinishSyntaxInvalid))- return FirmamentV2ParseResult.Failure(diagnostics.Append("firmament-v2-parse-failed").Order().ToArray());-- var primitiveOpen = source.IndexOf('{', primitive.Index);- var primitiveClose = FindMatchingBrace(source, primitiveOpen);- var modifyOpen = source.IndexOf('{', modify.Index);- var modifyClose = FindMatchingBrace(source, modifyOpen);- var edgeOpen = source.IndexOf('{', edge.Index);- var edgeClose = FindMatchingBrace(source, edgeOpen);- if (primitiveClose < 0 || modifyClose < 0 || edgeClose < 0 || edge.Index < modifyOpen || edgeClose > modifyClose)- {- diagnostics.Add(Phase3EdgeFinishSyntaxInvalid);- return FirmamentV2ParseResult.Failure(diagnostics.Append("firmament-v2-parse-failed").Order().ToArray());- }-- var primitiveBody = source[(primitiveOpen + 1)..primitiveClose];- var sizeMatch = Regex.Match(primitiveBody, @"\bSize\s*:\s*\[(?<values>[^\]]+)\]", RegexOptions.CultureInvariant);- var values = sizeMatch.Success ? sizeMatch.Groups["values"].Value.Split(',').Select(ParsePhase3Length).ToArray() : [];- var radiusMatch = Regex.Match(primitiveBody, @"\bRadius\s*:\s*(?<value>[-+0-9.eE]+mm)\b", RegexOptions.CultureInvariant);- var heightMatch = Regex.Match(primitiveBody, @"\bHeight\s*:\s*(?<value>[-+0-9.eE]+mm)\b", RegexOptions.CultureInvariant);- var radiusValue = radiusMatch.Success ? ParsePhase3Length(radiusMatch.Groups["value"].Value) : double.NaN;- var heightValue = heightMatch.Success ? ParsePhase3Length(heightMatch.Groups["value"].Value) : double.NaN;- var edgeBody = source[(edgeOpen + 1)..edgeClose];- var face = Regex.Match(edgeBody, @"\bFace\s*:\s*(?<value>[+-][XYZ])", RegexOptions.CultureInvariant);- var target = Regex.Match(edgeBody, @"\bTarget\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);- var kind = Regex.Match(edgeBody, @"\bKind\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);- var distance = Regex.Match(edgeBody, @"\bDistance\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);- var primitiveValid = primitive.Groups["type"].Value == "Box"- ? values.Length == 3 && values.All(v => double.IsFinite(v) && v > 0d)- : double.IsFinite(radiusValue) && radiusValue > 0d && double.IsFinite(heightValue) && heightValue > 0d;- if (!primitiveValid || !face.Success || !target.Success || !kind.Success || !distance.Success- || !double.TryParse(distance.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var distanceValue) || !double.IsFinite(distanceValue)- || primitive.Groups["name"].Value != modify.Groups["target"].Value)- {- diagnostics.Add(Phase3EdgeFinishSyntaxInvalid);- return FirmamentV2ParseResult.Failure(diagnostics.Append("firmament-v2-parse-failed").Order().ToArray());- }-- FirmamentV2PrimitiveRecord primitiveRecord = primitive.Groups["type"].Value == "Box"- ? new FirmamentV2BoxRecord(values, [])- : new FirmamentV2CylinderRecord(radiusValue, heightValue);- var solid = new FirmamentV2SolidBinding(primitive.Groups["name"].Value, primitive.Groups["type"].Value, primitiveRecord);- var finishes = new List<FirmamentV2EdgeFinishDecl> { new(edge.Groups["name"].Value, face.Groups["value"].Value, target.Groups["value"].Value, kind.Groups["value"].Value, distanceValue, new FirmamentV2SourceSpan(edge.Index, edgeClose - edge.Index + 1)) };- foreach (var additionalEdge in edges.Skip(1))- {- var additionalOpen = source.IndexOf('{', additionalEdge.Index);- var additionalClose = FindMatchingBrace(source, additionalOpen);- var additionalBody = additionalClose < 0 ? string.Empty : source[(additionalOpen + 1)..additionalClose];- var additionalFace = Regex.Match(additionalBody, @"\bFace\s*:\s*(?<value>[+-][XYZ])", RegexOptions.CultureInvariant);- var additionalTarget = Regex.Match(additionalBody, @"\bTarget\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);- var additionalKind = Regex.Match(additionalBody, @"\bKind\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);- var additionalDistance = Regex.Match(additionalBody, @"\bDistance\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);- if (additionalClose < 0 || !additionalFace.Success || !additionalTarget.Success || !additionalKind.Success- || !additionalDistance.Success || !double.TryParse(additionalDistance.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var additionalDistanceValue) || !double.IsFinite(additionalDistanceValue))- {- diagnostics.Add(Phase3EdgeFinishSyntaxInvalid);- return FirmamentV2ParseResult.Failure(diagnostics.Append("firmament-v2-parse-failed").Order().ToArray());- }- finishes.Add(new(additionalEdge.Groups["name"].Value, additionalFace.Groups["value"].Value, additionalTarget.Groups["value"].Value, additionalKind.Groups["value"].Value, additionalDistanceValue, new FirmamentV2SourceSpan(additionalEdge.Index, additionalClose - additionalEdge.Index + 1)));- }- var document = new FirmamentV2Document(model.Groups["name"].Value, "mm", [solid], [new FirmamentV2ModifyBlock(solid.Name, [], [], finishes)]);- diagnostics.Add("firmament-v2-phase3-edge-finish-parsed");- diagnostics.Add("firmament-v2-parse-succeeded");- diagnostics.Sort(StringComparer.Ordinal);- return FirmamentV2ParseResult.Success(document, diagnostics);- }-- /// <summary>Bounded direct syntax for AIR-ROUNDED-BOX-M6. It intentionally- /// accepts only one history-known rounded box and its single complete +Z boundary finish.</summary>- private static FirmamentV2ParseResult ParseRoundedBoxModelingDocument(string source, List<string> diagnostics)- {- var model = Regex.Match(source, @"^\s*(?:Model|Struct)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)(?:\s+(?<units>[A-Za-z_][A-Za-z0-9_]*))?\s*\{?", RegexOptions.CultureInvariant);- var primitive = Regex.Match(source, @"\bRoundedBox\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- if (!model.Success || !primitive.Success || Regex.Matches(source, @"\bRoundedBox\s+[A-Za-z_]", RegexOptions.CultureInvariant).Count != 1)- return RoundedBoxParseFailure(diagnostics);- if (model.Groups["units"].Success && model.Groups["units"].Value != "mm") return RoundedBoxParseFailure(diagnostics);- var open = source.IndexOf('{', primitive.Index); var close = FindMatchingBrace(source, open);- if (close < 0) return RoundedBoxParseFailure(diagnostics);- var body = source[(open + 1)..close];- var size = Regex.Match(body, @"\bSize\s*:\s*\[(?<values>[^\]]+)\]", RegexOptions.CultureInvariant);- var corner = Regex.Match(body, @"\bCornerRadius\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);- var values = size.Success ? size.Groups["values"].Value.Split(',').Select(ParsePhase3Length).ToArray() : [];- if (values.Length != 3 || values.Any(v => !double.IsFinite(v) || v <= 0d) || !corner.Success || !double.TryParse(corner.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var rc) || !double.IsFinite(rc) || rc <= 0d || rc >= double.Min(values[0], values[1]) / 2d)- return RoundedBoxParseFailure(diagnostics);-- var solid = new FirmamentV2SolidBinding(primitive.Groups["name"].Value, "RoundedBox", new FirmamentV2RoundedBoxRecord(values, rc));- var modifies = Regex.Matches(source, @"\bModify\s+(?<target>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant).Cast<Match>().ToArray();- if (modifies.Length > 1 || (modifies.Length == 1 && modifies[0].Groups["target"].Value != solid.Name)) return RoundedBoxParseFailure(diagnostics);- var blocks = new List<FirmamentV2ModifyBlock>();- if (modifies.Length == 1)- {- var modify = modifies[0]; var modifyOpen = source.IndexOf('{', modify.Index); var modifyClose = FindMatchingBrace(source, modifyOpen);- var finishes = Regex.Matches(source, @"\bEdgeFinish\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant).Cast<Match>().ToArray();- if (modifyClose < 0 || finishes.Length != 1) return RoundedBoxParseFailure(diagnostics);- var edge = finishes[0]; var edgeOpen = source.IndexOf('{', edge.Index); var edgeClose = FindMatchingBrace(source, edgeOpen);- if (edgeClose < 0 || edge.Index < modifyOpen || edgeClose > modifyClose) return RoundedBoxParseFailure(diagnostics);- var edgeBody = source[(edgeOpen + 1)..edgeClose];- var face = Regex.Match(edgeBody, @"\bFace\s*:\s*(?<value>[+-][XYZ])", RegexOptions.CultureInvariant);- var target = Regex.Match(edgeBody, @"\bTarget\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);- var kind = Regex.Match(edgeBody, @"\bKind\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);- var radius = Regex.Match(edgeBody, @"\bRadius\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);- if (!face.Success || !target.Success || !kind.Success || !radius.Success || !double.TryParse(radius.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var rf) || !double.IsFinite(rf)) return RoundedBoxParseFailure(diagnostics);- blocks.Add(new FirmamentV2ModifyBlock(solid.Name, [], [], [new FirmamentV2EdgeFinishDecl(edge.Groups["name"].Value, face.Groups["value"].Value, target.Groups["value"].Value, kind.Groups["value"].Value, rf, new FirmamentV2SourceSpan(edge.Index, edgeClose - edge.Index + 1))]));- }- diagnostics.Add("firmament-v2-rounded-box-parsed"); diagnostics.Add("firmament-v2-parse-succeeded"); diagnostics.Sort(StringComparer.Ordinal);- return FirmamentV2ParseResult.Success(new FirmamentV2Document(model.Groups["name"].Value, "mm", [solid], blocks), diagnostics.Distinct(StringComparer.Ordinal).ToArray());- }-- private static FirmamentV2ParseResult RoundedBoxParseFailure(List<string> diagnostics)- {- diagnostics.Add(Phase3EdgeFinishSyntaxInvalid); diagnostics.Add("firmament-v2-parse-failed");- return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray());- }-- /// <summary>- /// Bounded generic primitive construction syntax. Angle brackets are not a general type-argument escape hatch:- /// this parser accepts only the named construction policies and witnesses admitted by the production compiler.- /// </summary>- private static FirmamentV2ParseResult ParsePrimitiveConstructionPolicyDocument(string source, List<string> diagnostics)- {- var model = Regex.Match(source, @"^\s*(?:Struct|Model)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);- var primitive = Regex.Match(source, @"\b(?<type>[A-Za-z_][A-Za-z0-9_]*)\s*<\s*(?<policy>[A-Za-z_][A-Za-z0-9_]*)\s*>\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- if (!model.Success || !primitive.Success || Regex.Matches(source, @"\b(?:RoundedBox|Frustum|Cylinder|Box)\s*<\s*[A-Za-z_][A-Za-z0-9_]*\s*>\s+[A-Za-z_]", RegexOptions.CultureInvariant).Count != 1)- return ConstructionPolicyParseFailure(diagnostics);-- var type = primitive.Groups["type"].Value;- var policy = primitive.Groups["policy"].Value;- if (policy != "Hollow") { diagnostics.Add(UnknownConstructionPolicy); return ConstructionPolicyParseFailure(diagnostics); }- if (type is not ("RoundedBox" or "Frustum" or "Cylinder")) { diagnostics.Add(PrimitiveDoesNotSatisfyHollowConstructible); return ConstructionPolicyParseFailure(diagnostics); }- var open = source.IndexOf('{', primitive.Index); var close = FindMatchingBrace(source, open);- if (close < 0) return ConstructionPolicyParseFailure(diagnostics);- FirmamentV2ModifyBlock? modification = null;- var modify = Regex.Match(source[(close + 1)..], @"\bModify\s+(?<target>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- if (modify.Success)- {- var absoluteOpen = close + 1 + modify.Index + modify.Length - 1;- var modifyClose = FindMatchingBrace(source, absoluteOpen);- if (type != "Cylinder" || modify.Groups["target"].Value != primitive.Groups["name"].Value || modifyClose < 0 ||- Regex.Matches(source[(close + 1)..], @"\bModify\s+[A-Za-z_]", RegexOptions.CultureInvariant).Count != 1)- {- diagnostics.Add("firmament-v2-hollow-modify-unsupported");- return ConstructionPolicyParseFailure(diagnostics);- }- var modifyBody = source[(absoluteOpen + 1)..modifyClose];- var perforationHeader = CanonicalPerforationHeaderRegex.Match(modifyBody);- var perforationOpen = perforationHeader.Success ? modifyBody.IndexOf('{', perforationHeader.Index) : -1;- var perforationClose = perforationOpen >= 0 ? FindMatchingBrace(modifyBody, perforationOpen) : -1;- var outsidePerforation = perforationClose < 0 ? modifyBody :- modifyBody[..perforationHeader.Index] + modifyBody[(perforationClose + 1)..];- var perforations = ParseCanonicalPerforations(modifyBody, absoluteOpen + 1, diagnostics);- if (perforations.Count != 1 || perforations[0].SupportFace != "OuterWall" ||- perforations[0].Layout is not ("CylindricalGrid" or "CylindricalStaggered") ||- CanonicalPerforationHeaderRegex.Matches(modifyBody).Count != 1 ||- outsidePerforation.Trim(' ', '\t', '\r', '\n', ';').Length != 0 ||- Regex.IsMatch(modifyBody, @"\b(?:Hole|Region|EdgeFinish|Fillet|Chamfer)\b", RegexOptions.CultureInvariant) ||- diagnostics.Any(IsFatalDiagnosticCode))- {- diagnostics.Add("firmament-v2-hollow-modify-unsupported");- return ConstructionPolicyParseFailure(diagnostics);- }- modification = new FirmamentV2ModifyBlock(primitive.Groups["name"].Value, [], [], Perforations: perforations);- }- var body = source[(open + 1)..close];- var thickness = Regex.Match(body, @"\bWallThickness\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);- if (!thickness.Success) { diagnostics.Add(WallThicknessRequired); return ConstructionPolicyParseFailure(diagnostics); }- if (!double.TryParse(thickness.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var wall) || !double.IsFinite(wall) || wall <= 0d)- { diagnostics.Add(WallThicknessMustBePositive); return ConstructionPolicyParseFailure(diagnostics); }- var openings = Regex.Match(body, @"\bOpenings\s*:\s*\[(?<items>[^\]]*)\]", RegexOptions.CultureInvariant);- var openingItems = openings.Success ? openings.Groups["items"].Value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) : [];- if (openingItems.Length != 1 || openingItems[0] != "Top")- {- diagnostics.Add(openingItems.Length > 1 ? MultipleOpeningsNotSupported : UnsupportedOpening);- return ConstructionPolicyParseFailure(diagnostics);- }-- FirmamentV2PrimitiveRecord? record = null;- if (type == "RoundedBox")- {- var size = Regex.Match(body, @"\bSize\s*:\s*\[(?<values>[^\]]+)\]", RegexOptions.CultureInvariant);- var corner = Regex.Match(body, @"\bCornerRadius\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);- var values = size.Success ? size.Groups["values"].Value.Split(',').Select(ParsePhase3Length).ToArray() : [];- if (values.Length != 3 || values.Any(v => !double.IsFinite(v) || v <= 0d) || !corner.Success || !double.TryParse(corner.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var radius) || !double.IsFinite(radius) || radius <= 0d)- return ConstructionPolicyParseFailure(diagnostics);- record = new FirmamentV2RoundedBoxRecord(values, radius);- }- else if (type == "Cylinder")- {- double Read(string field)- {- var m = Regex.Match(body, $@"\b{field}\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);- return m.Success && double.TryParse(m.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : double.NaN;- }- var radius = Read("Radius"); var height = Read("Height");- if (!double.IsFinite(radius) || !double.IsFinite(height) || radius <= 0d || height <= 0d)- return ConstructionPolicyParseFailure(diagnostics);- record = new FirmamentV2CylinderRecord(radius, height);- }- else- {- double Read(string field)- {- var m = Regex.Match(body, $@"\b{field}\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);- return m.Success && double.TryParse(m.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : double.NaN;- }- var bottom = Read("BottomRadius"); var top = Read("TopRadius"); var height = Read("Height");- if (!double.IsFinite(bottom) || !double.IsFinite(top) || !double.IsFinite(height) || bottom <= 0d || top <= 0d || height <= 0d || double.Abs(top - bottom) <= 1e-12d)- return ConstructionPolicyParseFailure(diagnostics);- record = new FirmamentV2FrustumRecord(bottom, top, height);- }-- var bottomBlend = Regex.Match(body, @"\bBottomBlendRadius\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);- var bottomBlendRadius = 0d;- if (!bottomBlend.Success && Regex.IsMatch(body, @"\bBottomBlendRadius\b", RegexOptions.CultureInvariant))- {- diagnostics.Add("firmament-v2-hollow-bottom-blend-invalid");- return ConstructionPolicyParseFailure(diagnostics);- }- if (bottomBlend.Success)- {- if (type != "Cylinder" || !double.TryParse(bottomBlend.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out bottomBlendRadius) ||- !double.IsFinite(bottomBlendRadius) || bottomBlendRadius <= wall || record is not FirmamentV2CylinderRecord cylinder ||- bottomBlendRadius >= cylinder.Radius || bottomBlendRadius >= cylinder.Height)- {- diagnostics.Add("firmament-v2-hollow-bottom-blend-invalid");- return ConstructionPolicyParseFailure(diagnostics);- }- }- var hollow = new FirmamentV2HollowIntent(wall, ["Top"], new FirmamentV2SourceSpan(primitive.Index, close - primitive.Index + 1), bottomBlendRadius);- var solid = new FirmamentV2SolidBinding(primitive.Groups["name"].Value, type, record, ConstructionPolicy: FirmamentV2ConstructionPolicy.Hollow, Hollow: hollow);- diagnostics.Add("firmament-v2-hollow-policy-parsed"); diagnostics.Add("firmament-v2-parse-succeeded"); diagnostics.Sort(StringComparer.Ordinal);- return FirmamentV2ParseResult.Success(new FirmamentV2Document(model.Groups["name"].Value, "mm", [solid],- modification is null ? null : [modification]), diagnostics.Distinct(StringComparer.Ordinal).ToArray());- }-- private static FirmamentV2ParseResult ConstructionPolicyParseFailure(List<string> diagnostics)- {- diagnostics.Add("firmament-v2-parse-failed");- return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray());- }-private static FirmamentV2ParseResult ParseConceptModelingDocument(string source, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations = null){var resolution = ConceptIrResolver.Resolve(source, diagnostics);@@ -2066,49 +1758,6 @@ public static partial class FirmamentV2ParserFirmamentInterop.FirmamentV2DiagnosticAdapter.ParserSeverity(code)== Aetheris.Forge.Abstractions.FirmamentInterop.FirmamentDiagnosticSeverity.Fatal;- private static IReadOnlyList<FirmamentV2Exposure> ParseExposures(string body, List<string> diagnostics)- {- var match = ExposeRegex.Match(body);- if (!match.Success)- {- if (body.Contains("=>", StringComparison.Ordinal)) diagnostics.Add(FatArrowOutsideExpose);- return [];- }-- var exposures = new List<FirmamentV2Exposure>();- var aliases = new HashSet<string>(StringComparer.Ordinal);- foreach (var rawLine in match.Groups["body"].Value.Split('\n'))- {- var line = rawLine.Trim();- if (line.Length == 0) continue;- var binding = ExposureLineRegex.Match(line);- if (!binding.Success) { diagnostics.Add(SelectorUnsupported); continue; }- var alias = binding.Groups["alias"].Value;- if (!aliases.Add(alias)) { diagnostics.Add(ExposeAliasDuplicate); continue; }- var selector = binding.Groups["selector"].Value.Trim();- if (selector.StartsWith("edge(", StringComparison.Ordinal) || selector.StartsWith("vertex(", StringComparison.Ordinal)) { diagnostics.Add(SelectorUnsupported); continue; }- var face = FaceSelectorRegex.Match(selector);- if (!face.Success)- {- if (selector.StartsWith("face(", StringComparison.Ordinal)) diagnostics.Add(SelectorAxisInvalid);- else diagnostics.Add(SelectorUnsupported);- continue;- }- var axis = face.Groups["axis"].Value;- var sub = face.Groups["sub"].Success ? face.Groups["sub"].Value[1..] : null;- if (sub is not null && !string.Equals(sub, "outerLoop", StringComparison.Ordinal)) { diagnostics.Add(SelectorSubselectorUnsupported); continue; }- exposures.Add(new(alias, "face", selector, sub is null ? "FaceRef" : "LoopRef", axis, sub));- }- return exposures;- }-- private static IReadOnlyList<double>? ParseSizeField(string body, List<string> diagnostics, string missingDiagnostic)- {- var sizeMatch = SizeRegex.Match(body);- if (!sizeMatch.Success) { diagnostics.Add(missingDiagnostic); return null; }- return ParseSizeValues(sizeMatch.Groups["values"].Value, diagnostics);- }-private static IReadOnlyList<double>? ParseSizeValues(string raw, List<string> diagnostics){var parts = raw.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);@@ -2123,130 +1772,6 @@ public static partial class FirmamentV2Parserreturn diagnostics.Contains(DegenerateDimension) ? null : values;}- private static Dictionary<string, double> ParseScalarFields(string body, List<string> diagnostics)- {- var fields = FieldRegex.Matches(body).Select(m => m.Groups["field"].Value).Where(f => !f.StartsWith('@')).ToHashSet(StringComparer.Ordinal);- var values = new Dictionary<string, double>(StringComparer.Ordinal);- foreach (Match match in ScalarFieldRegex.Matches(body))- {- var raw = match.Groups["value"].Value;- if (!double.TryParse(raw.EndsWith("mm", StringComparison.Ordinal) ? raw[..^2] : raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) || !double.IsFinite(value))- {- diagnostics.Add(PrimitiveFieldInvalid);- continue;- }- values[match.Groups["field"].Value] = value;- }- foreach (var field in fields)- if (!values.ContainsKey(field)) diagnostics.Add(PrimitiveFieldInvalid);- return values;- }-- private static object? RequireFields(Dictionary<string, double> values, List<string> diagnostics, params string[] required)- {- foreach (var requiredField in required)- if (!values.ContainsKey(requiredField)) diagnostics.Add(PrimitiveFieldMissing);- foreach (var field in values.Keys)- if (!required.Contains(field, StringComparer.Ordinal)) diagnostics.Add(PrimitiveFieldUnknown);- return diagnostics.Contains(PrimitiveFieldMissing) || diagnostics.Contains(PrimitiveFieldUnknown) ? null : new object();- }-- private static void ValidatePrimitive(string recordType, Dictionary<string, double> values, List<string> diagnostics)- {- foreach (var (field, value) in values)- {- if (recordType == "Cone" && field == "topRadius" && value == 0d) continue;- if (value <= 0d) diagnostics.Add(DegenerateDimension);- }- if (recordType == "Cone" && values.TryGetValue("bottomRadius", out var bottom) && bottom <= 0d) diagnostics.Add(DegenerateDimension);- if (recordType == "Torus" && values.TryGetValue("majorRadius", out var major) && values.TryGetValue("minorRadius", out var minor) && major <= minor) diagnostics.Add(PrimitiveFieldInvalid);- }-- private static IReadOnlyList<FirmamentV2ModifyBlock> ParseModifyBlocks(string source, Dictionary<string, FirmamentV2SolidBinding> byName, List<string> diagnostics)- {- var blocks = new List<FirmamentV2ModifyBlock>();- foreach (Match match in ModifyHeaderRegex.Matches(source))- {- var target = match.Groups["target"].Value;- if (!byName.TryGetValue(target, out var solid)) { diagnostics.Add(ModifyTargetUnresolved); continue; }- if (!string.Equals(solid.RecordType, "Box", StringComparison.Ordinal)) { diagnostics.Add(ModifyTargetNotSolid); continue; }- var open = source.IndexOf('{', match.Index);- var close = FindMatchingBrace(source, open);- if (close < 0) { diagnostics.Add(RegionUnsupported); continue; }- var body = source[(open + 1)..close];- var regions = new List<FirmamentV2RegionDecl>();- var region = ParseRegion(body, solid, diagnostics);- if (region is not null) regions.Add(region);- var holes = ParseSemanticHoles(body, solid, diagnostics);- if (regions.Count > 0 || holes.Count > 0) blocks.Add(new(target, regions, holes));- }- return blocks;- }-- private static FirmamentV2RegionDecl? ParseRegion(string body, FirmamentV2SolidBinding solid, List<string> diagnostics)- {- var regions = RegionHeaderRegex.Matches(body);- if (regions.Count == 0) return null;- if (regions.Count != 1) { diagnostics.Add(RegionUnsupported); return null; }- var rm = regions[0];- if (!string.Equals(rm.Groups["name"].Value, "sideHole", StringComparison.Ordinal)) { diagnostics.Add(RegionUnsupported); return null; }- var attach = ResolveFaceTarget(rm.Groups["target"].Value, solid, RegionAttachmentSelectorUnsupported, diagnostics);- var open = body.IndexOf('{', rm.Index);- var close = FindMatchingBrace(body, open);- if (close < 0) { diagnostics.Add(RegionUnsupported); return null; }- var cut = ParseCut(body[(open + 1)..close], solid, diagnostics);- if (attach is null || cut is null) return null;- var centerU = cut.Tool.Center?.U ?? 0;- var centerV = cut.Tool.Center?.V ?? 0;- var route = FirmamentV2SideHoleRoutePolicy.Resolve(attach.Axis, cut.Tool.Through.Axis, solid.Box!.Size, cut.Tool.Radius, centerU, centerV);- if (!route.IsSupported)- {- diagnostics.Add(route.Diagnostic!);- if (route.Diagnostic is SideHoleRouteUnsupported && (attach.Kind == "Alias" || cut.Tool.Through.Kind == "Alias")) diagnostics.Add(SideHoleAliasResolvesToUnsupportedFace);- diagnostics.Add(SideHoleOnlyPlusXMinusXSupported);- }- return diagnostics.Any(IsFatalDiagnosticCode) ? null : new(rm.Groups["name"].Value, "FaceAttachedRegion", attach, cut);- }-- private static IReadOnlyList<FirmamentV2SemanticHoleDecl> ParseSemanticHoles(string body, FirmamentV2SolidBinding solid, List<string> diagnostics)- {- var holes = new List<FirmamentV2SemanticHoleDecl>();- foreach (Match hm in SemanticHoleHeaderRegex.Matches(body))- {- if (!Enum.TryParse<FirmamentV2SemanticHoleVariant>(hm.Groups["variant"].Value, true, out var variant)) { diagnostics.Add(HoleVariantUnknown); continue; }- var open = body.IndexOf('{', hm.Index);- var close = FindMatchingBrace(body, open);- if (close < 0) { diagnostics.Add(RegionUnsupported); continue; }- var hb = body[(open + 1)..close];- var on = Regex.Match(hb, @"\bon\s*:\s*(?<target>face\([^)]*\)|[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);- var face = on.Success ? ResolveFaceTarget(on.Groups["target"].Value, solid, HoleEntryFaceMissing, diagnostics) : null;- if (face is null) diagnostics.Add(HoleEntryFaceMissing);- var center = CenterRegex.IsMatch(hb) ? ParseCenter(hb, diagnostics) : null;- if (center is null) diagnostics.Add(HoleCenterMissing);- var hasShaftDiameter = ReadPositive(hb, ["shaftDiameter", "diameter"], out var shaftDiameter);- double shaftRadius = 0d;- var hasShaftRadius = !hasShaftDiameter && ReadPositive(hb, ["shaftRadius", "radius"], out shaftRadius);- var shaft = hasShaftDiameter || hasShaftRadius;- var shaftDia = hasShaftDiameter ? shaftDiameter : (hasShaftRadius ? shaftRadius * 2d : 0d);- if (!shaft) diagnostics.Add(HoleShaftMissing);- var end = ParseEnd(hb, diagnostics);- double? cbDia = null, cbDepth = null, csDia = null, csAngle = null;- if (variant == FirmamentV2SemanticHoleVariant.Counterbore)- {- if (!(ReadPositive(hb, ["counterboreDiameter"], out var d) || (ReadPositive(hb, ["counterboreRadius"], out var r) && (d = r * 2d) > 0)) || d <= shaftDia) diagnostics.Add(HoleCounterboreInvalid); else cbDia = d;- if (!ReadPositive(hb, ["counterboreDepth"], out var depth)) diagnostics.Add(HoleCounterboreInvalid); else cbDepth = depth;- }- if (variant == FirmamentV2SemanticHoleVariant.Countersink)- {- if (!(ReadPositive(hb, ["countersinkDiameter"], out var d) || (ReadPositive(hb, ["countersinkRadius"], out var r) && (d = r * 2d) > 0)) || d <= shaftDia) diagnostics.Add(HoleCountersinkInvalid); else csDia = d;- if (!ReadPositive(hb, ["countersinkAngle"], out var angle) || angle <= 0 || angle >= 180) diagnostics.Add(HoleCountersinkInvalid); else csAngle = angle;- }- if (face is not null && center is not null && shaft && end is not null && !diagnostics.Any(IsFatalDiagnosticCode))- holes.Add(new(hm.Groups["name"].Value, variant, face, center with { Convention = FirmamentV2FaceLocalPoint2D.ConventionFor(face.Axis) }, shaftDia, end, cbDia, cbDepth, csDia, csAngle));- }- return holes;- }-private static FirmamentV2SemanticHoleEnd? ParseEnd(string body, List<string> diagnostics){var m = Regex.Match(body, @"\bend\s*:\s*(?<kind>throughAll|depth)(?:\s+(?<value>[^\s}]+))?", RegexOptions.CultureInvariant);@@ -2271,28 +1796,6 @@ public static partial class FirmamentV2Parserreturn false;}- private static FirmamentV2CutOperation? ParseCut(string body, FirmamentV2SolidBinding solid, List<string> diagnostics)- {- var cuts = CutHeaderRegex.Matches(body);- if (cuts.Count != 1) { diagnostics.Add(CutUnsupported); return null; }- var cm = cuts[0];- if (!string.Equals(cm.Groups["tool"].Value, "Cylinder", StringComparison.Ordinal) && !string.Equals(cm.Groups["tool"].Value, "cylinder", StringComparison.Ordinal)) { diagnostics.Add(CutToolUnsupported); return null; }- var open = body.IndexOf('{', cm.Index);- var close = FindMatchingBrace(body, open);- if (close < 0) { diagnostics.Add(CutUnsupported); return null; }- var toolBody = body[(open + 1)..close];- var radiusMatch = RadiusRegex.Match(toolBody);- if (!radiusMatch.Success) { diagnostics.Add(CylinderRadiusMissing); return null; }- if (!double.TryParse(radiusMatch.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var radius)) { diagnostics.Add(CylinderRadiusInvalid); return null; }- if (!double.IsFinite(radius)) { diagnostics.Add(CylinderRadiusNotFinite); return null; }- if (radius <= 0) { diagnostics.Add(CylinderRadiusInvalid); return null; }- var center = ParseCenter(toolBody, diagnostics);- var throughMatch = ThroughRegex.Match(toolBody);- var through = throughMatch.Success ? ResolveFaceTarget(throughMatch.Groups["target"].Value, solid, ThroughSelectorUnsupported, diagnostics) : null;- if (through is null) { diagnostics.Add(ThroughSelectorUnsupported); return null; }- return new("Cut", new("Cylinder", radius, center, through));- }-private static FirmamentV2FaceLocalPoint2D? ParseCenter(string toolBody, List<string> diagnostics){var match = CenterRegex.Match(toolBody);@@ -3035,19 +2538,6 @@ public static partial class FirmamentV2Parserprivate static bool ContainsRawBackendId(string source) =>Regex.IsMatch(source, @"\b(brep|backend|coedge)\s*\.|STEP\s*#", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);- private sealed record SolidMatch(string Name, string Target, bool IsWith, string Body);-- private static IEnumerable<SolidMatch> FindSolids(string source)- {- foreach (Match match in SolidHeaderRegex.Matches(source))- {- var open = source.IndexOf('{', match.Index);- var close = FindMatchingBrace(source, open);- if (close < 0) continue;- yield return new(match.Groups["name"].Value, match.Groups["target"].Value, match.Groups["with"].Success, source[(open + 1)..close]);- }- }-private static int FindMatchingBrace(string source, int open){var depth = 0;diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/GearAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/GearAuthoring.csindex 2f0f0667..a6fd9e98 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/GearAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/GearAuthoring.cs@@ -1,5 +1,4 @@-using System.Globalization;-using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Geometry.Curves;@@ -103,89 +102,119 @@ public static class GearAuthoring{public const string Prefix = "firmament-gear-";private const double Tol = 1e-9;- private static readonly Regex Header = new(- @"\b(?<family>SpurGear|InternalSpurGear|BevelGear|MiterGear|RatchetGear|Pawl)\s+(?<name>[A-Za-z_]\w*)\s*\{",- RegexOptions.CultureInvariant);- private static readonly Regex InterfaceHeader = new(- @"\bInterface\s*<\s*Gear\s*>\s+(?<name>[A-Za-z_]\w*)\s*\{",- RegexOptions.CultureInvariant);+ private static bool IsGear(DeclarationSyntax declaration) => Enum.TryParse<GearFamily>(declaration.Type.Name.Text, out _);+ private static bool IsGearInterface(DeclarationSyntax declaration) => declaration.Type.Name.Text == "Interface"+ && declaration.Type.Arguments.Count == 1 && declaration.Type.Arguments[0].Name is null && declaration.Type.Arguments[0].Default is null+ && FirmamentSyntaxValues.Reference(declaration.Type.Arguments[0].Value) == "Gear";- public static bool IsGearSource(string source) => Header.IsMatch(source) || InterfaceHeader.IsMatch(source);- public static bool HasGearDefinitions(string source) => Header.IsMatch(source);+ public static bool IsGearSource(string source) => FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)+ .Any(d => IsGear(d) || IsGearInterface(d));+ public static bool HasGearDefinitions(string source) => FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Any(IsGear);- /// <summary>Parses only the compiler-owned Gear declarations in a mixed-domain source.</summary>- public static GearAuthoringDocument ParseDefinitions(string source)- {- ArgumentNullException.ThrowIfNull(source);- var diagnostics = new List<string>();- var modelMatch = Regex.Match(source, @"\bModel\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);- var modelName = modelMatch.Success ? modelMatch.Groups["name"].Value : "GearModel";- if (!Regex.IsMatch(source, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant))- diagnostics.Add(Prefix + "units-invalid:mm-required");- var gears = ParseGearDeclarations(source, diagnostics);- if (gears.Count == 0) diagnostics.Add(Prefix + "declaration-missing");- return new(modelName, gears, [], diagnostics.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray());- }+ /// <summary>Binds compiler-owned gear definitions within a mixed-domain document.</summary>+ public static GearAuthoringDocument ParseDefinitions(string source) => Bind(FirmamentSyntaxParser.Parse(source), definitionsOnly: true);+ public static GearAuthoringDocument Parse(string source) => Bind(FirmamentSyntaxParser.Parse(source));- public static GearAuthoringDocument Parse(string source)+ internal static GearAuthoringDocument Bind(SyntaxParseResult syntax, bool definitionsOnly = false){- ArgumentNullException.ThrowIfNull(source);- var diagnostics = new List<string>();- var modelMatch = Regex.Match(source, @"\bModel\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);- var modelName = modelMatch.Success ? modelMatch.Groups["name"].Value : "GearModel";- if (!Regex.IsMatch(source, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant))+ var declarations = FirmamentV2Parser.MechanicalDeclarations(syntax.Document.Statements).ToArray();+ // Definition extraction is an extension point of Assembly, not admission+ // of the enclosing document. Only syntax inside the gear definitions is+ // owned here; the Assembly frontend owns its requirements and mate syntax.+ var ownedSyntax = definitionsOnly ? syntax.Diagnostics.Where(d => d.SourceSpan is { } span && declarations.Where(IsGear)+ .Any(gear => span.Start >= gear.Span.Start && span.Start <= gear.Span.Start + gear.Span.Length)) : syntax.Diagnostics;+ var diagnostics = ownedSyntax.Select(d => d.Code + ": " + d.Message).ToList();+ var roots = syntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => !d.Modifiers.Any(m => m.Name.Text is "Template" or "Concept")).ToArray();+ var model = roots.FirstOrDefault(d => d.Type.Name.Text == "Model") ?? roots.FirstOrDefault(d => d.Type.Name.Text == "Struct"+ && FirmamentV2Parser.MechanicalDeclarations(d.Body?.Statements ?? []).Any(IsGear));+ var modelName = model?.Name?.Text ?? "GearModel";+ var units = (model?.Body?.Statements ?? syntax.Document.Statements).OfType<FieldSyntax>()+ .Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Units")).ToArray();+ if (units.Length == 0 || units.Any(f => FirmamentSyntaxValues.Reference(f.Value) != "mm"))diagnostics.Add(Prefix + "units-invalid:mm-required");-- var gears = ParseGearDeclarations(source, diagnostics);-+ if (!definitionsOnly) CloseScope(syntax.Document.Statements, diagnostics);+ var gears = new List<GearAir>();+ foreach (var declaration in declarations.Where(IsGear))+ {+ var family = Enum.Parse<GearFamily>(declaration.Type.Name.Text);+ var name = declaration.Name?.Text ?? "";+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);+ double? Length(string field) => OptionalNumber(fields, field, "mm");+ double? Angle(string field) => OptionalNumber(fields, field, "deg");+ var teethValue = OptionalNumber(fields, "Teeth", "");+ int? teeth = null;+ if (teethValue is { } count)+ {+ if (double.IsFinite(count) && count == Math.Truncate(count) && count is >= int.MinValue and <= int.MaxValue) teeth = (int)count;+ else fields.Invalid("Teeth");+ }+ var axisExpression = fields.Take("Axis");+ var axis = new[] { 0d, 0d, 1d };+ if (axisExpression is not null && (!FirmamentSyntaxValues.Vector(axisExpression, "", out axis) || axis.Length != 3))+ { fields.Invalid("Axis"); axis = [0d, 0d, 1d]; }+ var gear = new GearAir(name, family, Length("Module"), teeth, Angle("PressureAngle"),+ Length(family == GearFamily.Pawl ? "Thickness" : "FaceWidth") ?? 0d,+ Length("BoreDiameter") ?? 0d, Angle("Phase") ?? 0d, Length("Backlash") ?? 0d,+ Length("OutsideDiameter"), Angle("PitchConeAngle"), Length("HubDiameter"), Length("HubLength"),+ Length("Width"), Length("Length"), Length("PivotDiameter"), Length("NoseLength"),+ Angle("EngagementAngle"), Angle("DriveFaceAngle"), axis, declaration.Span);+ fields.Complete();+ if (declaration.Type.Arguments.Count > 0 || declaration.Modifiers.Count > 0 || name.Length == 0)+ diagnostics.Add(Prefix + "declaration-header-invalid:" + name);+ Validate(gear, diagnostics);+ gears.Add(gear);+ }+ foreach (var duplicate in gears.GroupBy(g => g.Name, StringComparer.Ordinal).Where(g => g.Count() > 1))+ diagnostics.Add(Prefix + "duplicate-identity:" + duplicate.Key);var interfaces = new List<InterfaceAir<GearAir>>();- foreach (Match header in InterfaceHeader.Matches(source))+ if (!definitionsOnly) foreach (var declaration in declarations.Where(IsGearInterface)){- var open = source.IndexOf('{', header.Index); var close = MatchingBrace(source, open);- if (close < 0) { diagnostics.Add(Prefix + "interface-unclosed:" + header.Groups["name"].Value); continue; }- var body = source[(open + 1)..close]; var aName = Identifier(body, "A"); var bName = Identifier(body, "B");- if (aName is null || bName is null) { diagnostics.Add(Prefix + "interface-endpoint-missing:" + header.Groups["name"].Value); continue; }- var a = gears.SingleOrDefault(gear => gear.Name == aName); var b = gears.SingleOrDefault(gear => gear.Name == bName);- if (a is null || b is null) { diagnostics.Add(Prefix + "interface-endpoint-unresolved:" + header.Groups["name"].Value); continue; }- interfaces.Add(EvaluateInterface(header.Groups["name"].Value, a, b,- Angle(body, "ShaftAngle"), Angle(body, "EngagementPhase"), Identifier(body, "AllowedDirection"),- new(header.Index, close - header.Index + 1)));+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);+ var name = declaration.Name?.Text ?? "";+ var aName = fields.Word("A"); var bName = fields.Word("B");+ var shaft = OptionalNumber(fields, "ShaftAngle", "deg");+ var phase = OptionalNumber(fields, "EngagementPhase", "deg");+ var directionExpression = fields.Take("AllowedDirection");+ var direction = FirmamentSyntaxValues.Reference(directionExpression);+ if (directionExpression is not null && direction is null) fields.Invalid("AllowedDirection");+ fields.Complete();+ var a = gears.FirstOrDefault(g => g.Name == aName); var b = gears.FirstOrDefault(g => g.Name == bName);+ if (aName is null || bName is null) diagnostics.Add(Prefix + "interface-endpoint-missing:" + name);+ else if (a is null || b is null) diagnostics.Add(Prefix + "interface-endpoint-unresolved:" + name);+ else interfaces.Add(EvaluateInterface(name, a, b, shaft, phase, direction, declaration.Span));}- diagnostics.AddRange(interfaces.Where(item => !item.Compatible).SelectMany(item => item.RejectionReasons.Select(reason => $"{Prefix}interface-incompatible:{item.Name}:{reason}")));+ diagnostics.AddRange(interfaces.Where(i => !i.Compatible).SelectMany(i => i.RejectionReasons.Select(r => $"{Prefix}interface-incompatible:{i.Name}:{r}")));if (gears.Count == 0) diagnostics.Add(Prefix + "declaration-missing");return new(modelName, gears, interfaces, diagnostics.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray());}- private static List<GearAir> ParseGearDeclarations(string source, List<string> diagnostics)+ private static double? OptionalNumber(FirmamentSyntaxFields fields, string name, string unit){- var gears = new List<GearAir>();- foreach (Match header in Header.Matches(source))+ var expression = fields.Take(name);+ if (expression is null) return null;+ if (FirmamentSyntaxValues.TryMeasure(expression, unit, out var value)) return value;+ fields.Invalid(name); return null;+ }++ private static void CloseScope(IEnumerable<StatementSyntax> statements, List<string> diagnostics)+ {+ foreach (var statement in statements){- var open = source.IndexOf('{', header.Index);- var close = MatchingBrace(source, open);- if (close < 0) { diagnostics.Add(Prefix + "declaration-unclosed:" + header.Groups["name"].Value); continue; }- var family = Enum.Parse<GearFamily>(header.Groups["family"].Value);- var name = header.Groups["name"].Value;- var body = source[(open + 1)..close];- double? module = Length(body, "Module");- int? teeth = Integer(body, "Teeth");- double? pressure = Angle(body, "PressureAngle");- var face = Length(body, family == GearFamily.Pawl ? "Thickness" : "FaceWidth") ?? 0d;- var bore = Length(body, "BoreDiameter") ?? 0d;- var gear = new GearAir(name, family, module, teeth, pressure, face, bore,- Angle(body, "Phase") ?? 0d, Length(body, "Backlash") ?? 0d,- Length(body, "OutsideDiameter"), Angle(body, "PitchConeAngle"),- Length(body, "HubDiameter"), Length(body, "HubLength"),- Length(body, "Width"), Length(body, "Length"), Length(body, "PivotDiameter"),- Length(body, "NoseLength"), Angle(body, "EngagementAngle"), Angle(body, "DriveFaceAngle"),- Vector3(body, "Axis") ?? [0d, 0d, 1d],- new(header.Index, close - header.Index + 1));- Validate(gear, diagnostics);- gears.Add(gear);+ if (statement is DirectiveSyntax) continue;+ if (statement is FieldSyntax field && FirmamentSyntaxFields.SameField(field.Name.Text, "Units")) continue;+ if (statement is DeclarationSyntax declaration)+ {+ if (IsGear(declaration) || IsGearInterface(declaration)) continue;+ if (declaration.Modifiers.Any(m => m.Name.Text is "Concept" or "Template")) continue;+ if (declaration.Type.Name.Text is "Model" or "Struct" && declaration.Body is not null)+ {+ if (declaration.Type.Arguments.Count > 0 || declaration.Parameters.Count > 0 || declaration.Clauses.Count > 0 || declaration.Annotation is not null || declaration.Initializer is not null)+ diagnostics.Add($"firmament-v2-domain-root-header-unsupported:{declaration.Type.Name.Text}:{declaration.Name?.Text}");+ CloseScope(declaration.Body.Statements, diagnostics); continue;+ }+ }+ diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:Gear:{(statement as DeclarationSyntax)?.Type.Name.Text ?? (statement as FieldSyntax)?.Name.Text ?? "expression"}");}- foreach (var duplicate in gears.GroupBy(gear => gear.Name, StringComparer.Ordinal).Where(group => group.Count() > 1))- diagnostics.Add(Prefix + "duplicate-identity:" + duplicate.Key);- return gears;}public static GearMaterialization? Materialize(GearAir gear, out IReadOnlyList<string> diagnostics)@@ -444,22 +473,7 @@ public static class GearAuthoringprivate static (double X, double Y) Bezier(LineArcCubicBezier2D curve, double t){ var s = 1d - t; return (s*s*s*curve.Start.X + 3*s*s*t*curve.Control1.X + 3*s*t*t*curve.Control2.X + t*t*t*curve.End.X, s*s*s*curve.Start.Y + 3*s*s*t*curve.Control1.Y + 3*s*t*t*curve.Control2.Y + t*t*t*curve.End.Y); }private static double Distance((double X, double Y) a, (double X, double Y) b) => Math.Sqrt((a.X-b.X)*(a.X-b.X)+(a.Y-b.Y)*(a.Y-b.Y));- private static double? Length(string body, string field) => NumberField(body, field, "mm");- private static double? Angle(string body, string field) => NumberField(body, field, "deg");- private static double? NumberField(string body, string field, string unit)- { var match = Regex.Match(body, $@"\b{Regex.Escape(field)}\s*:\s*(?<value>[-+.\deE]+)\s*{unit}\b", RegexOptions.CultureInvariant); return match.Success && double.TryParse(match.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : null; }- private static int? Integer(string body, string field)- { var match = Regex.Match(body, $@"\b{Regex.Escape(field)}\s*:\s*(?<value>[-+]?\d+)\b", RegexOptions.CultureInvariant); return match.Success && int.TryParse(match.Groups["value"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : null; }- private static string? Identifier(string body, string field)- { var match = Regex.Match(body, $@"\b{Regex.Escape(field)}\s*:\s*(?<value>[A-Za-z_]\w*)\b", RegexOptions.CultureInvariant); return match.Success ? match.Groups["value"].Value : null; }- private static IReadOnlyList<double>? Vector3(string body, string field)- {- var match = Regex.Match(body, $@"\b{Regex.Escape(field)}\s*:\s*\[\s*(?<x>[-+.\deE]+)\s*,\s*(?<y>[-+.\deE]+)\s*,\s*(?<z>[-+.\deE]+)\s*\]", RegexOptions.CultureInvariant);- return match.Success ? [Number(match.Groups["x"].Value), Number(match.Groups["y"].Value), Number(match.Groups["z"].Value)] : null;- }- private static double Number(string value) => double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture);- private static int MatchingBrace(string source, int open)- { var depth = 0; for (var index = open; index >= 0 && index < source.Length; index++) { if (source[index] == '{') depth++; else if (source[index] == '}' && --depth == 0) return index; } return -1; }+}internal sealed record GearBevelMaterializationResult(GearMaterialization? Materialization, IReadOnlyList<string> Diagnostics);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.csindex f1bbd116..adbbc892 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs@@ -1,5 +1,4 @@-using System.Globalization;-using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Firmament.Materializer;using Aetheris.Surfacing;@@ -14,8 +13,6 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;/// </summary>public static class LoftAuthoringParser{- private static readonly Regex Header = new(@"\bLoft(?:\s*<\s*(?<kind>Hollow)\s*>)?\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);-public static readonly IReadOnlyList<FirmamentAuthoringField> SolidFields = FirmamentSchemaAuthoringFields.For("Loft");public static readonly IReadOnlyList<FirmamentAuthoringField> HollowFields =[.. SolidFields,@@ -25,74 +22,58 @@ public static class LoftAuthoringParserpublic static bool TryGetAuthoringFields(string source, int offset, out IReadOnlyList<FirmamentAuthoringField> fields){fields = [];- foreach (Match match in Header.Matches(source))+ foreach (var declaration in FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Where(d => d.Type.Name.Text == "Loft")){- var open = match.Index + match.Length - 1;- if (offset <= open) continue;- var close = MatchingBrace(source, open);- if (close >= 0 && offset > close) continue;- fields = match.Groups["kind"].Success ? HollowFields : SolidFields;+ var span = declaration.Body?.Span ?? declaration.Span;+ if (offset <= span.Start || offset > span.Start + span.Length) continue;+ fields = declaration.Type.Arguments.Count > 0 ? HollowFields : SolidFields;return true;}return false;}- public static bool IsLoftSource(string source) => Header.IsMatch(source);+ public static bool IsLoftSource(string source) => FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Any(d => d.Type.Name.Text == "Loft");public static SectionChainAuthoringResult Compile(string source, bool materialize = true){ArgumentNullException.ThrowIfNull(source);source = FirmamentSourceSpelling.Normalize(source);var diagnostics = new List<string>();- if (!Regex.IsMatch(source, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant))+ var syntax = FirmamentSyntaxParser.Parse(source);+ FirmamentV2Parser.BindMaterialDomainScope(syntax.Document, "Loft", diagnostics);+ diagnostics.AddRange(syntax.Diagnostics.Select(d => d.Code + ": " + d.Message));+ if (!FirmamentSyntaxTraversal.Statements(syntax.Document).OfType<FieldSyntax>().Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Units") && FirmamentSyntaxValues.Reference(f.Value) == "mm"))diagnostics.Add("loft-units-invalid:millimetres-required");- var declarations = Header.Matches(source).Cast<Match>().ToArray();- if (declarations.Length != 1)- return Fail($"loft-count-invalid:expected=1:actual={declarations.Length}");- if (Regex.IsMatch(source, @"\bSectionChain\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant))- return Fail("loft-section-chain-ambiguous:one-surfacing-root-required");-+ var allDeclarations = FirmamentV2Parser.MechanicalDeclarations(syntax.Document.Statements).ToArray();+ var declarations = allDeclarations.Where(d => d.Type.Name.Text == "Loft").ToArray();+ if (declarations.Length != 1) return Fail($"loft-count-invalid:expected=1:actual={declarations.Length}");+ if (allDeclarations.Any(d => d.Type.Name.Text == "SectionChain")) return Fail("loft-section-chain-ambiguous:one-surfacing-root-required");var declaration = declarations[0];- var open = source.IndexOf('{', declaration.Index + declaration.Length - 1);- var close = MatchingBrace(source, open);- if (close < 0) return Fail("loft-block-unclosed");- var body = source[(open + 1)..close];- var name = declaration.Groups["name"].Value;- var hollow = declaration.Groups["kind"].Success;- var allowed = (hollow ? HollowFields : SolidFields).Select(field => field.Name).ToHashSet(StringComparer.Ordinal);- var fields = Regex.Matches(body, @"(?m)^\s*(?<key>[A-Za-z_]\w*)\s*:", RegexOptions.CultureInvariant)- .Cast<Match>().Select(match => match.Groups["key"].Value).ToArray();- foreach (var field in fields.Where(field => !allowed.Contains(field)))- diagnostics.Add($"loft-field-unknown:{field}");- foreach (var field in fields.GroupBy(field => field, StringComparer.Ordinal).Where(group => group.Count() > 1))- diagnostics.Add($"loft-field-duplicate:{field.Key}");- var rearProfileName = Field(body, "RearProfile");- var frontProfileName = Field(body, "FrontProfile");- var rearFrameName = Field(body, "RearFrame");- var frontFrameName = Field(body, "FrontFrame");- var rule = Field(body, "Rule");- var correspondence = Field(body, "Correspondence");+ var name = declaration.Name?.Text ?? "";+ var hollow = declaration.Type.Arguments.Count > 0;+ if (name.Length == 0 || declaration.Modifiers.Count > 0) diagnostics.Add("loft-header-invalid");+ if (hollow && (declaration.Type.Arguments.Count != 1 || declaration.Type.Arguments[0].Name is not null || declaration.Type.Arguments[0].Default is not null+ || FirmamentSyntaxValues.Reference(declaration.Type.Arguments[0].Value) != "Hollow"))+ diagnostics.Add("loft-construction-policy-unsupported");+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);+ var rearProfileName = fields.Word("RearProfile"); var frontProfileName = fields.Word("FrontProfile");+ var rearFrameName = fields.Word("RearFrame"); var frontFrameName = fields.Word("FrontFrame");+ var rule = fields.Word("Rule"); var correspondence = fields.Word("Correspondence");if (rule != "Ruled") diagnostics.Add($"loft-rule-unsupported:{rule ?? "<missing>"}:expected=Ruled");if (correspondence != "CommonRay") diagnostics.Add($"loft-correspondence-unsupported:{correspondence ?? "<missing>"}:expected=CommonRay");if (rearProfileName is null || frontProfileName is null || rearFrameName is null || frontFrameName is null)diagnostics.Add("loft-section-input-missing:RearProfile,FrontProfile,RearFrame,FrontFrame-required");- var thickness = 0d;- var thicknessText = Scalar(body, "Thickness");- if (hollow && (thicknessText is null || !ProfileAuthoringParser.TryMeasure(thicknessText, "mm", out thickness) || thickness <= 0))- diagnostics.Add("loft-thickness-invalid:positive-length-required");- var seamDegrees = 0.1d;- var seamText = RawField(body, "SeamGap");- if (seamText is not null && (!TryDegrees(seamText, out seamDegrees) || seamDegrees < 0.01 || seamDegrees > 5))- diagnostics.Add("loft-seam-gap-invalid:range=0.01..5deg");- var twistDegrees = 0d;- var twistText = RawField(body, "Twist");- if (twistText is not null && (!TryDegrees(twistText, out twistDegrees) || Math.Abs(twistDegrees) > 180))- diagnostics.Add("loft-twist-invalid:range=-180..180deg");- var referenceText = Regex.Match(body, @"(?m)^\s*Reference\s*:\s*\[\s*(?<x>[-+.\deE]+)\s*,\s*(?<y>[-+.\deE]+)\s*,\s*(?<z>[-+.\deE]+)\s*\]\s*;?\s*$", RegexOptions.CultureInvariant);+ var thickness = hollow ? fields.Number("Thickness", "mm") : 0d;+ if (hollow && !(thickness > 0)) diagnostics.Add("loft-thickness-invalid:positive-length-required");+ var seamDegrees = hollow ? fields.Number("SeamGap", "deg", 0.1d) : 0.1d;+ if (!double.IsFinite(seamDegrees) || seamDegrees < 0.01 || seamDegrees > 5) diagnostics.Add("loft-seam-gap-invalid:range=0.01..5deg");+ var twistDegrees = fields.Number("Twist", "deg", 0d);+ if (!double.IsFinite(twistDegrees) || Math.Abs(twistDegrees) > 180) diagnostics.Add("loft-twist-invalid:range=-180..180deg");Vector3D reference = default;- if (!referenceText.Success || !TryVector(referenceText, out reference) || reference.Length < 1e-8)+ if (!fields.Vector("Reference", "", out var coordinates) || coordinates.Length != 3 || (reference = new(coordinates[0], coordinates[1], coordinates[2])).Length < 1e-8)diagnostics.Add("loft-reference-invalid:nonzero-world-direction-required");+ fields.Complete();if (diagnostics.Count > 0) return Fail(diagnostics.ToArray());var rear = ProfileAuthoringParser.ResolveNamedProfile(source, rearProfileName!, out var rearDiagnostics);@@ -120,8 +101,7 @@ public static class LoftAuthoringParser[], SectionTransitionPolicy.Ruled, SectionTermination.Cap, SectionTermination.Cap, SectionChainContinuity.G0);var binding = new LoftAuthoredBinding(name, rearProfileName!, rearFrameName!, frontProfileName!, frontFrameName!,[reference.X, reference.Y, reference.Z], twistDegrees,- new FirmamentV2SourceSpan(declaration.Index, close - declaration.Index + 1),- FirmamentV2Parser.ReadAuthoredFields(body, open + 1));+ declaration.Span, fields.AuthoredFields);if (!materialize) return new(true, chain, null, [], binding);var result = SectionChainMaterializer.Materialize(chain);if (!result.IsSuccess) diagnostics.AddRange(result.Diagnostics.Select(item => $"{item.Code}:{item.Message}"));@@ -223,51 +203,4 @@ public static class LoftAuthoringParserreturn new(c*x-s*y, s*x+c*y);}- private static string? Field(string body, string key)- {- var match = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(key)}\s*:\s*(?<value>[A-Za-z_]\w*)\s*;?\s*$", RegexOptions.CultureInvariant);- return match.Success ? match.Groups["value"].Value : null;- }-- private static string? Scalar(string body, string key)- {- var match = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(key)}\s*:\s*(?<value>[-+.\deE]+(?:mm|deg))\s*;?\s*$", RegexOptions.CultureInvariant);- return match.Success ? match.Groups["value"].Value : null;- }-- private static string? RawField(string body, string key)- {- var match = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(key)}\s*:\s*(?<value>[^\r\n;]+)\s*;?\s*$", RegexOptions.CultureInvariant);- return match.Success ? match.Groups["value"].Value.Trim() : null;- }-- private static bool TryDegrees(string text, out double degrees)- {- degrees = 0;- return text.EndsWith("deg", StringComparison.Ordinal)- && double.TryParse(text[..^3], NumberStyles.Float, CultureInfo.InvariantCulture, out degrees)- && double.IsFinite(degrees);- }-- private static bool TryVector(Match match, out Vector3D vector)- {- vector = default;- if (!double.TryParse(match.Groups["x"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var x) ||- !double.TryParse(match.Groups["y"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var y) ||- !double.TryParse(match.Groups["z"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var z) ||- !double.IsFinite(x) || !double.IsFinite(y) || !double.IsFinite(z)) return false;- vector = new(x,y,z);- return true;- }-- private static int MatchingBrace(string source, int open)- {- var depth = 0;- for (var i = open; i < source.Length; i++)- {- if (source[i] == '{') depth++;- else if (source[i] == '}' && --depth == 0) return i;- }- return -1;- }}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/PlateauAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/PlateauAuthoring.csindex 2b665fb0..df9866e0 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/PlateauAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/PlateauAuthoring.cs@@ -1,5 +1,5 @@using System.Diagnostics;-using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Diagnostics;using Aetheris.Kernel.Core.Results;@@ -15,39 +15,60 @@ public sealed record FirmamentPlateauReport(PlanarPlateauContactPlan Contacts,double ContactGenerationMs, double TrimAndBrepGenerationMs, double TotalGenerationMs,string WidthLaw = "ExactHomotheticShortAxisInset");+internal sealed record FirmamentPlateauRequest(string Name, string Base, string Footprint, double Height, double Width, string? Seam);+/// <summary>One bounded semantic Plateau on an existing extruded planar support.</summary>public static class PlateauAuthoring{- private static readonly Regex Header = new(@"\bPlateau\s+(?<name>[A-Za-z_]\w*)\s*\{(?<body>[^{}]*)\}", RegexOptions.CultureInvariant);- public static bool IsSource(string source) => Regex.IsMatch(source, @"\bPlateau\s+[A-Za-z_]\w*\s*\{");+ public static bool IsSource(string source) => FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Any(d => d.Type.Name.Text == "Plateau");++ internal static FirmamentPlateauRequest? Bind(string source, List<string> diagnostics)+ {+ var syntax = FirmamentSyntaxParser.Parse(source);+ diagnostics.AddRange(syntax.Diagnostics.Select(d => d.Code + ": " + d.Message));+ var declarations = FirmamentV2Parser.MechanicalDeclarations(syntax.Document.Statements).ToArray();+ var plateaus = declarations.Where(d => d.Type.Name.Text == "Plateau").ToArray();+ if (plateaus.Length != 1) { diagnostics.Add("plateau-count-invalid"); return null; }+ var declaration = plateaus[0];+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);+ var name = declaration.Name?.Text;+ var baseName = fields.Reference("Base"); var footprint = fields.Reference("Footprint");+ var height = fields.Number("Height", "mm"); var width = fields.Number("Width", "mm");+ var seam = fields.Reference("Seam");+ if (fields.Reference("Continuity") != "G2" || fields.Reference("Inset") != "Homothetic")+ diagnostics.Add("plateau-requires-G2-and-Homothetic-inset");+ var extrusions = declarations.Where(d => d.Type.Name.Text == "Extrude").ToArray();+ if (extrusions.Length != 1 || baseName != extrusions[0].Name?.Text || declarations.Any(d => d.Type.Name.Text is "Modify" or "Compose" or "Boss" or "Pocket" or "Revolve" or "EdgeFinish"))+ diagnostics.Add("plateau-base-requires-one-unmodified-extrusion");+ if (!double.IsFinite(height) || !double.IsFinite(width)) diagnostics.Add("plateau-dimensions-invalid");+ if (name is null || footprint is null || declaration.Type.Arguments.Count > 0 || declaration.Modifiers.Count > 0) diagnostics.Add("plateau-header-or-footprint-invalid");+ fields.Complete();+ return diagnostics.Count == 0 ? new(name!, baseName!, footprint!, height, width, seam) : null;+ }- internal static KernelResult<FirmamentStepExportResult> Compile(string source)+ internal static KernelResult<FirmamentStepExportResult> Compile(string source, FirmamentPlateauRequest? admitted = null, ResolvedProfile2D? admittedBase = null, double admittedHeight = 0){KernelResult<FirmamentStepExportResult> Fail(IEnumerable<string> messages) => KernelResult<FirmamentStepExportResult>.Failure(messages.Select(m => new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, m, "FirmamentV2.Plateau")).ToArray());- var watch = Stopwatch.StartNew(); var declarations = Header.Matches(source).Cast<Match>().ToArray();- if (declarations.Length != 1) return Fail(["plateau-count-invalid"]);- var declaration = declarations[0]; var name = declaration.Groups["name"].Value; var body = declaration.Groups["body"].Value;- var fields = Regex.Matches(body, @"\b(?<key>[A-Za-z_]\w*)\s*:").Select(m => m.Groups["key"].Value).ToArray();- var allowed = new[] { "Base", "Footprint", "Height", "Width", "Inset", "Continuity", "Seam" };- if (fields.Any(f => !allowed.Contains(f)) || fields.Distinct().Count() != fields.Length)- return Fail(["plateau-unknown-or-duplicate-property"]);- string? Field(string field) => ProfileAuthoringParser.Property(body, field);- if (Field("Continuity") != "G2" || Field("Inset") != "Homothetic") return Fail(["plateau-requires-G2-and-Homothetic-inset"]);- var extrusions = Regex.Matches(source, @"\bExtrude\s+(?<name>[A-Za-z_]\w*)\s*\{");- if (extrusions.Count != 1 || Field("Base") != extrusions[0].Groups["name"].Value ||- Regex.IsMatch(source, @"\b(?:Modify|Compose|Boss|Pocket|Revolve|EdgeFinish)\s+")) return Fail(["plateau-base-requires-one-unmodified-extrusion"]);- if (!ProfileAuthoringParser.TryMeasure(Field("Height") ?? "", "mm", out var height) ||- !ProfileAuthoringParser.TryMeasure(Field("Width") ?? "", "mm", out var width)) return Fail(["plateau-dimensions-invalid"]);- var parsed = ProfileAuthoringParser.Parse(source);- if (parsed.Profile is null || parsed.Diagnostics.Count != 0) return Fail(parsed.Diagnostics);- var footprint = ProfileAuthoringParser.ResolveNamedProfile(source, Field("Footprint") ?? "", out var diagnostics);+ var watch = Stopwatch.StartNew();+ var bindingDiagnostics = new List<string>();+ var request = admitted ?? Bind(source, bindingDiagnostics);+ if (request is null) return Fail(bindingDiagnostics);+ var name = request.Name; var height = request.Height; var width = request.Width;+ var baseProfile = admittedBase; var extrusionHeight = admittedHeight;+ if (baseProfile is null)+ {+ var parsed = ProfileAuthoringParser.Parse(source);+ if (parsed.Profile is null || parsed.Diagnostics.Count != 0) return Fail(parsed.Diagnostics);+ baseProfile = parsed.Profile; extrusionHeight = parsed.Height;+ }+ var footprint = ProfileAuthoringParser.ResolveNamedProfile(source, request.Footprint, out var diagnostics);if (footprint is null || diagnostics.Count != 0) return Fail(diagnostics);- if (footprint.Loops.Count != 1 || footprint.PlaneFrame != parsed.Profile.PlaneFrame) return Fail(["plateau-footprint-frame-or-loops-unsupported"]);- var baseBody = LineArcProfileExtrudeEmitter.TryEmit(parsed.Profile, parsed.Height);+ if (footprint.Loops.Count != 1 || footprint.PlaneFrame != baseProfile.PlaneFrame) return Fail(["plateau-footprint-frame-or-loops-unsupported"]);+ var baseBody = LineArcProfileExtrudeEmitter.TryEmit(baseProfile, extrusionHeight);if (baseBody.Body is null) return Fail(baseBody.Diagnostics);- var frame = parsed.Profile.EffectiveConstructionPlane;- var origin = frame.Origin + frame.AxisZ.ToVector() * (parsed.Profile.LocalEndDepth ?? parsed.Height);+ var frame = baseProfile.EffectiveConstructionPlane;+ var origin = frame.Origin + frame.AxisZ.ToVector() * (baseProfile.LocalEndDepth ?? extrusionHeight);var candidates = baseBody.Body.Bindings.FaceBindings.Where(b => b.Orientation.IsAlignedWithSurface && baseBody.Body.Geometry.GetSurface(b.SurfaceGeometryId).Plane is { } p &&(p.Normal.ToVector() - frame.AxisZ.ToVector()).Length < 1e-10 && Math.Abs((p.Origin - origin).Dot(frame.AxisZ.ToVector())) < 1e-8).ToArray();if (candidates.Length != 1) return Fail(["plateau-base-face-unresolved"]);@@ -64,10 +85,10 @@ public static class PlateauAuthoringif (curve is null) return Fail(["plateau-footprint-curve-unsupported:" + segment.Name]);spans.Add(new(segment.Name, curve));}- var seam = Field("Seam") ?? spans.FirstOrDefault(s => s.Curve is SectionProfileCurve.Line)?.SpanId ?? spans[0].SpanId;+ var seam = request.Seam ?? spans.FirstOrDefault(s => s.Curve is SectionProfileCurve.Line)?.SpanId ?? spans[0].SpanId;var contactWatch = Stopwatch.StartNew();var contacts = PlanarPlateauContacts.Build(name, new(footprint.Name, spans, seam), new(origin, frame.AxisX, frame.AxisY, frame.AxisZ),- height, width, Field("Base") + ".Top", name + ".Top");+ height, width, request.Base + ".Top", name + ".Top");contactWatch.Stop();if (!contacts.IsSuccess) return Fail(contacts.Diagnostics);var trimWatch = Stopwatch.StartNew();diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.csindex 75f3635d..d4d6aef9 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs@@ -17,7 +17,7 @@ public static class ProfileAuthoringParserprivate 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 | RegexOptions.CultureInvariant);private static readonly Regex SpanHeader = new(@"\bSpan\s*<\s*(?<type>[A-Za-z_]\w*)\s*>\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex Pipeline = new(@"(?<expression>(?:Reverse\s+)?[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*(?:\s+From\s+[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)?(?:\s+To\s+[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)?(?:\s+As\s+[A-Za-z_]\w*)?\s*(?:\|>\s*(?:(?:Reverse\s+)?[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*(?:\s+From\s+[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)?(?:\s+To\s+[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)?(?:\s+As\s+[A-Za-z_]\w*)?|Close|TraceLoop)\s*)+)", RegexOptions.CultureInvariant);+ private static readonly Regex Pipeline = new(@"(?<expression>(?:Reverse\s+)?[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*(?:\s+From\s+[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)?(?:\s+To\s+[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)?(?:\s+(?:As|as)\s+[A-Za-z_]\w*)?\s*(?:\|>\s*(?:(?:Reverse\s+)?[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*(?:\s+From\s+[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)?(?:\s+To\s+[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)?(?:\s+(?:As|as)\s+[A-Za-z_]\w*)?|Close|TraceLoop)\s*)+)", RegexOptions.CultureInvariant);public static bool IsProfileSource(string source) => Regex.IsMatch(source, @"\bProfile\s+[A-Za-z_]\w*", RegexOptions.CultureInvariant);@@ -81,7 +81,7 @@ public static class ProfileAuthoringParserinternal static IReadOnlyList<string> ValidatePipelineContexts(string source){- var allowed = FindBlocks(source, @"\b(?:Profile\s+[A-Za-z_]\w*(?:\s+Using\s+[A-Za-z_]\w*)?|Concept\s+Path\s+[A-Za-z_]\w*)\s*\{").ToArray();+ var allowed = FindBlocks(source, @"\b(?:Profile\s+[A-Za-z_]\w*(?:\s+(?:Using|using)\s+[A-Za-z_]\w*)?|Concept\s+Path\s+[A-Za-z_]\w*)\s*\{").ToArray();return Pipeline.Matches(source).Cast<Match>().Where(pipeline => !allowed.Any(block => pipeline.Index >= block.Match.Index && pipeline.Index < block.EndIndex)).Select(pipeline => $"firmament-pipeline-context-type:{ParsePipelineStages(pipeline.Groups["expression"].Value)[0].Reference}")@@ -735,7 +735,7 @@ public static class ProfileAuthoringParser.GroupBy(entry => entry.Segment, StringComparer.Ordinal).Where(group => group.Select(entry => entry.Loop).Distinct(StringComparer.Ordinal).Count() > 1)){var loopNames = collision.Select(entry => entry.Loop).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal);- diagnostics.Add($"firmament-profile-segment-identity-collision:{collision.Key}:loops={string.Join(',', loopNames)}:use As alias or rename source guide/stage");+ diagnostics.Add($"firmament-profile-segment-identity-collision:{collision.Key}:loops={string.Join(',', loopNames)}:use as alias or rename source guide/stage");}return loops;}@@ -1020,7 +1020,7 @@ public static class ProfileAuthoringParserelse if (raw == "TraceLoop") stages.Add(new(PipelineStageKind.TraceLoop, null, null, false, localOffset));else{- var parsed = Regex.Match(raw, @"^(?<reverse>Reverse\s+)?(?<reference>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)(?:\s+From\s+(?<from>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*))?(?:\s+To\s+(?<to>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*))?(?:\s+As\s+(?<alias>[A-Za-z_]\w*))?$", RegexOptions.CultureInvariant);+ var parsed = Regex.Match(raw, @"^(?<reverse>Reverse\s+)?(?<reference>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)(?:\s+From\s+(?<from>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*))?(?:\s+To\s+(?<to>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*))?(?:\s+(?:As|as)\s+(?<alias>[A-Za-z_]\w*))?$", RegexOptions.CultureInvariant);stages.Add(parsed.Success && (!parsed.Groups["from"].Success || parsed.Groups["to"].Success)? new(PipelineStageKind.Trace, parsed.Groups["reference"].Value, parsed.Groups["alias"].Success ? parsed.Groups["alias"].Value : null, parsed.Groups["reverse"].Success, localOffset,parsed.Groups["from"].Success ? parsed.Groups["from"].Value : null, parsed.Groups["to"].Success ? parsed.Groups["to"].Value : null)@@ -1108,7 +1108,7 @@ public static class ProfileAuthoringParserdiagnostics.Add($"profile-layout-placement-unsupported:{frame}:{(index + 4 < tokens.Length ? tokens[index + 4].Text : "missing")}:Concept Struct layouts currently require On XY; use a traced Construction Plane for oriented profiles.");return null;}- diagnostics.Add($"profile-frame-unresolved:{frame}:Using must name a declared Concept Struct or Construction Plane.");+ diagnostics.Add($"profile-frame-unresolved:{frame}:using must name a declared Concept Struct or Construction Plane.");return null;}if (!ConceptIrResolver.TryResolvePlane(source, plane.Groups["trace"].Value, out var conceptPlane, out var traceDiagnostic) || conceptPlane is null) { diagnostics.Add(traceDiagnostic ?? "ConstructionPlaneTraceMissing"); return null; }diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/RevolveAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/RevolveAuthoringParser.csindex 1eab104f..84985711 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/RevolveAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/RevolveAuthoringParser.cs@@ -1,5 +1,4 @@-using System.Globalization;-using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Firmament.Materializer;@@ -19,32 +18,41 @@ public static class RevolveAuthoringParser{public const string Prefix = "firmament-revolve-";private const double Tol = 1e-9;- private static readonly Regex Revolve = new(@"\bRevolve\s+(?<name>[A-Za-z_]\w*)\s*\{(?<body>[\s\S]*?)\}", RegexOptions.CultureInvariant);- private static readonly Regex Axis = new(@"\bAxis\s+(?<name>[A-Za-z_]\w*)\s*\{\s*Origin\s*:\s*\[\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*,\s*(?<z>[-+.\deE]+)mm\s*\]\s*;?\s*Direction\s*:\s*\[\s*(?<dx>[-+.\deE]+)\s*,\s*(?<dy>[-+.\deE]+)\s*,\s*(?<dz>[-+.\deE]+)\s*\]", RegexOptions.CultureInvariant);+ public static bool IsRevolveSource(string source) => FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)+ .Any(d => d.Type.Name.Text == "Revolve");- public static bool IsRevolveSource(string source) => Revolve.IsMatch(source);-- public static ResolvedRevolve? Parse(string source, out IReadOnlyList<string> reportedDiagnostics)+ public static ResolvedRevolve? Parse(string source, out IReadOnlyList<string> reportedDiagnostics) => Bind(source, out reportedDiagnostics, expand: true);+ internal static ResolvedRevolve? BindExpanded(string source, SyntaxParseResult syntax, out IReadOnlyList<string> reportedDiagnostics) => Bind(source, out reportedDiagnostics, expand: false, syntax);+ private static ResolvedRevolve? Bind(string source, out IReadOnlyList<string> reportedDiagnostics, bool expand, SyntaxParseResult? parsedSyntax = null){ArgumentNullException.ThrowIfNull(source);var diagnostics = new List<string>();- var normalized = NormalizeSemanticSource(source, diagnostics);+ var normalized = expand ? NormalizeSemanticSource(source, diagnostics) : source;if (normalized is null){reportedDiagnostics = diagnostics.Distinct(StringComparer.Ordinal).ToArray();return null;}source = normalized;- var feature = Revolve.Match(source);- if (!feature.Success) { reportedDiagnostics = [Prefix + "missing"]; return null; }- var name = feature.Groups["name"].Value;- var body = feature.Groups["body"].Value;- var profileName = Field(body, "Profile");- var axisName = Field(body, "About");- var angleText = Field(body, "Angle");+ var syntax = parsedSyntax ?? FirmamentSyntaxParser.Parse(source);+ FirmamentV2Parser.BindMaterialDomainScope(syntax.Document, "Revolve", diagnostics);+ diagnostics.AddRange(syntax.Diagnostics.Select(d => d.Code + ": " + d.Message));+ var declarations = FirmamentV2Parser.MechanicalDeclarations(syntax.Document.Statements).ToArray();+ var features = declarations.Where(d => d.Type.Name.Text == "Revolve").ToArray();+ if (features.Length != 1)+ { reportedDiagnostics = diagnostics.Append(Prefix + (features.Length == 0 ? "missing" : "multiple-material-features-unsupported")).ToArray(); return null; }+ var feature = features[0];+ var name = feature.Name?.Text ?? "";+ var fields = new FirmamentSyntaxFields(feature, diagnostics);+ var profileName = fields.Word("Profile");+ var axisName = fields.Word("About");+ var angleExpression = fields.Take("Angle");+ fields.Complete();+ if (feature.Type.Arguments.Count > 0 || feature.Modifiers.Count > 0 || name.Length == 0)+ diagnostics.Add(Prefix + "header-invalid:" + name);if (profileName is null) diagnostics.Add(Prefix + "profile-not-found:" + name);if (axisName is null) diagnostics.Add(Prefix + "axis-not-found:" + name);- if (angleText is null) diagnostics.Add(Prefix + "angle-missing:" + name);+ if (angleExpression is null) diagnostics.Add(Prefix + "angle-missing:" + name);IReadOnlyList<string> profileDiagnostics = [];var profile = profileName is null ? null : ProfileAuthoringParser.ResolveNamedProfile(source, profileName, out profileDiagnostics);@@ -62,25 +70,33 @@ public static class RevolveAuthoringParserConceptIrAxisValue? axis = null;if (axisName is not null){- var axisMatch = Axis.Matches(source).Cast<Match>().FirstOrDefault(match => match.Groups["name"].Value == axisName);- if (axisMatch is null) diagnostics.Add(Prefix + "axis-not-found:" + name);- else if (!Numbers(axisMatch, ["x", "y", "z", "dx", "dy", "dz"], out var values)) diagnostics.Add(Prefix + "axis-invalid:" + name);+ var axes = declarations.Where(d => d.Type.Name.Text == "Axis" && d.Name?.Text == axisName).ToArray();+ if (axes.Length == 0) diagnostics.Add(Prefix + "axis-not-found:" + name);+ else if (axes.Length > 1) diagnostics.Add(Prefix + "axis-duplicate:" + axisName);else{- var direction = new Vector3D(values[3], values[4], values[5]);- if (!direction.TryNormalize(out _)) diagnostics.Add(Prefix + "axis-zero-direction:" + name);- else axis = new("axis:" + axisName,- new(values[0], values[1], values[2]),- new(direction.X, direction.Y, direction.Z),- "Axis:" + axisName);+ if (axes[0].Type.Arguments.Count > 0 || axes[0].Modifiers.Count > 0) diagnostics.Add(Prefix + "axis-header-invalid:" + axisName);+ var axisFields = new FirmamentSyntaxFields(axes[0], diagnostics);+ var originValid = axisFields.Vector("Origin", "mm", out var origin);+ var directionValid = axisFields.Vector("Direction", "", out var components);+ axisFields.Complete();+ if (!originValid || origin.Length != 3 || !directionValid || components.Length != 3)+ diagnostics.Add(Prefix + "axis-invalid:" + name);+ else+ {+ var direction = new Vector3D(components[0], components[1], components[2]);+ if (!direction.TryNormalize(out _)) diagnostics.Add(Prefix + "axis-zero-direction:" + name);+ else axis = new("axis:" + axisName, new(origin[0], origin[1], origin[2]),+ new(direction.X, direction.Y, direction.Z), "Axis:" + axisName);+ }}}var sweep = 0d;string? alias = null;- if (angleText is not null && !TryAngle(angleText, out sweep, out alias)) diagnostics.Add(Prefix + "angle-invalid:" + name);- else if (angleText is not null && Math.Abs(sweep) <= Tol) diagnostics.Add(Prefix + "zero-angle:" + name);- else if (angleText is not null && Math.Abs(sweep) > 2d * Math.PI + Tol) diagnostics.Add(Prefix + "angle-out-of-range:" + name);+ if (angleExpression is not null && !TryAngle(angleExpression, out sweep, out alias)) diagnostics.Add(Prefix + "angle-invalid:" + name);+ else if (angleExpression is not null && Math.Abs(sweep) <= Tol) diagnostics.Add(Prefix + "zero-angle:" + name);+ else if (angleExpression is not null && Math.Abs(sweep) > 2d * Math.PI + Tol) diagnostics.Add(Prefix + "angle-out-of-range:" + name);if (profile is not null && axis is not null){@@ -118,36 +134,25 @@ public static class RevolveAuthoringParserreturn staticAuthoring?.Source;}- private static string? Field(string body, string name)- {- var match = Regex.Match(body, $@"\b{Regex.Escape(name)}\s*:\s*(?<value>[^;\r\n}}]+)", RegexOptions.CultureInvariant);- return match.Success ? match.Groups["value"].Value.Trim() : null;- }-- private static bool Numbers(Match match, IReadOnlyList<string> groups, out double[] values)+ private static bool TryAngle(ExpressionSyntax expression, out double radians, out string? alias){- values = new double[groups.Count];- for (var i = 0; i < groups.Count; i++)- if (!double.TryParse(match.Groups[groups[i]].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out values[i]) || !double.IsFinite(values[i])) return false;- return true;+ var sign = 1d;+ while (expression is UnarySyntax { Operator: UnaryOperator.Positive or UnaryOperator.Negative } unary)+ { if (unary.Operator == UnaryOperator.Negative) sign = -sign; expression = unary.Operand; }+ alias = FirmamentSyntaxValues.Reference(expression)?.ToLowerInvariant();+ radians = sign * (alias switch { "quarter" => Math.PI / 2d, "half" => Math.PI, "full" => 2d * Math.PI, _ => double.NaN });+ if (double.IsFinite(radians)) return true;+ alias = null;+ if (FirmamentSyntaxValues.TryMeasure(expression, "deg", out var degrees)) radians = sign * degrees * Math.PI / 180d;+ else if (FirmamentSyntaxValues.TryMeasure(expression, "", out var numeric)) radians = sign * numeric;+ return double.IsFinite(radians);}internal static bool TryAngle(string text, out double radians, out string? alias){- radians = 0d; alias = null;- var normalized = text.Trim().ToLowerInvariant();- var sign = 1d;- if (normalized.StartsWith('+')) normalized = normalized[1..].Trim();- else if (normalized.StartsWith('-')) { sign = -1d; normalized = normalized[1..].Trim(); }- var factor = normalized switch { "quarter" => Math.PI / 2d, "half" => Math.PI, "full" => 2d * Math.PI, _ => double.NaN };- if (double.IsFinite(factor)) { radians = sign * factor; alias = normalized; return true; }- if (normalized.EndsWith("deg", StringComparison.Ordinal))- {- if (!double.TryParse(normalized[..^3], NumberStyles.Float, CultureInfo.InvariantCulture, out var degrees) || !double.IsFinite(degrees)) return false;- radians = sign * degrees * Math.PI / 180d; return true;- }- if (!double.TryParse(normalized, NumberStyles.Float, CultureInfo.InvariantCulture, out var numeric) || !double.IsFinite(numeric)) return false;- radians = sign * numeric; return true;+ var syntax = FirmamentSyntaxParser.ParseExpression(text);+ radians = double.NaN; alias = null;+ return syntax.Diagnostics.Count == 0 && syntax.Expression is not null && TryAngle(syntax.Expression, out radians, out alias);}private static bool CrossesAxis(ResolvedProfile2D profile, (double X, double Y, double Z) axisOrigin, Vector3D worldDirection, ConstructionPlane frame)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.csindex 32db6646..39d927bb 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs@@ -1,4 +1,4 @@-using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.Firmament.Materializer;using Aetheris.Surfacing;@@ -38,9 +38,8 @@ public static class SectionChainAuthoringParserreturn source is null || errors.Count != 0 ? new(false, null, null, errors.Select(d => d.Code + ":" + d.Message).ToArray()): Compile(source, materialize);}- public static bool IsSectionChainSource(string source) =>- Regex.IsMatch(source, @"\bSectionChain\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant)- || LoftAuthoringParser.IsLoftSource(source);+ public static bool IsSectionChainSource(string source) => FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)+ .Any(d => d.Type.Name.Text is "SectionChain" or "Loft");public static SectionChainAuthoringResult Compile(string source, bool materialize = true){@@ -59,38 +58,41 @@ public static class SectionChainAuthoringParservar templates = FirmamentV2TemplateExpansion.Expand(source, diagnostics);if (templates is null || diagnostics.Count > 0) return new(false, null, null, diagnostics);source = templates.Source;- if (!Regex.IsMatch(source, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant))+ var syntax = FirmamentSyntaxParser.Parse(source);+ FirmamentV2Parser.BindMaterialDomainScope(syntax.Document, "SectionChain", diagnostics);+ diagnostics.AddRange(syntax.Diagnostics.Select(d => d.Code + ": " + d.Message));+ if (!FirmamentSyntaxTraversal.Statements(syntax.Document).OfType<FieldSyntax>().Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Units") && FirmamentSyntaxValues.Reference(f.Value) == "mm"))diagnostics.Add("section-chain-units-invalid:millimetres-required");- var declarations = Blocks(source, "SectionChain").ToArray();- if (declarations.Length != 1)- return Fail(diagnostics.Append($"section-chain-count-invalid:expected=1:actual={declarations.Length}"));-+ var declarations = FirmamentV2Parser.MechanicalDeclarations(syntax.Document.Statements).Where(d => d.Type.Name.Text == "SectionChain").ToArray();+ if (declarations.Length != 1) return Fail(diagnostics.Append($"section-chain-count-invalid:expected=1:actual={declarations.Length}"));var declaration = declarations[0];+ var constructionStatements = declaration.Body?.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text is not ("Section" or "Correspond")).Cast<StatementSyntax>().ToArray() ?? [];+ FirmamentV2Parser.BindMaterialDomainScope(syntax.Document with { Statements = constructionStatements }, "SectionChain", diagnostics);+ var fields = new FirmamentSyntaxFields(declaration with { Body = declaration.Body is null ? null : declaration.Body with+ { Statements = declaration.Body.Statements.Where(s => s is not DeclarationSyntax).ToArray() } }, diagnostics);var profiles = ProfileAuthoringParser.BindPathDerivedProfiles(source, diagnostics);- var authoredTransition = Field(declaration.Body, "Transition");- var continuityText = Field(declaration.Body, "Continuity") ?? (authoredTransition == "Ruled" ? "G0" : "G1");- if (!Enum.TryParse<SectionChainContinuity>(continuityText, false, out var continuity))- diagnostics.Add($"section-chain-continuity-invalid:{continuityText}");- var transitionText = authoredTransition- ?? (continuity == SectionChainContinuity.G0 ? "Ruled" : "SmoothPolynomial");- if (!Enum.TryParse<SectionTransitionPolicy>(transitionText, false, out var transition))- diagnostics.Add($"section-chain-transition-policy-invalid:{transitionText}");- var startText = Field(declaration.Body, "Start") ?? "Open";- var endText = Field(declaration.Body, "End") ?? "Open";- if (!Enum.TryParse<SectionTermination>(startText, false, out var start))- diagnostics.Add($"section-chain-termination-invalid:Start:{startText}");- if (!Enum.TryParse<SectionTermination>(endText, false, out var end))- diagnostics.Add($"section-chain-termination-invalid:End:{endText}");+ var authoredTransition = fields.Reference("Transition");+ var continuityText = fields.Reference("Continuity") ?? (authoredTransition == "Ruled" ? "G0" : "G1");+ if (!Enum.TryParse<SectionChainContinuity>(continuityText, false, out var continuity)) diagnostics.Add($"section-chain-continuity-invalid:{continuityText}");+ var transitionText = authoredTransition ?? (continuity == SectionChainContinuity.G0 ? "Ruled" : "SmoothPolynomial");+ if (!Enum.TryParse<SectionTransitionPolicy>(transitionText, false, out var transition)) diagnostics.Add($"section-chain-transition-policy-invalid:{transitionText}");+ var startText = fields.Reference("Start") ?? "Open"; var endText = fields.Reference("End") ?? "Open";+ if (!Enum.TryParse<SectionTermination>(startText, false, out var start)) diagnostics.Add($"section-chain-termination-invalid:Start:{startText}");+ if (!Enum.TryParse<SectionTermination>(endText, false, out var end)) diagnostics.Add($"section-chain-termination-invalid:End:{endText}");var sections = new List<Section>();var derivations = new List<SectionChainProfileDerivation>();var boundaryEdits = new List<SectionChainBoundaryEditInspection>();- foreach (var authored in Blocks(declaration.Body, "Section"))+ foreach (var authored in declaration.Body?.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Section") ?? []){- var frameName = Field(authored.Body, "Frame");- var profileName = Field(authored.Body, "Profile");- var seam = Field(authored.Body, "Seam");- if (frameName is null) diagnostics.Add($"section-chain-frame-missing:{authored.Name}");+ if (authored.Name is null || authored.Type.Arguments.Count > 0 || authored.Modifiers.Count > 0)+ { diagnostics.Add("section-chain-section-header-invalid"); continue; }+ var sectionFields = new FirmamentSyntaxFields(authored, diagnostics);+ var frameName = sectionFields.Reference("Frame");+ var profileName = sectionFields.Reference("Profile");+ var seam = sectionFields.Reference("Seam");+ sectionFields.Complete();+ if (frameName is null) diagnostics.Add($"section-chain-frame-missing:{authored.Name!.Text}");ResolvedProfile2D? profile = null;if (profileName is not null && !profiles.TryGetValue(profileName, out profile)){@@ -98,41 +100,51 @@ public static class SectionChainAuthoringParserif (profile is null) diagnostics.AddRange(profileDiagnostics);}if (profile is null)- diagnostics.Add($"section-chain-profile-unresolved:{authored.Name}:{profileName ?? "<missing>"}");+ diagnostics.Add($"section-chain-profile-unresolved:{authored.Name!.Text}:{profileName ?? "<missing>"}");var plane = frameName is null ? null : ProfileAuthoringParser.ResolveNamedConstructionPlane(source, frameName, diagnostics);- if (frameName is not null && plane is null) diagnostics.Add($"section-chain-frame-unresolved:{authored.Name}:{frameName}");+ if (frameName is not null && plane is null) diagnostics.Add($"section-chain-frame-unresolved:{authored.Name!.Text}:{frameName}");if (plane is null || profile is null) continue;var outer = profile.Loops.Single(loop => loop.IsOuter);- if (profile.BoundaryEdits is { Count: > 0 }) boundaryEdits.Add(new(authored.Name, profile.Name, profile.BoundaryEdits));+ if (profile.BoundaryEdits is { Count: > 0 }) boundaryEdits.Add(new(authored.Name!.Text, profile.Name, profile.BoundaryEdits));if (outer.Segments.FirstOrDefault()?.Provenance is { } provenance&& provenance.ConceptStableId.StartsWith("concept-curve:", StringComparison.Ordinal))- derivations.Add(new(authored.Name, profile.Name, provenance.ConceptStableId,+ derivations.Add(new(authored.Name!.Text, profile.Name, provenance.ConceptStableId,provenance.TracedFrom ?? "", provenance.Derivation, profile.PlaneFrame));- if (profile.Loops.Count != 1) diagnostics.Add($"section-chain-profile-loop-count-invalid:{authored.Name}");- var spans = outer.Segments.Select(segment => Convert(segment, diagnostics, authored.Name)).Where(item => item is not null).Cast<SectionProfileSpan>().ToArray();+ if (profile.Loops.Count != 1) diagnostics.Add($"section-chain-profile-loop-count-invalid:{authored.Name!.Text}");+ var spans = outer.Segments.Select(segment => Convert(segment, diagnostics, authored.Name!.Text)).Where(item => item is not null).Cast<SectionProfileSpan>().ToArray();var seamId = seam ?? spans.FirstOrDefault()?.SpanId ?? string.Empty;- sections.Add(new(authored.Name, new(plane.Origin, plane.AxisX, plane.AxisY, plane.AxisZ), new(profile.Name, spans, seamId)));+ sections.Add(new(authored.Name!.Text, new(plane.Origin, plane.AxisX, plane.AxisY, plane.AxisZ), new(profile.Name, spans, seamId)));}if (sections.Count < 2) diagnostics.Add("section-chain-section-count-invalid:minimum=2");var correspondence = new List<AdjacentSectionCorrespondence>();- foreach (var authored in Blocks(declaration.Body, "Correspond"))+ foreach (var authored in declaration.Body?.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Correspond") ?? []){- var from = Field(authored.Body, "From"); var to = Field(authored.Body, "To");- if (from is null || to is null) { diagnostics.Add($"section-chain-correspondence-endpoint-missing:{authored.Name}"); continue; }- var mappings = Regex.Matches(authored.Body, @"(?m)^\s*(?<a>[A-Za-z_]\w*)\s*->\s*(?<b>[A-Za-z_]\w*)\s*;?\s*$", RegexOptions.CultureInvariant)- .Cast<Match>().Select(match => new SectionSpanCorrespondence(match.Groups["a"].Value, match.Groups["b"].Value)).ToArray();- foreach (var duplicate in mappings.GroupBy(item => item.TargetSpanId, StringComparer.Ordinal).Where(group => group.Count() > 1))+ if (authored.Type.Arguments.Count > 0 || authored.Modifiers.Count > 0) diagnostics.Add("section-chain-correspondence-header-invalid");+ var mappingStatements = authored.Body?.Statements.OfType<ExpressionStatementSyntax>().ToArray() ?? [];+ var mappingFields = new FirmamentSyntaxFields(authored with { Body = authored.Body is null ? null : authored.Body with+ { Statements = authored.Body.Statements.Where(s => s is not ExpressionStatementSyntax).ToArray() } }, diagnostics);+ var from = mappingFields.Reference("From"); var to = mappingFields.Reference("To");+ mappingFields.Complete();+ if (from is null || to is null) { diagnostics.Add($"section-chain-correspondence-endpoint-missing:{authored.Name?.Text}"); continue; }+ var mappings = new List<SectionSpanCorrespondence>();+ foreach (var mapping in mappingStatements)+ {+ if (mapping.Value is BinarySyntax { Operator: BinaryOperator.Direction, Left: ReferenceSyntax left, Right: ReferenceSyntax right })+ mappings.Add(new(left.Name.Text, right.Name.Text));+ else diagnostics.Add($"section-chain-correspondence-invalid:{authored.Name?.Text}");+ }+ foreach (var duplicate in mappings.GroupBy(item => item.TargetSpanId, StringComparer.Ordinal).Where(g => g.Count() > 1))diagnostics.Add($"section-chain-correspondence-duplicate:{from}:{to}:{duplicate.Key}");correspondence.Add(new(from, to, mappings));}-- var tolerance = 1e-5;- var toleranceText = ProfileAuthoringParser.Property(declaration.Body, "ApproximationTolerance");- if (toleranceText is not null && (!ProfileAuthoringParser.TryMeasure(toleranceText, "mm", out tolerance) || tolerance <= 0))- diagnostics.Add("section-chain-normalization-tolerance-invalid:positive-length-required");+ var tolerance = fields.Number("ApproximationTolerance", "mm", 1e-5);+ if (!(tolerance > 0)) diagnostics.Add("section-chain-normalization-tolerance-invalid:positive-length-required");+ fields.Complete();+ if (declaration.Type.Arguments.Count > 0 || declaration.Modifiers.Count > 0 || declaration.Name is null)+ diagnostics.Add("section-chain-header-invalid");if (diagnostics.Count != 0) return Fail(diagnostics);- var chain = new SectionChain(declaration.Name, sections, correspondence, transition, start, end, continuity, ProfileApproximationTolerance: tolerance);+ var chain = new SectionChain(declaration.Name!.Text, sections, correspondence, transition, start, end, continuity, ProfileApproximationTolerance: tolerance);if (!materialize) return new(true, chain, null, [], ProfileDerivations: derivations, BoundaryEdits: boundaryEdits, Patterns: staticSource.Document?.Patterns);var result = SectionChainMaterializer.Materialize(chain);if (!result.IsSuccess)@@ -144,33 +156,36 @@ public static class SectionChainAuthoringParserprivate static string ExpandSectionValues(string source, List<string> diagnostics){+ // Retain the existing inline-value lowering and its identities. Syntax owns+ // exact declaration/field boundaries, so no field suffix or sibling is lost.+ var syntax = FirmamentSyntaxParser.Parse(source);+ diagnostics.AddRange(syntax.Diagnostics.Select(d => d.Code + ": " + d.Message));var changes = new List<(int Start, int Length, string Text)>();- foreach (Match header in Regex.Matches(source, @"\bSection\s+(?<name>[A-Za-z_]\w*)\s*\{"))+ foreach (var section in FirmamentSyntaxTraversal.Declarations(syntax.Document).Where(d => d.Type.Name.Text == "Section")){- var open = source.IndexOf('{', header.Index); var close = MatchingBrace(source, open);- if (close < 0) { diagnostics.Add("section-chain-section-malformed"); continue; }- var body = source[(open + 1)..close]; var name = header.Groups["name"].Value;+ if (section.Name is null) { diagnostics.Add("section-chain-section-malformed"); continue; }+ var name = section.Name.Text;var prelude = "";- var frame = Regex.Match(body, @"\bFrame\s*:\s*Plane\s*\{");- if (frame.Success)- {- var frameOpen = body.IndexOf('{', frame.Index); var frameClose = MatchingBrace(body, frameOpen);- if (frameClose < 0) { diagnostics.Add("section-chain-inline-frame-invalid:" + name); continue; }- var concept = "__SectionDatum_" + name; var construction = "__SectionFrame_" + name;- prelude += $"Concept Struct {concept} {{ Support: Plane {{{body[(frameOpen + 1)..frameClose]}}} }}\nConstruction Plane {construction} {{ Trace: {concept}.Support }}\n";- body = body.Remove(frame.Index, frameClose - frame.Index + 1).Insert(frame.Index, "Frame: " + construction + "\n");- }- var profile = Regex.Match(body, @"\bProfile\s*:\s*(?<call>[A-Za-z_]\w*\s*<[^<>]+>)");- if (profile.Success)+ foreach (var field in section.Body?.Statements.OfType<FieldSyntax>() ?? []){- var profileName = "__SectionProfile_" + name;- prelude += $"Profile {profileName} = {profile.Groups["call"].Value}\n";- body = body.Remove(profile.Index, profile.Length).Insert(profile.Index, "Profile: " + profileName + "\n");+ if (FirmamentSyntaxFields.SameField(field.Name.Text, "Frame") && field.Value is ObjectSyntax { Type: ReferenceSyntax { Name.Text: "Plane" } } plane)+ {+ var concept = "__SectionDatum_" + name; var construction = "__SectionFrame_" + name;+ prelude += $"Concept Struct {concept} {{ Support: Plane {Slice(plane.Body.Span)} }}\nConstruction Plane {construction} {{ Trace: {concept}.Support }}\n";+ changes.Add((field.Value.Span.Start, field.Value.Span.Length, construction));+ }+ else if (FirmamentSyntaxFields.SameField(field.Name.Text, "Profile") && field.Value is SpecializationSyntax profile)+ {+ var profileName = "__SectionProfile_" + name;+ prelude += $"Profile {profileName} = {Slice(profile.Span)}\n";+ changes.Add((field.Value.Span.Start, field.Value.Span.Length, profileName));+ }}- if (prelude.Length > 0) changes.Add((header.Index, close - header.Index + 1, prelude + $"Section {name} {{{body}}}"));+ if (prelude.Length > 0) changes.Add((section.Span.Start, 0, prelude));}foreach (var change in changes.OrderByDescending(c => c.Start)) source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);return source;+ string Slice(FirmamentV2SourceSpan span) => source.Substring(span.Start, span.Length);}private static SectionProfileSpan? Convert(ResolvedProfileSegment2D segment, List<string> diagnostics, string section) => segment.Geometry switch@@ -181,43 +196,10 @@ public static class SectionChainAuthoringParser_ => Unsupported(segment, diagnostics, section)};- private static IEnumerable<Block> Blocks(string source, string keyword)- {- var regex = new Regex($@"\b{Regex.Escape(keyword)}(?:\s+(?<name>[A-Za-z_]\w*))?\s*\{{", RegexOptions.CultureInvariant);- for (var offset = 0; offset < source.Length;)- {- var match = regex.Match(source, offset); if (!match.Success) yield break;- var open = source.IndexOf('{', match.Index + match.Length - 1); var close = MatchingBrace(source, open);- if (close < 0) yield break;- yield return new(match.Groups["name"].Success ? match.Groups["name"].Value : keyword, source[(open + 1)..close]);- offset = close + 1;- }- }-- private static int MatchingBrace(string source, int open)- {- var depth = 0; var quoted = false;- for (var index = open; index < source.Length; index++)- {- if (source[index] == '"' && (index == 0 || source[index - 1] != '\\')) quoted = !quoted;- if (quoted) continue;- if (source[index] == '{') depth++;- else if (source[index] == '}' && --depth == 0) return index;- }- return -1;- }-- private static string? Field(string body, string name)- {- var match = Regex.Match(body, $@"(?m)^\s*{Regex.Escape(name)}\s*:\s*(?<value>[A-Za-z_]\w*)\s*;?\s*$", RegexOptions.CultureInvariant);- return match.Success ? match.Groups["value"].Value : null;- }-private static SectionProfileSpan? Unsupported(ResolvedProfileSegment2D segment, List<string> diagnostics, string section){diagnostics.Add($"section-chain-profile-curve-unsupported:{section}:{segment.Name}:{segment.Geometry.GetType().Name}");return null;}- private sealed record Block(string Name, string Body);}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.csindex f77c2e10..fbe7fccb 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs@@ -25,7 +25,12 @@ public sealed record IdentifierSyntax(string Text, FirmamentV2SourceSpan Span);public sealed record ArgumentSyntax(IdentifierSyntax? Name, ExpressionSyntax Value, ExpressionSyntax? Default, FirmamentV2SourceSpan Span);public sealed record TypeSyntax(IdentifierSyntax Name, IReadOnlyList<ArgumentSyntax> Arguments, FirmamentV2SourceSpan Span);public sealed record ClauseSyntax(ClauseKind Kind, ExpressionSyntax Value, FirmamentV2SourceSpan Span);-public sealed record BlockSyntax(IReadOnlyList<StatementSyntax> Statements, FirmamentV2SourceSpan Span);+public sealed record BlockSyntax(IReadOnlyList<StatementSyntax> Statements, FirmamentV2SourceSpan Span)+{+ [JsonIgnore] public bool Delimited { get; init; } = true;+ [JsonIgnore] public bool IsClosed { get; init; } = true;+ [JsonIgnore] public FirmamentV2SourceSpan ContentSpan => Delimited ? new(Span.Start + 1, Math.Max(0, Span.Length - (IsClosed ? 2 : 1))) : Span;+}public sealed record DeclarationSyntax(TypeSyntax Type, IdentifierSyntax? Name, IReadOnlyList<TypeSyntax> Modifiers,IReadOnlyList<ArgumentSyntax> Parameters, ExpressionSyntax? Annotation, ExpressionSyntax? ResultType,IReadOnlyList<ClauseSyntax> Clauses, ExpressionSyntax? Initializer, BlockSyntax? Body, bool Occurrence,@@ -66,7 +71,11 @@ public sealed record MemberSyntax(ExpressionSyntax Target, IdentifierSyntax Membpublic sealed record IndexSyntax(ExpressionSyntax Target, ExpressionSyntax? Index, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);public sealed record CallSyntax(ExpressionSyntax Target, IReadOnlyList<ArgumentSyntax> Arguments, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);public sealed record SpecializationSyntax(ExpressionSyntax Target, IReadOnlyList<ArgumentSyntax> Arguments, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);-public sealed record ObjectSyntax(ExpressionSyntax? Type, BlockSyntax Body, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);+public sealed record ObjectSyntax(ExpressionSyntax? Type, BlockSyntax Body, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span)+{+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]+ public IdentifierSyntax? Name { get; init; }+}public sealed record WithSyntax(ExpressionSyntax Target, BlockSyntax Body, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);public sealed record FrameSyntax(ExpressionSyntax Origin, IReadOnlyList<ArgumentSyntax> Axes, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);public sealed record AliasSyntax(ExpressionSyntax Value, IdentifierSyntax Name, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxEvidence.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxEvidence.csindex 97cac9cd..bcb49fff 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxEvidence.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxEvidence.cs@@ -21,56 +21,9 @@ public static class FirmamentSyntaxEvidencepublic static string Fingerprint(DocumentSyntax document) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join("\n", document.Statements.Select(Normalize)))));- public static IEnumerable<DeclarationSyntax> Declarations(DocumentSyntax document) =>- Statements(document).OfType<DeclarationSyntax>();-- public static IEnumerable<StatementSyntax> Statements(DocumentSyntax document) => document.Statements.SelectMany(Descendants);-- private static IEnumerable<StatementSyntax> Descendants(StatementSyntax statement)- {- yield return statement;- foreach (var child in ChildStatements(statement))- foreach (var descendant in Descendants(child)) yield return descendant;- }-- public static IEnumerable<DeclarationSyntax> Declarations(StatementSyntax statement)- {- if (statement is DeclarationSyntax declaration) yield return declaration;- foreach (var child in ChildStatements(statement))- foreach (var nested in Declarations(child)) yield return nested;- }-- private static IEnumerable<StatementSyntax> ChildStatements(StatementSyntax statement) => statement switch- {- DeclarationSyntax d => (d.Body?.Statements ?? []).Concat(d.Initializer is null ? [] : ExpressionBodies(d.Initializer))- .Concat(d.Annotation is null ? [] : ExpressionBodies(d.Annotation)),- FieldSyntax f => ExpressionBodies(f.Value),- ExpressionStatementSyntax e => ExpressionBodies(e.Value),- ReturnSyntax r => ExpressionBodies(r.Value),- MappingSyntax m => [m.Value],- _ => []- };-- private static IEnumerable<StatementSyntax> ExpressionBodies(ExpressionSyntax expression) => expression switch- {- ObjectSyntax o => o.Body.Statements.Concat(o.Type is null ? [] : ExpressionBodies(o.Type)),- WithSyntax w => w.Body.Statements.Concat(ExpressionBodies(w.Target)),- SequenceSyntax s => s.Items.SelectMany(a => ExpressionBodies(a.Value)),- CallSyntax c => ExpressionBodies(c.Target).Concat(c.Arguments.SelectMany(a => ExpressionBodies(a.Value))),- SpecializationSyntax s => ExpressionBodies(s.Target).Concat(s.Arguments.SelectMany(a => ExpressionBodies(a.Value))),- BinarySyntax b => ExpressionBodies(b.Left).Concat(ExpressionBodies(b.Right)),- UnarySyntax u => ExpressionBodies(u.Operand),- MemberSyntax m => ExpressionBodies(m.Target),- IndexSyntax i => ExpressionBodies(i.Target).Concat(i.Index is null ? [] : ExpressionBodies(i.Index)),- QuantitySyntax q => ExpressionBodies(q.Value),- FrameSyntax f => ExpressionBodies(f.Origin).Concat(f.Axes.SelectMany(a => ExpressionBodies(a.Value))),- AliasSyntax a => ExpressionBodies(a.Value),- TraceSyntax t => ExpressionBodies(t.Source).Concat(t.From is null ? [] : ExpressionBodies(t.From)).Concat(t.To is null ? [] : ExpressionBodies(t.To)),- TypedValueSyntax t => ExpressionBodies(t.Type).Concat(ExpressionBodies(t.Value)),- MatchSyntax m => ExpressionBodies(m.Scrutinee).Concat(m.Arms.SelectMany(a => ExpressionBodies(a.Pattern).Concat(ExpressionBodies(a.Value)))),- MemberSetSyntax m => ExpressionBodies(m.Target).Concat(m.Members.SelectMany(a => ExpressionBodies(a.Value))),- _ => []- };+ public static IEnumerable<DeclarationSyntax> Declarations(DocumentSyntax document) => FirmamentSyntaxTraversal.Declarations(document);+ public static IEnumerable<DeclarationSyntax> Declarations(StatementSyntax statement) => FirmamentSyntaxTraversal.Declarations(statement);+ public static IEnumerable<StatementSyntax> Statements(DocumentSyntax document) => FirmamentSyntaxTraversal.Statements(document);private static void RemoveSpans(JsonNode? node){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.csindex e12c3d19..47c137d8 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs@@ -99,6 +99,12 @@ public static class FirmamentSyntaxParservar key = Identifier(); Expect("="); Expect(">");return new MappingSyntax(key, Statement(), Span(start));}+ // The historical unit header has the same field meaning as units: mm.+ if (Is("units") && Peek(1).Kind == SyntaxTokenKind.Identifier)+ {+ var name = Identifier();+ return new FieldSyntax(name, Expression(allowObject: false), Span(start));+ }if (Is("return")) { at++; return new ReturnSyntax(Expression(), Span(start)); }if (Is("schema") || Is("include") || Is("Include") || Is("Use")){@@ -107,8 +113,14 @@ public static class FirmamentSyntaxParser}// A call or a pipeline is an expression statement. A bare name in an// Enum/Loop is also syntax, never implicitly an admitted declaration.- if (Is("Reverse") || Peek(1).Text is "(" or "." or "|" or "[" or "As" or "From" or "To" || Peek(1).Text is ";" or "}" || Peek(1).Kind == SyntaxTokenKind.End)- return new ExpressionStatementSyntax(Expression(), Span(start));+ if (Is("Reverse") || Peek(1).Text == "-" && Peek(2).Text == ">" || Peek(1).Text is "(" or "." or "|" or "[" or "As" or "as" or "From" or "To" || Peek(1).Text is ";" or "}" || Peek(1).Kind == SyntaxTokenKind.End)+ {+ var expression = Expression();+ // Selector aliases historically used =>; retain it as the+ // same alias node, with admission owned by expose.+ if (Pair("=", ">")) { at += 2; expression = new AliasSyntax(expression, Identifier(), Span(start)); }+ return new ExpressionStatementSyntax(expression, Span(start));+ }var declaration = Declaration(occurrence: false);if (declaration.Name is null && declaration.Body is null && declaration.Initializer is null&& declaration.Annotation is null && declaration.ResultType is null && declaration.Modifiers.Count == 0@@ -140,6 +152,12 @@ public static class FirmamentSyntaxParser}IdentifierSyntax? name = null;if (Current.Kind == SyntaxTokenKind.Identifier && !LineBreak && !IsClause(Current.Text)) name = Identifier();+ // Historical `Model Name mm` is a unit-bearing header. Admit it in+ // this grammar and bind its implicit file body, rather than selecting+ // an EdgeFinish-specific whole-document parser.+ IdentifierSyntax? headerUnit = null;+ if (type.Name.Text is "Model" or "Struct" && name is not null && Current.Kind == SyntaxTokenKind.Identifier+ && !LineBreak && !IsClause(Current.Text)) headerUnit = Identifier();var parameters = Take("(") ? Arguments(")") : [];if (type.Name.Text == "Replace" && Take(".")){@@ -164,6 +182,11 @@ public static class FirmamentSyntaxParserif (Current.Kind == SyntaxTokenKind.Identifier) initializer = new ReferenceSyntax(Identifier(), Previous.Span);}BlockSyntax? body = null;+ if (type.Name.Text == "solid" && Take("with"))+ {+ body = Block(context: $"solid {name?.Text}");+ if (annotation is not null) annotation = new WithSyntax(annotation, body, Span(annotation.Span.Start));+ }if (occurrence){Expect(">");@@ -183,9 +206,21 @@ public static class FirmamentSyntaxParserif (closeName.Text != type.Name.Text) Error("firmament-syntax-tag-mismatch", $"Expected closing tag for {type.Name.Text}, found {closeName.Text}.", closeName.Span);Expect(">"); body = new(statements.ToArray(), new(bodyStart, bodyEnd - bodyStart));}+ else if (body is not null) { /* Compatibility with body already consumed. */ }else if (Is("{")) body = Block(type.Name.Text == "Enum", $"{type.Name.Text} {name?.Text}".TrimEnd());+ else if (headerUnit is not null && contexts.Count == 0)+ {+ var bodyStart = Current.Span.Start;+ body = new(Statements(null), new(bodyStart, source.Length - bodyStart)) { Delimited = false };+ }else if (initializer is null && !End && !LineBreak && !Is(";") && !Is("}"))throw Fail("firmament-syntax-declaration-tail", $"Unexpected '{Current.Text}' after {type.Name.Text} {name?.Text}; expected a body, initializer or separator.");+ if (headerUnit is not null)+ {+ var unit = new ReferenceSyntax(headerUnit, headerUnit.Span);+ var field = new FieldSyntax(new("Units", headerUnit.Span), unit, headerUnit.Span);+ body = body is null ? new([field], headerUnit.Span) : body with { Statements = new StatementSyntax[] { field }.Concat(body.Statements).ToArray() };+ }return new(type, name, modifiers.ToArray(), parameters, annotation, result, clauses.ToArray(), initializer, body, occurrence, Span(start));}@@ -216,8 +251,9 @@ public static class FirmamentSyntaxParserstatements = values.ToArray();}else statements = Statements("}");- Expect("}");- return new(statements, Span(start));+ var closed = Take("}");+ if (!closed) Error("firmament-syntax-expected-token", $"Expected '}}'; found '{(End ? "end of file" : Current.Text)}'.", Current.Span);+ return new(statements, closed ? Span(start) : new(start, Current.Span.Start - start)) { IsClosed = closed };}finally { if (context is not null) contexts.Pop(); depth--; }}@@ -258,7 +294,8 @@ public static class FirmamentSyntaxParserelse if (Current.Kind == SyntaxTokenKind.Identifier){var name = Identifier(); left = new ReferenceSyntax(name, name.Span);- if (name.Text is "Blind" or "CenteredAt" && !Is("(") && !Is(">") && !Is(",") && !LineBreak)+ var compatibilityDepthEnd = name.Text == "depth" && at >= 3 && tokens[at - 2].Text == ":" && tokens[at - 3].Text is "end" or "End";+ if ((name.Text is "Blind" or "CenteredAt" || compatibilityDepthEnd) && !Is("(") && !Is(">") && !Is(",") && !LineBreak){var argument = Expression(80, allowObject, stopGreater);left = new CallSyntax(left, [new(null, argument, null, argument.Span)], Span(start));@@ -276,7 +313,7 @@ public static class FirmamentSyntaxParserwhile (!End){if (++suffixCount > MaxDepth) throw Fail("firmament-syntax-depth", $"Expression chain exceeds the bounded parser limit of {MaxDepth}.");- if (Take("As")) { left = new AliasSyntax(left, Identifier(), Span(start)); continue; }+ if (Take("As") || Take("as")) { left = new AliasSyntax(left, Identifier(), Span(start)); continue; }if (Current.Text is "From" or "To" && Peek(1).Text != ":"){ExpressionSyntax? from = null, to = null;@@ -314,6 +351,14 @@ public static class FirmamentSyntaxParser{at++; left = new SpecializationSyntax(left, Arguments(">"), Span(start)); continue;}+ // Existing surface section lists contain named object values, e.g.+ // Line S0 { ... }. Preserve the identity as syntax; its owner binds it.+ if (allowObject && left is ReferenceSyntax or SpecializationSyntax && Current.Kind == SyntaxTokenKind.Identifier+ && !LineBreak && Current.Text != "with" && Peek(1).Text == "{")+ {+ var objectName = Identifier();+ left = new ObjectSyntax(left, Block(), Span(start)) { Name = objectName }; continue;+ }if (allowObject && Is("{") && left is ReferenceSyntax or SpecializationSyntax or AliasSyntax){ left = new ObjectSyntax(left, Block(), Span(start)); continue; }if (allowObject && Take("with")) { left = new WithSyntax(left, Block(), Span(start)); continue; }@@ -342,7 +387,7 @@ public static class FirmamentSyntaxParservar value = Expression(stopGreater: close == ">");ExpressionSyntax? fallback = Take("=") ? Expression(stopGreater: close == ">") : null;args.Add(new(name, value, fallback, Span(start)));- if (!Take(",") && !(close == "]" && LineBreak && !Is(close))) break;+ if (!Take(",") && !(close == "]" && !Is(close) && (LineBreak || value is ObjectSyntax { Name: not null }))) break;}Expect(close); return args.ToArray();}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxTraversal.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxTraversal.csnew file mode 100644index 00000000..ae8df009--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxTraversal.cs@@ -0,0 +1,96 @@+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++/// <summary>Shared structural traversal for syntax owners and developer inspection.</summary>+public static class FirmamentSyntaxTraversal+{+ public static IEnumerable<DeclarationSyntax> Declarations(DocumentSyntax document) =>+ Statements(document).OfType<DeclarationSyntax>();++ public static IEnumerable<StatementSyntax> Statements(DocumentSyntax document) => document.Statements.SelectMany(Descendants);++ public static IEnumerable<ExpressionSyntax> Expressions(DocumentSyntax document) =>+ Statements(document).SelectMany(s => s switch+ {+ FieldSyntax f => Expressions(f.Value),+ ExpressionStatementSyntax e => Expressions(e.Value),+ ReturnSyntax r => Expressions(r.Value),+ DeclarationSyntax d => (d.Annotation is null ? [] : Expressions(d.Annotation))+ .Concat(d.Initializer is null ? [] : Expressions(d.Initializer))+ .Concat(d.Clauses.SelectMany(c => Expressions(c.Value))),+ _ => []+ });++ public static IEnumerable<ExpressionSyntax> Expressions(ExpressionSyntax expression)+ {+ yield return expression;+ IEnumerable<ExpressionSyntax> children = expression switch+ {+ AliasSyntax a => [a.Value],+ BinarySyntax b => [b.Left, b.Right],+ UnarySyntax u => [u.Operand],+ QuantitySyntax q => [q.Value],+ SequenceSyntax s => s.Items.Select(a => a.Value),+ CallSyntax c => new[] { c.Target }.Concat(c.Arguments.Select(a => a.Value)),+ SpecializationSyntax s => new[] { s.Target }.Concat(s.Arguments.Select(a => a.Value)),+ MemberSyntax m => [m.Target],+ IndexSyntax i => i.Index is null ? [i.Target] : [i.Target, i.Index],+ WithSyntax w => [w.Target],+ TraceSyntax t => new[] { t.Source, t.From, t.To }.OfType<ExpressionSyntax>(),+ TypedValueSyntax t => [t.Type, t.Value],+ ObjectSyntax o => o.Type is null ? [] : [o.Type],+ FrameSyntax f => new[] { f.Origin }.Concat(f.Axes.Select(a => a.Value)),+ MemberSetSyntax m => new[] { m.Target }.Concat(m.Members.Select(a => a.Value)),+ MatchSyntax m => new[] { m.Scrutinee }.Concat(m.Arms.SelectMany(a => new[] { a.Pattern, a.Value })),+ _ => []+ };+ foreach (var child in children)+ foreach (var nested in Expressions(child)) yield return nested;+ }++ private static IEnumerable<StatementSyntax> Descendants(StatementSyntax statement)+ {+ yield return statement;+ foreach (var child in ChildStatements(statement))+ foreach (var descendant in Descendants(child)) yield return descendant;+ }++ public static IEnumerable<DeclarationSyntax> Declarations(StatementSyntax statement)+ {+ if (statement is DeclarationSyntax declaration) yield return declaration;+ foreach (var child in ChildStatements(statement))+ foreach (var nested in Declarations(child)) yield return nested;+ }++ private static IEnumerable<StatementSyntax> ChildStatements(StatementSyntax statement) => statement switch+ {+ DeclarationSyntax d => (d.Body?.Statements ?? []).Concat(d.Initializer is null ? [] : ExpressionBodies(d.Initializer))+ .Concat(d.Annotation is null ? [] : ExpressionBodies(d.Annotation)),+ FieldSyntax f => ExpressionBodies(f.Value),+ ExpressionStatementSyntax e => ExpressionBodies(e.Value),+ ReturnSyntax r => ExpressionBodies(r.Value),+ MappingSyntax m => [m.Value],+ _ => []+ };++ private static IEnumerable<StatementSyntax> ExpressionBodies(ExpressionSyntax expression) => expression switch+ {+ ObjectSyntax o => o.Body.Statements.Concat(o.Type is null ? [] : ExpressionBodies(o.Type)),+ WithSyntax w => w.Body.Statements.Concat(ExpressionBodies(w.Target)),+ SequenceSyntax s => s.Items.SelectMany(a => ExpressionBodies(a.Value)),+ CallSyntax c => ExpressionBodies(c.Target).Concat(c.Arguments.SelectMany(a => ExpressionBodies(a.Value))),+ SpecializationSyntax s => ExpressionBodies(s.Target).Concat(s.Arguments.SelectMany(a => ExpressionBodies(a.Value))),+ BinarySyntax b => ExpressionBodies(b.Left).Concat(ExpressionBodies(b.Right)),+ UnarySyntax u => ExpressionBodies(u.Operand),+ MemberSyntax m => ExpressionBodies(m.Target),+ IndexSyntax i => ExpressionBodies(i.Target).Concat(i.Index is null ? [] : ExpressionBodies(i.Index)),+ QuantitySyntax q => ExpressionBodies(q.Value),+ FrameSyntax f => ExpressionBodies(f.Origin).Concat(f.Axes.SelectMany(a => ExpressionBodies(a.Value))),+ AliasSyntax a => ExpressionBodies(a.Value),+ TraceSyntax t => ExpressionBodies(t.Source).Concat(t.From is null ? [] : ExpressionBodies(t.From)).Concat(t.To is null ? [] : ExpressionBodies(t.To)),+ TypedValueSyntax t => ExpressionBodies(t.Type).Concat(ExpressionBodies(t.Value)),+ MatchSyntax m => ExpressionBodies(m.Scrutinee).Concat(m.Arms.SelectMany(a => ExpressionBodies(a.Pattern).Concat(ExpressionBodies(a.Value)))),+ MemberSetSyntax m => ExpressionBodies(m.Target).Concat(m.Members.SelectMany(a => ExpressionBodies(a.Value))),+ _ => []+ };++}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.csindex 0f769c64..f6e29ed4 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs@@ -16,10 +16,10 @@ internal static class FirmamentSyntaxValues_ => null};- public static bool TryMeasure(ExpressionSyntax? expression, string unit, out double value)+ public static bool TryMeasure(ExpressionSyntax? expression, string unit, out double value, string? implicitUnit = null){value = double.NaN;- if (!Evaluate(expression, unit, out var result, out var dimension) || dimension != (unit.Length == 0 ? 0 : 1)) return false;+ if (!Evaluate(expression, unit, out var result, out var dimension) || dimension != (unit.Length == 0 ? 0 : 1) && !(dimension == 0 && unit == implicitUnit)) return false;value = result; return double.IsFinite(value);}@@ -56,7 +56,7 @@ internal static class FirmamentSyntaxValues}}- public static bool Vector(ExpressionSyntax? expression, string unit, out double[] values)+ public static bool Vector(ExpressionSyntax? expression, string unit, out double[] values, string? implicitUnit = null){values = [];var sharedUnit = expression as QuantitySyntax;@@ -67,13 +67,13 @@ internal static class FirmamentSyntaxValuesCallSyntax { Target: ReferenceSyntax { Name.Text: "Point2" or "Point3" or "Vector2" or "Vector3" } } call => call.Arguments,_ => null};- if (items is null) return false;+ if (items is null || items.Any(item => item.Name is not null || item.Default is not null)) return false;var result = new double[items.Count];for (var i = 0; i < items.Count; i++){var item = items[i].Value;if (sharedUnit is not null) item = new QuantitySyntax(item, sharedUnit.Unit, item.Span);- if (!TryMeasure(item, unit, out result[i])) return false;+ if (!TryMeasure(item, unit, out result[i], implicitUnit)) return false;}values = result; return true;}@@ -81,7 +81,7 @@ internal static class FirmamentSyntaxValues/// <summary>Each semantic owner consumes its actual fields, then closes its scope./// No second field schema or spelling allowlist is maintained here.</summary>-internal sealed class FirmamentSyntaxFields(DeclarationSyntax declaration, List<string> diagnostics)+internal sealed class FirmamentSyntaxFields(DeclarationSyntax declaration, List<string> diagnostics, string? implicitUnit = null){private readonly HashSet<FieldSyntax> consumed = [];public DeclarationSyntax Declaration => declaration;@@ -92,12 +92,12 @@ internal sealed class FirmamentSyntaxFields(DeclarationSyntax declaration, List<if (fields.Length > 1) diagnostics.Add($"firmament-v2-field-duplicate:{declaration.Type.Name.Text}:{name}");return fields.Length == 1 ? fields[0].Value : null;}- public bool Measure(string name, string unit, out double value) => FirmamentSyntaxValues.TryMeasure(Take(name), unit, out value);+ public bool Measure(string name, string unit, out double value) => FirmamentSyntaxValues.TryMeasure(Take(name), unit, out value, implicitUnit);public double Number(string name, string unit, double fallback = double.NaN){var expression = Take(name);if (expression is null) return fallback;- if (FirmamentSyntaxValues.TryMeasure(expression, unit, out var value)) return value;+ if (FirmamentSyntaxValues.TryMeasure(expression, unit, out var value, implicitUnit)) return value;Invalid(name); return double.NaN;}public IReadOnlyList<FieldSyntax> TakeAll(string name)@@ -110,10 +110,18 @@ internal sealed class FirmamentSyntaxFields(DeclarationSyntax declaration, List<// Some owners intentionally try a reference and then an inline vector. A// conversion probe is not an error; the owner decides which forms it admits.public string? Word(string name) => FirmamentSyntaxValues.Reference(Take(name));- public bool Vector(string name, string unit, out double[] values) => FirmamentSyntaxValues.Vector(Take(name), unit, out values);+ public string? Reference(string name, string? fallback = null)+ {+ var expression = Take(name);+ if (expression is null) return fallback;+ var value = FirmamentSyntaxValues.Reference(expression);+ if (value is null) Invalid(name);+ return value;+ }+ public bool Vector(string name, string unit, out double[] values) => FirmamentSyntaxValues.Vector(Take(name), unit, out values, implicitUnit);public void Complete(){- if (declaration.Parameters.Count > 0 || declaration.Annotation is not null || declaration.Initializer is not null)+ if (declaration.Occurrence || declaration.Parameters.Count > 0 || declaration.Annotation is not null || declaration.ResultType is not null || declaration.Initializer is not null)diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:{declaration.Type.Name.Text}:header");if (declaration.Clauses.Count > 0)diagnostics.Add($"firmament-v2-placement-unsupported:{declaration.Type.Name.Text}:{declaration.Name?.Text}: This field-based construct does not admit header placement clauses; use its documented fields.");@@ -122,6 +130,14 @@ internal sealed class FirmamentSyntaxFields(DeclarationSyntax declaration, List<foreach (var statement in declaration.Body?.Statements.Where(s => s is not FieldSyntax) ?? [])diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:{declaration.Type.Name.Text}:{(statement as DeclarationSyntax)?.Type.Name.Text ?? "expression"}");}+ public static FirmamentSyntaxFields Object(ObjectSyntax value, string? name, List<string> diagnostics)+ {+ var type = value.Type as ReferenceSyntax;+ var typeName = type?.Name ?? new IdentifierSyntax("object", value.Span);+ if (type is null) diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:object:header");+ return new(new(new(typeName, [], typeName.Span), value.Name ?? (name is null ? null : new(name, value.Span)),+ [], [], null, null, [], null, value.Body, false, value.Span), diagnostics);+ }public static bool SameField(string authored, string canonical) => authored == canonical || authored == FirmamentSourceSpelling.PreferredField(canonical);public IReadOnlyList<FirmamentV2AuthoredField> AuthoredFields => (declaration.Body?.Statements.OfType<FieldSyntax>() ?? []).Select(f => new FirmamentV2AuthoredField(f.Name.Text, f.Span, f.Value.Span)).ToArray();diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.csindex ccff9a52..b4639760 100644--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs@@ -210,7 +210,7 @@ public static class PrismaticProfileCompositionParserprivate static readonly Regex SlotCornerRadius = new(@"\bCornerRadius\s*:\s*(?<v>[-+.\d]+)mm", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);private static readonly Regex SlotExtent = new(@"\bExtent\s*:\s*(?<v>ThroughAll|Between\s*\(\s*(?<from>[-+.\d]+)mm\s*,\s*(?<to>[-+.\d]+)mm\s*\))", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);- public static bool IsCompositionSource(string source) => FirmamentSyntaxEvidence.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d => d.Type.Name.Text == "Compose");+ public static bool IsCompositionSource(string source) => FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d => d.Type.Name.Text == "Compose");public static PrismaticProfileCompositionParseResult Parse(string source){@@ -293,7 +293,7 @@ public static class PrismaticProfileCompositionParser}var syntax = FirmamentSyntaxParser.Parse(source);- var compose = FirmamentSyntaxEvidence.Declarations(syntax.Document).FirstOrDefault(d => d.Type.Name.Text == "Compose");+ var compose = FirmamentSyntaxTraversal.Declarations(syntax.Document).FirstOrDefault(d => d.Type.Name.Text == "Compose");if (compose?.Body is null || compose.Name is null) return new(null, profiles, diagnostics.Append("compose-source-missing-compose").ToArray());if (compose.Clauses.Count > 0 || compose.Type.Arguments.Count > 0)return new(null, profiles, diagnostics.Append("compose-header-unsupported: Declare a supported Placement block inside Compose.").ToArray());diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.mdindex 355b3e09..fdbf149e 100644--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md@@ -80,3 +80,36 @@ production-status statements:| #22 | Production route visibility plus optional evidence tooling | Normal explain reports UnifiedMechanical. Developer AST/comparison tooling is retained without controlling engineering admission. || #23 | Remaining X1 coverage prerequisite | The production mechanical AST does not yet define every other domain's grammar. || #5, #6, #10, #11, #13, #15-#21, #24 | Original dispositions retained | No new frame/kernel capability or global syntax reconciliation is claimed by the mechanical migration. |+++## Continuing production domain migration (2026-10-14)++The [domain migration report](../release/FIRMAMENT-DOMAIN-FRONTEND-MIGRATION.md)+extends production ownership; it is not another shadow-only milestone. Original+recommendations and rationale above remain preserved. Whole-language completion+is withheld until the remaining domain consumers have actually migrated.++| Recommendations | Current change | Remaining qualification / ownership |+| --- | --- | --- |+| #1, #2, #3, #4 | Gear/Revolve validation uses common build preflight and structured diagnostics. Gear, Revolve/Axis, Panel, Plateau, Loft and SectionChain record fields bind from AST and close their scopes. | Source-based Concept/profile adapters, lowercase V2 and other domain consumers remain. No universal claim for unknown intent in those owners. |+| #7, #14 | Legacy unit-bearing headers and wrapper-free profile construction share mechanical AST binding. Phase3, RoundedBox, primitive-policy and standalone-profile document parsers are deleted. | Lowercase V2, Assembly/Scene, Wire/Sweep and the other domain compilers retain their existing owners pending migration. Explicit V1 serialization remains deliberate compatibility. |+| #9 | Panel surface equations and Revolve angle aliases use shared expression syntax. | Existing semantic algebras/lowerers retain their domain-specific dimensional and geometry contracts. |+| #8, #12 | SectionChain inline frame/profile extraction uses AST spans and preserves existing generated identities. | Scoped AST specialization/substitution with expansion provenance remains required before deleting Template/Feature/Pattern source expansion. |+| #22, #23 | Migrated domain routes are inspectable; incomplete blocks remain in AST for language-service context while compilation fails. | A complete grammar/reference must await remaining domain coverage; developer comparison tooling grants no admission. |+| All other recommendations | Prior dispositions retained. | This change introduces no kernel capability, runtime execution model, general Let, inheritance or new value/reference semantics. |+++## Lowercase compatibility and preferred spelling (2026-10-14)++The [lowercase production cutover](../release/FIRMAMENT-LOWERCASE-AST-MIGRATION.md)+continues direct migration. Historical spellings are compatibility input, not a+second preferred syntax. Recommendations and their original rationale above+remain intact; this amendment records only implemented changes.++| Recommendations | Implemented disposition | Remaining ownership |+| --- | --- | --- |+| #1-#4, #7, #14 | Primitive solids, immutable Box derivation, exposure aliases and Hole modifications in lowercase V2 now consume shared AST nodes and reuse native primitive/Hole binding. Unknown intent in these scopes rejects; old solid/field/Modify/Hole regex readers are removed. | Explicit CompatibilityExtensions owners retain region/cut, typed lets/tolerances, PMI, manufacturing concepts, process Templates, recognition/replacement and lattice grammars. No claim of universal AST admission. |+| #22, #23 | Explain identifies UnifiedCompatibility versus remaining CompatibilityExtensions ownership. | Assembly/Scene, Wire/Sweep, expansion and other domain consumers still require direct migration and geometry qualification. |+| Casing / syntax reconciliation | Prefer PascalCase constructs/types, camelCase built-in fields, lowercase using/as links and preserved engineering symbols. Shared parsing, Profile binding, formatting and language-service token classification admit as. The syntax reference is reorganized and examples updated in place. | User-defined names and published members are not globally folded or renamed. Legacy aliases remain only as bounded compatibility; this is not a promise to perpetuate every V1-to-V2 grammar detail. |+| Invalid selector override fixture | Still invalid, now with a precise firmament-syntax-statement at @ rather than a later record-binding error. | Original failing source remains unchanged; fixture diagnostic metadata follows its migrated owner. |+| All other recommendations | Prior disposition retained. | No kernel, units doctrine, runtime model, general computation or new shadow-only milestone is introduced. |diff --git a/docs/public/firmament/language-style.md b/docs/public/firmament/language-style.mdindex 94c88d42..77d9a242 100644--- a/docs/public/firmament/language-style.md+++ b/docs/public/firmament/language-style.md@@ -10,7 +10,7 @@ The [design proposal](casing-and-layout-proposal.md) records the reasoning.| Type and reusable recipe | PascalCase | `Length`, `PickupSpec`, `Humbucker`, `ControlKnob` || Concrete value, local geometry, occurrence, parameter, port | camelCase | `layout`, `outline`, `neckPickup`, `bottomSeat`, `width` || Built-in property label | camelCase | `units`, `size`, `from`, `translateLocal`, `minimumBendRadius` |-| Linking and scope word | lowercase | `using`, `on`, `over`, `with`, `return`, `include`, `expose`, `bind` |+| Linking and scope word | lowercase | `using`, `as`, `on`, `over`, `with`, `return`, `include`, `expose`, `bind` || Scalar function | camelCase | `fretDistance`, `halfWidth` || Engineering symbol, enum, external identity | Preserve domain spelling | `XY`, `+Z`, `Outer`, `World`, `Origin`, `Fixed`, `Periodic`, `Stock`, `mm`, `m`, `304_Annealed` |@@ -59,8 +59,17 @@ members are not guessed or renamed by the formatter. Property completion acceptseither prefix spelling; generated entry snippets prefer the new spelling, whileschema/field identities in inspection APIs remain stable.-Historical lowercase `model`/`solid` scopes retain their existing grammar and-are left untouched by the spelling pass; they are not migrated to native V2.+Historical lowercase `model`/`solid` scopes are compatibility syntax, not the+preferred style. Their primitive solids, immutable Box derivations, exposure+aliases and Hole modifications now bind through the shared AST and existing+engineering owners. The spelling pass leaves this grammar untouched: converting+`solid stock: Box` to `Box stock` also requires making inherited length units+explicit. Remaining PMI, lattice and manufacturing scopes retain their semantic+owners; see the [migration boundary](../../release/FIRMAMENT-LOWERCASE-AST-MIGRATION.md).++Use lowercase `using` and `as` in Profile headers and pipelines. `Using` and `As`+remain grammar-position aliases, and convention formatting prefers lowercase.+This does not rename a user-defined member or identifier named `As`.Authored names require a manual, binding-aware edit. For example, `.Frame`,`.BottomSeat`, `Spec`, `R` and `H` can be authored public contracts; their casingdiff --git a/docs/public/firmament/overview.md b/docs/public/firmament/overview.mdindex 859e3c10..58218934 100644--- a/docs/public/firmament/overview.md+++ b/docs/public/firmament/overview.md@@ -2,6 +2,15 @@Firmament is a semantic engineering authoring language. It expresses named bodies, dimensions and units, manufacturable features, reusable typed Templates, engineering requirements, Sheet Metal intent, and analyses. Aetheris is the compiler, kernel, and runtime that validates that intent and lowers supported constructions into artifacts such as STEP AP242, flat STEP, SVG, and FEA results.+The useful programming analogy is compile-time object construction. A `Model` is+class-like: it names the enclosing engineering object. A `Struct` is struct-like:+it groups reusable construction or component data. A `Feature` is function-like:+it binds typed inputs to a semantic construction result. A `Pattern` is loop-like:+it expands a finite collection into named, deterministic instances. Aetheris+compiles these declarations into static artifacts; they do not create runtime+objects, mutable execution state, or runtime loops. These analogies do not add+inheritance, heap allocation, or new copy/reference semantics to the language.+A Template is compile-time typed engineering reuse. It accepts values or Records, checks its requirements, specializes deterministically, and then uses the ordinary Firmament lowering path. It is not a text macro or a hidden C# geometry generator.Units are part of values and types. Lengths such as `8mm`, forces such as `500N`, and angles such as `90deg` are checked by the binder. Static Records, arrays, Tables, `with` derivation, and patterns organize finite engineering data and are erased after specialization.diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 314d1952..72a6e4d5 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -1,59 +1,124 @@# Firmament V2 syntax-## Frontend schema+## Definitions, values and construction-`schema` is an optional file-level frontend selector, not a namespace or data-validation schema. Put it before `Model` (comments and whitespace may precede it). Schema-free files retain compatibility routing; new specialized sources should state their owner explicitly.--| Schema | Use it for |-| --- | --- |-| `Mechanical` | Ordinary V2 mechanical parts and features. |-| `WireForm` | Formed wire, bends, coils, and knots. |-| `Sweep` | Circular-section Concept Path sweeps. |-| `SectionChain` | Standalone ruled/G1 section-chain bodies. |-| `Garment` | Profile panels, stitch interfaces, figure measurements and declarative fitting poses. See [garment authoring](garments.md). |--For example, begin a formed-wire program with `schema WireForm`. An explicit schema is authoritative: if its frontend rejects the program, Firmament does not retry another frontend. Historical V1 `schema:` mappings remain compatibility metadata; they are distinct from this `schema <Name>` header.--A canonical native part begins with `Model`, declares `Units`, creates named solids, and applies semantic features in `Modify` or `Compose`:--The bounded material-offset subset is `AddOffset<Prism>` and `RemoveOffset<Prism>` inside an active `Compose`; see [bounded material offsets](material-offsets.md). `Cylinder` and `Sphere` offset families are reserved but not qualified.+Firmament describes a finite engineering artifact at compile time. `Model` is the+class-like owner of an artifact, `Struct` groups reusable construction, `Feature`+is a typed function-like recipe, and `Pattern` performs bounded repetition.+These analogies explain organization; they do not introduce runtime objects,+inheritance, mutable state or arbitrary loops.```firmamentModel Plate {- Units: mm- Box Body { Size: [80mm, 50mm, 8mm] }- Modify Body {- Hole<Shaft> Mount { On: +Z Center: Point2(0mm, 0mm) Diameter: 8mm End: ThroughAll }+ units: mm+ Box stock { size: [80mm, 50mm, 8mm] }+ Modify stock {+ Hole<Shaft> mount {+ on: +Z+ center: Point2(0mm, 0mm)+ diameter: 8mm+ end: ThroughAll}+ }}```-Constructs and types use PascalCase; built-in fields prefer camelCase under the [language-style contract](language-style.md). Existing owner-specific PascalCase field aliases remain compatible, and many examples below retain those aliases. User-defined identifiers and external domain symbols preserve their spelling. There is no global case folding; unsupported casing must be diagnosed by its owner rather than silently ignored.--`Revolve` is a construct under `schema Mechanical`; `schema Revolve` is not an available frontend selector.+A declaration has a PascalCase construct or type, an optional `<Variant>`, a+case-sensitive name and a brace-delimited body. Fields use `camelCase: value`.+Lists use brackets; calls use parentheses. Separate adjacent fields with a newline+or semicolon; dense one-line bodies may also use the owning grammar's established+field boundaries. Required terminators in specialized grammars are documented in+their guides.-Use `aetheris validate file.firmament --json` before building. Generic mechanical validation runs engineering compilation in memory; `--parse-only` reports `parsed-not-built`. This X0 qualification is incomplete for advanced Compose/boundary source consumption; see the [qualification report](../../release/FIRMAMENT-FRONTEND-X0.md). See [diagnostics](../reference/diagnostics.md) for the diagnostic representation.+| Source role | Preferred spelling |+| --- | --- |+| Constructs and types | `Model`, `Struct`, `Box`, `Profile`, `Feature`, `Length` |+| Built-in fields | `units`, `size`, `center`, `counterboreDepth` |+| Linking words | `using`, `as`, `on`, `over`, `with`, `include`, `expose`, `bind` |+| Local values and parameters | `stock`, `outline`, `mountPoint`, `depth` |+| Engineering symbols and enum values | `XY`, `+Z`, `Outer`, `ThroughAll`, `World`, `mm` |++`Profile outline using layout` selects its construction frame/context;+`guide.Bottom as south` gives traced geometry an explicit identity. `Using` and+`As` remain admitted aliases at those grammar positions. A field such as+`on: +Z` is distinct from a header clause such as `Concept Struct layout on XY`.+See [language style](language-style.md) for formatting and compatibility rules.++Built-in PascalCase field aliases remain admitted by their owners. User names,+named recipe arguments and published members preserve their authored spelling;+`Spec.Width` is not automatically renamed to `spec.width`. Unknown statements or+fields are errors in migrated AST scopes, regardless of whether the remaining+geometry could build.++## Frontend schema and validation++An optional `schema <Name>` header selects a specialized frontend. Put it before+`Model`, after any leading comments. Explicit selection is authoritative: rejection+does not retry another frontend. `Revolve` belongs to `Mechanical`; it is not a+schema name.++| Schema | Authoring guide |+| --- | --- |+| `Mechanical` | Ordinary parts, profiles and semantic features; the example above. |+| `WireForm` | [Formed wire](wire-form.md), bends and coils. |+| `Sweep` | Circular-section Concept Path sweeps. |+| `SectionChain` | [Section chains](section-chains.md) and ruled/G1 bodies. |+| `Garment` | [Garments](garments.md), panels, stitch interfaces and fitting poses. |++Use `aetheris validate file.firmament --json` before building. Normal mechanical+validation performs engineering compilation in memory. `--parse-only` reports+`ParsedNotBuilt`, rather than claiming geometry construction has succeeded.+`--explain` exposes the chosen parser route as developer metadata. See+[diagnostics](../reference/diagnostics.md) for the structured diagnostic contract.++Normal mechanical construction, Revolve, Gear, Panel, Plateau, SectionChain and+Loft bind their admitted inputs from the shared recursive-descent AST. Lowercase+primitive solids, derived Box records, exposure aliases, Hole modifications and region/cut operations now+use that AST too; their remaining legacy semantic extensions have separate owners.+See [migration status](../../release/FIRMAMENT-LOWERCASE-AST-MIGRATION.md) for the+qualified boundary. Specialized frontend coverage is not a promise of a single+whole-language AST binder yet.++## Compatibility spelling++New source uses `Model`, `units: mm` and direct named primitives, as above.+Historical `model`, `units mm`, `solid name: Box`, `modify` and `hole<shaft>` are+bounded compatibility spellings. Inside that historical primitive grammar only,+bare length values inherit the model's millimetres. Native fields retain explicit+dimensional values: write `size: [30mm, 24mm, 12mm]`.++`solid tall: stock with { size: [30, 24, 20] }` retains immutable Box derivation:+the original `stock` is unchanged. `expose { face(+Z) as top }` names a face;+the historical `face(+Z) => top` association remains compatible. Neither form+requests an extra geometric operation.++These aliases preserve legitimate existing intent; they do not establish a second+preferred language. The convention formatter does not mechanically convert old+solid grammar into native declarations. Serialization-shaped V1 `model:` and+`firmament:` documents have an explicit compatibility boundary and are not native+V2 examples. Unknown casing is never a request for arbitrary case-insensitive+interpretation.## Reusable semantic construction with Feature-`Feature` is Firmament's function-like abstraction for reusable semantic construction. It accepts typed inputs and returns exactly one typed semantic output. Feature evaluation is pure, deterministic, file-local in X1, and expanded before Feature AIR; a definition does not materialize geometry until it is invoked.+`Feature` is Firmament's function-like abstraction for reusable semantic construction. It accepts typed inputs and returns exactly one typed semantic output. Feature evaluation is pure, deterministic, file-local, and expanded before Feature AIR; a definition does not materialize geometry until it is invoked.```firmament-Feature M8Counterbore(Center: Point2, Depth: Length = 4mm) -> Hole<Counterbore> {- let CounterboreDiameter: Length = 8.5mm + 5.5mm+Feature M8Counterbore(center: Point2, depth: Length = 4mm) -> Hole<Counterbore> {+ let counterboreDiameter: Length = 8.5mm + 5.5mmreturn Hole<Counterbore> {- On: +Z- Center: Center- Diameter: 8.5mm- CounterboreDiameter: CounterboreDiameter- CounterboreDepth: Depth- End: ThroughAll+ on: +Z+ center: center+ diameter: 8.5mm+ counterboreDiameter: counterboreDiameter+ CounterboreDepth: depth+ end: ThroughAll}}Modify Plate {- M8Counterbore(Center: Point2(-20mm, 0mm))- M8Counterbore(Center: Point2(20mm, 0mm), Depth: 5mm)+ M8Counterbore(center: Point2(-20mm, 0mm))+ M8Counterbore(center: Point2(20mm, 0mm), depth: 5mm)}```@@ -76,12 +141,12 @@ Use each abstraction for its single role:Feature composes with an existing bounded Pattern without exposing its internals:```firmament-Feature MountHole(Center: Point3, Diameter: Length = 6mm) -> Hole<Shaft> {+Feature MountHole(center: Point3, diameter: Length = 6mm) -> Hole<Shaft> {return Hole<Shaft> {- On: Base.Top- Center: Center- Diameter: Diameter- End: ThroughAll+ on: Base.Top+ center: center+ diameter: diameter+ end: ThroughAll}}@@ -96,11 +161,35 @@ Concept Struct Design {Pattern Mounts {Source: Design.Points- MountHole(Center: Item)+ MountHole(center: Item)}```-The two-column, two-row Grid is the explicit four-hole rectangular distribution. This semantic PointSet Pattern uses `Item`. The older `Pattern Name Over Records { Template<Current> }` form remains the record-array composition syntax for finite feature Templates; `Current` is the selected record. Feature functions do not replace that compatibility form.+The two-column, two-row Grid is the explicit four-hole rectangular distribution. This semantic PointSet Pattern uses `Item`. The older `Pattern Name over Records { Template<Current> }` form remains the record-array composition syntax for finite feature Templates; `Current` is the selected record. Feature functions do not replace that compatibility form.++A Feature may return a call to another Feature with the same declared result type:++```firmament+Feature CoreCounterbore(center: Point2, depth: Length) -> Hole<Counterbore> {+ return Hole<Counterbore> {+ on: +Z+ center: center+ diameter: 8.5mm+ counterboreDiameter: 14mm+ CounterboreDepth: depth+ end: ThroughAll+ }+}++Feature M8Counterbore(center: Point2) -> Hole<Counterbore> {+ return CoreCounterbore(center: center, depth: 4mm)+}+```++Structurally different edge finishes should be separate Features —for example, `StandardChamfer` and `StandardFillet`. A caller may instead select a specialized product with Template where that owning Template grammar admits the returned construction. Feature itself cannot branch between them.++Feature is supported by the `Mechanical` frontend. `WireForm`, `Sweep`, and `SectionChain` reject Feature declarations explicitly; shared cross-schema Feature IR and module/library packaging are deferred.+## Finite named sets and mapping@@ -114,8 +203,8 @@ Static MountPoints: Set<Point2> {UpperRight => Point2(16mm, 9mm)}-Pattern Mounts Over MountPoints {- point => M8Counterbore(Center: point)+Pattern Mounts over MountPoints {+ point => M8Counterbore(center: point)}```@@ -132,8 +221,8 @@ Mirror and radial Pattern are resolved before geometry materialization. They traAn explicitly named destination derives from an existing Profile or concrete feature and an existing Plane:```firmament-Plane CenterPlane { Origin: [0mm,0mm,0mm]; Normal: [1,0,0]; Up: [0,0,1] }-Hole<Shaft> LeftMount { On: +Z; Center: Point2(24mm,0mm); Diameter: 6mm; End: ThroughAll }+Plane CenterPlane { origin: [0mm,0mm,0mm]; normal: [1,0,0]; up: [0,0,1] }+Hole<Shaft> LeftMount { on: +Z; center: Point2(24mm,0mm); diameter: 6mm; end: ThroughAll }Mirrored Feature RightMount From LeftMount { Across: CenterPlane }```@@ -144,8 +233,8 @@ Keep the source Profile semantic too. For example, an arbitrary triangular sourcA radial feature Pattern uses an existing Axis and includes the source construction as instance zero:```firmament-Axis MainAxis { Origin: [0mm,0mm,0mm]; Direction: [0,0,1] }-Hole<Shaft> BoltSeed { On: +Z; Center: Point2(26mm,0mm); Diameter: 6mm; End: ThroughAll }+Axis MainAxis { origin: [0mm,0mm,0mm]; direction: [0,0,1] }+Hole<Shaft> BoltSeed { on: +Z; center: Point2(26mm,0mm); diameter: 6mm; end: ThroughAll }Radial Pattern BoltCircle { Source: BoltSeed About: MainAxis Count: 6 Angle: full }```@@ -167,44 +256,21 @@ A Profile exactly on its reflection line may be retained as an equivalent named`Polygon2<Rhombus>` is the first bounded closed-polygon authoring form. A rhombus is specified by its center and full horizontal/vertical diagonal lengths:```firmament-Concept Struct Layout On XY {+Concept Struct Layout on XY {Polygon2<Rhombus> MountBoundaryShape {Center: [0mm, 0mm]Diagonals: [90mm, 64mm]}}-Profile MountBoundary Using Layout {+Profile MountBoundary using Layout {Loop Outer { MountBoundaryShape |> TraceLoop }}```This produces vertices at south, east, north, and west half-diagonal offsets and a counter-clockwise closed boundary. It lowers before pipeline validation to the ordinary typed `Point2`, `Line2`, and Profile path, so closure, orientation, Span containment, materialization, and STEP export keep their existing owners.-The angle-bracket argument is a closed built-in shape variant, not a general generic or user-defined type. X1 admits only `Rhombus`; both diagonals must be finite positive lengths. It intentionally does not add arbitrary vertex arrays, `Connect`, a scene graph, or a second polygon materializer. Use `Rect2` when the four sides are axis-aligned; unequal horizontal and vertical rhombus diagonals do not describe that rectangle.--A Feature may return a call to another Feature with the same declared result type:--```firmament-Feature CoreCounterbore(Center: Point2, Depth: Length) -> Hole<Counterbore> {- return Hole<Counterbore> {- On: +Z- Center: Center- Diameter: 8.5mm- CounterboreDiameter: 14mm- CounterboreDepth: Depth- End: ThroughAll- }-}--Feature M8Counterbore(Center: Point2) -> Hole<Counterbore> {- return CoreCounterbore(Center: Center, Depth: 4mm)-}-```--Structurally different edge finishes should be separate Features in X1—for example, `StandardChamfer` and `StandardFillet`. A caller may instead select a specialized product with Template where that owning Template grammar admits the returned construction. Feature itself cannot branch between them.--For X1, Feature is supported by the `Mechanical` frontend. `WireForm`, `Sweep`, and `SectionChain` reject Feature declarations explicitly; shared cross-schema Feature IR and module/library packaging are deferred.+The angle-bracket argument is a closed built-in shape variant, not a general generic or user-defined type. The admitted variant is `Rhombus`; both diagonals must be finite positive lengths. It intentionally does not add arbitrary vertex arrays, `Connect`, a scene graph, or a second polygon materializer. Use `Rect2` when the four sides are axis-aligned; unequal horizontal and vertical rhombus diagonals do not describe that rectangle.## Finite Profile and Path composition@@ -215,7 +281,7 @@ for From/On/Translate/Rotate and bounded uniform Scale/Pivot syntax.`|>` composes compatible semantic geometry in a finite authoring pipeline. In a Profile loop, each source span is traced in authored order and automatically oriented to continue from the preceding endpoint:```firmament-Profile BaseProfile Using Layout {+Profile BaseProfile using Layout {Loop Outer {Stock.Bottom|> Stock.Right@@ -226,18 +292,18 @@ Profile BaseProfile Using Layout {}```-The first stage uses its source direction. Later stages match the current endpoint against the candidate span's endpoints. A unique end match reverses the traced geometry automatically; no match reports `firmament-profile-pipeline-disconnected`, and a degenerate two-way match reports `firmament-profile-pipeline-orientation-ambiguous`. `Reverse Stock.Left` prefers reversed orientation first and then falls back to the normal connectable orientation; on the opening stage it selects the initial direction. `Stock.Bottom As MountingEdge` changes the output segment identity while retaining source provenance.+The first stage uses its source direction. Later stages match the current endpoint against the candidate span's endpoints. A unique end match reverses the traced geometry automatically; no match reports `firmament-profile-pipeline-disconnected`, and a degenerate two-way match reports `firmament-profile-pipeline-orientation-ambiguous`. `Reverse Stock.Left` prefers reversed orientation first and then falls back to the normal connectable orientation; on the opening stage it selects the initial direction. `Stock.Bottom as MountingEdge` changes the output segment identity while retaining source provenance.To trace only part of a guide, use `Guide To Point`. The current pipeline endpoint is the implicit start. On the opening stage, use `Guide From Start To End`; `Guide To End` may omit `From` when the guide's natural start is intended. Endpoints must be named points on the guide. This is bounded selection, not a general slicing expression:```firmament-Profile Bracket Using Layout {- Horizontal.Bottom As South- |> Horizontal.Right As East- |> Horizontal.Top To Notch As Inner- |> Vertical.Right To Vertical.TopRight As Upright- |> Vertical.Top As North- |> Vertical.Left To Horizontal.BottomLeft As West+Profile Bracket using Layout {+ Horizontal.Bottom as South+ |> Horizontal.Right as East+ |> Horizontal.Top To Notch as Inner+ |> Vertical.Right To Vertical.TopRight as Upright+ |> Vertical.Top as North+ |> Vertical.Left To Horizontal.BottomLeft as West|> Close}```@@ -250,16 +316,16 @@ A half-circle revolve meridian uses the same syntax through the ordinary Mechanischema MechanicalModel RevolvedSphere {- Units: mm- Axis MainAxis { Origin: [0mm, 0mm, 0mm]; Direction: [0, 1, 0] }- Point2 South { Position: [0mm, -20mm] }- Point2 North { Position: [0mm, 20mm] }- Point2 Center { Position: [0mm, 0mm] }- Concept Circle2 Meridian { Center: Center; Radius: 20mm }- Line2 Diameter { From: North; To: South }+ units: mm+ Axis MainAxis { origin: [0mm, 0mm, 0mm]; direction: [0, 1, 0] }+ Point2 South { position: [0mm, -20mm] }+ Point2 North { position: [0mm, 20mm] }+ Point2 Center { position: [0mm, 0mm] }+ Concept Circle2 Meridian { center: Center; radius: 20mm }+ Line2 Diameter { from: North; to: South }Profile SphereSection {- Meridian From South To North As Arc- |> Diameter As AxisClosure+ Meridian From South To North as Arc+ |> Diameter as AxisClosure|> Close}Revolve Ball { Profile: SphereSection; About: MainAxis; Angle: full }@@ -271,13 +337,13 @@ Model RevolvedSphere {Recognized guide declarations may appear at the start of an implicit-loop Profile body, followed by exactly one pipeline expression:```firmament-Profile SideProfile Using PositiveXWorkplane {- Rect2 Outline { Center: [0mm, 0mm]; Size: [20mm, 10mm] }+Profile SideProfile using PositiveXWorkplane {+ Rect2 Outline { center: [0mm, 0mm]; size: [20mm, 10mm] }Outline |> TraceLoop}```-Segment names are Profile-wide identities. Manual `Segment` and pipeline stages both preserve their authored or inherited leaf names; loops do not silently qualify them. A traced full `Circle2` or `Ellipse2` derives its segment identity from the guide name, so `Outside |> TraceLoop` and `Inside |> TraceLoop` have distinct identities. If two loops would introduce the same name, binding reports `firmament-profile-segment-identity-collision`. Resolve the collision explicitly with `As` on the pipeline stages (for example, `Cutout.Bottom As CutoutBottom`) or by renaming a manual Segment.+Segment names are Profile-wide identities. Manual `Segment` and pipeline stages both preserve their authored or inherited leaf names; loops do not silently qualify them. A traced full `Circle2` or `Ellipse2` derives its segment identity from the guide name, so `Outside |> TraceLoop` and `Inside |> TraceLoop` have distinct identities. If two loops would introduce the same name, binding reports `firmament-profile-segment-identity-collision`. Resolve the collision explicitly with `as` on the pipeline stages (for example, `Cutout.Bottom as CutoutBottom`) or by renaming a manual Segment.A `Concept Path` may also compose existing named spans and remain open:@@ -285,8 +351,8 @@ A `Concept Path` may also compose existing named spans and remain open:Concept Path Guide {Stock.Bottom|> Stock.Right- |> Stock.Top As Return+ |> Stock.Top as Return}```-Pipeline source order is semantic order. Stages are limited to geometry references (qualified or unqualified), bounded `From`/`To` named endpoints, optional `Reverse`, optional `As`, `Close`, and `TraceLoop` in their admitted contexts. The operator has lower binding precedence than member access and does not admit arithmetic stages, calls, lambdas, conditionals, filtering, mutation, runtime execution, or repetition. Use Feature for a reusable semantic transformation, Pattern for bounded repetition, Template for specialization, and `|>` for finite semantic composition. Manual `Segment { Trace/From/To }` remains supported for compatibility and deliberate low-level parity tests; ordinary canonical Profile authoring does not require it.+Pipeline source order is semantic order. Stages are limited to geometry references (qualified or unqualified), bounded `From`/`To` named endpoints, optional `Reverse`, optional `as`, `Close`, and `TraceLoop` in their admitted contexts. The operator has lower binding precedence than member access and does not admit arithmetic stages, calls, lambdas, conditionals, filtering, mutation, runtime execution, or repetition. Use Feature for a reusable semantic transformation, Pattern for bounded repetition, Template for specialization, and `|>` for finite semantic composition. Manual `Segment { Trace/From/To }` remains supported for compatibility and deliberate low-level parity tests; ordinary canonical Profile authoring does not require it.diff --git a/docs/release/FIRMAMENT-DOMAIN-FRONTEND-MIGRATION.evidence.json b/docs/release/FIRMAMENT-DOMAIN-FRONTEND-MIGRATION.evidence.jsonnew file mode 100644index 00000000..3c426663--- /dev/null+++ b/docs/release/FIRMAMENT-DOMAIN-FRONTEND-MIGRATION.evidence.json@@ -0,0 +1,472 @@+{+ "baselineCommit": "83855e91",+ "geometry": [+ {+ "source": "fixtures/Canonical/Gears/bevel-basic.firmament",+ "command": "build",+ "artifact": "before-000.step",+ "expectedExitCode": 0,+ "beforeSha256": "42d432cec557bf52da34c7543ae87d6f267893fbc878f67ac51a4ea7ea1231e6",+ "afterSha256": "42d432cec557bf52da34c7543ae87d6f267893fbc878f67ac51a4ea7ea1231e6",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Gears/bevel-pair-gear.firmament",+ "command": "build",+ "artifact": "before-001.step",+ "expectedExitCode": 0,+ "beforeSha256": "bceb43b217b5411b6329da026b20907eaebbf3d2ccb80eaab2f35c4f4eed569f",+ "afterSha256": "bceb43b217b5411b6329da026b20907eaebbf3d2ccb80eaab2f35c4f4eed569f",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Gears/bevel-pair-pinion.firmament",+ "command": "build",+ "artifact": "before-002.step",+ "expectedExitCode": 0,+ "beforeSha256": "647a2646434d7abacbfe864660f134d0b971d5532626f732b092a2d872898de6",+ "afterSha256": "647a2646434d7abacbfe864660f134d0b971d5532626f732b092a2d872898de6",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Gears/internal-spur-basic.firmament",+ "command": "build",+ "artifact": "before-003.step",+ "expectedExitCode": 0,+ "beforeSha256": "91da8edb7c4569b988dc2fd48dba2bb1d97e246d75fa959f39963e072f4f924b",+ "afterSha256": "91da8edb7c4569b988dc2fd48dba2bb1d97e246d75fa959f39963e072f4f924b",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Gears/miter-basic.firmament",+ "command": "build",+ "artifact": "before-004.step",+ "expectedExitCode": 0,+ "beforeSha256": "3cec7390e3feb1fa0a253aa23838bb6919196e62e52465340b77fc10f99aa1ac",+ "afterSha256": "3cec7390e3feb1fa0a253aa23838bb6919196e62e52465340b77fc10f99aa1ac",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Gears/pawl-basic.firmament",+ "command": "build",+ "artifact": "before-005.step",+ "expectedExitCode": 0,+ "beforeSha256": "632261bdb3a31aa42383105737d685f3bb6f3dfc5620277683b417de5a4a59d5",+ "afterSha256": "632261bdb3a31aa42383105737d685f3bb6f3dfc5620277683b417de5a4a59d5",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Gears/ratchet-basic.firmament",+ "command": "build",+ "artifact": "before-006.step",+ "expectedExitCode": 0,+ "beforeSha256": "7aff0eeb85662c432d1626deccdef0f8df79ba0f040730ceb65364885c52da82",+ "afterSha256": "7aff0eeb85662c432d1626deccdef0f8df79ba0f040730ceb65364885c52da82",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Gears/spur-basic.firmament",+ "command": "build",+ "artifact": "before-007.step",+ "expectedExitCode": 0,+ "beforeSha256": "ee6d1883e020c1c148423b1b7cb42dff2f1d5f9eb31256c62c379f082325dfce",+ "afterSha256": "ee6d1883e020c1c148423b1b7cb42dff2f1d5f9eb31256c62c379f082325dfce",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Gears/spur-driven-48.firmament",+ "command": "build",+ "artifact": "before-008.step",+ "expectedExitCode": 0,+ "beforeSha256": "12d0e33a6e4d01e2d14ca369846b162f091ae7e329f0ad301034d2d6346262e8",+ "afterSha256": "12d0e33a6e4d01e2d14ca369846b162f091ae7e329f0ad301034d2d6346262e8",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Gears/spur-high-tooth.firmament",+ "command": "build",+ "artifact": "before-009.step",+ "expectedExitCode": 0,+ "beforeSha256": "f32c8d2159f266a1b0bdd9704715fec764b1c2f56080ac0a81348ac0c4fff448",+ "afterSha256": "f32c8d2159f266a1b0bdd9704715fec764b1c2f56080ac0a81348ac0c4fff448",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Revolve/arbitrary-axis.firmament",+ "command": "build",+ "artifact": "before-010.step",+ "expectedExitCode": 0,+ "beforeSha256": "8cd408bc2a221267724c3c342dd184a0ef1c24045b3650c57b5fca60bebe2fd2",+ "afterSha256": "8cd408bc2a221267724c3c342dd184a0ef1c24045b3650c57b5fca60bebe2fd2",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Revolve/knob.firmament",+ "command": "build",+ "artifact": "before-011.step",+ "expectedExitCode": 0,+ "beforeSha256": "9cf92939b4b39d9848a8d4a913321d322857d4dc89159978ea013d4d13570a67",+ "afterSha256": "9cf92939b4b39d9848a8d4a913321d322857d4dc89159978ea013d4d13570a67",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Revolve/partial-quarter.firmament",+ "command": "build",+ "artifact": "before-012.step",+ "expectedExitCode": 0,+ "beforeSha256": "451976bd3245a189dc22a95196d3987f67b5ca15987484cacc7d3918cc666386",+ "afterSha256": "451976bd3245a189dc22a95196d3987f67b5ca15987484cacc7d3918cc666386",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Revolve/sphere.firmament",+ "command": "build",+ "artifact": "before-013.step",+ "expectedExitCode": 0,+ "beforeSha256": "d60833130cda91d4846e0a96cba74fb5c5a184448ecabd1b0462584e866db1da",+ "afterSha256": "d60833130cda91d4846e0a96cba74fb5c5a184448ecabd1b0462584e866db1da",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Revolve/stepped-shaft.firmament",+ "command": "build",+ "artifact": "before-014.step",+ "expectedExitCode": 0,+ "beforeSha256": "f42ce8a891f446177fa875d6419a4ac0c4dbde1699f8397514a7058b294d1b1e",+ "afterSha256": "f42ce8a891f446177fa875d6419a4ac0c4dbde1699f8397514a7058b294d1b1e",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/SectionChain/eight-section-ergonomic.firmament",+ "command": "section-chain",+ "artifact": "section-before-000.step",+ "expectedExitCode": 0,+ "beforeSha256": "0c5d6e741f86bfaae69f7c3a89b88a787d6716cdf0853d20acb8999b2b445608",+ "afterSha256": "0c5d6e741f86bfaae69f7c3a89b88a787d6716cdf0853d20acb8999b2b445608",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/SectionChain/explicit-sketch-ruled.firmament",+ "command": "section-chain",+ "artifact": "section-before-001.step",+ "expectedExitCode": 0,+ "beforeSha256": "9db84419023660b1d63163141e840140bbebf79557954f000c13e55143e3d298",+ "afterSha256": "9db84419023660b1d63163141e840140bbebf79557954f000c13e55143e3d298",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/SectionChain/g0-explicit-ruled.firmament",+ "command": "section-chain",+ "artifact": "section-before-002.step",+ "expectedExitCode": 0,+ "beforeSha256": "d420bcc2915f890a26d1e2958aab96103a615044db9ade356d55d9e3077cc09b",+ "afterSha256": "d420bcc2915f890a26d1e2958aab96103a615044db9ade356d55d9e3077cc09b",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/SectionChain/g1-two-transition.firmament",+ "command": "section-chain",+ "artifact": "section-before-003.step",+ "expectedExitCode": 0,+ "beforeSha256": "890881a31a2f7779e1ffa3e7ae2d07e70dd4894ed9b77c1f636954c4bf91c2c8",+ "afterSha256": "890881a31a2f7779e1ffa3e7ae2d07e70dd4894ed9b77c1f636954c4bf91c2c8",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/SectionChain/hollow-loft-twist.firmament",+ "command": "section-chain",+ "artifact": "section-before-004.step",+ "expectedExitCode": 0,+ "beforeSha256": "208fb0ccef3c309f2b0376d2e27200a88209ff5f9d8cb14da4ebc0dab4481bd1",+ "afterSha256": "208fb0ccef3c309f2b0376d2e27200a88209ff5f9d8cb14da4ebc0dab4481bd1",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/SectionChain/normalized-rounded-sections.firmament",+ "command": "section-chain",+ "artifact": "section-before-005.step",+ "expectedExitCode": 0,+ "beforeSha256": "bad0c4fc8ad571e14d837e25880251e0592ea9319d73b23356eefc86a7dc564e",+ "afterSha256": "bad0c4fc8ad571e14d837e25880251e0592ea9319d73b23356eefc86a7dc564e",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/SectionChain/open-chain.firmament",+ "command": "section-chain",+ "artifact": "section-before-006.step",+ "expectedExitCode": 0,+ "beforeSha256": "56d0000dac6523f3528e6a2671d643a5403bf6b665f5b16e9fde39008cfc52f4",+ "afterSha256": "56d0000dac6523f3528e6a2671d643a5403bf6b665f5b16e9fde39008cfc52f4",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/SectionChain/six-section-ergonomic.firmament",+ "command": "section-chain",+ "artifact": "section-before-007.step",+ "expectedExitCode": 0,+ "beforeSha256": "97dccd26fcf8aac02804cf793af57cb76496677bef28fea4fb6c4ef5e3495b89",+ "afterSha256": "97dccd26fcf8aac02804cf793af57cb76496677bef28fea4fb6c4ef5e3495b89",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/SectionChain/smooth-corner-sections.firmament",+ "command": "section-chain",+ "artifact": "section-before-008.step",+ "expectedExitCode": 0,+ "beforeSha256": "d3ea843dd9f5fb695459d7488853d36b74c5b7b2d4273eaabd9f2d2623522356",+ "afterSha256": "d3ea843dd9f5fb695459d7488853d36b74c5b7b2d4273eaabd9f2d2623522356",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/SectionChain/solid-loft-common-ray.firmament",+ "command": "section-chain",+ "artifact": "section-before-009.step",+ "expectedExitCode": 0,+ "beforeSha256": "10d5fe263138f9a9bf33715aa0623d405e3af0a4b889dc60f2fbba4bc6af550c",+ "afterSha256": "10d5fe263138f9a9bf33715aa0623d405e3af0a4b889dc60f2fbba4bc6af550c",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/SectionChain/two-section-ruled.firmament",+ "command": "section-chain",+ "artifact": "section-before-010.step",+ "expectedExitCode": 0,+ "beforeSha256": "4dc0d3fc84e37cd87b9631923500095cea9d5aa8f8865622cb4e5986bd6e709c",+ "afterSha256": "4dc0d3fc84e37cd87b9631923500095cea9d5aa8f8865622cb4e5986bd6e709c",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Compatibility/LegacyV1/Experiments/air-fillet-junction-m4a/canonical-r1.firmament",+ "command": "build",+ "artifact": "header-before-000.step",+ "expectedExitCode": 0,+ "beforeSha256": "55fef3c2bca4df7cc246619524149a3de934362cc51e544f56b7211ec5ddc650",+ "afterSha256": "55fef3c2bca4df7cc246619524149a3de934362cc51e544f56b7211ec5ddc650",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Compatibility/LegacyV1/Experiments/air-fillet-junction-m4a/larger-r2.firmament",+ "command": "build",+ "artifact": "header-before-001.step",+ "expectedExitCode": 0,+ "beforeSha256": "9dcc7ca557a7b5df256a5685bc10860b58ebb6063e2298432177ee07b9571846",+ "afterSha256": "9dcc7ca557a7b5df256a5685bc10860b58ebb6063e2298432177ee07b9571846",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Compatibility/LegacyV1/Experiments/air-fillet-junction-m4a/nonsquare-r1.firmament",+ "command": "build",+ "artifact": "header-before-002.step",+ "expectedExitCode": 0,+ "beforeSha256": "9a1c02e58856dfd4de0b7c79aaadace9d95cb8cbc0bc0e113a7dcf1736edc21e",+ "afterSha256": "9a1c02e58856dfd4de0b7c79aaadace9d95cb8cbc0bc0e113a7dcf1736edc21e",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Invalid/Chamfer/air-cylinder-top-rim-oversized.invalid.firmament",+ "command": "build",+ "artifact": "header-before-003.step",+ "expectedExitCode": 1,+ "beforeSha256": null,+ "afterSha256": null,+ "actualExitCode": 1,+ "matched": true+ },+ {+ "source": "fixtures/Invalid/Chamfer/air-cylinder-top-rim-zero.invalid.firmament",+ "command": "build",+ "artifact": "header-before-004.step",+ "expectedExitCode": 1,+ "beforeSha256": null,+ "afterSha256": null,+ "actualExitCode": 1,+ "matched": true+ },+ {+ "source": "fixtures/Regression/Chamfer/valid/air-cylinder-top-rim-chamfer.valid.firmament",+ "command": "build",+ "artifact": "header-before-005.step",+ "expectedExitCode": 0,+ "beforeSha256": "f5916b29365988f6112a4cbc3d2fe487f2f1ebc4c591f5e34e32d6db64fee997",+ "afterSha256": "f5916b29365988f6112a4cbc3d2fe487f2f1ebc4c591f5e34e32d6db64fee997",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Regression/Chamfer/valid/air-cylinder-top-rim-variant.valid.firmament",+ "command": "build",+ "artifact": "header-before-006.step",+ "expectedExitCode": 0,+ "beforeSha256": "fd37ca186dce6995b0205a04e2f1ee7399c714a5dea9ce237acb172b26526191",+ "afterSha256": "fd37ca186dce6995b0205a04e2f1ee7399c714a5dea9ce237acb172b26526191",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Regression/Chamfer/valid/air-top-boundary-chamfer-distance-2.valid.firmament",+ "command": "build",+ "artifact": "header-before-007.step",+ "expectedExitCode": 0,+ "beforeSha256": "89273fbfeb1bd7697e54c539830d189213226cc6e9b2ce2bf864ec6188567864",+ "afterSha256": "89273fbfeb1bd7697e54c539830d189213226cc6e9b2ce2bf864ec6188567864",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Regression/Chamfer/valid/air-top-boundary-chamfer-non-square.valid.firmament",+ "command": "build",+ "artifact": "header-before-008.step",+ "expectedExitCode": 0,+ "beforeSha256": "b82bfb8a03cffbedeb9f8051d79a5798c7b9d79f7f5cec666cc24a9bb64c6d9b",+ "afterSha256": "b82bfb8a03cffbedeb9f8051d79a5798c7b9d79f7f5cec666cc24a9bb64c6d9b",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Regression/Chamfer/valid/air-top-boundary-chamfer.valid.firmament",+ "command": "build",+ "artifact": "header-before-009.step",+ "expectedExitCode": 0,+ "beforeSha256": "677d6b2f0ee902e528310348370b651b663bbbef2aeef1e7a0ca8910f81f7d95",+ "afterSha256": "677d6b2f0ee902e528310348370b651b663bbbef2aeef1e7a0ca8910f81f7d95",+ "actualExitCode": 0,+ "matched": true+ },+ {+ "source": "fixtures/Canonical/Surfacing/g2-planar-plateau.firmament",+ "command": "build",+ "artifact": "plateau.step",+ "expectedExitCode": 0,+ "beforeSha256": "c14bda427b7e335e9bedce983b2d6b94c18fcb8e7f90b6c2dc00a602f54b8535",+ "baselineNote": "Captured before Plateau AST field migration with the existing field parser and restored declaration recognition.",+ "afterSha256": "c14bda427b7e335e9bedce983b2d6b94c18fcb8e7f90b6c2dc00a602f54b8535",+ "actualExitCode": 0,+ "matched": true+ }+ ],+ "qualification": "Meaningful progression: named production families qualified; whole-language migration incomplete.",+ "geometryQualification": {+ "matched": 37,+ "witnesses": 37,+ "acceptedStepHashes": 35,+ "rejectedBeforeAndAfter": 2+ },+ "focusedTests": {+ "domainAndPlateau": {+ "passed": 60,+ "failed": 0+ },+ "cli": {+ "passed": 50,+ "failed": 0+ },+ "coreFastLane": {+ "passed": 1068,+ "failed": 0+ }+ },+ "build": {+ "configuration": "Release",+ "sdk": "net10.0",+ "errors": 0,+ "warnings": 9,+ "command": "dotnet build Aetheris.slnx -c Release -m:1 --no-restore"+ },+ "remainingAssemblyBoundary": {+ "source": "fixtures/Canonical/AssemblyInterfaces/executable-machine.firmament",+ "line": 3,+ "construct": "Role A/B requires AxisCapable",+ "sharedSyntaxCode": "firmament-syntax-declaration-tail",+ "columns": [+ 39,+ 68+ ],+ "legacyInspection": "asm inspect exit 0; shared AST reports syntax errors at both requires tokens.",+ "requiredOwnerMigration": [+ "AssemblyM0Parser.ParseInterfaces",+ "AssemblyM0Parser.ParseMates",+ "InterfaceDefinition",+ "MateSource"+ ]+ },+ "showcases": [+ {+ "command": "asm inspect",+ "source": "fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar-x0.firmament",+ "exitCode": 0+ },+ {+ "command": "asm inspect",+ "source": "fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas/atlas-industrial.firmament",+ "exitCode": 0+ },+ {+ "command": "scene inspect",+ "source": "fixtures/Canonical/Scene/WarmModernHouse/house.firmament",+ "exitCode": 0+ },+ {+ "command": "scene inspect",+ "source": "fixtures/Canonical/Scene/warehouse.firmament",+ "exitCode": 0+ },+ {+ "command": "scene inspect",+ "source": "fixtures/Canonical/Scene/FactoryX0/factory.firmament",+ "exitCode": 0+ },+ {+ "command": "asm inspect",+ "source": "fixtures/Canonical/AssemblyInterfaces/executable-machine.firmament",+ "exitCode": 0+ }+ ],+ "mechanicalQualification": {+ "unchangedStepHashes": 29,+ "validateBuildWitnessesAgreed": 4+ },+ "fullRegression": {+ "command": "dotnet test Aetheris.slnx -c Release --no-build -m:1 --settings artifacts/local/mechanical-frontend-migration/serial.runsettings -- RunConfiguration.MaxCpuCount=1",+ "xunitAssemblyParallelism": false,+ "xunitCollectionParallelism": false,+ "maxParallelThreads": 1,+ "total": 4721,+ "passed": 4721,+ "failed": 0,+ "notExecuted": 0,+ "error": 0,+ "timeout": 0,+ "aborted": 0,+ "projectResults": 21,+ "nonemptyProjects": 20+ }+}diff --git a/docs/release/FIRMAMENT-DOMAIN-FRONTEND-MIGRATION.md b/docs/release/FIRMAMENT-DOMAIN-FRONTEND-MIGRATION.mdnew file mode 100644index 00000000..804ca8bc--- /dev/null+++ b/docs/release/FIRMAMENT-DOMAIN-FRONTEND-MIGRATION.md@@ -0,0 +1,184 @@+# Firmament production domain migration++Date: 2026-10-14. Baseline: `83855e91`. This extends the+[mechanical migration](FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.md), using the+production recursive-descent AST and established engineering lowerers. It is not+a shadow qualification milestone or a claim that all remaining frontends have+been migrated.++## Production changes++Gear families and `Interface<Gear>`, Revolve and its Axis, Panel surfaces and+boundaries, Plateau, Loft, and SectionChain records now consume shared AST nodes. Unknown+fields, duplicate fields, unknown statements, malformed values and unsupported+headers fail at the owning binder. Gear and Revolve retain their bound+engineering records for build; build does not reparse them through another+domain grammar. SectionChain's bound chain can likewise execute through the+ordinary in-memory compiler. Dedicated section-chain commands retain their+inspection/export metadata and use the same AST binder.++The Panel character expression parser is removed. Its shared expression syntax+binds to the existing surface expression algebra; geometry, dimensional checking,+surface factories, tessellation and BRep emission retain their existing owners.+Named `Line S0 { ... }` objects in existing surface lists retain their identity.+Incomplete blocks retain their enclosing AST nodes for editor completion while+remaining invalid for compilation.++The legacy `Model Name mm` header now binds an implicit file body in the shared+grammar, with its original unit-token provenance. Wrapper-free Profile/Extrude+and Compose construction projects its statements into the mechanical scope+without rewriting source. The obsolete Phase3, RoundedBox,+PrimitiveConstructionPolicy and StandaloneProfile document parsers are removed.+Existing geometry lowerers and explicit V1 serialization compatibility remain.++Parser-route names (`UnifiedMechanical`, `UnifiedGear`, `UnifiedRevolve`,+`UnifiedPanel`, `UnifiedSectionChain`) are debug metadata. Structural admission+ownership, rather than a list of route strings, controls the build gate.+Generic traversal now belongs to `FirmamentSyntaxTraversal`, separate from+developer comparison/evidence tooling.++Plateau is an additive feature on an admitted extrusion. Its AST request and+bound base profile now drive execution; the ordinary base cannot execute alone+when Plateau admission fails. Existing geometry tests detect omission through+face counts and exact surface/pcurve checks. The canonical Plateau STEP hash is+unchanged. Source heuristics for unmigrated Wire/Sweep cannot reroute an admitted+mechanical object because of construct-shaped comment text; explicit schema+selection retains its authority.++## Compatibility and diagnostics++Wrapper-free Revolve retains implicit millimetres. Assembly gear definitions can+use top-level Units and repeated identical millimetre declarations. Conflicting+units fail. Existing camelCase/PascalCase field aliases bind through the same+field consumer; authored identities retain their case.++Inline SectionChain frames/profile specializations retain the existing bounded+expansion and generated names. AST spans now own its extraction boundaries. The+generated construction declarations inside the chain are bound through the+existing construction owner; they are neither rejected as unknown material nor+silently discarded. This is not an AST replacement of Template/Pattern expansion.++Gear and Revolve normal CLI validation use the common structured report and+normal engineering preflight. A semantically compatible gear train remains+inspectable, but cannot report normal single-body build admission: build requires+an Assembly for multiple gears. SectionChain validation likewise returns+structured diagnostics and explicit Built/ParsedNotBuilt metadata. Unambiguous+field tokens retain precise locations; old semantic producers without spans+receive a disclosed document anchor. Messages are preserved.++## Qualification++The durable baseline and reproduction inputs are in+[the evidence record](FIRMAMENT-DOMAIN-FRONTEND-MIGRATION.evidence.json).+Run `scripts/qualify-firmament-domain-frontend.ps1` after a serial Release build.+It checks 15 gear/revolve sources, 11 section-chain/loft sources, 10 historical+unit-header sources and one Plateau source. Thirty-five baselines produced STEP;+two were already rejected. The script checks acceptance and exact STEP SHA-256 values, and writes+detailed output only under ignored `artifacts/local/`.++Geometry qualification passed: all 37 domain/header outcomes matched, including+35 identical STEP hashes and two preserved rejections. The previous mechanical+corpus also matched all 29 STEP hashes and all four validate/build witnesses.+Sixty focused domain/Plateau checks and 50 focused CLI checks pass. Panel equation+coverage checks nine world-space points and the existing reversed boundary order+for Back orientation. Comment perturbation cases prove WireForm/Sweep/Plateau+text cannot reroute an admitted Box or change its STEP output.++Real CLI inspection passes for guitar, Industrial ATLAS, WarmModernHouse,+warehouse, FactoryX0 and executable-machine. Inspection is not a new claim of+full assembly export, interactive Helios qualification, or collision certification.+The final serial Release build completed with zero errors and nine warnings.+The fast Core lane passed 1,068 tests. The full .NET regression passed **4,721+of 4,721 tests**, with zero failed, skipped, timed out or aborted tests, across+20 nonempty projects (21 result files; FrictionLab discovers zero tests). This+includes the full slow Core corpus, all 2,278 Firmament tests and all 491 CLI+tests. Tests ran with project concurrency one and xUnit assembly/collection+parallelism disabled; no execution budgets or test exclusions were changed.+Earlier failing runs remain under ignored artifacts: specific EdgeFinish messages,+inline SectionChain construction ownership, editor recovery and Plateau omission+were repaired and exercised again through the full suite.++A clean checkout can reproduce the serial settings by writing this generated+configuration under `artifacts/local/` before the full test command:++```xml+<RunSettings>+ <RunConfiguration><MaxCpuCount>1</MaxCpuCount></RunConfiguration>+ <xUnit>+ <ParallelizeAssembly>false</ParallelizeAssembly>+ <ParallelizeTestCollections>false</ParallelizeTestCollections>+ <MaxParallelThreads>1</MaxParallelThreads>+ </xUnit>+</RunSettings>+```++Then run `dotnet test Aetheris.slnx -c Release --no-build -m:1 --settings+<saved.runsettings> -- RunConfiguration.MaxCpuCount=1`. Geometry reproduction+requires the built repository CLI DLL, not an independently installed binary.++## Code-quality review++The migrated Gear, Revolve, Panel, Plateau, Loft and SectionChain files contain no regex+parsers. No diagnostic-code fatality list, whole-document keyword dispatch,+second field schema or new global mutable parser state was introduced. Build+admission ownership is structural; debug route names do not decide execution.+Existing feature admission owns nonpositive EdgeFinish radius/distance errors,+preserving its specific engineering diagnostics during normal preflight.++Gear definition extraction is an Assembly extension point, not validation of an+entire Assembly. It consumes gear declarations and syntax diagnostics within+those spans; the enclosing Assembly owner remains responsible for its own+capability requirements and mates. Tests cover this ownership boundary, preceding+Concept definitions, model summary identity, invalid optional values, and+unchanged accepted geometry. Language-service context tests cover incomplete+Loft blocks; they do not claim interactive Helios qualification.++## Remaining production owners++| Owner | Actual remaining dependency before deletion |+| --- | --- |+| Lowercase V2 | The [next production cutover](FIRMAMENT-LOWERCASE-AST-MIGRATION.md) migrates primitive solids, Box derivation, exposure aliases and Hole modifications to AST binding. Region/cut, imported-face recognition/replacement, let/PMI/concept applications and lattice fill still retain semantic adapters. This is distinct from explicit version-1 serialization. |+| Concept / Interface / profile derivation | Existing semantic resolution and several pipeline/path/Span readers remain source-based. Migrated record boundaries do not imply these evaluators have been consolidated. |+| Template / Feature / Pattern | Existing finite specialization and expansion still produce source. Replacing them requires scoped AST substitution with identity/provenance parity, rather than removing their current owner behind an AST gate. |+| Wire / Sweep | WireForm, WireRoute, coils, knots and circular sweeps retain their existing source binders and state replay. |+| Assembly / Scene | Product containment, capability requirements, mating, published ports, appearance and spatial compilation retain their existing owners. |+| Other domains | SheetMetal, Piping, Structural, PlasticShell, Sculpting and Garment have separate semantic/compiler entry points that have not been replaced by this change. |++These routes are deliberately retained until their real consumers are migrated+and qualified. No compiler-wide completion or universal rejection guarantee is+claimed. The next cutover must carry the existing domain records and their+binding/expansion semantics into the shared AST, then remove each source reader;+a structural parse gate alone is insufficient.++The compile-time object-construction mental model is documented in the public+[overview](../public/firmament/overview.md). It does not introduce runtime+objects, inheritance, general loops or new copy/reference semantics.+++## Concrete next boundary++`fixtures/Canonical/AssemblyInterfaces/executable-machine.firmament`, line 3,+contains `Role A requires AxisCapable` and `Role B requires AxisCapable`. The+ordinary `asm inspect` exits 0, while the shared syntax parser reports `firmament-syntax-declaration-tail` at columns 39+and 68: `Unexpected 'requires' after Role A/B`. Its existing owner is+`AssemblyM0Parser.ParseInterfaces`; mate and requirement binding continues into+`InterfaceDefinition`, `MateSource` and the existing Assembly compiler.++The smallest Assembly cutover prerequisite is representation of capability+requirements and mate relations in syntax, followed by binding those nodes into+that existing IR. Merely adding a syntax gate would reject legitimate legacy+assembly source; merely adding a `requires` token without its binder would not+admit or check the requested relationship. The old Assembly parser is therefore+retained pending that migration and qualification.+++## Executive verdict++**Meaningful progression.** The named production families and four removed+compatibility routes are qualified against actual compilation and geometry.+The requested whole-language migration is **not complete**: lowercase V2,+Wire/Sweep, Assembly/Scene and the other listed domain owners remain. The+capability-role witness above identifies a specific unsupported AST/binding+boundary that prevents safe deletion of the Assembly reader. No new shadow-only+milestone or parallel validator is proposed; the remaining work is direct syntax+and binding migration into the existing engineering IR.diff --git a/docs/release/FIRMAMENT-LOWERCASE-AST-MIGRATION.evidence.json b/docs/release/FIRMAMENT-LOWERCASE-AST-MIGRATION.evidence.jsonnew file mode 100644index 00000000..3566c2d1--- /dev/null+++ b/docs/release/FIRMAMENT-LOWERCASE-AST-MIGRATION.evidence.json@@ -0,0 +1,286 @@+{+ "milestone": "Lowercase compatibility AST and spelling reconciliation",+ "baseline": "Built with the domain-migrated frontend before lowercase ownership changes on 2026-10-14",+ "geometry": [+ {+ "source": "fixtures/Regression/Primitive/valid/box-v2.valid.firmfixture",+ "command": "build",+ "artifact": "0.step",+ "expectedExitCode": 0,+ "beforeSha256": "9c6fb751251809f32a53e549750c49f4922ba796ecb8deac0daae667659cca4e"+ },+ {+ "source": "fixtures/Regression/Primitive/valid/pipeline-v2-box-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "1.step",+ "expectedExitCode": 0,+ "beforeSha256": "9c6fb751251809f32a53e549750c49f4922ba796ecb8deac0daae667659cca4e"+ },+ {+ "source": "fixtures/Regression/Primitive/valid/primitive-v2-cone-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "2.step",+ "expectedExitCode": 0,+ "beforeSha256": "5e30962b3121ced41cfb805c9bd2926fca77bda3696cac4d8e93b9377e9541d1"+ },+ {+ "source": "fixtures/Regression/Primitive/valid/primitive-v2-cylinder-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "3.step",+ "expectedExitCode": 0,+ "beforeSha256": "69107f183e38a264a998f80147eaa42689b3438658a816c508601b6b81d22781"+ },+ {+ "source": "fixtures/Regression/Primitive/valid/primitive-v2-sphere-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "4.step",+ "expectedExitCode": 0,+ "beforeSha256": "3802387cb2bea96cb74f57208f35b960218823efa0f7dfeafc720c337b26e03d"+ },+ {+ "source": "fixtures/Regression/Primitive/valid/primitive-v2-torus-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "5.step",+ "expectedExitCode": 0,+ "beforeSha256": "f2837235b0d83eaeddb69cb68deb6c80b53e70ee2d7786178a685f7dab34d9a4"+ },+ {+ "source": "fixtures/Regression/RecordDerivation/valid/box-with-size-variant-v2.valid.firmfixture",+ "command": "build",+ "artifact": "6.step",+ "expectedExitCode": 0,+ "beforeSha256": "69a07c4dd76f139722a8f3c9a4eef8f937cb2e4c949099c30de116da8b6e26cd"+ },+ {+ "source": "fixtures/Regression/RecordDerivation/valid/derivation-v2-with-chained-twice-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "7.step",+ "expectedExitCode": 0,+ "beforeSha256": "663a4e2e5f536fab6df4f7a3d64467d9c72ddf2cb883ff7eaae4ebe2f08657a1"+ },+ {+ "source": "fixtures/Regression/RecordDerivation/valid/derivation-v2-with-size-override-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "8.step",+ "expectedExitCode": 0,+ "beforeSha256": "297432bf79ec25b71fa60a631452a196a23b82b4e6e5923ce6a02d0f4debfab7"+ },+ {+ "source": "fixtures/Regression/SemanticRefs/valid/named-box-faces-v2.valid.firmfixture",+ "command": "build",+ "artifact": "9.step",+ "expectedExitCode": 0,+ "beforeSha256": "9c6fb751251809f32a53e549750c49f4922ba796ecb8deac0daae667659cca4e"+ },+ {+ "source": "fixtures/Regression/SemanticRefs/valid/semanticref-v2-expose-face-alias-resolves-in-step.valid.firmfixture",+ "command": "build",+ "artifact": "10.step",+ "expectedExitCode": 0,+ "beforeSha256": "38e9eeee4296158ecafab3dd7d9b0617a47b812aa7e9a30748f7254c80cafdab"+ },+ {+ "source": "fixtures/Regression/Composite/valid/composite-v2-adjacent-non-overlapping-holes-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "11.step",+ "expectedExitCode": 0,+ "beforeSha256": "65db9629caaed20c9ab1c266d60f9d893b205dd387bef7ae320360ac12f3a24b"+ },+ {+ "source": "fixtures/Regression/Composite/valid/composite-v2-hole-plus-derived-variant-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "12.step",+ "expectedExitCode": 0,+ "beforeSha256": "0afb5417d71b818654263e5dee21bc4131682dbf359260e09be28d5d9dba8791"+ },+ {+ "source": "fixtures/Regression/Composite/valid/composite-v2-two-independent-holes-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "13.step",+ "expectedExitCode": 0,+ "beforeSha256": "c0a8da0252d96fee313a57e4d837f2a3c8602ee71ca8a19cf3d9b3e927151cc8"+ },+ {+ "source": "fixtures/Regression/Hole/valid/feature-v2-counterbore-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "14.step",+ "expectedExitCode": 0,+ "beforeSha256": "0631e966e51bf059a6a8fc4e3b970053740efd30e50c87f82bdd6826ae752a41"+ },+ {+ "source": "fixtures/Regression/Hole/valid/feature-v2-countersink-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "15.step",+ "expectedExitCode": 0,+ "beforeSha256": "1a4a9167bb5a370348a4ae13ef71cdac9fbc83c68f5fc885268145d011b87a55"+ },+ {+ "source": "fixtures/Regression/Hole/valid/feature-v2-shaft-hole-blind-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "16.step",+ "expectedExitCode": 0,+ "beforeSha256": "b45deb18a09cfba0e4087f1ac69b4f17f61b67543ed52d89e36246b2bca20206"+ },+ {+ "source": "fixtures/Regression/Hole/valid/feature-v2-shaft-hole-through-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "17.step",+ "expectedExitCode": 0,+ "beforeSha256": "38e9eeee4296158ecafab3dd7d9b0617a47b812aa7e9a30748f7254c80cafdab"+ },+ {+ "source": "fixtures/Regression/Hole/valid/hole-x4-counterbore-through.valid.firmfixture",+ "command": "build",+ "artifact": "18.step",+ "expectedExitCode": 0,+ "beforeSha256": "c23e744dee53070cd4129d694dca3e95bb33e3b40dc41fdf7822110a2f347bf2"+ },+ {+ "source": "fixtures/Regression/Hole/valid/hole-x4-countersink-depth.valid.firmfixture",+ "command": "build",+ "artifact": "19.step",+ "expectedExitCode": 0,+ "beforeSha256": "25b00ec5f9df4ed62cdf0a01ebb5ab91bc5353f4b054db18f7b705f142aa2980"+ },+ {+ "source": "fixtures/Regression/Hole/valid/hole-x4-shaft-through.valid.firmfixture",+ "command": "build",+ "artifact": "20.step",+ "expectedExitCode": 0,+ "beforeSha256": "7adb97a6ddf065bb697a2a9903b15b20d295087a6e992687dd329e109f7e84ec"+ },+ {+ "source": "fixtures/Regression/Hole/valid/semantic-shaft-selection.firmament",+ "command": "build",+ "artifact": "21.step",+ "expectedExitCode": 0,+ "beforeSha256": "20773af900c7c88c675fcf2c6e55d8432272b84a87bc919207a5836d11d4b076"+ },+ {+ "source": "fixtures/Regression/Chamfer/valid/air-hole-entry-chamfer-variant.valid.firmament",+ "command": "build",+ "artifact": "22.step",+ "expectedExitCode": 0,+ "beforeSha256": "449ef7a6d4b8891960664a7f110fc767afd18a3c356b15654db8149f2a5a61fc"+ },+ {+ "source": "fixtures/Regression/Chamfer/valid/air-hole-entry-chamfer.valid.firmament",+ "command": "build",+ "artifact": "23.step",+ "expectedExitCode": 0,+ "beforeSha256": "cdf161f54a7745b0053f23df2d19c3bf1f3630a44adc35910ef5bd917aa4fddd"+ },+ {+ "source": "fixtures/Regression/Region/valid/feature-v2-side-hole-step-verified.valid.firmfixture",+ "command": "build",+ "artifact": "region-0.step",+ "expectedExitCode": 0,+ "beforeSha256": "a344f7f45cbefe1dd77cde2d8400c970632107179164ecee21d0cc363d04ccb3"+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-aliases-reverse-x-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-1.step",+ "expectedExitCode": 1,+ "beforeSha256": null+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-aliases-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-2.step",+ "expectedExitCode": 0,+ "beforeSha256": "09c731871d463ff98953fcea5b7eec951fa32fe5d0d3a7410555c91fc6c7fbb8"+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-aliases-y-axis-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-3.step",+ "expectedExitCode": 1,+ "beforeSha256": null+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-aliases-z-axis-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-4.step",+ "expectedExitCode": 1,+ "beforeSha256": null+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-center-y1-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-5.step",+ "expectedExitCode": 0,+ "beforeSha256": "09c731871d463ff98953fcea5b7eec951fa32fe5d0d3a7410555c91fc6c7fbb8"+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-center-y1-z1-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-6.step",+ "expectedExitCode": 0,+ "beforeSha256": "cc5933f4cfe43d488efc9f52f600b09b13864ce17526493b995910299fedcd1c"+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-center-z1-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-7.step",+ "expectedExitCode": 0,+ "beforeSha256": "37cb59539e95c5b55ba0f079b986cd56788548903affdd2e37bc52f63540a311"+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-radius-0_5-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-8.step",+ "expectedExitCode": 0,+ "beforeSha256": "12ac593c13304f95e36f2358e554dbed5126787debbdd87707d965690fc078e1"+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-radius-1_5-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-9.step",+ "expectedExitCode": 0,+ "beforeSha256": "b8b866976eeb8c8d5fbf0948cc1c5d3e86cc6ef75c20069d359b035c4d280af1"+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-reverse-x-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-10.step",+ "expectedExitCode": 1,+ "beforeSha256": null+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-reverse-y-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-11.step",+ "expectedExitCode": 1,+ "beforeSha256": null+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-reverse-z-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-12.step",+ "expectedExitCode": 1,+ "beforeSha256": null+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-13.step",+ "expectedExitCode": 0,+ "beforeSha256": "a344f7f45cbefe1dd77cde2d8400c970632107179164ecee21d0cc363d04ccb3"+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-y-axis-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-14.step",+ "expectedExitCode": 1,+ "beforeSha256": null+ },+ {+ "source": "fixtures/Regression/Region/valid/side-hole-z-axis-v2.valid.firmfixture",+ "command": "build",+ "artifact": "region-15.step",+ "expectedExitCode": 1,+ "beforeSha256": null+ }+ ]+}diff --git a/docs/release/FIRMAMENT-LOWERCASE-AST-MIGRATION.md b/docs/release/FIRMAMENT-LOWERCASE-AST-MIGRATION.mdnew file mode 100644index 00000000..ea47f2da--- /dev/null+++ b/docs/release/FIRMAMENT-LOWERCASE-AST-MIGRATION.md@@ -0,0 +1,83 @@+# Firmament lowercase AST migration and spelling reconciliation++Date: 2026-10-14. This continues the production migration described in+[FIRMAMENT-DOMAIN-FRONTEND-MIGRATION](FIRMAMENT-DOMAIN-FRONTEND-MIGRATION.md).++## Production ownership++The shared recursive-descent parser now represents historical `units mm`,+`solid name: Primitive`, Box `with` derivation and selector alias associations.+The primitive and Hole binders are shared with native mechanical source. There+is no new whole-document regex dispatch or source-rewrite pass. The obsolete+solid scanner, direct/derived primitive parsers, exposure line parser and+Modify/Hole/region/cut regex readers are removed.++`UnifiedCompatibility` identifies documents whose primitive, derivation,+exposure, Hole and region/cut scopes have AST admission. Both normal validate and build+consume their resulting engineering records; unknown statements and fields fail.+Dimensional defaults are explicitly limited to the historical millimetre context.+Native declarations retain explicit length units. Unresolved face aliases retain+the existing semantic resolver and engineering diagnostics.++`CompatibilityExtensions` identifies documents containing existing typed let,+tolerance, PMI, manufacturing/feature concepts, process Templates, imported-face+recognition/replacement, lattice fill adapters. Their primitive+and Hole inputs now bind from AST, but their remaining semantic scopes are still+source-owned. They are not claimed to have whole-document AST admission. The+old `LegacyLowercase` route name is retired; explicit V1 serialization remains+separate. No legacy semantic owner is deleted before its consumers migrate.++## Spelling decisions++New authoring uses PascalCase constructs/types, camelCase built-in fields,+lowercase linking words (`using`, `as`, `on`, `over`, `with`) and preserved+engineering symbols. User identifiers, recipe parameter labels and published+members remain case-sensitive. PascalCase field and linking aliases remain+compatible at their established vocabulary positions; arbitrary case folding+is not introduced. Uppercase `MODIFY` remains a bounded existing compatibility+alias and still rejects unsupported imported-body edits.++`as` now works in the shared expression parser, Profile pipeline binder,+convention formatter and language-service token classification. Formatting finds+alias nodes in the shared AST; it does not guess from an identifier's spelling.+Profile source adapters retain bounded `As|as` recognition while their remaining+semantic grammar is migrated. `From`/`To`, `Reverse`, `Close` and `TraceLoop` are+unchanged; this does not invent a global lowercase operator grammar.++The public [syntax reference](../public/firmament/syntax.md) now begins with the+compile-time Model/Struct/Feature/Pattern mental model, vocabulary rules and a+preferred mechanical example. Historical grammar has a distinct compatibility+section. Feature delegation examples live with Feature. Existing source is not+mass-renamed, and legacy syntax is not presented as a second preferred style.++## Diagnostic changes++Migrated scopes close their fields and statements at the actual AST owner.+Syntax diagnostics keep their shared `firmament-syntax-*` codes and original+spans rather than being renamed to match old code prefixes. In particular,+`@front:` in a Box override is a located syntax error; this previously invalid+fixture remains invalid. Corpus checks must verify actual V2 disposition and+absence of V1 fallback, not assume every error starts with `firmament-v2-`.++## Qualification++Qualification is in progress; final counts and geometry evidence are recorded+when the complete serial regression lane and CLI witnesses finish.++## Runtime resource checks++The interrupted work left no test hosts or CLI processes alive. Existing MSBuild+and compiler servers belonged to the open Visual Studio session and were left+untouched. Subsequent builds disable node reuse, MSBuild server reuse and shared+compilation. Test assemblies and collections run serially, with process/memory+snapshots between lanes. A prior one-off dotnet hostpolicy launch error did not+recur in the explicit-project retry; it is not attributed to the parser without+reproduction. No runtime memory leak has been established by these observations.++## Remaining boundary++The remaining lowercase families are the explicit compatibility extension+owners above; region/cut now binds its existing side-hole route policy from AST. Native Concept/profile+adapters, expansion, Wire/Sweep, Assembly/Scene and other domain frontends also+remain as listed in the preceding migration report. This is a production cutover+of the stated families, not whole-language migration completion.diff --git a/fixtures/Compatibility/LegacyAliases/Invalid/RecordDerivation/with-selector-target-v2.invalid.firmfixture b/fixtures/Compatibility/LegacyAliases/Invalid/RecordDerivation/with-selector-target-v2.invalid.firmfixtureindex 31125ce1..682019da 100644--- a/fixtures/Compatibility/LegacyAliases/Invalid/RecordDerivation/with-selector-target-v2.invalid.firmfixture+++ b/fixtures/Compatibility/LegacyAliases/Invalid/RecordDerivation/with-selector-target-v2.invalid.firmfixture@@ -6,7 +6,8 @@// implementation: parser-backed// expected: invalid// expected-stage: parsed-// expected-diagnostic: firmament-v2-with-requires-record+// expected-diagnostic: firmament-syntax-statement+// migration: shared AST rejects the invalid @ token at its original location.// notes: AIR-FIRMAMENT-X2 parser-backed invalid derivation fixture; selectors are not records.model WithSelectorTarget {diff --git a/fixtures/Regression/FrontendMigration/gear.firmament b/fixtures/Regression/FrontendMigration/gear.firmamentnew file mode 100644index 00000000..670d33d0--- /dev/null+++ b/fixtures/Regression/FrontendMigration/gear.firmament@@ -0,0 +1,5 @@+Model GearModel { Units: mm;+ SpurGear Drive { Module: 2mm; Teeth: 24; PressureAngle: 20deg; FaceWidth: 10mm; BoreDiameter: 8mm; Axis: [0,0,1];+ // intent+ }+}diff --git a/fixtures/Regression/FrontendMigration/incidental-domain-text.firmament b/fixtures/Regression/FrontendMigration/incidental-domain-text.firmamentnew file mode 100644index 00000000..d5fadb75--- /dev/null+++ b/fixtures/Regression/FrontendMigration/incidental-domain-text.firmament@@ -0,0 +1,5 @@+Model BoxOnly {+ Units: mm+ Box Body { Size: [10mm, 20mm, 30mm] }+}+/* $domain Ghost { */diff --git a/fixtures/Regression/FrontendMigration/legacy-unit-header.firmament b/fixtures/Regression/FrontendMigration/legacy-unit-header.firmamentnew file mode 100644index 00000000..80c0c18c--- /dev/null+++ b/fixtures/Regression/FrontendMigration/legacy-unit-header.firmament@@ -0,0 +1,3 @@+Model Old mm+Box Base { Size: [10mm,8mm,6mm] }+Modify Base { EdgeFinish E { Face: +Z; Target: Boundary; Kind: Chamfer; Distance: 1mm } }diff --git a/fixtures/Regression/FrontendMigration/lowercase-compatibility.firmament b/fixtures/Regression/FrontendMigration/lowercase-compatibility.firmamentnew file mode 100644index 00000000..d9c10d8a--- /dev/null+++ b/fixtures/Regression/FrontendMigration/lowercase-compatibility.firmament@@ -0,0 +1,16 @@+// Historical spellings retain the same engineering records and geometry.+model CompatibilityPlate {+ units mm+ solid stock: Box {+ size: [30, 24, 12]+ expose { face(+Z) as top }+ }+ modify stock {+ hole<shaft> bore {+ on: top+ center: [0, 0]+ diameter: 4+ end: throughAll+ }+ }+}diff --git a/fixtures/Regression/FrontendMigration/lowercase-ignored-fillet.firmament b/fixtures/Regression/FrontendMigration/lowercase-ignored-fillet.firmamentnew file mode 100644index 00000000..d7d0f2f7--- /dev/null+++ b/fixtures/Regression/FrontendMigration/lowercase-ignored-fillet.firmament@@ -0,0 +1,6 @@+// Must reject instead of silently omitting the requested fillet.+model IgnoredFillet {+ units mm+ solid stock: Box { size: [30, 24, 12] }+ modify stock { Fillet corners { radius: 1 } }+}diff --git a/fixtures/Regression/FrontendMigration/lowercase-unknown-field.firmament b/fixtures/Regression/FrontendMigration/lowercase-unknown-field.firmamentnew file mode 100644index 00000000..76e27fdc--- /dev/null+++ b/fixtures/Regression/FrontendMigration/lowercase-unknown-field.firmament@@ -0,0 +1,5 @@+// Must reject instead of silently building the unaffected stock.+model UnknownField {+ units mm+ solid stock: Box { size: [30, 24, 12]; heigth: 20 }+}diff --git a/fixtures/Regression/FrontendMigration/named-surface-section-syntax.firmament b/fixtures/Regression/FrontendMigration/named-surface-section-syntax.firmamentnew file mode 100644index 00000000..cba0504a--- /dev/null+++ b/fixtures/Regression/FrontendMigration/named-surface-section-syntax.firmament@@ -0,0 +1 @@+Static Sections: Any = [ Line S0 { Start: [0mm,0mm,0mm]; End: [1mm,0mm,0mm] } Line S1 { Start: [0mm,1mm,0mm]; End: [1mm,1mm,0mm] } ]diff --git a/fixtures/Regression/FrontendMigration/panel-parametric.firmament b/fixtures/Regression/FrontendMigration/panel-parametric.firmamentnew file mode 100644index 00000000..67ec07af--- /dev/null+++ b/fixtures/Regression/FrontendMigration/panel-parametric.firmament@@ -0,0 +1,15 @@+Model Equations {+ Units: mm+ Panel Saddle {+ Surface: ParametricSurface {+ DomainU: [-1, 1]+ DomainV: [-1, 1]+ X: 20mm * u+ Y: 15mm * v+ Z: 6mm * u * v+ }+ Orientation: Back+ Thickness: 1.2mm+ Material: "Aluminum"+ }+}diff --git a/fixtures/Regression/FrontendMigration/panel.firmament b/fixtures/Regression/FrontendMigration/panel.firmamentnew file mode 100644index 00000000..44c2014c--- /dev/null+++ b/fixtures/Regression/FrontendMigration/panel.firmament@@ -0,0 +1,5 @@+Model PanelModel { Units: mm;+ Panel P { Surface: HyperbolicParaboloid { Width: 40mm; Depth: 30mm; Rise: 6mm; }+ // intent+ }+}diff --git a/fixtures/Regression/FrontendMigration/preferred-profile-links.firmament b/fixtures/Regression/FrontendMigration/preferred-profile-links.firmamentnew file mode 100644index 00000000..b40c042a--- /dev/null+++ b/fixtures/Regression/FrontendMigration/preferred-profile-links.firmament@@ -0,0 +1,16 @@+Model PreferredLinks {+ units: mm+ Concept Struct layout on XY {+ Rect2 boundary { center: [0mm, 0mm]; size: [30mm, 24mm] }+ }+ Profile outline using layout {+ Loop Outer {+ boundary.Bottom as south+ |> boundary.Right as east+ |> boundary.Top as north+ |> boundary.Left as west+ |> Close+ }+ }+ Extrude stock { profile: outline; from: 0mm; to: 12mm }+}diff --git a/fixtures/Regression/FrontendMigration/revolve.firmament b/fixtures/Regression/FrontendMigration/revolve.firmamentnew file mode 100644index 00000000..971b450e--- /dev/null+++ b/fixtures/Regression/FrontendMigration/revolve.firmament@@ -0,0 +1,8 @@+Model Ring { Units: mm;+ Axis Axis { Origin: [0mm,0mm,0mm]; Direction: [0,1,0] }+ Rect2 Boundary { Center: [15mm,0mm]; Size: [10mm,20mm] }+ Profile Section { Loop Outer { Boundary |> TraceLoop } }+ Revolve Turn { Profile: Section; About: Axis; Angle: full;+ // intent+ }+}diff --git a/scripts/qualify-firmament-domain-frontend.ps1 b/scripts/qualify-firmament-domain-frontend.ps1new file mode 100644index 00000000..68e743be--- /dev/null+++ b/scripts/qualify-firmament-domain-frontend.ps1@@ -0,0 +1,37 @@+param(+ [string]$OutputDirectory = "artifacts/local/domain-frontend-migration/qualification",+ [string]$EvidenceFile = "docs/release/FIRMAMENT-DOMAIN-FRONTEND-MIGRATION.evidence.json"+)+$ErrorActionPreference = "Stop"+$repo = Split-Path $PSScriptRoot -Parent+Push-Location $repo+try {+ $evidence = Get-Content -LiteralPath $EvidenceFile -Raw | ConvertFrom-Json+ New-Item -ItemType Directory -Force -Path $OutputDirectory | Out-Null+ $records = foreach ($witness in $evidence.geometry) {+ $target = Join-Path $OutputDirectory $witness.artifact+ $arguments = @("Aetheris.CLI/bin/Release/net10.0/aetheris.dll")+ if ($witness.command -eq "section-chain") { $arguments += "section-chain" }+ $arguments += @("build", $witness.source, "--out", $target, "--json")+ & dotnet @arguments 2>&1 | Out-File -LiteralPath "$target.log" -Encoding utf8+ $exitCode = $LASTEXITCODE+ $hash = if ($exitCode -eq 0 -and (Test-Path -LiteralPath $target)) {+ (Get-FileHash -LiteralPath $target -Algorithm SHA256).Hash.ToLowerInvariant()+ } else { $null }+ [pscustomobject]@{+ source = $witness.source+ expectedExitCode = $witness.expectedExitCode+ actualExitCode = $exitCode+ beforeSha256 = $witness.beforeSha256+ afterSha256 = $hash+ matched = $exitCode -eq $witness.expectedExitCode -and $hash -eq $witness.beforeSha256+ }+ }+ ConvertTo-Json -InputObject @($records) -Depth 8 | Set-Content -LiteralPath (Join-Path $OutputDirectory "comparison.json") -Encoding utf8+ $failures = @($records | Where-Object { -not $_.matched })+ Write-Output "Domain frontend witnesses: $(@($records).Count); matched: $(@($records).Count - $failures.Count); failed: $($failures.Count)."+ if ($failures.Count -gt 0) {+ $failures | Format-Table source, expectedExitCode, actualExitCode+ throw "Frontend admission or STEP geometry changed; inspect comparison.json and the owning build log."+ }+} finally { Pop-Location }