Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Validate frontend schema directives before parsing and export
Yuechen Lib49dbd094515
diff --git a/Aetheris.CLI.Tests/FirmamentDirectiveCliTests.cs b/Aetheris.CLI.Tests/FirmamentDirectiveCliTests.csnew file mode 100644index 00000000..80ec7450--- /dev/null+++ b/Aetheris.CLI.Tests/FirmamentDirectiveCliTests.cs@@ -0,0 +1,38 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class FirmamentDirectiveCliTests+{+ [Theory]+ [InlineData("ignored-include", "firmament-v2-directive-unconsumed")]+ [InlineData("malformed-include", "firmament-v2-directive-malformed")]+ [InlineData("schema-inline-unknown", "firmament-schema-unknown")]+ [InlineData("schema-comment-unknown", "firmament-schema-unknown")]+ [InlineData("schema-inline-wire", "firmament-schema-mismatch")]+ [InlineData("schema-template-mismatch", "firmament-schema-mismatch")]+ public void ValidateBuildAndParseOnlyCannotBypassDirectives(string name, string code)+ {+ var outputPath = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../artifacts/local/firmament-directives-casing", Guid.NewGuid() + ".step"));+ var path = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures/Regression/FrontendDirectives", name + ".firmament"));+ foreach (var command in new[] { "validate", "build", "parse-only" })+ {+ var output = new StringWriter(); var error = new StringWriter();+ string[] arguments = command == "build" ? ["build", path, "--output", outputPath, "--json"]+ : ["validate", path, "--json", .. (command == "parse-only" ? new[] { "--parse-only" } : [])];+ Assert.Equal(1, CliRunner.Run(arguments, output, error));+ using var json = JsonDocument.Parse(output.ToString());+ var root = command == "build" ? json.RootElement : json.RootElement.GetProperty("firmamentV2Validation");+ var diagnostics = root.GetProperty("diagnostics").EnumerateArray().ToArray();+ Assert.Contains(diagnostics, d => d.GetProperty("code").GetString()!.StartsWith(code, StringComparison.Ordinal));+ Assert.All(diagnostics, d => Assert.Equal(JsonValueKind.Object, d.ValueKind));+ if (name != "schema-inline-wire") Assert.All(diagnostics, d =>+ {+ Assert.Equal(path, d.GetProperty("sourceFile").GetString());+ Assert.True(d.GetProperty("line").GetInt32() > 0);+ Assert.False(string.IsNullOrWhiteSpace(d.GetProperty("message").GetString()));+ });+ Assert.False(File.Exists(outputPath));+ }+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 2ffcd444..e6b968b8 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -491,6 +491,8 @@ public static class CliRunnerif (File.Exists(sourcePath)){var source = File.ReadAllText(sourcePath);+ var frontend = FirmamentFrontendSchemas.Select(source);+ if (!frontend.IsSuccess) return WriteFrontendRejection(frontend, source, sourcePath, "build", json, stdout, stderr);if (Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.HasRoot(source)){ stderr.WriteLine("garment-step-export-unsupported: Fabric is a material-space surface; use garment build or garment drape."); return 1; }if (Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(source))@@ -2355,8 +2357,11 @@ Model CanonicalPanel {return FrontendShadowCommand.Run([sourcePath, "--validate", .. (json ? new[] { "--json" } : []), .. (shadowAst ? new[] { "--ast" } : [])], stdout, stderr);}var validationSource=File.ReadAllText(sourcePath);+ var authoredValidationSource = validationSource;+ var frontend = FirmamentFrontendSchemas.Select(validationSource);+ if (!frontend.IsSuccess) return WriteFrontendRejection(frontend, validationSource, sourcePath, "validate", json, stdout, stderr);if (Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.HasRoot(validationSource)- || FirmamentFrontendSchemas.Select(validationSource).Schema == FirmamentFrontendSchema.Garment)+ || frontend.Schema == FirmamentFrontendSchema.Garment)return GarmentCommand.Run(["inspect", sourcePath, .. (json ? new[] { "--json" } : Array.Empty<string>())], stdout, stderr);if (Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(validationSource)){@@ -2366,13 +2371,6 @@ Model CanonicalPanel {else { stdout.WriteLine(scene.IsSuccess ? "Scene source valid; engineering definitions are checked by scene inspect/export." : "Scene source invalid."); foreach(var d in scene.Diagnostics) stderr.WriteLine(d.Code+": "+d.Message); }return scene.IsSuccess ? 0 : 1;}- var frontend = FirmamentFrontendSchemas.Select(validationSource);- if (!frontend.IsSuccess)- {- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = new { source = sourcePath, status = "invalid", diagnostics = frontend.Diagnostics } }, JsonOptions));- else foreach (var diagnostic in frontend.Diagnostics) stderr.WriteLine("error: " + diagnostic);- return 1;- }validationSource = frontend.Source;if (PlasticShellFirmament.LooksLikePlasticShell(validationSource)){@@ -2485,14 +2483,14 @@ Model CanonicalPanel {var parse = FirmamentV2Parser.Parse(library.Source,Path.GetDirectoryName(Path.GetFullPath(sourcePath)),- runtimeConfiguration.Catalog);+ runtimeConfiguration.Catalog, frontend.Schema);var runtimeValidation = FirmamentV2RuntimeConceptValidation.Validate(parse.Document, runtimeConfiguration);var report = FirmamentV2ValidationReportBuilder.Build(parse, sourcePath, runtimeValidation, runtimeConfiguration.Catalog, validationSource);if (parseOnly || forgePackPaths.Count > 0){if (report.Status != "invalid") report = report with { Status = "parsed-not-built" };}- else report = FirmamentBuildAdmissionValidation.Admit(report, validationSource, Path.GetDirectoryName(Path.GetFullPath(sourcePath)));+ else report = FirmamentBuildAdmissionValidation.Admit(report, authoredValidationSource, Path.GetDirectoryName(Path.GetFullPath(sourcePath)));if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = report }, JsonOptions));else stdout.WriteLine($"Firmament V2 validation: {report.Status} ({report.Summary.FatalDiagnosticCount} fatal, {report.Summary.WarningDiagnosticCount} warning)");if (!json)@@ -2504,6 +2502,19 @@ Model CanonicalPanel {return report.Status == "invalid" ? 1 : 0;}+ private static int WriteFrontendRejection(FirmamentFrontendSelection selection, string source, string path,+ string command, bool json, TextWriter stdout, TextWriter stderr)+ {+ var report = FirmamentV2ValidationReportBuilder.Build(selection.Failure(source), path);+ if (json)+ {+ if (command == "validate") stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = report }, JsonOptions));+ else stdout.WriteLine(JsonSerializer.Serialize(new { command, success = false, input = path, diagnostics = report.Diagnostics }, JsonOptions));+ }+ else foreach (var d in report.Diagnostics) stderr.WriteLine($"{path}({d.Line},{d.Column}): {d.Severity} {d.Code}: {d.Message}");+ return 1;+ }+private static FirmamentV2ForgeRuntimeConfiguration CreateValidateForgeRuntimeConfiguration(IReadOnlyList<string> forgePackPaths){if (forgePackPaths.Count == 0)diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentCompatibilityAstMigrationTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentCompatibilityAstMigrationTests.csindex 10390cf3..58f01701 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentCompatibilityAstMigrationTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentCompatibilityAstMigrationTests.cs@@ -38,10 +38,12 @@ public sealed class FirmamentCompatibilityAstMigrationTestsvar source = "model Witness { units mm " + body + " }";var parsed = FirmamentV2Parser.Parse(source);Assert.False(parsed.IsSuccess);- Assert.Equal("UnifiedCompatibility", parsed.ParserRoute);+ Assert.Equal(token == "Use" ? "UnifiedDirectives" : "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.Contains(report.Diagnostics, d => d.SourceSpan is { } span && (token == "Use"+ ? source.Substring(span.Start, span.Length) == "Use Ignored.Module" && d.Code == "firmament-v2-directive-unconsumed"+ : source.Substring(span.Start, span.Length) == token));Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentDirectiveAndCasingTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentDirectiveAndCasingTests.csnew file mode 100644index 00000000..1e4b93ec--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentDirectiveAndCasingTests.cs@@ -0,0 +1,146 @@+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentDirectiveAndCasingTests+{+ [Theory]+ [InlineData("ignored-include", "firmament-v2-directive-unconsumed")]+ [InlineData("malformed-include", "firmament-v2-directive-malformed")]+ [InlineData("schema-inline-unknown", "firmament-schema-unknown")]+ [InlineData("schema-comment-unknown", "firmament-schema-unknown")]+ [InlineData("schema-inline-wire", "firmament-schema-mismatch")]+ [InlineData("schema-template-mismatch", "firmament-schema-mismatch")]+ public void DirectiveIntentCannotDisappear(string fixture, string code)+ {+ var source = File.ReadAllText(Fixture(fixture));+ var parsed = FirmamentV2Parser.Parse(source);+ var report = FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(parsed, Fixture(fixture)), source);+ Assert.False(parsed.IsSuccess);+ Assert.Equal("invalid", report.Status);+ var build = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(Fixture(fixture)));+ Assert.False(build.IsSuccess);+ if (fixture == "schema-template-mismatch")+ {+ Assert.True(FirmamentBuildAndExport.CompileSource(source.Replace("schema WireForm", "schema Mechanical", StringComparison.Ordinal)).IsSuccess);+ var erased = FirmamentFrontendSchemas.Select(source).Source;+ Assert.True(FirmamentV2Parser.Parse(erased, null, null, FirmamentFrontendSchema.Mechanical).IsSuccess);+ Assert.False(FirmamentV2Parser.Parse(erased, null, null, FirmamentFrontendSchema.WireForm).IsSuccess);+ Assert.False(FirmamentV2Parser.Parse(source, null, null, FirmamentFrontendSchema.Mechanical).IsSuccess);+ }+ Assert.Contains(report.Diagnostics, d => d.Code.StartsWith(code, StringComparison.Ordinal));+ if (fixture.StartsWith("schema-", StringComparison.Ordinal))+ {+ var original = Assert.Single(parsed.SyntaxDiagnostics);+ var presented = FirmamentBuildAdmissionValidation.Present(Assert.Single(build.Diagnostics), Fixture(fixture), source);+ Assert.Equal(original.SourceSpan, presented.SourceSpan);+ Assert.Equal(original.Message, presented.Message);+ }+ if (fixture == "ignored-include")+ {+ var located = Assert.Single(parsed.SyntaxDiagnostics);+ Assert.Equal("include \"__missing_syntax_review__.firmament\"", source.Substring(located.SourceSpan!.Start, located.SourceSpan.Length));+ Assert.Contains(build.Diagnostics, d => d.Message.Contains("standalone part compilation", StringComparison.Ordinal));+ var marker = Assert.Single(FirmamentLanguageAnalysisService.Analyze(source, Fixture(fixture), "1").Diagnostics);+ Assert.Equal(located.SourceSpan.Start, marker.Start);+ Assert.Contains("__missing_syntax_review__.firmament", marker.Message, StringComparison.Ordinal);+ Assert.False(FirmamentV2Parser.Parse(source.Replace("include", "Include", StringComparison.Ordinal)).IsSuccess);+ }+ }++ [Fact]+ public void SchemaCommentsAndInlineSpacingPreserveGeometryAndOffsets()+ {+ var source = File.ReadAllText(Fixture("schema-block-comment")).Replace("\r\n", "\n", StringComparison.Ordinal);+ var selection = FirmamentFrontendSchemas.Select(source);+ Assert.True(selection.IsSuccess);+ Assert.Equal(source.Length, selection.Source.Length);+ Assert.Equal(source.IndexOf("Box", StringComparison.Ordinal), selection.Source.IndexOf("Box", StringComparison.Ordinal));+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join(";", built.Diagnostics));+ var inline = source.Replace("schema Mechanical // a trailing comment is also trivia\n", "schema Mechanical ", StringComparison.Ordinal);+ Assert.Equal(built.Value.StepText, FirmamentBuildAndExport.CompileSource(inline).Value.StepText);+ Assert.Equal(built.Value.StepText, FirmamentBuildAndExport.CompileSource(selection.Source).Value.StepText);+ }++ [Theory]+ [InlineData("mirrored-hole")]+ [InlineData("mirrored-feature-with-override")]+ [InlineData("mirrored-profile")]+ [InlineData("mirrored-revolve")]+ [InlineData("radial-bolt-circle")]+ [InlineData("partial-radial-pattern")]+ public void SymmetryUsesAstAliasesWithoutChangingStepOrIdentities(string name)+ {+ var source = File.ReadAllText(Canonical("Symmetry/" + name));+ var preferred = FirmamentSourceSpelling.Prefer(source);+ Assert.Equal(preferred, FirmamentSourceSpelling.Prefer(preferred));+ Assert.True(FirmamentSyntaxParser.Parse(preferred).IsSuccess);+ var directDiagnostics = new List<string>();+ Assert.NotNull(SemanticSymmetryAuthoring.Expand(preferred, directDiagnostics));+ Assert.Empty(directDiagnostics);+ var before = FirmamentV2Parser.Parse(source); var after = FirmamentV2Parser.Parse(preferred);+ Assert.True(after.IsSuccess, string.Join(";", after.Diagnostics));+ Assert.Equal(before.Document!.ModelName, after.Document!.ModelName);+ Assert.Equal((before.Document.StaticAuthoring?.Mirrors ?? []).Select(m => (m.Destination, m.Source)), (after.Document.StaticAuthoring?.Mirrors ?? []).Select(m => (m.Destination, m.Source)));+ Assert.Equal(FirmamentBuildAndExport.CompileSource(source).Value.StepText, FirmamentBuildAndExport.CompileSource(preferred).Value.StepText);+ Assert.DoesNotContain("Across:", preferred);+ Assert.DoesNotContain("Count:", preferred);+ }++ [Fact]+ public void DenseSeedFieldsAndCamelCaseOverrideRetainAllRequestedGeometry()+ {+ var source = File.ReadAllText(Canonical("Symmetry/mirrored-feature-with-override"));+ var dense = source.Replace(";", "", StringComparison.Ordinal).Replace("From LeftMount", "from LeftMount", StringComparison.Ordinal)+ .Replace("Diameter: 8mm", "diameter: 8mm", StringComparison.Ordinal);+ var baseline = FirmamentBuildAndExport.CompileSource(source);+ var changed = FirmamentBuildAndExport.CompileSource(dense);+ Assert.True(changed.IsSuccess, string.Join(";", changed.Diagnostics));+ Assert.Equal(baseline.Value.StepText, changed.Value.StepText);+ var holes = FirmamentV2Parser.Parse(dense).Document!.ModifyBlocks!.Single().SemanticHoles;+ Assert.Equal(2, holes.Count);+ Assert.Contains(holes, h => h.Name == "RightMountCustom" && h.ShaftDiameter == 8);+ }++ [Theory]+ [InlineData("Across: CenterPlane", "acros: CenterPlane", "acros")]+ [InlineData("Across: CenterPlane", "Across: CenterPlane; across: CenterPlane", "field-duplicate")]+ [InlineData("Normal: [1,0,0]", "Normal: [1,0,0]; typo: 3", "typo")]+ public void AstSymmetryClosesItsConsumedScopes(string oldText, string newText, string code)+ {+ var source = File.ReadAllText(Canonical("Symmetry/mirrored-hole")).Replace(oldText, newText, StringComparison.Ordinal);+ Assert.False(FirmamentV2Parser.Parse(source).IsSuccess);+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);+ Assert.Contains(FirmamentV2Parser.Parse(source).Diagnostics, d => d.Contains(code, StringComparison.Ordinal));+ }++ [Fact]+ public void EndpointLinksAreAstBoundAndPreservePublishedNames()+ {+ var source = File.ReadAllText(Canonical("Revolve/sphere"));+ var preferred = FirmamentSourceSpelling.Prefer(source);+ Assert.Contains("Meridian from South to North as Arc", preferred);+ Assert.Contains("Line2 Diameter { from: North; to: South }", preferred);+ var before = FirmamentBuildAndExport.CompileSource(source); var after = FirmamentBuildAndExport.CompileSource(preferred);+ Assert.True(after.IsSuccess, string.Join(";", after.Diagnostics));+ Assert.Equal(before.Value.StepText, after.Value.StepText);+ var profile = ProfileAuthoringParser.ResolveNamedProfile(preferred, "SphereSection", out var diagnostics);+ Assert.NotNull(profile);+ Assert.Empty(diagnostics);+ Assert.Equal(new[] { "Arc", "AxisClosure" }, profile!.Loops.Single().Segments.Select(s => s.Name));+ const string authored = "Static from: String = \"From To Across\"; Static spec: Spec { From: 1 To: 2 }";+ Assert.True(FirmamentSyntaxParser.Parse(authored).IsSuccess);+ Assert.Equal(authored, FirmamentSourceSpelling.Prefer(authored));+ var namedFrom = File.ReadAllText(Fixture("schema-block-comment")).Replace("stock", "from", StringComparison.Ordinal);+ Assert.True(FirmamentBuildAndExport.CompileSource(namedFrom).IsSuccess);+ Assert.Equal("from", FirmamentV2Parser.Parse(namedFrom).Document!.Solids.Single().Name);+ var profileNamedFrom = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/FrontendMigration/preferred-profile-links.firmament"))+ .Replace("outline", "from", StringComparison.Ordinal);+ Assert.True(FirmamentBuildAndExport.CompileSource(profileNamedFrom).IsSuccess);+ }++ private static string Fixture(string name) => FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/FrontendDirectives/" + name + ".firmament");+ private static string Canonical(string name) => FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/" + name + ".firmament");+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendSchemaTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendSchemaTests.csindex e6d4b74a..969a653d 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendSchemaTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendSchemaTests.cs@@ -33,4 +33,19 @@ public sealed class FirmamentFrontendSchemaTestsAssert.True(selection.IsSuccess);Assert.False(selection.IsExplicit);}++ [Theory]+ [InlineData("schema ;", "firmament-schema-malformed")]+ [InlineData("schema \"Mechanical\"", "firmament-schema-malformed")]+ [InlineData("schema Mechanical\nschema Mechanical", "firmament-schema-duplicate")]+ [InlineData("Model X { schema Mechanical }", "firmament-schema-late")]+ [InlineData("Model X { schema ; }", "firmament-schema-malformed")]+ [InlineData("schema Sweep\nFeature MissingResult() { }", "firmament-feature-schema-unsupported")]+ public void DirectivesHaveStructuralPlacementAndValueRules(string source, string code)+ {+ var selected = FirmamentFrontendSchemas.Select(source);+ Assert.False(selected.IsSuccess);+ Assert.Contains(selected.Diagnostics, d => d.StartsWith(code, StringComparison.Ordinal));+ Assert.All(selected.LocatedDiagnostics, d => Assert.NotNull(d.SourceSpan));+ }}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 5f0516b7..66271c9e 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -43,7 +43,7 @@ public static class FirmamentBuildAndExportvar fullSourcePath = Path.GetFullPath(sourcePath);var sourceText = NormalizeLf(File.ReadAllText(fullSourcePath, Encoding.UTF8));var frontend = FirmamentFrontendSchemas.Select(sourceText);- if (!frontend.IsSuccess) return KernelResult<FirmamentBuildAndExportResult>.Failure(frontend.Diagnostics.Select(SchemaDiagnostic).ToArray());+ if (!frontend.IsSuccess) return KernelResult<FirmamentBuildAndExportResult>.Failure(frontend.LocatedDiagnostics.Select(d => SchemaDiagnostic(d.Code + ": " + d.Message)).ToArray());sourceText = frontend.Source;if (PipingAuthoring.IsPipingSource(sourceText)){@@ -127,7 +127,7 @@ public static class FirmamentBuildAndExportArgumentNullException.ThrowIfNull(sourceText);var normalized = NormalizeLf(sourceText);var frontend = FirmamentFrontendSchemas.Select(normalized);- if (!frontend.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(frontend.Diagnostics.Select(SchemaDiagnostic).ToArray());+ if (!frontend.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(frontend.LocatedDiagnostics.Select(d => SchemaDiagnostic(d.Code + ": " + d.Message)).ToArray());normalized = frontend.Source;if (PipingAuthoring.IsPipingSource(normalized)){@@ -273,7 +273,7 @@ public static class FirmamentBuildAndExport// 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);+ var v2Parse = FirmamentV2Parser.Parse(sourceText, sourceDirectory, null, explicitSchema);canonicalParseWatch.Stop();var templateBindWatch = new System.Diagnostics.Stopwatch();string materializerSource;@@ -324,6 +324,8 @@ public static class FirmamentBuildAndExportvar materializerInput = staticExpansion.Source;materializerSource = FirmamentV2Parser.TryGetCanonicalAdvancedBody(materializerInput, out var canonicalBody) ? canonicalBody : materializerInput;}+ if (explicitSchema is { } declaredSchema && FirmamentFrontendSchemas.DomainMismatch(declaredSchema, materializerSource, admittedSchema: v2Parse.BoundSchema) is { } mismatch)+ return KernelResult<FirmamentStepExportResult>.Failure([SchemaDiagnostic(mismatch.Code + ": " + mismatch.Message)]);if (v2Parse.BoundSectionChain?.Chain is { } chain){var materialized = Aetheris.Surfacing.SectionChainMaterializer.Materialize(chain);diff --git a/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs b/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.csindex d5825239..7b3f5d02 100644--- a/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs+++ b/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs@@ -1,5 +1,5 @@-using System.Text.RegularExpressions;using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.Firmament.Materializer;namespace Aetheris.Kernel.Firmament;@@ -10,38 +10,76 @@ public enum FirmamentFrontendSchema { Mechanical, WireForm, Sweep, SectionChain,public sealed record FirmamentFrontendSelection(FirmamentFrontendSchema? Schema, string Source, IReadOnlyList<string> Diagnostics){+ public IReadOnlyList<FirmamentV2ValidationDiagnostic> LocatedDiagnostics { get; init; } = [];+ public FirmamentV2SourceSpan? DirectiveSpan { get; init; }public bool IsExplicit => Schema is not null;public bool IsSuccess => Diagnostics.Count == 0;+ public FirmamentV2ParseResult Failure(string originalSource) => FirmamentV2ParseResult.Failure(Diagnostics) with+ {+ OriginalSource = originalSource, SyntaxDiagnostics = LocatedDiagnostics, ParserRoute = "UnifiedDirectives", OwnsUnifiedAdmission = true+ };}public static class FirmamentFrontendSchemas{- private static readonly Regex Declaration = new(@"(?m)^\s*schema\s+(?<name>[A-Za-z_]\w*)\s*;?\s*$", RegexOptions.CultureInvariant);public static readonly IReadOnlyList<string> Names = ["Mechanical", "WireForm", "Sweep", "SectionChain", "Garment"];public static FirmamentFrontendSelection Select(string source){ArgumentNullException.ThrowIfNull(source);- var declarations = Declaration.Matches(source).Cast<Match>().ToArray();+ if (!source.Contains("schema", StringComparison.Ordinal)) return new(null, source, []);+ var syntax = FirmamentSyntaxParser.Parse(source);+ if (syntax.Diagnostics.FirstOrDefault(d => d.Code == "firmament-schema-malformed") is { SourceSpan: { } malformedSpan } malformed)+ return Reject(malformed.Code, malformed.Message, malformedSpan);+ var declarations = FirmamentSyntaxTraversal.Statements(syntax.Document).OfType<DirectiveSyntax>()+ .Where(d => d.Kind == DirectiveKind.Schema).ToArray();if (declarations.Length == 0) return new(null, source, []);- if (declarations.Length != 1) return new(null, source, ["firmament-schema-duplicate"]);+ if (declarations.Length != 1) return Reject("firmament-schema-duplicate", "Declare exactly one frontend schema.", declarations[1].Span);var declaration = declarations[0];- var prefix = source[..declaration.Index];- if (prefix.Split(['\r', '\n']).Any(line => { var text = line.Trim(); return text.Length > 0 && !text.StartsWith("//", StringComparison.Ordinal) && !text.StartsWith('#'); }))- return new(null, source, ["firmament-schema-late"]);- var name = declaration.Groups["name"].Value;+ var first = syntax.Document.Tokens.First(t => t.Kind is not (SyntaxTokenKind.Comment or SyntaxTokenKind.Whitespace));+ if (!ReferenceEquals(syntax.Document.Statements.FirstOrDefault(), declaration) || first.Span.Start != declaration.Span.Start)+ return Reject("firmament-schema-late", "Place the schema before all declarations and directives.", declaration.Span);+ if (declaration.Value is not ReferenceSyntax reference)+ return Reject("firmament-schema-malformed", "A schema name must be an unqualified frontend identifier.", declaration.Value.Span);+ var name = reference.Name.Text;if (!Enum.TryParse<FirmamentFrontendSchema>(name, false, out var schema))- return new(null, source, [$"firmament-schema-unknown:{name}:available={string.Join(',', Names)}"]);+ return Reject($"firmament-schema-unknown:{name}:available={string.Join(',', Names)}", $"Unknown schema '{name}'. Available schemas: {string.Join(", ", Names)}.", reference.Span);// Erase the selector without moving author-source diagnostic offsets.- var erased = new string(declaration.Value.Select(character => character is '\r' or '\n' ? character : ' ').ToArray());- var normalized = source.Remove(declaration.Index, declaration.Length).Insert(declaration.Index, erased);+ var span = declaration.Span;+ var erased = new string(source.AsSpan(span.Start, span.Length).ToArray().Select(character => character is '\r' or '\n' ? character : ' ').ToArray());+ var normalized = source.Remove(span.Start, span.Length).Insert(span.Start, erased);+ if (DomainMismatch(schema, normalized, syntax.Document) is { } mismatch)+ return Reject(mismatch.Code, mismatch.Message, declaration.Span, schema);+ return new(schema, normalized, []) { DirectiveSpan = declaration.Span };++ FirmamentFrontendSelection Reject(string code, string message, FirmamentV2SourceSpan location, FirmamentFrontendSchema? selectedSchema = null) =>+ new(selectedSchema, source, [code]) { LocatedDiagnostics = [Located(source, code, message, location)] };+ }++ // Specialization cannot introduce a material owner outside the selected frontend.+ internal static FirmamentV2ValidationDiagnostic? DomainMismatch(FirmamentFrontendSchema schema, string source,+ DocumentSyntax? syntax = null, FirmamentFrontendSchema? admittedSchema = null)+ {+ if (admittedSchema is { } bound)+ return bound != schema ? new($"firmament-schema-mismatch:declared={schema}:source={bound}", "fatal", $"Schema {schema} cannot compile a {bound} document.") : null;+ syntax ??= FirmamentSyntaxParser.Parse(source).Document;if (schema != FirmamentFrontendSchema.Mechanical && schema != FirmamentFrontendSchema.Garment- && Regex.IsMatch(normalized, @"\bFeature\s+[A-Za-z_]\w*\s*\(", RegexOptions.CultureInvariant))- return new(schema, normalized, [$"firmament-feature-schema-unsupported:{schema}"]);- var detected = DetectDistinctFrontend(normalized);- if (detected is not null && detected != schema)- return new(schema, normalized, [$"firmament-schema-mismatch:declared={schema}:source={detected}"]);- return new(schema, normalized, []);+ && FirmamentSyntaxTraversal.Declarations(syntax).Any(d => d.Type.Name.Text == "Feature"))+ return new($"firmament-feature-schema-unsupported:{schema}", "fatal", $"Feature recipes are not supported by schema {schema}.");+ var detected = DetectDistinctFrontend(source);+ if (detected is null && FirmamentV2Parser.MechanicalDeclarations(syntax.Statements)+ .Any(d => FirmamentV2Parser.IsPrimitiveDeclaration(d) || d.Type.Name.Text is "Compose" or "Extrude" or "Revolve" || Enum.TryParse<GearFamily>(d.Type.Name.Text, out _)))+ detected = FirmamentFrontendSchema.Mechanical;+ return detected is not null && detected != schema+ ? new($"firmament-schema-mismatch:declared={schema}:source={detected}", "fatal", $"Schema {schema} cannot compile a {detected} document.") : null;+ }++ internal static FirmamentV2ValidationDiagnostic Located(string source, string code, string message, FirmamentV2SourceSpan span)+ {+ var prefix = source.AsSpan(0, span.Start);+ var line = 1; var column = 1;+ foreach (var character in prefix) { if (character == '\n') { line++; column = 1; } else column++; }+ return new(code, "fatal", message, Target: "document directive") { SourceSpan = span, Line = line, Column = column, Stage = "frontend admission" };}private static FirmamentFrontendSchema? DetectDistinctFrontend(string source) =>diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.csindex 35992499..965f30b8 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs@@ -352,6 +352,7 @@ internal static class ConceptIrResolver/// <summary>Resolves a compile-time Concept plane for a Construction Plane trace without materializing a BRep feature.</summary>public static bool TryResolvePlane(string source, string reference, out ConceptIrPlaneValue? plane, out string? diagnostic){+ source = FirmamentSourceSpelling.Normalize(source);plane = null; diagnostic = null;var match = Regex.Match(reference, @"^(?<instance>[A-Za-z_][A-Za-z0-9_]*)\.(?<member>[A-Za-z_][A-Za-z0-9_]*)$", RegexOptions.CultureInvariant);if (!match.Success) { diagnostic = "ConstructionPlaneTraceMissing: Trace must name ConceptStruct.Plane"; return false; }diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.csindex 8cf235cd..1ab50ceb 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs@@ -34,6 +34,11 @@ public static class FirmamentBuildAdmissionValidation? diagnostic.Message[..separator]: diagnostic.Message.All(character => char.IsLetterOrDigit(character) || character is '-' or '_' or '.')? diagnostic.Message : diagnostic.Code.ToString();+ if (source is not null && (code.StartsWith("firmament-schema-", StringComparison.Ordinal) || code.StartsWith("firmament-v2-directive-", StringComparison.Ordinal)))+ {+ var original = FirmamentV2Parser.Parse(source).SyntaxDiagnostics.FirstOrDefault(d => d.Code == code || d.Code.StartsWith(code + ":", StringComparison.Ordinal));+ if (original is not null) return original with { SourceFile = sourceFile };+ }if (source is not null && code.StartsWith("firmament-syntax-", StringComparison.Ordinal)){var candidates = Syntax.FirmamentSyntaxParser.Parse(source, sourceFile).Diagnostics.Where(d => d.Code == code).ToArray();diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.csindex f62c666a..14044314 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs@@ -46,7 +46,8 @@ public static class FirmamentLanguageAnalysisService}// Imported authoring modules need project context. Do not feed them into// the unrelated concrete-part parser and manufacture syntax errors.- if (lexemes.Any(t => t.Text == "Include" && t.Shape == "identifier"))+ if (lexemes.Any(t => t.Text == "Include" && t.Shape == "identifier")+ && !Syntax.FirmamentSyntaxParser.Parse(source).Document.Statements.OfType<Syntax.DeclarationSyntax>().Any(d => d.Type.Name.Text is "Model" or "model"))return new(document, revision, tokens, [new("information", "firmament-language-project-context-required", "Imported declarations require project-aware analysis.", 0, 0)]);if (HasAssemblyRoot(source)){@@ -69,7 +70,9 @@ public static class FirmamentLanguageAnalysisServicevar failures = parse.Diagnostics.Where(item => FirmamentV2Parser.IsFatalDiagnosticCode(item) ||item == "firmament-v2-parse-failed").Distinct(StringComparer.Ordinal).ToArray();if (failures.Length > 1) failures = failures.Where(item => item != "firmament-v2-parse-failed").ToArray();- var diagnostics = failures.Select(item => LocateDiagnostic(source, lexemes, item)).ToArray();+ var diagnostics = failures.Select(item => parse.SyntaxDiagnostics.FirstOrDefault(d => d.Code == item) is { SourceSpan: { } span } located+ ? new FirmamentLanguageDiagnostic("error", located.Code, located.Message, span.Start, span.Length)+ : LocateDiagnostic(source, lexemes, item)).ToArray();return new(document, revision, tokens, diagnostics);}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.csindex 3e881bf6..d6639b49 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs@@ -14,7 +14,7 @@ public static class FirmamentSourceSpellingprivate static readonly Dictionary<string, string> Links = new(StringComparer.Ordinal){["As"] = "as", ["Using"] = "using", ["On"] = "on", ["Over"] = "over",- ["Include"] = "include", ["Expose"] = "expose", ["Bind"] = "bind"+ ["Include"] = "include", ["Expose"] = "expose", ["Bind"] = "bind", ["From"] = "from", ["To"] = "to"};public static string PreferredField(string name) => name.Length == 0 ? name : char.ToLowerInvariant(name[0]) + name[1..];@@ -25,6 +25,27 @@ public static class FirmamentSourceSpelling{ArgumentNullException.ThrowIfNull(source);var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(t => t.Shape != "comment").ToArray();+ var syntax = FirmamentSyntaxParser.Parse(source).Document;+ var endpointPositions = new Dictionary<int, string>();+ foreach (var trace in FirmamentSyntaxTraversal.Expressions(syntax).OfType<TraceSyntax>())+ {+ Endpoint(trace.From, "From"); Endpoint(trace.To, "To");+ void Endpoint(ExpressionSyntax? endpoint, string canonical)+ {+ if (endpoint is null) return;+ var token = tokens.LastOrDefault(t => t.Start >= trace.Source.Span.Start + trace.Source.Span.Length && t.Start < endpoint.Span.Start+ && (t.Text == canonical || t.Text == Links[canonical]));+ if (token is not null) endpointPositions[token.Start] = canonical;+ }+ }+ var symmetryFields = new Dictionary<int, string>();+ foreach (var declaration in FirmamentSyntaxTraversal.Declarations(syntax))+ {+ foreach (var clause in declaration.Clauses.Where(c => c.Kind == ClauseKind.From)) endpointPositions[clause.Span.Start] = "From";+ foreach (var field in declaration.Body?.Statements.OfType<FieldSyntax>() ?? [])+ if (SemanticSymmetryAuthoring.FieldsFor(declaration).FirstOrDefault(name => FirmamentSyntaxFields.SameField(field.Name.Text, name)) is { } canonical)+ symmetryFields[field.Name.Span.Start] = canonical;+ }var aliasPositions = tokens.Any(t => t.Text is "As" or "as") ? FirmamentSyntaxTraversal.Expressions(FirmamentSyntaxParser.Parse(source).Document).OfType<AliasSyntax>()@@ -79,7 +100,9 @@ public static class FirmamentSourceSpellingif (t.Shape != "identifier" || scopes.Any(s => s.AuthoredData)) continue;var fieldPosition = i + 1 < tokens.Length && tokens[i + 1].Text == ":";string? canonical = null;- if (fieldPosition && scopes.TryPeek(out var scope) && parentheses == scope.Parentheses && angles == scope.Angles+ if (fieldPosition && symmetryFields.TryGetValue(t.Start, out var symmetryField)) canonical = symmetryField;+ else if (!fieldPosition && endpointPositions.TryGetValue(t.Start, out var endpointWord)) canonical = endpointWord;+ else if (fieldPosition && scopes.TryPeek(out var scope) && parentheses == scope.Parentheses && angles == scope.Angles&& Fields.TryGetValue(scope.Owner, out var fields))canonical = fields.FirstOrDefault(f => t.Text == f || t.Text == PreferredField(f));else if (!fieldPosition && (i == 0 || tokens[i - 1].Text != "."))diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex b224510b..8fdf5294 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -333,6 +333,8 @@ public sealed record FirmamentV2ParseResult(internal ResolvedProfile2D? BoundProfile { get; init; }internal double ExtrusionHeight { get; init; }internal string? BoundSource { get; init; }+ // Set by the engineering binder, never inferred from debug parser-route names.+ internal FirmamentFrontendSchema? BoundSchema { get; init; }public static FirmamentV2ParseResult Success(FirmamentV2Document document, IReadOnlyList<string> diagnostics) => new(true, document, diagnostics, FirmamentV2ParseDisposition.RecognizedValid);public static FirmamentV2ParseResult Failure(IReadOnlyList<string> diagnostics, FirmamentV2ParseDisposition disposition = FirmamentV2ParseDisposition.RecognizedInvalid) => new(false, null, diagnostics, disposition);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.csindex be57a444..2f81735e 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs@@ -16,7 +16,7 @@ public static partial class FirmamentV2Parser}}- private static bool IsPrimitiveDeclaration(DeclarationSyntax d) => d.Type.Name.Text is+ internal static bool IsPrimitiveDeclaration(DeclarationSyntax d) => d.Type.Name.Text is"Box" or "Cylinder" or "Cone" or "Sphere" or "Torus" or "RoundedBox" or "Frustum" or "StandardPart" or "ExactCoaxialPart";/// <summary>Mechanical syntax has one owner. Selection of a material lowerer@@ -358,7 +358,11 @@ public static partial class FirmamentV2Parser{foreach (var statement in statements){- if (statement is DirectiveSyntax) continue;+ if (statement is DirectiveSyntax directive)+ {+ diagnostics.Add($"firmament-v2-directive-unconsumed:{directive.Kind}: Every directive must be consumed before mechanical binding.");+ continue;+ }if (statement is DeclarationSyntax definition && definition.Modifiers.Any(m => m.Name.Text == "Template")) continue;if (statement is FieldSyntax field){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex c5d19724..eb5097cb 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -286,6 +286,12 @@ public static partial class FirmamentV2Parserstring sourceText,string? sourceDirectory,FirmamentV2ForgeConceptCatalog? conceptCatalog)+ => Parse(sourceText, sourceDirectory, conceptCatalog, null);++ /// <summary>Carries a selected schema through library/specialization processing;+ /// it cannot override a conflicting authored schema.</summary>+ public static FirmamentV2ParseResult Parse(string sourceText, string? sourceDirectory,+ FirmamentV2ForgeConceptCatalog? conceptCatalog, FirmamentFrontendSchema? expectedSchema){using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("firmament.v2-parse");ArgumentNullException.ThrowIfNull(sourceText);@@ -294,8 +300,8 @@ public static partial class FirmamentV2Parser// immutable records, except InlineStep, which reads a STEP file; those, and parses with a// concept catalog, always run.if (conceptCatalog is not null || sourceText.Contains("InlineStep", StringComparison.OrdinalIgnoreCase))- return CompleteAdmission(ParseUncached(sourceText, sourceDirectory, conceptCatalog), sourceText);- var key = (sourceDirectory ?? string.Empty) + "\0" + sourceText;+ return ParseWithDirectives(sourceText, sourceDirectory, conceptCatalog, expectedSchema);+ var key = expectedSchema + "\0" + (sourceDirectory ?? string.Empty) + "\0" + sourceText;lock (RecentParses){var index = RecentParses.FindIndex(entry => string.Equals(entry.Key, key, StringComparison.Ordinal));@@ -307,7 +313,7 @@ public static partial class FirmamentV2Parserreturn hit.Result;}}- var result = CompleteAdmission(ParseUncached(sourceText, sourceDirectory, conceptCatalog), sourceText);+ var result = ParseWithDirectives(sourceText, sourceDirectory, conceptCatalog, expectedSchema);lock (RecentParses){RecentParses.Add((key, result));@@ -319,8 +325,40 @@ public static partial class FirmamentV2Parserprivate const int RecentParseCapacity = 8;private static readonly List<(string Key, FirmamentV2ParseResult Result)> RecentParses = [];+ private static FirmamentV2ParseResult ParseWithDirectives(string source, string? directory, FirmamentV2ForgeConceptCatalog? catalog,+ FirmamentFrontendSchema? expectedSchema)+ {+ var frontend = FirmamentFrontendSchemas.Select(source);+ if (!frontend.IsSuccess) return frontend.Failure(source);+ if (frontend.Schema is { } authored && expectedSchema is { } expected && authored != expected)+ return FirmamentV2ParseResult.Failure(["firmament-schema-context-conflict"]) with { OriginalSource = source,+ SyntaxDiagnostics = [FirmamentFrontendSchemas.Located(source, "firmament-schema-context-conflict", $"The authored schema {authored} conflicts with the caller's {expected} compilation context.", frontend.DirectiveSpan!)],+ ParserRoute = "UnifiedDirectives", OwnsUnifiedAdmission = true };+ var syntax = FirmamentSyntaxParser.Parse(frontend.Source);+ var pending = FirmamentSyntaxTraversal.Statements(syntax.Document).OfType<DirectiveSyntax>()+ .Where(d => !syntax.Document.Statements.Contains(d) || !ProfileModificationTemplateLibrary.IsImport(d)).ToArray();+ var malformed = syntax.Diagnostics.Where(d => d.Code == "firmament-v2-directive-malformed").ToArray();+ if (pending.Length > 0 || malformed.Length > 0)+ {+ var reported = pending.Select(d => FirmamentFrontendSchemas.Located(source,+ "firmament-v2-directive-unconsumed", $"The {d.Kind.ToString().ToLowerInvariant()} directive '{FirmamentSyntaxValues.Reference(d.Value) ?? source.Substring(d.Value.Span.Start, d.Value.Span.Length)}' is not supported by standalone part compilation. Resolve file includes through the documented Assembly/project loader, or use the registered owner of a shipped library import.", d.Span)).Concat(malformed).ToArray();+ return FirmamentV2ParseResult.Failure(reported.Select(d => d.Code).ToArray()) with+ { OriginalSource = source, SyntaxDiagnostics = reported, ParserRoute = "UnifiedDirectives", OwnsUnifiedAdmission = true };+ }+ var parsed = ParseUncached(frontend.Source, directory, catalog);+ if (parsed.IsSuccess && (frontend.Schema ?? expectedSchema) is { } schema+ && FirmamentFrontendSchemas.DomainMismatch(schema, parsed.BoundSource ?? frontend.Source, admittedSchema: parsed.BoundSchema) is { } mismatch)+ return (frontend with { Diagnostics = [mismatch.Code], LocatedDiagnostics =+ [frontend.DirectiveSpan is { } span ? FirmamentFrontendSchemas.Located(source, mismatch.Code, mismatch.Message, span)+ : mismatch with { LocationNote = "The schema was supplied by the caller; its original header span is unavailable." }] }).Failure(source);+ return CompleteAdmission(parsed, source);+ }+private static FirmamentV2ParseResult CompleteAdmission(FirmamentV2ParseResult result, string originalSource){+ if (result.IsSuccess && result.OwnsUnifiedAdmission && result.BoundSchema is null)+ result = result with { IsSuccess = false, Disposition = FirmamentV2ParseDisposition.RecognizedInvalid,+ Diagnostics = [.. result.Diagnostics, "firmament-v2-admission-domain-missing: The engineering binder did not identify its admitted frontend schema."] };if (result.SyntaxDiagnostics.Count > 0){var original = FirmamentSyntaxParser.Parse(originalSource);@@ -365,7 +403,7 @@ public static partial class FirmamentV2Parser?? 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 }+ with { ParserRoute = "UnifiedSectionChain", OwnsUnifiedAdmission = true, BoundSchema = FirmamentFrontendSchema.SectionChain, BoundSectionChain = section, BoundSource = source }: FirmamentV2ParseResult.Failure(diagnostics.Append("firmament-v2-parse-failed").ToArray())with { ParserRoute = "UnifiedSectionChain", OwnsUnifiedAdmission = true, SyntaxDiagnostics = authoredSyntax.Diagnostics };}@@ -446,7 +484,7 @@ public static partial class FirmamentV2Parserdiagnostics.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 }+ with { ParserRoute = "UnifiedGear", OwnsUnifiedAdmission = true, BoundSchema = FirmamentFrontendSchema.Mechanical, BoundGear = gear, BoundSource = source, SyntaxDiagnostics = syntax.Diagnostics }: FirmamentV2ParseResult.Failure(diagnostics.Append("firmament-v2-parse-failed").ToArray())with { ParserRoute = "UnifiedGear", OwnsUnifiedAdmission = true, SyntaxDiagnostics = syntax.Diagnostics };}@@ -463,7 +501,7 @@ public static partial class FirmamentV2ParserFeatureDefinitions: 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 = "UnifiedPanel", OwnsUnifiedAdmission = true, BoundSource = source };+ with { ParserRoute = "UnifiedPanel", OwnsUnifiedAdmission = true, BoundSchema = FirmamentFrontendSchema.Mechanical, BoundSource = source };}// Canonical V2 is parsed as one document, before compatibility adapters. The@@ -499,7 +537,7 @@ public static partial class FirmamentV2Parserif (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 };+ with { ParserRoute = "UnifiedRevolve", OwnsUnifiedAdmission = true, BoundSchema = FirmamentFrontendSchema.Mechanical, BoundRevolve = revolve, BoundSource = source };}if (modelSyntax is not null && (hasMechanicalMaterial || !dedicatedMaterialDomain)){@@ -519,7 +557,7 @@ public static partial class FirmamentV2Parserif (standaloneConstruction) parsed = parsed with { Document = parsed.Document with { ModelName = parsed.BoundProfile?.Name ?? parsed.BoundComposition?.Feature?.Name ?? parsed.Document.ModelName } };return WithFeatureMetadata(AttachVolumeAssertionsAndSymbols(WithPolygonMetadata(parsed, polygonExpansion), source, canonicalStaticExpansion.Document, diagnostics),- featureExpansion) with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true, BoundSource = parsed.BoundSource ?? source };+ featureExpansion) with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true, BoundSchema = FirmamentFrontendSchema.Mechanical, BoundSource = parsed.BoundSource ?? source };}if (syntax.Document.Statements.OfType<DeclarationSyntax>().Any(d => d.Type.Name.Text is "Model" or "Struct" or "Concept"@@ -576,7 +614,7 @@ public static partial class FirmamentV2Parser!hasFatalDiagnostics,document,diagnostics,- hasFatalDiagnostics ? FirmamentV2ParseDisposition.RecognizedInvalid : FirmamentV2ParseDisposition.RecognizedValid) { ParserRoute = compatibilityCore ? "UnifiedCompatibility" : "CompatibilityExtensions", OwnsUnifiedAdmission = compatibilityCore, SyntaxDiagnostics = compatibilityCore ? syntax.Diagnostics : [] };+ hasFatalDiagnostics ? FirmamentV2ParseDisposition.RecognizedInvalid : FirmamentV2ParseDisposition.RecognizedValid) { ParserRoute = compatibilityCore ? "UnifiedCompatibility" : "CompatibilityExtensions", OwnsUnifiedAdmission = compatibilityCore, BoundSchema = compatibilityCore ? FirmamentFrontendSchema.Mechanical : null, SyntaxDiagnostics = compatibilityCore ? syntax.Diagnostics : [] };}private static FirmamentV2ParseResult Recognized(FirmamentV2ParseResult result) =>diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.csindex adbbc892..ac28ef7e 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/LoftAuthoringParser.cs@@ -37,6 +37,9 @@ public static class LoftAuthoringParserpublic static SectionChainAuthoringResult Compile(string source, bool materialize = true){ArgumentNullException.ThrowIfNull(source);+ var frontend = FirmamentFrontendSchemas.Select(source);+ if (!frontend.IsSuccess) return new(false, null, null, frontend.Diagnostics);+ source = frontend.Source;source = FirmamentSourceSpelling.Normalize(source);var diagnostics = new List<string>();var syntax = FirmamentSyntaxParser.Parse(source);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.csindex d4d6aef9..7ef332d4 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs@@ -17,7 +17,6 @@ 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|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,12 +80,14 @@ public static class ProfileAuthoringParserinternal static IReadOnlyList<string> ValidatePipelineContexts(string source){- 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}")- .Distinct(StringComparer.Ordinal)- .ToArray();+ var syntax = FirmamentSyntaxParser.Parse(source).Document;+ var allowed = FirmamentSyntaxTraversal.Declarations(syntax).Where(d => d.Type.Name.Text == "Profile"+ || d.Type.Name.Text == "Path" && d.Modifiers.Any(m => m.Name.Text == "Concept"))+ .Select(d => d.Body?.Span).OfType<FirmamentV2SourceSpan>().ToArray();+ return FirmamentSyntaxTraversal.Expressions(syntax).OfType<BinarySyntax>().Where(e => e.Operator == BinaryOperator.Pipeline)+ .Where(e => !allowed.Any(span => e.Span.Start >= span.Start && e.Span.Start + e.Span.Length <= span.Start + span.Length))+ .Select(e => $"firmament-pipeline-context-type:{ParsePipelineStages(e)[0].Reference}")+ .Distinct(StringComparer.Ordinal).ToArray();}/// <summary>@@ -233,8 +234,13 @@ public static class ProfileAuthoringParserreturn profiles;}- private static string ExpandBuiltInPolygons(string source, List<string> diagnostics) =>- ClosedBoundary2Authoring.Expand(source, diagnostics)?.Source ?? source;+ private static string ExpandBuiltInPolygons(string source, List<string> diagnostics)+ {+ // Direct profile/path API consumers use the same AST-position aliases as+ // whole-document compilation, including remaining compatibility adapters.+ source = FirmamentSourceSpelling.Normalize(source);+ return ClosedBoundary2Authoring.Expand(source, diagnostics)?.Source ?? source;+ }internal static ConstructionPlane? ResolveNamedConstructionPlane(string source, string frame, List<string> diagnostics)=> ResolveConstructionPlane(source, frame, diagnostics);@@ -477,10 +483,12 @@ public static class ProfileAuthoringParservar parsedDeltas=SemanticProfileDeltaParser.Parse(source);diagnostics.AddRange(parsedDeltas.Diagnostics);var cornerPrograms = FindBlocks(source, @"\bCornerProfile\s+(?<owner>[A-Za-z_]\w*)\.(?<corner>[A-Za-z_]\w*)\s*\{").ToArray();- foreach (var rectangle in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Where(d => d.Type.Name.Text == "Rect2" && d.Name is not null))+ var declarations = SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).ToArray();+ foreach (var rectangle in declarations.Where(d => d.Type.Name.Text == "Rect2" && d.Name is not null)){var name = rectangle.Name!.Text;- var isProfileSource = Regex.IsMatch(source, $@"\bProfile\s+[A-Za-z_]\w*\s+From\s+{Regex.Escape(name)}\b", RegexOptions.CultureInvariant);+ var isProfileSource = declarations.Any(d => d.Type.Name.Text == "Profile"+ && d.Clauses.Any(c => c.Kind == ClauseKind.From && FirmamentSyntaxValues.Reference(c.Value) == name));if (!isProfileSource && !programs.Any(x => x.Match.Groups["owner"].Value == name) && !cornerPrograms.Any(x => x.Match.Groups["owner"].Value == name)&&!parsedDeltas.Deltas.Any(delta=>delta.OwnerPath.StartsWith(name+".",StringComparison.Ordinal))) continue;var fields = new FirmamentSyntaxFields(rectangle, diagnostics);@@ -748,20 +756,18 @@ public static class ProfileAuthoringParserdiagnostics.Add($"firmament-profile-pipeline-mixed-authoring:{profile.Name}:{loopName}");return [];}- var matches = Pipeline.Matches(body).Cast<Match>().ToArray();- var unconsumed = matches.Aggregate(body, (remaining, pipeline) => remaining.Replace(pipeline.Value, string.Empty, StringComparison.Ordinal));- unconsumed = RemoveRecognizedProfileDeclarations(unconsumed);- if (matches.Length != 1 || unconsumed.Any(character => !char.IsWhiteSpace(character) && character != ';'))+ var expression = ReadPipeline(MaskRecognizedProfileDeclarations(body));+ if (expression is null){diagnostics.Add($"firmament-profile-pipeline-expression-required:{profile.Name}:{loopName}");return [];}- return BindProfilePipeline(profile, loopName, matches[0], paths, points, guides, diagnostics);+ return BindProfilePipeline(profile, loopName, expression, paths, points, guides, diagnostics);}- private static IReadOnlyList<ResolvedProfileSegment2D> BindProfilePipeline(ProfileBlock profile, string loopName, Match match, IReadOnlyDictionary<string, BoundPath> paths, IReadOnlyDictionary<string, (double X, double Y)> points, IReadOnlyDictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics)+ private static IReadOnlyList<ResolvedProfileSegment2D> BindProfilePipeline(ProfileBlock profile, string loopName, ExpressionSyntax expression, IReadOnlyDictionary<string, BoundPath> paths, IReadOnlyDictionary<string, (double X, double Y)> points, IReadOnlyDictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics){- var stages = ParsePipelineStages(match.Groups["expression"].Value);+ var stages = ParsePipelineStages(expression);if (stages.Count == 2 && stages[1].Kind == PipelineStageKind.TraceLoop){if (stages[0].Kind != PipelineStageKind.Trace || stages[0].From is not null || stages[0].To is not null)@@ -770,7 +776,7 @@ public static class ProfileAuthoringParserreturn [];}if (guides.TryGetValue(stages[0].Reference!, out var closedGuide) && closedGuide is LineArcFullCircle2D or LineArcFullEllipse2D)- return [PipelineSegment(profile, loopName, stages[0].Alias ?? stages[0].Reference!.Split('.').Last(), closedGuide, $"concept:{profile.Frame ?? "XY"}.{stages[0].Reference}", stages[0].Reference!, false, 0, match.Index)];+ return [PipelineSegment(profile, loopName, stages[0].Alias ?? stages[0].Reference!.Split('.').Last(), closedGuide, $"concept:{profile.Frame ?? "XY"}.{stages[0].Reference}", stages[0].Reference!, false, 0, expression.Span.Start)];if (!paths.TryGetValue(stages[0].Reference!, out var path)){diagnostics.Add($"firmament-profile-traceloop-not-loop:{stages[0].Reference}");@@ -789,7 +795,7 @@ public static class ProfileAuthoringParser{var inherited = entry.Step.Curves.Count == 1 ? entry.Step.Name : $"{entry.Step.Name}.curve{entry.Ordinal:D2}";var name = inherited;- return PipelineSegment(profile, loopName, name, entry.Curve, $"concept-path:{path.Name}.{entry.Step.Name}", $"{path.Name}.{entry.Step.Name}", reversedLoop, index, match.Index);+ return PipelineSegment(profile, loopName, name, entry.Curve, $"concept-path:{path.Name}.{entry.Step.Name}", $"{path.Name}.{entry.Step.Name}", reversedLoop, index, expression.Span.Start);}).ToArray();}if (stages.Any(stage => stage.Kind == PipelineStageKind.TraceLoop))@@ -834,7 +840,7 @@ public static class ProfileAuthoringParservar inheritedName = stage.Reference!.Split('.').Last();var name = stage.Alias ?? inheritedName;if (!names.Add(name)) { diagnostics.Add($"firmament-profile-pipeline-identity-collision:{name}"); continue; }- result.Add(PipelineSegment(profile, loopName, name, oriented, $"concept:{profile.Frame ?? "XY"}.{stage.Reference}", stage.Reference!, reversed, index, match.Index + stage.Offset));+ result.Add(PipelineSegment(profile, loopName, name, oriented, $"concept:{profile.Frame ?? "XY"}.{stage.Reference}", stage.Reference!, reversed, index, expression.Span.Start + stage.Offset));}if (close && first is not null && current is not null && Distance(first.Value, current.Value) > Tolerance)diagnostics.Add($"firmament-pipeline-close-open:{loopName}:first={DescribeEndpoint(first.Value, points)}:current={currentIdentity}");@@ -843,14 +849,13 @@ public static class ProfileAuthoringParserprivate static BoundPath? BindPathPipeline(string name, string body, IReadOnlyDictionary<string, (double X, double Y)> points, IReadOnlyDictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics){- var match = Pipeline.Match(body);- var unconsumed = match.Success ? body.Replace(match.Value, string.Empty, StringComparison.Ordinal) : body;- if (!match.Success || unconsumed.Any(character => !char.IsWhiteSpace(character) && character != ';'))+ var expression = ReadPipeline(body);+ if (expression is null){diagnostics.Add($"firmament-path-pipeline-expression-required:{name}");return null;}- var stages = ParsePipelineStages(match.Groups["expression"].Value);+ var stages = ParsePipelineStages(expression);if (stages.Any(stage => stage.Kind is PipelineStageKind.Close or PipelineStageKind.TraceLoop)){diagnostics.Add($"firmament-pipeline-stage-type:{stages.First(stage => stage.Kind is PipelineStageKind.Close or PipelineStageKind.TraceLoop).Kind}");@@ -871,7 +876,7 @@ public static class ProfileAuthoringParservar stepName = stage.Alias ?? stage.Reference!.Split('.').Last();if (!names.Add(stepName)) { diagnostics.Add($"firmament-profile-pipeline-identity-collision:{stepName}"); continue; }var start = Start(oriented); var end = End(oriented);- steps.Add(new(stepName, oriented is LineArcCircularArc2D ? "ArcTransition" : "Span", $"{name}.{stepName}", $"{name}.{stepName}.End", [oriented], start, end, Heading(start, end), stage.Reference, reversed, steps.Count, $"offset:{match.Index + stage.Offset}"));+ steps.Add(new(stepName, oriented is LineArcCircularArc2D ? "ArcTransition" : "Span", $"{name}.{stepName}", $"{name}.{stepName}.End", [oriented], start, end, Heading(start, end), stage.Reference, reversed, steps.Count, $"offset:{expression.Span.Start + stage.Offset}"));current = end;}return steps.Count == 0 ? null : new BoundPath(name, steps[0].Start, Heading(steps[0].Start, steps[0].End), steps);@@ -991,13 +996,14 @@ public static class ProfileAuthoringParserOnLine(point, line) && point.X >= Math.Min(line.Start.X, line.End.X) - Tolerance && point.X <= Math.Max(line.Start.X, line.End.X) + Tolerance&& point.Y >= Math.Min(line.Start.Y, line.End.Y) - Tolerance && point.Y <= Math.Max(line.Start.Y, line.End.Y) + Tolerance;- private static string RemoveRecognizedProfileDeclarations(string body)+ private static string MaskRecognizedProfileDeclarations(string body){var declarationPattern = @"\b(?:(?:Concept\s+)?(?:Point2|Line2|Rect2|Square2|Circle2|Ellipse2|Ellipse2Guide|Slot2|RoundedRect2|SmoothRoundedRect2)|(?:Triangle2|Polygon2|RegularPolygon2)\s*<[^>]+>|Concept\s+Path)\s+[A-Za-z_]\w*\s*\{";var blocks = FindBlocks(body, declarationPattern).OrderByDescending(block => block.Match.Index).ToArray();- foreach (var block in blocks) body = body.Remove(block.Match.Index, block.EndIndex - block.Match.Index + 1);- body = Regex.Replace(body, @"//[^\r\n]*|/\*[\s\S]*?\*/", string.Empty, RegexOptions.CultureInvariant);- return body;+ var characters = body.ToCharArray();+ foreach (var block in blocks)+ for (var i = block.Match.Index; i <= block.EndIndex; i++) if (characters[i] is not ('\r' or '\n')) characters[i] = ' ';+ return new string(characters);}private static string Disconnected((double X, double Y) current, string reference, LineArcProfileCurve2D candidate, IReadOnlyDictionary<string, (double X, double Y)>? points) =>@@ -1009,25 +1015,46 @@ public static class ProfileAuthoringParserprivate static ResolvedProfileSegment2D PipelineSegment(ProfileBlock profile, string loop, string name, LineArcProfileCurve2D geometry, string conceptId, string tracedFrom, bool reversed, int index, int offset) =>new(name, geometry, new($"profile:{profile.Name}.{loop}.{name}", conceptId, profile.SourceSpan, $"PipelineTrace({tracedFrom});reversed={reversed.ToString().ToLowerInvariant()};pipelineIndex={index}", profile.Frame ?? "XY", tracedFrom, reversed, index, $"offset:{offset}"));- private static IReadOnlyList<PipelineStage> ParsePipelineStages(string expression)+ private static ExpressionSyntax? ReadPipeline(string body)+ {+ var parsed = FirmamentSyntaxParser.Parse(body);+ return parsed.IsSuccess && parsed.Document.Statements.Count == 1+ && parsed.Document.Statements[0] is ExpressionStatementSyntax { Value: BinarySyntax { Operator: BinaryOperator.Pipeline } expression }+ && !ParsePipelineStages(expression).Any(stage => stage.Kind == PipelineStageKind.Invalid && stage.Reference is null)+ ? expression : null;+ }++ private static IReadOnlyList<PipelineStage> ParsePipelineStages(ExpressionSyntax expression){var stages = new List<PipelineStage>();- var offset = 0;- foreach (var raw in expression.Split("|>", StringSplitOptions.TrimEntries))+ Add(expression);+ return stages;+ void Add(ExpressionSyntax value){- var localOffset = expression.IndexOf(raw, offset, StringComparison.Ordinal); offset = localOffset + raw.Length;- if (raw == "Close") stages.Add(new(PipelineStageKind.Close, null, null, false, localOffset));- else if (raw == "TraceLoop") stages.Add(new(PipelineStageKind.TraceLoop, null, null, false, localOffset));- else+ if (value is BinarySyntax { Operator: BinaryOperator.Pipeline } pipeline) { Add(pipeline.Left); Add(pipeline.Right); return; }+ var offset = value.Span.Start - expression.Span.Start;+ if (value is ReferenceSyntax { Name.Text: "Close" }) { stages.Add(new(PipelineStageKind.Close, null, null, false, offset)); return; }+ if (value is ReferenceSyntax { Name.Text: "TraceLoop" }) { stages.Add(new(PipelineStageKind.TraceLoop, null, null, false, offset)); return; }+ string? alias = null, from = null, to = null;+ var reverse = false; var valid = true; var traced = false;+ var inner = value;+ while (true){- 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)- : new(PipelineStageKind.Invalid, raw, null, false, localOffset, null, null));+ if (inner is AliasSyntax a) { valid &= alias is null; alias = a.Name.Text; inner = a.Value; }+ else if (inner is TraceSyntax t)+ {+ valid &= !traced; traced = true;+ from = FirmamentSyntaxValues.Reference(t.From); to = FirmamentSyntaxValues.Reference(t.To);+ valid &= (t.From is null || from is not null) && (t.To is null || to is not null) && (from is null || to is not null);+ inner = t.Source;+ }+ else if (inner is UnarySyntax { Operator: UnaryOperator.Reverse } u) { valid &= !reverse; reverse = true; inner = u.Operand; }+ else break;}+ var reference = inner is ReferenceSyntax or MemberSyntax ? FirmamentSyntaxValues.Reference(inner) : null;+ valid &= reference is not null;+ stages.Add(new(valid ? PipelineStageKind.Trace : PipelineStageKind.Invalid, reference, alias, reverse, offset, from, to));}- return stages;}private static bool IsClosed(IReadOnlyList<LineArcProfileCurve2D> curves) => curves.Count > 0 && Distance(Start(curves[0]), End(curves[^1])) <= Tolerance && curves.Zip(curves.Skip(1)).All(pair => Distance(End(pair.First), Start(pair.Second)) <= Tolerance);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileModificationTemplateLibrary.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileModificationTemplateLibrary.csindex fb17c956..1c4ee874 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileModificationTemplateLibrary.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileModificationTemplateLibrary.cs@@ -1,13 +1,27 @@using System.Reflection;-using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;namespace Aetheris.Kernel.Firmament.FirmamentV2;public static class ProfileModificationTemplateLibrary{private const string ResourceName="Aetheris.Kernel.Firmament.Resources.ProfileModifications.firmament";- public static string ResolveImports(string source) => Regex.IsMatch(source, @"\bUse\s+Profile\.Modifications\s*;")- ? Source + Environment.NewLine + Regex.Replace(source, @"\bUse\s+Profile\.Modifications\s*;", "") : source;+ internal static bool IsImport(DirectiveSyntax directive) => directive.Kind == DirectiveKind.Use+ && FirmamentSyntaxValues.Reference(directive.Value) == "Profile.Modifications";+ public static string ResolveImports(string source)+ {+ if (!source.Contains("Use", StringComparison.Ordinal)) return source;+ var syntax = FirmamentSyntaxParser.Parse(source);+ var imports = syntax.Document.Statements.OfType<DirectiveSyntax>().Where(IsImport).ToArray();+ if (imports.Length == 0) return source;+ foreach (var import in imports.OrderByDescending(d => d.Span.Start))+ {+ var length = import.Span.Length;+ if (import.Span.Start + length < source.Length && source[import.Span.Start + length] == ';') length++;+ source = source.Remove(import.Span.Start, length);+ }+ return Source + Environment.NewLine + source;+ }public static string Source{getdiff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.csindex 39d927bb..32b558bb 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs@@ -45,6 +45,9 @@ public static class SectionChainAuthoringParser{using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("sectionchain.authoring-compile");ArgumentNullException.ThrowIfNull(source);+ var frontend = FirmamentFrontendSchemas.Select(source);+ if (!frontend.IsSuccess) return new(false, null, null, frontend.Diagnostics);+ source = frontend.Source;source = FirmamentSourceSpelling.Normalize(source);if (LoftAuthoringParser.IsLoftSource(source))return LoftAuthoringParser.Compile(source, materialize);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSymmetryAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSymmetryAuthoring.csindex a9f766fb..5b7b914f 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSymmetryAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSymmetryAuthoring.cs@@ -2,6 +2,7 @@ using System.Globalization;using System.Text;using System.Text.RegularExpressions;using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.Firmament.Materializer;namespace Aetheris.Kernel.Firmament.FirmamentV2;@@ -15,101 +16,94 @@ internal static class SemanticSymmetryAuthoringinternal const string Prefix = "firmament-symmetry-";private const double Tolerance = 1e-8;private const int MaxInstances = 1024;- private static readonly Regex MirrorHeader = new(@"\bMirrored\s+(?<kind>Profile|Feature)\s+(?<destination>[A-Za-z_]\w*)\s+From\s+(?<source>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex UnsupportedMirrorHeader = new(@"\bMirrored\s+(?<kind>[A-Za-z_]\w*(?:\s*<[^>]+>)?)\s+(?<destination>[A-Za-z_]\w*)\s+From\s+(?<source>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex RadialHeader = new(@"\bRadial\s+Pattern\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex FeatureHeader = new(@"\b(?<kind>Hole\s*<\s*(?:Shaft|Counterbore|Countersink)\s*>|Boss|Pocket)\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex AxisHeader = 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);- private static readonly Regex PlaneHeader = new(@"\bPlane\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*Normal\s*:\s*\[\s*(?<nx>[-+.\deE]+)\s*,\s*(?<ny>[-+.\deE]+)\s*,\s*(?<nz>[-+.\deE]+)\s*\](?:\s*;?\s*Up\s*:\s*\[[^]]+\])?", RegexOptions.CultureInvariant);+ private enum MirrorField { Across }+ private enum RadialField { Source, About, Count, Angle }+ internal static IReadOnlyList<string> FieldsFor(DeclarationSyntax d) =>+ d.Type.Name.Text is "Feature" or "Profile" && d.Modifiers.Any(m => m.Name.Text == "Mirrored") ? Enum.GetNames<MirrorField>() :+ d.Type.Name.Text == "Pattern" && d.Modifiers.Any(m => m.Name.Text == "Radial") ? Enum.GetNames<RadialField>() : [];+ private static DeclarationSyntax[] Declarations(string source) => FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).ToArray();+ private static Change Remove(DeclarationSyntax d) => new(d.Span.Start, d.Span.Length, string.Empty);internal sealed record Result(string Source, IReadOnlyList<FirmamentV2MirrorDerivation> Mirrors, IReadOnlyList<FirmamentV2RadialPatternDecl> RadialPatterns);public static Result? Expand(string source, List<string> diagnostics){- if (!Regex.IsMatch(source, @"\b(?:Mirrored\s+|Radial\s+Pattern\s+)", RegexOptions.CultureInvariant))- return new(source, [], []);-+ // Negative fast path only. Positive recognition and admission belong to AST nodes.+ if (!source.Contains("Mirrored", StringComparison.Ordinal) && !source.Contains("Radial", StringComparison.Ordinal)) return new(source, [], []);+ var declarations = Declarations(source);+ var mirrorDeclarations = declarations.Where(d => d.Modifiers.Any(m => m.Name.Text == "Mirrored")).ToArray();+ if (mirrorDeclarations.Length == 0 && !declarations.Any(d => d.Modifiers.Any(m => m.Name.Text == "Radial"))) return new(source, [], []);+ var before = diagnostics.Count;var mirrors = new List<FirmamentV2MirrorDerivation>();var radialPatterns = new List<FirmamentV2RadialPatternDecl>();-- foreach (Match unsupported in UnsupportedMirrorHeader.Matches(source))- if (!MirrorHeader.Matches(source).Cast<Match>().Any(valid => valid.Index == unsupported.Index))- diagnostics.Add(Prefix + "type-unsupported:" + unsupported.Groups["kind"].Value.Replace(" ", string.Empty, StringComparison.Ordinal));- if (HasErrors(diagnostics)) return null;-- // Profiles are resolved from semantic guides and emitted again as semantic guides.- // Removing all derivation declarations avoids recursive expansion in ResolveNamedProfile.- var resolutionSource = RemoveDeclarations(source, MirrorHeader).Source;+ var resolutionSource = Apply(source, mirrorDeclarations.Select(Remove));var mirrorChanges = new List<Change>();- var mirrorPlaneRemovals = new Dictionary<int, Change>();- foreach (Match declaration in MirrorHeader.Matches(source))+ var planeRemovals = new Dictionary<int, Change>();+ foreach (var declaration in mirrorDeclarations){- var open = source.IndexOf('{', declaration.Index);- var close = Matching(source, open, '{', '}');- if (close < 0) { diagnostics.Add(Prefix + "mirror-malformed:" + declaration.Groups["destination"].Value); continue; }- var destination = declaration.Groups["destination"].Value;- var sourceName = declaration.Groups["source"].Value;- var kind = Regex.Replace(declaration.Groups["kind"].Value, @"\s+", string.Empty);- if ((kind == "Profile" && Regex.IsMatch(resolutionSource, $@"\bProfile\s+{Regex.Escape(destination)}\b", RegexOptions.CultureInvariant))- || (kind != "Profile" && FindFeature(resolutionSource, destination) is not null))+ var destination = declaration.Name?.Text;+ var kind = declaration.Type.Name.Text;+ if (kind is not ("Profile" or "Feature") || declaration.Type.Arguments.Count > 0)+ { diagnostics.Add(Prefix + "type-unsupported:" + kind); continue; }+ var from = declaration.Clauses.Where(c => c.Kind == ClauseKind.From).ToArray();+ var sourceName = from.Length == 1 ? FirmamentSyntaxValues.Reference(from[0].Value) : null;+ var fields = new FirmamentSyntaxFields(declaration with { Clauses = declaration.Clauses.Where(c => c.Kind != ClauseKind.From).ToArray() }, diagnostics);+ var acrossName = fields.Word(nameof(MirrorField.Across)); fields.Complete();+ if (destination is null || sourceName is null || declaration.Body is null)+ { diagnostics.Add(Prefix + "mirror-malformed:" + destination); continue; }+ if (Declarations(resolutionSource).Any(d => d.Name?.Text == destination && d.Type.Name.Text == (kind == "Profile" ? "Profile" : "Hole"))+ || kind == "Feature" && FindFeature(resolutionSource, destination) is not null){ diagnostics.Add(Prefix + "identity-collision:" + destination); continue; }- var acrossName = Field(source[(open + 1)..close], "Across");string? planeDiagnostic = null;SemanticSymmetryTransform.Plane? across = null;- if (acrossName is null || !TryResolvePlane(resolutionSource, acrossName, out across, out planeDiagnostic))+ if (acrossName is null || !TryResolvePlane(resolutionSource, acrossName, diagnostics, out across, out planeDiagnostic)){ diagnostics.Add(planeDiagnostic ?? Prefix + "plane-unresolved:" + destination); continue; }-- string? lowered;IReadOnlyList<FirmamentV2MirrorMemberProvenance> members;- if (kind == "Profile")- lowered = MirrorProfile(resolutionSource, destination, sourceName, across!, diagnostics, out members);- else- lowered = MirrorFeature(resolutionSource, destination, sourceName, across!, diagnostics, out members);+ var lowered = kind == "Profile"+ ? MirrorProfile(resolutionSource, destination, sourceName, across!, diagnostics, out members)+ : MirrorFeature(resolutionSource, destination, sourceName, across!, diagnostics, out members);if (lowered is null) continue;- mirrorChanges.Add(new(declaration.Index, close - declaration.Index + 1, lowered));- var directPlane = PlaneHeader.Matches(source).Cast<Match>().FirstOrDefault(match => match.Groups["name"].Value == acrossName);- if (directPlane is not null)- {- var planeOpen = source.IndexOf('{', directPlane.Index); var planeClose = Matching(source, planeOpen, '{', '}');- if (planeClose >= 0) mirrorPlaneRemovals[directPlane.Index] = new(directPlane.Index, planeClose - directPlane.Index + 1, string.Empty);- }+ mirrorChanges.Add(new(declaration.Span.Start, declaration.Span.Length, lowered));+ var directPlane = Declarations(source).FirstOrDefault(d => d.Type.Name.Text == "Plane" && d.Name?.Text == acrossName && d.Modifiers.Count == 0);+ if (directPlane is not null) planeRemovals[directPlane.Span.Start] = Remove(directPlane);resolutionSource += Environment.NewLine + lowered;mirrors.Add(new(destination, kind, sourceName, acrossName, "CanonicalRightHanded", members,- new(declaration.Index, close - declaration.Index + 1), [sourceName, $"Mirror({acrossName})", destination]));+ declaration.Span, [sourceName, $"Mirror({acrossName})", destination]));}- if (HasErrors(diagnostics)) return null;- source = Apply(source, mirrorChanges.Concat(mirrorPlaneRemovals.Values));-- // Immutable divergence is ordinary source cloning plus explicit field replacement.+ if (diagnostics.Count != before) return null;+ source = Apply(source, mirrorChanges.Concat(planeRemovals.Values));source = ExpandFeatureWith(source, mirrors, diagnostics);- if (HasErrors(diagnostics)) return null;+ if (diagnostics.Count != before) return null;var radialChanges = new List<Change>();- var radialSourceRemovals = new Dictionary<int, Change>();- var radialAxisRemovals = new Dictionary<int, Change>();- foreach (Match declaration in RadialHeader.Matches(source))+ var sourceRemovals = new Dictionary<int, Change>();+ var axisRemovals = new Dictionary<int, Change>();+ var radialDeclarations = Declarations(source);+ foreach (var declaration in radialDeclarations.Where(d => d.Modifiers.Any(m => m.Name.Text == "Radial"))){- var open = source.IndexOf('{', declaration.Index); var close = Matching(source, open, '{', '}');- var name = declaration.Groups["name"].Value;- if (close < 0) { diagnostics.Add(Prefix + "radial-malformed:" + name); continue; }- var body = source[(open + 1)..close];- var sourceName = Field(body, "Source"); var axisName = Field(body, "About"); var countText = Field(body, "Count"); var angleText = Field(body, "Angle");- if (sourceName is null || axisName is null || countText is null || angleText is null)+ var name = declaration.Name?.Text;+ if (declaration.Type.Name.Text != "Pattern" || name is null)+ { diagnostics.Add(Prefix + "type-unsupported:" + declaration.Type.Name.Text); continue; }+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);+ var sourceName = fields.Word(nameof(RadialField.Source)); var axisName = fields.Word(nameof(RadialField.About));+ var countValue = fields.Number(nameof(RadialField.Count), ""); var angleValue = fields.Take(nameof(RadialField.Angle));+ fields.Complete();+ if (sourceName is null || axisName is null || angleValue is null || !double.IsFinite(countValue)){ diagnostics.Add(Prefix + "radial-field-missing:" + name); continue; }- if (!int.TryParse(countText, NumberStyles.Integer, CultureInfo.InvariantCulture, out var count) || count < 1 || count > MaxInstances)- { diagnostics.Add(Prefix + "radial-count-invalid:" + name + ":" + countText); continue; }- if (!RevolveAuthoringParser.TryAngle(angleText, out var angle, out _))- { diagnostics.Add(Prefix + "radial-angle-invalid:" + name + ":" + angleText); continue; }- if (!TryResolveAxis(source, axisName, out var axis))+ if (countValue != Math.Truncate(countValue) || countValue < 1 || countValue > MaxInstances)+ { diagnostics.Add(Prefix + "radial-count-invalid:" + name + ":" + countValue); continue; }+ var count = (int)countValue;+ if (!RevolveAuthoringParser.TryAngle(source.Substring(angleValue.Span.Start, angleValue.Span.Length), out var angle, out _))+ { diagnostics.Add(Prefix + "radial-angle-invalid:" + name); continue; }+ if (!TryResolveAxis(source, axisName, diagnostics, out var axis)){ diagnostics.Add(Prefix + "radial-axis-invalid:" + name + ":" + axisName); continue; }- var feature = FindFeature(source, sourceName);+ var feature = FindFeature(source, sourceName, radialDeclarations);if (feature is null) { diagnostics.Add(Prefix + "radial-source-unsupported:" + name + ":" + sourceName); continue; }- if (!TryPoint2(feature.Body, out var center)) { diagnostics.Add(Prefix + "feature-center-unsupported:" + sourceName); continue; }+ if (!TryPoint2(feature, out var center)) { diagnostics.Add(Prefix + "feature-center-unsupported:" + sourceName); continue; }if (Math.Abs(Math.Abs(axis!.Direction.Z) - 1d) > Tolerance){ diagnostics.Add(Prefix + "radial-axis-not-profile-normal:" + name); continue; }- if (Enumerable.Range(0, count).Any(index => FindFeature(source, name + "_Instance" + index.ToString(CultureInfo.InvariantCulture)) is not null))+ if (Enumerable.Range(0, count).Any(index => radialDeclarations.Any(d => d.Name?.Text == name + "_Instance" + index.ToString(CultureInfo.InvariantCulture)))){ diagnostics.Add(Prefix + "identity-collision:" + name); continue; }-var denominator = NearlyFull(angle) ? count : Math.Max(1, count - 1);var instances = new List<FirmamentV2RadialInstance>(); var emitted = new List<string>();for (var index = 0; index < count; index++)@@ -118,20 +112,17 @@ internal static class SemanticSymmetryAuthoringvar rotated = SemanticSymmetryTransform.Rotate(new Point3D(center.X, center.Y, 0), axis, theta);var semanticId = name + ".Instance" + index.ToString(CultureInfo.InvariantCulture);var materialId = name + "_Instance" + index.ToString(CultureInfo.InvariantCulture);- emitted.Add(CloneFeature(feature, materialId, (rotated.X, rotated.Y), semanticId));+ emitted.Add(CloneFeature(feature, materialId, (rotated.X, rotated.Y)));instances.Add(new(semanticId, index, theta, rotated.X, rotated.Y, [sourceName, $"Rotate({axisName},{theta:R})", semanticId]));}- radialChanges.Add(new(declaration.Index, close - declaration.Index + 1, string.Join(Environment.NewLine, emitted)));- radialSourceRemovals[feature.Start] = new(feature.Start, feature.Length, string.Empty);- var axisDeclaration = AxisHeader.Matches(source).Cast<Match>().First(item => item.Groups["name"].Value == axisName);- var axisOpen = source.IndexOf('{', axisDeclaration.Index); var axisClose = Matching(source, axisOpen, '{', '}');- if (axisClose >= 0) radialAxisRemovals[axisDeclaration.Index] = new(axisDeclaration.Index, axisClose - axisDeclaration.Index + 1, string.Empty);- radialPatterns.Add(new(name, sourceName, axisName, count, angle, NearlyFull(angle) ? "FullOpenEndpoint" : "PartialInclusiveEndpoints", instances,- new(declaration.Index, close - declaration.Index + 1)));+ radialChanges.Add(new(declaration.Span.Start, declaration.Span.Length, string.Join(Environment.NewLine, emitted)));+ sourceRemovals[feature.Start] = new(feature.Start, feature.Length, string.Empty);+ var axisDeclaration = radialDeclarations.Single(d => d.Type.Name.Text == "Axis" && d.Name?.Text == axisName);+ axisRemovals[axisDeclaration.Span.Start] = Remove(axisDeclaration);+ radialPatterns.Add(new(name, sourceName, axisName, count, angle, NearlyFull(angle) ? "FullOpenEndpoint" : "PartialInclusiveEndpoints", instances, declaration.Span));}- if (HasErrors(diagnostics)) return null;- source = Apply(source, radialChanges.Concat(radialSourceRemovals.Values).Concat(radialAxisRemovals.Values));- return new(source, mirrors, radialPatterns);+ if (diagnostics.Count != before) return null;+ return new(Apply(source, radialChanges.Concat(sourceRemovals.Values).Concat(axisRemovals.Values)), mirrors, radialPatterns);}private static string? MirrorProfile(string source, string destination, string sourceName, SemanticSymmetryTransform.Plane across,@@ -202,39 +193,52 @@ internal static class SemanticSymmetryAuthoringmembers = [];var feature = FindFeature(source, sourceName);if (feature is null) { diagnostics.Add(Prefix + "feature-source-invalid:" + sourceName); return null; }- if (!TryPoint2(feature.Body, out var center)) { diagnostics.Add(Prefix + "feature-center-unsupported:" + sourceName); return null; }+ if (!TryPoint2(feature, out var center)) { diagnostics.Add(Prefix + "feature-center-unsupported:" + sourceName); return null; }var reflected = SemanticSymmetryTransform.Reflect(new Point3D(center.X, center.Y, 0), across);if (Math.Abs(reflected.Z) > Tolerance) { diagnostics.Add(Prefix + "feature-plane-mismatch:" + destination); return null; }if (Math.Abs(reflected.X - center.X) <= Tolerance && Math.Abs(reflected.Y - center.Y) <= Tolerance){ diagnostics.Add(Prefix + "redundant-feature-mirror:" + destination); return null; }members = [new(destination + ".Center", sourceName + ".Center", "Mirror", $"offset:{feature.Start}")];- return CloneFeature(feature, destination, (reflected.X, reflected.Y), destination);+ return CloneFeature(feature, destination, (reflected.X, reflected.Y));}private static string ExpandFeatureWith(string source, List<FirmamentV2MirrorDerivation> mirrors, List<string> diagnostics){- var changes = new List<Change>();- foreach (Match declaration in Regex.Matches(source, @"\bFeature\s+(?<destination>[A-Za-z_]\w*)\s*=\s*(?<source>[A-Za-z_]\w*)\s+with\s*\{", RegexOptions.CultureInvariant))+ // Rebind after each derivation so a later with may refer to its predecessor.+ while (Declarations(source).FirstOrDefault(d => d.Type.Name.Text == "Feature" && d.Initializer is WithSyntax) is { } declaration){- var open = source.IndexOf('{', declaration.Index); var close = Matching(source, open, '{', '}');- if (close < 0) { diagnostics.Add(Prefix + "with-malformed:" + declaration.Groups["destination"].Value); continue; }- var feature = FindFeature(source, declaration.Groups["source"].Value);- if (feature is null) { diagnostics.Add(Prefix + "with-source-invalid:" + declaration.Groups["source"].Value); continue; }- var body = feature.Body;- foreach (Match field in Regex.Matches(source[(open + 1)..close], @"\b(?<name>[A-Za-z_]\w*)\s*:\s*(?<value>[^;\r\n}]+)", RegexOptions.CultureInvariant))+ var derived = (WithSyntax)declaration.Initializer!;+ var sourceName = FirmamentSyntaxValues.Reference(derived.Target);+ var feature = sourceName is null ? null : FindFeature(source, sourceName);+ if (feature is null || declaration.Name is null)+ { diagnostics.Add(Prefix + "with-source-invalid:" + sourceName); return source; }+ if (declaration.Span.Start < feature.Start + feature.Length && feature.Start < declaration.Span.Start + declaration.Span.Length)+ { diagnostics.Add(Prefix + "with-source-cycle:" + sourceName); return source; }+ var replacements = new List<Change>();+ var seen = new HashSet<string>(StringComparer.Ordinal);+ foreach (var statement in derived.Body.Statements){- var replacement = new Regex($@"\b{Regex.Escape(field.Groups["name"].Value)}\s*:\s*[^;\r\n}}]+", RegexOptions.CultureInvariant);- if (!replacement.IsMatch(body)) { diagnostics.Add(Prefix + "with-field-unknown:" + declaration.Groups["destination"].Value + ":" + field.Groups["name"].Value); continue; }- body = replacement.Replace(body, field.Groups["name"].Value + ": " + field.Groups["value"].Value.Trim(), 1);+ if (statement is not FieldSyntax field)+ { diagnostics.Add(Prefix + "with-statement-unsupported:" + declaration.Name.Text); continue; }+ var candidates = feature.Declaration.Body!.Statements.OfType<FieldSyntax>()+ .Where(f => FirmamentSyntaxFields.SameField(field.Name.Text, f.Name.Text) || FirmamentSyntaxFields.SameField(f.Name.Text, field.Name.Text)).ToArray();+ if (candidates.Length != 1)+ { diagnostics.Add(Prefix + "with-field-unknown:" + declaration.Name.Text + ":" + field.Name.Text); continue; }+ var target = candidates[0];+ if (!seen.Add(target.Name.Text)) { diagnostics.Add(Prefix + "with-field-duplicate:" + field.Name.Text); continue; }+ replacements.Add(new(target.Value.Span.Start - feature.BodyStart, target.Value.Span.Length,+ source.Substring(field.Value.Span.Start, field.Value.Span.Length)));}- var destination = declaration.Groups["destination"].Value;+ if (replacements.Count == 0 || declaration.Type.Arguments.Count > 0 || declaration.Parameters.Count > 0 || declaration.Clauses.Count > 0)+ { diagnostics.Add(Prefix + "with-malformed:" + declaration.Name.Text); return source; }+ var body = Apply(feature.Body, replacements);+ var destination = declaration.Name.Text;var lowered = feature.Kind + " " + destination + " {" + body + "}";- changes.Add(new(declaration.Index, close - declaration.Index + 1, lowered));- changes.Add(new(feature.Start, feature.Length, string.Empty));- var origin = mirrors.FirstOrDefault(item => item.Destination == declaration.Groups["source"].Value);+ source = Apply(source, [new(declaration.Span.Start, declaration.Span.Length, lowered), new(feature.Start, feature.Length, string.Empty)]);+ var origin = mirrors.FirstOrDefault(item => item.Destination == sourceName);if (origin is not null) mirrors.Add(origin with { Destination = destination, Kind = "FeatureWith", Provenance = origin.Provenance.Concat([$"with({destination})"]).ToArray() });}- return Apply(source, changes);+ return source;}private static LineArcProfileCurve2D? ReflectCurve(LineArcProfileCurve2D curve, ConstructionPlane frame, SemanticSymmetryTransform.Plane across, List<string> diagnostics, string destination)@@ -276,75 +280,76 @@ internal static class SemanticSymmetryAuthoring_ => curve};- private static bool TryResolvePlane(string source, string reference, out SemanticSymmetryTransform.Plane? plane, out string? diagnostic)+ private static bool TryResolvePlane(string source, string reference, List<string> diagnostics, out SemanticSymmetryTransform.Plane? plane, out string? diagnostic){- plane = null; diagnostic = null; var conceptReference = reference;- var direct = PlaneHeader.Matches(source).Cast<Match>().FirstOrDefault(match => match.Groups["name"].Value == reference);- if (direct is not null && Numbers(direct, ["x", "y", "z", "nx", "ny", "nz"], out var values)- && Direction3D.TryCreate(new(values[3], values[4], values[5]), out var directNormal))+ plane = null; diagnostic = null;+ var candidates = Declarations(source).Where(d => d.Type.Name.Text == "Plane" && d.Name?.Text == reference).ToArray();+ var conceptReference = reference;+ if (candidates.Length > 1) { diagnostic = Prefix + "plane-ambiguous:" + reference; return false; }+ if (candidates.SingleOrDefault() is { } declaration){- plane = new(new(values[0], values[1], values[2]), directNormal);- return true;+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);+ if (declaration.Modifiers.Any(m => m.Name.Text == "Construction"))+ {+ conceptReference = fields.Word("Trace") ?? reference; fields.Complete();+ }+ else+ {+ var valid = fields.Vector("Origin", "mm", out var origin) && origin.Length == 3;+ valid &= fields.Vector("Normal", "", out var normalValues) && normalValues.Length == 3;+ var up = fields.Take("Up");+ if (up is not null) valid &= FirmamentSyntaxValues.Vector(up, "", out var u) && u.Length == 3;+ fields.Complete();+ if (!valid || !Direction3D.TryCreate(new(normalValues[0], normalValues[1], normalValues[2]), out var normal))+ { diagnostic = Prefix + "plane-invalid:" + reference; return false; }+ plane = new(new(origin[0], origin[1], origin[2]), normal); return true;+ }}- var construction = Regex.Matches(source, @"\bConstruction\s+Plane\s+(?<name>[A-Za-z_]\w*)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)", RegexOptions.CultureInvariant)- .Cast<Match>().FirstOrDefault(match => match.Groups["name"].Value == reference);- if (construction is not null) conceptReference = construction.Groups["trace"].Value;if (!ConceptIrResolver.TryResolvePlane(source, conceptReference, out var resolved, out diagnostic) || resolved is null){ diagnostic = Prefix + "plane-invalid:" + reference + ":" + (diagnostic ?? "unresolved"); return false; }- if (!Direction3D.TryCreate(new(resolved.Normal.X, resolved.Normal.Y, resolved.Normal.Z), out var normal))+ if (!Direction3D.TryCreate(new(resolved.Normal.X, resolved.Normal.Y, resolved.Normal.Z), out var resolvedNormal)){ diagnostic = Prefix + "plane-invalid:" + reference + ":normal"; return false; }- plane = new(new(resolved.Origin.X, resolved.Origin.Y, resolved.Origin.Z), normal); return true;+ plane = new(new(resolved.Origin.X, resolved.Origin.Y, resolved.Origin.Z), resolvedNormal); return true;}- private static bool TryResolveAxis(string source, string name, out SemanticSymmetryTransform.Axis? axis)+ private static bool TryResolveAxis(string source, string name, List<string> diagnostics, out SemanticSymmetryTransform.Axis? axis){axis = null;- var match = AxisHeader.Matches(source).Cast<Match>().FirstOrDefault(item => item.Groups["name"].Value == name);- if (match is null || !Numbers(match, ["x", "y", "z", "dx", "dy", "dz"], out var v) || !Direction3D.TryCreate(new(v[3], v[4], v[5]), out var direction)) return false;- axis = new(new(v[0], v[1], v[2]), direction); return true;+ var candidates = Declarations(source).Where(d => d.Type.Name.Text == "Axis" && d.Name?.Text == name).ToArray();+ if (candidates.Length != 1) return false;+ var fields = new FirmamentSyntaxFields(candidates[0], diagnostics);+ var valid = fields.Vector("Origin", "mm", out var origin) && origin.Length == 3;+ valid &= fields.Vector("Direction", "", out var vector) && vector.Length == 3;+ fields.Complete();+ if (!valid || !Direction3D.TryCreate(new(vector[0], vector[1], vector[2]), out var direction)) return false;+ axis = new(new(origin[0], origin[1], origin[2]), direction); return true;}- private static FeatureBlock? FindFeature(string source, string name)+ private static FeatureBlock? FindFeature(string source, string name, DeclarationSyntax[]? declarations = null){- foreach (Match header in FeatureHeader.Matches(source))- {- if (header.Groups["name"].Value != name) continue;- var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}');- if (close >= 0) return new(header.Groups["kind"].Value, name, source[(open + 1)..close], header.Index, close - header.Index + 1);- }- return null;+ var candidates = (declarations ?? Declarations(source)).Where(d => d.Name?.Text == name && d.Modifiers.Count == 0+ && d.Type.Name.Text is "Hole" or "Boss" or "Pocket" && d.Body is not null).ToArray();+ if (candidates.Length != 1) return null;+ var declaration = candidates[0]; var body = declaration.Body!.ContentSpan;+ return new(declaration, source.Substring(declaration.Type.Span.Start, declaration.Type.Span.Length), name,+ source.Substring(body.Start, body.Length), body.Start, declaration.Span.Start, declaration.Span.Length);}- private static string CloneFeature(FeatureBlock feature, string name, (double X, double Y) center, string semanticId)+ private static string CloneFeature(FeatureBlock feature, string name, (double X, double Y) center){- var body = Regex.Replace(feature.Body, @"\bCenter\s*:\s*Point2\(\s*[-+0-9.eE]+mm\s*,\s*[-+0-9.eE]+mm\s*\)", $"Center: Point2({F(center.X)}mm, {F(center.Y)}mm)", RegexOptions.CultureInvariant);+ var field = feature.Declaration.Body!.Statements.OfType<FieldSyntax>().Single(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Center"));+ var body = Apply(feature.Body, [new(field.Span.Start - feature.BodyStart, field.Span.Length,+ $"Center: Point2({F(center.X)}mm, {F(center.Y)}mm)")]);return feature.Kind + " " + name + " {" + body + Environment.NewLine + "}";}- private static bool TryPoint2(string body, out (double X, double Y) center)- {- center = default; var match = Regex.Match(body, @"\bCenter\s*:\s*Point2\(\s*(?<x>[-+0-9.eE]+)mm\s*,\s*(?<y>[-+0-9.eE]+)mm\s*\)", RegexOptions.CultureInvariant);- return match.Success && double.TryParse(match.Groups["x"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out center.X) && double.TryParse(match.Groups["y"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out center.Y);- }-- private static bool Numbers(Match match, string[] groups, out double[] values)- {- values = new double[groups.Length];- for (var i = 0; i < groups.Length; i++) if (!double.TryParse(match.Groups[groups[i]].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out values[i]) || !double.IsFinite(values[i])) return false;- return true;- }-- private static string? Field(string body, string name)- {- var match = Regex.Match(body, $@"\b{Regex.Escape(name)}\s*:\s*(?<value>[^;\s}}]+)", RegexOptions.CultureInvariant);- return match.Success ? match.Groups["value"].Value.Trim() : null;- }-- private static (string Source, IReadOnlyList<Change> Changes) RemoveDeclarations(string source, Regex header)+ private static bool TryPoint2(FeatureBlock feature, out (double X, double Y) center){- var changes = new List<Change>();- foreach (Match match in header.Matches(source)) { var open = source.IndexOf('{', match.Index); var close = Matching(source, open, '{', '}'); if (close >= 0) changes.Add(new(match.Index, close - match.Index + 1, string.Empty)); }- return (Apply(source, changes), changes);+ center = default;+ var fields = feature.Declaration.Body!.Statements.OfType<FieldSyntax>().Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Center")).ToArray();+ if (fields.Length != 1 || fields[0].Value is not CallSyntax { Target: ReferenceSyntax { Name.Text: "Point2" } }+ || !FirmamentSyntaxValues.Vector(fields[0].Value, "mm", out var values) || values.Length != 2) return false;+ center = (values[0], values[1]); return true;}private static string Apply(string source, IEnumerable<Change> changes)@@ -354,13 +359,6 @@ internal static class SemanticSymmetryAuthoringreturn source;}- private static int Matching(string source, int open, char opening, char closing)- {- if (open < 0) return -1; var depth = 0;- for (var i = open; i < source.Length; i++) { if (source[i] == opening) depth++; else if (source[i] == closing && --depth == 0) return i; }- return -1;- }-private static void Endpoints(LineArcProfileCurve2D curve, out (double X, double Y) start, out (double X, double Y) end){if (curve is LineArcLineSegment2D line) { start = line.Start; end = line.End; return; }@@ -369,10 +367,9 @@ internal static class SemanticSymmetryAuthoringend = (arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians));}- private static bool HasErrors(IEnumerable<string> diagnostics) => diagnostics.Any(item => item.StartsWith(Prefix, StringComparison.Ordinal));private static bool NearlyFull(double angle) => Math.Abs(Math.Abs(angle) - 2d * Math.PI) <= Tolerance;private static string Safe(string value) => Regex.Replace(value, @"[^A-Za-z0-9_]", "_");private static string F(double value) => (Math.Abs(value) < 1e-12 ? 0d : value).ToString("R", CultureInfo.InvariantCulture);private sealed record Change(int Start, int Length, string Text);- private sealed record FeatureBlock(string Kind, string Name, string Body, int Start, int Length);+ private sealed record FeatureBlock(DeclarationSyntax Declaration, string Kind, string Name, string Body, int BodyStart, int Start, int Length);}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.csindex 47c137d8..c6baf4ec 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs@@ -109,11 +109,21 @@ public static class FirmamentSyntaxParserif (Is("schema") || Is("include") || Is("Include") || Is("Use")){var kind = Current.Text switch { "schema" => DirectiveKind.Schema, "Use" => DirectiveKind.Use, _ => DirectiveKind.Include };- at++; return new DirectiveSyntax(kind, Expression(allowObject: false), Span(start));+ at++;+ try { return new DirectiveSyntax(kind, Expression(allowObject: false), Span(start)); }+ catch (ParseFailure)+ {+ Error(kind == DirectiveKind.Schema ? "firmament-schema-malformed" : "firmament-v2-directive-malformed",+ $"Expected a valid value for the {kind.ToString().ToLowerInvariant()} directive.", Span(start));+ throw;+ }}// 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 == "-" && 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)+ if (Is("Reverse") || Peek(1).Text == "-" && Peek(2).Text == ">" || Peek(1).Text is "(" or "." or "|" or "[" or "As" or "as"+ || Peek(1).Text is "From" or "from" or "To" or "to" && Peek(2).Kind == SyntaxTokenKind.Identifier+ && (Peek(3).Text is "." or "To" or "to" or "As" or "as" or "|" or ";" or "}" || Peek(3).Kind == SyntaxTokenKind.End)+ || Peek(1).Text is ";" or "}" || Peek(1).Kind == SyntaxTokenKind.End){var expression = Expression();// Selector aliases historically used =>; retain it as the@@ -151,7 +161,9 @@ public static class FirmamentSyntaxParsermodifiers.Add(type); type = Type();}IdentifierSyntax? name = null;- if (Current.Kind == SyntaxTokenKind.Identifier && !LineBreak && !IsClause(Current.Text)) name = Identifier();+ // Lowercase from was already a legal authored name. It becomes a link+ // only after the declaration name, never a newly reserved identifier.+ if (Current.Kind == SyntaxTokenKind.Identifier && !LineBreak && (Current.Text == "from" || !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.@@ -314,11 +326,11 @@ public static class FirmamentSyntaxParser{if (++suffixCount > MaxDepth) throw Fail("firmament-syntax-depth", $"Expression chain exceeds the bounded parser limit of {MaxDepth}.");if (Take("As") || Take("as")) { left = new AliasSyntax(left, Identifier(), Span(start)); continue; }- if (Current.Text is "From" or "To" && Peek(1).Text != ":")+ if (Current.Text is "From" or "from" or "To" or "to" && Peek(1).Text != ":"){ExpressionSyntax? from = null, to = null;- if (Take("From")) from = EndpointReference();- if (Take("To")) to = EndpointReference();+ if (Take("From") || Take("from")) from = EndpointReference();+ if (Take("To") || Take("to")) to = EndpointReference();left = new TraceSyntax(left, from, to, Span(start)); continue;}if (left is SequenceSyntax && Current.Text is "x" or "y" or "z" or "normal" && Peek(1).Text == "[")@@ -424,7 +436,7 @@ public static class FirmamentSyntaxParserprivate static bool TryClause(string text, out ClauseKind kind){kind = text switch { "On" or "on" => ClauseKind.On, "Using" or "using" => ClauseKind.Using,- "Over" or "over" => ClauseKind.Over, "From" => ClauseKind.From, "Key" => ClauseKind.Key, _ => (ClauseKind)(-1) };+ "Over" or "over" => ClauseKind.Over, "From" or "from" => ClauseKind.From, "Key" => ClauseKind.Key, _ => (ClauseKind)(-1) };return (int)kind >= 0;}private IdentifierSyntax Identifier()diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.mdindex a4ffbe81..411cd108 100644--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md@@ -1,9 +1,17 @@# October 2026 Firmament language decision register+Directive/casing follow-up: [implementation and qualification](../release/FIRMAMENT-DIRECTIVES-AND-CASING.md)+closes the syntax review's ignored-include and schema-formatting witnesses.+Recommendations #1–#4 gain directive admission and located structured CLI errors;+#17 gains AST-bound symmetry field aliases and lowercase from/to links. The+24 original recommendations and broader deferred scopes remain preserved below.+This does not claim a universal module system or completed syntax reconciliation.+The October 14 [syntax review](FIRMAMENT-SYNTAX-REVIEW-2026-10.md) supplements-this register with twenty current language/teaching seams and exact execution-witnesses. Its ignored-include and schema-formatting findings remain open;-documentation repair does not implement recommendations #1–#4, #7 or #23.+this register with twenty language/teaching seams and exact execution witnesses.+Its initial documentation-only pass left include/schema findings open; the+implementation follow-up above supersedes that status. Documentation changes+alone did not implement recommendations #1–#4, #7 or #23.All 24 original recommendations and their historical dispositions are preservedbelow. Later production amendments supersede only the scopes they qualify.diff --git a/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md b/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.mdindex dde7a2ec..db3f8e4a 100644--- a/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md+++ b/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md@@ -1,5 +1,10 @@# Firmament syntax review — 2026-10-14+Implementation follow-up: the [directive/casing pass](../release/FIRMAMENT-DIRECTIVES-AND-CASING.md)+repairs S01 (symmetry fields), S02 (Profile/mirror links), S14 and S15.+It also repairs S13's dense mirror/override witness; specialized semicolon rules+elsewhere are unchanged. Original observations below remain pre-repair evidence.+## Purpose and boundaryThis review accompanies the rewrite of [Writing Firmament](../public/firmament/syntax.md).diff --git a/docs/development/firmament-language-inconsistencies.md b/docs/development/firmament-language-inconsistencies.mdindex a4d86272..576ec403 100644--- a/docs/development/firmament-language-inconsistencies.md+++ b/docs/development/firmament-language-inconsistencies.md@@ -1,5 +1,11 @@# Firmament language reconciliation register+The subsequent [directive/casing implementation](../release/FIRMAMENT-DIRECTIVES-AND-CASING.md)+repairs the review's mechanical include/schema witnesses, symmetry casing and+Profile endpoint links. Wider source-consumption and language-design questions+remain scoped in the current review; the historical classifications below do+not imply whole-language completion.+October 14 documentation review: the [current syntax review](FIRMAMENT-SYNTAX-REVIEW-2026-10.md)records twenty author-visible seams, including reproduced ignored mechanicalincludes, schema-formatting admission gaps and symmetry casing failures.diff --git a/docs/public/firmament/geometry.md b/docs/public/firmament/geometry.mdindex 40d5c07f..feed51ad 100644--- a/docs/public/firmament/geometry.md+++ b/docs/public/firmament/geometry.md@@ -133,7 +133,7 @@ The canonical [Boss + Pocket block](../../../fixtures/Canonical/Features/Boss/boFor readable local geometry, start with the [line/arc Concept Path](../../../fixtures/Canonical/Profiles/concept-path-line-arc-profile.firmament). The [profile-delta recess](../../../fixtures/Canonical/Profiles/profile-delta-recess-extrusion.firmament) then shows that semantic `ProfileDelta` programming is not Sheet-Metal-specific: a Table row, `with` override, and typed Template modify an ordinary extruded profile.-For geometry that already exposes named spans, prefer the finite [Profile pipeline flagship](../../../fixtures/Canonical/Pipeline/profile-pipeline-flagship.firmament). `Stock.Bottom |> Stock.Right |> Stock.Top |> Stock.Left |> Close` inherits segment identities and derives endpoint continuity and orientation from the named source geometry. The [mixed line/arc witness](../../../fixtures/Canonical/Pipeline/line-arc-profile.firmament), [inner-loop witness](../../../fixtures/Canonical/Pipeline/profile-with-inner-loop.firmament), [open Concept Path](../../../fixtures/Canonical/Pipeline/open-path.firmament), and [whole-loop trace](../../../fixtures/Canonical/Pipeline/traceloop-profile.firmament) exercise the same resolved Profile/Path boundary. Pipelines also support named endpoint selection with `From`/`To` and arc traversal with `Reverse`; see [syntax](syntax.md#constructing-from-a-layout). Use manual `Segment` declarations when deliberate low-level control or debugging requires them.+For geometry that already exposes named spans, prefer the finite [Profile pipeline flagship](../../../fixtures/Canonical/Pipeline/profile-pipeline-flagship.firmament). `Stock.Bottom |> Stock.Right |> Stock.Top |> Stock.Left |> Close` inherits segment identities and derives endpoint continuity and orientation from the named source geometry. The [mixed line/arc witness](../../../fixtures/Canonical/Pipeline/line-arc-profile.firmament), [inner-loop witness](../../../fixtures/Canonical/Pipeline/profile-with-inner-loop.firmament), [open Concept Path](../../../fixtures/Canonical/Pipeline/open-path.firmament), and [whole-loop trace](../../../fixtures/Canonical/Pipeline/traceloop-profile.firmament) exercise the same resolved Profile/Path boundary. Pipelines also support named endpoint selection with `from`/`to` and arc traversal with `Reverse`; see [syntax](syntax.md#constructing-from-a-layout). Use manual `Segment` declarations when deliberate low-level control or debugging requires them.Sheet Metal has its own `Hole Name` syntax for planar circular openings; countersink and counterbore forms are Model-domain features and deliberately fail in Sheet Metal rather than being ignored.diff --git a/docs/public/firmament/language-style.md b/docs/public/firmament/language-style.mdindex 5ac2aa0c..bbd10518 100644--- a/docs/public/firmament/language-style.md+++ b/docs/public/firmament/language-style.md@@ -11,7 +11,7 @@ global case folding. The [design proposal](casing-and-layout-proposal.md) record| 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`, `as`, `on`, `over`, `with`, `return`, `include`, `expose`, `bind` |+| Linking and scope word | lowercase | `using`, `as`, `from`, `to`, `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` |@@ -28,12 +28,15 @@ standards, imported identities and part numbers retain their source spelling.Existing PascalCase properties and supported historical aliases remain accepted,without style warnings. Older examples need not be rewritten wholesale.-The table describes preferred style, not universal case folding. Some owners-still require PascalCase built-ins: Profile pipeline `From`/`To`, `Reverse`,-`Close`, `TraceLoop`, mirror `From`/`Across`, and radial `Source`/`About`/`Count`/`Angle`.-Use those admitted forms today. The [syntax review](../../development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md)-tracks these gaps; the formatter must not be treated as proof that every owner-admits a lowercased spelling.+The table describes preferred style, not universal case folding. Profile endpoint+and mirror-header links prefer `from`/`to`, with `From`/`To` retained as aliases.+Mirror/radial fields prefer `across`, `source`, `about`, `count`, `angle`; their+PascalCase aliases bind to the same AST fields. Unknown and duplicate fields+reject. `Reverse`, `Close` and `TraceLoop` remain PascalCase geometry operations.+The formatter recognizes these linking/field positions structurally and preserves+authored identifiers. It does not impose this grammar on unrelated domain owners;+the [syntax review](../../development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md) tracks the+remaining differences. Formatting is still not proof of successful compilation.```firmamentFeature Coil(center: Point2, width: Length, depth: Length,@@ -59,8 +62,9 @@ V2 `Format` API also prefers these spellings while arranging layout, and checksboth token equivalence and parser admission. Imported modules use the conservativepass and their consuming project's compiler; they are not standalone parts.-Compatibility is scoped to schema-owned properties plus the bounded profile,-frame, assembly, point and wire vocabularies used by the guitar. The parser maps+Compatibility is scoped to schema-owned properties, AST-position Profile links+and symmetry fields, plus the bounded frame, assembly, point and wire+vocabularies used by the guitar. The parser mapsthese aliases back to existing semantic identities. Unknown blocks, Record andStatic data, explicit station keys, named template/Feature arguments and dottedmembers are not guessed or renamed by the formatter. Property completion acceptsdiff --git a/docs/public/firmament/revolve.md b/docs/public/firmament/revolve.mdindex 36a38e0b..7b74c2de 100644--- a/docs/public/firmament/revolve.md+++ b/docs/public/firmament/revolve.md@@ -38,7 +38,7 @@ Model RevolvedSphere {Concept Circle2 meridian { center: center; radius: 20mm }Line2 diameter { from: north; to: south }Profile sphereSection {- meridian From south To north as arc+ meridian from south to north as arc|> diameter as axisClosure|> Close}@@ -46,8 +46,8 @@ Model RevolvedSphere {}```-Pipeline endpoint words currently use `From`/`To`; fields such as `from:` use-camelCase. See [Writing Firmament](syntax.md) for the distinction and conventions.+Pipeline endpoint links prefer `from`/`to`, with `From`/`To` retained as aliases.+See [Writing Firmament](syntax.md) for the distinction from fields such as `from:`.## Anglesdiff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 57f28c08..592ab9f5 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -99,7 +99,7 @@ because the preferred local name is camelCase.| Constructs and types | PascalCase | `Model`, `Box`, `Feature`, `Length`, `Point2` || Built-in fields | camelCase | `units`, `size`, `counterboreDepth` || Local geometry, values and parameters | camelCase | `stock`, `outline`, `mountPoint`, `depth` |-| Linking words in their admitted positions | lowercase | `using`, `as`, `on`, `over`, `with`, `include`, `expose`, `bind` |+| Linking words in their admitted positions | lowercase | `using`, `as`, `from`, `to`, `on`, `over`, `with`, `include`, `expose`, `bind` || Engineering symbols and enum values | Preserve domain spelling | `XY`, `+Z`, `Outer`, `ThroughAll`, `World`, `mm` |`Profile outline using layout` selects a construction context;@@ -107,12 +107,13 @@ because the preferred local name is camelCase.accepted aliases at those positions. A header clause such as`Concept Struct layout on XY` differs from a field such as `on: +Z`.-This convention is not global case-insensitive parsing. Owners admit many-PascalCase field aliases, but some still **require** particular spellings.-Use `From`, `To`, `Reverse`, `Close` and `TraceLoop` in Profile pipelines.-Symmetry currently requires `From`, `Across`, `Source`, `About`, `Count` and-`Angle` in the forms below. Do not lowercase them merely to match the style table.-See [language style](language-style.md) for formatter behavior.+This convention is not global case-insensitive parsing. Profile endpoint links+use `from`/`to`; `From`/`To` remain accepted aliases. Mirror headers use `from`.+Symmetry fields use `across`, `source`, `about`, `count` and `angle`, with their+PascalCase aliases retained. These positions bind through the shared AST, which+keeps authored names and members unchanged. Geometry operations `Reverse`,+`Close` and `TraceLoop` remain PascalCase, like other constructs. See+[language style](language-style.md) for formatter behavior and domain scope.### Whitespace, comments and terminators@@ -120,9 +121,9 @@ Use two-space indentation. Put ordinary fields on separate lines, or separatethem with semicolons in a short body. Separate list elements and call argumentswith commas. Do not rely on the parser guessing dense adjacent field boundaries.-Use `//` for comments, including before an optional `schema` header. The shared-lexer also recognizes `/* ... */`, but the schema selector currently rejects a-block comment before that header. `#` is not a general comment marker.+Use `//` or `/* ... */` for comments, including before an optional `schema`+header or after its name. Comments do not disable schema selection. `#` is not+a general comment marker.Some specialized forms **require** semicolons: scalar Function expressions,point-recipe fields, PMI Note fields and Assembly root-provenance statements.@@ -196,10 +197,10 @@ ordinary profiles can use pipelines.and points already declared:**```firmament-guide From startPoint To endPoint as selectedEdge+guide from startPoint to endPoint as selectedEdge```-After the opening stage, `guide To endPoint` uses the preceding endpoint as its+After the opening stage, `guide to endPoint` uses the preceding endpoint as itsstart. Endpoints must be named points on the guide. Circular spans use the sameform; `Reverse` selects the opposite traversal. `|>` is not a general map, filter,arithmetic or function-composition operator. A Concept Path may remain open;@@ -336,7 +337,7 @@ have different Pattern forms:| Named Set mapped to a Feature | `Pattern name over values { value => Recipe(value) }` || Semantic PointSet / Grid | `Pattern name { Source: layout.Points ... Item ... }` || Record array with finite feature Template | `Pattern name over records { Recipe<Current> }` |-| Radial feature symmetry | `Radial Pattern name { Source: seed About: axis Count: n Angle: full }` |+| Radial feature symmetry | `Radial Pattern name { source: seed; about: axis; count: n; angle: full }` |These are context-specific forms, not interchangeable spellings of one loop.`Item`, `Current` and an explicit element name are not global aliases. See@@ -376,18 +377,18 @@ general `if`/`else` control flow. Use domain-specific forms only where admitted.## Mirror and radial symmetrySymmetry transforms semantic construction before materialization. It does not-mirror a finished STEP/BRep. These fragments use the **currently required**-PascalCase symmetry fields, despite the general camelCase field convention.+mirror a finished STEP/BRep. Its headers and fields follow the same lowercase+link / camelCase field conventions as ordinary mechanical construction.**Fragment — inside Modify, with a concrete `leftMount` Hole and a model-level`centerPlane` already declared:**```firmament-Mirrored Feature rightMount From leftMount { Across: centerPlane }-Feature largerMount = rightMount with { Diameter: 8mm }+Mirrored Feature rightMount from leftMount { across: centerPlane }+Feature largerMount = rightMount with { diameter: 8mm }```-`Mirrored Profile result From source { Across: plane }` derives a Profile.+`Mirrored Profile result from source { across: plane }` derives a Profile.Reflection transforms curves, restores loop winding and reconstructs aright-handed frame. Construction Planes traced from Concept Planes are admittedin the Profile form. Material, scalar magnitudes and enum tags are invariant;@@ -400,10 +401,10 @@ feature with an unchanged center rejects as a redundant coincident feature.**Fragment — inside Modify, with `boltSeed` and a model-level `mainAxis`:**```firmament-Radial Pattern boltCircle { Source: boltSeed About: mainAxis Count: 6 Angle: full }+Radial Pattern boltCircle { source: boltSeed; about: mainAxis; count: 6; angle: full }```-The source is instance zero. `Count` is 1..1024. A full circle uses+The source is instance zero. `count` is 1..1024. A full circle uses`theta[i] = i * 2*pi/Count`, without a duplicate endpoint. A partial angle includesboth endpoints: `theta[i] = i * Angle/(Count-1)` when Count exceeds one. Anglesaccept the Revolve spellings `radians`, `deg`, `quarter`, `half`, `full`.@@ -416,12 +417,13 @@ Complete sources: [mirrored hole](../../../fixtures/Canonical/Symmetry/mirrored-## Choosing a domain and organizing files-An optional `schema Name` header selects one of these frontends. Put it on its-own line before declarations, preceded only by blank lines or `//` comments.-Do not put a trailing comment on the selector line: selection can currently be-bypassed by that formatting. Names are case-sensitive. A recognized explicit-selection is authoritative; rejection does not retry another frontend.-Revolve is an operation in Mechanical, not a schema.+An optional `schema Name` header selects one of these frontends. Declare it once,+before other directives or declarations. Prefer a separate line for readability;+inline declarations and leading/trailing comments also retain schema selection.+Names are case-sensitive. Unknown names, duplicate or nested/late headers and+mismatched domains reject; rejection does not retry another frontend. Revolve+is an operation in Mechanical, not a schema. Template specialization must also+remain within the selected domain; it cannot change the schema after admission.| Schema | Guide || --- | --- |@@ -447,9 +449,10 @@ Do not invent `schema Assembly` or wrap arbitrary domain declarations in a ModelAssembly occurrence trees use `<Assembly>` / `<Part>` tags as well as bracebodies. Tree nesting does not create a Mate. Inclusion is owned by the consumingproject/domain; `include` is **not** a universal mechanical preprocessor.-A bare include before an ordinary mechanical Model can currently be ignored,-even when its file is missing. Use a documented include consumer; the review-below preserves this reproduction.+Standalone part compilation rejects an unresolved include explicitly, even if+the named file exists. Use a documented Assembly/project loader to resolve file+dependencies before part compilation. The shipped `Use Profile.Modifications`+import retains its existing library owner. Other unconsumed directives reject.## Reading older source@@ -477,9 +480,10 @@ angle brackets and `with`. Some are legitimate domain distinctions; others arecompatibility debt or bugs.The [October syntax review](../../development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md)-records witnesses, current behavior, ownership and open decisions. It includes-the ignored mechanical include and schema-comment failures. It describes the-language as it exists, not unimplemented syntax. The [decision register](../../development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md)+records the original witnesses and their subsequent repair status, ownership+and open decisions. The include, schema-header and symmetry casing repairs are+described in the [implementation report](../../release/FIRMAMENT-DIRECTIVES-AND-CASING.md).+The [decision register](../../development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md)preserves the original authoring audit and later migration dispositions.Use [supported features](../reference/supported-features.md) for capabilitydiff --git a/docs/release/FIRMAMENT-DIRECTIVES-AND-CASING.md b/docs/release/FIRMAMENT-DIRECTIVES-AND-CASING.mdnew file mode 100644index 00000000..87c65f77--- /dev/null+++ b/docs/release/FIRMAMENT-DIRECTIVES-AND-CASING.md@@ -0,0 +1,152 @@+# Firmament directive admission and AST casing++## Result and scope++This pass repairs the ignored mechanical include and schema-formatting failures+from the [October syntax review](../development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md).+It reconciles Profile endpoint links and symmetry fields through the shared AST,+while retaining the existing engineering transforms and materializers.+Qualification evidence is recorded below; this is not whole-language migration+acceptance.++## Language decisions++| Role | Preferred source | Compatibility / limits |+| --- | --- | --- |+| Constructs and types | PascalCase: Model, Feature, Point2 | Existing admitted grammar aliases remain. No arbitrary case folding. |+| Built-in fields | camelCase, including symmetry `across/source/about/count/angle` | PascalCase aliases read the same AST field; duplicate alias pairs reject. |+| Linking words | Lowercase, including pipeline `from/to` and mirror `from` | From/To remain admitted aliases. Rewriting applies only at AST linking positions. |+| Geometry operations | `Reverse`, `Close`, `TraceLoop` | Kept PascalCase as operations, not connecting words. |+| Authored names / domain symbols | Preserve exact spelling | Parameters, Record members, published geometry names, XY, +Z, ThroughAll and schema names are not folded. |+| Schema | One leading document directive | Comments, newlines, a trailing comment and same-line declarations do not disable selection. Unknown, late, nested, duplicate and mismatched selectors reject. |+| Include | Resolved by the documented project/domain consumer | Standalone part compilation rejects any unconsumed include, even if its target exists. No new mechanical module loader. |+| Shipped Profile import | `Use Profile.Modifications` | Existing owner retained; AST-recognized imports are consumed there. Unknown/unowned Use directives reject. |++No decision in this pass requires user input. Point/list policy, Pattern binder+unification, general units/root rules and broader expression consolidation remain+separate work in the syntax review. They are not being deferred because an+approval or product choice is missing.++## Repairs and ownership++- Schema selection reads DirectiveSyntax from the shared parser instead of+ matching whole lines. The original token spans survive selector erasure.+ A native material declaration also cannot be compiled under an incompatible+ specialized selector. Validation carries the authored schema through normal+ engineering preflight rather than compiling only the header-stripped source.+ Direct Loft/SectionChain entry points consume the same selector before material+ binding, including file-backed and source-snapshot assembly definitions.+ The selected schema is retained as compilation context across specialization,+ and the bound engineering owner identifies its admitted domain independently+ of debug parser-route names. The same domain rule gates expanded input before+ geometry execution. A Template-produced Revolve under WireForm rejects, including+ parse-only validation; it succeeds when explicitly selected as Mechanical.+ Parse-cache keys include the schema context, so the same resolved source cannot+ reuse admission from another frontend.+- Part admission requires consumption of every directive before expansion.+ Unsupported includes fail with `firmament-v2-directive-unconsumed`, a source+ span and an explanation of the project-loader boundary. The existing Assembly+ and source-snapshot loaders retain their authority.+- Profile.Modifications imports use AST spans. Comment/string contents cannot+ trigger the import. This removes its old source-wide import regex.+- Mirror/radial headers, fields, Plane/Axis inputs, seed centers and feature+ overrides bind from AST nodes. Consumed scopes close against unknown and+ duplicate fields. Transform math, instance identities and engineering+ capability limits remain with their existing owners.+ Concept-derived planes retain Concept IR resolution and enter it through the+ same established spelling boundary, rather than a second plane evaluator.+- Profile/Path pipeline expressions are consumed from the shared AST. Endpoint+ links and alias positions are recognized structurally; calls and arithmetic+ are still rejected as pipeline stages. Inline guide extraction and other+ unmodified profile adapters retain their existing bounded ownership.+- Feature overrides replace the exact parsed value span. Dense adjacent seed+ fields no longer let an override consume a following termination field.+- CLI schema failures use the structured validation diagnostic contract in both+ validate and build; the language service projects original directive spans.++The source formatter projects the symmetry owner's field vocabulary and AST+link positions. It does not maintain a second symmetry field schema or rename+authored members. In particular, adding a lowercase `from` link does not reserve+an existing authored name such as `Box from`. Remaining regex use in the modified symmetry owner is only+the preexisting generated-identifier sanitization; header/field extraction and+brace scanning have been removed. Negative string fast paths only avoid parsing+when the relevant keyword is absent; they grant no admission.++## Qualification++Expanded focused Release checks: 144 compiler/parser tests and 19 CLI tests passed.+These include normal validate/build rejection, parse-only directive rejection,+comments/spacing, all six existing symmetry fixtures, alias geometry parity,+published identities, unknown/duplicate fields, malformed directives, direct+Loft/snapshot compatibility, authored `from` names and the dense override witness.+The specialization regression verifies both rejection under WireForm and a real+successful build under Mechanical; it also checks schema-specific cache admission+and rejection of a caller context that conflicts with an authored header.+See the [compiler regressions](../../Aetheris.Kernel.Firmament.Tests/FirmamentDirectiveAndCasingTests.cs)+and [CLI regressions](../../Aetheris.CLI.Tests/FirmamentDirectiveCliTests.cs).++All ten pre-change Release STEP hashes match byte-for-byte after rebuilding:+the six canonical symmetry files, preferred-profile-links, through-hole,+generic-mounting-plate and pattern-feature-map. The+[baseline](../../artifacts/local/firmament-directives-casing/baseline.json) and+[comparison](../../artifacts/local/firmament-directives-casing/step-parity.json)+are ignored local evidence. Alias tests additionally compare the new preferred+spellings to their retained PascalCase sources. All five complete examples in+syntax.md and revolve.md compile through the normal in-memory engineering path.++The required fast lane passed 1,068 tests. The solution Release build succeeded;+its existing nullable/analyzer/platform and SQLite WebAssembly warnings remain.++The full solution lane passed **4,775 tests across 20 test assemblies, zero+failures or skips**, including all 2,326 Firmament tests. Commands ran serially:++```sh+dotnet build Aetheris.slnx -c Release --no-restore -m:1 -nr:false -p:UseSharedCompilation=false+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build -m:1 -nr:false --filter "Category!=SlowCorpus" -- RunConfiguration.MaxCpuCount=1+dotnet test Aetheris.slnx -c Release --no-build -m:1 -nr:false -- RunConfiguration.MaxCpuCount=1+```++MSBuild node reuse and the CLI build server were disabled for these runs. The+existing FrictionLab test project reports no discoverable tests; it is not+included among the 20 executed test assemblies. The full lane includes the+corpus tests omitted by the fast lane. Final logs are under ignored+`artifacts/local/firmament-directives-casing/`.++Seven [real CLI showcase checks](../../artifacts/local/firmament-directives-casing/cli-showcases.json)+also passed, using each domain's documented consuming path:++| Source | Command / evidence |+| --- | --- |+| Threaded hex bolt | `validate`, valid / Built. |+| GuitarX0 | `asm inspect`, success through the Assembly project loader. |+| Industrial ATLAS | `asm inspect`, success through the Assembly project loader. |+| Warm-modern house | `scene inspect`, success. |+| FactoryX0 | `scene inspect`, success. |+| Four-wall sheet-metal tray Template | `validate`, valid. |+| Hole-diameter / datum PMI example | `validate`, valid / Built. |++Assembly includes are intentionally exercised through `asm inspect`, rather than+the standalone-part `validate` command. Scene inspection is not a new claim of+manufacturing simulation or a pre/post hash comparison for every Scene artifact.+The byte-identical geometry claim is bounded to the ten recorded STEP files;+the full regression suite supplies broader existing behavior coverage.++Documentation relative links, balanced fences and `git diff --check` pass.+Runtime inspection after qualification found zero remaining dotnet, testhost,+MSBuild or VBCSCompiler processes. No background service was created.++## Remaining boundaries++This is not a new AST expansion engine, a universal include system, a global+capitalization migration or an additional parser route for geometry. Existing+Template/Feature/Pattern expansion and other domain frontends retain their+documented owners. Explicit serialization-shaped V1 compatibility remains+separate. The historical review witnesses remain preserved as pre-repair evidence.++## Verdict++**Success for this pass.** The known ignored-include and schema-formatting+witnesses fail truthfully, schema trivia cannot bypass selection, and preferred+Profile/symmetry spelling binds through AST ownership with retained aliases.+The recorded accepted STEP outputs remain identical. No deferred item awaits a+user decision; the wider syntax review remains the register for subsequent work.diff --git a/fixtures/Regression/FrontendDirectives/ignored-include.firmament b/fixtures/Regression/FrontendDirectives/ignored-include.firmamentnew file mode 100644index 00000000..59abab77--- /dev/null+++ b/fixtures/Regression/FrontendDirectives/ignored-include.firmament@@ -0,0 +1,5 @@+include "__missing_syntax_review__.firmament";+Model Example {+ units: mm+ Box stock { size: [30mm, 20mm, 6mm] }+}diff --git a/fixtures/Regression/FrontendDirectives/malformed-include.firmament b/fixtures/Regression/FrontendDirectives/malformed-include.firmamentnew file mode 100644index 00000000..c7c24383--- /dev/null+++ b/fixtures/Regression/FrontendDirectives/malformed-include.firmament@@ -0,0 +1,5 @@+include ;+Model Example {+ units: mm+ Box stock { size: [30mm, 20mm, 6mm] }+}diff --git a/fixtures/Regression/FrontendDirectives/schema-block-comment.firmament b/fixtures/Regression/FrontendDirectives/schema-block-comment.firmamentnew file mode 100644index 00000000..c3981106--- /dev/null+++ b/fixtures/Regression/FrontendDirectives/schema-block-comment.firmament@@ -0,0 +1,6 @@+/* A leading comment must not change the language. */+schema Mechanical // a trailing comment is also trivia+Model Example {+ units: mm+ Box stock { size: [30mm, 20mm, 6mm] }+}diff --git a/fixtures/Regression/FrontendDirectives/schema-comment-unknown.firmament b/fixtures/Regression/FrontendDirectives/schema-comment-unknown.firmamentnew file mode 100644index 00000000..b93289e4--- /dev/null+++ b/fixtures/Regression/FrontendDirectives/schema-comment-unknown.firmament@@ -0,0 +1,5 @@+schema DoesNotExist // selector+Model Example {+ units: mm+ Box stock { size: [30mm, 20mm, 6mm] }+}diff --git a/fixtures/Regression/FrontendDirectives/schema-inline-unknown.firmament b/fixtures/Regression/FrontendDirectives/schema-inline-unknown.firmamentnew file mode 100644index 00000000..03fab85d--- /dev/null+++ b/fixtures/Regression/FrontendDirectives/schema-inline-unknown.firmament@@ -0,0 +1,4 @@+schema DoesNotExist Model Example {+ units: mm+ Box stock { size: [30mm, 20mm, 6mm] }+}diff --git a/fixtures/Regression/FrontendDirectives/schema-inline-wire.firmament b/fixtures/Regression/FrontendDirectives/schema-inline-wire.firmamentnew file mode 100644index 00000000..a0363996--- /dev/null+++ b/fixtures/Regression/FrontendDirectives/schema-inline-wire.firmament@@ -0,0 +1,4 @@+schema WireForm Model Example {+ units: mm+ Box stock { size: [30mm, 20mm, 6mm] }+}diff --git a/fixtures/Regression/FrontendDirectives/schema-template-mismatch.firmament b/fixtures/Regression/FrontendDirectives/schema-template-mismatch.firmamentnew file mode 100644index 00000000..91d33d71--- /dev/null+++ b/fixtures/Regression/FrontendDirectives/schema-template-mismatch.firmament@@ -0,0 +1,18 @@+schema WireForm++Template<>+Model SphereFamily {+ 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 section {+ meridian from south to north as arc |> diameter as closure |> Close+ }+ Revolve ball { profile: section; about: mainAxis; angle: full }+}++Model Example = SphereFamily<>