Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Refine Firmament geometry modeling and validation

Yuechen Li83855e9107c6
diff --git a/Aetheris.CLI.Tests/FirmamentFrontendX0CliTests.cs b/Aetheris.CLI.Tests/FirmamentFrontendX0CliTests.cs
index 0b0a09d1..41df238c 100644
--- a/Aetheris.CLI.Tests/FirmamentFrontendX0CliTests.cs
+++ b/Aetheris.CLI.Tests/FirmamentFrontendX0CliTests.cs
@@ -9,6 +9,8 @@ public sealed class FirmamentFrontendX0CliTests
[InlineData("unknown-model-statement")]
[InlineData("unknown-modify-statement")]
[InlineData("unknown-box-field")]
+ [InlineData("unknown-compose-statement")]
+ [InlineData("unknown-boundary-field")]
[InlineData("unsupported-xz-layout")]
[InlineData("combined-fillet-hole")]
[InlineData("unresolved-semantic-source")]
@@ -40,7 +42,7 @@ public sealed class FirmamentFrontendX0CliTests
var stdout = new StringWriter();
Assert.Equal(0, CliRunner.Run(["validate", Fixture("combined-fillet-hole"), "--parse-only", "--explain"], stdout, new StringWriter()));
Assert.Contains("parsed-not-built", stdout.ToString(), StringComparison.Ordinal);
- Assert.Contains("Canonical", stdout.ToString(), StringComparison.Ordinal);
+ Assert.Contains("UnifiedMechanical", stdout.ToString(), StringComparison.Ordinal);
Assert.Contains("ParsedNotBuilt", stdout.ToString(), StringComparison.Ordinal);
}
diff --git a/Aetheris.CLI.Tests/FirmamentFrontendX1CliTests.cs b/Aetheris.CLI.Tests/FirmamentFrontendX1CliTests.cs
new file mode 100644
index 00000000..57d03478
--- /dev/null
+++ b/Aetheris.CLI.Tests/FirmamentFrontendX1CliTests.cs
@@ -0,0 +1,50 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class FirmamentFrontendX1CliTests
+{
+ [Fact]
+ public void Explain_ProductionRejectsStructurallyRecognizedUnsupportedIntent()
+ {
+ var stdout = new StringWriter();
+ var source = Fixture("Regression/FrontendX0/unknown-compose-statement.firmament");
+ Assert.Equal(1, CliRunner.Run(["validate", source, "--shadow", "--explain", "--json"], stdout, new StringWriter()));
+ using var json = JsonDocument.Parse(stdout.ToString());
+ var root = json.RootElement; var shadow = root.GetProperty("shadow");
+ Assert.Equal("Parsed", shadow.GetProperty("shadowStatus").GetString());
+ Assert.Equal("StructuralOnlyUnbound", shadow.GetProperty("validationLevel").GetString());
+ Assert.Equal("UnifiedMechanical", shadow.GetProperty("productionProjection").GetProperty("parserRoute").GetString());
+ Assert.False(shadow.GetProperty("comparison").GetProperty("semanticParityQualified").GetBoolean());
+
+ Assert.Equal("invalid", root.GetProperty("productionValidation").GetProperty("firmamentV2Validation").GetProperty("status").GetString());
+ Assert.Equal(JsonValueKind.Null, root.GetProperty("ast").ValueKind);
+ }
+
+ [Fact]
+ public void ExplicitAst_ContainsOriginalFieldsAndSpans()
+ {
+ var stdout = new StringWriter();
+ Assert.Equal(0, CliRunner.Run(["frontend-shadow", Fixture("Regression/FrontendX0/unknown-boundary-field.firmament"), "--ast"], stdout, new StringWriter()));
+ using var json = JsonDocument.Parse(stdout.ToString());
+ Assert.Equal(JsonValueKind.Object, json.RootElement.GetProperty("ast").ValueKind);
+ Assert.Contains("heigth", json.RootElement.GetProperty("ast").GetRawText());
+ Assert.Contains("\"span\"", json.RootElement.GetProperty("ast").GetRawText());
+ }
+
+ [Fact]
+ public void StructuralFailure_IsNotMaskedByProductionProjection()
+ {
+ var stdout = new StringWriter();
+ Assert.Equal(1, CliRunner.Run(["frontend-shadow", Fixture("Regression/FrontendX1/malformed-field.firmament"), "--json"], stdout, new StringWriter()));
+ using var json = JsonDocument.Parse(stdout.ToString());
+ var shadow = json.RootElement.GetProperty("shadow");
+ Assert.Equal("Rejected", shadow.GetProperty("shadowStatus").GetString());
+ var diagnostic = Assert.Single(shadow.GetProperty("diagnostics").EnumerateArray());
+ Assert.Equal("Syntax", diagnostic.GetProperty("stage").GetString());
+ Assert.Equal("Box Body", diagnostic.GetProperty("target").GetString());
+ Assert.Equal(2, diagnostic.GetProperty("line").GetInt32());
+ }
+
+ private static string Fixture(string relative) => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures", relative));
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 8347a49a..01ab78ce 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -136,7 +136,7 @@ public static class CliRunner
private const string TopLevelUsage = "Usage: aetheris <command> [options]";
private const string BuildUsage = "Usage: aetheris build <file.firmament|file.firmasm> [--output <path>] [--json]";
private const string MeshUsage = "Usage: aetheris mesh <file.firmament|file.firmfixture|file.firmasm|file.step> [--format stl|obj|assembly-json] [--output <path>] [--debug-ir <path>] [--json]";
- private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--forge-pack <path>] [--parse-only] [--explain] [--json]";
+ private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--forge-pack <path>] [--parse-only] [--explain] [--shadow [--ast]] [--json]";
private const string InspectProfileUsage = "Usage: aetheris inspect-profile <file.firmament> [--json]";
private const string InspectSpansUsage = "Usage: aetheris inspect-spans <file.firmament> --json";
private const string InspectComposeUsage = "Usage: aetheris inspect-compose <file.firmament> --json [--materialize]";
@@ -218,6 +218,7 @@ public static class CliRunner
"build" => RunBuild(args.Skip(1).ToArray(), stdout, stderr),
"mesh" => RunMesh(args.Skip(1).ToArray(), stdout, stderr),
"validate" => RunValidate(args.Skip(1).ToArray(), stdout, stderr),
+ "frontend-shadow" => FrontendShadowCommand.Run(args.Skip(1).ToArray(), stdout, stderr),
"format" => RunFormat(args.Skip(1).ToArray(), stdout, stderr),
"inspect" => RunInspect(args.Skip(1).ToArray(), stdout, stderr),
"inspect-3dm" => ThreeDmCli.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),
@@ -2301,6 +2302,8 @@ Model CanonicalPanel {
var json = false;
var explain = false;
var parseOnly = false;
+ var shadow = false;
+ var shadowAst = false;
var forgePackPaths = new List<string>();
for (var i = 1; i < args.Length; i++)
{
@@ -2316,6 +2319,12 @@ Model CanonicalPanel {
case "--explain":
explain = true;
break;
+ case "--shadow":
+ shadow = true;
+ break;
+ case "--ast":
+ shadowAst = true;
+ break;
case "--parse-only":
parseOnly = true;
break;
@@ -2339,6 +2348,12 @@ Model CanonicalPanel {
return 1;
}
+ if (shadowAst && !shadow) { stderr.WriteLine("--ast requires --shadow."); return 1; }
+ if (shadow)
+ {
+ if (forgePackPaths.Count > 0 || parseOnly) { stderr.WriteLine("--shadow uses normal production validation; --forge-pack/--parse-only are not supported together with it."); return 1; }
+ return FrontendShadowCommand.Run([sourcePath, "--validate", .. (json ? new[] { "--json" } : []), .. (shadowAst ? new[] { "--ast" } : [])], stdout, stderr);
+ }
var validationSource=File.ReadAllText(sourcePath);
if (Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.HasRoot(validationSource)
|| FirmamentFrontendSchemas.Select(validationSource).Schema == FirmamentFrontendSchema.Garment)
@@ -5160,6 +5175,8 @@ Model CanonicalPanel {
stdout.WriteLine(ValidateUsage);
stdout.WriteLine(" --json Emit Firmament V2 validation report JSON, including validation level and parser route.");
stdout.WriteLine(" --explain Show V2 parser route, admission level and available instance counts.");
+ stdout.WriteLine(" --shadow Developer report with separate original-source AST, bounded comparison and normal production validation.");
+ stdout.WriteLine(" --ast Include the detailed AST with --shadow. Structural parsing does not establish semantic admission.");
stdout.WriteLine(" --parse-only Check static semantics only; success is labelled parsed-not-built.");
stdout.WriteLine(" --forge-pack <path> Load a trusted local .NET assembly containing IForgeConceptPack implementations. This executes local code; Aetheris does not sandbox external packs. Do not load untrusted packs.");
}
diff --git a/Aetheris.CLI/ConceptStepMatcher.cs b/Aetheris.CLI/ConceptStepMatcher.cs
index 0c6e223d..f44038c6 100644
--- a/Aetheris.CLI/ConceptStepMatcher.cs
+++ b/Aetheris.CLI/ConceptStepMatcher.cs
@@ -35,7 +35,7 @@ public static class ConceptStepMatcher
tolerances ??= new ConceptStepTolerance();
var source = File.ReadAllText(conceptPath);
var roles = ParseRoles(source);
- var parse = FirmamentV2Parser.Parse(StripMatchBlocks(source));
+ var parse = FirmamentV2Parser.Parse(source);
if (!parse.IsSuccess || parse.Document?.ConceptIr is null)
return new(ConceptStepOverallStatus.InvalidConcept, "<unresolved>", "body-0", tolerances, new { }, [], parse.Diagnostics);
@@ -146,8 +146,6 @@ public static class ConceptStepMatcher
}
return roles;
}
- private static string StripMatchBlocks(string source) { var result = source; foreach (Match m in Regex.Matches(source, @"\bMatch\s*\{")) { var open = source.IndexOf('{', m.Index); var close = BraceClose(source, open); if (close >= 0) result = result.Remove(open, close - open + 1).Insert(open, new string(' ', close - open + 1)); } return result; }
- private static int BraceClose(string text, int open) { var d = 0; for (var i = open; i < text.Length; i++) { if (text[i] == '{') d++; else if (text[i] == '}' && --d == 0) return i; } return -1; }
private static ConceptIrVector3 Axis(string value) => value switch { "+X" => new(1, 0, 0), "-X" => new(-1, 0, 0), "+Y" => new(0, 1, 0), "-Y" => new(0, -1, 0), "+Z" => new(0, 0, 1), _ => new(0, 0, -1) };
private static Point3D ToPoint(ConceptIrPoint3 p) => new(p.X, p.Y, p.Z);
private static Vector3D Normalize(ConceptIrVector3 v) => Normalize(new Vector3D(v.X, v.Y, v.Z));
diff --git a/Aetheris.CLI/FrontendShadowCommand.cs b/Aetheris.CLI/FrontendShadowCommand.cs
new file mode 100644
index 00000000..a967df1a
--- /dev/null
+++ b/Aetheris.CLI/FrontendShadowCommand.cs
@@ -0,0 +1,120 @@
+using System.Diagnostics;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+namespace Aetheris.CLI;
+
+/// <summary>Developer-only collection. Production validation remains in CliRunner;
+/// this command never grants permission to build and never writes geometry.</summary>
+internal static class FrontendShadowCommand
+{
+ private static readonly JsonSerializerOptions Json = new()
+ {
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true, MaxDepth = 1024,
+ Converters = { new JsonStringEnumConverter() }
+ };
+ private sealed record Measurement(double ParseMilliseconds, long ParseAllocatedBytes);
+ private sealed record Benchmark(int Iterations, int SourceCharacters, double MedianMilliseconds, double P95Milliseconds, long MedianAllocatedBytes);
+ private sealed record Entry(string Source, string SourceGroup, FirmamentShadowReport Shadow,
+ Measurement Measurement, Benchmark? Benchmark, JsonElement? ProductionValidation, int? ProductionExitCode, DocumentSyntax? Ast);
+
+ public static int Run(string[] args, TextWriter stdout, TextWriter stderr)
+ {
+ if (args.Length == 0 || args[0] is "--help" or "-h")
+ {
+ stdout.WriteLine("Usage: aetheris frontend-shadow <file> [--json] [--ast] [--validate] [--benchmark]");
+ stdout.WriteLine(" aetheris frontend-shadow --corpus <directory> [--output-dir <directory>]");
+ stdout.WriteLine("Developer syntax evidence. Structural success alone does not grant engineering admission; normal mechanical validation uses the unified AST binder.");
+ return args.Length == 0 ? 1 : 0;
+ }
+ var corpus = args[0] == "--corpus";
+ var input = corpus && args.Length > 1 ? args[1] : args[0];
+ var json = false; var ast = false; var validate = false; var benchmark = false;
+ var output = Path.Combine("artifacts", "local", "frontend-x1", "corpus");
+ for (var i = corpus ? 2 : 1; i < args.Length; i++)
+ {
+ switch (args[i])
+ {
+ case "--json": json = true; break;
+ case "--ast": ast = true; break;
+ case "--validate": validate = true; break;
+ case "--benchmark": benchmark = true; break;
+ case "--output-dir" when i + 1 < args.Length: output = args[++i]; break;
+ default: stderr.WriteLine($"Unknown or incomplete shadow option '{args[i]}'."); return 1;
+ }
+ }
+ if (corpus)
+ {
+ if (!Directory.Exists(input)) { stderr.WriteLine($"Corpus directory not found: {input}"); return 1; }
+ if (ast || validate || benchmark) { stderr.WriteLine("Use --ast/--validate/--benchmark on individual files; corpus collection compares the generic production projection only."); return 1; }
+ var files = Directory.EnumerateFiles(input, "*", SearchOption.AllDirectories)
+ .Where(p => Path.GetExtension(p) is ".firmament" or ".firmfixture" or ".firmasm").Order(StringComparer.Ordinal).ToArray();
+ var entries = new List<Entry>();
+ foreach (var path in files) entries.Add(Analyze(path, false, false, false, Path.GetFullPath(input)));
+ var parsed = entries.Count(e => e.Shadow.ShadowStatus == "Parsed");
+ var summary = new { schemaVersion = 1, qualified = false, mode = "ShadowOnly", sourceCount = files.Length,
+ parsed, rejected = entries.Count - parsed, semanticParityQualified = false,
+ comparedFacts = entries.Sum(e => e.Shadow.Comparison.ComparedFacts),
+ differences = entries.Sum(e => e.Shadow.Comparison.Differences.Count), entries };
+ Directory.CreateDirectory(output);
+ File.WriteAllText(Path.Combine(output, "report.json"), JsonSerializer.Serialize(summary, Json));
+ var lines = new List<string> { "# Firmament X1 shadow collection", "", $"Sources: {files.Length}; structurally parsed: {parsed}; rejected: {entries.Count - parsed}.",
+ "", "Qualification: false. Generic production projection and bounded structural comparison only; no semantic or geometry parity claim.", "",
+ "| Source | Shadow | Production route | Facts compared | Differences |", "| --- | --- | --- | --- | --- |" };
+ lines.AddRange(entries.Select(e => $"| {e.Source} | {e.Shadow.ShadowStatus} | {e.Shadow.ProductionProjection.ParserRoute ?? "Unselected"} | {e.Shadow.Comparison.ComparedFacts} | {e.Shadow.Comparison.Differences.Count} |"));
+ File.WriteAllLines(Path.Combine(output, "report.md"), lines);
+ stdout.WriteLine($"Collected {files.Length} sources: {parsed} parsed, {files.Length - parsed} rejected. Semantic parity unqualified. Reports: {Path.GetFullPath(output)}");
+ return 0; // collection completed, not a qualification pass
+ }
+ if (!File.Exists(input)) { stderr.WriteLine($"Shadow input not found: {input}"); return 1; }
+ var entry = Analyze(input, ast, validate, benchmark, null);
+ if (json || ast) stdout.WriteLine(JsonSerializer.Serialize(entry, Json));
+ else
+ {
+ stdout.WriteLine($"Shadow: {entry.Shadow.ShadowStatus} ({entry.Shadow.ValidationLevel}); language: {entry.Shadow.LanguageVersion}; production projection route: {entry.Shadow.ProductionProjection.ParserRoute ?? "Unselected"}");
+ stdout.WriteLine($"Declarations: {entry.Shadow.Summary.DeclarationCount}; compared facts: {entry.Shadow.Comparison.ComparedFacts}; differences: {entry.Shadow.Comparison.Differences.Count}; semantic parity: unqualified.");
+ foreach (var d in entry.Shadow.Diagnostics) stderr.WriteLine($"{input}({d.Line},{d.Column}): {d.Severity} {d.Code}: {d.Message}");
+ foreach (var d in entry.Shadow.Comparison.Differences) stdout.WriteLine($"{d.Category} {d.Code}: {d.Message}");
+ if (validate) stdout.WriteLine($"Production validate exit code: {entry.ProductionExitCode}");
+ }
+ return entry.Shadow.ShadowStatus == "Rejected" || entry.ProductionExitCode == 1 ? 1 : 0;
+ }
+
+ private static Entry Analyze(string path, bool ast, bool validate, bool benchmark, string? corpusRoot)
+ {
+ var source = File.ReadAllText(path);
+ var allocated = GC.GetAllocatedBytesForCurrentThread();
+ var stopwatch = Stopwatch.StartNew();
+ var syntax = FirmamentSyntaxParser.Parse(source, path);
+ stopwatch.Stop();
+ var measurement = new Measurement(stopwatch.Elapsed.TotalMilliseconds, GC.GetAllocatedBytesForCurrentThread() - allocated);
+ Benchmark? timings = null;
+ if (benchmark)
+ {
+ _ = FirmamentSyntaxParser.Parse(source, path); // warm-up, no retained parse cache
+ var samples = new List<Measurement>();
+ for (var i = 0; i < 20; i++)
+ {
+ allocated = GC.GetAllocatedBytesForCurrentThread(); stopwatch.Restart();
+ _ = FirmamentSyntaxParser.Parse(source, path); stopwatch.Stop();
+ samples.Add(new(stopwatch.Elapsed.TotalMilliseconds, GC.GetAllocatedBytesForCurrentThread() - allocated));
+ }
+ timings = new(20, source.Length, samples.Select(s => s.ParseMilliseconds).Order().ElementAt(10),
+ samples.Select(s => s.ParseMilliseconds).Order().ElementAt(18), samples.Select(s => s.ParseAllocatedBytes).Order().ElementAt(10));
+ }
+ var production = FirmamentV2Parser.Parse(source, Path.GetDirectoryName(Path.GetFullPath(path)));
+ var report = FirmamentShadowAnalysis.Compare(syntax, production, source);
+ JsonElement? validation = null; int? exit = null;
+ if (validate)
+ {
+ var captured = new StringWriter(); var errors = new StringWriter();
+ exit = CliRunner.Run(["validate", path, "--json"], captured, errors);
+ using var document = JsonDocument.Parse(captured.ToString()); validation = document.RootElement.Clone();
+ }
+ var relative = corpusRoot is null ? path : Path.GetRelativePath(corpusRoot, Path.GetFullPath(path)).Replace('\\', '/');
+ var group = path.Replace('\\', '/').Split('/').FirstOrDefault(p => p is "Canonical" or "Regression" or "Compatibility" or "Speculative") ?? "Other";
+ return new(relative, group, report, measurement, timings, validation, exit, ast ? syntax.Document : null);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX0Tests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX0Tests.cs
index a7768ab1..9364b881 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX0Tests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX0Tests.cs
@@ -8,11 +8,11 @@ namespace Aetheris.Kernel.Firmament.Tests;
public sealed class FirmamentFrontendX0Tests
{
[Theory]
- [InlineData("malformed-v2", "Canonical")]
- [InlineData("unknown-model-statement", "Canonical")]
- [InlineData("unknown-modify-statement", "Canonical")]
- [InlineData("unknown-box-field", "Canonical")]
- [InlineData("unsupported-xz-layout", "StandaloneProfile")]
+ [InlineData("malformed-v2", "UnifiedMechanical")]
+ [InlineData("unknown-model-statement", "UnifiedMechanical")]
+ [InlineData("unknown-modify-statement", "UnifiedMechanical")]
+ [InlineData("unknown-box-field", "UnifiedMechanical")]
+ [InlineData("unsupported-xz-layout", "UnifiedMechanical")]
public void InvalidSource_IsRejectedByParserReportAndEngineeringCompiler(string fixture, string route)
{
var source = Read(fixture);
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX1Tests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX1Tests.cs
new file mode 100644
index 00000000..c286d28c
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX1Tests.cs
@@ -0,0 +1,222 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentFrontendX1Tests
+{
+ [Fact]
+ public void SharedLexer_IsLosslessAndPreservesNumericAndStringTokens()
+ {
+ var source = Read("lexical");
+ var parsed = Parse(source);
+ Assert.Equal(source, string.Concat(parsed.Document.Tokens.Select(t => t.Text)));
+ Assert.Equal(SyntaxTokenKind.End, parsed.Document.Tokens[^1].Kind);
+ Assert.Contains(parsed.Document.Tokens, t => t.Kind == SyntaxTokenKind.Number && t.Text == "1e-3");
+ Assert.Contains(parsed.Document.Tokens, t => t.Kind == SyntaxTokenKind.Number && t.Text == ".5");
+ Assert.Contains(parsed.Document.Tokens, t => t.Kind == SyntaxTokenKind.String && t.Text.Contains("// not a comment"));
+ foreach (var token in parsed.Document.Tokens)
+ Assert.Equal(token.Text, source.Substring(token.Span.Start, token.Span.Length));
+ Assert.Equal("StructuralOnlyUnbound", parsed.ValidationLevel);
+ }
+
+ [Theory]
+ [InlineData("fixtures/Canonical/Templates/nested-template-pmi.firmament")]
+ [InlineData("fixtures/Canonical/AssemblyInterfaces/GuitarX0/pickup.firmament")]
+ [InlineData("fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas/atlas-industrial.firmament")]
+ [InlineData("fixtures/Canonical/Scene/warehouse.firmament")]
+ [InlineData("fixtures/Canonical/Scene/WarmModernHouse/house.firmament")]
+ [InlineData("fixtures/Canonical/Symmetry/radial-bolt-circle.firmament")]
+ [InlineData("fixtures/Canonical/PMI/counterbore-shaft-diameter.firmament")]
+ [InlineData("fixtures/Canonical/Revolve/sphere.firmament")]
+ [InlineData("fixtures/Regression/CanonicalGeometry/profile-chamfer-reflex-junction-top.firmament")]
+ [InlineData("fixtures/Regression/ProfileComposition/valid/semantic-split-compose-chamfer.firmament")]
+ public void EstablishedSource_ProducesStructuredBodiesBeforeExpansion(string path)
+ {
+ var parsed = Parse(File.ReadAllText(Root(path)));
+ var declarations = FirmamentSyntaxEvidence.Declarations(parsed.Document).ToArray();
+ Assert.NotEmpty(declarations);
+ Assert.All(declarations, d => Assert.True(d.Span.Length > 0));
+ Assert.Equal(FirmamentSyntaxEvidence.Fingerprint(parsed.Document), FirmamentSyntaxEvidence.Fingerprint(Parse(File.ReadAllText(Root(path))).Document));
+ }
+
+ [Fact]
+ public void NestedGenericsAndTemplateBodies_AreStructuredNotOpaqueText()
+ {
+ var parsed = Parse(Read("nested-generics"));
+ var family = Assert.IsType<DeclarationSyntax>(Assert.Single(parsed.Document.Statements));
+ Assert.Equal("Struct", family.Type.Name.Text);
+ var template = Assert.Single(family.Modifiers);
+ Assert.Equal("Template", template.Name.Text);
+ var outer = Assert.IsType<SpecializationSyntax>(template.Arguments[0].Value);
+ Assert.IsType<SpecializationSyntax>(Assert.Single(outer.Arguments).Value);
+ Assert.NotNull(template.Arguments[1].Default);
+ Assert.Equal(2, family.Body!.Statements.Count);
+ var child = Assert.IsType<DeclarationSyntax>(family.Body.Statements[1]);
+ var invocation = Assert.IsType<SpecializationSyntax>(child.Initializer);
+ Assert.Equal("Spec", invocation.Arguments[0].Name!.Text);
+ Assert.IsType<SpecializationSyntax>(invocation.Arguments[0].Value);
+ }
+
+ [Fact]
+ public void Expressions_RetainPrecedenceCallsMemberIndexAndWithStructure()
+ {
+ var declarations = Parse(Read("expressions")).Document.Statements.Cast<DeclarationSyntax>().ToArray();
+ var add = Assert.IsType<BinarySyntax>(declarations[0].Initializer);
+ Assert.Equal(BinaryOperator.Add, add.Operator);
+ var multiply = Assert.IsType<BinarySyntax>(add.Right);
+ Assert.Equal(BinaryOperator.Multiply, multiply.Operator);
+ Assert.Equal(BinaryOperator.Power, Assert.IsType<BinarySyntax>(multiply.Right).Operator);
+ var point = Assert.IsType<CallSyntax>(declarations[1].Initializer);
+ var shifted = Assert.IsType<BinarySyntax>(point.Arguments[0].Value);
+ Assert.IsType<IndexSyntax>(Assert.IsType<MemberSyntax>(shifted.Left).Target);
+ Assert.IsType<WithSyntax>(declarations[2].Initializer);
+ Assert.Equal(BinaryOperator.Or, Assert.IsType<BinarySyntax>(declarations[3].Initializer).Operator);
+ }
+
+ [Theory]
+ [InlineData("unrelated-static")]
+ [InlineData("unrelated-slot")]
+ [InlineData("unrelated-pattern")]
+ [InlineData("unrelated-profile")]
+ public void UnrelatedSiblings_DoNotChangeAnyExistingSubtree(string sibling)
+ {
+ var source = File.ReadAllText(Root("fixtures/Regression/FrontendX0/combined-fillet-hole.firmament"));
+ var before = Assert.IsType<DeclarationSyntax>(Assert.Single(Parse(source).Document.Statements));
+ var insertion = Read(sibling) + "\n";
+ var afterSource = source.Insert(source.LastIndexOf('}'), insertion);
+ var after = Assert.IsType<DeclarationSyntax>(Assert.Single(Parse(afterSource).Document.Statements));
+ Assert.Equal(before.Body!.Statements.Select(FirmamentSyntaxEvidence.Normalize),
+ after.Body!.Statements.Take(before.Body.Statements.Count).Select(FirmamentSyntaxEvidence.Normalize));
+ // Offsets shift when inserted before the declaration as well.
+ var prefixed = Parse(insertion + source).Document.Statements.OfType<DeclarationSyntax>().Single(d => d.Type.Name.Text == "Model");
+ Assert.Equal(FirmamentSyntaxEvidence.Normalize(before), FirmamentSyntaxEvidence.Normalize(prefixed));
+ }
+
+ [Fact]
+ public void ProductionRejectsUnconsumedComposeIntent()
+ {
+ var source = File.ReadAllText(Root("fixtures/Regression/FrontendX0/unknown-compose-statement.firmament"));
+ var syntax = Parse(source);
+ var fillet = Assert.Single(FirmamentSyntaxEvidence.Declarations(syntax.Document), d => d.Type.Name.Text == "Fillet");
+ Assert.Equal("LostIntent", fillet.Name!.Text);
+ var rejected = FirmamentBuildAndExport.CompileSource(source);
+ Assert.False(rejected.IsSuccess);
+ Assert.Contains(rejected.Diagnostics, d => d.Message.Contains("Compose:Fillet", StringComparison.Ordinal));
+ var admitted = FirmamentV2Parser.Parse(source);
+ Assert.False(admitted.IsSuccess);
+ Assert.Equal("invalid", FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(admitted), source).Status);
+ var boundary = File.ReadAllText(Root("fixtures/Regression/FrontendX0/unknown-boundary-field.firmament"));
+ var shape = Assert.Single(FirmamentSyntaxEvidence.Declarations(Parse(boundary).Document), d => d.Name?.Text == "RecessGuide");
+ var unknown = Assert.Single(shape.Body!.Statements.OfType<FieldSyntax>(), f => f.Name.Text == "heigth");
+ Assert.Equal("heigth", boundary.Substring(unknown.Name.Span.Start, unknown.Name.Span.Length));
+ }
+
+ [Fact]
+ public void InvalidExpression_RejectsAndRecoversIntoNextDeclaration_WithOriginalLocation()
+ {
+ var source = Read("malformed-field");
+ var result = FirmamentSyntaxParser.Parse(source, "broken.firmament");
+ Assert.False(result.IsSuccess);
+ var diagnostic = Assert.Single(result.Diagnostics);
+ Assert.Equal("broken.firmament", diagnostic.SourceFile);
+ Assert.Equal(";", source.Substring(diagnostic.SourceSpan!.Start, diagnostic.SourceSpan.Length));
+ Assert.Equal(2, diagnostic.Line);
+ Assert.Equal("Box Body", diagnostic.Target);
+ Assert.Contains(FirmamentSyntaxEvidence.Declarations(result.Document), d => d.Name?.Text == "Retained");
+ }
+
+ [Theory]
+ [InlineData("/* unfinished")]
+ [InlineData("Static label = \"unfinished")]
+ public void UnterminatedLexerTokens_AreErrors(string source)
+ {
+ var result = FirmamentSyntaxParser.Parse(source);
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics, d => d.Code == "firmament-syntax-unterminated-token");
+ }
+
+ [Fact]
+ public void ExcessiveNesting_IsBoundedAndDiagnostic()
+ {
+ var source = "Static x = " + new string('(', 300) + "1" + new string(')', 300);
+ var result = FirmamentSyntaxParser.Parse(source);
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics, d => d.Code == "firmament-syntax-depth");
+ Assert.NotEmpty(FirmamentSyntaxEvidence.Fingerprint(result.Document));
+ }
+
+ [Fact]
+ public void MalformedOccurrence_RecoveryAdvancesPastUnexpectedScopeTokens()
+ {
+ var result = FirmamentSyntaxParser.Parse("<Assembly A> } </Assembly>");
+ Assert.False(result.IsSuccess);
+ Assert.Single(result.Diagnostics);
+ }
+
+ [Fact]
+ public void WrappingInModelOrStruct_PreservesTheExistingDeclaration()
+ {
+ var source = File.ReadAllText(Root("fixtures/Regression/FrontendX0/combined-fillet-hole.firmament"));
+ var box = Assert.Single(FirmamentSyntaxEvidence.Declarations(Parse(source).Document), d => d.Type.Name.Text == "Box");
+ var original = source.Substring(box.Span.Start, box.Span.Length);
+ foreach (var owner in new[] { "Model Wrapper", "Struct Wrapper" })
+ {
+ var wrapped = Assert.Single(FirmamentSyntaxEvidence.Declarations(Parse(owner + " {\n" + original + "\n}").Document), d => d.Type.Name.Text == "Box");
+ Assert.Equal(FirmamentSyntaxEvidence.Normalize(box), FirmamentSyntaxEvidence.Normalize(wrapped));
+ }
+ }
+
+ [Fact]
+ public void Comparison_DetectsActualRecordDimensionDifferences()
+ {
+ var source = File.ReadAllText(Root("fixtures/Canonical/Basics/box.firmament"));
+ var production = FirmamentV2Parser.Parse(source);
+ Assert.True(production.IsSuccess);
+ var solid = Assert.Single(production.Document!.Solids);
+ var changed = production with { Document = production.Document with
+ { Solids = [solid with { Primitive = new FirmamentV2BoxRecord([81d, 50d, 25d], []) }] } };
+ var report = FirmamentShadowAnalysis.Compare(Parse(source), changed, source);
+ Assert.Contains(report.Comparison.Differences, d => d.Code == "box-size-mismatch" && d.SourceSpan is not null);
+ }
+
+ [Fact]
+ public void UnsupportedFrame_IsRetainedAsAuthoredBeforeSemanticRejection()
+ {
+ var source = File.ReadAllText(Root("fixtures/Regression/FrontendX0/unsupported-xz-layout.firmament"));
+ var declaration = Assert.Single(FirmamentSyntaxEvidence.Declarations(Parse(source).Document), d => d.Name?.Text == "Layout");
+ var frame = Assert.IsType<ReferenceSyntax>(Assert.Single(declaration.Clauses).Value);
+ Assert.Equal("XZ", frame.Name.Text);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Fact]
+ public void UnusedSlot_DoesNotChangeAdmissionOrCompiledGeometry()
+ {
+ var source = Read("slot-route-perturbation");
+ var syntax = Parse(source);
+ var slot = Assert.Single(FirmamentSyntaxEvidence.Declarations(syntax.Document), d => d.Type.Name.Text == "Slot2");
+ var baseline = source.Remove(slot.Span.Start, slot.Span.Length);
+ var before = FirmamentBuildAndExport.CompileSource(baseline);
+ var after = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(before.IsSuccess, string.Join("; ", before.Diagnostics.Select(d => d.Message)));
+ Assert.True(after.IsSuccess, string.Join("; ", after.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(before.Value.StepText, after.Value.StepText);
+ Assert.Equal("UnifiedMechanical", FirmamentV2Parser.Parse(baseline).ParserRoute);
+ Assert.Equal("UnifiedMechanical", FirmamentV2Parser.Parse(source).ParserRoute);
+ Assert.Equal("valid", FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(FirmamentV2Parser.Parse(source)), source).Status);
+ var original = Assert.IsType<DeclarationSyntax>(Assert.Single(Parse(baseline).Document.Statements));
+ var changed = Assert.IsType<DeclarationSyntax>(Assert.Single(syntax.Document.Statements));
+ Assert.Equal(original.Body!.Statements.Select(FirmamentSyntaxEvidence.Normalize),
+ changed.Body!.Statements.Take(original.Body.Statements.Count).Select(FirmamentSyntaxEvidence.Normalize));
+ }
+
+ private static SyntaxParseResult Parse(string source)
+ {
+ var parsed = FirmamentSyntaxParser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("; ", parsed.Diagnostics.Select(d => $"{d.Line}:{d.Column} {d.Message}")));
+ return parsed;
+ }
+ private static string Read(string name) => File.ReadAllText(Root($"fixtures/Regression/FrontendX1/{name}.firmament"));
+ private static string Root(string path) => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../..", path));
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentMechanicalFrontendMigrationTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentMechanicalFrontendMigrationTests.cs
new file mode 100644
index 00000000..34d38b7d
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentMechanicalFrontendMigrationTests.cs
@@ -0,0 +1,162 @@
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentMechanicalFrontendMigrationTests
+{
+ [Theory]
+ [InlineData("unknown-compose-statement", "Fillet")]
+ [InlineData("unknown-boundary-field", "heigth")]
+ public void LostIntent_RejectsInBothProductionPaths_AtOriginalToken(string fixture, string token)
+ {
+ var source = Read("FrontendX0/" + fixture);
+ var parsed = FirmamentV2Parser.Parse(source);
+ var report = FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(parsed, "intent.firmament"), source);
+ Assert.False(parsed.IsSuccess);
+ Assert.Equal("invalid", report.Status);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ var diagnostic = Assert.Single(report.Diagnostics.Where(d => d.Code.EndsWith(":" + token, StringComparison.Ordinal)));
+ Assert.Equal(token, source.Substring(diagnostic.SourceSpan!.Start, diagnostic.SourceSpan.Length));
+ Assert.Equal("intent.firmament", diagnostic.SourceFile);
+ }
+
+ [Theory]
+ [InlineData("Box Body { Size: [40mm,20mm,6mm]; heigth: 8mm }", "Box:heigth")]
+ [InlineData("Box Body On XZ { Size: [40mm,20mm,6mm] }", "placement-unsupported")]
+ [InlineData("Box Body { Size: [40mm,20mm,6mm] } Slot2<Unknown> unused { Center: [0mm,0mm]; Length: 12mm; Width: 3mm }", "variant-unsupported")]
+ [InlineData("Box Body { Size: [40mm,20mm,6mm] } Modify Body { Fillet Lost { Radius: 1mm } }", "Modify:Fillet")]
+ [InlineData("Box Body { Size: [40mm,20mm,6mm]; Size: [4mm,2mm,1mm] }", "field-duplicate:Box:Size")]
+ [InlineData("Box Body { Size: [40mm,20mm,6mm] } Compose Other { }", "material-owners-unsupported")]
+ [InlineData("Box Body { Size: [40mm,20mm,6mm] } Slot2 unused { Center: [0mm,0mm]; Length: 12mm; Width: 3mm; typo: ; }", "firmament-syntax-expression")]
+ public void AstOwner_RejectsUnknownOrContradictoryIntent(string body, string expected)
+ {
+ var source = "Model Test { Units: mm " + body + " }";
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.Contains(parsed.Diagnostics, d => d.Contains(expected, StringComparison.Ordinal));
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Theory]
+ [InlineData("Static unused = 4mm")]
+ [InlineData("Rect2 unusedGuide { Center: [0mm,0mm]; Size: [12mm,3mm] } Profile unused { Loop Outer { unusedGuide.Bottom |> unusedGuide.Right |> unusedGuide.Top |> unusedGuide.Left |> Close } }")]
+ [InlineData("Slot2 unused { center: [0mm,0mm]; length: 12mm; width: 3mm }")]
+ public void UnusedConstruction_CannotSelectAnotherMechanicalGrammar(string unused)
+ {
+ const string stock = "Model Test { Units: mm Box Body { Size: [40mm,20mm,6mm] } }";
+ var changed = stock.Insert(stock.LastIndexOf('}'), unused);
+ var before = FirmamentBuildAndExport.CompileSource(stock);
+ var after = FirmamentBuildAndExport.CompileSource(changed);
+ Assert.True(before.IsSuccess);
+ Assert.True(after.IsSuccess, string.Join("; ", after.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(before.Value.StepText, after.Value.StepText);
+ Assert.Equal("UnifiedMechanical", FirmamentV2Parser.Parse(changed).ParserRoute);
+ var body = Step242Importer.ImportBody(after.Value.StepText);
+ Assert.True(body.IsSuccess);
+ Assert.Equal(6, body.Value.Topology.Faces.Count());
+ }
+
+ [Fact]
+ public void ProfileSelections_RetainTheirAdmittedMemberSet_AndBuild()
+ {
+ var path = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,
+ "../../../../fixtures/Regression/CanonicalGeometry/profile-chamfer-reflex-junction-top.firmament"));
+ var source = File.ReadAllText(path);
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("; ", parsed.Diagnostics));
+ Assert.Equal("UnifiedMechanical", parsed.ParserRoute);
+ var selection = Assert.Single(parsed.Document!.Selections!);
+ Assert.Contains(".[", selection.Source, StringComparison.Ordinal);
+ var report = FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(parsed), source);
+ Assert.Equal("valid", report.Status);
+ Assert.Equal("Built", report.ValidationLevel);
+ Assert.True(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Fact]
+ public void StructAndModelStock_UseTheSameAstBinderAndGeometry()
+ {
+ const string stock = "Model Test { Units: mm Box Body { Size: [40mm,20mm,6mm] } }";
+ var alternative = stock.Replace("Model", "Struct", StringComparison.Ordinal);
+ Assert.Equal("UnifiedMechanical", FirmamentV2Parser.Parse(alternative).ParserRoute);
+ Assert.Equal(FirmamentBuildAndExport.CompileSource(stock).Value.StepText,
+ FirmamentBuildAndExport.CompileSource(alternative).Value.StepText);
+ }
+
+ [Fact]
+ public void SyntaxFailure_HasOriginalLocation_AfterComments()
+ {
+ const string source = "// retained provenance\nModel Test { Units: mm\nBox Body { Size: ; }\n}";
+ var report = FirmamentV2ValidationReportBuilder.Build(FirmamentV2Parser.Parse(source), "broken.firmament");
+ Assert.Equal("invalid", report.Status);
+ var diagnostic = Assert.Single(report.Diagnostics, d => d.Code == "firmament-syntax-expression");
+ Assert.Equal(3, diagnostic.Line);
+ Assert.Equal(";", source.Substring(diagnostic.SourceSpan!.Start, diagnostic.SourceSpan.Length));
+ Assert.Contains("expression", diagnostic.Message, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void ExistingStaticMatch_IsStructured_BeforeExistingSemanticEvaluation()
+ {
+ var syntax = FirmamentSyntaxParser.Parse(FirmamentV2StaticLogicTests.Source());
+ Assert.True(syntax.IsSuccess, string.Join("; ", syntax.Diagnostics.Select(d => d.Message)));
+ var design = Assert.Single(FirmamentSyntaxEvidence.Declarations(syntax.Document), d => d.Name?.Text == "BracketConcept");
+ Assert.IsType<MatchSyntax>(Assert.Single(design.Body!.Statements.OfType<FieldSyntax>(), f => f.Name.Text == "ChamferDistance").Value);
+ Assert.True(FirmamentV2Parser.Parse(FirmamentV2StaticLogicTests.Source()).IsSuccess);
+ }
+
+ [Theory]
+ [InlineData(" Box Base {", " Box Base { heigth: 99mm;", "Box:heigth")]
+ [InlineData(" Modify Base {", " Modify Base { Fillet Lost { Radius: 1mm }", "Modify:Fillet")]
+ public void ConceptValuedStock_CannotBypassMechanicalConsumption(string before, string after, string expected)
+ {
+ var source = FirmamentV2StaticLogicTests.Source().Replace(before, after, StringComparison.Ordinal);
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.Contains(parsed.Diagnostics, d => d.Contains(expected, StringComparison.Ordinal));
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Fact]
+ public void EveryExtrusion_ContributesToTheBoundEngineeringBody()
+ {
+ const string source = """
+ Model Stack {
+ Units: mm
+ Rect2 guide { Center: [0mm,0mm]; Size: [40mm,20mm] }
+ Profile section { Loop Outer { guide.Bottom |> guide.Right |> guide.Top |> guide.Left |> Close } }
+ Extrude bottom { Profile: section; From: 0mm; To: 2mm }
+ Extrude upper { Profile: section; From: 2mm; To: 8mm }
+ }
+ """;
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("; ", parsed.Diagnostics));
+ Assert.Equal(["bottom", "upper"], Assert.Single(parsed.Document!.Composes!).Operations);
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));
+ var imported = Step242Importer.ImportBody(built.Value.StepText);
+ Assert.True(imported.IsSuccess);
+ var points = imported.Value.Topology.Vertices.Select(v => { Assert.True(imported.Value.TryGetVertexPoint(v.Id, out var p)); return p; }).ToArray();
+ Assert.Equal(0d, points.Min(p => p.Z), 8);
+ Assert.Equal(8d, points.Max(p => p.Z), 8);
+ }
+
+ [Theory]
+ [InlineData("Width: 40mm")]
+ [InlineData("Extent: ThroughAll")]
+ public void BoundedFeatureReaders_CannotDiscardAnExpressionSuffix(string field)
+ {
+ var source = File.ReadAllText(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,
+ "../../../../fixtures/Canonical/Features/Slots/straight-slot.firmament")));
+ Assert.True(FirmamentV2Parser.Parse(source).IsSuccess);
+ var invalid = source.Replace(field, field + " + 1mm", StringComparison.Ordinal);
+ Assert.NotEqual(source, invalid);
+ Assert.False(FirmamentV2Parser.Parse(invalid).IsSuccess);
+ Assert.False(FirmamentBuildAndExport.CompileSource(invalid).IsSuccess);
+ }
+
+ private static string Read(string relative) => File.ReadAllText(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,
+ "../../../../fixtures/Regression", relative + ".firmament")));
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs
index 19e82b8d..9da2ff5c 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs
@@ -408,8 +408,7 @@ public sealed class FirmamentV2CanonicalAdvancedGrammarTests
Assert.Contains(FirmamentV2Parser.EdgeFinishProfileComposeBoundaryUnsupported, parse.Diagnostics);
var build = FirmamentBuildAndExport.Run(path, output);
Assert.False(build.IsSuccess);
- var diagnostic = Assert.Single(build.Diagnostics);
- Assert.Contains(FirmamentBuildAndExport.EdgeFinishProfileComposeBoundaryUnsupported, diagnostic.Message, StringComparison.Ordinal);
+ var diagnostic = Assert.Single(build.Diagnostics.Where(d => d.Message.StartsWith(FirmamentBuildAndExport.EdgeFinishProfileComposeBoundaryUnsupported + ":", StringComparison.Ordinal)));
Assert.DoesNotContain("SemanticSourceNotFound", diagnostic.Message, StringComparison.Ordinal);
}
finally
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalSafetyAndLabelingTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalSafetyAndLabelingTests.cs
index 29ecad6f..e52bf0e6 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalSafetyAndLabelingTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalSafetyAndLabelingTests.cs
@@ -59,7 +59,7 @@ public sealed class FirmamentV2CanonicalSafetyAndLabelingTests
""");
Assert.False(parse.IsSuccess);
- Assert.Contains(FirmamentV2Parser.CanonicalFieldUnknown, parse.Diagnostics);
+ Assert.Contains(parse.Diagnostics, d => d.StartsWith(FirmamentV2Parser.CanonicalFieldUnknown + ":Hole:", StringComparison.Ordinal));
}
[Fact]
diff --git a/Aetheris.Kernel.Firmament.Tests/HoleRuntimeCorrespondenceTests.cs b/Aetheris.Kernel.Firmament.Tests/HoleRuntimeCorrespondenceTests.cs
index 03e2a963..56d1c88e 100644
--- a/Aetheris.Kernel.Firmament.Tests/HoleRuntimeCorrespondenceTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/HoleRuntimeCorrespondenceTests.cs
@@ -55,13 +55,15 @@ public sealed class HoleRuntimeCorrespondenceTests
}
[Fact]
- public void ExistingAdvancedHoleSelectionDeclarationIsNotAcceptedInSimpleHoleSource()
+ public void HoleSelectionDeclaration_BindsWithoutChangingPrimitiveGeometry()
{
var source = Source(6);
source = source[..^1] + " Selection WallH { Target: HoleWall Source: Hole(H) Require: NonEmptyFaceSet } }";
var build = FirmamentBuildAndExport.CompileSource(source);
- Assert.False(build.IsSuccess);
- Assert.Contains(build.Diagnostics, d => d.Message.Contains("firmament-v2-phase3-edge-finish-syntax-invalid", StringComparison.Ordinal));
+ Assert.True(build.IsSuccess, string.Join("; ", build.Diagnostics.Select(d => d.Message)));
+ var parsed = FirmamentV2.FirmamentV2Parser.Parse(source);
+ Assert.Equal("WallH", Assert.Single(parsed.Document!.Selections!).Name);
+ Assert.Equal(FirmamentBuildAndExport.CompileSource(Source(6)).Value.StepText, build.Value.StepText);
}
[Fact]
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 3134c437..0211fbc3 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -282,59 +282,62 @@ public static class FirmamentBuildAndExport
? KernelResult<FirmamentStepExportResult>.Success(new(step.Value, authored.Chain!.StableId, 0, "section-chain", "section-chain"))
: KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
}
- // The V2 parser owns canonical-root admission. Profile/composition
- // materializers consume only the extracted normalized declaration body,
- // so their historical top-level spelling is no longer author-visible.
- // Static authoring is intentionally erased before this boundary, too:
- // parser admission alone is insufficient because the profile/composition
- // materializers read source declarations directly.
- var staticDiagnostics = new List<string>();
+ // Production mechanical execution consumes the result of AST admission.
+ // Its expansion pipeline runs once in the frontend. Other domain owners keep
+ // their existing expansion boundary until their own mechanical migration.
sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);
- var boundaryExpansion = ClosedBoundary2Authoring.Expand(sourceText, staticDiagnostics);
- if (boundaryExpansion is null)
- {
- return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
- Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.ClosedBoundary2")).ToArray());
- }
- var templateBindWatch = System.Diagnostics.Stopwatch.StartNew();
- var templateExpansion = FirmamentV2TemplateExpansion.Expand(boundaryExpansion.Source, staticDiagnostics);
- templateBindWatch.Stop();
- if (templateExpansion is null)
+ var canonicalParseWatch = System.Diagnostics.Stopwatch.StartNew();
+ var v2Parse = FirmamentV2Parser.Parse(sourceText, sourceDirectory);
+ canonicalParseWatch.Stop();
+ var templateBindWatch = new System.Diagnostics.Stopwatch();
+ string materializerSource;
+ if (v2Parse.ParserRoute == "UnifiedMechanical")
{
- return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
- Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.TemplateExpansion")).ToArray());
+ if (!v2Parse.IsSuccess) return V2ParseFailure(v2Parse);
+ materializerSource = v2Parse.BoundSource!;
}
- var featureExpansion = FirmamentV2FeatureExpansion.Expand(templateExpansion.Source, staticDiagnostics);
- if (featureExpansion is null)
+ else
{
- return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
- Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.FeatureExpansion")).ToArray());
+ var staticDiagnostics = new List<string>();
+ var boundaryExpansion = ClosedBoundary2Authoring.Expand(sourceText, staticDiagnostics);
+ if (boundaryExpansion is null)
+ {
+ return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
+ Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.ClosedBoundary2")).ToArray());
+ }
+ templateBindWatch.Start();
+ var templateExpansion = FirmamentV2TemplateExpansion.Expand(boundaryExpansion.Source, staticDiagnostics);
+ templateBindWatch.Stop();
+ if (templateExpansion is null)
+ {
+ return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
+ Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.TemplateExpansion")).ToArray());
+ }
+ var featureExpansion = FirmamentV2FeatureExpansion.Expand(templateExpansion.Source, staticDiagnostics);
+ if (featureExpansion is null)
+ {
+ return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
+ Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.FeatureExpansion")).ToArray());
+ }
+ var specializedBoundaries = ClosedBoundary2Authoring.Expand(featureExpansion.Source, staticDiagnostics);
+ if (specializedBoundaries is null)
+ return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(SchemaDiagnostic).ToArray());
+ var staticExpansion = CanonicalStaticAuthoring.Expand(specializedBoundaries.Source, staticDiagnostics);
+ if (staticExpansion is null)
+ {
+ return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics
+ .Distinct(StringComparer.Ordinal)
+ .Order(StringComparer.Ordinal)
+ .Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
+ Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
+ Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
+ diagnostic,
+ "FirmamentV2.StaticAuthoring"))
+ .ToArray());
+ }
+ var materializerInput = staticExpansion.Source;
+ materializerSource = FirmamentV2Parser.TryGetCanonicalAdvancedBody(materializerInput, out var canonicalBody) ? canonicalBody : materializerInput;
}
- var specializedBoundaries = ClosedBoundary2Authoring.Expand(featureExpansion.Source, staticDiagnostics);
- if (specializedBoundaries is null)
- return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(SchemaDiagnostic).ToArray());
- var staticExpansion = CanonicalStaticAuthoring.Expand(specializedBoundaries.Source, staticDiagnostics);
- if (staticExpansion is null)
- {
- return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics
- .Distinct(StringComparer.Ordinal)
- .Order(StringComparer.Ordinal)
- .Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
- Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
- Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
- diagnostic,
- "FirmamentV2.StaticAuthoring"))
- .ToArray());
- }
- var materializerInput = staticExpansion.Source;
- // Parse the canonical document before selecting the materializer. Advanced
- // Profile/Compose hosts still use their bounded section-stack materializer,
- // but their normalized PMI records must follow the same AP242 route.
- var canonicalParseWatch = System.Diagnostics.Stopwatch.StartNew();
- var v2Parse = FirmamentV2Parser.Parse(sourceText, sourceDirectory);
- canonicalParseWatch.Stop();
- var canonicalAdvanced = FirmamentV2Parser.TryGetCanonicalAdvancedBody(materializerInput, out var canonicalBody);
- var materializerSource = canonicalAdvanced ? canonicalBody : materializerInput;
if (PlateauAuthoring.IsSource(materializerSource))
{
if (!v2Parse.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(v2Parse.Diagnostics.Select(SchemaDiagnostic).ToArray());
@@ -448,13 +451,9 @@ public static class FirmamentBuildAndExport
authored.Value.Path.StableId, "Circle", authored.Value.Diameter, "Diameter", "Add", PolicySource: "CircularSweepFeatureAir", MaterializationRoute: "CircularSweepBRepPlan")]),
[]);
}
- // Profile/Compose adapters still own additional admitted syntax (junction
- // selections and derived profiles) absent from the generic V2 document.
- // A blanket V2 gate here breaks established engineering fixtures. X0 keeps
- // this boundary explicit pending consumed-source admission (see release report).
- if (PrismaticProfileCompositionParser.IsCompositionSource(materializerSource))
+ if (v2Parse.BoundComposition is not null || (v2Parse.ParserRoute != "UnifiedMechanical" && PrismaticProfileCompositionParser.IsCompositionSource(materializerSource)))
{
- var parsed = PrismaticProfileCompositionParser.Parse(materializerSource);
+ var parsed = v2Parse.BoundComposition ?? PrismaticProfileCompositionParser.Parse(materializerSource);
var stack = PrismaticSectionStackCompiler.Normalize(parsed, out var diagnostics);
if (stack is null)
return KernelResult<FirmamentStepExportResult>.Failure(diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.ProfileComposition")).ToArray());
@@ -495,9 +494,11 @@ public static class FirmamentBuildAndExport
Features: CompositionHoleReports(stack.Feature),
EngineeringFeatures: EngineeringFeatureReports(stack.Feature)));
}
- if (ProfileAuthoringParser.IsProfileSource(materializerSource))
+ if (v2Parse.BoundProfile is not null || (v2Parse.ParserRoute != "UnifiedMechanical" && ProfileAuthoringParser.IsProfileSource(materializerSource)))
{
- var parsed = ProfileAuthoringParser.Parse(materializerSource);
+ var parsed = v2Parse.BoundProfile is { } boundProfile
+ ? (Profile: (ResolvedProfile2D?)boundProfile, Height: v2Parse.ExtrusionHeight, Diagnostics: (IReadOnlyList<string>)[])
+ : ProfileAuthoringParser.Parse(materializerSource);
if (parsed.Profile is null) return KernelResult<FirmamentStepExportResult>.Failure(parsed.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.Profile")).ToArray());
var emitted = ResolvedProfile2DValidator.Extrude(parsed.Profile, parsed.Height);
if (emitted.Status != LineArcProfileExtrudeStatus.Succeeded || emitted.Body is null) return KernelResult<FirmamentStepExportResult>.Failure(emitted.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.Profile")).ToArray());
@@ -741,7 +742,9 @@ public static class FirmamentBuildAndExport
private static KernelResult<FirmamentStepExportResult> V2ParseFailure(FirmamentV2ParseResult parse)
{
- var errors = parse.Diagnostics.Where(FirmamentV2Parser.IsFatalDiagnosticCode).Distinct(StringComparer.Ordinal).ToArray();
+ var syntaxCodes = parse.SyntaxDiagnostics.Select(d => d.Code).ToHashSet(StringComparer.Ordinal);
+ var errors = parse.Diagnostics.Where(FirmamentV2Parser.IsFatalDiagnosticCode).Where(code => !syntaxCodes.Contains(code))
+ .Concat(parse.SyntaxDiagnostics.Select(d => d.Code + ": " + d.Message)).Distinct(StringComparer.Ordinal).ToArray();
if (errors.Length == 0) errors = ["firmament-v2-parse-failed"];
return KernelResult<FirmamentStepExportResult>.Failure(errors.Select(code => new KernelDiagnostic(
KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, code, "FirmamentV2.Parse")).ToArray());
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
index 66f9d061..56cf3849 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
@@ -1,4 +1,5 @@
using Aetheris.Kernel.Firmament.Materializer;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
@@ -13,10 +14,6 @@ internal static class ClosedBoundary2Authoring
{
internal const string Prefix = "firmament-boundary2-";
private const double Tol = 1e-9;
- private static readonly Regex Header = new(
- @"\b(?:(?<plain>Rect2|Square2|Circle2|Ellipse2|Slot2|RoundedRect2|SmoothRoundedRect2)|(?<family>Triangle2|Polygon2)\s*<\s*(?<variant>[A-Za-z_]\w*)\s*>|RegularPolygon2\s*<\s*(?<count>[-+]?\d+)\s*>)\s+(?<name>[A-Za-z_]\w*)\s*\{",
- RegexOptions.CultureInvariant);
-
internal sealed record Result(string Source, IReadOnlyList<FirmamentV2ClosedBoundary2Decl> Boundaries)
{
public IReadOnlyList<FirmamentV2Polygon2Decl> Polygons => Boundaries.Where(x => x.ShapeType == "Polygon2")
@@ -40,21 +37,28 @@ internal static class ClosedBoundary2Authoring
}
bool InTemplate(int offset) => templates.Any(span => offset >= span.Start && offset < span.Start + span.Length);
var shapes = new List<Shape>(); var names = new HashSet<string>(StringComparer.Ordinal);
- foreach (Match header in Header.Matches(source))
+ var syntax = FirmamentSyntaxParser.Parse(source);
+ foreach (var declaration in BoundaryDeclarations(syntax.Document))
{
- // `Concept Circle2 Name { ... }` is a concise reusable curve concept, not a
- // closed material boundary declaration. Its Circle2 payload is consumed by
- // the ordinary profile-guide binder and must not be rewritten here.
- var prefix = source[..header.Index].TrimEnd();
- if (prefix.EndsWith("Concept", StringComparison.Ordinal) && (prefix.Length == 7 || !char.IsLetterOrDigit(prefix[^8]) && prefix[^8] != '_')) continue;
- if (InTemplate(header.Index)) continue;
- var open = source.IndexOf('{', header.Index); var close = Matching(source, open); var name = header.Groups["name"].Value;
- if (close < 0) { diagnostics.Add(Prefix + "malformed:" + name); continue; }
+ if (InTemplate(declaration.Span.Start)) continue;
+ var syntaxErrors = syntax.Diagnostics.Where(d => d.SourceSpan is { } span && span.Start >= declaration.Span.Start && span.Start < declaration.Span.Start + declaration.Span.Length).ToArray();
+ if (syntaxErrors.Length > 0)
+ {
+ diagnostics.AddRange(syntaxErrors.Select(d => d.Code + ": " + d.Message));
+ continue;
+ }
+ var name = declaration.Name!.Text;
if (!names.Add(name)) { diagnostics.Add(Prefix + "duplicate-name:" + name); continue; }
- var shape = Bind(source, header, source[(open + 1)..close], close, diagnostics);
- if (shape is not null) shapes.Add(shape);
+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);
+ // ProfileGuide is an established authoring annotation emitted by the
+ // static geometry expander; it does not request a material operation.
+ fields.Word("Role");
+ var shape = Bind(source, declaration, fields, diagnostics);
+ // Unbound template/record expressions remain with their specialization
+ // owner. Successful shape binding must consume every authored field.
+ if (shape is not null) { fields.Complete(); shapes.Add(shape); }
}
- if (diagnostics.Any(x => x.StartsWith(Prefix, StringComparison.Ordinal) || x.StartsWith("firmament-polygon2-", StringComparison.Ordinal))) return null;
+ if (diagnostics.Any(FirmamentV2Parser.IsFatalDiagnosticCode)) return null;
var changes = new List<(int Start, int Length, string Text)>();
foreach (var shape in shapes)
{
@@ -93,13 +97,21 @@ internal static class ClosedBoundary2Authoring
return new(source, shapes.Select(x => x.Declaration).ToArray());
}
- private static Shape? Bind(string source, Match header, string body, int close, List<string> diagnostics)
+ private static IEnumerable<DeclarationSyntax> BoundaryDeclarations(DocumentSyntax syntax) =>
+ FirmamentSyntaxEvidence.Declarations(syntax)
+ .Where(d => d.Name is not null && d.Body is not null && !d.Modifiers.Any(m => m.Name.Text == "Concept")
+ && d.Type.Name.Text is "Rect2" or "Square2" or "Circle2" or "Ellipse2" or "Slot2" or "RoundedRect2" or "SmoothRoundedRect2" or "Triangle2" or "Polygon2" or "RegularPolygon2");
+
+ private static Shape? Bind(string source, DeclarationSyntax declaration, FirmamentSyntaxFields body, List<string> diagnostics)
{
- var name = header.Groups["name"].Value;
- var type = header.Groups["plain"].Success ? header.Groups["plain"].Value : header.Groups["family"].Success ? header.Groups["family"].Value : "RegularPolygon2";
- var variant = header.Groups["variant"].Success ? header.Groups["variant"].Value : header.Groups["count"].Success ? header.Groups["count"].Value : null;
+ var name = declaration.Name!.Text;
+ var type = declaration.Type.Name.Text;
+ if (declaration.Type.Arguments.Count > 1 || declaration.Type.Arguments.Count > 0 && type is not ("Triangle2" or "Polygon2" or "RegularPolygon2"))
+ return Invalid(name, "variant-unsupported", diagnostics);
+ var variant = declaration.Type.Arguments.FirstOrDefault()?.Value is { } argument
+ ? FirmamentSyntaxValues.Reference(argument) ?? (argument as LiteralSyntax)?.Raw : null;
var rotation = Angle(body, "Rotation", 0d, out var rotationOk); if (!rotationOk) return Invalid(name, "invalid-rotation", diagnostics);
- var span = new FirmamentV2SourceSpan(header.Index, close - header.Index + 1);
+ var span = declaration.Span;
if (type == "Rect2")
{
if (!Point(body, "Center", out var c) || !Vector(body, "Size", out var size)) return null; // legacy/template Rect2 is bound after static specialization
@@ -132,7 +144,7 @@ internal static class ClosedBoundary2Authoring
return Make(name, "Rect2", null, c, 0, new Dictionary<string, double> { ["Width"] = w, ["Height"] = h }, points, edges, "Line", span, null, map, string.Join(" |> ", edges.Select(x => name + "." + x)) + " |> Close", w * h, 2 * (w + h));
}
- private static Shape? Triangle(string name, string variant, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
+ private static Shape? Triangle(string name, string variant, FirmamentSyntaxFields body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
{
(double X, double Y) c; IReadOnlyList<(double X, double Y)> vertices; var dimensions = new Dictionary<string, double>();
switch (variant)
@@ -156,7 +168,7 @@ internal static class ClosedBoundary2Authoring
return Linear(name, "Triangle2", variant, c, rotation, vertices, ["A", "B", "C"], ["AB", "BC", "CA"], span, dimensions);
}
- private static Shape? Circle(string source, string name, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
+ private static Shape? Circle(string source, string name, FirmamentSyntaxFields body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
{
var inline = Point(body, "Center", out var c); var centerRef = Identifier(body, "Center");
if (!inline && (centerRef is null || !ResolvePoint(source, centerRef, out c))) return null; // legacy/template Circle2 remains on its existing binder path
@@ -167,7 +179,7 @@ internal static class ClosedBoundary2Authoring
return Make(name, "Circle2", null, c, rotation, new Dictionary<string, double> { ["Radius"] = radius, ["Diameter"] = 2 * radius }, ["Center"], ["Boundary"], "Circle", span, lowered, map, guide + " |> TraceLoop", Math.PI * radius * radius, 2 * Math.PI * radius);
}
- private static Shape? Ellipse(string name, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
+ private static Shape? Ellipse(string name, FirmamentSyntaxFields body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
{
if (!Point(body, "Center", out var c) || !(Vector(body, "AxisLengths", out var axes) || Vector(body, "Axes", out axes)) || !Positive(axes.X, axes.Y)) return Invalid(name, "invalid-dimensions", diagnostics);
var major = Math.Max(axes.X, axes.Y) / 2; var minor = Math.Min(axes.X, axes.Y) / 2; if (axes.Y > axes.X) rotation += 90;
@@ -178,7 +190,7 @@ internal static class ClosedBoundary2Authoring
new Dictionary<string, string> { ["Center"] = name + "_Center", ["MajorPositive"] = name + "_MajorPositive", ["MajorNegative"] = name + "_MajorNegative", ["MinorPositive"] = name + "_MinorPositive", ["MinorNegative"] = name + "_MinorNegative", ["Boundary"] = name + "_Curve" }, name + "_Curve |> TraceLoop", Math.PI * major * minor, EllipsePerimeter(major, minor));
}
- private static Shape? Slot(string name, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
+ private static Shape? Slot(string name, FirmamentSyntaxFields body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
{
if (!Point(body, "Center", out var c) || !Length(body, "Length", out var length) || !Length(body, "Width", out var width) || width <= 0 || length < width) return Invalid(name, "invalid-dimensions", diagnostics);
var straight = length - width; var r = width / 2; var start = Rotate((c.X - straight / 2, c.Y - r), c, rotation);
@@ -193,7 +205,7 @@ internal static class ClosedBoundary2Authoring
return Make(name, "Slot2", null, c, rotation, new Dictionary<string, double> { ["OverallLength"] = length, ["Width"] = width }, [], guides, "Line+Circle", span, path, map, name + "_Path |> TraceLoop", width * straight + Math.PI * r * r, 2 * straight + 2 * Math.PI * r);
}
- private static Shape? RoundedRect(string name, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
+ private static Shape? RoundedRect(string name, FirmamentSyntaxFields body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
{
if (!Point(body, "Center", out var c) || !Vector(body, "Size", out var size) || !Length(body, "Radius", out var r) || !Positive(size.X, size.Y) || r < 0 || r > Math.Min(size.X, size.Y) / 2) return Invalid(name, "invalid-dimensions", diagnostics);
if (r <= Tol) return Linear(name, "RoundedRect2", null, c, rotation, Rectangle(c, size.X, size.Y, rotation), ["BottomLeft", "BottomRight", "TopRight", "TopLeft"], ["Bottom", "Right", "Top", "Left"], span, new Dictionary<string, double> { ["Width"] = size.X, ["Height"] = size.Y, ["Radius"] = 0 });
@@ -215,24 +227,21 @@ internal static class ClosedBoundary2Authoring
var close = Matching(source, source.IndexOf('{', feature.Index));
if (close >= 0) templates.Add(new(feature.Index, close - feature.Index + 1));
}
- foreach (Match header in Header.Matches(source))
+ foreach (var declaration in BoundaryDeclarations(FirmamentSyntaxParser.Parse(source).Document).Where(d => d.Type.Name.Text == "SmoothRoundedRect2"))
{
- if (templates.Any(span => header.Index >= span.Start && header.Index < span.Start + span.Length)) continue;
- if (header.Groups["plain"].Value != "SmoothRoundedRect2") continue;
- var open = source.IndexOf('{', header.Index); var close = Matching(source, open);
- if (close < 0) continue;
- var body = source[(open + 1)..close];
+ if (templates.Any(span => declaration.Span.Start >= span.Start && declaration.Span.Start < span.Start + span.Length)) continue;
+ var body = new FirmamentSyntaxFields(declaration, diagnostics);
var rotation = Angle(body, "Rotation", 0d, out _);
- var shape = SmoothRoundedRect(header.Groups["name"].Value, body, rotation,
- new(header.Index, close - header.Index + 1), diagnostics);
+ var shape = SmoothRoundedRect(declaration.Name!.Text, body, rotation, declaration.Span, diagnostics);
if (shape is null) continue;
Point(body, "Center", out var center); Vector(body, "Size", out var size); Length(body, "CornerExtent", out var extent);
- foreach (var curve in SmoothCurves(center, size, extent, rotation)) guides.TryAdd(shape.Declaration.Name + "." + curve.Key, curve.Value);
+ foreach (var guide in SmoothCurves(center, size, extent, rotation))
+ guides.TryAdd(declaration.Name.Text + "." + guide.Key, guide.Value);
}
return guides;
}
- private static Shape? SmoothRoundedRect(string name, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
+ private static Shape? SmoothRoundedRect(string name, FirmamentSyntaxFields body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
{
if (!Point(body, "Center", out var c) || !Vector(body, "Size", out var size) ||
!Length(body, "CornerExtent", out var r) || !Positive(size.X, size.Y, r) || r >= Math.Min(size.X, size.Y) / 2)
@@ -281,7 +290,7 @@ internal static class ClosedBoundary2Authoring
return (Speed(0) + Speed(1) + Enumerable.Range(1, n - 1).Sum(i => (i % 2 == 0 ? 2 : 4) * Speed((double)i / n))) / (3 * n);
}
- private static Shape? Polygon(string source, string name, string variant, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
+ private static Shape? Polygon(string source, string name, string variant, FirmamentSyntaxFields body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
{
IReadOnlyList<(double X, double Y)> vertices; IReadOnlyList<string> pointNames; Dictionary<string, double> dimensions = []; (double X, double Y) c;
switch (variant)
@@ -307,7 +316,7 @@ internal static class ClosedBoundary2Authoring
return Linear(name, "Polygon2", variant, c, rotation, vertices, pointNames, edgeNames, span, dimensions);
}
- private static Shape? RegularPolygon(string name, string countText, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
+ private static Shape? RegularPolygon(string name, string countText, FirmamentSyntaxFields body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
{
if (!int.TryParse(countText, NumberStyles.Integer, CultureInfo.InvariantCulture, out var count) || count is < 3 or > 1024) return Invalid(name, "regular-count-out-of-range", diagnostics);
if (!Point(body, "Center", out var c)) return Invalid(name, "invalid-center", diagnostics); double radius; var dimensions = new Dictionary<string, double> { ["VertexCount"] = count };
@@ -344,24 +353,21 @@ internal static class ClosedBoundary2Authoring
private static double Cross((double X, double Y) a, (double X, double Y) b, (double X, double Y) c) => (b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X);
private static double Distance((double X, double Y) a, (double X, double Y) b) => Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));
private static double EllipsePerimeter(double a, double b) => Math.PI * (3 * (a + b) - Math.Sqrt((3 * a + b) * (a + 3 * b)));
- private static bool Point(string body, string field, out (double X, double Y) value)
+ private static bool Point(FirmamentSyntaxFields body, string field, out (double X, double Y) value)
{
value = default;
- var expression = ProfileAuthoringParser.Property(body, field)?.Trim();
- if (expression is null) return false;
- string components;
- if (expression.StartsWith("[") && expression.EndsWith("]")) components = expression[1..^1];
- else if (expression.StartsWith("Point2(") && expression.EndsWith(")")) components = expression[7..^1];
- else return false;
- var items = components.Split(',');
- return items.Length == 2 && ProfileAuthoringParser.TryMeasure(items[0], "mm", out value.X)
- && ProfileAuthoringParser.TryMeasure(items[1], "mm", out value.Y);
+ if (!body.Vector(field, "mm", out var items) || items.Length != 2) return false;
+ value = (items[0], items[1]); return true;
+ }
+ private static bool Vector(FirmamentSyntaxFields body, string field, out (double X, double Y) value) => Point(body, field, out value);
+ private static bool Length(FirmamentSyntaxFields body, string field, out double value) => body.Measure(field, "mm", out value);
+ private static double Angle(FirmamentSyntaxFields body, string field, double fallback, out bool valid)
+ {
+ var expression = body.Take(field);
+ valid = expression is null || FirmamentSyntaxValues.TryMeasure(expression, "deg", out _);
+ return expression is null ? fallback : FirmamentSyntaxValues.TryMeasure(expression, "deg", out var value) ? value : double.NaN;
}
- private static bool Vector(string body, string field, out (double X, double Y) value) => Point(body, field, out value);
- private static bool Length(string body, string field, out double value) =>
- ProfileAuthoringParser.TryMeasure(ProfileAuthoringParser.Property(body, field) ?? "", "mm", out value);
- private static double Angle(string body, string field, double fallback, out bool valid) { var m = Regex.Match(body, $@"\b{field}\s*:\s*(?<v>[-+.\deE]+)deg\b", RegexOptions.CultureInvariant); if (!m.Success) { valid = true; return fallback; } valid = Number(m.Groups["v"].Value, out var value); return value; }
- private static string? Identifier(string body, string field) { var m = Regex.Match(body, $@"\b{field}\s*:\s*(?<v>[A-Za-z_]\w*)\b", RegexOptions.CultureInvariant); return m.Success ? m.Groups["v"].Value : null; }
+ private static string? Identifier(FirmamentSyntaxFields body, string field) => body.Word(field);
private static bool ResolvePoint(string source, string name, out (double X, double Y) p) { var m = Regex.Match(source, $@"\bPoint2\s+{Regex.Escape(name)}\s*\{{\s*Position\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm", RegexOptions.CultureInvariant); p = default; return m.Success && Number(m.Groups["x"].Value, out p.X) && Number(m.Groups["y"].Value, out p.Y); }
private static bool PointSet(string source, string name, out IReadOnlyList<string> names, out IReadOnlyList<(double X, double Y)> points) { names = []; points = []; var h = Regex.Match(source, $@"\bStatic\s+{Regex.Escape(name)}\s*:\s*Set\s*<\s*Point2\s*>\s*\{{", RegexOptions.CultureInvariant); if (!h.Success) return false; var open = source.IndexOf('{', h.Index); var close = Matching(source, open); if (close < 0) return false; var ns = new List<string>(); var ps = new List<(double, double)>(); foreach (Match e in Regex.Matches(source[(open + 1)..close], @"\b(?<n>[A-Za-z_]\w*)\s*=>\s*Point2\s*\(\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*\)", RegexOptions.CultureInvariant)) if (Number(e.Groups["x"].Value, out var x) && Number(e.Groups["y"].Value, out var y)) { ns.Add(e.Groups["n"].Value); ps.Add((x, y)); } names = ns; points = ps; return true; }
private static bool Number(string text, out double value) => double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
index ee3c6838..2ae4f742 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
@@ -1,4 +1,5 @@
using System.Globalization;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Air;
@@ -251,6 +252,17 @@ internal static class ConceptIrResolver
var allInstances = instanceList.ToDictionary(i => i.Name, StringComparer.Ordinal);
var boxBody = source[(boxOpen + 1)..boxClose];
+ var syntaxDeclarations = FirmamentSyntaxEvidence.Declarations(FirmamentSyntaxParser.Parse(source).Document).ToArray();
+ var boxSyntax = syntaxDeclarations.FirstOrDefault(d => d.Type.Name.Text == "Box" && d.Body?.Span.Start == boxOpen);
+ if (boxSyntax is null) { diagnostics.Add(FirmamentV2Parser.CanonicalPrimitiveMalformed); return null; }
+ var boxFields = new FirmamentSyntaxFields(boxSyntax, diagnostics);
+ var boundsExpression = boxFields.Take("Bounds"); var sizeExpression = boxFields.Take("Size");
+ if (boundsExpression is not null && sizeExpression is not null) diagnostics.Add("firmament-v2-field-conflict:Box:Bounds:Size");
+ boxFields.Complete();
+ var modifySyntax = syntaxDeclarations.FirstOrDefault(d => d.Type.Name.Text == "Modify" && d.Body?.Span.Start == modifyOpen);
+ foreach (var statement in modifySyntax?.Body?.Statements ?? [])
+ if (statement is not DeclarationSyntax feature || !(feature.Type.Name.Text.Equals("Hole", StringComparison.OrdinalIgnoreCase) || feature.Type.Name.Text is "Pattern" or "EdgeFinish"))
+ diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:Modify:{(statement as DeclarationSyntax)?.Type.Name.Text ?? "expression"}");
IReadOnlyList<double>? size = null;
ConceptIrBox3Value? resolvedBounds = null;
string boundsProvenance;
@@ -263,9 +275,7 @@ internal static class ConceptIrResolver
}
else
{
- var sizeMatch = Regex.Match(boxBody, @"\bSize\s*:\s*\[(?<values>[^\]]+)\]", RegexOptions.CultureInvariant);
- var values = sizeMatch.Success ? sizeMatch.Groups["values"].Value.Split(',').Select(ParseLength).ToArray() : [];
- size = values.Length == 3 && values.All(v => double.IsFinite(v) && v > 0) ? values : null;
+ size = FirmamentSyntaxValues.Vector(sizeExpression, "mm", out var values) && values.Length == 3 && values.All(v => v > 0) ? values : null;
boundsProvenance = $"{materialized.Groups["name"].Value}.{box.Groups["name"].Value}.Size";
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs
index 0fbae804..8cf235cd 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-syntax-", StringComparison.Ordinal))
+ {
+ var candidates = Syntax.FirmamentSyntaxParser.Parse(source, sourceFile).Diagnostics.Where(d => d.Code == code).ToArray();
+ if (candidates.Length == 1) return candidates[0] with { Source = diagnostic.Source, Stage = "Syntax" };
+ }
return Locate(new(diagnostic.Message, diagnostic.Severity switch
{
KernelDiagnosticSeverity.Error => "fatal",
@@ -51,6 +56,7 @@ public static class FirmamentBuildAdmissionValidation
public static FirmamentV2ValidationDiagnostic Locate(
FirmamentV2ValidationDiagnostic diagnostic, string? source, string sourceFile)
{
+ if (diagnostic.SourceSpan is not null) return diagnostic with { SourceFile = sourceFile };
if (source is null) return diagnostic with { SourceFile = sourceFile, LocationNote = "Original source is unavailable." };
var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(token => token.Shape != "comment").ToArray();
// Only these parser-owned diagnostics identify a specific original token.
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs
index b73605cb..49a7ccfe 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs
@@ -55,16 +55,23 @@ public static class FirmamentV2DiagnosticAdapter
public static string MessageFor(string diagnosticCode) => diagnosticCode switch
{
FirmamentV2Parser.CanonicalPrimitiveMalformed => "Malformed primitive: check the required dimension fields and their length units.",
+ FirmamentV2Parser.CanonicalModifyMalformed => "Malformed Modify feature. Check the target, feature variant, required fields and termination.",
+ FirmamentV2Parser.CanonicalUnitsInvalid => "This mechanical document requires Units: mm; conflicting unit declarations are not admitted.",
+ FirmamentV2Parser.HoleVariantUnknown => "Unknown Hole variant. Use an admitted Hole<Shaft>, Hole<Counterbore> or Hole<Countersink> contract.",
FirmamentV2Parser.CanonicalDocumentMalformed => "Malformed Model document. Check its declarations and closing braces.",
"firmament-v2-parse-failed" => "Firmament V2 parsing or binding failed; the program has not been admitted for compilation.",
FirmamentV2Parser.PmiDimensionMissingTolerance => "PMI dimension resolves to a value without tolerance evidence.",
FirmamentV2Parser.ConceptMissingRequiredField => "Forge concept application is missing a required descriptor field.",
FirmamentV2Parser.PmiUnknownDatum => "PMI relation references an unknown datum.",
FirmamentV2Parser.ToleranceDroppedThroughArithmetic => "A toleranced value was used in arithmetic and only the nominal value was preserved.",
+ _ when diagnosticCode.StartsWith("firmament-v2-field-duplicate:", StringComparison.Ordinal)
+ => $"Field '{diagnosticCode.Split(':')[^1]}' is specified more than once in {diagnosticCode.Split(':')[1]}. Keep one value.",
+ _ when diagnosticCode.StartsWith("firmament-v2-field-value-invalid:", StringComparison.Ordinal)
+ => $"Invalid value for field '{diagnosticCode.Split(':')[^1]}' in {diagnosticCode.Split(':')[1]}. Check the value type, units and admitted vocabulary.",
_ when diagnosticCode.StartsWith(FirmamentV2Parser.CanonicalFieldUnknown + ":", StringComparison.Ordinal)
=> $"Unknown field '{diagnosticCode.Split(':')[^1]}' in {diagnosticCode.Split(':')[1]}. Check this construct's documented fields.",
_ when diagnosticCode.StartsWith(FirmamentV2Parser.CanonicalDeclarationUnknown + ":", StringComparison.Ordinal)
- => $"Unknown statement '{diagnosticCode.Split(':')[^1]}'. Use an admitted construct in this context.",
+ => $"Unknown statement '{diagnosticCode.Split(':')[^1]}'{(diagnosticCode.Split(':').Length > 2 ? " in " + diagnosticCode.Split(':')[1] : "")}. Use an admitted construct in this context.",
_ => diagnosticCode
};
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
index 578c48d0..2d4b7534 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
@@ -19,7 +19,7 @@ public sealed record FirmamentLanguageFormat(string Document, string Revision, s
/// </summary>
public static class FirmamentLanguageAnalysisService
{
- internal sealed record Lexeme(int Start, int Length, string Text, string Shape);
+ internal sealed record Lexeme(int Start, int Length, string Text, string Shape, string? Error = null);
private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "With", "with", "Expose", "Include", "Subassembly", "Assembly", "Part", "Template", "Function", "Record", "Pattern", "Over", "Using", "Output"];
private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Function", "Pattern", "Section", "SectionChain", "FrameTransform", "Points"];
private static readonly HashSet<string> Types = ["Length", "Angle", "Float", "Int", "Bool", "Box3", "Plane", "Point2", "Point3"];
@@ -295,15 +295,21 @@ public static class FirmamentLanguageAnalysisService
return new("error", diagnostic, message, presented.SourceSpan?.Start ?? 0, presented.SourceSpan?.Length ?? 0);
}
- internal static List<Lexeme> Lex(string source)
+ internal static List<Lexeme> Lex(string source, bool lossless = false)
{
var result = new List<Lexeme>();
for (var at = 0; at < source.Length;)
{
- if (char.IsWhiteSpace(source[at])) { at++; continue; }
var start = at;
string shape;
- if (at + 1 < source.Length && source[at] == '/' && source[at + 1] == '/')
+ string? error = null;
+ if (char.IsWhiteSpace(source[at]))
+ {
+ while (at < source.Length && char.IsWhiteSpace(source[at])) at++;
+ if (!lossless) continue;
+ shape = "whitespace";
+ }
+ else if (at + 1 < source.Length && source[at] == '/' && source[at + 1] == '/')
{
at += 2;
while (at < source.Length && source[at] != '\n') at++;
@@ -314,17 +320,21 @@ public static class FirmamentLanguageAnalysisService
var end = source.IndexOf("*/", at + 2, StringComparison.Ordinal);
at = end < 0 ? source.Length : end + 2;
shape = "comment";
+ if (end < 0) error = "Unterminated block comment; expected '*/'.";
}
else if (source[at] == '"')
{
at++;
+ var closed = false;
while (at < source.Length)
{
if (source[at] == '\\' && at + 1 < source.Length) { at += 2; continue; }
if (source[at++] != '"') continue;
+ closed = true;
break;
}
shape = "string";
+ if (!closed) error = "Unterminated string literal; expected a closing quote.";
}
else if (char.IsLetter(source[at]) || source[at] == '_')
{
@@ -332,15 +342,45 @@ public static class FirmamentLanguageAnalysisService
while (at < source.Length && (char.IsLetterOrDigit(source[at]) || source[at] == '_')) at++;
shape = "identifier";
}
+ else if (source[at] == '.' && result.Count > 0 && result[^1].Shape == "identifier"
+ && result[^1].Start + result[^1].Length == at)
+ {
+ at++;
+ shape = "punctuation";
+ }
+ else if (char.IsDigit(source[at]) && result.Count > 1 && result[^1].Text == "."
+ && result[^2].Shape == "identifier" && result[^1].Start + 1 == at)
+ {
+ // External domain symbols such as StainlessSteel.304_Annealed.
+ at++;
+ while (at < source.Length && (char.IsLetterOrDigit(source[at]) || source[at] == '_')) at++;
+ shape = "identifier";
+ }
else if (char.IsDigit(source[at]) || source[at] == '.' && at + 1 < source.Length && char.IsDigit(source[at + 1]))
{
at++;
- while (at < source.Length && (char.IsDigit(source[at]) || source[at] == '.')) at++;
+ while (at < source.Length && char.IsDigit(source[at])) at++;
+ if (source[start] != '.' && at + 1 < source.Length && source[at] == '.' && char.IsDigit(source[at + 1]))
+ {
+ at++;
+ while (at < source.Length && char.IsDigit(source[at])) at++;
+ }
+ if (at < source.Length && source[at] is 'e' or 'E')
+ {
+ var exponent = at + 1;
+ if (exponent < source.Length && source[exponent] is '+' or '-') exponent++;
+ if (exponent < source.Length && char.IsDigit(source[exponent]))
+ {
+ at = exponent + 1;
+ while (at < source.Length && char.IsDigit(source[at])) at++;
+ }
+ }
shape = "number";
}
else { at++; shape = "punctuation"; }
- result.Add(new(start, at - start, source[start..at], shape));
+ result.Add(new(start, at - start, source[start..at], shape, error));
}
+ if (lossless) result.Add(new(source.Length, 0, "", "end"));
return result;
}
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 5ab53d18..4add9355 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -274,7 +274,7 @@ public sealed record FirmamentV2ProfileDecl(string Name, string Frame, double Fr
public sealed record FirmamentV2ComposeDecl(string Name, IReadOnlyList<string> Operations, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2BossDecl(string Name, string Host, string On, string Profile, double Height, string StableId, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2PocketDecl(string Name, string Host, string On, string Profile, double Depth, double HostThickness, double RemainingFloor, double MinimumFloorThickness, string MinimumFloorPolicySource, string StableId, FirmamentV2SourceSpan SourceSpan);
-public sealed record FirmamentV2SelectionDecl(string Name, string Target, string Source, string Requirement, FirmamentV2SourceSpan SourceSpan);
+public sealed record FirmamentV2SelectionDecl(string Name, string Target, string Source, string Requirement, FirmamentV2SourceSpan SourceSpan) { public IReadOnlyList<string>? Sources { get; init; } }
/// <summary>Normalized, erased-before-materialization evidence for canonical static authoring.</summary>
public sealed record FirmamentV2StaticAuthoringDocument(IReadOnlyList<FirmamentV2RecordTypeDecl> RecordTypes, IReadOnlyList<FirmamentV2StaticArrayDecl> Arrays, IReadOnlyList<FirmamentV2CanonicalTemplateDecl> Templates, IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, IReadOnlyList<FirmamentV2RequireDecl> Requires, IReadOnlyList<FirmamentV2SemanticConstraint>? SemanticConstraints = null, IReadOnlyDictionary<string, FirmamentV2PmiProjection>? PmiProjections = null, IReadOnlyList<FirmamentV2StaticRecordDecl>? StaticRecords = null, IReadOnlyList<FirmamentV2StaticTableDecl>? Tables = null, IReadOnlyList<FirmamentV2StaticSetDecl>? Sets = null, IReadOnlyList<FirmamentV2MirrorDerivation>? Mirrors = null, IReadOnlyList<FirmamentV2RadialPatternDecl>? RadialPatterns = null, IReadOnlyList<FirmamentV2LinearPatternDecl>? LinearPatterns = null, IReadOnlyList<FirmamentV2Axis2Decl>? PlanarAxes = null, IReadOnlyList<ConceptIrKeyedPointSetValue>? ConceptPoints = null);
public sealed record FirmamentV2RecordTypeDecl(string Name, IReadOnlyDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);
@@ -320,7 +320,14 @@ public sealed record FirmamentV2ParseResult(
{
/// <summary>Debug metadata, assigned where the existing parser route is selected.</summary>
public string? ParserRoute { get; init; }
+ public IReadOnlyList<FirmamentV2ValidationDiagnostic> SyntaxDiagnostics { get; init; } = [];
internal string? OriginalSource { get; init; }
+ // Bound engineering inputs are retained for execution; a successful AST admission
+ // cannot be replaced by a different whole-document parser in the build path.
+ internal PrismaticProfileCompositionParseResult? BoundComposition { get; init; }
+ internal ResolvedProfile2D? BoundProfile { get; init; }
+ internal double ExtrusionHeight { get; init; }
+ internal string? BoundSource { 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.cs
new file mode 100644
index 00000000..3e78e8ca
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
@@ -0,0 +1,331 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+public static partial class FirmamentV2Parser
+{
+ private static IEnumerable<DeclarationSyntax> MechanicalDeclarations(IEnumerable<StatementSyntax> statements)
+ {
+ foreach (var declaration in statements.OfType<DeclarationSyntax>())
+ {
+ if (declaration.Modifiers.Any(m => m.Name.Text == "Template") || declaration.Type.Name.Text == "Template") continue;
+ yield return declaration;
+ if (declaration.Type.Name.Text == "Struct" && !declaration.Modifiers.Any(m => m.Name.Text == "Concept"))
+ foreach (var child in MechanicalDeclarations(declaration.Body?.Statements ?? [])) yield return child;
+ }
+ }
+
+ private 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
+ /// follows declared material bodies; unused construction data cannot select a grammar.</summary>
+ private static FirmamentV2ParseResult BindMechanicalModel(DocumentSyntax syntax, DeclarationSyntax model,
+ string source, List<string> diagnostics, string? sourceDirectory,
+ IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations)
+ {
+ if (model.Body is null || model.Name is null) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
+ if (model.Clauses.Count > 0 || model.Type.Arguments.Count > 0)
+ return CanonicalFailure(diagnostics, "firmament-v2-mechanical-root-header-unsupported: Use the admitted Model/Struct header and declare placement in its owning construct.");
+ if (model.Annotation is not null)
+ return ParseConceptModelingDocument(source, diagnostics, templateInstantiations);
+ BindMechanicalScope(syntax.Statements.Where(s => !ReferenceEquals(s, model)).ToArray(), diagnostics);
+ BindMechanicalScope(model.Body.Statements, diagnostics);
+ if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
+ var declarations = MechanicalDeclarations(model.Body.Statements).ToArray();
+ var primitives = declarations.Where(IsPrimitiveDeclaration).ToArray();
+ var constructions = declarations.Where(d => d.Type.Name.Text is "Compose" or "Extrude").ToArray();
+ var materialConstruction = constructions.Length > 0;
+ if (constructions.Length > 1 && constructions.All(d => d.Type.Name.Text == "Extrude") && primitives.Length == 0)
+ return BindMechanicalExtrusionStack(model, constructions, source, diagnostics);
+ if (constructions.Length > 1 || materialConstruction && primitives.Length > 0)
+ return CanonicalFailure(diagnostics, "firmament-v2-mechanical-material-owners-unsupported: Use one material body per mechanical document; use Assembly for separate parts.");
+ // Concept-valued stock retains its existing semantic resolver. Its actual
+ // declarations do not change the grammar of neighbouring nodes.
+ var semanticStock = declarations.Any(d => d.Type.Name.Text == "Modify" && d.Body?.Statements.OfType<DeclarationSyntax>().Any(f => f.Type.Name.Text == "Pattern") == true)
+ || declarations.Any(d => d.Type.Name.Text == "Struct" && d.Annotation is not null)
+ || declarations.Where(d => d.Type.Name.Text == "Modify").SelectMany(d => d.Body?.Statements.OfType<DeclarationSyntax>() ?? [])
+ .Any(d => d.Type.Name.Text == "Hole" && d.Body?.Statements.OfType<FieldSyntax>().Any(f => f.Name.Text == "From" || f.Name.Text == "On" && FirmamentSyntaxValues.Reference(f.Value) is not ("+X" or "-X" or "+Y" or "-Y" or "+Z" or "-Z")) == true);
+ if (materialConstruction || semanticStock || primitives.Any(d => d.Body?.Statements.OfType<FieldSyntax>().Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Bounds")) == true))
+ return BindMechanicalConstruction(source, model, diagnostics, templateInstantiations);
+
+ var units = model.Body.Statements.OfType<FieldSyntax>().Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Units")).ToArray();
+ if (units.Length == 0 && model.Type.Name.Text != "Struct" || units.Any(f => FirmamentSyntaxValues.Reference(f.Value) != "mm")) return CanonicalFailure(diagnostics, CanonicalUnitsInvalid);
+ foreach (var profile in declarations.Where(d => d.Type.Name.Text == "Profile" && d.Name is not null))
+ {
+ _ = ProfileAuthoringParser.ResolveNamedProfile(source, profile.Name!.Text, out var profileDiagnostics);
+ diagnostics.AddRange(profileDiagnostics);
+ }
+ var solids = new Dictionary<string, FirmamentV2SolidBinding>(StringComparer.Ordinal);
+ foreach (var declaration in primitives)
+ {
+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);
+ var primitive = BindMechanicalPrimitive(fields, diagnostics);
+ FirmamentV2HollowIntent? hollow = null;
+ if (declaration.Type.Arguments.Count > 0)
+ hollow = BindMechanicalHollow(fields, primitive, diagnostics);
+ fields.Complete();
+ if (primitive is null) { diagnostics.Add(CanonicalPrimitiveMalformed); continue; }
+ if (declaration.Name is null || !solids.TryAdd(declaration.Name.Text, new(declaration.Name.Text,
+ declaration.Type.Name.Text, primitive, ConstructionPolicy: hollow is null ? FirmamentV2ConstructionPolicy.Solid : FirmamentV2ConstructionPolicy.Hollow, Hollow: hollow, SourceSpan: declaration.Span, AuthoredFields: fields.AuthoredFields))) diagnostics.Add(DuplicateName);
+ }
+ foreach (var declaration in declarations.Where(d => d.Type.Name.Text == "InlineStep"))
+ {
+ var body = declaration.Body;
+ if (body is null || declaration.Name is null) { diagnostics.Add(CanonicalPrimitiveMalformed); continue; }
+ var imported = ParseInlineStep(declaration.Name.Text, source.Substring(body.Span.Start + 1, body.Span.Length - 2), diagnostics, sourceDirectory);
+ if (imported is not null && !solids.TryAdd(imported.Name, imported)) diagnostics.Add(DuplicateName);
+ }
+ if (solids.Count == 0) diagnostics.Add(MissingSolid);
+ var modifies = new List<FirmamentV2ModifyBlock>();
+ foreach (var modify in declarations.Where(d => d.Type.Name.Text == "Modify"))
+ {
+ if (modify.Clauses.Count > 0 || modify.Type.Arguments.Count > 0) diagnostics.Add(CanonicalModifyMalformed);
+ if (modify.Name is null || !solids.TryGetValue(modify.Name.Text, out var solid)) { diagnostics.Add(ModifyTargetUnresolved); continue; }
+ var holes = new List<FirmamentV2SemanticHoleDecl>(); var finishes = new List<FirmamentV2EdgeFinishDecl>(); var perforations = new List<FirmamentV2PerforationDecl>();
+ foreach (var statement in modify.Body?.Statements ?? [])
+ {
+ if (statement is not DeclarationSyntax feature) { diagnostics.Add(CanonicalModifyMalformed); continue; }
+ var fields = new FirmamentSyntaxFields(feature, diagnostics);
+ switch (feature.Type.Name.Text)
+ {
+ case "Hole":
+ if (BindMechanicalHole(fields, diagnostics) is { } hole) holes.Add(hole);
+ break;
+ case "EdgeFinish":
+ if (BindMechanicalFinish(fields, diagnostics) is { } finish) finishes.Add(finish);
+ break;
+ case "Perforation":
+ if (BindMechanicalPerforation(fields, diagnostics) is { } perforation) perforations.Add(perforation);
+ break;
+ default: diagnostics.Add($"{CanonicalDeclarationUnknown}:Modify:{feature.Type.Name.Text}"); break;
+ }
+ fields.Complete();
+ }
+ if (holes.Count > 0 && solid.Box is null) diagnostics.Add(ModifyTargetNotSolid);
+ if (solid.ConstructionPolicy == FirmamentV2ConstructionPolicy.Hollow &&
+ (solid.Cylinder is null || holes.Count > 0 || finishes.Count > 0 || perforations.Count != 1 ||
+ perforations.Any(p => p.SupportFace != "OuterWall" || p.Layout is not ("CylindricalGrid" or "CylindricalStaggered"))))
+ diagnostics.Add("firmament-v2-hollow-modify-unsupported");
+ modifies.Add(new(solid.Name, [], holes, finishes, perforations));
+ }
+ var bodyText = source.Substring(model.Body.Span.Start + 1, model.Body.Span.Length - 2);
+ var recognized = ParseCanonicalRecognizedRegions(bodyText, solids, diagnostics);
+ var replacements = ParseCanonicalReplacements(bodyText, solids, recognized, diagnostics);
+ var selections = ParseCanonicalSelections(bodyText, model.Body.Span.Start + 1, diagnostics);
+ ValidateCanonicalSelectionSources(bodyText, selections, [], diagnostics);
+ var (pmi, pmiBlock, boundPmi) = ParsePmi(source, solids, modifies, recognized, [], [], diagnostics);
+ if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
+ return FirmamentV2ParseResult.Success(new(model.Name.Text, "mm", solids.Values.ToArray(), modifies,
+ Pmi: pmi, RecognizedRegions: recognized, Replacements: replacements, PmiBlock: pmiBlock, BoundPmi: boundPmi, Selections: selections),
+ diagnostics.Append("firmament-v2-unified-canonical-parsed").Append("firmament-v2-parse-succeeded").Distinct(StringComparer.Ordinal).Order().ToArray());
+ }
+
+ // Multiple explicit extrusions are material requests, not alternative parser
+ // hints. Bind every one into the existing section-stack engineering IR.
+ private static FirmamentV2ParseResult BindMechanicalExtrusionStack(DeclarationSyntax model, IReadOnlyList<DeclarationSyntax> extrusions,
+ string source, List<string> diagnostics)
+ {
+ var units = model.Body!.Statements.OfType<FieldSyntax>().Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Units")).ToArray();
+ if (units.Length == 0 && model.Type.Name.Text != "Struct" || units.Any(f => FirmamentSyntaxValues.Reference(f.Value) != "mm")) return CanonicalFailure(diagnostics, CanonicalUnitsInvalid);
+ if (MechanicalDeclarations(model.Body.Statements).Any(d => d.Type.Name.Text == "Modify"))
+ return CanonicalFailure(diagnostics, "firmament-v2-extrusion-stack-modify-unsupported: Use Compose for features on a multi-extrusion body.");
+ var profiles = new Dictionary<string, ResolvedProfile2D>(StringComparer.Ordinal);
+ var operations = new List<PrismaticProfileOperation>();
+ foreach (var d in extrusions)
+ {
+ var fields = new FirmamentSyntaxFields(d, diagnostics);
+ var profileName = fields.Word("Profile"); var from = fields.Number("From", "mm"); var to = fields.Number("To", "mm");
+ var role = fields.Word("Role") ?? "Stock";
+ fields.Complete();
+ if (profileName is null || d.Name is null || !double.IsFinite(from) || !double.IsFinite(to) || from >= to)
+ { diagnostics.Add("profile-extrude-missing-or-mismatched"); continue; }
+ if (!profiles.TryGetValue(profileName, out var profile))
+ {
+ profile = ProfileAuthoringParser.ResolveNamedProfile(source, profileName, out var reported);
+ diagnostics.AddRange(reported);
+ if (profile is null) continue;
+ profiles.Add(profileName, profile);
+ }
+ if (profile.EffectiveConstructionPlane != ConstructionPlane.WorldXY)
+ { diagnostics.Add("firmament-v2-extrusion-stack-frame-unsupported: Multiple extrusions currently require the shared world XY frame."); continue; }
+ if (operations.Any(operation => operation.Name == d.Name.Text)) { diagnostics.Add(DuplicateName); continue; }
+ operations.Add(new(d.Name.Text, operations.Count == 0 ? PrismaticProfileIntent.Base : PrismaticProfileIntent.Add,
+ profileName, from, to, role, $"offset:{d.Span.Start}"));
+ }
+ if (diagnostics.Any(IsFatalDiagnosticCode) || operations.Count != extrusions.Count) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
+ var name = model.Name!.Text;
+ var placement = new PrismaticProfilePlacement("LegacyImplicitWorldXY", 0, 0, 0, "XY", "+Z", "+X", false);
+ var feature = new PrismaticProfileCompositionFeature(name, "XY", "+Z", placement, operations,
+ operations.SelectMany(o => new[] { o.From, o.To }).Distinct().Order().ToArray(), "ast-extrusion-stack");
+ var composition = new PrismaticProfileCompositionParseResult(feature, profiles, []);
+ var solids = new Dictionary<string, FirmamentV2SolidBinding>(StringComparer.Ordinal)
+ { [name] = new(name, "Compose", new FirmamentV2AdvancedMaterialRecord("Compose")) };
+ var selections = ParseCanonicalSelections(source, 0, diagnostics);
+ ValidateCanonicalSelectionSources(source, selections, profiles.Keys, diagnostics);
+ var (pmi, pmiBlock, boundPmi) = ParsePmi(source, solids, [], [], [], [], diagnostics);
+ if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
+ var document = new FirmamentV2Document(name, "mm", solids.Values.ToArray(),
+ Pmi: pmi, PmiBlock: pmiBlock, BoundPmi: boundPmi, Selections: selections,
+ Profiles: profiles.Values.Select(p => new FirmamentV2ProfileDecl(p.Name, p.EffectiveConstructionPlane.StableId, 0, 0, model.Span)).ToArray(),
+ Composes: [new(name, operations.Select(o => o.Name).ToArray(), model.Span)]);
+ return FirmamentV2ParseResult.Success(document, diagnostics.Append("firmament-v2-parse-succeeded").Distinct(StringComparer.Ordinal).Order().ToArray())
+ with { BoundComposition = composition, BoundSource = source };
+ }
+
+ private static FirmamentV2HollowIntent? BindMechanicalHollow(FirmamentSyntaxFields f, FirmamentV2PrimitiveRecord? primitive, List<string> diagnostics)
+ {
+ var d = f.Declaration;
+ if (d.Type.Arguments.Count != 1 || FirmamentSyntaxValues.Reference(d.Type.Arguments[0].Value) != "Hollow")
+ { diagnostics.Add(UnknownConstructionPolicy); return null; }
+ if (d.Type.Name.Text is not ("RoundedBox" or "Cylinder" or "Frustum"))
+ { diagnostics.Add(PrimitiveDoesNotSatisfyHollowConstructible); return null; }
+ var wallExpression = f.Take("WallThickness");
+ if (wallExpression is null) diagnostics.Add(WallThicknessRequired);
+ var wall = FirmamentSyntaxValues.TryMeasure(wallExpression, "mm", out var w) ? w : double.NaN;
+ if (!(wall > 0)) diagnostics.Add(WallThicknessMustBePositive);
+ var openings = f.Take("Openings") as SequenceSyntax;
+ var items = openings?.Items.Select(a => FirmamentSyntaxValues.Reference(a.Value)).ToArray() ?? [];
+ if (items.Length != 1 || items[0] != "Top") diagnostics.Add(items.Length > 1 ? MultipleOpeningsNotSupported : UnsupportedOpening);
+ var blendExpression = f.Take("BottomBlendRadius");
+ var blend = blendExpression is null ? 0 : FirmamentSyntaxValues.TryMeasure(blendExpression, "mm", out var b) ? b : double.NaN;
+ if (blendExpression is not null && (primitive is not FirmamentV2CylinderRecord cylinder || !(blend > wall && blend < cylinder.Radius && blend < cylinder.Height)))
+ diagnostics.Add("firmament-v2-hollow-bottom-blend-invalid");
+ return new(wall, items.OfType<string>().ToArray(), d.Span, blend);
+ }
+
+ private static FirmamentV2PrimitiveRecord? BindMechanicalPrimitive(FirmamentSyntaxFields f, List<string> diagnostics)
+ {
+ var type = f.Declaration.Type.Name.Text;
+ double Length(string name) => f.Number(name, "mm");
+ double[]? Size() => f.Vector("Size", "mm", out var values) && values.Length == 3 && values.All(v => v > 0) ? values : null;
+ switch (type)
+ {
+ case "Box": return Size() is { } box ? new FirmamentV2BoxRecord(box, []) : null;
+ case "Cylinder":
+ var radius = Length("Radius"); var height = Length("Height");
+ return radius > 0 && height > 0 ? new FirmamentV2CylinderRecord(radius, height) : null;
+ case "Cone":
+ var bottom = Length("BottomRadius"); var top = Length("TopRadius"); var coneHeight = Length("Height");
+ return bottom > 0 && top >= 0 && coneHeight > 0 ? new FirmamentV2ConeRecord(bottom, top, coneHeight) : null;
+ case "Sphere": var sphere = Length("Radius"); return sphere > 0 ? new FirmamentV2SphereRecord(sphere) : null;
+ case "Torus":
+ var major = Length("MajorRadius"); var minor = Length("MinorRadius");
+ return major > minor && minor > 0 ? new FirmamentV2TorusRecord(major, minor) : null;
+ case "RoundedBox":
+ var size = Size(); var corner = Length("CornerRadius");
+ return size is not null && corner > 0 && corner < Math.Min(size[0], size[1]) / 2 ? new FirmamentV2RoundedBoxRecord(size, corner) : null;
+ case "Frustum":
+ var low = Length("BottomRadius"); var high = Length("TopRadius"); var h = Length("Height");
+ return low > 0 && high > 0 && h > 0 && Math.Abs(low - high) > 1e-12 ? new FirmamentV2FrustumRecord(low, high, h) : null;
+ // These recipe binders own family-specific field schemas. Their input
+ // is admitted through their existing typed recipe authority below.
+ case "StandardPart":
+ var family = f.Word("Family");
+ if (family is null) return null;
+ return new FirmamentV2StandardPartRecord(family, RecipeFields(f));
+ case "ExactCoaxialPart": return new FirmamentV2ExactCoaxialPartRecord(RecipeFields(f));
+ default: return null;
+ }
+ }
+
+ private static Dictionary<string, string> RecipeFields(FirmamentSyntaxFields f)
+ {
+ var result = new Dictionary<string, string>(StringComparer.Ordinal);
+ foreach (var field in f.Declaration.Body?.Statements.OfType<FieldSyntax>() ?? [])
+ {
+ var value = f.Take(field.Name.Text);
+ if (field.Name.Text == "Family") continue;
+ result[field.Name.Text] = value switch
+ {
+ LiteralSyntax literal => literal.Raw,
+ QuantitySyntax { Value: LiteralSyntax literal } q => literal.Raw + q.Unit.Text,
+ _ => FirmamentSyntaxValues.Reference(value) ?? ""
+ };
+ }
+ return result;
+ }
+
+ private static FirmamentV2SemanticHoleDecl? BindMechanicalHole(FirmamentSyntaxFields f, List<string> diagnostics)
+ {
+ var d = f.Declaration;
+ var variantName = d.Type.Arguments.Count == 1 ? FirmamentSyntaxValues.Reference(d.Type.Arguments[0].Value) : null;
+ if (!Enum.TryParse<FirmamentV2SemanticHoleVariant>(variantName, out var variant)) { diagnostics.Add(HoleVariantUnknown); return null; }
+ var axis = f.Word("On"); var point = f.Take("Center"); var diameter = f.Number("Diameter", "mm");
+ var endExpression = f.Take("End"); var end = FirmamentSyntaxValues.Reference(endExpression);
+ f.Take("PatternIdentity");
+ FirmamentV2SemanticHoleEnd? termination = end == "ThroughAll" ? new(FirmamentV2SemanticHoleEndKind.ThroughAll) : null;
+ if (endExpression is CallSyntax { Target: ReferenceSyntax { Name.Text: "Blind" }, Arguments.Count: 1 } blind
+ && FirmamentSyntaxValues.TryMeasure(blind.Arguments[0].Value, "mm", out var depth) && depth > 0) termination = new(FirmamentV2SemanticHoleEndKind.Depth, depth);
+ double? cbDiameter = null, cbDepth = null, csDiameter = null, csAngle = null;
+ if (variant == FirmamentV2SemanticHoleVariant.Counterbore) { cbDiameter = f.Number("CounterboreDiameter", "mm"); cbDepth = f.Number("CounterboreDepth", "mm"); }
+ if (variant == FirmamentV2SemanticHoleVariant.Countersink) { csDiameter = f.Number("CountersinkDiameter", "mm"); csAngle = f.Number("CountersinkAngle", "deg"); }
+ if (point is not CallSyntax { Target: ReferenceSyntax { Name.Text: "Point2" } } || !FirmamentSyntaxValues.Vector(point, "mm", out var center) || center.Length != 2) { diagnostics.Add(CanonicalPoint2Invalid); return null; }
+ if (axis is not ("+X" or "-X" or "+Y" or "-Y" or "+Z" or "-Z") || termination is null || d.Name is null) { diagnostics.Add(CanonicalModifyMalformed); return null; }
+ if (!(diameter > 0)) { diagnostics.Add(HoleDiameterInvalid); return null; }
+ if (cbDiameter is not null && (!(cbDiameter > diameter) || !(cbDepth > 0))) { diagnostics.Add(HoleCounterboreInvalid); return null; }
+ if (csDiameter is not null && (!(csDiameter > diameter) || !(csAngle > 0 && csAngle < 180))) { diagnostics.Add(HoleCountersinkInvalid); return null; }
+ var face = FirmamentV2FaceTarget.Direct(axis);
+ return new(d.Name.Text, variant, face, new(center[0], center[1], FirmamentV2FaceLocalPoint2D.ConventionFor(axis)), diameter, termination,
+ cbDiameter, cbDepth, csDiameter, csAngle, SourceSpan: d.Span, AuthoredFields: f.AuthoredFields);
+ }
+
+ private static FirmamentV2EdgeFinishDecl? BindMechanicalFinish(FirmamentSyntaxFields f, List<string> diagnostics)
+ {
+ if (f.Declaration.Type.Arguments.Count != 0) { diagnostics.Add(CanonicalModifyMalformed); return null; }
+ var axis = f.Word("Face"); var target = f.Word("Target"); var kind = f.Word("Kind");
+ var distance = f.Take("Distance"); var radius = f.Take("Radius");
+ if ((distance is not null && radius is not null) || f.Declaration.Name is null || axis is null || target is null || kind is null
+ || !FirmamentSyntaxValues.TryMeasure(distance ?? radius, "mm", out var value) || value <= 0)
+ { diagnostics.Add(CanonicalModifyMalformed); return null; }
+ return new(f.Declaration.Name.Text, axis, target, kind, value, f.Declaration.Span);
+ }
+
+ private static FirmamentV2PerforationDecl? BindMechanicalPerforation(FirmamentSyntaxFields f, List<string> diagnostics)
+ {
+ var on = f.Word("On"); var layout = f.Word("Layout");
+ var diameter = f.Number("Diameter", "mm"); var pitch = f.Number("Pitch", "mm");
+ var margin = f.Number("Margin", "mm", 0); var ligament = f.Number("MinimumLigament", "mm", 0);
+ var offsetX = f.Number("OffsetX", "mm", 0); var offsetY = f.Number("OffsetY", "mm", 0);
+ var circumferential = f.Number("CircumferentialPitch", "mm");
+ var top = f.Number("MarginTop", "mm"); var bottom = f.Number("MarginBottom", "mm"); var angle = f.Number("StartAngle", "deg", 0);
+ if (on is null || layout is null || !(diameter > 0 && pitch > 0 && margin >= 0 && ligament >= 0) || f.Declaration.Name is null)
+ { diagnostics.Add("perforation-field-invalid"); return null; }
+ return new(f.Declaration.Name.Text, on, layout, diameter, pitch, margin, ligament, offsetX, offsetY, f.Declaration.Span,
+ double.IsNaN(circumferential) ? null : circumferential, double.IsNaN(top) ? null : top, double.IsNaN(bottom) ? null : bottom, angle);
+ }
+
+ private static void BindMechanicalScope(IReadOnlyList<StatementSyntax> statements, List<string> diagnostics)
+ {
+ foreach (var statement in statements)
+ {
+ if (statement is DirectiveSyntax) continue;
+ if (statement is DeclarationSyntax definition && definition.Modifiers.Any(m => m.Name.Text == "Template")) continue;
+ if (statement is FieldSyntax field)
+ {
+ if (!FirmamentSyntaxFields.SameField(field.Name.Text, "Units") && !FirmamentSyntaxFields.SameField(field.Name.Text, "Material"))
+ diagnostics.Add($"{CanonicalFieldUnknown}:Model:{field.Name.Text}");
+ continue;
+ }
+ if (statement is not DeclarationSyntax declaration)
+ {
+ diagnostics.Add(CanonicalDeclarationUnrecognized); continue;
+ }
+ if (declaration.Modifiers.Any(m => m.Name.Text == "Assert")) continue;
+ switch (declaration.Type.Name.Text)
+ {
+ case "Struct" when declaration.Annotation is not null: break;
+ case "Struct" when !declaration.Modifiers.Any(m => m.Name.Text == "Concept"):
+ BindMechanicalScope(declaration.Body?.Statements ?? [], diagnostics); break;
+ case "Box" or "Cylinder" or "Cone" or "Sphere" or "Torus" or "RoundedBox" or "Frustum" or "StandardPart" or "ExactCoaxialPart":
+ case "Plane" or "Axis" or "Axis2" or "Point2" or "Line2" or "CubicBezier2" or "Rect2" or "Square2" or "Triangle2" or "Polygon2" or "RegularPolygon2" or "Circle2" or "Ellipse2" or "Ellipse2Guide" or "Slot2" or "RoundedRect2" or "SmoothRoundedRect2" or "Path":
+ case "Plateau" or "Concept" or "Struct" or "Profile" or "Span" or "Compose" or "Boss" or "Pocket" or "AddOffset" or "RemoveOffset" or "EdgeFinish" or "Extrude":
+ case "Enum" or "Expose" or "Record" or "Static" or "Template" or "template" or "Feature" or "ProfileDelta" or "Selection" or "InlineStep" or "Recognize" or "Replace" or "Pmi" or "Modify" or "Match" or "Require" or "Assert" or "Thread":
+ break;
+ case "Solid": diagnostics.Add(CanonicalConstructNotYetSupported + ":Solid"); break;
+ default: diagnostics.Add(CanonicalDeclarationUnrecognized); diagnostics.Add($"{CanonicalDeclarationUnknown}:{declaration.Type.Name.Text}"); break;
+ }
+ }
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 57fbb7a9..55754125 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -4,10 +4,11 @@ using System.Text;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Air;
using Aetheris.Kernel.Firmament.Materializer;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
-public static class FirmamentV2Parser
+public static partial class FirmamentV2Parser
{
public const string MissingModel = "firmament-v2-missing-model";
public const string MissingUnits = "firmament-v2-missing-units";
@@ -281,15 +282,11 @@ public static class FirmamentV2Parser
private static readonly Regex FillRegionHeaderRegex = new(@"\bregion\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex FillHeaderRegex = new(@"\bfill\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex CanonicalModelRegex = new(@"^\s*Model\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
- private static readonly Regex CanonicalPrimitiveHeaderRegex = new(@"\b(?<type>Box|Cylinder|Cone|Sphere|Torus|RoundedBox|Frustum|StandardPart|ExactCoaxialPart)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex CanonicalInlineStepHeaderRegex = new(@"\bInlineStep\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
- private static readonly Regex CanonicalModifyHeaderRegex = new(@"\bModify\s+(?<target>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
// Match the declaration-shaped header first; variant admission belongs in the
// binder so a misspelled family can never disappear from a Modify block.
- private static readonly Regex CanonicalHoleHeaderRegex = new(@"\bHole\s*<\s*(?<variant>[A-Za-z_][A-Za-z0-9_]*)\s*>\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex CanonicalPerforationHeaderRegex = new(@"\bPerforation\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex CanonicalThreadHeaderRegex = new(@"\bThread\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
- private static readonly Regex CanonicalEdgeHeaderRegex = new(@"\bEdgeFinish\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex CanonicalRecognizeHeaderRegex = new(@"\bRecognize\s+(?<body>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex CanonicalRegionHeaderRegex = new(@"\bRegion\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex CanonicalReplaceHeaderRegex = new(@"\bReplace\s+(?<body>[A-Za-z_][A-Za-z0-9_]*)\.(?<region>[A-Za-z_][A-Za-z0-9_]*)\s+With\s+(?<kind>[A-Za-z_][A-Za-z0-9_]*(?:\s*<\s*[A-Za-z_][A-Za-z0-9_]*\s*>)?)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
@@ -337,6 +334,13 @@ public static class FirmamentV2Parser
private static FirmamentV2ParseResult CompleteAdmission(FirmamentV2ParseResult result, string originalSource)
{
+ if (result.SyntaxDiagnostics.Count > 0)
+ {
+ var original = FirmamentSyntaxParser.Parse(originalSource);
+ result = result with { SyntaxDiagnostics = original.Diagnostics.Count > 0 ? original.Diagnostics
+ : result.SyntaxDiagnostics.Select(d => d with { SourceSpan = null, Line = null, Column = null,
+ LocationNote = "The error occurs after expansion; original-source provenance is unavailable." }).ToArray() };
+ }
var hasErrors = result.Diagnostics.Any(IsFatalDiagnosticCode);
return result with
{
@@ -449,23 +453,26 @@ public static class FirmamentV2Parser
// Canonical V2 is parsed as one document, before compatibility adapters. The
// adapters below remain only for old fixtures and no longer define the language
// an author must select for ordinary mechanical work.
- if (CanonicalModelRegex.IsMatch(source))
- {
- var declarationDiagnostics = ScanCanonicalTopLevelDeclarations(source);
- if (declarationDiagnostics.Count > 0)
- {
- diagnostics.AddRange(declarationDiagnostics);
- return Recognized(CanonicalFailure(diagnostics, CanonicalDocumentMalformed)) with { ParserRoute = "Canonical" };
- }
- var parsed = Recognized(ContainsCanonicalAdvancedDeclaration(source)
- ? ParseCanonicalAdvancedDocument(source, diagnostics, templateExpansion.Instantiations)
- : ParseCanonicalDocument(source, diagnostics, sourceDirectory));
- parsed = parsed with { ParserRoute = ContainsCanonicalAdvancedDeclaration(source) ? "CanonicalAdvanced" : "Canonical" };
- if (parsed.Document is null) return parsed;
-
+ var syntax = FirmamentSyntaxParser.Parse(source);
+ var modelSyntax = syntax.Document.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d =>
+ d.Type.Name.Text is "Model" or "Struct" && !d.Modifiers.Any(m => m.Name.Text is "Template" or "Concept") && d.Body is not null
+ && (d.Type.Name.Text == "Model" || MechanicalDeclarations(d.Body.Statements).Any(n => IsPrimitiveDeclaration(n) || n.Type.Name.Text is "Compose" or "Extrude")));
+ // Dedicated material domains retain their established semantic owners.
+ // This is a decision over material declaration nodes, never a keyword
+ // search that lets an unused guide choose the mechanical grammar.
+ var rootMaterials = modelSyntax?.Body is null ? [] : MechanicalDeclarations(modelSyntax.Body.Statements).ToArray();
+ var hasMechanicalMaterial = rootMaterials.Any(d => IsPrimitiveDeclaration(d) || d.Type.Name.Text is "Compose" or "Extrude");
+ var dedicatedMaterialDomain = rootMaterials.Any(d => d.Type.Name.Text is "Revolve" or "WireForm" or "WireRoute" or "Sweep" or "SectionChain");
+ if (modelSyntax is not null && (hasMechanicalMaterial || !dedicatedMaterialDomain))
+ {
+ if (!syntax.IsSuccess)
+ return FirmamentV2ParseResult.Failure(diagnostics.Concat(syntax.Diagnostics.Select(d => d.Code)).ToArray(), FirmamentV2ParseDisposition.RecognizedInvalid)
+ with { ParserRoute = "UnifiedMechanical", SyntaxDiagnostics = syntax.Diagnostics };
+ var parsed = Recognized(BindMechanicalModel(syntax.Document, modelSyntax, source, diagnostics, sourceDirectory, templateExpansion.Instantiations));
+ if (parsed.Document is null) return parsed with { ParserRoute = "UnifiedMechanical" };
return WithFeatureMetadata(
AttachVolumeAssertionsAndSymbols(WithPolygonMetadata(parsed, polygonExpansion), source, canonicalStaticExpansion.Document, diagnostics),
- featureExpansion) with { ParserRoute = parsed.ParserRoute };
+ featureExpansion) with { ParserRoute = "UnifiedMechanical", BoundSource = parsed.BoundSource ?? source };
}
if (Regex.IsMatch(source, @"\b(?:RoundedBox|Frustum|Cylinder|Box)\s*<\s*[A-Za-z_][A-Za-z0-9_]*\s*>\s+[A-Za-z_]", RegexOptions.CultureInvariant))
@@ -1019,65 +1026,9 @@ public static class FirmamentV2Parser
}
/// <summary>
- /// The author-facing V2 grammar. It deliberately builds the same normalized
- /// document as all compatibility forms: materializer selection sees primitive
- /// and feature semantics, never the spelling that introduced them.
- /// </summary>
- private static bool ContainsCanonicalAdvancedDeclaration(string source) =>
- Regex.IsMatch(source, @"\b(?:Concept|Struct|Construction\s+Plane|Profile|Span|Compose|Selection|Template|Enum|Pattern|Require|Match)\b", RegexOptions.CultureInvariant);
-
- /// <summary>
- /// Canonical roots have one owner for every declaration-shaped block. This
- /// deliberately scans only brace-depth zero, so fields and feature blocks
- /// retain their more specific parsers and diagnostics.
+ /// Brace-depth extraction retained by legacy semantic adapters. Mechanical
+ /// document and statement admission is owned by the unified syntax tree.
/// </summary>
- private static IReadOnlyList<string> ScanCanonicalTopLevelDeclarations(string source)
- {
- var model = CanonicalModelRegex.Match(source);
- var rootOpen = model.Success ? source.IndexOf('{', model.Index) : -1;
- var rootClose = rootOpen < 0 ? -1 : FindMatchingBrace(source, rootOpen);
- if (rootClose < 0) return [];
-
- var known = new HashSet<string>(StringComparer.Ordinal)
- {
- "Box", "Cylinder", "Cone", "Sphere", "Torus", "RoundedBox", "Frustum", "StandardPart", "ExactCoaxialPart", "Plane", "Axis2", "Point2", "Line2", "CubicBezier2", "Rect2", "Circle2", "Ellipse2Guide", "SmoothRoundedRect2", "Plateau", "Concept", "Struct", "Construction", "Profile", "Span", "Compose", "Boss", "Pocket", "AddOffset", "RemoveOffset", "EdgeFinish",
- "Extrude", "Record", "Static", "Template", "template", "ProfileDelta", "Selection", "InlineStep", "Recognize", "Replace", "Pmi", "Modify", "Match", "Require", "Assert", "Thread"
- };
- var compatibilityOnly = new HashSet<string>(StringComparer.Ordinal)
- {
- "Solid", "Let", "Fill", "Manufacturing", "Feature", "Expose"
- };
- var diagnostics = new List<string>();
- var tokens = FirmamentLanguageAnalysisService.Lex(source[(rootOpen + 1)..rootClose])
- .Where(token => token.Shape != "comment").ToArray();
- for (var index = 0; index < tokens.Length;)
- {
- if (tokens[index].Text == ";") { index++; continue; }
- var keyword = tokens[index].Text;
- if (keyword is "Units" or "units" && index + 2 < tokens.Length && tokens[index + 1].Text == ":")
- { index += 3; continue; }
- if (!known.Contains(keyword))
- {
- if (!compatibilityOnly.Contains(keyword)) diagnostics.Add(CanonicalDeclarationUnrecognized);
- diagnostics.Add((compatibilityOnly.Contains(keyword) ? CanonicalConstructNotYetSupported : CanonicalDeclarationUnknown) + ":" + keyword);
- }
- // The admitted unbraced Profile form has four tokens and no executable body.
- if (keyword == "Profile" && index + 3 < tokens.Length && tokens[index + 2].Text == "From")
- { index += 4; continue; }
- while (index < tokens.Length && tokens[index].Text != "{") index++;
- if (index == tokens.Length) { diagnostics.Add(CanonicalDocumentMalformed); break; }
- var depth = 0;
- do
- {
- if (tokens[index].Text == "{") depth++;
- else if (tokens[index].Text == "}") depth--;
- index++;
- } while (index < tokens.Length && depth > 0);
- if (depth != 0) diagnostics.Add(CanonicalDocumentMalformed);
- }
- return diagnostics.Distinct(StringComparer.Ordinal).ToArray();
- }
-
private static int BraceDepth(string source, int start, int end)
{
var depth = 0;
@@ -1097,26 +1048,19 @@ public static class FirmamentV2Parser
/// production profile and section-stack readers remain semantic adapters; this
/// method owns the root, units, disposition, and normalized declaration list.
/// </summary>
- private static FirmamentV2ParseResult ParseCanonicalAdvancedDocument(string source, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations)
+ private static FirmamentV2ParseResult BindMechanicalConstruction(string source, DeclarationSyntax model, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations)
{
- var model = CanonicalModelRegex.Match(source);
- var rootOpen = model.Success ? source.IndexOf('{', model.Index) : -1;
- var rootClose = rootOpen >= 0 ? FindMatchingBrace(source, rootOpen) : -1;
- if (!model.Success || rootClose < 0 || !string.IsNullOrWhiteSpace(source[(rootClose + 1)..]))
- return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
-
- var body = source[(rootOpen + 1)..rootClose];
- var units = Regex.Match(body, @"\bUnits\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)\b", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
- if (!units.Success || units.Groups["value"].Value != "mm")
+ var rootOpen = model.Body!.Span.Start;
+ var body = source.Substring(rootOpen + 1, model.Body.Span.Length - 2);
+ var units = model.Body.Statements.OfType<FieldSyntax>().Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Units")).ToArray();
+ if (units.Length == 0 && model.Type.Name.Text != "Struct" || units.Any(f => FirmamentSyntaxValues.Reference(f.Value) != "mm"))
return CanonicalFailure(diagnostics, CanonicalUnitsInvalid);
- if (Regex.IsMatch(body, @"\b(?!(?:InlineStep|Recognize|Replace)\b)(?:Inline[A-Za-z_][A-Za-z0-9_]*|Recogniz[A-Za-z_][A-Za-z0-9_]*|Replac[A-Za-z_][A-Za-z0-9_]*)\b", RegexOptions.CultureInvariant))
- return CanonicalFailure(diagnostics, CanonicalDeclarationUnrecognized);
- var adapterSource = Regex.Replace(body, @"(?m)^\s*Units\s*:\s*mm\s*$", string.Empty, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
-
- if (TryParseExactCoaxialTemplateDocument(adapterSource, model.Groups["name"].Value, templateInstantiations, diagnostics, out var exactDocument))
+ var adapterSource = source[..model.Span.Start] + body + source[(model.Span.Start + model.Span.Length)..];
+ var declarations = MechanicalDeclarations(model.Body.Statements).ToArray();
+ if (TryParseExactCoaxialTemplateDocument(adapterSource, model.Name!.Text, templateInstantiations, diagnostics, out var exactDocument))
return FirmamentV2ParseResult.Success(exactDocument!, diagnostics.Append("firmament-v2-exact-coaxial-template-parsed").Append("firmament-v2-parse-succeeded").Distinct(StringComparer.Ordinal).Order().ToArray());
- if (PrismaticProfileCompositionParser.IsCompositionSource(adapterSource))
+ if (declarations.Any(d => d.Type.Name.Text == "Compose"))
{
var composition = PrismaticProfileCompositionParser.Parse(adapterSource);
if (composition.Feature is null)
@@ -1148,7 +1092,7 @@ public static class FirmamentV2Parser
}
if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
var document = new FirmamentV2Document(
- model.Groups["name"].Value,
+ model.Name!.Text,
"mm",
[new FirmamentV2SolidBinding(feature.Name, "Compose", new FirmamentV2AdvancedMaterialRecord("Compose"))],
Profiles: composition.Profiles.Values.Select(profile => new FirmamentV2ProfileDecl(profile.Name, profile.EffectiveConstructionPlane.StableId, profile.LocalStartDepth ?? 0d, profile.LocalEndDepth ?? 0d, new(0, 0))).ToArray(),
@@ -1165,10 +1109,10 @@ public static class FirmamentV2Parser
diagnostics.Add("firmament-v2-profile-compose-adapted");
diagnostics.Add("firmament-v2-parse-succeeded");
diagnostics.Sort(StringComparer.Ordinal);
- return FirmamentV2ParseResult.Success(document, diagnostics.Distinct(StringComparer.Ordinal).ToArray());
+ return FirmamentV2ParseResult.Success(document, diagnostics.Distinct(StringComparer.Ordinal).ToArray()) with { BoundComposition = composition, BoundSource = adapterSource };
}
- if (ProfileAuthoringParser.IsProfileSource(adapterSource))
+ if (declarations.Any(d => d.Type.Name.Text == "Extrude"))
{
var profile = ProfileAuthoringParser.Parse(adapterSource);
if (profile.Profile is null)
@@ -1199,7 +1143,7 @@ public static class FirmamentV2Parser
}
if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
var document = new FirmamentV2Document(
- model.Groups["name"].Value,
+ model.Name!.Text,
"mm",
[new FirmamentV2SolidBinding(resolved.Name, "Profile", new FirmamentV2AdvancedMaterialRecord("Profile"))],
Profiles: [new FirmamentV2ProfileDecl(resolved.Name, resolved.EffectiveConstructionPlane.StableId, resolved.LocalStartDepth ?? 0d, resolved.LocalEndDepth ?? profile.Height, new(0, body.Length))],
@@ -1212,10 +1156,10 @@ public static class FirmamentV2Parser
diagnostics.Add("firmament-v2-profile-adapted");
diagnostics.Add("firmament-v2-parse-succeeded");
diagnostics.Sort(StringComparer.Ordinal);
- return FirmamentV2ParseResult.Success(document, diagnostics.Distinct(StringComparer.Ordinal).ToArray());
+ return FirmamentV2ParseResult.Success(document, diagnostics.Distinct(StringComparer.Ordinal).ToArray()) with { BoundProfile = resolved, ExtrusionHeight = profile.Height, BoundSource = adapterSource };
}
- var concept = ParseConceptModelingDocument(adapterSource, diagnostics, templateInstantiations);
+ var concept = ParseConceptModelingDocument(declarations.Any(d => d.Type.Name.Text == "Struct" && !d.Modifiers.Any(m => m.Name.Text == "Concept")) ? adapterSource : source, diagnostics, templateInstantiations);
if (!concept.IsSuccess || concept.Document is null) return concept;
var conceptSolids = concept.Document.Solids.ToDictionary(solid => solid.Name, StringComparer.Ordinal);
var (conceptPmi, conceptPmiBlock, conceptBoundPmi) = ParsePmi(
@@ -1237,7 +1181,7 @@ public static class FirmamentV2Parser
}
var normalized = concept.Document with
{
- ModelName = model.Groups["name"].Value,
+ ModelName = model.Name!.Text,
Selections = conceptSelections,
Pmi = conceptPmi,
PmiBlock = conceptPmiBlock,
@@ -1257,7 +1201,7 @@ public static class FirmamentV2Parser
var open = source.IndexOf('{', primitive.Index); var close = FindMatchingBrace(source, open);
var materialized = Regex.Match(source, @"\bStruct\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<concept>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
if (close < 0 || !materialized.Success) { diagnostics.Add(CanonicalPrimitiveMalformed); return false; }
- if (ParseCanonicalPrimitive("ExactCoaxialPart", source[(open + 1)..close], diagnostics) is not FirmamentV2ExactCoaxialPartRecord recipe)
+ if (ReadExactCoaxialTemplateRecipe(source[(open + 1)..close]) is not FirmamentV2ExactCoaxialPartRecord recipe)
{ diagnostics.Add(CanonicalPrimitiveMalformed); return false; }
static string TextValue(string value) => value.Length >= 2 && value[0] == '"' && value[^1] == '"' ? value[1..^1] : value;
@@ -1305,37 +1249,22 @@ public static class FirmamentV2Parser
{
var selections = new List<FirmamentV2SelectionDecl>();
var names = new HashSet<string>(StringComparer.Ordinal);
- foreach (Match header in Regex.Matches(body, @"\bSelection\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant))
- {
- var name = header.Groups["name"].Value;
- var open = body.IndexOf('{', header.Index);
- var close = FindMatchingBrace(body, open);
- if (close < 0)
- {
- diagnostics.Add($"{SelectionMalformed}:{name}");
- continue;
- }
-
- if (!names.Add(name))
- {
- diagnostics.Add($"{SelectionDuplicateName}:{name}");
- continue;
- }
-
- var content = body[(open + 1)..close];
- string Field(string field) => Regex.Match(content, $@"\b{Regex.Escape(field)}\s*:\s*(?<value>[\s\S]*?)(?=\s+(?:Target|Source|Require)\s*:|\z)", RegexOptions.CultureInvariant).Groups["value"].Value.Trim();
- var target = Field("Target");
- var source = Field("Source");
- var requirement = Field("Require");
- if (string.IsNullOrWhiteSpace(target) || string.IsNullOrWhiteSpace(source) || string.IsNullOrWhiteSpace(requirement))
- {
- diagnostics.Add($"{SelectionMalformed}:{name}");
- continue;
- }
-
- selections.Add(new(name, target, source, requirement, new(offset + header.Index, close - header.Index + 1)));
+ var syntax = FirmamentSyntaxParser.Parse(body);
+ foreach (var declaration in FirmamentSyntaxEvidence.Declarations(syntax.Document).Where(d => d.Type.Name.Text == "Selection"))
+ {
+ var name = declaration.Name?.Text ?? "";
+ if (!names.Add(name)) { diagnostics.Add($"{SelectionDuplicateName}:{name}"); continue; }
+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);
+ var target = fields.Word("Target");
+ var sources = fields.TakeAll("Source");
+ var requirement = fields.Word("Require");
+ fields.Complete();
+ if (name.Length == 0 || sources.Count == 0 || requirement is null)
+ { diagnostics.Add($"{SelectionMalformed}:{name}"); continue; }
+ var sourceTexts = sources.Select(f => body.Substring(f.Value.Span.Start, f.Value.Span.Length)).ToArray();
+ selections.Add(new(name, target ?? "ProfileBoundary", sourceTexts[0], requirement,
+ new(offset + declaration.Span.Start, declaration.Span.Length)) { Sources = sourceTexts });
}
-
return selections;
}
@@ -1474,35 +1403,32 @@ public static class FirmamentV2Parser
return "ScalarOrUnsupported";
}
- private static void ValidateCanonicalSelectionSources(
- string body,
- IReadOnlyList<FirmamentV2SelectionDecl> selections,
- IEnumerable<string> profileNames,
- List<string> diagnostics)
+ private static void ValidateCanonicalSelectionSources(string body, IReadOnlyList<FirmamentV2SelectionDecl> selections,
+ IEnumerable<string> profileNames, List<string> diagnostics)
{
var profiles = profileNames.ToHashSet(StringComparer.Ordinal);
- var slots = Regex.Matches(body, @"\bSlot\s*<[^>]+>\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant)
- .Select(match => match.Groups["name"].Value)
- .ToHashSet(StringComparer.Ordinal);
- var holes = Regex.Matches(body, @"\bHole\s*<[^>]+>\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant)
- .Select(match => match.Groups["name"].Value)
- .ToHashSet(StringComparer.Ordinal);
- var allowedTargets = new HashSet<string>(StringComparer.Ordinal)
- {
- "TopBoundary", "BottomBoundary", "SideBoundary", "HoleEntry", "HoleExit", "HoleWall", "ShaftToDrillPoint", "DrillPoint", "Tip",
- "SlotEntry", "SlotExit", "SlotWall", "SlotStraightWall", "SlotEndWall"
- };
-
+ var declarations = FirmamentSyntaxEvidence.Declarations(FirmamentSyntaxParser.Parse(body).Document).ToArray();
foreach (var selection in selections)
{
- if (!allowedTargets.Contains(selection.Target)) diagnostics.Add($"{SelectionResultKindInvalid}:{selection.Name}:{selection.Target}");
- var profile = Regex.Match(selection.Source, @"^(?<profile>[A-Za-z_][A-Za-z0-9_]*)\.Profile(?:Segments|Loop)\s*\(", RegexOptions.CultureInvariant);
- var slot = Regex.Match(selection.Source, @"^Slot\s*\(\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\)$", RegexOptions.CultureInvariant);
- var hole = Regex.Match(selection.Source, @"^Hole\s*\(\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\)$", RegexOptions.CultureInvariant);
- if (profile.Success && !profiles.Contains(profile.Groups["profile"].Value)) diagnostics.Add($"{SelectionUnknownSource}:{selection.Name}:{profile.Groups["profile"].Value}");
- else if (slot.Success && !slots.Contains(slot.Groups["name"].Value)) diagnostics.Add($"{SelectionUnknownSource}:{selection.Name}:{slot.Groups["name"].Value}");
- else if (hole.Success && !holes.Contains(hole.Groups["name"].Value)) diagnostics.Add($"{SelectionUnknownSource}:{selection.Name}:{hole.Groups["name"].Value}");
- else if (!profile.Success && !slot.Success && !hole.Success) diagnostics.Add($"{SelectionUnknownSource}:{selection.Name}");
+ // Result categories retain the existing semantic contract. Source syntax
+ // is bound structurally, including the admitted profile member-set form.
+ if (selection.Target is not ("ProfileBoundary" or "TopBoundary" or "BottomBoundary" or "SideBoundary" or "HoleEntry" or "HoleExit" or "HoleWall" or "ShaftToDrillPoint" or "DrillPoint" or "Tip" or "SlotEntry" or "SlotExit" or "SlotWall" or "SlotStraightWall" or "SlotEndWall"))
+ diagnostics.Add($"{SelectionResultKindInvalid}:{selection.Name}:{selection.Target}");
+ foreach (var text in selection.Sources ?? [selection.Source])
+ {
+ var expression = FirmamentSyntaxParser.ParseExpression(text).Expression;
+ string? owner = null; string? kind = null;
+ if (expression is CallSyntax { Target: ReferenceSyntax r, Arguments.Count: 1 } call && r.Name.Text is "Slot" or "Hole")
+ { kind = r.Name.Text; owner = FirmamentSyntaxValues.Reference(call.Arguments[0].Value); }
+ else
+ {
+ var target = expression switch { MemberSetSyntax set => set.Target, CallSyntax invocation => invocation.Target, _ => expression };
+ while (target is MemberSyntax member) { owner = FirmamentSyntaxValues.Reference(member.Target); target = member.Target; }
+ kind = "Profile";
+ }
+ var found = owner is not null && (kind == "Profile" ? profiles.Contains(owner) : declarations.Any(d => d.Type.Name.Text == kind && d.Name?.Text == owner));
+ if (!found) diagnostics.Add($"{SelectionUnknownSource}:{selection.Name}:{owner}");
+ }
}
}
@@ -1510,96 +1436,10 @@ public static class FirmamentV2Parser
/// production materializer boundary. It is intentionally not a second parser.</summary>
public static bool TryGetCanonicalAdvancedBody(string source, out string body)
{
- body = string.Empty;
- var model = CanonicalModelRegex.Match(source);
- if (!model.Success || !ContainsCanonicalAdvancedDeclaration(source)) return false;
- var open = source.IndexOf('{', model.Index); var close = FindMatchingBrace(source, open);
- if (open < 0 || close < 0 || !string.IsNullOrWhiteSpace(source[(close + 1)..])) return false;
- var candidate = source[(open + 1)..close];
- if (!Regex.IsMatch(candidate, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant)) return false;
- body = Regex.Replace(candidate, @"(?m)^\s*Units\s*:\s*mm\s*$", string.Empty, RegexOptions.CultureInvariant);
- return true;
- }
-
- private static FirmamentV2ParseResult ParseCanonicalDocument(string source, List<string> diagnostics, string? sourceDirectory)
- {
- var model = CanonicalModelRegex.Match(source);
- var rootOpen = model.Success ? source.IndexOf('{', model.Index) : -1;
- var rootClose = rootOpen >= 0 ? FindMatchingBrace(source, rootOpen) : -1;
- if (!model.Success || rootClose < 0 || !string.IsNullOrWhiteSpace(source[(rootClose + 1)..]))
- return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
-
- var body = source[(rootOpen + 1)..rootClose];
- var units = Regex.Match(body, @"\bUnits\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)\b", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
- if (!units.Success || units.Groups["value"].Value != "mm")
- return CanonicalFailure(diagnostics, CanonicalUnitsInvalid);
- if (Regex.IsMatch(body, @"\b(?!(?:InlineStep|Recognize|Replace)\b)(?:Inline[A-Za-z_][A-Za-z0-9_]*|Recogniz[A-Za-z_][A-Za-z0-9_]*|Recognis[A-Za-z_][A-Za-z0-9_]*|Replac[A-Za-z_][A-Za-z0-9_]*)\b", RegexOptions.CultureInvariant))
- return CanonicalFailure(diagnostics, CanonicalDeclarationUnrecognized);
-
- var solids = new List<FirmamentV2SolidBinding>();
- var byName = new Dictionary<string, FirmamentV2SolidBinding>(StringComparer.Ordinal);
- foreach (Match primitive in CanonicalPrimitiveHeaderRegex.Matches(body))
- {
- var open = body.IndexOf('{', primitive.Index);
- var close = FindMatchingBrace(body, open);
- if (close < 0) return CanonicalFailure(diagnostics, CanonicalPrimitiveMalformed);
- var name = primitive.Groups["name"].Value;
- if (!byName.TryAdd(name, null!)) return CanonicalFailure(diagnostics, DuplicateName);
- var primitiveBody = body[(open + 1)..close];
- var record = ParseCanonicalPrimitive(primitive.Groups["type"].Value, primitiveBody, diagnostics);
- if (record is null) return CanonicalFailure(diagnostics, CanonicalPrimitiveMalformed);
- var solid = new FirmamentV2SolidBinding(name, primitive.Groups["type"].Value, record,
- SourceSpan: new FirmamentV2SourceSpan(rootOpen + 1 + primitive.Index, close - primitive.Index + 1),
- AuthoredFields: ReadAuthoredFields(primitiveBody, rootOpen + 1 + open + 1));
- byName[name] = solid;
- solids.Add(solid);
- }
- foreach (Match inlineStep in CanonicalInlineStepHeaderRegex.Matches(body))
- {
- var open = body.IndexOf('{', inlineStep.Index);
- var close = FindMatchingBrace(body, open);
- if (close < 0) return CanonicalFailure(diagnostics, CanonicalPrimitiveMalformed);
- var name = inlineStep.Groups["name"].Value;
- if (!byName.TryAdd(name, null!)) return CanonicalFailure(diagnostics, DuplicateName);
- var binding = ParseInlineStep(name, body[(open + 1)..close], diagnostics, sourceDirectory);
- if (binding is null) return CanonicalFailure(diagnostics, InlineStepPathMissing);
- byName[name] = binding;
- solids.Add(binding);
- }
- if (solids.Count == 0) return CanonicalFailure(diagnostics, MissingSolid);
-
- var modifies = new List<FirmamentV2ModifyBlock>();
- foreach (Match modify in CanonicalModifyHeaderRegex.Matches(body))
- {
- var target = modify.Groups["target"].Value;
- if (!byName.TryGetValue(target, out var solid)) return CanonicalFailure(diagnostics, ModifyTargetUnresolved);
- var open = body.IndexOf('{', modify.Index);
- var close = FindMatchingBrace(body, open);
- if (close < 0) return CanonicalFailure(diagnostics, CanonicalModifyMalformed);
- var modifyBody = body[(open + 1)..close];
- diagnostics.AddRange(ValidateCanonicalModifyStatements(modifyBody));
- if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalModifyMalformed);
- if (solid.Box is null && !CanonicalPerforationHeaderRegex.IsMatch(modifyBody)) return CanonicalFailure(diagnostics, ModifyTargetNotSolid);
- var holes = ParseCanonicalHoles(modifyBody, solid, rootOpen + 1 + open + 1, diagnostics);
- var perforations = ParseCanonicalPerforations(modifyBody, rootOpen + 1 + open + 1, diagnostics);
- var finishes = ParseCanonicalEdgeFinishes(modifyBody, rootOpen + 1 + open + 1, diagnostics);
- if (diagnostics.Any(IsFatalDiagnosticCode) || diagnostics.Contains(CanonicalPoint2Invalid) || diagnostics.Contains(CanonicalModifyMalformed) || diagnostics.Contains(CanonicalFieldUnknown))
- return CanonicalFailure(diagnostics, CanonicalModifyMalformed);
- // Empty Modify blocks are valid; feature admission belongs to the selected
- // production route, not to a phase parser's minimum-count rule.
- modifies.Add(new FirmamentV2ModifyBlock(target, [], holes, finishes, perforations));
- }
-
- var recognizedRegions = ParseCanonicalRecognizedRegions(body, byName, diagnostics);
- var replacements = ParseCanonicalReplacements(body, byName, recognizedRegions, diagnostics);
- var (pmi, pmiBlock, boundPmi) = ParsePmi(source, byName, modifies, recognizedRegions, [], [], diagnostics);
- if (diagnostics.Any(IsFatalDiagnosticCode) || diagnostics.Contains(CanonicalDeclarationUnrecognized) || diagnostics.Contains(CanonicalFieldUnknown))
- return CanonicalFailure(diagnostics, CanonicalDeclarationUnrecognized);
-
- diagnostics.Add("firmament-v2-unified-canonical-parsed");
- diagnostics.Add("firmament-v2-parse-succeeded");
- diagnostics.Sort(StringComparer.Ordinal);
- return FirmamentV2ParseResult.Success(new FirmamentV2Document(model.Groups["name"].Value, "mm", solids, modifies, Pmi: pmi, RecognizedRegions: recognizedRegions, Replacements: replacements, PmiBlock: pmiBlock, BoundPmi: boundPmi), diagnostics.Distinct(StringComparer.Ordinal).ToArray());
+ var syntax = FirmamentSyntaxParser.Parse(source);
+ var model = syntax.Document.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d => d.Type.Name.Text == "Model" && !d.Modifiers.Any(m => m.Name.Text == "Template") && d.Body is not null);
+ body = model?.Body is { } block ? source[..model.Span.Start] + source.Substring(block.Span.Start + 1, block.Span.Length - 2) + source[(model.Span.Start + model.Span.Length)..] : string.Empty;
+ return model?.Body is not null;
}
// Source provenance is read from lexical field boundaries, independently of the legacy
@@ -1718,89 +1558,12 @@ public static class FirmamentV2Parser
}
}
- private static FirmamentV2PrimitiveRecord? ParseCanonicalPrimitive(string type, string body, List<string> diagnostics)
+ private static FirmamentV2ExactCoaxialPartRecord? ReadExactCoaxialTemplateRecipe(string body)
{
- // Product recipes have separately owned, family-dependent schemas.
- if (type is not ("StandardPart" or "ExactCoaxialPart") && FirmamentSemanticSchemas.Get(type) is { } schema)
- {
- var unknown = ReadAuthoredFields(body, 0)
- .Where(field => !schema.Fields.Any(known => known.Name == field.Name
- || FirmamentSourceSpelling.PreferredField(known.Name) == field.Name)).ToArray();
- foreach (var field in unknown) diagnostics.Add($"{CanonicalFieldUnknown}:{type}:{field.Name}");
- if (unknown.Length > 0) return null;
- }
- double Number(string field, bool allowZero = false)
- {
- var match = Regex.Match(body, $@"\b{field}\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
- return match.Success && double.TryParse(match.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) && double.IsFinite(value) && (allowZero ? value >= 0d : value > 0d) ? value : double.NaN;
- }
- IReadOnlyList<double>? Size()
- {
- var match = Regex.Match(body, @"\bSize\s*:\s*\[(?<values>[^\]]+)\]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
- if (!match.Success) return null;
- var values = match.Groups["values"].Value.Split(',', StringSplitOptions.TrimEntries);
- var parsed = values.Select(ParsePhase3Length).ToArray();
- return parsed.Length == 3 && parsed.All(v => double.IsFinite(v) && v > 0d) ? parsed : null;
- }
- FirmamentV2StandardPartRecord? StandardPart()
- {
- var matches = Regex.Matches(body, "\\b(?<name>[A-Za-z_]\\w*)\\s*:\\s*(?<value>\"[^\"]*\"|[A-Za-z_]\\w*|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?)", RegexOptions.CultureInvariant).Cast<Match>().ToArray();
- if (matches.Length == 0 || matches.Select(match => match.Groups["name"].Value).Distinct(StringComparer.Ordinal).Count() != matches.Length)
- return null;
- var fields = matches.ToDictionary(match => match.Groups["name"].Value, match => match.Groups["value"].Value, StringComparer.Ordinal);
- if (!fields.Remove("Family", out var family)) return null;
- family = family.Trim();
- if (family.Length >= 2 && family[0] == '"' && family[^1] == '"') family = family[1..^1];
- return string.IsNullOrWhiteSpace(family) ? null : new FirmamentV2StandardPartRecord(family, fields);
- }
- FirmamentV2ExactCoaxialPartRecord? ExactCoaxialPart()
- {
- var matches = Regex.Matches(body, "\\b(?<name>[A-Za-z_]\\w*)\\s*:\\s*(?<value>\"[^\"]*\"|[A-Za-z_]\\w*|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?)", RegexOptions.CultureInvariant).Cast<Match>().ToArray();
- var fields = matches.GroupBy(match => match.Groups["name"].Value, StringComparer.Ordinal).ToDictionary(group => group.Key, group => group.Last().Groups["value"].Value, StringComparer.Ordinal);
- var required = new[] { "StableId", "Sides", "AcrossFlats", "AxialHeight", "FlatDiameter", "ConeAngle", "BlendRadius", "ShaftDiameter", "AxialLength", "EndChamferLength", "EndDiameter", "SemanticAxialRegionLength", "Designation", "Grade" };
- return required.All(fields.ContainsKey) ? new(fields) : null;
- }
- return type switch
- {
- "Box" when Size() is { } size => new FirmamentV2BoxRecord(size, []),
- "Cylinder" when Number("Radius") is var radius && Number("Height") is var height && double.IsFinite(radius) && double.IsFinite(height) => new FirmamentV2CylinderRecord(radius, height),
- "Cone" when Number("BottomRadius") is var coneBottom && Number("TopRadius", allowZero: true) is var coneTop && Number("Height") is var coneHeight && double.IsFinite(coneBottom) && double.IsFinite(coneTop) && double.IsFinite(coneHeight) => new FirmamentV2ConeRecord(coneBottom, coneTop, coneHeight),
- "Sphere" when Number("Radius") is var sphereRadius && double.IsFinite(sphereRadius) => new FirmamentV2SphereRecord(sphereRadius),
- "Torus" when Number("MajorRadius") is var majorRadius && Number("MinorRadius") is var minorRadius && double.IsFinite(majorRadius) && double.IsFinite(minorRadius) && majorRadius > minorRadius => new FirmamentV2TorusRecord(majorRadius, minorRadius),
- "RoundedBox" when Size() is { } roundedSize && Number("CornerRadius") is var corner && double.IsFinite(corner) && corner < double.Min(roundedSize[0], roundedSize[1]) / 2d => new FirmamentV2RoundedBoxRecord(roundedSize, corner),
- "Frustum" when Number("BottomRadius") is var bottom && Number("TopRadius") is var top && Number("Height") is var frustumHeight && double.IsFinite(bottom) && double.IsFinite(top) && double.IsFinite(frustumHeight) && double.Abs(bottom - top) > 1e-12d => new FirmamentV2FrustumRecord(bottom, top, frustumHeight),
- "StandardPart" => StandardPart(),
- "ExactCoaxialPart" => ExactCoaxialPart(),
- _ => null
- };
- }
-
- private static IReadOnlyList<string> ValidateCanonicalModifyStatements(string body)
- {
- var tokens = FirmamentLanguageAnalysisService.Lex(body).Where(token => token.Shape != "comment").ToArray();
- var diagnostics = new List<string>();
- for (var index = 0; index < tokens.Length;)
- {
- if (tokens[index].Text == ";") { index++; continue; }
- var keyword = tokens[index].Text;
- var admitted = keyword is "Hole" or "EdgeFinish" or "Perforation"
- || keyword is "Radial" or "Linear" && index + 1 < tokens.Length && tokens[index + 1].Text == "Pattern"
- || keyword == "Mirrored" && index + 1 < tokens.Length && tokens[index + 1].Text == "Feature";
- if (!admitted) diagnostics.Add($"{CanonicalDeclarationUnknown}:Modify:{keyword}");
- // Existing feature parsers own headers and fields. Consume exactly one
- // balanced statement block here, so unowned neighbours cannot disappear.
- while (index < tokens.Length && tokens[index].Text != "{") index++;
- if (index == tokens.Length) { diagnostics.Add(CanonicalModifyMalformed); break; }
- var depth = 0;
- do
- {
- if (tokens[index].Text == "{") depth++;
- else if (tokens[index].Text == "}") depth--;
- index++;
- } while (index < tokens.Length && depth > 0);
- if (depth != 0) diagnostics.Add(CanonicalModifyMalformed);
- }
- return diagnostics;
+ var matches = Regex.Matches(body, "\\b(?<name>[A-Za-z_]\\w*)\\s*:\\s*(?<value>\"[^\"]*\"|[A-Za-z_]\\w*|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?)", RegexOptions.CultureInvariant).Cast<Match>().ToArray();
+ var fields = matches.GroupBy(match => match.Groups["name"].Value, StringComparer.Ordinal).ToDictionary(group => group.Key, group => group.Last().Groups["value"].Value, StringComparer.Ordinal);
+ var required = new[] { "StableId", "Sides", "AcrossFlats", "AxialHeight", "FlatDiameter", "ConeAngle", "BlendRadius", "ShaftDiameter", "AxialLength", "EndChamferLength", "EndDiameter", "SemanticAxialRegionLength", "Designation", "Grade" };
+ return required.All(fields.ContainsKey) ? new(fields) : null;
}
private static IReadOnlyList<FirmamentV2PerforationDecl> ParseCanonicalPerforations(string body, int bodyOffset, List<string> diagnostics)
@@ -1851,89 +1614,6 @@ public static class FirmamentV2Parser
return result;
}
- private static IReadOnlyList<FirmamentV2SemanticHoleDecl> ParseCanonicalHoles(string body, FirmamentV2SolidBinding solid, int bodyOffset, List<string> diagnostics)
- {
- var holes = new List<FirmamentV2SemanticHoleDecl>();
- var headers = CanonicalHoleHeaderRegex.Matches(body);
- if (Regex.Matches(body, @"\bHole\s*<", RegexOptions.CultureInvariant).Count != headers.Count)
- {
- diagnostics.Add(CanonicalModifyMalformed);
- return holes;
- }
- foreach (Match hole in headers)
- {
- var open = body.IndexOf('{', hole.Index); var close = FindMatchingBrace(body, open);
- if (close < 0) { diagnostics.Add(CanonicalModifyMalformed); continue; }
- var holeBody = body[(open + 1)..close];
- if (!Enum.TryParse<FirmamentV2SemanticHoleVariant>(hole.Groups["variant"].Value, ignoreCase: false, out var variant))
- {
- diagnostics.Add(HoleVariantUnknown);
- continue;
- }
-
- var variantFields = variant switch
- {
- FirmamentV2SemanticHoleVariant.Counterbore => new[] { "CounterboreDiameter", "CounterboreDepth" },
- FirmamentV2SemanticHoleVariant.Countersink => new[] { "CountersinkDiameter", "CountersinkAngle" },
- _ => []
- };
- var knownFields = FirmamentSemanticSchemas.Get("Hole")!.Fields.Select(field => field.Name).Concat(variantFields).ToArray();
- if (CanonicalBodyHasUnknownField(holeBody, knownFields))
- {
- diagnostics.Add(CanonicalFieldUnknown);
- continue;
- }
- var on = Regex.Match(holeBody, @"\bOn\s*:\s*(?<face>[+-][XYZ])\b", RegexOptions.CultureInvariant);
- var point = Regex.Match(holeBody, @"\bCenter\s*:\s*Point2\(\s*(?<u>[-+0-9.eE]+)mm\s*,\s*(?<v>[-+0-9.eE]+)mm\s*\)", RegexOptions.CultureInvariant);
- var diameter = Regex.Match(holeBody, @"\bDiameter\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);
- var end = Regex.Match(holeBody, @"\bEnd\s*:\s*(?<kind>ThroughAll|Blind)\b(?:\s+(?<depth>[-+0-9.eE]+)mm)?", RegexOptions.CultureInvariant);
- if (!on.Success || !diameter.Success || !end.Success) { diagnostics.Add(CanonicalModifyMalformed); continue; }
- if (!point.Success || !double.TryParse(point.Groups["u"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var u) || !double.TryParse(point.Groups["v"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) || !double.IsFinite(u) || !double.IsFinite(v)) { diagnostics.Add(CanonicalPoint2Invalid); continue; }
- if (!double.TryParse(diameter.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var shaft) || !double.IsFinite(shaft) || shaft <= 0d) { diagnostics.Add(HoleDiameterInvalid); continue; }
- FirmamentV2SemanticHoleEnd endValue;
- if (end.Groups["kind"].Value == "ThroughAll") endValue = new(FirmamentV2SemanticHoleEndKind.ThroughAll);
- else if (double.TryParse(end.Groups["depth"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var depth) && depth > 0d && double.IsFinite(depth)) endValue = new(FirmamentV2SemanticHoleEndKind.Depth, depth);
- else { diagnostics.Add(HoleBlindDepthInvalid); continue; }
- double? counterboreDiameter = null, counterboreDepth = null, countersinkDiameter = null, countersinkAngle = null;
- if (variant == FirmamentV2SemanticHoleVariant.Counterbore)
- {
- var cbDiameter = Regex.Match(holeBody, @"\bCounterboreDiameter\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);
- var cbDepth = Regex.Match(holeBody, @"\bCounterboreDepth\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);
- if (!cbDiameter.Success || !cbDepth.Success ||
- !double.TryParse(cbDiameter.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var diameterValue) ||
- !double.TryParse(cbDepth.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var depthValue) ||
- !double.IsFinite(diameterValue) || !double.IsFinite(depthValue) || diameterValue <= shaft || depthValue <= 0d)
- {
- diagnostics.Add(HoleCounterboreInvalid);
- continue;
- }
- counterboreDiameter = diameterValue;
- counterboreDepth = depthValue;
- }
- if (variant == FirmamentV2SemanticHoleVariant.Countersink)
- {
- var csDiameter = Regex.Match(holeBody, @"\bCountersinkDiameter\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);
- var csAngle = Regex.Match(holeBody, @"\bCountersinkAngle\s*:\s*(?<value>[-+0-9.eE]+)deg\b", RegexOptions.CultureInvariant);
- if (!csDiameter.Success || !csAngle.Success ||
- !double.TryParse(csDiameter.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var diameterValue) ||
- !double.TryParse(csAngle.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var angleValue) ||
- !double.IsFinite(diameterValue) || !double.IsFinite(angleValue) || diameterValue <= shaft || angleValue <= 0d || angleValue >= 180d)
- {
- diagnostics.Add(HoleCountersinkInvalid);
- continue;
- }
- countersinkDiameter = diameterValue;
- countersinkAngle = angleValue;
- }
- var face = FirmamentV2FaceTarget.Direct(on.Groups["face"].Value);
- holes.Add(new(hole.Groups["name"].Value, variant, face, new FirmamentV2FaceLocalPoint2D(u, v, FirmamentV2FaceLocalPoint2D.ConventionFor(face.Axis)), shaft, endValue,
- counterboreDiameter, counterboreDepth, countersinkDiameter, countersinkAngle,
- SourceSpan: new FirmamentV2SourceSpan(bodyOffset + hole.Index, close - hole.Index + 1),
- AuthoredFields: ReadAuthoredFields(holeBody, bodyOffset + open + 1)));
- }
- return holes;
- }
-
private static bool CanonicalBodyHasUnknownField(string body, IReadOnlyCollection<string> knownFields) =>
ReadAuthoredFields(body, 0).Any(field => !knownFields.Contains(field.Name, StringComparer.Ordinal));
@@ -2064,24 +1744,6 @@ public static class FirmamentV2Parser
return values.Length == 3 && values.All(value => double.IsFinite(value) && value > 0d) ? values : null;
}
- private static IReadOnlyList<FirmamentV2EdgeFinishDecl> ParseCanonicalEdgeFinishes(string body, int bodyOffset, List<string> diagnostics)
- {
- var finishes = new List<FirmamentV2EdgeFinishDecl>();
- foreach (Match edge in CanonicalEdgeHeaderRegex.Matches(body))
- {
- var open = body.IndexOf('{', edge.Index); var close = FindMatchingBrace(body, open);
- if (close < 0) { diagnostics.Add(CanonicalModifyMalformed); continue; }
- var edgeBody = body[(open + 1)..close];
- var face = Regex.Match(edgeBody, @"\bFace\s*:\s*(?<value>[+-][XYZ])\b", RegexOptions.CultureInvariant);
- var target = Regex.Match(edgeBody, @"\bTarget\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)\b", RegexOptions.CultureInvariant);
- var kind = Regex.Match(edgeBody, @"\bKind\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)\b", RegexOptions.CultureInvariant);
- var distance = Regex.Match(edgeBody, @"\b(?:Distance|Radius)\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);
- if (!face.Success || !target.Success || !kind.Success || !distance.Success || !double.TryParse(distance.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) || !double.IsFinite(value) || value <= 0d) { diagnostics.Add(CanonicalModifyMalformed); continue; }
- finishes.Add(new FirmamentV2EdgeFinishDecl(edge.Groups["name"].Value, face.Groups["value"].Value, target.Groups["value"].Value, kind.Groups["value"].Value, value, new FirmamentV2SourceSpan(bodyOffset + edge.Index, close - edge.Index + 1)));
- }
- return finishes;
- }
-
private static FirmamentV2ParseResult CanonicalFailure(List<string> diagnostics, string diagnostic)
{
diagnostics.Add(diagnostic);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
index 26bb9e37..f6de891e 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
@@ -55,7 +55,9 @@ public static class FirmamentV2ValidationReportBuilder
var diagnostics = parse.Diagnostics
.Distinct(StringComparer.Ordinal)
.Where(code => !IsParserTraceDiagnostic(code))
+ .Where(code => !parse.SyntaxDiagnostics.Any(d => d.Code == code))
.Select(ToParserDiagnostic)
+ .Concat(parse.SyntaxDiagnostics)
.Concat(runtimeValidation.Diagnostics.Select(ToRuntimeDiagnostic))
.Distinct()
.ToArray();
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
index e1e08837..75f3635d 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
@@ -1,4 +1,5 @@
using System.Globalization;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Firmament.Materializer;
@@ -13,12 +14,6 @@ public static class ProfileAuthoringParser
{
public const string SegmentEndpointMustReferenceNamedPoint = "ProfileSegmentEndpointMustReferenceNamedPoint";
private const double Tolerance = 1e-9;
- private static readonly Regex Point = new(@"\bPoint2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*Position\s*:\s*(?:\[(?<xy>[^\[\]\r\n]+)\]|Point2\s*\((?<xy>[^()\r\n]+)\))", RegexOptions.Singleline | RegexOptions.CultureInvariant);
- private static readonly Regex Line = new(@"\bLine2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*From\s*:\s*(?<a>[\w.]+)\s*;?\s*To\s*:\s*(?<b>[\w.]+)", RegexOptions.Singleline | RegexOptions.CultureInvariant);
- private static readonly Regex CubicBezier = new(@"\bCubicBezier2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*From\s*:\s*(?<a>[\w.]+)\s*;?\s*Control1\s*:\s*(?<c1>[\w.]+)\s*;?\s*Control2\s*:\s*(?<c2>[\w.]+)\s*;?\s*To\s*:\s*(?<b>[\w.]+)", RegexOptions.Singleline | RegexOptions.CultureInvariant);
- private static readonly Regex Circle = new(@"(?:\bConcept\s+)?\bCircle2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*Center\s*:\s*(?<c>[\w.]+)\s*;?\s*Radius\s*:\s*(?<r>[-+.\deE]+)mm", RegexOptions.Singleline | RegexOptions.CultureInvariant);
- private static readonly Regex EllipseGuide = new(@"\bEllipse2Guide\s+(?<n>[A-Za-z_]\w*)\s*\{\s*Center\s*:\s*(?<c>[\w.]+)\s*;?\s*SemiAxes\s*:\s*\[\s*(?<a>[-+.\deE]+)mm\s*,\s*(?<b>[-+.\deE]+)mm\s*\]\s*;?\s*Rotation\s*:\s*(?<r>[-+.\deE]+)deg", RegexOptions.Singleline | RegexOptions.CultureInvariant);
- private static readonly Regex Rect = new(@"\bRect2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*Center\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*(?:\]|\))\s*;?\s*Size\s*:\s*\[(?<w>[-+.\deE]+)mm\s*,\s*(?<h>[-+.\deE]+)mm\]", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex ConstructionPlaneDeclaration = new(@"\bConstruction\s+Plane\s+(?<name>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*\}", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex Segment = new(@"\bSegment\s+(?<n>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*From\s*:\s*(?<from>[\w.]+)\s*;?\s*To\s*:\s*(?<to>[\w.]+)(?:\s*;?\s*Sweep\s*:\s*(?<sweep>Clockwise|CounterClockwise))?", RegexOptions.Singleline | 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);
@@ -246,67 +241,79 @@ public static class ProfileAuthoringParser
private static void AddOrdinaryGuides(string source, Dictionary<string, (double X, double Y)> points, Dictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics, bool applySpans = true)
{
- foreach (Match match in Point.Matches(source))
+ var declarations = SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Where(d => d.Name is not null && d.Body is not null).ToArray();
+ foreach (var d in declarations.Where(d => d.Type.Name.Text == "Point2"))
{
- // Profile Templates substitute dimensions before this binder. Reuse the
- // bounded, unit-checked scalar evaluator for authored control arithmetic.
- var xy = match.Groups["xy"].Value.Split(',');
- if (xy.Length == 2 && FirmamentV2FeatureExpansion.TryEvaluateScalar(xy[0], out var x, out var xu) && xu == "mm"
- && FirmamentV2FeatureExpansion.TryEvaluateScalar(xy[1], out var y, out var yu) && yu == "mm")
- points[match.Groups["n"].Value] = (x, y);
- else diagnostics.Add($"profile-layout-point-invalid:{match.Groups["n"].Value}:expected-two-finite-lengths");
+ var fields = new FirmamentSyntaxFields(d, diagnostics);
+ if (fields.Vector("Position", "mm", out var xy) && xy.Length == 2) points[d.Name!.Text] = (xy[0], xy[1]);
+ else diagnostics.Add($"profile-layout-point-invalid:{d.Name!.Text}:expected-two-finite-lengths");
+ fields.Complete();
}
- foreach (Match match in Rect.Matches(source))
+ foreach (var d in declarations.Where(d => d.Type.Name.Text == "Rect2"))
{
- var name = match.Groups["n"].Value;
- if (!TryNumber(match.Groups["w"].Value, out var width) || !TryNumber(match.Groups["h"].Value, out var height) || !TryNumber(match.Groups["x"].Value, out var x) || !TryNumber(match.Groups["y"].Value, out var y) || width <= 0 || height <= 0)
+ var fields = new FirmamentSyntaxFields(d, diagnostics); var name = d.Name!.Text;
+ fields.Word("Role");
+ if (!fields.Vector("Center", "mm", out var center) || center.Length != 2 || !fields.Vector("Size", "mm", out var size) || size.Length != 2 || size.Any(n => n <= 0))
{ diagnostics.Add($"rect2-invalid-size:{name}"); continue; }
+ fields.Complete();
+ var x = center[0]; var y = center[1]; var width = size[0]; var height = size[1];
points[$"{name}.BottomLeft"] = (x - width / 2, y - height / 2);
points[$"{name}.BottomRight"] = (x + width / 2, y - height / 2);
points[$"{name}.TopRight"] = (x + width / 2, y + height / 2);
points[$"{name}.TopLeft"] = (x - width / 2, y + height / 2);
+ var bl = points[$"{name}.BottomLeft"]; var br = points[$"{name}.BottomRight"]; var tr = points[$"{name}.TopRight"]; var tl = points[$"{name}.TopLeft"];
+ guides[$"{name}.Bottom"] = new LineArcLineSegment2D(bl, br); guides[$"{name}.Right"] = new LineArcLineSegment2D(br, tr);
+ guides[$"{name}.Top"] = new LineArcLineSegment2D(tr, tl); guides[$"{name}.Left"] = new LineArcLineSegment2D(tl, bl);
}
- foreach (Match match in Line.Matches(source))
+ foreach (var d in declarations.Where(d => d.Type.Name.Text is "Line2" or "CubicBezier2"))
{
- var name = match.Groups["n"].Value;
- if (!points.TryGetValue(match.Groups["a"].Value, out var from) || !points.TryGetValue(match.Groups["b"].Value, out var to)) diagnostics.Add($"profile-layout-unresolved-line:{name}");
- else guides[name] = new LineArcLineSegment2D(from, to);
- }
- foreach (Match match in CubicBezier.Matches(source))
- {
- var name = match.Groups["n"].Value;
- if (!points.TryGetValue(match.Groups["a"].Value, out var from) ||
- !points.TryGetValue(match.Groups["c1"].Value, out var control1) ||
- !points.TryGetValue(match.Groups["c2"].Value, out var control2) ||
- !points.TryGetValue(match.Groups["b"].Value, out var to))
- diagnostics.Add($"profile-layout-unresolved-cubic-bezier:{name}");
- else guides[name] = new LineArcCubicBezier2D(from, control1, control2, to);
+ var fields = new FirmamentSyntaxFields(d, diagnostics); var name = d.Name!.Text;
+ var a = fields.Word("From"); var b = fields.Word("To");
+ var c1 = d.Type.Name.Text == "CubicBezier2" ? fields.Word("Control1") : null;
+ var c2 = d.Type.Name.Text == "CubicBezier2" ? fields.Word("Control2") : null;
+ fields.Complete();
+ if (a is null || b is null || !points.TryGetValue(a, out var from) || !points.TryGetValue(b, out var to))
+ { diagnostics.Add($"profile-layout-unresolved-line:{name}"); continue; }
+ if (d.Type.Name.Text == "Line2") guides[name] = new LineArcLineSegment2D(from, to);
+ else if (c1 is not null && c2 is not null && points.TryGetValue(c1, out var control1) && points.TryGetValue(c2, out var control2))
+ guides[name] = new LineArcCubicBezier2D(from, control1, control2, to);
+ else diagnostics.Add($"profile-layout-unresolved-cubic-bezier:{name}");
}
- foreach (Match match in Rect.Matches(source))
+ foreach (var d in declarations.Where(d => d.Type.Name.Text is "Circle2" or "Ellipse2Guide"))
{
- var name = match.Groups["n"].Value;
- if (points.TryGetValue($"{name}.BottomLeft", out var bl) && points.TryGetValue($"{name}.BottomRight", out var br) && points.TryGetValue($"{name}.TopRight", out var tr) && points.TryGetValue($"{name}.TopLeft", out var tl))
+ var fields = new FirmamentSyntaxFields(d, diagnostics); var name = d.Name!.Text;
+ var centerName = fields.Word("Center");
+ if (centerName is null || !points.TryGetValue(centerName, out var center)) { diagnostics.Add($"profile-layout-unresolved-circle:{name}"); continue; }
+ if (d.Type.Name.Text == "Circle2")
{
- guides[$"{name}.Bottom"] = new LineArcLineSegment2D(bl, br); guides[$"{name}.Right"] = new LineArcLineSegment2D(br, tr);
- guides[$"{name}.Top"] = new LineArcLineSegment2D(tr, tl); guides[$"{name}.Left"] = new LineArcLineSegment2D(tl, bl);
+ var radius = fields.Number("Radius", "mm");
+ if (radius > 0) guides[name] = new LineArcFullCircle2D(center, radius);
+ else diagnostics.Add($"profile-layout-unresolved-circle:{name}");
}
- }
- foreach (Match match in Circle.Matches(source))
- {
- if (!points.TryGetValue(match.Groups["c"].Value, out var center) || !TryNumber(match.Groups["r"].Value, out var radius) || radius <= 0) { diagnostics.Add($"profile-layout-unresolved-circle:{match.Groups["n"].Value}"); continue; }
- // A circle remains a guide; segments choose its directed arc below.
- guides[match.Groups["n"].Value] = new LineArcFullCircle2D(center, radius);
- }
- foreach (Match match in EllipseGuide.Matches(source))
- {
- if (!points.TryGetValue(match.Groups["c"].Value, out var center) || !TryNumber(match.Groups["a"].Value, out var major) || !TryNumber(match.Groups["b"].Value, out var minor) || !TryNumber(match.Groups["r"].Value, out var rotation) || major <= 0 || minor <= 0 || minor > major)
- { diagnostics.Add($"profile-layout-unresolved-ellipse:{match.Groups["n"].Value}"); continue; }
- guides[match.Groups["n"].Value] = new LineArcFullEllipse2D(center, major, minor, rotation * Math.PI / 180d);
+ else
+ {
+ var rotation = fields.Number("Rotation", "deg");
+ if (fields.Vector("SemiAxes", "mm", out var axes) && axes.Length == 2 && axes[0] >= axes[1] && axes[1] > 0 && double.IsFinite(rotation))
+ guides[name] = new LineArcFullEllipse2D(center, axes[0], axes[1], rotation * Math.PI / 180d);
+ else diagnostics.Add($"profile-layout-unresolved-ellipse:{name}");
+ }
+ fields.Complete();
}
foreach (var guide in ClosedBoundary2Authoring.SmoothGuides(source, diagnostics)) guides[guide.Key] = guide.Value;
if (applySpans) ApplyGeometricSpans(source, points, guides, diagnostics, addGuides: true);
}
+ private static IEnumerable<DeclarationSyntax> SourceDeclarations(IEnumerable<StatementSyntax> statements)
+ {
+ foreach (var d in statements.OfType<DeclarationSyntax>())
+ {
+ if (d.Type.Name.Text == "Template" || d.Modifiers.Any(m => m.Name.Text == "Template")) continue;
+ yield return d;
+ if (d.Body is not null)
+ foreach (var child in SourceDeclarations(d.Body.Statements)) yield return child;
+ }
+ }
+
private static IReadOnlyList<GeometricSpanView> ApplyGeometricSpans(
string source,
IReadOnlyDictionary<string, (double X, double Y)> points,
@@ -470,14 +477,15 @@ public static class ProfileAuthoringParser
var 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 (Match rectangle in Rect.Matches(source))
+ foreach (var rectangle in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Where(d => d.Type.Name.Text == "Rect2" && d.Name is not null))
{
- var name = rectangle.Groups["n"].Value;
+ 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);
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;
- if (!TryNumber(rectangle.Groups["w"].Value, out var width) || !TryNumber(rectangle.Groups["h"].Value, out var height) ||
- !TryNumber(rectangle.Groups["x"].Value, out var cx) || !TryNumber(rectangle.Groups["y"].Value, out var cy)) continue;
+ var fields = new FirmamentSyntaxFields(rectangle, diagnostics);
+ if (!fields.Vector("Size", "mm", out var size) || size.Length != 2 || !fields.Vector("Center", "mm", out var center) || center.Length != 2) continue;
+ var width = size[0]; var height = size[1]; var cx = center[0]; var cy = center[1];
if (result.ContainsKey(name)) { diagnostics.Add($"profile-edge-owner-name-collision:{name}"); continue; }
var bl = (X: cx - width / 2, Y: cy - height / 2); var br = (X: cx + width / 2, Y: cy - height / 2);
var tr = (X: cx + width / 2, Y: cy + height / 2); var tl = (X: cx - width / 2, Y: cy + height / 2);
@@ -1110,18 +1118,27 @@ public static class ProfileAuthoringParser
private static (double Start, double End, double Height) ResolveExtrude(string source, string profileName, List<string> diagnostics)
{
- var block = FindBlocks(source, @"\bExtrude\s+\w+\s*\{")
- .FirstOrDefault(x => Property(x.Body, "Profile") == profileName);
- if (block is null || !TryMeasure(Property(block.Body, "From") ?? "", "mm", out var start)
- || !TryMeasure(Property(block.Body, "To") ?? "", "mm", out var end))
- { diagnostics.Add("profile-extrude-missing-or-mismatched"); return default; }
- return (start, end, Math.Abs(end - start));
+ foreach (var d in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Where(d => d.Type.Name.Text == "Extrude"))
+ {
+ var fields = new FirmamentSyntaxFields(d, diagnostics);
+ if (fields.Word("Profile") != profileName) continue;
+ var start = fields.Number("From", "mm"); var end = fields.Number("To", "mm");
+ fields.Complete();
+ if (!double.IsFinite(start) || !double.IsFinite(end)) break;
+ return (start, end, Math.Abs(end - start));
+ }
+ diagnostics.Add("profile-extrude-missing-or-mismatched"); return default;
}
private static IEnumerable<ProfileBlock> FindProfiles(string source)
{
- foreach (var block in FindBlocks(source, @"\bProfile\s+(?<name>[A-Za-z_]\w*)(?:\s+Using\s+(?<frame>[A-Za-z_]\w*))?\s*\{")) yield return new(block.Match.Groups["name"].Value, block.Match.Groups["frame"].Success ? block.Match.Groups["frame"].Value : null, null, block.Body, $"source:{block.Match.Index}");
- foreach (Match match in Regex.Matches(source, @"\bProfile\s+(?<name>[A-Za-z_]\w*)\s+From\s+(?<path>[A-Za-z_]\w*)\b", RegexOptions.CultureInvariant)) yield return new(match.Groups["name"].Value, null, match.Groups["path"].Value, null, $"source:{match.Index}");
+ foreach (var d in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Where(d => d.Type.Name.Text == "Profile" && d.Name is not null))
+ {
+ var frame = FirmamentSyntaxValues.Reference(d.Clauses.FirstOrDefault(c => c.Kind == ClauseKind.Using)?.Value);
+ var path = FirmamentSyntaxValues.Reference(d.Clauses.FirstOrDefault(c => c.Kind == ClauseKind.From)?.Value);
+ var body = d.Body is null ? null : source.Substring(d.Body.Span.Start + 1, d.Body.Span.Length - 2);
+ yield return new(d.Name!.Text, frame, path, body, $"source:{d.Span.Start}");
+ }
}
private static IEnumerable<Block> FindBlocks(string source, string headerPattern)
@@ -1162,8 +1179,8 @@ public static class ProfileAuthoringParser
}
internal static bool TryMeasure(string text, string unit, out double value)
{
- var parser = new BoundedMeasureExpression(text, unit);
- return parser.TryEvaluate(out value);
+ var parsed = FirmamentSyntaxParser.ParseExpression(text);
+ return FirmamentSyntaxValues.TryMeasure(parsed.Diagnostics.Count == 0 ? parsed.Expression : null, unit, out value);
}
private static bool TryNumber(string text, out double value) => double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);
private static (double X, double Y) Advance((double X, double Y) point, double heading, double length) { var radians = DegreesToRadians(heading); return (point.X + length * Math.Cos(radians), point.Y + length * Math.Sin(radians)); }
@@ -1183,53 +1200,4 @@ public static class ProfileAuthoringParser
private enum PipelineStageKind { Trace, Close, TraceLoop, Invalid }
private sealed record PipelineStage(PipelineStageKind Kind, string? Reference, string? Alias, bool Reverse, int Offset, string? From = null, string? To = null);
- /// <summary>Small deterministic dimensional expression evaluator used after Template specialization.</summary>
- /// <remarks>Admits only numeric literals, one requested unit, parentheses, and + - * /.</remarks>
- private sealed class BoundedMeasureExpression(string source, string unit)
- {
- private int index;
- public bool TryEvaluate(out double value)
- {
- value = default; index = 0;
- if (!Expression(out var result) || result.Dimension != 1) return false;
- Space();
- if (index != source.Length || !double.IsFinite(result.Value)) return false;
- value = result.Value; return true;
- }
- private bool Expression(out Quantity result)
- {
- if (!Term(out result)) return false;
- while (true)
- {
- Space(); if (index >= source.Length || source[index] is not ('+' or '-')) return true;
- var operation = source[index++]; if (!Term(out var right) || result.Dimension != right.Dimension) return false;
- result = new(operation == '+' ? result.Value + right.Value : result.Value - right.Value, result.Dimension);
- }
- }
- private bool Term(out Quantity result)
- {
- if (!Factor(out result)) return false;
- while (true)
- {
- Space(); if (index >= source.Length || source[index] is not ('*' or '/')) return true;
- var operation = source[index++]; if (!Factor(out var right)) return false;
- var dimension = operation == '*' ? result.Dimension + right.Dimension : result.Dimension - right.Dimension;
- if (dimension is < 0 or > 1 || operation == '/' && Math.Abs(right.Value) <= double.Epsilon) return false;
- result = new(operation == '*' ? result.Value * right.Value : result.Value / right.Value, dimension);
- }
- }
- private bool Factor(out Quantity result)
- {
- Space(); result = default; if (index >= source.Length) return false;
- if (source[index] == '(') { index++; if (!Expression(out result)) return false; Space(); return index < source.Length && source[index++] == ')'; }
- var sign = 1d; if (source[index] is '+' or '-') sign = source[index++] == '-' ? -1d : 1d;
- Space(); var start = index;
- while (index < source.Length && (char.IsDigit(source[index]) || source[index] is '.' or 'e' or 'E' || source[index] is '+' or '-' && index > start && source[index - 1] is 'e' or 'E')) index++;
- if (start == index || !TryNumber(source[start..index], out var number)) return false;
- var dimension = 0; if (source.AsSpan(index).StartsWith(unit, StringComparison.Ordinal)) { index += unit.Length; dimension = 1; }
- result = new(sign * number, dimension); return true;
- }
- private void Space() { while (index < source.Length && char.IsWhiteSpace(source[index])) index++; }
- private readonly record struct Quantity(double Value, int Dimension);
- }
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs
new file mode 100644
index 00000000..f77c2e10
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs
@@ -0,0 +1,85 @@
+using System.Text.Json.Serialization;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+public enum SyntaxTokenKind { Identifier, Number, String, Punctuation, Whitespace, Comment, End }
+public sealed record SyntaxToken(SyntaxTokenKind Kind, string Text, FirmamentV2SourceSpan Span);
+public enum DirectiveKind { Schema, Include, Use }
+public enum ClauseKind { On, Using, Over, From, Key }
+public enum LiteralKind { Number, String, Boolean }
+public enum SequenceKind { List, Tuple }
+public enum UnaryOperator { Positive, Negative, Not, Reverse }
+public enum BinaryOperator { Pipeline, Direction, Or, And, Equal, NotEqual, Less, LessEqual, Greater, GreaterEqual, Add, Subtract, Multiply, Divide, Remainder, Power }
+
+// This is source syntax, not engineering AIR. Open type names and fields are retained
+// for their semantic owners to admit; structural success is never called validity.
+[JsonPolymorphic(TypeDiscriminatorPropertyName = "node")]
+[JsonDerivedType(typeof(DeclarationSyntax), "declaration")]
+[JsonDerivedType(typeof(FieldSyntax), "field")]
+[JsonDerivedType(typeof(DirectiveSyntax), "directive")]
+[JsonDerivedType(typeof(ExpressionStatementSyntax), "expressionStatement")]
+[JsonDerivedType(typeof(ReturnSyntax), "return")]
+[JsonDerivedType(typeof(MappingSyntax), "mapping")]
+public abstract record StatementSyntax(FirmamentV2SourceSpan Span);
+public sealed record IdentifierSyntax(string Text, FirmamentV2SourceSpan Span);
+public sealed record ArgumentSyntax(IdentifierSyntax? Name, ExpressionSyntax Value, ExpressionSyntax? Default, FirmamentV2SourceSpan Span);
+public sealed record TypeSyntax(IdentifierSyntax Name, IReadOnlyList<ArgumentSyntax> Arguments, FirmamentV2SourceSpan Span);
+public sealed record ClauseSyntax(ClauseKind Kind, ExpressionSyntax Value, FirmamentV2SourceSpan Span);
+public sealed record BlockSyntax(IReadOnlyList<StatementSyntax> Statements, FirmamentV2SourceSpan Span);
+public sealed record DeclarationSyntax(TypeSyntax Type, IdentifierSyntax? Name, IReadOnlyList<TypeSyntax> Modifiers,
+ IReadOnlyList<ArgumentSyntax> Parameters, ExpressionSyntax? Annotation, ExpressionSyntax? ResultType,
+ IReadOnlyList<ClauseSyntax> Clauses, ExpressionSyntax? Initializer, BlockSyntax? Body, bool Occurrence,
+ FirmamentV2SourceSpan Span) : StatementSyntax(Span);
+public sealed record FieldSyntax(IdentifierSyntax Name, ExpressionSyntax Value, FirmamentV2SourceSpan Span) : StatementSyntax(Span);
+public sealed record DirectiveSyntax(DirectiveKind Kind, ExpressionSyntax Value, FirmamentV2SourceSpan Span) : StatementSyntax(Span);
+public sealed record ExpressionStatementSyntax(ExpressionSyntax Value, FirmamentV2SourceSpan Span) : StatementSyntax(Span);
+public sealed record ReturnSyntax(ExpressionSyntax Value, FirmamentV2SourceSpan Span) : StatementSyntax(Span);
+public sealed record MappingSyntax(IdentifierSyntax Key, StatementSyntax Value, FirmamentV2SourceSpan Span) : StatementSyntax(Span);
+
+[JsonPolymorphic(TypeDiscriminatorPropertyName = "node")]
+[JsonDerivedType(typeof(ReferenceSyntax), "reference")]
+[JsonDerivedType(typeof(LiteralSyntax), "literal")]
+[JsonDerivedType(typeof(UnarySyntax), "unary")]
+[JsonDerivedType(typeof(BinarySyntax), "binary")]
+[JsonDerivedType(typeof(SequenceSyntax), "sequence")]
+[JsonDerivedType(typeof(MemberSyntax), "member")]
+[JsonDerivedType(typeof(IndexSyntax), "index")]
+[JsonDerivedType(typeof(CallSyntax), "call")]
+[JsonDerivedType(typeof(SpecializationSyntax), "specialization")]
+[JsonDerivedType(typeof(ObjectSyntax), "object")]
+[JsonDerivedType(typeof(WithSyntax), "with")]
+[JsonDerivedType(typeof(QuantitySyntax), "quantity")]
+[JsonDerivedType(typeof(FrameSyntax), "frame")]
+[JsonDerivedType(typeof(AliasSyntax), "alias")]
+[JsonDerivedType(typeof(TraceSyntax), "trace")]
+[JsonDerivedType(typeof(MemberSetSyntax), "memberSet")]
+[JsonDerivedType(typeof(TypedValueSyntax), "typedValue")]
+[JsonDerivedType(typeof(MatchSyntax), "match")]
+public abstract record ExpressionSyntax(FirmamentV2SourceSpan Span);
+public sealed record ReferenceSyntax(IdentifierSyntax Name, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record LiteralSyntax(LiteralKind Kind, string Raw, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record QuantitySyntax(ExpressionSyntax Value, IdentifierSyntax Unit, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record UnarySyntax(UnaryOperator Operator, ExpressionSyntax Operand, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record BinarySyntax(ExpressionSyntax Left, BinaryOperator Operator, ExpressionSyntax Right, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record SequenceSyntax(SequenceKind Kind, IReadOnlyList<ArgumentSyntax> Items, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record MemberSyntax(ExpressionSyntax Target, IdentifierSyntax Member, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record IndexSyntax(ExpressionSyntax Target, ExpressionSyntax? Index, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record CallSyntax(ExpressionSyntax Target, IReadOnlyList<ArgumentSyntax> Arguments, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record SpecializationSyntax(ExpressionSyntax Target, IReadOnlyList<ArgumentSyntax> Arguments, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record ObjectSyntax(ExpressionSyntax? Type, BlockSyntax Body, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record WithSyntax(ExpressionSyntax Target, BlockSyntax Body, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record FrameSyntax(ExpressionSyntax Origin, IReadOnlyList<ArgumentSyntax> Axes, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record AliasSyntax(ExpressionSyntax Value, IdentifierSyntax Name, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record TraceSyntax(ExpressionSyntax Source, ExpressionSyntax? From, ExpressionSyntax? To, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record MemberSetSyntax(ExpressionSyntax Target, IReadOnlyList<ArgumentSyntax> Members, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record TypedValueSyntax(ExpressionSyntax Type, ExpressionSyntax Value, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record MatchArmSyntax(ExpressionSyntax Pattern, ExpressionSyntax Value, FirmamentV2SourceSpan Span);
+public sealed record MatchSyntax(ExpressionSyntax Scrutinee, IReadOnlyList<MatchArmSyntax> Arms, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+public sealed record DocumentSyntax(string SourceFile, IReadOnlyList<StatementSyntax> Statements,
+ IReadOnlyList<SyntaxToken> Tokens, FirmamentV2SourceSpan Span);
+public sealed record SyntaxParseResult(DocumentSyntax Document, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics)
+{
+ public bool IsSuccess => Diagnostics.All(d => d.Severity is not ("fatal" or "error"));
+ public string ValidationLevel => "StructuralOnlyUnbound";
+}
+public sealed record SyntaxExpressionParseResult(ExpressionSyntax? Expression, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxEvidence.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxEvidence.cs
new file mode 100644
index 00000000..97cac9cd
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxEvidence.cs
@@ -0,0 +1,193 @@
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+/// <summary>Deterministic structural evidence, independent of production route and
+/// shifted source offsets. Original token spellings and scope order remain significant.</summary>
+public static class FirmamentSyntaxEvidence
+{
+ private static readonly JsonSerializerOptions StructuralJson = new() { MaxDepth = 1024 };
+ public static string Normalize(StatementSyntax node)
+ {
+ var json = JsonSerializer.SerializeToNode(node, StructuralJson)!;
+ RemoveSpans(json);
+ return json.ToJsonString(StructuralJson);
+ }
+
+ public static string Fingerprint(DocumentSyntax document) => Convert.ToHexString(SHA256.HashData(
+ Encoding.UTF8.GetBytes(string.Join("\n", document.Statements.Select(Normalize)))));
+
+ public static IEnumerable<DeclarationSyntax> Declarations(DocumentSyntax document) =>
+ Statements(document).OfType<DeclarationSyntax>();
+
+ public static IEnumerable<StatementSyntax> Statements(DocumentSyntax document) => document.Statements.SelectMany(Descendants);
+
+ private static IEnumerable<StatementSyntax> Descendants(StatementSyntax statement)
+ {
+ yield return statement;
+ foreach (var child in ChildStatements(statement))
+ foreach (var descendant in Descendants(child)) yield return descendant;
+ }
+
+ public static IEnumerable<DeclarationSyntax> Declarations(StatementSyntax statement)
+ {
+ if (statement is DeclarationSyntax declaration) yield return declaration;
+ foreach (var child in ChildStatements(statement))
+ foreach (var nested in Declarations(child)) yield return nested;
+ }
+
+ private static IEnumerable<StatementSyntax> ChildStatements(StatementSyntax statement) => statement switch
+ {
+ DeclarationSyntax d => (d.Body?.Statements ?? []).Concat(d.Initializer is null ? [] : ExpressionBodies(d.Initializer))
+ .Concat(d.Annotation is null ? [] : ExpressionBodies(d.Annotation)),
+ FieldSyntax f => ExpressionBodies(f.Value),
+ ExpressionStatementSyntax e => ExpressionBodies(e.Value),
+ ReturnSyntax r => ExpressionBodies(r.Value),
+ MappingSyntax m => [m.Value],
+ _ => []
+ };
+
+ private static IEnumerable<StatementSyntax> ExpressionBodies(ExpressionSyntax expression) => expression switch
+ {
+ ObjectSyntax o => o.Body.Statements.Concat(o.Type is null ? [] : ExpressionBodies(o.Type)),
+ WithSyntax w => w.Body.Statements.Concat(ExpressionBodies(w.Target)),
+ SequenceSyntax s => s.Items.SelectMany(a => ExpressionBodies(a.Value)),
+ CallSyntax c => ExpressionBodies(c.Target).Concat(c.Arguments.SelectMany(a => ExpressionBodies(a.Value))),
+ SpecializationSyntax s => ExpressionBodies(s.Target).Concat(s.Arguments.SelectMany(a => ExpressionBodies(a.Value))),
+ BinarySyntax b => ExpressionBodies(b.Left).Concat(ExpressionBodies(b.Right)),
+ UnarySyntax u => ExpressionBodies(u.Operand),
+ MemberSyntax m => ExpressionBodies(m.Target),
+ IndexSyntax i => ExpressionBodies(i.Target).Concat(i.Index is null ? [] : ExpressionBodies(i.Index)),
+ QuantitySyntax q => ExpressionBodies(q.Value),
+ FrameSyntax f => ExpressionBodies(f.Origin).Concat(f.Axes.SelectMany(a => ExpressionBodies(a.Value))),
+ AliasSyntax a => ExpressionBodies(a.Value),
+ TraceSyntax t => ExpressionBodies(t.Source).Concat(t.From is null ? [] : ExpressionBodies(t.From)).Concat(t.To is null ? [] : ExpressionBodies(t.To)),
+ TypedValueSyntax t => ExpressionBodies(t.Type).Concat(ExpressionBodies(t.Value)),
+ MatchSyntax m => ExpressionBodies(m.Scrutinee).Concat(m.Arms.SelectMany(a => ExpressionBodies(a.Pattern).Concat(ExpressionBodies(a.Value)))),
+ MemberSetSyntax m => ExpressionBodies(m.Target).Concat(m.Members.SelectMany(a => ExpressionBodies(a.Value))),
+ _ => []
+ };
+
+ private static void RemoveSpans(JsonNode? node)
+ {
+ if (node is JsonObject obj)
+ {
+ obj.Remove("Span");
+ foreach (var property in obj) RemoveSpans(property.Value);
+ }
+ else if (node is JsonArray array) foreach (var item in array) RemoveSpans(item);
+ }
+
+ // Only literal comparison, not an expression evaluator or admission policy.
+ internal static double[]? LiteralMillimeters(ExpressionSyntax expression)
+ {
+ var sharedUnit = expression is QuantitySyntax q ? q.Unit.Text : null;
+ var value = expression is QuantitySyntax quantity ? quantity.Value : expression;
+ if (value is not SequenceSyntax { Kind: SequenceKind.List } sequence) return null;
+ var values = new List<double>();
+ foreach (var arg in sequence.Items)
+ {
+ var literal = arg.Value is QuantitySyntax item ? item.Value : arg.Value;
+ var unit = arg.Value is QuantitySyntax itemQuantity ? itemQuantity.Unit.Text : sharedUnit;
+ if (literal is not LiteralSyntax { Kind: LiteralKind.Number } number || unit != "mm"
+ || !double.TryParse(number.Raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var scalar)) return null;
+ values.Add(scalar);
+ }
+ return values.ToArray();
+ }
+}
+
+public enum ShadowDifferenceCategory { A_NewParserRegression, B_ExistingParserDefect, C_LanguageAmbiguity, D_CompatibilityAlias, E_UnsupportedSource, Unclassified }
+public sealed record ShadowDifference(string Code, ShadowDifferenceCategory Category, string Message,
+ FirmamentV2SourceSpan? SourceSpan, string? Context);
+public sealed record ShadowComparison(int ComparedFacts, int UncomparedDeclarations, int UncomparedFields, bool SemanticParityQualified,
+ IReadOnlyList<ShadowDifference> Differences, IReadOnlyList<string> Limitations);
+public sealed record SyntaxSummary(int TokenCount, int DeclarationCount, int FieldCount,
+ IReadOnlyDictionary<string, int> ConstructCounts, string Fingerprint);
+public sealed record ProductionSyntaxProjection(bool IsSuccess, string Disposition, string? ParserRoute,
+ string? ModelName, int TemplateInstanceCount, int FeatureInvocationCount, int StaticPatternGeneratedCount,
+ IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics);
+public sealed record FirmamentShadowReport(string LanguageVersion, string ShadowStatus, string ValidationLevel,
+ SyntaxSummary Summary, ProductionSyntaxProjection ProductionProjection, ShadowComparison Comparison,
+ IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics);
+
+/// <summary>Comparison is deliberately partial. Legacy AIR has already erased most
+/// fields and source scopes. A missing receipt is a gap, never a parity success.</summary>
+public static class FirmamentShadowAnalysis
+{
+ public static FirmamentShadowReport Compare(SyntaxParseResult syntax, FirmamentV2ParseResult production, string source)
+ {
+ var declarations = FirmamentSyntaxEvidence.Declarations(syntax.Document).ToArray();
+ var differences = new List<ShadowDifference>();
+ var compared = new HashSet<DeclarationSyntax>();
+ var facts = 0;
+ var comparedFields = 0;
+ var doc = production.Document;
+ var model = syntax.Document.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d => d.Type.Name.Text == "Model");
+ if (model?.Name is not null && doc is not null)
+ {
+ facts++; compared.Add(model);
+ if (model.Name.Text != doc.ModelName) differences.Add(new("owner-name-mismatch", ShadowDifferenceCategory.Unclassified,
+ $"Original Model '{model.Name.Text}' differs from production owner '{doc.ModelName}'.", model.Name.Span, "Model"));
+ }
+ foreach (var solid in doc?.Solids ?? [])
+ {
+ var named = declarations.Where(d => d.Name?.Text == solid.Name).ToArray();
+ var typed = named.Where(d => d.Type.Name.Text == solid.RecordType).ToArray();
+ var candidates = typed.Length > 0 ? typed : named;
+ if (candidates.Length != 1) continue; // expansion/scoping requires X2 provenance
+ var candidate = candidates[0]; compared.Add(candidate); facts++;
+ if (candidate.Type.Name.Text != solid.RecordType)
+ differences.Add(new("primitive-type-mismatch", ShadowDifferenceCategory.Unclassified,
+ $"Original declaration type '{candidate.Type.Name.Text}' differs from production record '{solid.RecordType}'. Expansion may require provenance.", candidate.Type.Span, solid.Name));
+ if (solid.Box is null) continue;
+ var sizes = candidate.Body?.Statements.OfType<FieldSyntax>().Where(f => f.Name.Text is "Size" or "size").ToArray() ?? [];
+ if (sizes.Length != 1) continue;
+ var size = sizes[0];
+ var literals = FirmamentSyntaxEvidence.LiteralMillimeters(size.Value);
+ if (literals is null) continue;
+ facts++;
+ comparedFields++;
+ if (!literals.SequenceEqual(solid.Box.Size)) differences.Add(new("box-size-mismatch", ShadowDifferenceCategory.Unclassified,
+ "Original literal Box size differs from the production primitive record.", size.Span, solid.Name));
+ }
+ foreach (var compose in doc?.Composes ?? [])
+ {
+ var candidates = declarations.Where(d => d.Type.Name.Text == "Compose" && d.Name?.Text == compose.Name).ToArray();
+ if (candidates.Length != 1) continue;
+ var declaration = candidates[0]; compared.Add(declaration);
+ foreach (var child in declaration.Body?.Statements.OfType<DeclarationSyntax>() ?? [])
+ {
+ if (child.Name is null) continue;
+ facts++;
+ if (!compose.Operations.Contains(child.Name.Text, StringComparer.Ordinal))
+ differences.Add(new("compose-operation-without-receipt", ShadowDifferenceCategory.Unclassified,
+ $"Source {child.Type.Name.Text} '{child.Name.Text}' has no operation in production Compose '{compose.Name}'. Expansion may require provenance; this is not semantic parity.", child.Span, compose.Name));
+ }
+ }
+ if (!syntax.IsSuccess && production.IsSuccess)
+ differences.Add(new("production-accepted-shadow-rejected", ShadowDifferenceCategory.Unclassified,
+ "Production projection accepts source rejected by the shadow grammar. Classify each syntax diagnostic before migration.", null, null));
+ var existingReport = FirmamentV2ValidationReportBuilder.Build(production, syntax.Document.SourceFile, sourceText: source);
+ var tokens = syntax.Document.Tokens;
+ var leading = tokens.Where(t => t.Kind is not (SyntaxTokenKind.Whitespace or SyntaxTokenKind.Comment or SyntaxTokenKind.End)).Take(2).ToArray();
+ var legacy = production.ParserRoute == "LegacySerialization";
+ var fieldCount = FirmamentSyntaxEvidence.Statements(syntax.Document).OfType<FieldSyntax>().Count();
+ var summary = new SyntaxSummary(tokens.Count, declarations.Length, fieldCount,
+ declarations.GroupBy(d => d.Type.Name.Text).OrderBy(g => g.Key, StringComparer.Ordinal)
+ .ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal), FirmamentSyntaxEvidence.Fingerprint(syntax.Document));
+ return new(legacy ? "LegacySerialization" : leading.Length == 0 ? "Empty" : production.Disposition != FirmamentV2ParseDisposition.NotRecognized ? "V2" : "V2Candidate",
+ syntax.IsSuccess ? "Parsed" : "Rejected", syntax.ValidationLevel, summary,
+ new(production.IsSuccess, production.Disposition.ToString(), production.ParserRoute, doc?.ModelName,
+ doc?.TemplateInstantiations?.Count ?? 0, doc?.FeatureInvocations?.Count ?? 0,
+ doc?.StaticAuthoring?.Patterns.Sum(p => p.GeneratedCount) ?? 0, existingReport.Diagnostics),
+ new(facts, declarations.Length - compared.Count, fieldCount - comparedFields, false, differences.ToArray(),
+ ["No semantic admission, expansion, dimensional evaluation or geometry is performed by the shadow parser.",
+ "Comparison covers original Model identity, unambiguous primitive type/name, literal-mm Box size and Compose operation receipts only.",
+ "Legacy AIR does not retain complete original nesting, field consumption or expansion provenance; other declarations and all unmatched fields are unqualified."]), syntax.Diagnostics);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
new file mode 100644
index 00000000..e12c3d19
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
@@ -0,0 +1,425 @@
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+/// <summary>Shared recursive descent over the editor's lexer. No expansion, name
+/// resolution, casing rewrite, engineering admission or geometry is performed.</summary>
+public static class FirmamentSyntaxParser
+{
+ public static SyntaxExpressionParseResult ParseExpression(string source) => new Parser(source, "inline").ParseExpression();
+ public static SyntaxParseResult Parse(string source, string sourceFile = "inline")
+ {
+ ArgumentNullException.ThrowIfNull(source);
+ return new Parser(source, sourceFile).Parse();
+ }
+
+ private sealed class ParseFailure : Exception;
+ private sealed class Parser
+ {
+ private readonly string source;
+ private readonly string file;
+ private readonly SyntaxToken[] all;
+ private readonly SyntaxToken[] tokens;
+ private readonly List<FirmamentV2ValidationDiagnostic> diagnostics = [];
+ private readonly Stack<string> contexts = [];
+ private int at;
+ private int depth;
+ private const int MaxDepth = 128;
+ private SyntaxToken Current => tokens[at];
+ private SyntaxToken Previous => tokens[Math.Max(0, at - 1)];
+ private bool End => Current.Kind == SyntaxTokenKind.End;
+ private bool LineBreak => at > 0 && source.AsSpan(Previous.Span.Start + Previous.Span.Length,
+ Current.Span.Start - Previous.Span.Start - Previous.Span.Length).ContainsAny('\r', '\n');
+
+ public Parser(string source, string file)
+ {
+ this.source = source;
+ this.file = file;
+ var lexemes = FirmamentLanguageAnalysisService.Lex(source, lossless: true);
+ all = lexemes.Select(t => new SyntaxToken(t.Shape switch
+ {
+ "identifier" => SyntaxTokenKind.Identifier, "number" => SyntaxTokenKind.Number,
+ "string" => SyntaxTokenKind.String, "whitespace" => SyntaxTokenKind.Whitespace,
+ "comment" => SyntaxTokenKind.Comment, "end" => SyntaxTokenKind.End,
+ _ => SyntaxTokenKind.Punctuation
+ }, t.Text, new(t.Start, t.Length))).ToArray();
+ tokens = all.Where(t => t.Kind is not (SyntaxTokenKind.Whitespace or SyntaxTokenKind.Comment)).ToArray();
+ foreach (var t in lexemes.Where(t => t.Error is not null))
+ Error("firmament-syntax-unterminated-token", t.Error!, new(t.Start, t.Length));
+ }
+
+ public SyntaxParseResult Parse() => new(new(file, Statements(null), all, new(0, source.Length)), diagnostics.ToArray());
+
+ public SyntaxExpressionParseResult ParseExpression()
+ {
+ ExpressionSyntax? expression = null;
+ try
+ {
+ expression = Expression();
+ if (!End) throw Fail("firmament-syntax-expression", $"Unexpected '{Current.Text}' after expression.");
+ }
+ catch (ParseFailure) { expression = null; }
+ return new(expression, diagnostics.ToArray());
+ }
+
+ private IReadOnlyList<StatementSyntax> Statements(string? close)
+ {
+ var result = new List<StatementSyntax>();
+ while (!End && (close is null || !Is(close)))
+ {
+ if (Take(";")) continue;
+ var before = at;
+ try { result.Add(Statement()); }
+ catch (ParseFailure) { Recover(before, close); }
+ if (at == before && !End) at++; // recovery must always advance
+ }
+ return result.ToArray();
+ }
+
+ private StatementSyntax Statement()
+ {
+ Enter();
+ try { return StatementCore(); }
+ finally { depth--; }
+ }
+
+ private StatementSyntax StatementCore()
+ {
+ var start = Current.Span.Start;
+ if (Is("<") && Peek(1).Kind == SyntaxTokenKind.Identifier) return Declaration(occurrence: true);
+ if (Current.Kind == SyntaxTokenKind.Identifier)
+ {
+ if (Peek(1).Text == ":")
+ {
+ var name = Identifier(); Expect(":");
+ var value = Expression();
+ if (Take("=")) value = new TypedValueSyntax(value, Expression(), Span(value.Span.Start));
+ return new FieldSyntax(name, value, Span(start));
+ }
+ if (Pair("=", ">", offset: 1))
+ {
+ var key = Identifier(); Expect("="); Expect(">");
+ return new MappingSyntax(key, Statement(), Span(start));
+ }
+ if (Is("return")) { at++; return new ReturnSyntax(Expression(), Span(start)); }
+ if (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));
+ }
+ // A call or a pipeline is an expression statement. A bare name in an
+ // Enum/Loop is also syntax, never implicitly an admitted declaration.
+ if (Is("Reverse") || Peek(1).Text is "(" or "." or "|" or "[" or "As" or "From" or "To" || Peek(1).Text is ";" or "}" || Peek(1).Kind == SyntaxTokenKind.End)
+ return new ExpressionStatementSyntax(Expression(), Span(start));
+ var declaration = Declaration(occurrence: false);
+ if (declaration.Name is null && declaration.Body is null && declaration.Initializer is null
+ && declaration.Annotation is null && declaration.ResultType is null && declaration.Modifiers.Count == 0
+ && declaration.Parameters.Count == 0 && declaration.Clauses.Count == 0)
+ {
+ ExpressionSyntax reference = new ReferenceSyntax(declaration.Type.Name, declaration.Type.Name.Span);
+ if (declaration.Type.Span.Length > declaration.Type.Name.Span.Length)
+ reference = new SpecializationSyntax(reference, declaration.Type.Arguments, declaration.Type.Span);
+ return new ExpressionStatementSyntax(reference, declaration.Span);
+ }
+ return declaration;
+ }
+ throw Fail("firmament-syntax-statement", $"Expected a declaration, field or expression; found '{Current.Text}'.");
+ }
+
+ private DeclarationSyntax Declaration(bool occurrence)
+ {
+ var start = Current.Span.Start;
+ if (occurrence) Expect("<");
+ var modifiers = new List<TypeSyntax>();
+ var type = Type();
+ // Prefixes are finite syntax roles, not a list of admitted engineering types.
+ while ((type.Name.Text is "Template" or "Concept" or "Construction" or "Radial" or "Linear" or "Mirror" or "Mirrored" or "Semantic"
+ && Current.Kind == SyntaxTokenKind.Identifier && (Peek(1).Kind == SyntaxTokenKind.Identifier || Peek(1).Text == "<"))
+ || type.Name.Text == "Static" && Is("Table")
+ || type.Name.Text is "Assert" or "Analysis" && Current.Kind == SyntaxTokenKind.Identifier)
+ {
+ modifiers.Add(type); type = Type();
+ }
+ IdentifierSyntax? name = null;
+ if (Current.Kind == SyntaxTokenKind.Identifier && !LineBreak && !IsClause(Current.Text)) name = Identifier();
+ var parameters = Take("(") ? Arguments(")") : [];
+ if (type.Name.Text == "Replace" && Take("."))
+ {
+ var member = Identifier();
+ name = new IdentifierSyntax(name!.Text + "." + member.Text, new(name.Span.Start, member.Span.Start + member.Span.Length - name.Span.Start));
+ }
+ ExpressionSyntax? annotation = null, result = null, initializer = null;
+ if (Take(":")) annotation = Expression(allowObject: false, stopGreater: occurrence);
+ if (Pair("-", ">")) { at += 2; result = Expression(allowObject: false); }
+ var clauses = new List<ClauseSyntax>();
+ while (TryClause(Current.Text, out var clause))
+ {
+ var clauseStart = Current.Span.Start; at++;
+ if (clause == ClauseKind.Key) Take(":");
+ clauses.Add(new(clause, Expression(allowObject: false), Span(clauseStart)));
+ }
+ if (Pair("=", ">")) { at += 2; initializer = Expression(stopGreater: occurrence); }
+ else if (Take("=")) initializer = Expression(stopGreater: occurrence);
+ if (type.Name.Text == "Replace" && Take("With"))
+ {
+ result = Expression(allowObject: false);
+ if (Current.Kind == SyntaxTokenKind.Identifier) initializer = new ReferenceSyntax(Identifier(), Previous.Span);
+ }
+ BlockSyntax? body = null;
+ if (occurrence)
+ {
+ Expect(">");
+ var bodyStart = Previous.Span.Start + Previous.Span.Length;
+ var statements = new List<StatementSyntax>();
+ while (!End && !Pair("<", "/"))
+ {
+ if (Take(";")) continue;
+ var before = at;
+ try { statements.Add(Statement()); }
+ catch (ParseFailure) { Recover(before, "<"); }
+ if (at == before && !End) at++;
+ }
+ var bodyEnd = Current.Span.Start;
+ Expect("<"); Expect("/");
+ var closeName = Identifier();
+ if (closeName.Text != type.Name.Text) Error("firmament-syntax-tag-mismatch", $"Expected closing tag for {type.Name.Text}, found {closeName.Text}.", closeName.Span);
+ Expect(">"); body = new(statements.ToArray(), new(bodyStart, bodyEnd - bodyStart));
+ }
+ else if (Is("{")) body = Block(type.Name.Text == "Enum", $"{type.Name.Text} {name?.Text}".TrimEnd());
+ else if (initializer is null && !End && !LineBreak && !Is(";") && !Is("}"))
+ throw Fail("firmament-syntax-declaration-tail", $"Unexpected '{Current.Text}' after {type.Name.Text} {name?.Text}; expected a body, initializer or separator.");
+ return new(type, name, modifiers.ToArray(), parameters, annotation, result, clauses.ToArray(), initializer, body, occurrence, Span(start));
+ }
+
+ private TypeSyntax Type()
+ {
+ var name = Identifier();
+ var args = Take("<") ? Arguments(">") : [];
+ return new(name, args, Span(name.Span.Start));
+ }
+
+ private BlockSyntax Block(bool enumValues = false, string? context = null)
+ {
+ Enter();
+ if (context is not null) contexts.Push(context);
+ try
+ {
+ var start = Current.Span.Start; Expect("{");
+ IReadOnlyList<StatementSyntax> statements;
+ if (enumValues)
+ {
+ var values = new List<StatementSyntax>();
+ while (!End && !Is("}"))
+ {
+ if (Take(";") || Take(",")) continue;
+ var name = Identifier();
+ values.Add(new ExpressionStatementSyntax(new ReferenceSyntax(name, name.Span), name.Span));
+ }
+ statements = values.ToArray();
+ }
+ else statements = Statements("}");
+ Expect("}");
+ return new(statements, Span(start));
+ }
+ finally { if (context is not null) contexts.Pop(); depth--; }
+ }
+
+ private ExpressionSyntax Expression(int minimum = 0, bool allowObject = true, bool stopGreater = false)
+ {
+ Enter();
+ try
+ {
+ var start = Current.Span.Start;
+ ExpressionSyntax left;
+ if (Take("+") || Take("-") || Take("!") || Take("Reverse"))
+ {
+ var op = Previous.Text switch { "+" => UnaryOperator.Positive, "-" => UnaryOperator.Negative, "Reverse" => UnaryOperator.Reverse, _ => UnaryOperator.Not };
+ left = new UnarySyntax(op, Expression(80, allowObject, stopGreater), Span(start));
+ }
+ else if (Current.Kind is SyntaxTokenKind.Number or SyntaxTokenKind.String || Is("true") || Is("false"))
+ {
+ var t = Current; at++;
+ left = new LiteralSyntax(t.Kind == SyntaxTokenKind.String ? LiteralKind.String : t.Kind == SyntaxTokenKind.Number ? LiteralKind.Number : LiteralKind.Boolean, t.Text, t.Span);
+ }
+ else if (Take("Match"))
+ {
+ var scrutinee = Expression(allowObject: false);
+ Expect("{");
+ var arms = new List<MatchArmSyntax>();
+ while (!End && !Is("}"))
+ {
+ if (Take(";") || Take(",")) continue;
+ var armStart = Current.Span.Start;
+ var pattern = Expression(allowObject: false);
+ Expect("="); Expect(">");
+ arms.Add(new(pattern, Expression(), Span(armStart)));
+ }
+ Expect("}");
+ left = new MatchSyntax(scrutinee, arms.ToArray(), Span(start));
+ }
+ else if (Current.Kind == SyntaxTokenKind.Identifier)
+ {
+ var name = Identifier(); left = new ReferenceSyntax(name, name.Span);
+ if (name.Text is "Blind" or "CenteredAt" && !Is("(") && !Is(">") && !Is(",") && !LineBreak)
+ {
+ var argument = Expression(80, allowObject, stopGreater);
+ left = new CallSyntax(left, [new(null, argument, null, argument.Span)], Span(start));
+ }
+ }
+ else if (allowObject && Is("{")) left = new ObjectSyntax(null, Block(), Span(start));
+ else if (Is("[") || Is("("))
+ {
+ var list = Take("["); if (!list) Expect("(");
+ left = new SequenceSyntax(list ? SequenceKind.List : SequenceKind.Tuple, Arguments(list ? "]" : ")"), Span(start));
+ }
+ else throw Fail("firmament-syntax-expression", $"Expected an expression; found '{(End ? "end of file" : Current.Text)}'.");
+
+ var suffixCount = 0;
+ while (!End)
+ {
+ if (++suffixCount > MaxDepth) throw Fail("firmament-syntax-depth", $"Expression chain exceeds the bounded parser limit of {MaxDepth}.");
+ if (Take("As")) { left = new AliasSyntax(left, Identifier(), Span(start)); continue; }
+ if (Current.Text is "From" or "To" && Peek(1).Text != ":")
+ {
+ ExpressionSyntax? from = null, to = null;
+ if (Take("From")) from = EndpointReference();
+ if (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 == "[")
+ {
+ var axes = new List<ArgumentSyntax>();
+ while (Current.Text is "x" or "y" or "z" or "normal" && Peek(1).Text == "[")
+ {
+ var axis = Identifier(); var vectorStart = Current.Span.Start; Expect("[");
+ var vector = new SequenceSyntax(SequenceKind.List, Arguments("]"), Span(vectorStart));
+ axes.Add(new(axis, vector, null, Span(axis.Span.Start)));
+ }
+ left = new FrameSyntax(left, axes.ToArray(), Span(start)); continue;
+ }
+ if (Take("."))
+ {
+ left = Take("[") ? new MemberSetSyntax(left, Arguments("]"), Span(start))
+ : new MemberSyntax(left, Identifier(), Span(start));
+ continue;
+ }
+ if (Take("(")) { left = new CallSyntax(left, Arguments(")"), Span(start)); continue; }
+ if (Take("["))
+ {
+ var index = Is("]") ? null : Expression(); Expect("]");
+ left = new IndexSyntax(left, index, Span(start)); continue;
+ }
+ // Angle suffixes belong to type/call-shaped names. Comparisons
+ // require a non-adjacent '<'; ambiguous forms require explicit spacing.
+ if (Is("<") && left is ReferenceSyntax or MemberSyntax && (Current.Span.Start == left.Span.Start + left.Span.Length
+ || Peek(1).Text == ">" || Peek(1).Kind == SyntaxTokenKind.Identifier && Peek(2).Text == ":"))
+ {
+ at++; left = new SpecializationSyntax(left, Arguments(">"), Span(start)); continue;
+ }
+ if (allowObject && Is("{") && left is ReferenceSyntax or SpecializationSyntax or AliasSyntax)
+ { left = new ObjectSyntax(left, Block(), Span(start)); continue; }
+ if (allowObject && Take("with")) { left = new WithSyntax(left, Block(), Span(start)); continue; }
+ if (Current.Kind == SyntaxTokenKind.Identifier && !LineBreak &&
+ (Current.Text is "mm" or "cm" or "m" or "deg" or "rad"
+ || left is LiteralSyntax { Kind: LiteralKind.Number } && Current.Span.Start == left.Span.Start + left.Span.Length)
+ && left is LiteralSyntax or SequenceSyntax)
+ { left = new QuantitySyntax(left, Identifier(), Span(start)); continue; }
+ if (!Operator(out var binary, out var precedence, out var width) || precedence < minimum || stopGreater && Is(">")) break;
+ at += width;
+ left = new BinarySyntax(left, binary, Expression(precedence + (binary == BinaryOperator.Power ? 0 : 1), allowObject, stopGreater), Span(start));
+ }
+ return left;
+ }
+ finally { depth--; }
+ }
+
+ private IReadOnlyList<ArgumentSyntax> Arguments(string close)
+ {
+ var args = new List<ArgumentSyntax>();
+ while (!End && !Is(close))
+ {
+ var start = Current.Span.Start;
+ IdentifierSyntax? name = null;
+ if (Current.Kind == SyntaxTokenKind.Identifier && Peek(1).Text == ":") { name = Identifier(); Expect(":"); }
+ var value = Expression(stopGreater: close == ">");
+ ExpressionSyntax? fallback = Take("=") ? Expression(stopGreater: close == ">") : null;
+ args.Add(new(name, value, fallback, Span(start)));
+ if (!Take(",") && !(close == "]" && LineBreak && !Is(close))) break;
+ }
+ Expect(close); return args.ToArray();
+ }
+
+ private bool Operator(out BinaryOperator op, out int precedence, out int width)
+ {
+ width = 1;
+ (op, precedence) = Current.Text switch
+ {
+ "+" => (BinaryOperator.Add, 50), "-" => (BinaryOperator.Subtract, 50),
+ "*" => (BinaryOperator.Multiply, 60), "/" => (BinaryOperator.Divide, 60), "%" => (BinaryOperator.Remainder, 60),
+ "^" => (BinaryOperator.Power, 70), "<" => (BinaryOperator.Less, 40), ">" => (BinaryOperator.Greater, 40),
+ _ => (default, -1)
+ };
+ if (Pair("|", ">")) { op = BinaryOperator.Pipeline; precedence = 10; width = 2; }
+ else if (Pair("-", ">")) { op = BinaryOperator.Direction; precedence = 15; width = 2; }
+ else if (Pair("|", "|")) { op = BinaryOperator.Or; precedence = 20; width = 2; }
+ else if (Pair("&", "&")) { op = BinaryOperator.And; precedence = 30; width = 2; }
+ else if (Pair("=", "=")) { op = BinaryOperator.Equal; precedence = 40; width = 2; }
+ else if (Pair("!", "=")) { op = BinaryOperator.NotEqual; precedence = 40; width = 2; }
+ else if (Pair("<", "=")) { op = BinaryOperator.LessEqual; precedence = 40; width = 2; }
+ else if (Pair(">", "=")) { op = BinaryOperator.GreaterEqual; precedence = 40; width = 2; }
+ return precedence >= 0;
+ }
+
+ private static bool IsClause(string text) => TryClause(text, out _);
+ private ExpressionSyntax EndpointReference()
+ {
+ var name = Identifier();
+ ExpressionSyntax result = new ReferenceSyntax(name, name.Span);
+ while (Take(".")) result = new MemberSyntax(result, Identifier(), Span(name.Span.Start));
+ return result;
+ }
+ private 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) };
+ return (int)kind >= 0;
+ }
+ private IdentifierSyntax Identifier()
+ {
+ if (Current.Kind != SyntaxTokenKind.Identifier) throw Fail("firmament-syntax-identifier", $"Expected an identifier; found '{Current.Text}'.");
+ var t = Current; at++; return new(t.Text, t.Span);
+ }
+ private void Enter()
+ {
+ if (depth >= MaxDepth) throw Fail("firmament-syntax-depth", $"Syntax nesting exceeds the bounded parser limit of {MaxDepth}.");
+ depth++;
+ }
+ private void Recover(int before, string? close)
+ {
+ // Skip a damaged statement's balanced groups, not the enclosing scope.
+ var nesting = 0;
+ while (!End)
+ {
+ if (nesting == 0 && (Is("}") || close is not null && Is(close))) return;
+ if (at > before && nesting == 0 && (LineBreak || Take(";"))) return;
+ if (Is("{") || Is("[") || Is("(")) nesting++;
+ if (Is("}") || Is("]") || Is(")")) nesting = Math.Max(0, nesting - 1);
+ at++;
+ }
+ }
+ private ParseFailure Fail(string code, string message) { Error(code, message, Current.Span); return new(); }
+ private void Error(string code, string message, FirmamentV2SourceSpan span)
+ {
+ var preceding = source.AsSpan(0, span.Start);
+ var line = 1; foreach (var c in preceding) if (c == '\n') line++;
+ var lastBreak = preceding.LastIndexOf('\n');
+ diagnostics.Add(new(code, "fatal", message, Target: contexts.TryPeek(out var context) ? context : null) { SourceFile = file, SourceSpan = span, Line = line,
+ Column = span.Start - lastBreak, Stage = "Syntax", Source = "UnifiedParser" });
+ }
+ private SyntaxToken Peek(int offset) => tokens[Math.Min(tokens.Length - 1, at + offset)];
+ private bool Is(string text) => Current.Text == text;
+ private bool Pair(string first, string second, int offset = 0) => Peek(offset).Text == first && Peek(offset + 1).Text == second
+ && Peek(offset).Span.Start + Peek(offset).Span.Length == Peek(offset + 1).Span.Start;
+ private bool Take(string text) { if (!Is(text)) return false; at++; return true; }
+ private void Expect(string text) { if (!Take(text)) throw Fail("firmament-syntax-expected-token", $"Expected '{text}'; found '{(End ? "end of file" : Current.Text)}'."); }
+ private FirmamentV2SourceSpan Span(int start) => new(start, Math.Max(0, Previous.Span.Start + Previous.Span.Length - start));
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs
new file mode 100644
index 00000000..0f769c64
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs
@@ -0,0 +1,128 @@
+using System.Globalization;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+/// <summary>Literal and bounded dimensional binding over syntax. This preserves the
+/// existing profile evaluator's one-unit, dimension-0/1 arithmetic contract.</summary>
+internal static class FirmamentSyntaxValues
+{
+ public static string? Reference(ExpressionSyntax? value) => value switch
+ {
+ ReferenceSyntax r => r.Name.Text,
+ MemberSyntax m when Reference(m.Target) is { } target => target + "." + m.Member.Text,
+ UnarySyntax { Operator: UnaryOperator.Positive } u when Reference(u.Operand) is { } axis => "+" + axis,
+ UnarySyntax { Operator: UnaryOperator.Negative } u when Reference(u.Operand) is { } axis => "-" + axis,
+ LiteralSyntax { Kind: LiteralKind.String } s => System.Text.Json.JsonSerializer.Deserialize<string>(s.Raw),
+ _ => null
+ };
+
+ public static bool TryMeasure(ExpressionSyntax? expression, string unit, out double value)
+ {
+ value = double.NaN;
+ if (!Evaluate(expression, unit, out var result, out var dimension) || dimension != (unit.Length == 0 ? 0 : 1)) return false;
+ value = result; return double.IsFinite(value);
+ }
+
+ private static bool Evaluate(ExpressionSyntax? expression, string unit, out double value, out int dimension)
+ {
+ value = double.NaN; dimension = 0;
+ switch (expression)
+ {
+ case LiteralSyntax { Kind: LiteralKind.Number } literal:
+ return double.TryParse(literal.Raw, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);
+ case QuantitySyntax quantity when quantity.Unit.Text == unit:
+ if (!Evaluate(quantity.Value, unit, out value, out dimension) || dimension != 0) return false;
+ dimension = 1; return true;
+ case UnarySyntax { Operator: UnaryOperator.Positive or UnaryOperator.Negative } unary:
+ if (!Evaluate(unary.Operand, unit, out value, out dimension)) return false;
+ if (unary.Operator == UnaryOperator.Negative) value = -value;
+ return true;
+ case SequenceSyntax { Kind: SequenceKind.Tuple, Items.Count: 1 } group:
+ return Evaluate(group.Items[0].Value, unit, out value, out dimension);
+ case BinarySyntax binary:
+ if (!Evaluate(binary.Left, unit, out var left, out var ld) || !Evaluate(binary.Right, unit, out var right, out var rd)) return false;
+ switch (binary.Operator)
+ {
+ case BinaryOperator.Add or BinaryOperator.Subtract when ld == rd:
+ dimension = ld; value = binary.Operator == BinaryOperator.Add ? left + right : left - right; break;
+ case BinaryOperator.Multiply:
+ dimension = ld + rd; value = left * right; break;
+ case BinaryOperator.Divide when Math.Abs(right) > double.Epsilon:
+ dimension = ld - rd; value = left / right; break;
+ default: return false;
+ }
+ return dimension is >= 0 and <= 1 && double.IsFinite(value);
+ default: return false;
+ }
+ }
+
+ public static bool Vector(ExpressionSyntax? expression, string unit, out double[] values)
+ {
+ values = [];
+ var sharedUnit = expression as QuantitySyntax;
+ var inner = sharedUnit?.Value ?? expression;
+ IReadOnlyList<ArgumentSyntax>? items = inner switch
+ {
+ SequenceSyntax { Kind: SequenceKind.List } sequence => sequence.Items,
+ CallSyntax { Target: ReferenceSyntax { Name.Text: "Point2" or "Point3" or "Vector2" or "Vector3" } } call => call.Arguments,
+ _ => null
+ };
+ if (items is null) return false;
+ var result = new double[items.Count];
+ for (var i = 0; i < items.Count; i++)
+ {
+ var item = items[i].Value;
+ if (sharedUnit is not null) item = new QuantitySyntax(item, sharedUnit.Unit, item.Span);
+ if (!TryMeasure(item, unit, out result[i])) return false;
+ }
+ values = result; return true;
+ }
+}
+
+/// <summary>Each semantic owner consumes its actual fields, then closes its scope.
+/// No second field schema or spelling allowlist is maintained here.</summary>
+internal sealed class FirmamentSyntaxFields(DeclarationSyntax declaration, List<string> diagnostics)
+{
+ private readonly HashSet<FieldSyntax> consumed = [];
+ public DeclarationSyntax Declaration => declaration;
+ public ExpressionSyntax? Take(string name)
+ {
+ var fields = declaration.Body?.Statements.OfType<FieldSyntax>().Where(f => SameField(f.Name.Text, name)).ToArray() ?? [];
+ foreach (var field in fields) consumed.Add(field);
+ if (fields.Length > 1) diagnostics.Add($"firmament-v2-field-duplicate:{declaration.Type.Name.Text}:{name}");
+ return fields.Length == 1 ? fields[0].Value : null;
+ }
+ public bool Measure(string name, string unit, out double value) => FirmamentSyntaxValues.TryMeasure(Take(name), unit, out value);
+ public double Number(string name, string unit, double fallback = double.NaN)
+ {
+ var expression = Take(name);
+ if (expression is null) return fallback;
+ if (FirmamentSyntaxValues.TryMeasure(expression, unit, out var value)) return value;
+ Invalid(name); return double.NaN;
+ }
+ public IReadOnlyList<FieldSyntax> TakeAll(string name)
+ {
+ var fields = declaration.Body?.Statements.OfType<FieldSyntax>().Where(f => SameField(f.Name.Text, name)).ToArray() ?? [];
+ foreach (var field in fields) consumed.Add(field);
+ return fields;
+ }
+ public void Invalid(string name) => diagnostics.Add($"firmament-v2-field-value-invalid:{declaration.Type.Name.Text}:{name}");
+ // Some owners intentionally try a reference and then an inline vector. A
+ // conversion probe is not an error; the owner decides which forms it admits.
+ public string? Word(string name) => FirmamentSyntaxValues.Reference(Take(name));
+ public bool Vector(string name, string unit, out double[] values) => FirmamentSyntaxValues.Vector(Take(name), unit, out values);
+ public void Complete()
+ {
+ if (declaration.Parameters.Count > 0 || declaration.Annotation is not null || declaration.Initializer is not null)
+ diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:{declaration.Type.Name.Text}:header");
+ if (declaration.Clauses.Count > 0)
+ diagnostics.Add($"firmament-v2-placement-unsupported:{declaration.Type.Name.Text}:{declaration.Name?.Text}: This field-based construct does not admit header placement clauses; use its documented fields.");
+ foreach (var field in declaration.Body?.Statements.OfType<FieldSyntax>() ?? [])
+ if (!consumed.Contains(field)) diagnostics.Add($"{FirmamentV2Parser.CanonicalFieldUnknown}:{declaration.Type.Name.Text}:{field.Name.Text}");
+ foreach (var statement in declaration.Body?.Statements.Where(s => s is not FieldSyntax) ?? [])
+ diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:{declaration.Type.Name.Text}:{(statement as DeclarationSyntax)?.Type.Name.Text ?? "expression"}");
+ }
+ public static bool SameField(string authored, string canonical) => authored == canonical || authored == FirmamentSourceSpelling.PreferredField(canonical);
+ public IReadOnlyList<FirmamentV2AuthoredField> AuthoredFields => (declaration.Body?.Statements.OfType<FieldSyntax>() ?? [])
+ .Select(f => new FirmamentV2AuthoredField(f.Name.Text, f.Span, f.Value.Span)).ToArray();
+}
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
index 5bacc0c8..ccff9a52 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
@@ -2,6 +2,7 @@ using System.Globalization;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using Aetheris.Semantics;
namespace Aetheris.Kernel.Firmament.Materializer;
@@ -177,12 +178,7 @@ public static class PrismaticProfileCompositionParser
private static readonly Regex Rect = new(@"\bRect2\s+(?<n>\w+)\s*\{\s*Center\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\s*(?:\]|\))\s*;?\s*Size\s*:\s*\[(?<w>[-+.\d]+)mm\s*,\s*(?<h>[-+.\d]+)mm\]", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex ProfileHead = new(@"\bProfile\s+(?<n>\w+)\s+Using\s+(?<layout>\w+)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex Segment = new(@"\bSegment\s+(?<n>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*From\s*:\s*(?<from>[\w.]+)\s*;?\s*To\s*:\s*(?<to>[\w.]+)(?:\s*;?\s*Sweep\s*:\s*(?<sweep>Clockwise|CounterClockwise))?", RegexOptions.Singleline | RegexOptions.CultureInvariant);
- private static readonly Regex ComposeHead = new(@"\bCompose\s+(?<n>\w+)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex ModifyHead = new(@"\bModify\s+(?<target>\w+)\s*\{", RegexOptions.CultureInvariant);
- private static readonly Regex Placement = new(@"\bPlacement\s+(?<n>\w+)\s*\{\s*Anchor\s*:\s*\[(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\s*,\s*(?<z>[-+.\d]+)mm\]\s*;?\s*ProfilePlane\s*:\s*(?<plane>\w+)\s*;?\s*Axis\s*:\s*(?<axis>[+-][XYZ])\s*;?\s*ReferenceDirection\s*:\s*(?<reference>[+-][XYZ])", RegexOptions.Singleline | RegexOptions.CultureInvariant);
- private static readonly Regex Operation = new(@"\b(?<intent>Base|Add|Remove)\s+(?<n>\w+)\s*\{\s*Profile\s*:\s*(?<profile>\w+)\s*;?\s*From\s*:\s*(?<from>[-+.\d]+)mm\s*;?\s*To\s*:\s*(?<to>[-+.\d]+)mm(?:\s*;?\s*Role\s*:\s*(?<role>\w+))?", RegexOptions.Singleline | RegexOptions.CultureInvariant);
- private static readonly Regex BossHeader = new(@"\bBoss\s+(?<n>\w+)\s*\{", RegexOptions.CultureInvariant);
- private static readonly Regex PocketHeader = new(@"\bPocket\s+(?<n>\w+)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex OffsetHeader = new(@"\b(?<intent>AddOffset|RemoveOffset)\s*<\s*(?<tool>[A-Za-z_]\w*)\s*>\s+(?<n>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex OffsetTarget = new(@"\bTarget\s*:\s*(?<value>[A-Za-z_]\w*)", RegexOptions.CultureInvariant);
private static readonly Regex OffsetDirection = new(@"\b(?:Along|Axis|Direction)\s*:\s*(?<value>[+-][XYZ])", RegexOptions.CultureInvariant);
@@ -214,7 +210,7 @@ public static class PrismaticProfileCompositionParser
private static readonly Regex SlotCornerRadius = new(@"\bCornerRadius\s*:\s*(?<v>[-+.\d]+)mm", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
private static readonly Regex SlotExtent = new(@"\bExtent\s*:\s*(?<v>ThroughAll|Between\s*\(\s*(?<from>[-+.\d]+)mm\s*,\s*(?<to>[-+.\d]+)mm\s*\))", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
- public static bool IsCompositionSource(string source) => ComposeHead.IsMatch(source);
+ public static bool IsCompositionSource(string source) => FirmamentSyntaxEvidence.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d => d.Type.Name.Text == "Compose");
public static PrismaticProfileCompositionParseResult Parse(string source)
{
@@ -296,33 +292,59 @@ public static class PrismaticProfileCompositionParser
diagnostics.Add($"compose-profile-duplicate:{consumed.Value.Name}");
}
- var compose = ComposeHead.Match(source);
- if (!compose.Success) return new(null, profiles, diagnostics.Append("compose-source-missing-compose").ToArray());
- var composeBody = Block(source, compose.Index + compose.Length - 1);
- if (composeBody is null) return new(null, profiles, diagnostics.Append("compose-source-unclosed-compose").ToArray());
- composeBody = BindExternalModifyFeatures(source, compose.Groups["n"].Value, composeBody, diagnostics);
+ var syntax = FirmamentSyntaxParser.Parse(source);
+ var compose = FirmamentSyntaxEvidence.Declarations(syntax.Document).FirstOrDefault(d => d.Type.Name.Text == "Compose");
+ if (compose?.Body is null || compose.Name is null) return new(null, profiles, diagnostics.Append("compose-source-missing-compose").ToArray());
+ if (compose.Clauses.Count > 0 || compose.Type.Arguments.Count > 0)
+ return new(null, profiles, diagnostics.Append("compose-header-unsupported: Declare a supported Placement block inside Compose.").ToArray());
+ var composeBody = source.Substring(compose.Body.Span.Start + 1, compose.Body.Span.Length - 2);
+ composeBody = BindExternalModifyFeatures(source, compose.Name.Text, composeBody, diagnostics);
+ var beforeAdmission = diagnostics.Count;
+ var operationsSyntax = FirmamentSyntaxParser.Parse(composeBody);
+ diagnostics.AddRange(operationsSyntax.Diagnostics.Select(d => d.Code + ":" + d.Message));
+ foreach (var declaration in operationsSyntax.Document.Statements.OfType<DeclarationSyntax>())
+ foreach (var repeated in (declaration.Body?.Statements.OfType<FieldSyntax>() ?? []).GroupBy(f => FirmamentSourceSpelling.PreferredField(f.Name.Text), StringComparer.Ordinal).Where(g => g.Count() > 1))
+ diagnostics.Add($"firmament-v2-field-duplicate:{declaration.Type.Name.Text}:{repeated.Key}");
+ foreach (var statement in operationsSyntax.Document.Statements)
+ {
+ if (statement is DeclarationSyntax declared && declared.Type.Name.Text is
+ "Base" or "Add" or "Remove" or "Boss" or "Pocket" or "AddOffset" or "RemoveOffset" or "Hole" or "Slot" or "EdgeFinish" or "Placement" or "Point2" or "Line2" or "Circle2" or "Path" or "Profile" or "Rect2" or "Axis2" or "Plane") continue;
+ diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:Compose:{(statement as DeclarationSyntax)?.Type.Name.Text ?? "expression"}");
+ }
+ if (diagnostics.Count > beforeAdmission) return new(null, profiles, diagnostics);
var spanInspection = ProfileAuthoringParser.InspectGeometricSpans(source);
diagnostics.AddRange(spanInspection.Diagnostics);
var surfaceSpans = spanInspection.Spans.Where(span => span.SpanType == "Plane").ToDictionary(span => span.SpanId, StringComparer.Ordinal);
- var placementMatch = Placement.Match(composeBody);
+ var placements = operationsSyntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Placement").ToArray();
var placement = new PrismaticProfilePlacement("LegacyImplicitWorldXY", 0d, 0d, 0d, "XY", "+Z", "+X", false);
- if (placementMatch.Success)
+ if (placements.Length > 1) diagnostics.Add("compose-placement-multiple-unsupported");
+ if (placements.FirstOrDefault() is { } authoredPlacement)
{
- placement = new(placementMatch.Groups["n"].Value, N(placementMatch, "x"), N(placementMatch, "y"), N(placementMatch, "z"), placementMatch.Groups["plane"].Value, placementMatch.Groups["axis"].Value, placementMatch.Groups["reference"].Value, true);
- if (!placement.TryResolveConstructionPlane(out _, out var placementDiagnostic))
- diagnostics.Add(placementDiagnostic!);
+ var fields = new FirmamentSyntaxFields(authoredPlacement, diagnostics);
+ var anchorValid = fields.Vector("Anchor", "mm", out var anchor) && anchor.Length == 3;
+ var plane = fields.Word("ProfilePlane"); var axis = fields.Word("Axis"); var reference = fields.Word("ReferenceDirection");
+ fields.Complete();
+ if (!anchorValid || plane is null || axis is null || reference is null) diagnostics.Add("compose-placement-fields-invalid");
+ else
+ {
+ placement = new(authoredPlacement.Name?.Text ?? "", anchor[0], anchor[1], anchor[2], plane, axis, reference, true);
+ if (!placement.TryResolveConstructionPlane(out _, out var placementDiagnostic)) diagnostics.Add(placementDiagnostic!);
+ }
}
var operations = new List<PrismaticProfileOperation>();
var names = new HashSet<string>(StringComparer.Ordinal);
- foreach (Match match in Operation.Matches(composeBody))
+ foreach (var declaration in operationsSyntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text is "Base" or "Add" or "Remove"))
{
- var name = match.Groups["n"].Value;
- var profile = match.Groups["profile"].Value;
- var from = N(match, "from"); var to = N(match, "to");
+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);
+ var name = declaration.Name?.Text ?? "";
+ var profile = fields.Word("Profile") ?? "";
+ var from = fields.Number("From", "mm"); var to = fields.Number("To", "mm");
+ var role = fields.Word("Role") ?? declaration.Type.Name.Text;
+ fields.Complete();
if (!names.Add(name)) diagnostics.Add($"compose-duplicate-operation:{name}");
if (!profiles.ContainsKey(profile)) diagnostics.Add($"ConceptPathProfileNotAdmittedByCompose:{name}:{profile}");
if (!double.IsFinite(from) || !double.IsFinite(to) || from >= to) diagnostics.Add($"compose-invalid-interval:{name}:{from:R}:{to:R}");
- operations.Add(new(name, Enum.Parse<PrismaticProfileIntent>(match.Groups["intent"].Value), profile, from, to, match.Groups["role"].Success ? match.Groups["role"].Value : match.Groups["intent"].Value, $"offset:{match.Index}"));
+ operations.Add(new(name, Enum.Parse<PrismaticProfileIntent>(declaration.Type.Name.Text), profile, from, to, role, $"offset:{declaration.Span.Start}"));
}
var baseOperations = operations.Where(o => o.Intent == PrismaticProfileIntent.Base).ToArray();
if (baseOperations.Length != 1)
@@ -335,14 +357,13 @@ public static class PrismaticProfileCompositionParser
var stock = baseOperations.Length == 1 ? baseOperations[0] : null;
if (stock is not null)
{
- foreach (Match header in BossHeader.Matches(composeBody))
+ foreach (var declaration in operationsSyntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Boss"))
{
- var name = header.Groups["n"].Value;
- var body = Block(composeBody, header.Index + header.Length - 1);
- if (body is null) { diagnostics.Add($"firmament-boss-malformed:{name}:unclosed"); continue; }
- var profileMatch = SemanticProfile.Match(body); var support = SemanticSupport.Match(body); var heightMatch = BossHeight.Match(body);
- if (!profileMatch.Success || !support.Success || !heightMatch.Success) { diagnostics.Add($"firmament-boss-missing-required-field:{name}:required=On,Profile,Height"); continue; }
- var profileName = profileMatch.Groups["profile"].Value; var face = support.Groups["face"].Value; var height = N(heightMatch, "value");
+ var name = declaration.Name?.Text ?? "";
+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);
+ var profileName = fields.Word("Profile"); var face = fields.Word("On"); var height = fields.Number("Height", "mm");
+ fields.Complete();
+ if (profileName is null || face is null || !double.IsFinite(height)) { diagnostics.Add($"firmament-boss-missing-required-field:{name}:required=On,Profile,Height"); continue; }
if (!names.Add(name)) { diagnostics.Add($"compose-duplicate-operation:{name}"); continue; }
if (!profiles.TryGetValue(profileName, out var bossProfile)) { diagnostics.Add($"firmament-boss-invalid-profile:{name}:profile={profileName}"); continue; }
if (!double.IsFinite(height) || height <= 0d) { diagnostics.Add($"firmament-boss-height-must-be-positive:{name}:height={height:R}mm"); continue; }
@@ -357,23 +378,24 @@ public static class PrismaticProfileCompositionParser
: ResolveTopSupports(face, stock, operations, bossProfile, profiles)
: ResolveSpanTopSupports(supportSpan, operations, bossProfile, profiles);
if (candidates.Count == 0) { diagnostics.Add(face.EndsWith(".Top", StringComparison.Ordinal)
- ? $"feature-support-not-found:{name}:{face}:host={compose.Groups["n"].Value}:profile={profileName}"
- : $"firmament-boss-disconnected-from-host:{name}:host={compose.Groups["n"].Value}:profile={profileName}:support=Top"); continue; }
+ ? $"feature-support-not-found:{name}:{face}:host={compose.Name.Text}:profile={profileName}"
+ : $"firmament-boss-disconnected-from-host:{name}:host={compose.Name.Text}:profile={profileName}:support=Top"); continue; }
if (candidates.Count > 1) { diagnostics.Add($"feature-support-ambiguous:Top:feature={name}:candidates={string.Join(",", candidates.Select(x => x.Name).Order(StringComparer.Ordinal))}"); continue; }
var selectedSupport = candidates[0];
- var stableId = $"boss:{compose.Groups["n"].Value}.{name}"; var sourceSpan = $"offset:{header.Index}";
- bosses.Add(new(name, stableId, compose.Groups["n"].Value, face, profileName, height, selectedSupport.To, selectedSupport.To + height, sourceSpan, supportSpan?.SpanId, supportSpan?.ParentId));
+ var stableId = $"boss:{compose.Name.Text}.{name}"; var sourceSpan = $"offset:{declaration.Span.Start}";
+ bosses.Add(new(name, stableId, compose.Name.Text, face, profileName, height, selectedSupport.To, selectedSupport.To + height, sourceSpan, supportSpan?.SpanId, supportSpan?.ParentId));
operations.Add(new(name, PrismaticProfileIntent.Add, profileName, selectedSupport.To, selectedSupport.To + height, "Boss", sourceSpan, stableId, "Boss"));
}
- foreach (Match header in PocketHeader.Matches(composeBody))
+ foreach (var declaration in operationsSyntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Pocket"))
{
- var name = header.Groups["n"].Value;
- var body = Block(composeBody, header.Index + header.Length - 1);
- if (body is null) { diagnostics.Add($"firmament-pocket-malformed:{name}:unclosed"); continue; }
- var profileMatch = SemanticProfile.Match(body); var support = SemanticSupport.Match(body); var depthMatch = PocketDepth.Match(body);
- if (!profileMatch.Success || !support.Success || !depthMatch.Success) { diagnostics.Add($"firmament-pocket-missing-required-field:{name}:required=On,Profile,Depth"); continue; }
- var profileName = profileMatch.Groups["profile"].Value; var face = support.Groups["face"].Value; var depth = N(depthMatch, "value");
+ var name = declaration.Name?.Text ?? "";
+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);
+ var profileName = fields.Word("Profile"); var face = fields.Word("On"); var depth = fields.Number("Depth", "mm");
+ fields.Take("MinimumFloorThickness");
+ fields.Complete();
+ if (profileName is null || face is null || !double.IsFinite(depth)) { diagnostics.Add($"firmament-pocket-missing-required-field:{name}:required=On,Profile,Depth"); continue; }
+ var body = composeBody.Substring(declaration.Body!.Span.Start + 1, declaration.Body.Span.Length - 2);
if (!names.Add(name)) { diagnostics.Add($"compose-duplicate-operation:{name}"); continue; }
if (!profiles.TryGetValue(profileName, out var pocketProfile)) { diagnostics.Add($"firmament-pocket-invalid-profile:{name}:profile={profileName}"); continue; }
if (!double.IsFinite(depth) || depth <= 0d) { diagnostics.Add($"firmament-pocket-depth-must-be-positive:{name}:depth={depth:R}mm"); continue; }
@@ -396,16 +418,16 @@ public static class PrismaticProfileCompositionParser
}
if (remaining <= 1e-7d)
{
- diagnostics.Add($"firmament-pocket-through-depth:{name}:host={compose.Groups["n"].Value}:depth={depth:R}mm:hostThickness={hostThickness:R}mm:remainingFloor={remaining:R}mm:requiredFloor={minimumFloor:R}mm:Use Remove with Role: ThroughCut for a through cut; Pocket requires a remaining floor.");
+ diagnostics.Add($"firmament-pocket-through-depth:{name}:host={compose.Name.Text}:depth={depth:R}mm:hostThickness={hostThickness:R}mm:remainingFloor={remaining:R}mm:requiredFloor={minimumFloor:R}mm:Use Remove with Role: ThroughCut for a through cut; Pocket requires a remaining floor.");
continue;
}
if (remaining + 1e-7d < minimumFloor)
{
- diagnostics.Add($"firmament-pocket-minimum-floor-thickness:{name}:host={compose.Groups["n"].Value}:depth={depth:R}mm:hostThickness={hostThickness:R}mm:remainingFloor={remaining:R}mm:requiredFloor={minimumFloor:R}mm:policy={policySource}");
+ diagnostics.Add($"firmament-pocket-minimum-floor-thickness:{name}:host={compose.Name.Text}:depth={depth:R}mm:hostThickness={hostThickness:R}mm:remainingFloor={remaining:R}mm:requiredFloor={minimumFloor:R}mm:policy={policySource}");
continue;
}
- var stableId = $"pocket:{compose.Groups["n"].Value}.{name}"; var sourceSpan = $"offset:{header.Index}";
- pockets.Add(new(name, stableId, compose.Groups["n"].Value, face, profileName, depth, hostThickness, remaining, minimumFloor, policySource, selectedSupport.To - depth, selectedSupport.To, sourceSpan, supportSpan?.SpanId, supportSpan?.ParentId));
+ var stableId = $"pocket:{compose.Name.Text}.{name}"; var sourceSpan = $"offset:{declaration.Span.Start}";
+ pockets.Add(new(name, stableId, compose.Name.Text, face, profileName, depth, hostThickness, remaining, minimumFloor, policySource, selectedSupport.To - depth, selectedSupport.To, sourceSpan, supportSpan?.SpanId, supportSpan?.ParentId));
operations.Add(new(name, PrismaticProfileIntent.Remove, profileName, selectedSupport.To - depth, selectedSupport.To, "Pocket", sourceSpan, stableId, "Pocket"));
}
@@ -433,8 +455,8 @@ public static class PrismaticProfileCompositionParser
var profileName = profileMatch.Groups["profile"].Value;
var support = supportMatch.Groups["face"].Value;
var direction = directionMatch.Success ? directionMatch.Groups["value"].Value : "+Z";
- if (!string.Equals(target, compose.Groups["n"].Value, StringComparison.Ordinal))
- { diagnostics.Add($"offset-target-not-found:{name}:target={target}:active={compose.Groups["n"].Value}"); continue; }
+ if (!string.Equals(target, compose.Name.Text, StringComparison.Ordinal))
+ { diagnostics.Add($"offset-target-not-found:{name}:target={target}:active={compose.Name.Text}"); continue; }
if (!string.Equals(direction, "+Z", StringComparison.Ordinal))
{ diagnostics.Add($"offset-axis-invalid:{name}:axis={direction}:qualified=+Z-prismatic-compose"); continue; }
if (!names.Add(name)) { diagnostics.Add($"compose-duplicate-operation:{name}"); continue; }
@@ -522,7 +544,7 @@ public static class PrismaticProfileCompositionParser
}
var bounds = ProfileBounds(offsetProfile);
- var stableId = $"offset:{compose.Groups["n"].Value}.{name}";
+ var stableId = $"offset:{compose.Name.Text}.{name}";
var sourceSpan = $"offset:{header.Index}";
materialOffsets.Add(new(name, stableId, intent, "Prism", target, support, profileName, direction,
termination, from, to, extent, sourceSpan,
@@ -537,20 +559,23 @@ public static class PrismaticProfileCompositionParser
var roundedRectangleSlots = new List<PrismaticRoundedRectangleSlotFeature>();
var materialFrom = operations.Count == 0 ? 0d : operations.Min(x => x.From);
var materialTo = operations.Count == 0 ? 0d : operations.Max(x => x.To);
- foreach (Match header in HoleHeader.Matches(composeBody))
+ foreach (var declaration in operationsSyntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Hole"))
{
- var name = header.Groups["n"].Value;
- var body = Block(composeBody, header.Index + header.Length - 1);
+ var name = declaration.Name?.Text ?? "";
+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);
+ var body = declaration.Body is null ? null : composeBody.Substring(declaration.Body.Span.Start + 1, declaration.Body.Span.Length - 2);
if (body is null) { diagnostics.Add($"compose-hole-unclosed:{name}"); continue; }
+ fields.Take("PatternIdentity");
var patternIdentityMatch = Regex.Match(body, @"\bPatternIdentity\s*:\s*(?<id>[A-Za-z_]\w*\.[A-Za-z_]\w*)", RegexOptions.CultureInvariant);
var diagnosticName = patternIdentityMatch.Success ? patternIdentityMatch.Groups["id"].Value : name;
- var center = HoleCenter.Match(body); if (!center.Success) center = HolePoint2Center.Match(body);
- var diameter = HoleDiameter.Match(body); var end = HoleEnd.Match(body); var role = HoleRole.Match(body);
- var counterboreDiameter = HoleCounterboreDiameter.Match(body); var counterboreDepth = HoleCounterboreDepth.Match(body); var on = HoleOn.Match(body);
- var from = HoleFrom.Match(body); var depthEnd = HoleDepthEnd.Match(body); var termination = HoleTermination.Match(body);
+ var center = ReadFeatureField(fields, composeBody, HoleCenter, "Center"); if (!center.Success) center = ReadFeatureField(fields, composeBody, HolePoint2Center, "Center");
+ var diameter = ReadFeatureField(fields, composeBody, HoleDiameter, "Diameter"); var end = ReadFeatureField(fields, composeBody, HoleEnd, "End"); var role = ReadFeatureField(fields, composeBody, HoleRole, "Role");
+ var counterboreDiameter = ReadFeatureField(fields, composeBody, HoleCounterboreDiameter, "CounterboreDiameter"); var counterboreDepth = ReadFeatureField(fields, composeBody, HoleCounterboreDepth, "CounterboreDepth"); var on = ReadFeatureField(fields, composeBody, HoleOn, "On");
+ var from = ReadFeatureField(fields, composeBody, HoleFrom, "From"); var depthEnd = ReadFeatureField(fields, composeBody, HoleDepthEnd, "End"); var termination = ReadFeatureField(fields, composeBody, HoleTermination, "Termination");
+ fields.Complete();
if (from.Success)
{
- if (!string.Equals(header.Groups["variant"].Value, "Shaft", StringComparison.OrdinalIgnoreCase)
+ if (!string.Equals((FirmamentSyntaxValues.Reference(declaration.Type.Arguments.FirstOrDefault()?.Value) ?? ""), "Shaft", StringComparison.OrdinalIgnoreCase)
|| !depthEnd.Success || !termination.Success)
{ diagnostics.Add($"compose-construction-plane-blind-hole-invalid-contract:{name}"); continue; }
if (!center.Success || !diameter.Success) { diagnostics.Add($"compose-construction-plane-blind-hole-missing-center-or-diameter:{name}"); continue; }
@@ -558,20 +583,20 @@ public static class PrismaticProfileCompositionParser
string? planeDiagnostic = null; string? frameDiagnostic = null;
if (trace is null || !ConceptIrResolver.TryResolvePlane(source, trace, out var conceptPlane, out planeDiagnostic)
|| conceptPlane is null
- || !ConstructionPlane.TryTrace($"construction:{from.Groups["plane"].Value}", conceptPlane, $"offset:{header.Index}", out var plane, out frameDiagnostic))
+ || !ConstructionPlane.TryTrace($"construction:{from.Groups["plane"].Value}", conceptPlane, $"offset:{declaration.Span.Start}", out var plane, out frameDiagnostic))
{ diagnostics.Add(planeDiagnostic ?? frameDiagnostic ?? $"compose-construction-plane-not-found:{from.Groups["plane"].Value}"); continue; }
var localX = N(center, "x"); var localY = N(center, "y"); var localDiameter = N(diameter, "d"); var declaredDepth = N(depthEnd, "depth");
var angle = termination.Groups["angle"].Success ? N(termination, "angle") : 118d;
if (!double.IsFinite(localX) || !double.IsFinite(localY) || !double.IsFinite(localDiameter) || localDiameter <= 0d || !double.IsFinite(declaredDepth) || declaredDepth < 0d || !double.IsFinite(angle) || angle <= 0d || angle >= 180d)
{ diagnostics.Add($"compose-construction-plane-blind-hole-invalid-geometry:{name}"); continue; }
if (!names.Add(name)) { diagnostics.Add($"compose-duplicate-operation:{name}"); continue; }
- var blindStableId = $"hole:{compose.Groups["n"].Value}.{name}";
+ var blindStableId = $"hole:{compose.Name.Text}.{name}";
constructionPlaneBlindDrills.Add(new(name, blindStableId, plane!.StableId, plane.SourceConceptId, plane.Origin, plane.AxisX, plane.AxisY, plane.AxisZ,
localX, localY, localDiameter, declaredDepth, string.Equals(depthEnd.Groups["kind"].Value, "TotalDepth", StringComparison.OrdinalIgnoreCase), angle,
- role.Success ? role.Groups["role"].Value : "BlindDrillPoint", $"offset:{header.Index}", plane.Provenance));
+ role.Success ? role.Groups["role"].Value : "BlindDrillPoint", $"offset:{declaration.Span.Start}", plane.Provenance));
continue;
}
- var variant = header.Groups["variant"].Value;
+ var variant = (FirmamentSyntaxValues.Reference(declaration.Type.Arguments.FirstOrDefault()?.Value) ?? "");
if (string.Equals(variant, "Counterbore", StringComparison.OrdinalIgnoreCase))
{
if (!end.Success || !string.Equals(end.Groups["end"].Value, "ThroughAll", StringComparison.OrdinalIgnoreCase))
@@ -589,7 +614,7 @@ public static class PrismaticProfileCompositionParser
if (boreDepth > hostDepth + 1e-8d)
{ diagnostics.Add($"ComposeCounterboreDepthExceedsHost:{name}:depth={boreDepth:R}:hostDepth={hostDepth:R}"); continue; }
if (!names.Add(name)) { diagnostics.Add($"compose-duplicate-operation:{name}"); continue; }
- var counterboreStableId = $"hole:{compose.Groups["n"].Value}.{name}";
+ var counterboreStableId = $"hole:{compose.Name.Text}.{name}";
if (!CircleContainedInBaseProfile(operations, profiles, counterboreX, counterboreY, boreDiameter / 2d))
{ diagnostics.Add($"ComposeCounterboreFootprintLeavesProfileMaterial:{name}:radius={boreDiameter / 2d:R}"); continue; }
double? supportMargin = null;
@@ -607,9 +632,9 @@ public static class PrismaticProfileCompositionParser
{ diagnostics.Add($"ComposeCounterboreIntersectsExistingCavity:{name}"); continue; }
var shaftProfile = $"{name}ShaftProfile"; var boreProfile = $"{name}CounterboreProfile";
if (profiles.ContainsKey(shaftProfile) || profiles.ContainsKey(boreProfile)) { diagnostics.Add($"compose-hole-profile-name-collision:{name}"); continue; }
- profiles.Add(shaftProfile, CircleProfile(shaftProfile, counterboreX, counterboreY, shaftDiameter / 2d, counterboreStableId, $"offset:{header.Index}"));
- profiles.Add(boreProfile, CircleProfile(boreProfile, counterboreX, counterboreY, boreDiameter / 2d, counterboreStableId, $"offset:{header.Index}"));
- var counterboreSourceSpan = $"offset:{header.Index}"; var counterboreSemanticRole = role.Success ? role.Groups["role"].Value : "CounterboreHole";
+ profiles.Add(shaftProfile, CircleProfile(shaftProfile, counterboreX, counterboreY, shaftDiameter / 2d, counterboreStableId, $"offset:{declaration.Span.Start}"));
+ profiles.Add(boreProfile, CircleProfile(boreProfile, counterboreX, counterboreY, boreDiameter / 2d, counterboreStableId, $"offset:{declaration.Span.Start}"));
+ var counterboreSourceSpan = $"offset:{declaration.Span.Start}"; var counterboreSemanticRole = role.Success ? role.Groups["role"].Value : "CounterboreHole";
counterboreHoles.Add(new(name, counterboreStableId, shaftProfile, boreProfile, counterboreX, counterboreY, shaftDiameter, boreDiameter, boreDepth, materialFrom, materialTo, counterboreSemanticRole, counterboreSourceSpan, supportSpan?.SpanId, supportSpan?.ParentId, supportMargin));
operations.Add(new($"{name}Shaft", PrismaticProfileIntent.Remove, shaftProfile, materialFrom, materialTo, counterboreSemanticRole, counterboreSourceSpan, counterboreStableId, "Hole<Counterbore>", shaftDiameter));
operations.Add(new($"{name}Counterbore", PrismaticProfileIntent.Remove, boreProfile, materialTo - boreDepth, materialTo, counterboreSemanticRole, counterboreSourceSpan, counterboreStableId, "Hole<Counterbore>", boreDiameter));
@@ -624,7 +649,7 @@ public static class PrismaticProfileCompositionParser
if (!names.Add(name)) { diagnostics.Add($"compose-duplicate-operation:{name}"); continue; }
var profileName = $"{name}ShaftProfile";
if (profiles.ContainsKey(profileName)) { diagnostics.Add($"compose-hole-profile-name-collision:{name}:{profileName}"); continue; }
- var stableId = $"hole:{compose.Groups["n"].Value}.{name}";
+ var stableId = $"hole:{compose.Name.Text}.{name}";
GeometricSpanView? shaftSupport = null; double? shaftSupportMargin = null;
if (on.Success && !string.Equals(on.Groups["face"].Value, "+Z", StringComparison.OrdinalIgnoreCase))
{
@@ -638,13 +663,13 @@ public static class PrismaticProfileCompositionParser
{ diagnostics.Add($"firmament-feature-footprint-outside-span:{diagnosticName}:{shaftSupport.SpanId}:center=[{x:R},{y:R}]:radius={d / 2d:R}:margin={margin:R}"); continue; }
shaftSupportMargin = margin;
}
- var holeProfile = CircleProfile(profileName, x, y, d / 2d, stableId, $"offset:{header.Index}");
+ var holeProfile = CircleProfile(profileName, x, y, d / 2d, stableId, $"offset:{declaration.Span.Start}");
var validation = ResolvedProfile2DValidator.Validate(holeProfile);
diagnostics.AddRange(validation.Diagnostics);
if (!validation.IsValid) continue;
profiles.Add(profileName, holeProfile);
var semanticRole = role.Success ? role.Groups["role"].Value : "ShaftHole";
- var sourceSpan = $"offset:{header.Index}";
+ var sourceSpan = $"offset:{declaration.Span.Start}";
shaftHoles.Add(new(name, stableId, profileName, x, y, d, materialFrom, materialTo, semanticRole, sourceSpan, shaftSupport?.SpanId, shaftSupport?.ParentId, shaftSupportMargin));
operations.Add(new(name, PrismaticProfileIntent.Remove, profileName, materialFrom, materialTo, semanticRole, sourceSpan, stableId, "Hole<Shaft>", d));
}
@@ -656,12 +681,15 @@ public static class PrismaticProfileCompositionParser
foreach (var counterbore in counterboreHoles)
if (CirclesTouchOrOverlap(shaft.CenterX, shaft.CenterY, shaft.Diameter / 2d, counterbore.CenterX, counterbore.CenterY, counterbore.CounterboreDiameter / 2d))
diagnostics.Add($"ComposeCounterboreIntersectsExistingCavity:{counterbore.Name}:shaft={shaft.Name}");
- foreach (Match header in SlotHeader.Matches(composeBody))
+ foreach (var declaration in operationsSyntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Slot"))
{
- var name = header.Groups["n"].Value; var body = Block(composeBody, header.Index + header.Length - 1);
+ var name = declaration.Name?.Text ?? "";
+ var fields = new FirmamentSyntaxFields(declaration, diagnostics); var body = declaration.Body is null ? null : composeBody.Substring(declaration.Body.Span.Start + 1, declaration.Body.Span.Length - 2);
if (body is null) { diagnostics.Add($"SlotProfileDegenerate:{name}:unclosed"); continue; }
- var center = SlotCenter.Match(body); var direction = SlotDirection.Match(body); var length = SlotLength.Match(body); var width = SlotWidth.Match(body); var extent = SlotExtent.Match(body); var role = HoleRole.Match(body);
- var variant=header.Groups["variant"].Value;
+ var center = ReadFeatureField(fields, composeBody, SlotCenter, "Center"); var direction = ReadFeatureField(fields, composeBody, SlotDirection, "Direction"); var length = ReadFeatureField(fields, composeBody, SlotLength, "Length"); var width = ReadFeatureField(fields, composeBody, SlotWidth, "Width"); var extent = ReadFeatureField(fields, composeBody, SlotExtent, "Extent"); var role = ReadFeatureField(fields, composeBody, HoleRole, "Role");
+ var corner = ReadFeatureField(fields, composeBody, SlotCornerRadius, "CornerRadius");
+ fields.Complete();
+ var variant=(FirmamentSyntaxValues.Reference(declaration.Type.Arguments.FirstOrDefault()?.Value) ?? "");
if (!string.Equals(variant,"Capsule",StringComparison.OrdinalIgnoreCase) && !string.Equals(variant,"RoundedRectangle",StringComparison.OrdinalIgnoreCase)) { diagnostics.Add($"UnsupportedSlotHostTopology:{name}:supported variants are Capsule and RoundedRectangle"); continue; }
if (!center.Success || !direction.Success || !length.Success || !width.Success || !extent.Success) { diagnostics.Add($"SlotProfileDegenerate:{name}:missing Center, Direction, Length, Width, or Extent"); continue; }
var x=N(center,"x"); var y=N(center,"y"); var dx=N(direction,"x"); var dy=N(direction,"y"); var l=N(length,"v"); var w=N(width,"v");
@@ -673,7 +701,7 @@ public static class PrismaticProfileCompositionParser
if (!names.Add(name)) { diagnostics.Add($"compose-duplicate-operation:{name}"); continue; }
var from=materialFrom; var to=materialTo; var extentText=extent.Groups["v"].Value;
if (!string.Equals(extentText, "ThroughAll", StringComparison.OrdinalIgnoreCase)) { from=N(extent,"from"); to=N(extent,"to"); if (from >= to) { diagnostics.Add($"SlotExtentInvalid:{name}:entry={from:R}:exit={to:R}"); continue; } if (to <= materialFrom || from >= materialTo) { diagnostics.Add($"SlotDoesNotIntersectMaterial:{name}:host=[{materialFrom:R},{materialTo:R}]"); continue; } from=Math.Max(from,materialFrom); to=Math.Min(to,materialTo); }
- dx/=norm; dy/=norm; var stableId=$"slot:{compose.Groups["n"].Value}.{name}"; var sourceSpan=$"offset:{header.Index}"; var semanticRole=role.Success ? role.Groups["role"].Value : $"{variant}Slot";
+ dx/=norm; dy/=norm; var stableId=$"slot:{compose.Name.Text}.{name}"; var sourceSpan=$"offset:{declaration.Span.Start}"; var semanticRole=role.Success ? role.Groups["role"].Value : $"{variant}Slot";
if (string.Equals(variant,"Capsule",StringComparison.OrdinalIgnoreCase))
{
var profileName=$"{name}CapsuleProfile"; var profile=CapsuleProfile(profileName,x,y,dx,dy,l,w,stableId,sourceSpan); var validation=ResolvedProfile2DValidator.Validate(profile); diagnostics.AddRange(validation.Diagnostics); if (!validation.IsValid) { diagnostics.Add($"SlotProfileDegenerate:{name}"); continue; }
@@ -681,17 +709,34 @@ public static class PrismaticProfileCompositionParser
}
else
{
- var corner=SlotCornerRadius.Match(body); if (!corner.Success) { diagnostics.Add($"SlotProfileDegenerate:{name}:RoundedRectangle requires CornerRadius"); continue; }
+ if (!corner.Success) { diagnostics.Add($"SlotProfileDegenerate:{name}:RoundedRectangle requires CornerRadius"); continue; }
var r=N(corner,"v"); if (!double.IsFinite(r) || r <= 0 || 2*r > Math.Min(l,w)) { diagnostics.Add($"SlotProfileDegenerate:{name}:CornerRadius={r:R} must be positive and no greater than min(Length,Width)/2"); continue; }
var profileName=$"{name}RoundedRectangleProfile"; var profile=RoundedRectangleProfile(profileName,x,y,dx,dy,l,w,r,stableId,sourceSpan); var validation=ResolvedProfile2DValidator.Validate(profile); diagnostics.AddRange(validation.Diagnostics); if (!validation.IsValid) { diagnostics.Add($"SlotProfileDegenerate:{name}"); continue; }
profiles.Add(profileName,profile); roundedRectangleSlots.Add(new(name,stableId,profileName,x,y,dx,dy,l,w,r,from,to,extentText,semanticRole,sourceSpan)); operations.Add(new(name,PrismaticProfileIntent.Remove,profileName,from,to,semanticRole,sourceSpan,stableId,"Slot<RoundedRectangle>"));
}
}
var levels = operations.SelectMany(o => new[] { o.From, o.To }).Distinct().Order().ToArray();
- var feature = diagnostics.Count == 0 ? new PrismaticProfileCompositionFeature(compose.Groups["n"].Value, placement.ProfilePlane, placement.Axis, placement, operations, levels, "parser-backed-scaffold-profile-composition", shaftHoles, capsuleSlots, roundedRectangleSlots, constructionPlaneBlindDrills, counterboreHoles, bosses, pockets, materialOffsets) : null;
+ var feature = diagnostics.Count == 0 ? new PrismaticProfileCompositionFeature(compose.Name.Text, placement.ProfilePlane, placement.Axis, placement, operations, levels, "parser-backed-scaffold-profile-composition", shaftHoles, capsuleSlots, roundedRectangleSlots, constructionPlaneBlindDrills, counterboreHoles, bosses, pockets, materialOffsets) : null;
return new(feature, profiles, diagnostics.Distinct().ToArray(), expansion.Evidence);
}
+ // Transitional engineering value readers operate on one AST field, never on
+ // arbitrary surrounding source. Field consumption and statement boundaries are
+ // owned by the recursive-descent frontend; existing domain checks stay here.
+ private static Match ReadFeatureField(FirmamentSyntaxFields fields, string source, Regex reader, string name)
+ {
+ var nodes = fields.TakeAll(name);
+ if (nodes.Count == 0) return Match.Empty;
+ if (nodes.Count > 1) return Match.Empty; // duplicate is rejected by the owner below
+ var fieldSource = source.Substring(nodes[0].Span.Start, nodes[0].Span.Length);
+ var match = reader.Match(fieldSource);
+ // An engineering value reader must consume the entire AST field. A
+ // recognized prefix cannot discard an operator, placement or suffix.
+ if (match.Success && (match.Index != 0 || !string.IsNullOrWhiteSpace(fieldSource[(match.Index + match.Length)..]))) match = Match.Empty;
+ if (!match.Success && name is not ("Center" or "End")) fields.Invalid(name);
+ return match;
+ }
+
private static bool IsTopSelector(string selector) => selector is "Top" or "+Z" || selector.EndsWith(".Top", StringComparison.Ordinal);
private static IReadOnlyList<PrismaticProfileOperation> ResolveSpanTopSupports(
diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
index a60a4be5..355b3e09 100644
--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
@@ -3,18 +3,18 @@
Source: [Claude's original authoring audit](firmament-authoring-pass-2026-10.md).
This register preserves its 24 recommendations and their rationale. A future
milestone assignment is a disposition, not an implemented feature. X0 remains
-partially qualified; see [the release report](../release/FIRMAMENT-FRONTEND-X0.md).
+partially qualified across the whole language; the [production mechanical migration](../release/FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.md) closes the named mechanical admission defects. Historical X0/X1 classifications below remain evidence of their original observations.
| # | Original recommendation and rationale | Disposition | Decision / remaining boundary |
| --- | --- | --- | --- |
| 1 | Validate through parsing, binding and capability admission; F2/F5/F10/F18/F22 contradicted builds | Fixed in X0, bounded | Generic mechanical validation invokes existing CompileSource; static/external-pack analysis is explicitly ParsedNotBuilt. Specialized domains and source consumption remain unqualified. |
-| 2 | Every V2 error stops compilation; no fatal-code allowlist or accidental V1 fallback | Fixed in X0 for fallback; X1 unified parser for profile admission | Shared severity adapter defaults legacy diagnostic strings to errors; explicit traces/information and the existing tolerance warning remain nonfatal. The attempted universal gate exposed legitimate junction/derived-profile admission missing from the generic parser and was backed out; this remains an explicit gap. Serialization-shaped roots remain with the legacy reader even when data values are V2 keywords; that reader must prove explicit version 1. |
-| 3 | Unknown statements/fields must error; never silently omit Fillet | X1 unified parser, partially fixed in X0 | Canonical root/Modify block checks use lexer boundaries; Box fields reuse generated metadata. Advanced Compose and erased boundary fields still need consumption receipts. |
+| 2 | Every V2 error stops compilation; no fatal-code allowlist or accidental V1 fallback | Fixed in X0 for fallback; X1 unified parser for profile admission | Shared severity adapter defaults legacy diagnostic strings to errors; explicit traces/information and the existing tolerance warning remain nonfatal. The earlier universal gate exposed legitimate junction/derived-profile admission missing from the generic parser. Production mechanical AST binding now admits those existing selectors and gates Profile/Compose execution; dedicated non-mechanical domain migration remains separate. Serialization-shaped roots remain with the legacy reader even when data values are V2 keywords; that reader must prove explicit version 1. |
+| 3 | Unknown statements/fields must error; never silently omit Fillet | Fixed for named production mechanical cases; remaining X1/X2 | Canonical root/Modify block checks use lexer boundaries; Box fields reuse generated metadata. The production mechanical migration now rejects the Compose Fillet and erased Rect2 field witnesses through AST-owned consumption. Other domain owners still require migration. |
| 4 | Every error has a sentence, span and consistent JSON; preserve SemanticSourceNotFound text | X1 unified parser, partially fixed in X0 | Generic build/report share an object shape and original token spans where identifiable. Enclosing locations disclose lost provenance. Legacy/domain producers still need typed located diagnostics. |
| 5 | Reject ignored frames such as On XZ | Fixed in X0, bounded | Profile layout frame resolution rejects unsupported XZ and unresolved Using frames. Asymmetric bounds witness retained. This does not qualify every attachment/frame owner. |
| 6 | Correct Model summary and suggest through-cut vocabulary for Pocket | Fixed in X0 | Document owner is projected from existing semantic parse metadata; Pocket through-depth error suggests Remove with Role: ThroughCut. |
-| 7 | Parse once into an AST over Lex, migrate construct families in shadow mode | X1 unified parser | Route metadata now comes from actual branch selection. No AST or new route architecture added. |
-| 8 | Replace text rewrites with AST transforms; lexical Pattern substitution leaks scope | X1 unified parser | First retain consumed spans and expansion origin receipts; then migrate transforms in shadow mode. |
+| 7 | Parse once into an AST over Lex, migrate construct families in shadow mode | Production mechanical migration; remaining X1 unified parser | The shared recursive-descent AST over the existing lexer is now used by production mechanical admission. Existing engineering lowerers are retained. Other domain syntax coverage and complete AST expansion remain tracked work, not a shadow-only prerequisite for this mechanical repair. |
+| 8 | Replace text rewrites with AST transforms; lexical Pattern substitution leaks scope | X1 structure; X2 semantic consolidation | Original Template/Feature/Pattern bodies are now structured in shadow mode. Production rewrites, expansion origin receipts and scoped AST transforms remain unimplemented; they require X2 binding. |
| 9 | One expression evaluator in every value position | X2 semantic consolidation | Do not expand arithmetic admission during X0. Existing owner-specific evaluators remain. |
| 10 | One point literal: arrays and typed Point2 constructor mean the same thing | X3 syntax reconciliation | Preserve existing route-dependent aliases; do not broaden syntax by accidental regex acceptance. |
| 11 | One generic variant mechanism; EdgeFinish<Chamfer/Fillet>, retaining Kind alias | X3 syntax reconciliation | Generic EdgeFinish is not implemented. Its failed build is now rejected by normal validation. |
@@ -28,11 +28,55 @@ partially qualified; see [the release report](../release/FIRMAMENT-FRONTEND-X0.m
| 19 | Scope-local named values with arithmetic | X2 semantic consolidation | General Let remains a non-goal for X0; decide syntax only after binding ownership is unified. |
| 20 | Inline vertex lists for polygon/revolve outlines | X3 syntax reconciliation | No new polygon/revolve grammar during X0. Existing named-point diagnostics retained. |
| 21 | Uniform planar-face references (+Z, face(+Z), Body.Top, Top) | X2 semantic consolidation | Typed target binding must precede alias expansion; current owner-specific constraints remain explicit. |
-| 22 | Explain route, expansion and bound Pattern instances | Fixed in X0, bounded; X1 unified parser for full expansion | --explain prints actual selected route, admission level and readily available template/solid counts. Complete expanded-source/source-map explanation deferred. |
-| 23 | Generate a grammar reference from the AST | X1 unified parser | Existing opt-in semantic field metadata is not a complete grammar; do not present it as one. |
+| 22 | Explain route, expansion and bound Pattern instances | Fixed in X0, bounded; X1 shadow evidence | --shadow --explain separates original structural status/summary, actual generic production route and normal production validation. --ast exposes original bodies/trivia. Bound expansion explanation remains X2; no invented expansion provenance. |
+| 23 | Generate a grammar reference from the AST | X1 unified parser, deferred pending coverage | A compact AST now exists, but remaining Interface/domain syntax gaps and absent binding mean it cannot yet generate the authoritative complete grammar. Existing field metadata remains intentionally incomplete. |
| 24 | Fillet+Hole, box shell/hollow, non-XY Compose capability gaps | Separate geometry/kernel feature | Improve rejection and preserve existing admitted frame mechanisms. No new kernel feature or general plane capability added. |
The September [profile-pipeline audit](firmament-v2-language-audit.md) and earlier
[reconciliation register](firmament-language-inconsistencies.md) are historical
evidence, not proof that October's route-dependent behavior is resolved. Their
previous resolved classifications must be read with this qualification.
+
+## X1 differential decisions (2026-10-14)
+
+See the [X1 qualification](../release/FIRMAMENT-FRONTEND-X1.md). Categories A-E
+classify observed differences, not automatic permission to change production.
+Machine reports deliberately retain `Unclassified` where source receipts cannot
+justify a stronger conclusion. This table records the **historical shadow-only foundation** before production
+mechanical migration. Current outcomes for the named defects are below. Recommendations not amended above retain their
+original X0 dispositions, including all syntax design and kernel deferrals.
+
+| Audit finding / recommendation | Old behavior | Shadow interpretation / category | Authority and next decision |
+| --- | --- | --- | --- |
+| F3 / #3 unknown Compose Fillet | Builds while Compose AIR has no LostIntent operation | AST retains Fillet LostIntent and exact span; receipt comparison flags the omission. **B: existing parser defect** for this witness. | Production remains authoritative but defective here. Complete Compose operation admission over AST before migration; X2 capability ownership must reject unsupported Fillet. |
+| F3 / #3 erased boundary field | Rect2 RecessGuide builds with heigth discarded | Original field/value/span survive in AST. Field-consumption comparison is explicitly unqualified. **B: existing parser defect** for the witness. | Reuse boundary owner's field schema/consumption receipts in an AST adapter; do not add another field vocabulary. Not fixed by structural acceptance. |
+| F10 / #1/#2 profile admission | ReflexNotch generic parsing rejects; actual build succeeds | AST retains .[Inner, Upright] as member-set syntax. **B: generic admission defect**. | Existing profile lowerer remains geometry authority; migration requires its actual selectors and admission semantics, not generic-parser success. |
+| F6/F16/F20 / #7/#14 | Unrelated declarations can affect whole-document production route | Box/Hole/Modify/EdgeFinish subtrees remain identical with Static, Slot2, Pattern, Profile siblings and admitted structural wrappers. The SlotRoutePerturbation witness builds without the unused Slot2, then rejects on CanonicalAdvanced when it is added. **B** route dependence; structural invariance is proved, semantic invariance is not. | No new root rule. Production root admission remains X2/X3 work; do not infer semantic parity from AST identity. |
+| F15/F17 / #8/#12 | Pattern/Template bodies are rewritten as text | Keyed mappings, typed arguments, generic invocations and occurrence bodies are structured. **B** scope/provenance gaps remain in production expansion. | No text expansion replacement in X1; X2 owns scoped binding and expansion receipts. Pattern syntax reconciliation stays X3. |
+| F4/F23 / #10/#17 | Owner-specific case and point aliases | AST preserves authored spelling and distinct array/constructor forms. **D: compatibility aliases**, only where existing owners admit them. | No global normalizer or equivalence assertion. Binding normalization in X2; language reconciliation X3. |
+| #7 Interface/domain coverage | Role requires, Mate relations and imported #face selectors have existing owners | These forms currently receive located shadow syntax errors. **A: missing new-parser coverage** for admitted fixtures. | Complete these structural forms before claiming X1 Accepted; do not weaken the production owners. |
+| #7/#16 specialized shorthand | Blind 10mm, CenteredAt 50mm and some Extend forms remain domain syntax | Shadow rejects these forms rather than consuming opaque header text. **A: missing coverage**. | Add bounded typed syntax and source tests within X1 follow-up; preserve lowerers. |
+| #7 Sculpting +Model sources | Canonical fixtures contain leading plus characters | Shadow reports the actual plus token. **C: language ambiguity** pending owning frontend audit. | Do not strip punctuation globally or silently bless an accidental source spelling. |
+| #9/#19 expressions | Existing evaluators admit different value positions | Structural precedence/member/index/call syntax is represented; values remain unbound. **C** where grammar/generic-spacing is ambiguous. | No evaluator replacement. X2 owns dimension/type/name checks; X3 owns grammar reconciliation. |
+| #22 explanation | Production route and limited counts only | Separate shadow/production results plus explicit coverage limits are available. | Expanded/generated spans and bound instances remain unavailable when old rewrites lose provenance; X2 prerequisite. |
+| #23 generated grammar | No complete unified grammar | AST is a partial structural contract, not complete language authority. | Generate a reference only after all admitted source forms and context admission have qualified. |
+
+
+## Production mechanical dispositions (2026-10-14)
+
+The user authorized direct production migration instead of another shadow-only
+milestone. The earlier findings and rationale above are preserved, not rewritten
+as if they had never existed. Current mechanical outcomes supersede the old
+production-status statements:
+
+| Recommendations | Current disposition | Evidence / remaining ownership |
+| --- | --- | --- |
+| #1, #2 | Fixed for the migrated mechanical path | Shared AST admission, retained bound engineering inputs and authoritative build gate; member-set profile witness agrees in validate/build. Dedicated domain owners remain outside this cutover. |
+| #3 | Named mechanical P0 cases fixed | Compose Fillet rejects; erased Rect2 heigth rejects; actual AST field readers close their scopes. No universal claim for every old path/derivation/domain adapter. |
+| #4 | Improved in production migration | Syntax messages and original spans survive validate/build; generated-source provenance limitations remain disclosed. |
+| #7, #14 | Production migration, remaining X1/X3 work | Model and material-bearing Struct use UnifiedMechanical. Unused Slot2 no longer changes grammar or STEP. Existing V1 and dedicated material-domain paths remain explicit compatibility boundaries. |
+| #8, #12 | X2/X3 remain | Existing expansion is reused once for mechanical execution; AST expansion and Pattern reconciliation are not implemented. |
+| #9 | Bounded mechanical consolidation; remainder X2 | Profile measure parsing uses AST expressions; no general Let or cross-domain evaluator replacement. |
+| #22 | Production route visibility plus optional evidence tooling | Normal explain reports UnifiedMechanical. Developer AST/comparison tooling is retained without controlling engineering admission. |
+| #23 | Remaining X1 coverage prerequisite | The production mechanical AST does not yet define every other domain's grammar. |
+| #5, #6, #10, #11, #13, #15-#21, #24 | Original dispositions retained | No new frame/kernel capability or global syntax reconciliation is claimed by the mechanical migration. |
diff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.md
index 9a871f9a..f9172c15 100644
--- a/docs/public/reference/cli.md
+++ b/docs/public/reference/cli.md
@@ -4,7 +4,8 @@ Primary public commands:
| Command | Purpose |
|---|---|
-| `validate <file> [--json]` | Parse, bind, check units/targets/static semantics without geometry |
+| `validate <file> [--json]` | Check admission; generic mechanical validation includes in-memory geometry preflight |
+| `frontend-shadow <file> [--json] [--ast] [--validate] [--benchmark]` | Developer-only original-source structural evidence and bounded production comparison |
| `build <file> [--output path] [--json]` | Materialize and export exact STEP AP242 |
| `inspect <firmament-or-step> [--json]` | Inspect source semantics or route STEP to analysis |
| `inspect-3dm <file.3dm> [--json]` | Inventory Rhino/OpenNURBS metadata, units, BRep topology, and unsupported objects |
@@ -22,7 +23,24 @@ Primary public commands:
Generic mechanical `validate` now runs the existing engineering compilation in memory, including selection binding, capability checks and geometry/STEP preflight. It writes no output file. Its report includes `validationLevel` (`Built`, `BuildRejected`, or `ParsedNotBuilt`) and developer-only `parserRoute` metadata. `--explain` prints the route, admission level and available instance counts. `--parse-only` explicitly requests static analysis and reports `parsed-not-built` on success. External `--forge-pack` validation is also labelled `parsed-not-built`: those descriptor providers are not installed into normal build. Domain-specific validators retain their separate scope; inspect their reports. This is not a promise that unchanged source can never encounter a later environment or kernel failure.
-X0 remains partially qualified: the advanced Compose/boundary route still lacks complete statement/field consumption checking. Successful compilation alone does not close that known source-intent gap; see the [X0 qualification report](../../release/FIRMAMENT-FRONTEND-X0.md).
+Mechanical Model and material-bearing Struct documents now use the unified lexer/AST admission path (`UnifiedMechanical`). The ignored Compose Fillet, erased Rect2 field and unused Slot2 route-perturbation cases are repaired. Profile/Compose build execution consumes admitted engineering inputs. Other dedicated domains retain their existing owners; see the [production migration qualification](../../release/FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.md) for its scope and evidence.
+
+`validate file.firmament --shadow --explain --json` opts into the X1 developer
+envelope: `shadow` contains original-source syntax status, AST summary, original
+diagnostics and a bounded comparison against the generic production projection;
+`productionValidation` contains the ordinary validation command's unchanged
+report. `Parsed` means `StructuralOnlyUnbound`, not engineering validity. The
+comparison explicitly reports unqualified declarations and fields. `--ast` adds
+the detailed source tree and trivia only when requested. `frontend-shadow`
+without `--validate` collects syntax/projection evidence without geometry.
+
+`frontend-shadow --corpus fixtures` writes JSON and Markdown under ignored
+`artifacts/local/frontend-x1/corpus` by default. It includes invalid, legacy and
+speculative sources; exit zero means collection completed, while `qualified:
+false` remains explicit. Per-file exit one means structural rejection or, with
+`--validate`, production rejection. Normal mechanical compilation uses the same syntax parser through its production
+AST binder; the developer comparison does not control admission. `--benchmark` measures twenty warm structural parses and current
+thread allocations, excluding file IO, production parsing, comparison and geometry.
Run `aetheris <command> --help` for exact options. JSON is a public automation surface, but its root is command-specific: process exit status is authoritative, `validate` reports `firmamentV2Validation.status`, and materializing/analysis commands report `success` where documented. Diagnostics are structured; artifact paths are explicit; wireframe reports trim/pcurve coverage and a deterministic SVG hash; Sheet Metal reports regions, bends, and lowered features separately; FEA reports requested/result artifacts; sculpting builds report every `BodyState`, `GeometricDelta`, validation evidence, surface-family inventory, and the sibling `.delta.json` path; other builds report emitted features and PMI export evidence. Counts describe semantic items at the stated layer, not arbitrary STEP entity counts.
diff --git a/docs/release/FIRMAMENT-FRONTEND-X1.evidence.json b/docs/release/FIRMAMENT-FRONTEND-X1.evidence.json
new file mode 100644
index 00000000..d4cddf41
--- /dev/null
+++ b/docs/release/FIRMAMENT-FRONTEND-X1.evidence.json
@@ -0,0 +1,333 @@
+{
+ "schemaVersion": 1,
+ "date": "2026-10-14",
+ "verdict": "Meaningful progression",
+ "productionFamiliesMigrated": [],
+ "reproductionCommand": "./scripts/qualify-firmament-frontend-x1.ps1",
+ "inventory": {
+ "extensions": [
+ ".firmament",
+ ".firmfixture",
+ ".firmasm"
+ ],
+ "sources": 1232,
+ "sourceManifestSha256": "276e45a7f0cf6b1b8fb906021d6a4e43dcd28e75117a9336c4acf27146a2d596",
+ "parsed": 741,
+ "rejected": 491,
+ "groups": {
+ "Canonical": {
+ "sources": 323,
+ "parsed": 300,
+ "rejected": 23
+ },
+ "Compatibility": {
+ "sources": 417,
+ "parsed": 42,
+ "rejected": 375
+ },
+ "Other": {
+ "sources": 233,
+ "parsed": 211,
+ "rejected": 22
+ },
+ "Regression": {
+ "sources": 214,
+ "parsed": 164,
+ "rejected": 50
+ },
+ "Speculative": {
+ "sources": 45,
+ "parsed": 24,
+ "rejected": 21
+ }
+ }
+ },
+ "comparison": {
+ "qualified": false,
+ "factsCompared": 465,
+ "differences": 121,
+ "productionAcceptedShadowRejected": 57,
+ "uncomparedDeclarations": 9267,
+ "uncomparedFields": 19102,
+ "scope": "Generic production projection only; complete semantic, field-consumption and domain-admission parity unqualified."
+ },
+ "reproductions": [
+ {
+ "source": "fixtures/Regression/CanonicalGeometry/profile-chamfer-reflex-junction-top.firmament",
+ "structuralStatus": "Parsed",
+ "productionRoute": "CanonicalAdvanced",
+ "genericProductionParseAccepted": false,
+ "normalValidateExit": 1,
+ "normalBuildAccepted": true,
+ "differenceCodes": []
+ },
+ {
+ "source": "fixtures/Regression/ProfileComposition/valid/semantic-split-compose-chamfer.firmament",
+ "structuralStatus": "Parsed",
+ "productionRoute": "LegacyLowercase",
+ "genericProductionParseAccepted": false,
+ "normalValidateExit": 1,
+ "normalBuildAccepted": false,
+ "differenceCodes": []
+ },
+ {
+ "source": "fixtures/Regression/FrontendX1/slot-route-perturbation.firmament",
+ "structuralStatus": "Parsed",
+ "productionRoute": "CanonicalAdvanced",
+ "genericProductionParseAccepted": false,
+ "normalValidateExit": 1,
+ "normalBuildAccepted": false,
+ "differenceCodes": []
+ },
+ {
+ "source": "fixtures/Regression/FrontendX0/unknown-boundary-field.firmament",
+ "structuralStatus": "Parsed",
+ "productionRoute": "CanonicalAdvanced",
+ "genericProductionParseAccepted": true,
+ "normalValidateExit": 0,
+ "normalBuildAccepted": true,
+ "differenceCodes": []
+ },
+ {
+ "source": "fixtures/Regression/FrontendX0/unknown-compose-statement.firmament",
+ "structuralStatus": "Parsed",
+ "productionRoute": "CanonicalAdvanced",
+ "genericProductionParseAccepted": true,
+ "normalValidateExit": 0,
+ "normalBuildAccepted": true,
+ "differenceCodes": [
+ "compose-operation-without-receipt"
+ ]
+ }
+ ],
+ "tests": {
+ "releaseBuildErrors": 0,
+ "releaseBuildWarnings": 7,
+ "focusedParserPassed": 27,
+ "focusedCliPassed": 3,
+ "fastCorePassed": 1068,
+ "fullRegression": {
+ "command": "dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1",
+ "projects": 20,
+ "passed": 4652,
+ "failed": 0,
+ "skipped": 0,
+ "qualification": "Final source, including repaired evidence link. Earlier missing-link failure retained in raw logs."
+ },
+ "layoutGuard": "Passed for 5144 tracked paths; new paths reviewed against the same content policy.",
+ "diffWhitespaceCheck": "Passed"
+ },
+ "showcases": [
+ {
+ "name": "threaded-bolt",
+ "exitCode": 0,
+ "command": "build fixtures/Thread/hexbolt-threaded.firmament --output artifacts/local/frontend-x1/showcase-bolt.step --json"
+ },
+ {
+ "name": "pmi",
+ "exitCode": 0,
+ "command": "build fixtures/Canonical/PMI/counterbore-shaft-diameter.firmament --output artifacts/local/frontend-x1/showcase-pmi.step --json"
+ },
+ {
+ "name": "sheet-metal",
+ "exitCode": 0,
+ "command": "build fixtures/Canonical/SheetMetal/four-wall-tray-template.firmament --output artifacts/local/frontend-x1/showcase-sheet.step --json"
+ },
+ {
+ "name": "templates",
+ "exitCode": 0,
+ "command": "build fixtures/Canonical/Templates/nested-template-pmi.firmament --output artifacts/local/frontend-x1/showcase-template.step --json"
+ },
+ {
+ "name": "radial-pattern",
+ "exitCode": 0,
+ "command": "build fixtures/Canonical/Symmetry/radial-bolt-circle.firmament --output artifacts/local/frontend-x1/showcase-pattern.step --json"
+ },
+ {
+ "name": "guitar",
+ "exitCode": 0,
+ "command": "asm inspect fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar-x0.firmament --json"
+ },
+ {
+ "name": "industrial-atlas",
+ "exitCode": 0,
+ "command": "asm inspect fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas/atlas-industrial.firmament --json"
+ },
+ {
+ "name": "warm-modern-house",
+ "exitCode": 0,
+ "command": "scene inspect fixtures/Canonical/Scene/WarmModernHouse/house.firmament --json"
+ },
+ {
+ "name": "warehouse",
+ "exitCode": 0,
+ "command": "scene inspect fixtures/Canonical/Scene/warehouse.firmament --json"
+ },
+ {
+ "name": "factory",
+ "exitCode": 0,
+ "command": "scene inspect fixtures/Canonical/Scene/FactoryX0/factory.firmament --json"
+ }
+ ],
+ "stepHashComparisons": [
+ {
+ "case": "unknown-compose-statement",
+ "baseline": "same-checkout before X1 implementation",
+ "before": "c1b68c96ce8b082c60b8380c0886aa93d094a717888f962cc3d3e907ff6abce3",
+ "after": "c1b68c96ce8b082c60b8380c0886aa93d094a717888f962cc3d3e907ff6abce3",
+ "equal": true
+ },
+ {
+ "case": "unknown-boundary-field",
+ "baseline": "same-checkout before X1 implementation",
+ "before": "c1b68c96ce8b082c60b8380c0886aa93d094a717888f962cc3d3e907ff6abce3",
+ "after": "c1b68c96ce8b082c60b8380c0886aa93d094a717888f962cc3d3e907ff6abce3",
+ "equal": true
+ },
+ {
+ "case": "bolt",
+ "baseline": "historical X0 qualification",
+ "before": "b9dee30ff017af95a3d2c073b582c0301928a094ecc1bfe56e3caf3fd8508c3a",
+ "after": "b9dee30ff017af95a3d2c073b582c0301928a094ecc1bfe56e3caf3fd8508c3a",
+ "equal": true
+ },
+ {
+ "case": "pmi",
+ "baseline": "historical X0 qualification",
+ "before": "d1b6f8c60f1b4d4bc97c43fc9fe7591f77dd13511f44e4d375326fc7e541e0ed",
+ "after": "d1b6f8c60f1b4d4bc97c43fc9fe7591f77dd13511f44e4d375326fc7e541e0ed",
+ "equal": true
+ },
+ {
+ "case": "sheet",
+ "baseline": "historical X0 qualification",
+ "before": "940ba27513ac59ec8b2d4a13063085b3af20d0d5c3c55b4e2dba725d591352a4",
+ "after": "940ba27513ac59ec8b2d4a13063085b3af20d0d5c3c55b4e2dba725d591352a4",
+ "equal": true
+ },
+ {
+ "case": "template",
+ "baseline": "historical X0 qualification",
+ "before": "d51106507342d65828cfb81540c3ddf6edc899fde895fe3d069a92903cd2b736",
+ "after": "d51106507342d65828cfb81540c3ddf6edc899fde895fe3d069a92903cd2b736",
+ "equal": true
+ },
+ {
+ "case": "pattern",
+ "baseline": "historical X0 qualification",
+ "before": "4b4f8fd69d10e73bb403f1538c6fc13995f895e4c1c17e0605a3e4a008e5356e",
+ "after": "4b4f8fd69d10e73bb403f1538c6fc13995f895e4c1c17e0605a3e4a008e5356e",
+ "equal": true
+ }
+ ],
+ "benchmarks": [
+ {
+ "source": "fixtures/Canonical/Basics/box.firmament",
+ "shadowStatus": "Parsed",
+ "benchmark": {
+ "iterations": 20,
+ "sourceCharacters": 206,
+ "medianMilliseconds": 0.0142,
+ "p95Milliseconds": 0.0174,
+ "medianAllocatedBytes": 17264
+ }
+ },
+ {
+ "source": "fixtures/Regression/FrontendX0/unknown-compose-statement.firmament",
+ "shadowStatus": "Parsed",
+ "benchmark": {
+ "iterations": 20,
+ "sourceCharacters": 942,
+ "medianMilliseconds": 0.0553,
+ "p95Milliseconds": 0.07,
+ "medianAllocatedBytes": 69360
+ }
+ },
+ {
+ "source": "fixtures/Canonical/Templates/nested-template-pmi.firmament",
+ "shadowStatus": "Parsed",
+ "benchmark": {
+ "iterations": 20,
+ "sourceCharacters": 1268,
+ "medianMilliseconds": 0.0619,
+ "p95Milliseconds": 0.0705,
+ "medianAllocatedBytes": 76368
+ }
+ },
+ {
+ "source": "fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar-x0.firmament",
+ "shadowStatus": "Parsed",
+ "benchmark": {
+ "iterations": 20,
+ "sourceCharacters": 955,
+ "medianMilliseconds": 0.039,
+ "p95Milliseconds": 0.0434,
+ "medianAllocatedBytes": 50512
+ }
+ },
+ {
+ "source": "fixtures/Canonical/Scene/WarmModernHouse/house.firmament",
+ "shadowStatus": "Parsed",
+ "benchmark": {
+ "iterations": 20,
+ "sourceCharacters": 3654,
+ "medianMilliseconds": 0.2168,
+ "p95Milliseconds": 4.2788,
+ "medianAllocatedBytes": 288768
+ }
+ },
+ {
+ "source": "fixtures/Canonical/Scene/FactoryX0/kit.firmament",
+ "shadowStatus": "Parsed",
+ "benchmark": {
+ "iterations": 20,
+ "sourceCharacters": 11757,
+ "medianMilliseconds": 0.8195,
+ "p95Milliseconds": 2.1082,
+ "medianAllocatedBytes": 1123520
+ }
+ }
+ ],
+ "limitations": [
+ "No production family migrated.",
+ "Legacy serialization and unsupported domain syntax remain in the inventoried rejection counts.",
+ "No complete AST-to-AIR adapter, scoped expansion, semantic parity or new geometry capability.",
+ "Benchmarks are per-file warm syntax parsing, excluding transitive includes and production compilation.",
+ "No native Helios interaction or remote CI qualification."
+ ],
+ "canonicalShadowRejectedSources": [
+ "Canonical/AssemblyInterfaces/AuthoringFoundation/product-notes.firmasm",
+ "Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm",
+ "Canonical/AssemblyInterfaces/executable-machine.firmament",
+ "Canonical/AssemblyInterfaces/register.firmament",
+ "Canonical/Assembly/bearing-module.firmament",
+ "Canonical/Assembly/coil-on-stem.firmament",
+ "Canonical/Assembly/template-block-pair.firmament",
+ "Canonical/Drawings/bearing-block-production-drawing.firmament",
+ "Canonical/FEA/inline-step-cantilever.firmament",
+ "Canonical/Features/Holes/blind-hole.firmament",
+ "Canonical/Integration/inline-step-recognize-replace.firmament",
+ "Canonical/Sculpting/sculpt-branch-variants.firmament",
+ "Canonical/Sculpting/sculpt-offset-region.firmament",
+ "Canonical/Sculpting/sculpt-preserve-interface.firmament",
+ "Canonical/Sculpting/sculpted-housing.firmament",
+ "Canonical/Sculpting/surf-x1-freeform-housing.firmament",
+ "Canonical/Sculpting/surf-x1a-trimmed-freeform-housing.firmament",
+ "Canonical/Sculpting/surf-x2-g1-blend.firmament",
+ "Canonical/Sculpting/surf-x2-judged-housing.firmament",
+ "Canonical/Sculpting/surf-x2-manual-candidate.firmament",
+ "Canonical/SheetMetal/network-appliance-enclosure.firmament",
+ "Canonical/SheetMetal/power-supply-enclosure.firmament",
+ "Canonical/SheetMetal/profiledelta-remove-area.firmament"
+ ],
+ "slotPerturbationControl": {
+ "derivedFrom": "fixtures/Regression/FrontendX1/slot-route-perturbation.firmament",
+ "transformation": "Remove exactly the AST span of the Slot2 sibling; retain all other source.",
+ "normalCliBuildExit": 0,
+ "normalCliBuildSuccess": true,
+ "withSlotNormalCliBuildSuccess": false,
+ "baselineProductionRoute": "Canonical",
+ "withSlotProductionRoute": "CanonicalAdvanced",
+ "originalSubtreeEquality": "Asserted by focused regression test."
+ }
+}
diff --git a/docs/release/FIRMAMENT-FRONTEND-X1.md b/docs/release/FIRMAMENT-FRONTEND-X1.md
new file mode 100644
index 00000000..3a0870d9
--- /dev/null
+++ b/docs/release/FIRMAMENT-FRONTEND-X1.md
@@ -0,0 +1,238 @@
+# FIRMAMENT-FRONTEND-X1 — unified structural parser, shadow qualification
+
+Historical foundation report: subsequent [production mechanical migration](FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.md) supersedes the production-status statements below.
+
+Date: 2026-10-14. Verdict: **Meaningful progression; not Accepted.**
+
+Original source now has a lexer-driven, typed structural representation before
+production expansion can erase intent. The shadow tooling exposes the omitted
+Compose operation, preserves the unknown boundary field, and separates structural
+parsing from actual production validation. No construct family has migrated.
+Remaining admitted syntax and incomplete semantic/source-consumption comparison
+prevent an X1 acceptance claim.
+
+## Inputs and ownership audit
+
+Read the [October authoring audit](../development/firmament-authoring-pass-2026-10.md),
+[September profile audit](../development/firmament-v2-language-audit.md),
+[reconciliation register](../development/firmament-language-inconsistencies.md),
+[X0 qualification](FIRMAMENT-FRONTEND-X0.md),
+[24-recommendation decision register](../development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md),
+public syntax and the active grammar inventory. The historical 281-file audit is
+not the current corpus size.
+
+The inspected production chain remains: source spelling/import resolution,
+ClosedBoundary2 expansion, Template specialization, Feature expansion, boundary
+expansion again, static/Pattern expansion, then whole-document parser selection.
+`FirmamentV2Parser.ParseUncached` still selects Panel, CanonicalAdvanced,
+Canonical, PrimitiveConstructionPolicy, RoundedBox, StandaloneProfile,
+ConceptModeling, Phase3 or LegacyLowercase. Serialization-shaped inputs retain
+their X0 compatibility boundary. The existing cache remains production-only.
+
+`ClosedBoundary2Authoring` erases boundaries into Profile text. Template IR retains
+typed parameters but carries body text; Feature expansion retains return/local
+construction text; `CanonicalStaticAuthoring` and Concept IR expand finite patterns
+through source substitution. Generic document AIR is a lossy post-expansion
+projection. It cannot prove original field consumption or recover every scope.
+
+`ProfileAuthoringParser`/`ClosedBoundary2Authoring`, prismatic composition and the
+existing Mechanical, SheetMetal, WireForm, Surfacing, Assembly, Scene and PMI owners
+remain the engineering authorities. Formatter and language-service paths still
+use the original lexer and production diagnostic owners. No Helios validator or
+new domain dispatch was introduced.
+
+## Reproduction evidence
+
+The first two cases were replayed through the repository CLI before implementation,
+producing successful STEP builds. They were replayed after the changes as well.
+
+| Source | Current production behavior | Shadow evidence / disposition |
+| --- | --- | --- |
+| FrontendX0/unknown-compose-statement | Validate/build succeed; CanonicalAdvanced omits Fillet LostIntent | Typed declaration and original span survive. Compose operation receipt comparison identifies LostIntent as absent. Existing parser defect (B), not repaired in production. |
+| FrontendX0/unknown-boundary-field | Validate/build succeed despite Rect2 heigth | AST retains the field, its literal and original token span. Field comparison explicitly remains unqualified; no duplicated field schema was invented. Existing parser defect (B). |
+| CanonicalGeometry/profile-chamfer-reflex-junction-top | Generic CanonicalAdvanced parse/validate reject; actual build succeeds | Member-set selector Bracket.Outer.[Inner, Upright] is represented structurally. Existing admission defect (B); lowerer semantics must govern migration. |
+| ProfileComposition/valid/semantic-split-compose-chamfer | Generic LegacyLowercase parse and normal build both reject in this checkout; build reports EdgeFinishProfileComposeBoundaryUnsupported | Original profiles, aliases and repeated Source fields parse structurally. Historical acceptance must not be inferred from the directory name or X0 report. |
+| Added Static/Slot2/Pattern/Profile siblings | Old document route remains production metadata, independent of shadow | Metamorphic tests compare every original body statement, excluding shifted spans; existing AST interpretation is unchanged. This proves structural invariance only. |
+| FrontendX1/slot-route-perturbation | Hole plate builds on Canonical after removing the Slot2 sibling; including the correctly spelled unused Slot2 selects CanonicalAdvanced and rejects the build | Both sources parse structurally with identical original subtrees. Concrete route-dependent admission defect (B) remains in production. |
+| Unsupported-XZ L bracket | Normal build rejects as established in X0 | AST retains literal XZ rather than substituting XY. Existing X0 asymmetric world-bounds regression remains active. |
+
+Fixtures were preserved; no accepted source was edited to fit the new grammar.
+The original twelve complete authoring programs were not supplied by the October
+audit. X0 reconstructed witnesses remain identified as such; no X4 retest claim.
+
+## Architecture and AST
+
+New code lives under `FirmamentV2/Syntax/`:
+
+- `FirmamentSyntax`: compact immutable record model for declarations, contextual
+ prefixes, type arguments, parameters/defaults, annotations, clauses, fields,
+ directives, keyed mappings, occurrences and nested bodies.
+- Expressions have typed literal, quantity, reference, member/member-set, index,
+ call, specialization, sequence, object, immutable-with, unary/binary, frame,
+ trace-endpoint and alias nodes. No body is an opaque source-text payload.
+- `FirmamentSyntaxParser`: recursive descent statements/types and a precedence
+ parser for expressions. Every recognized scope closes explicitly. Unconsumed
+ tokens are parsed into nodes or produce a fatal located diagnostic. Recovery
+ synchronizes at separators, lines and scope boundaries; both ordinary and
+ occurrence loops guarantee progress. Nesting/expression chains are bounded.
+- `FirmamentSyntaxEvidence`: normalized structural fingerprints and a deliberately
+ partial comparison with production AIR. It performs literal-mm comparison only,
+ not expression evaluation or engineering admission.
+
+AST type names are open authored identifiers; node categories and operators are
+typed. A syntactically shaped Fillet declaration is retained for a semantic owner
+to reject. `Parsed` always means **StructuralOnlyUnbound**. It does not certify
+names, types, dimensional legality, capability, placement, expansion or geometry.
+Unknown fields/statements are not thereby admitted for execution.
+
+Source offsets use original UTF-16 positions, matching existing editor spans.
+Every node carries a span; the document retains all tokens, whitespace, comments
+and EOF. Concatenating token text reproduces the original source exactly. No
+spelling normalization or production expansion runs inside the structural parser.
+There is no generated-source location to fabricate: this AST is original source.
+
+The sole existing `FirmamentLanguageAnalysisService.Lex` scanner gained a lossless
+view and unterminated token evidence. Its normal view still omits trivia/EOF as
+before. Numeric scanning now distinguishes fractions, exponents and member dots;
+domain symbols such as StainlessSteel.304_Annealed remain identifiers after a
+member delimiter. No second lexer, global case normalizer, regex, source macro
+pass or whole-document parser dispatch was added.
+
+## Compatibility, expressions and remaining syntax
+
+Existing casing and root spellings are preserved in the tree. No point constructor,
+cut vocabulary, optional-root or generic-variant semantics changed. Adjacent angle
+suffixes and explicitly named/empty spaced generic applications are represented;
+other comparison/generic-spacing ambiguities remain a decision, not a new language
+promise. Expression nodes retain precedence without evaluating engineering values.
+
+Template/Feature definitions, defaults, nested generics, keyed Set/Pattern mappings,
+radial/linear/mirror declarations, finite template invocations and XML-shaped
+Part/Assembly bodies have structural coverage. Imported declarations are parsed in
+their own inventoried files; this parser does not specialize or resolve includes.
+There is no AST-to-AIR adapter disguised as a call back into regex syntax parsing.
+
+Important outstanding forms include Interface Role/requires and Mate relations,
+imported STEP #face selectors, specialized Blind/CenteredAt value shorthand,
+Replace/Extend headers and drawing-specific metadata. Canonical Sculpting fixtures
+with literal leading plus signs require an owner decision. These are located
+shadow failures; the corpus does not hide them. Finishing these forms is bounded
+X1 work. Unifying evaluators and scoped expansion remains X2.
+
+## Diagnostics and developer tooling
+
+Syntax errors reuse `FirmamentV2ValidationDiagnostic`: stable code, fatal severity,
+sentence, original file/span, line/column, enclosing context where available and
+stage Syntax. New codes are `firmament-syntax-statement`, `-expression`,
+`-identifier`, `-expected-token`, `-declaration-tail`, `-tag-mismatch`, `-depth`
+and `-unterminated-token`. Warnings were not globally promoted.
+
+`frontend-shadow file --json` provides summary, structural outcome, actual generic
+production route/diagnostics and partial comparison. `--ast` adds the full tree
+only when requested. `--validate` invokes the unchanged normal validation command
+and includes its separate JSON result/exit code. `validate file --shadow --explain
+--json` exposes the same developer envelope. Ordinary validate/build output does
+not run or include shadow analysis. Shadow failure returns failure on an individual
+file even when the production projection accepted it.
+
+Comparison checks original Model identity, unambiguous primitive name/type,
+literal-mm Box dimensions and direct Compose operation receipts. Unmatched fields
+and declarations are counted explicitly. It does **not** claim complete semantic
+or geometry parity. Most legacy AIR fields/nesting/references no longer have the
+original syntax needed for a trustworthy full differential. Diagnostics and source
+spans from the production projection remain separately visible. A-E dispositions
+for investigated cases are in the decision register; other machine differences
+remain Unclassified rather than receiving invented automated explanations.
+
+## Corpus, tests and geometry
+
+`scripts/qualify-firmament-frontend-x1.ps1` inventories every `.firmament`,
+`.firmfixture` and `.firmasm` under fixtures, compares original syntax against the
+generic production projection and writes machine JSON/Markdown under ignored
+`artifacts/local/frontend-x1/corpus`. Compatibility, invalid and speculative files
+are included. Collection exit zero means the report completed, not qualification;
+`qualified: false` and `semanticParityQualified: false` are explicit.
+
+Final counts, benchmark samples, test totals and geometry hash comparisons are in
+the adjacent compact [evidence record](FIRMAMENT-FRONTEND-X1.evidence.json). Raw
+diagnostics and per-file outcomes remain in the ignored report. The required
+canonical showcase sources and their included modules are part of that inventory;
+no failure list was silently excluded to improve a percentage.
+
+Final collection: **1,232 sources, 741 structurally parsed, 491 rejected**;
+Canonical contains 323 source files including legacy `.firmasm`, with 300 parsed
+and 23 rejected. There are 57 generic-production-accepted/shadow-rejected files.
+These are coverage gaps, not an authoring success rate.
+
+Final validation: Release build succeeded with zero errors and seven existing
+warnings; 27 parser tests, three CLI tests and 1,068 fast Core tests passed.
+The normal full solution lane passed **4,652 tests across 20 projects**, zero
+failed/skipped. All ten real showcase CLI checks passed. Both same-checkout
+pre-X1 intent-loss STEP hashes and all five historical X0 showcase STEP hashes
+match. The normal CLI hole-plate control also builds successfully after removing
+only the unused Slot2 AST span; the source containing Slot2 rejects.
+
+Focused coverage includes lossless lexing, nested generics/defaults, precedence,
+member/index/with/frame/trace syntax, original source diagnostics, error recovery,
+depth limits, occurrence progress, retained unknown intent, structural sibling/root
+invariance, literal-dimension differential detection, unsupported-XZ preservation,
+CLI JSON shape and separate production/shadow outcomes. Production geometry is
+exercised through existing lowerers; no new geometry engine is involved.
+
+The closeout full run initially caught a missing linked evidence file in this
+report. The file was added, and the final full regression qualification was rerun
+with it present. This was a documentation packaging error, not a kernel failure.
+
+Reproduce with the repository SDK/CLI:
+
+```powershell
+dotnet build Aetheris.slnx -c Release -m:1
+./scripts/qualify-firmament-frontend-x1.ps1
+dotnet test Aetheris.Kernel.Firmament.Tests -c Release --no-build --filter FullyQualifiedName~FirmamentFrontendX1Tests
+dotnet test Aetheris.CLI.Tests -c Release --no-build --filter FullyQualifiedName~FirmamentFrontendX1CliTests
+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter "Category!=SlowCorpus"
+dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1
+```
+
+## Performance and code-quality pass
+
+`--benchmark` measures twenty warm parses after warm-up, with current-thread
+allocated bytes. IO, production parsing, comparison, serialization and geometry
+are excluded. The samples cover a Box, ordinary Compose part, nested Template/PMI,
+guitar entry source, house entry source and largest current Firmament fixture
+(FactoryX0 kit). These are per-file syntax measurements, not transitive whole
+guitar/scene compilation or interactive-session throughput. No cache/session
+redesign was introduced. Raw samples and exact sizes remain in evidence.
+
+The review found and fixed an occurrence recovery progress hole, corrected frame
+vector/body spans, preserved repeated fields, and made comparison coverage explicit.
+New parsing uses no regex, no source slicing for grammar reconstruction, no mutable
+global parser state, no field schema copy and no fatal-code allowlist. JSON options
+are read-only configuration. No unrelated formatting or domain lowerer edits were
+made. Native Helios interaction and remote CI are not claimed; existing diagnostic
+consumers and all production authorities remain in place.
+
+## Migration gates, prerequisites and verdict
+
+No migration gate is waived. AST coverage and diagnostics have focused evidence;
+complete structural/semantic parity, binding, original field consumption, expansion
+provenance and family-specific AP242 parity are not established. Accepted geometry
+must continue through existing owners until all gates pass.
+
+The smallest next steps are:
+
+1. Complete the named Interface/domain syntax gaps and classify every admitted
+ source rejected by shadow. Preserve invalid/legacy classifications separately.
+2. Build explicit typed adapters for a bounded family, projecting AST fields and
+ references into its existing binder/lowerer with consumption receipts. Do not
+ gate profiles on the lossy generic document parse.
+3. Extend differential evidence to full scoped fields/references/expressions and
+ actual domain admission. Then qualify geometry/STEP before any route retirement.
+4. X2 may consolidate binding, dimension evaluation and finite scoped expansion
+ once these syntax receipts exist. X3 syntax choices and X4 authoring retest
+ remain separate milestones.
+
+**Meaningful progression:** original-source structural loss is no longer a blocker
+to inspecting and testing intent in shadow mode. Production honesty gaps remain;
+the next blockers are explicit missing syntax forms and missing semantic/source
+consumption adapters. X1 is not Accepted, and no production cutover is justified.
diff --git a/docs/release/FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.evidence.json b/docs/release/FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.evidence.json
new file mode 100644
index 00000000..f9032012
--- /dev/null
+++ b/docs/release/FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.evidence.json
@@ -0,0 +1,594 @@
+{
+ "schemaVersion": 1,
+ "date": "2026-10-14",
+ "verdict": "Accepted for the production mechanical Model/Struct migration; whole-language qualification remains bounded",
+ "productionParserRoute": "UnifiedMechanical",
+ "baselineContext": "Same checkout before production mechanical edits, with the earlier X1 AST foundation present. Historical X0 showcase comparisons are recorded separately.",
+ "tests": {
+ "releaseBuild": {
+ "errors": 0,
+ "warnings": 11,
+ "command": "dotnet build Aetheris.slnx -c Release -m:1 --no-restore"
+ },
+ "fastCore": {
+ "passed": 1068,
+ "failed": 0,
+ "skipped": 0
+ },
+ "focusedFirmament": {
+ "passed": 2236,
+ "failed": 0,
+ "skipped": 0
+ },
+ "full": {
+ "total": 4675,
+ "passed": 4675,
+ "failed": 0,
+ "skipped": 0,
+ "nonemptyProjects": 20,
+ "command": "dotnet test Aetheris.slnx -c Release --no-build -m:1 --settings artifacts/local/mechanical-frontend-migration/serial.runsettings -- RunConfiguration.MaxCpuCount=1",
+ "collections": "Serialized with existing X0 xUnit settings; no tests excluded or execution budgets changed",
+ "assemblies": [
+ {
+ "assembly": "aetheris.cli.tests.dll",
+ "total": 487,
+ "passed": 487,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.collaboration.tests.dll",
+ "total": 5,
+ "passed": 5,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.continuum.tests.dll",
+ "total": 159,
+ "passed": 159,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.drawing.tests.dll",
+ "total": 13,
+ "passed": 13,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.fea.tests.dll",
+ "total": 43,
+ "passed": 43,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.forge.host.tests.dll",
+ "total": 39,
+ "passed": 39,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "Aetheris.FrictionLab.Tests (zero discovered tests)",
+ "total": 0,
+ "passed": 0,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.geometry.tests.dll",
+ "total": 58,
+ "passed": 58,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.humanoid.tests.dll",
+ "total": 90,
+ "passed": 90,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.kernel.core.tests.dll",
+ "total": 1201,
+ "passed": 1201,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.kernel.firmament.tests.dll",
+ "total": 2236,
+ "passed": 2236,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.kernel.standardlibrary.tests.dll",
+ "total": 6,
+ "passed": 6,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.modules.tests.dll",
+ "total": 112,
+ "passed": 112,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.plasticshell.tests.dll",
+ "total": 18,
+ "passed": 18,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.reconstruction.tests.dll",
+ "total": 24,
+ "passed": 24,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.sculpture.tests.dll",
+ "total": 2,
+ "passed": 2,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.semantics.tests.dll",
+ "total": 9,
+ "passed": 9,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.server.tests.dll",
+ "total": 63,
+ "passed": 63,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.sheetmetal.tests.dll",
+ "total": 99,
+ "passed": 99,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.samples.databasedrivencad.tests.dll",
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "skipped": 0
+ },
+ {
+ "assembly": "aetheris.editablev8.tests.dll",
+ "total": 3,
+ "passed": 3,
+ "failed": 0,
+ "skipped": 0
+ }
+ ]
+ },
+ "defaultCollectionRun": {
+ "failed": 3,
+ "scope": "Native Core display execution-budget failures; all 487 CLI and 2234 then-current Firmament tests passed. The final code adds two suffix-consumption regressions and passes the serialized full lane."
+ },
+ "closeoutBuild": {
+ "errors": 0,
+ "warnings": 4,
+ "note": "Incremental build after comment and release-document cleanup; production semantics unchanged"
+ }
+ },
+ "geometryComparisons": [
+ {
+ "source": "fixtures/Canonical/Primitives/cone.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "420b623a7103d10f0303ba2263ef8195a13fcbc405af13c0ac2bdd49259f7a02",
+ "afterSha256": "420b623a7103d10f0303ba2263ef8195a13fcbc405af13c0ac2bdd49259f7a02",
+ "identical": true,
+ "artifactName": "00-cone.step"
+ },
+ {
+ "source": "fixtures/Canonical/Primitives/frustum.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "6d2c54d5496dad7268388c1e8cd8f3dcae00f1d3924a8d1802efababef0def8e",
+ "afterSha256": "6d2c54d5496dad7268388c1e8cd8f3dcae00f1d3924a8d1802efababef0def8e",
+ "identical": true,
+ "artifactName": "01-frustum.step"
+ },
+ {
+ "source": "fixtures/Canonical/Primitives/pointed-cone.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "5b660833181fe7304472082dc0f643edec517310bd26471b3b224fb43c35adc9",
+ "afterSha256": "5b660833181fe7304472082dc0f643edec517310bd26471b3b224fb43c35adc9",
+ "identical": true,
+ "artifactName": "02-pointed-cone.step"
+ },
+ {
+ "source": "fixtures/Canonical/Primitives/rounded-box.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "b387cfc00793cf3d58da554860dfe5458d5628fbe92fd48150fea0eff369695f",
+ "afterSha256": "b387cfc00793cf3d58da554860dfe5458d5628fbe92fd48150fea0eff369695f",
+ "identical": true,
+ "artifactName": "03-rounded-box.step"
+ },
+ {
+ "source": "fixtures/Canonical/Primitives/sphere.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "ef7df681298062560ffc49217d559effda5d64c8be2897aae8525bc441ed39fb",
+ "afterSha256": "ef7df681298062560ffc49217d559effda5d64c8be2897aae8525bc441ed39fb",
+ "identical": true,
+ "artifactName": "04-sphere.step"
+ },
+ {
+ "source": "fixtures/Canonical/Primitives/torus.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "e3e2d73777a95251482d670deff393a632f878b75baa703df72f70d9e5ba518c",
+ "afterSha256": "e3e2d73777a95251482d670deff393a632f878b75baa703df72f70d9e5ba518c",
+ "identical": true,
+ "artifactName": "05-torus.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/Holes/blind-hole.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "d33e58403c6641da7b5e9ef0898f59eead720fa2ec6c1edac450d430bb6d74f7",
+ "afterSha256": "d33e58403c6641da7b5e9ef0898f59eead720fa2ec6c1edac450d430bb6d74f7",
+ "identical": true,
+ "artifactName": "06-blind-hole.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/Holes/counterbore.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "7e6ec904fe986543a9ac63079e96be756d8455fb56d18aa7a22b9afaa24495af",
+ "afterSha256": "7e6ec904fe986543a9ac63079e96be756d8455fb56d18aa7a22b9afaa24495af",
+ "identical": true,
+ "artifactName": "07-counterbore.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/Holes/countersink.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "af15824dbb6067aa12d1aa701acc70857c43e142d5e34f23e921f965ce2e4640",
+ "afterSha256": "af15824dbb6067aa12d1aa701acc70857c43e142d5e34f23e921f965ce2e4640",
+ "identical": true,
+ "artifactName": "08-countersink.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/Holes/through-hole.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "5999f127e5a1477e5825afa656dceb7f89241d8f85312b0e6bcd793639a0f548",
+ "afterSha256": "5999f127e5a1477e5825afa656dceb7f89241d8f85312b0e6bcd793639a0f548",
+ "identical": true,
+ "artifactName": "09-through-hole.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/EdgeFinish/boundary-chamfer.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "7c7728da4a940d7f828c3aef9c058cb39c0ea456b1f97ec790a0b88a75298a34",
+ "afterSha256": "7c7728da4a940d7f828c3aef9c058cb39c0ea456b1f97ec790a0b88a75298a34",
+ "identical": true,
+ "artifactName": "10-boundary-chamfer.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/EdgeFinish/semantic-selection-chamfer.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "faca2548ebfe16f18656b64839ce158906f9d8ada22dd804e738cbc407227058",
+ "afterSha256": "faca2548ebfe16f18656b64839ce158906f9d8ada22dd804e738cbc407227058",
+ "identical": true,
+ "artifactName": "11-semantic-selection-chamfer.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/EdgeFinish/single-edge-fillet.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "d313c98053b7c68e21c75a907424929cf5c8c3d84ebb47b2947211b12f435aec",
+ "afterSha256": "d313c98053b7c68e21c75a907424929cf5c8c3d84ebb47b2947211b12f435aec",
+ "identical": true,
+ "artifactName": "12-single-edge-fillet.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/Pocket/rectangular-pocket.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "c1b68c96ce8b082c60b8380c0886aa93d094a717888f962cc3d3e907ff6abce3",
+ "afterSha256": "c1b68c96ce8b082c60b8380c0886aa93d094a717888f962cc3d3e907ff6abce3",
+ "identical": true,
+ "artifactName": "13-rectangular-pocket.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/Boss/boss-pocket-block.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "0ec6fe5577b03c9bebf6724ba9d4dba4c21d4df58f34950c681e077d8a2f8c9f",
+ "afterSha256": "0ec6fe5577b03c9bebf6724ba9d4dba4c21d4df58f34950c681e077d8a2f8c9f",
+ "identical": true,
+ "artifactName": "14-boss-pocket-block.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/Boss/circular-boss-through-hole.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "ac566ae6b87572df21014a1141f41ca5846a186f7861a985bc6ecd82d5e4aeca",
+ "afterSha256": "ac566ae6b87572df21014a1141f41ca5846a186f7861a985bc6ecd82d5e4aeca",
+ "identical": true,
+ "artifactName": "15-circular-boss-through-hole.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/Boss/rectangular-boss.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "35bc44d83c7c338efccb8bac76f2a69fed149bcaa782362e9704d64bd9f29b6a",
+ "afterSha256": "35bc44d83c7c338efccb8bac76f2a69fed149bcaa782362e9704d64bd9f29b6a",
+ "identical": true,
+ "artifactName": "16-rectangular-boss.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/Slots/rounded-rectangle-opening.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "ee95181200cec5c7ccc62f53f0cefd988eb87beb5c37422d9e1d93a5f6f403bc",
+ "afterSha256": "ee95181200cec5c7ccc62f53f0cefd988eb87beb5c37422d9e1d93a5f6f403bc",
+ "identical": true,
+ "artifactName": "17-rounded-rectangle-opening.step"
+ },
+ {
+ "source": "fixtures/Canonical/Features/Slots/straight-slot.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "a6784518079f2edd33e9261cddc2e44253ae195a03a043cdaa10ac6062e8ec9a",
+ "afterSha256": "a6784518079f2edd33e9261cddc2e44253ae195a03a043cdaa10ac6062e8ec9a",
+ "identical": true,
+ "artifactName": "18-straight-slot.step"
+ },
+ {
+ "source": "fixtures/Canonical/Profiles/closed-loop-profile.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "382645dcd82b1720cbcb2483462b9b39c2162a0ab53e877e284fdfcd7d48fbb5",
+ "afterSha256": "382645dcd82b1720cbcb2483462b9b39c2162a0ab53e877e284fdfcd7d48fbb5",
+ "identical": true,
+ "artifactName": "19-closed-loop-profile.step"
+ },
+ {
+ "source": "fixtures/Canonical/Profiles/concept-path-line-arc-profile.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "96a06a693094c0177d1770076445bf675c87bcb9aee71f23a62111171cfa05df",
+ "afterSha256": "96a06a693094c0177d1770076445bf675c87bcb9aee71f23a62111171cfa05df",
+ "identical": true,
+ "artifactName": "20-concept-path-line-arc-profile.step"
+ },
+ {
+ "source": "fixtures/Canonical/Profiles/line-arc-profile-extrusion.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "b2ecbaaf46df4b48741a4a2941502d6dae9614d624aa70ba96704959b5a1dd95",
+ "afterSha256": "b2ecbaaf46df4b48741a4a2941502d6dae9614d624aa70ba96704959b5a1dd95",
+ "identical": true,
+ "artifactName": "21-line-arc-profile-extrusion.step"
+ },
+ {
+ "source": "fixtures/Canonical/Profiles/profile-delta-recess-extrusion.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "ea73c289fa803602271407479761547bd1944824a2f270be0406b27ed86dcb4c",
+ "afterSha256": "ea73c289fa803602271407479761547bd1944824a2f270be0406b27ed86dcb4c",
+ "identical": true,
+ "artifactName": "22-profile-delta-recess-extrusion.step"
+ },
+ {
+ "source": "fixtures/Canonical/Profiles/rect2-profile-extrusion.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "6b48d96e925a2a2a8e7a512296bd50703a744e05f5da068e9d6222c0698bf691",
+ "afterSha256": "6b48d96e925a2a2a8e7a512296bd50703a744e05f5da068e9d6222c0698bf691",
+ "identical": true,
+ "artifactName": "23-rect2-profile-extrusion.step"
+ },
+ {
+ "source": "fixtures/Canonical/Profiles/template-control-arithmetic.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "6dd25297e4d52687998c4546076ea3ee886295fa7cdce152088876a08e5eaad4",
+ "afterSha256": "6dd25297e4d52687998c4546076ea3ee886295fa7cdce152088876a08e5eaad4",
+ "identical": true,
+ "artifactName": "24-template-control-arithmetic.step"
+ },
+ {
+ "source": "fixtures/Canonical/Boundary2/closed-boundary-family.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "2d0e0d7dc26e837c296b5ea72e591d18aea569cee1eb35f68b6d8aa800fe5cd4",
+ "afterSha256": "2d0e0d7dc26e837c296b5ea72e591d18aea569cee1eb35f68b6d8aa800fe5cd4",
+ "identical": true,
+ "artifactName": "25-closed-boundary-family.step"
+ },
+ {
+ "source": "fixtures/Canonical/Boundary2/edited-panel.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "4e00abf9b39d9a1d75e883c2c44f66ba54f32cf3421cd5cc891eb7fb6a3bfe35",
+ "afterSha256": "4e00abf9b39d9a1d75e883c2c44f66ba54f32cf3421cd5cc891eb7fb6a3bfe35",
+ "identical": true,
+ "artifactName": "26-edited-panel.step"
+ },
+ {
+ "source": "fixtures/Canonical/PMI/counterbore-shaft-diameter.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "d1b6f8c60f1b4d4bc97c43fc9fe7591f77dd13511f44e4d375326fc7e541e0ed",
+ "afterSha256": "d1b6f8c60f1b4d4bc97c43fc9fe7591f77dd13511f44e4d375326fc7e541e0ed",
+ "identical": true,
+ "artifactName": "27-counterbore-shaft-diameter.step"
+ },
+ {
+ "source": "fixtures/Thread/hexbolt-threaded.firmament",
+ "beforeExit": 0,
+ "afterExit": 0,
+ "beforeSha256": "b9dee30ff017af95a3d2c073b582c0301928a094ecc1bfe56e3caf3fd8508c3a",
+ "afterSha256": "b9dee30ff017af95a3d2c073b582c0301928a094ecc1bfe56e3caf3fd8508c3a",
+ "identical": true,
+ "artifactName": "28-hexbolt-threaded.step"
+ }
+ ],
+ "admissionComparisons": [
+ {
+ "source": "fixtures/Regression/FrontendX0/unknown-compose-statement.firmament",
+ "expectedAccepted": false,
+ "validateExit": 1,
+ "buildExit": 1,
+ "consistent": true
+ },
+ {
+ "source": "fixtures/Regression/FrontendX0/unknown-boundary-field.firmament",
+ "expectedAccepted": false,
+ "validateExit": 1,
+ "buildExit": 1,
+ "consistent": true
+ },
+ {
+ "source": "fixtures/Regression/FrontendX1/slot-route-perturbation.firmament",
+ "expectedAccepted": true,
+ "validateExit": 0,
+ "buildExit": 0,
+ "consistent": true
+ },
+ {
+ "source": "fixtures/Regression/CanonicalGeometry/profile-chamfer-reflex-junction-top.firmament",
+ "expectedAccepted": true,
+ "validateExit": 0,
+ "buildExit": 0,
+ "consistent": true
+ }
+ ],
+ "showcases": [
+ {
+ "name": "threaded-bolt",
+ "command": "build fixtures/Thread/hexbolt-threaded.firmament --output artifacts/local/mechanical-frontend-migration/showcase-bolt.step --json",
+ "exitCode": 0
+ },
+ {
+ "name": "pmi",
+ "command": "build fixtures/Canonical/PMI/counterbore-shaft-diameter.firmament --output artifacts/local/mechanical-frontend-migration/showcase-pmi.step --json",
+ "exitCode": 0
+ },
+ {
+ "name": "sheet-metal",
+ "command": "build fixtures/Canonical/SheetMetal/four-wall-tray-template.firmament --output artifacts/local/mechanical-frontend-migration/showcase-sheet.step --json",
+ "exitCode": 0
+ },
+ {
+ "name": "templates",
+ "command": "build fixtures/Canonical/Templates/nested-template-pmi.firmament --output artifacts/local/mechanical-frontend-migration/showcase-template.step --json",
+ "exitCode": 0
+ },
+ {
+ "name": "radial-pattern",
+ "command": "build fixtures/Canonical/Symmetry/radial-bolt-circle.firmament --output artifacts/local/mechanical-frontend-migration/showcase-pattern.step --json",
+ "exitCode": 0
+ },
+ {
+ "name": "guitar",
+ "command": "asm inspect fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar-x0.firmament --json",
+ "exitCode": 0
+ },
+ {
+ "name": "industrial-atlas",
+ "command": "asm inspect fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas/atlas-industrial.firmament --json",
+ "exitCode": 0
+ },
+ {
+ "name": "warm-modern-house",
+ "command": "scene inspect fixtures/Canonical/Scene/WarmModernHouse/house.firmament --json",
+ "exitCode": 0
+ },
+ {
+ "name": "warehouse",
+ "command": "scene inspect fixtures/Canonical/Scene/warehouse.firmament --json",
+ "exitCode": 0
+ },
+ {
+ "name": "factory",
+ "command": "scene inspect fixtures/Canonical/Scene/FactoryX0/factory.firmament --json",
+ "exitCode": 0
+ }
+ ],
+ "historicalShowcaseHashes": [
+ {
+ "case": "bolt",
+ "before": "b9dee30ff017af95a3d2c073b582c0301928a094ecc1bfe56e3caf3fd8508c3a",
+ "after": "b9dee30ff017af95a3d2c073b582c0301928a094ecc1bfe56e3caf3fd8508c3a",
+ "identical": true
+ },
+ {
+ "case": "pmi",
+ "before": "d1b6f8c60f1b4d4bc97c43fc9fe7591f77dd13511f44e4d375326fc7e541e0ed",
+ "after": "d1b6f8c60f1b4d4bc97c43fc9fe7591f77dd13511f44e4d375326fc7e541e0ed",
+ "identical": true
+ },
+ {
+ "case": "sheet",
+ "before": "940ba27513ac59ec8b2d4a13063085b3af20d0d5c3c55b4e2dba725d591352a4",
+ "after": "940ba27513ac59ec8b2d4a13063085b3af20d0d5c3c55b4e2dba725d591352a4",
+ "identical": true
+ },
+ {
+ "case": "template",
+ "before": "d51106507342d65828cfb81540c3ddf6edc899fde895fe3d069a92903cd2b736",
+ "after": "d51106507342d65828cfb81540c3ddf6edc899fde895fe3d069a92903cd2b736",
+ "identical": true
+ },
+ {
+ "case": "pattern",
+ "before": "4b4f8fd69d10e73bb403f1538c6fc13995f895e4c1c17e0605a3e4a008e5356e",
+ "after": "4b4f8fd69d10e73bb403f1538c6fc13995f895e4c1c17e0605a3e4a008e5356e",
+ "identical": true
+ }
+ ],
+ "intentionalGeometryCorrection": {
+ "source": "fixtures/Canonical/Scene/FactoryX0/kit.firmament",
+ "construct": "Bin",
+ "before": "Profile route selected only the first of two explicit extrusions; rim names were colliding and unused",
+ "after": "Both explicit XY extrusions enter the existing section-stack IR; inner rim segments use existing explicit As aliases",
+ "unchangedGeometryClaim": false
+ },
+ "remainingBoundaries": [
+ "Dedicated non-mechanical domain frontends retain existing owners",
+ "Legacy lowercase, no-brace headers and bare standalone Profile forms retain compatibility admission",
+ "Template/Feature/Pattern expansion and some semantic value adapters still use source text",
+ "No general frame, expression, Fillet+Hole or kernel expansion is claimed"
+ ],
+ "codeQuality": {
+ "newWholeDocumentRegexDispatch": false,
+ "newGlobalRewriteSystem": false,
+ "newDiagnosticFatalityAllowlist": false,
+ "kernelGeometryChanges": false,
+ "whitespaceCheck": "git diff --check passed"
+ },
+ "rawEvidenceDirectory": "artifacts/local/mechanical-frontend-migration",
+ "reproduction": {
+ "script": "scripts/qualify-firmament-mechanical-frontend.ps1",
+ "retainedBaselineManifest": true,
+ "versionedHashFallbackVerified": true
+ }
+}
diff --git a/docs/release/FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.md b/docs/release/FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.md
new file mode 100644
index 00000000..2d61d003
--- /dev/null
+++ b/docs/release/FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.md
@@ -0,0 +1,188 @@
+# Mechanical frontend production migration
+
+Date: 2026-10-14. This supersedes the production-status statements in the
+[X1 foundation qualification](FIRMAMENT-FRONTEND-X1.md). That report remains a
+historical record of the earlier shadow-only implementation.
+
+## Production change
+
+Normal mechanical `Model` and material-bearing `Struct` documents now enter the
+shared lexer and recursive-descent syntax tree, then bind into existing Firmament
+engineering records. `validate` and `build` use this admission path. The route
+metadata is `UnifiedMechanical`; it is an implementation detail.
+
+The mechanical frontend no longer chooses Canonical versus CanonicalAdvanced
+grammar because a source happens to contain a Profile, Concept or Slot2. It selects
+an existing engineering lowerer from the actual material declaration nodes. An
+unused guide cannot change Box/Hole syntax. Competing material families are rejected instead of silently choosing one.
+Multiple explicit XY extrusions bind to the existing section-stack composition
+IR, retaining each material request.
+
+Primitive dimensions (including Concept-valued Box field consumption),
+Hole/EdgeFinish/Perforation fields, bounded dimensional
+arithmetic, closed-boundary fields, ordinary profile guides and extrusion headers
+bind from AST nodes. Compose Base/Add/Remove, Boss/Pocket and Placement records
+also consume AST fields. Compose Hole/Slot record boundaries and field consumption
+use AST nodes while retaining their established bounded engineering value readers.
+Unknown Compose statements are errors at the Compose owner. Unknown fields are
+reported by the owner after its actual field reads; there is no duplicate global
+field schema or error-code fatality allowlist.
+
+Profile and Compose admission retains the bound profile/composition engineering
+inputs for execution. Build cannot bypass failed mechanical admission by entering
+a source parser later. The exporter no longer repeats the top-level frontend expansion pipeline;
+it consumes the admitted expansion and engineering inputs. Existing
+kernel, topology, feature identities, materialization and STEP exporters remain
+the engineering authority.
+
+Deleted debt includes the old canonical root scanner and primitive/Modify
+declaration parsing, the unused canonical Hole/EdgeFinish parsers, whole-document
+advanced-keyword selection, ordinary guide/header recognition regexes, and the
+separate profile character-based measure parser. The STEP matcher also passes
+original source to the shared compiler instead of stripping Match bodies and
+leaving damaged syntax behind.
+
+## Motivating reproductions
+
+| Source evidence | Before migration | Required production outcome |
+| --- | --- | --- |
+| `FrontendX1/slot-route-perturbation.firmament` | Box/Hole succeeds without the unused Slot2; adding Slot2 selects CanonicalAdvanced and rejects | Both forms admitted; identical STEP text and unchanged topology |
+| `FrontendX0/unknown-compose-statement.firmament` | Fillet LostIntent disappears while the pocket body builds | Parser, normal validate and build reject `Compose:Fillet`, located at the original Fillet token |
+| `FrontendX0/unknown-boundary-field.firmament` | Rect2 heigth disappears during boundary lowering | Validate/build reject `Rect2:heigth`, located at the original field |
+| `CanonicalGeometry/profile-chamfer-reflex-junction-top.firmament` | Generic validation rejects an admitted member-set selection while build succeeds through its profile bypass | Selection member-set is bound; validate/build both admit the existing geometry |
+
+The source specimens remain in `fixtures/Regression/`. Tests also exercise
+duplicate dimensions, malformed tokens inside a rewritten boundary, mixed
+material bodies, ordinary Struct/Model equivalence, unrelated valid construction
+siblings, original syntax locations after comments and existing static Match
+syntax before its unchanged evaluator runs.
+
+## Diagnostics and compatibility
+
+The existing structured CLI contract remains: code, severity, explanatory
+message, file, span/line/column where available, stage/context and a disclosed
+location limitation otherwise. Syntax diagnostics retain their explanatory text
+through build as well as validate. Transformed-source offsets are never presented
+as precise original offsets; the original AST supplies the location when possible.
+Existing semantic-source messages and capability diagnostics remain intact.
+
+`valid` with validation level `Built` includes normal engineering compilation in
+memory. `--parse-only` and external descriptor-pack analysis remain explicitly
+`ParsedNotBuilt`. Static admission does not prove kernel execution cannot fail.
+Warnings retain their existing severity. V1 serialization compatibility keeps its
+explicit version boundary and does not become fallback for recognized V2 errors.
+
+PascalCase and existing camelCase field aliases are preserved. Primitive Hole
+centers retain the existing Point2 requirement; this migration does not redesign
+point syntax. Identical repeated `Units: mm` declarations emitted by existing
+module composition remain admitted; conflicting units fail. Historical
+`Role: ProfileGuide` boundary annotations remain admitted. Typed Concept/Expose
+and named construction-plane semantics retain their established semantic owner.
+Profile selections support the already-built member-set form without requiring
+the unrelated Target field, and repeated Source entries are retained and checked.
+
+The optional `frontend-shadow` command remains a developer evidence tool over the
+same syntax parser. Structural success alone grants no engineering admission.
+There is no new shadow-only runtime or migration milestone.
+
+## Additional canonical-source defect exposed
+
+FactoryX0's Bin template declared two Extrudes (`bottom` and `sides`). The old
+profile route selected only the first; the unused rim profile also had colliding
+inner/outer segment names. AST consumption exposed both problems. Multiple XY
+extrusions now bind into the existing section-stack lowerer, and the canonical
+Bin rim explicitly names its inner segments with existing `As` aliases. This is
+an intentional correction to previously omitted geometry: bins now contain their
+requested side walls. It is not claimed as unchanged historical Bin geometry.
+The focused witness proves a second extrusion reaches Z=8 rather than stopping
+at the first extrusion's Z=2; factory checks exercise the real canonical source.
+No new kernel operation, parser route or source macro implements this repair.
+
+## Remaining boundaries
+
+This is production mechanical migration, not replacement of every Firmament
+domain. Dedicated Revolve, WireForm/WireRoute, Sweep, SectionChain, Panel, Assembly,
+Scene, SheetMetal and other domain owners retain their existing semantic and
+geometry paths. AST material declarations identify the boundary; source-wide
+incidental guide keywords do not select mechanical grammar. A complete language
+frontend replacement must migrate those owners deliberately.
+
+Template/Feature/Pattern and some profile/path derivation transforms still use
+existing source expansion. Their complete scope/provenance migration and semantic
+expression consolidation remain separate work. Some semantic adapters still read
+bounded source values. Legacy lowercase, old no-brace headers and bare standalone
+Profile document forms also retain compatibility admission; this does not claim
+that every historical mechanical spelling has migrated. This report does not claim universal field-consumption
+coverage across those unmigrated domains or all 1,232 historical/speculative
+sources. General non-XY support, Fillet+Hole capability and syntax reconciliation
+have not been added. All 24 recommendations retain an explicit disposition in the
+[language decision register](../development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md).
+
+## Qualification
+
+**Accepted for the production mechanical Model/Struct migration.** This is not
+whole-language X0 acceptance: the compatibility and dedicated-domain boundaries
+above remain explicit. The requested production path and motivating defects are
+repaired without a shadow-only admission layer.
+
+- Release solution build: zero errors (11 existing warnings in the qualification
+ build).
+- Fast Core lane: 1,068 passed.
+- Focused complete Firmament project: 2,236 passed.
+- Full solution, including the slow corpus: **4,675 passed, zero failed or skipped,
+ across 20 nonempty test projects**. FrictionLab's existing empty test assembly
+ discovers zero tests.
+- Real CLI admission witnesses: 4/4 have the expected, consistent validate/build
+ outcome. Both rejected intent-loss sources retain actionable original-token
+ diagnostics; Slot2 and the existing profile member-set selection are admitted.
+- Same-checkout pre-change STEP comparisons: **29/29 byte-identical**. The set
+ covers primitives, holes, edge finishes, Boss/Pocket, slots, profiles,
+ closed boundaries, PMI and the threaded bolt. Five additional historical X0
+ showcase comparisons also match (two overlap this set).
+- Ten real showcase CLI checks pass: threaded bolt, PMI, sheet metal, templates,
+ radial pattern (build/STEP); guitar, industrial ATLAS (assembly inspection);
+ warm-modern house, warehouse and factory (scene inspection). Inspection is not
+ being represented as an additional STEP export or interactive Helios session.
+
+The normal full run passed all CLI and then-current Firmament tests but hit three existing
+Core native display execution budgets. The final full lane uses the existing X0
+serial xUnit settings (`ParallelizeTestCollections=false`, `MaxParallelThreads=1`)
+and `RunConfiguration.MaxCpuCount=1`; all 4,675 tests pass without excluding tests,
+changing execution budgets or modifying kernel code. Raw failed and final runs
+remain separate in the ignored evidence directory.
+
+The dedicated quality pass checked ownership of field reads, duplicate and
+unconsumed fields, unsupported headers/variants, full consumption of bounded
+feature values, severity, V1 fallback, source locations, message propagation,
+parser/build duplication and global state. The existing parse cache is reused;
+no new global parser state, broad regex dispatch, global rewrite system or
+fatality allowlist was added. `git diff --check` passes. Existing tests asserting
+the old broken Slot2/Fillet behavior now assert actual production acceptance,
+rejection and geometry; tests do not require exact diagnostic sentences.
+
+The compact [evidence record](FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.evidence.json)
+contains the per-source hashes, outcome witnesses, showcase commands and complete
+project test totals. Raw output is under ignored
+`artifacts/local/mechanical-frontend-migration/`. The geometry/admission script
+uses the retained pre-change manifest or, when those ignored artifacts are absent,
+the recorded release hashes:
+
+```powershell
+dotnet build Aetheris.slnx -c Release -m:1 --no-restore
+./scripts/qualify-firmament-mechanical-frontend.ps1
+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter "Category!=SlowCorpus"
+dotnet test Aetheris.slnx -c Release --no-build -m:1 --settings artifacts/local/mechanical-frontend-migration/serial.runsettings -- RunConfiguration.MaxCpuCount=1
+```
+
+For a fresh checkout, create the ignored `serial.runsettings` used above with:
+
+```xml
+<RunSettings>
+ <RunConfiguration><MaxCpuCount>1</MaxCpuCount></RunConfiguration>
+ <xUnit>
+ <ParallelizeAssembly>false</ParallelizeAssembly>
+ <ParallelizeTestCollections>false</ParallelizeTestCollections>
+ <MaxParallelThreads>1</MaxParallelThreads>
+ </xUnit>
+</RunSettings>
+```
diff --git a/fixtures/Canonical/Scene/FactoryX0/kit.firmament b/fixtures/Canonical/Scene/FactoryX0/kit.firmament
index 67355443..c317c542 100644
--- a/fixtures/Canonical/Scene/FactoryX0/kit.firmament
+++ b/fixtures/Canonical/Scene/FactoryX0/kit.firmament
@@ -15,7 +15,21 @@ Template<L: Length, W: Length, H: Length> Struct Bin {
RoundedRect2 outer { center: [0mm, 0mm]; size: [L, W]; radius: 16mm; }
RoundedRect2 inner { center: [0mm, 0mm]; size: [L - 16mm, W - 16mm]; radius: 8mm; }
Profile base { Loop Outer { outer |> TraceLoop } }
- Profile rim { Loop Outer { outer |> TraceLoop } Loop Inner { inner |> TraceLoop } }
+ // The inner loop has distinct semantic segment identities from the outer wall.
+ Profile rim {
+ Loop Outer { outer |> TraceLoop }
+ Loop Inner {
+ Reverse inner.Bottom As InnerBottom
+ |> Reverse inner.BottomLeftCorner As InnerBottomLeftCorner
+ |> Reverse inner.Left As InnerLeft
+ |> Reverse inner.TopLeftCorner As InnerTopLeftCorner
+ |> Reverse inner.Top As InnerTop
+ |> Reverse inner.TopRightCorner As InnerTopRightCorner
+ |> Reverse inner.Right As InnerRight
+ |> Reverse inner.BottomRightCorner As InnerBottomRightCorner
+ |> Close
+ }
+ }
Extrude bottom { profile: base; from: 0mm; to: 8mm; }
Extrude sides { profile: rim; from: 8mm; to: H; }
}
diff --git a/fixtures/Regression/FrontendX1/README.md b/fixtures/Regression/FrontendX1/README.md
new file mode 100644
index 00000000..63ef1fee
--- /dev/null
+++ b/fixtures/Regression/FrontendX1/README.md
@@ -0,0 +1,19 @@
+# Unified frontend specimens (X1 foundation and production regressions)
+
+These are source syntax evidence, not manufacturing examples or proof of semantic
+admission. Nested Set and synthetic unrelated siblings deliberately exercise
+structure independently of the production routes. The existing FrontendX0
+specimens remain the authority for the two known production intent-loss witnesses.
+
+`lexical` preserves trivia and spelling; `expressions` fixes structural precedence;
+`nested-generics` fixes balanced parameter/argument structure; `malformed-field`
+requires rejection and recovery into the next declaration. The four `unrelated-*`
+files are inserted into a Model by metamorphic tests. These synthetic snippets
+remain syntax evidence; production admission is tested separately.
+
+`slot-route-perturbation` preserves the original route defect: before migration,
+removing Slot2 built on Canonical while including it selected CanonicalAdvanced
+and rejected. Both forms now use UnifiedMechanical and emit identical STEP.
+The original subtrees and admitted PascalCase fields remain in the specimen.
+The FrontendX0 ignored-Fillet and unknown-boundary-field witnesses now reject
+through the production AST admission path.
diff --git a/fixtures/Regression/FrontendX1/expressions.firmament b/fixtures/Regression/FrontendX1/expressions.firmament
new file mode 100644
index 00000000..8dcbd752
--- /dev/null
+++ b/fixtures/Regression/FrontendX1/expressions.firmament
@@ -0,0 +1,4 @@
+Static precedence: Float = 1 + 2 * 3 ^ 4;
+Static location: Point2 = Point2(Layout.Points[0].x + 2mm, -3mm);
+Static copy = Spec with { width: 8mm; };
+Static predicate: Bool = Count >= 2 && Count != 4 || false;
diff --git a/fixtures/Regression/FrontendX1/lexical.firmament b/fixtures/Regression/FrontendX1/lexical.firmament
new file mode 100644
index 00000000..a88170a3
--- /dev/null
+++ b/fixtures/Regression/FrontendX1/lexical.firmament
@@ -0,0 +1,4 @@
+/* A lossless source witness. */
+Static tiny: Length = 1e-3mm;
+Static label: String = "escaped \"quote\" and // not a comment";
+Static values: Float[] = [.5, 2.75, 3e+2]; // trailing trivia
diff --git a/fixtures/Regression/FrontendX1/malformed-field.firmament b/fixtures/Regression/FrontendX1/malformed-field.firmament
new file mode 100644
index 00000000..6a973a06
--- /dev/null
+++ b/fixtures/Regression/FrontendX1/malformed-field.firmament
@@ -0,0 +1,4 @@
+Model Broken {
+ Box Body { size: ; }
+ Box Retained { size: [8mm, 7mm, 6mm] }
+}
diff --git a/fixtures/Regression/FrontendX1/nested-generics.firmament b/fixtures/Regression/FrontendX1/nested-generics.firmament
new file mode 100644
index 00000000..c9d25323
--- /dev/null
+++ b/fixtures/Regression/FrontendX1/nested-generics.firmament
@@ -0,0 +1,7 @@
+// Structural evidence only: semantic admission of nested Set is intentionally X2.
+Template<T: Set<Set<Point2>>, D: Length = 3mm> Struct Family {
+ Static sites: Set<Set<Point2>> {
+ first => Point2(1mm, 2mm)
+ }
+ Struct Child = Product<Spec: Config<Points: T>, Depth: D>
+}
diff --git a/fixtures/Regression/FrontendX1/slot-route-perturbation.firmament b/fixtures/Regression/FrontendX1/slot-route-perturbation.firmament
new file mode 100644
index 00000000..4493781a
--- /dev/null
+++ b/fixtures/Regression/FrontendX1/slot-route-perturbation.firmament
@@ -0,0 +1,8 @@
+Model SlotRoutePerturbation {
+ Units: mm
+ Box Body { Size: [40mm, 20mm, 6mm] }
+ Modify Body {
+ Hole<Shaft> Shaft { On: +Z; Center: Point2(0mm, 0mm); Diameter: 4mm; End: ThroughAll }
+ }
+ Slot2 unrelatedSlot { Center: [0mm, 0mm]; Length: 12mm; Width: 3mm }
+}
diff --git a/fixtures/Regression/FrontendX1/unrelated-pattern.firmament b/fixtures/Regression/FrontendX1/unrelated-pattern.firmament
new file mode 100644
index 00000000..66b2b728
--- /dev/null
+++ b/fixtures/Regression/FrontendX1/unrelated-pattern.firmament
@@ -0,0 +1 @@
+Pattern unrelatedPattern Over sites { item => HoleRecipe(Center: item.point) }
diff --git a/fixtures/Regression/FrontendX1/unrelated-profile.firmament b/fixtures/Regression/FrontendX1/unrelated-profile.firmament
new file mode 100644
index 00000000..724aa2a2
--- /dev/null
+++ b/fixtures/Regression/FrontendX1/unrelated-profile.firmament
@@ -0,0 +1 @@
+Profile unrelatedProfile Using XY { Loop Outer { Guide.Bottom |> Guide.Right |> Guide.Top |> Guide.Left |> Close } }
diff --git a/fixtures/Regression/FrontendX1/unrelated-slot.firmament b/fixtures/Regression/FrontendX1/unrelated-slot.firmament
new file mode 100644
index 00000000..ad2b4ae3
--- /dev/null
+++ b/fixtures/Regression/FrontendX1/unrelated-slot.firmament
@@ -0,0 +1 @@
+Slot2 unrelatedSlot { Center: [0mm, 0mm]; Length: 12mm; Width: 3mm }
diff --git a/fixtures/Regression/FrontendX1/unrelated-static.firmament b/fixtures/Regression/FrontendX1/unrelated-static.firmament
new file mode 100644
index 00000000..18916489
--- /dev/null
+++ b/fixtures/Regression/FrontendX1/unrelated-static.firmament
@@ -0,0 +1,2 @@
+Record Position { point: Point2 }
+Static sites: Set<Position> { first => Position { point: Point2(1mm, 2mm) } }
diff --git a/scripts/qualify-firmament-frontend-x1.ps1 b/scripts/qualify-firmament-frontend-x1.ps1
new file mode 100644
index 00000000..748770d4
--- /dev/null
+++ b/scripts/qualify-firmament-frontend-x1.ps1
@@ -0,0 +1,39 @@
+param([string]$OutputDirectory = 'artifacts/local/frontend-x1')
+$ErrorActionPreference = 'Stop'
+$cli = Join-Path $PSScriptRoot '../Aetheris.CLI/bin/Release/net10.0/aetheris.dll'
+$repo = Split-Path $PSScriptRoot -Parent
+Push-Location $repo
+try {
+ New-Item -ItemType Directory -Force $OutputDirectory | Out-Null
+ dotnet $cli frontend-shadow --corpus fixtures --output-dir (Join-Path $OutputDirectory 'corpus')
+ if ($LASTEXITCODE -ne 0) { throw 'Shadow corpus collection did not complete.' }
+ $witnesses = @(
+ 'Regression/FrontendX0/unknown-compose-statement.firmament',
+ 'Regression/FrontendX0/unknown-boundary-field.firmament',
+ 'Regression/FrontendX1/slot-route-perturbation.firmament',
+ 'Regression/CanonicalGeometry/profile-chamfer-reflex-junction-top.firmament',
+ 'Regression/ProfileComposition/valid/semantic-split-compose-chamfer.firmament'
+ )
+ foreach ($relative in $witnesses) {
+ $name = [IO.Path]::GetFileNameWithoutExtension($relative)
+ dotnet $cli frontend-shadow (Join-Path 'fixtures' $relative) --json --validate > (Join-Path $OutputDirectory "$name-shadow.json")
+ # Rejection is evidence. Each file preserves both statuses and located diagnostics.
+ dotnet $cli build (Join-Path 'fixtures' $relative) --output (Join-Path $OutputDirectory "$name.step") --json > (Join-Path $OutputDirectory "$name-build.json")
+ }
+ $benchmarks = @(
+ 'fixtures/Canonical/Basics/box.firmament',
+ 'fixtures/Regression/FrontendX0/unknown-compose-statement.firmament',
+ 'fixtures/Canonical/Templates/nested-template-pmi.firmament',
+ 'fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar-x0.firmament',
+ 'fixtures/Canonical/Scene/WarmModernHouse/house.firmament'
+ )
+ $largest = Get-ChildItem fixtures -Recurse -File -Filter '*.firmament' | Sort-Object Length -Descending | Select-Object -First 1
+ $benchmarks += $largest.FullName
+ $results = foreach ($source in $benchmarks) {
+ $raw = dotnet $cli frontend-shadow $source --json --benchmark
+ if ([string]::IsNullOrWhiteSpace($raw)) { throw "No shadow evidence for $source" }
+ $entry = $raw | ConvertFrom-Json
+ [pscustomobject]@{ source = [IO.Path]::GetRelativePath($repo, [IO.Path]::GetFullPath($source)); shadowStatus = $entry.shadow.shadowStatus; benchmark = $entry.benchmark }
+ }
+ $results | ConvertTo-Json -Depth 10 | Set-Content (Join-Path $OutputDirectory 'benchmarks.json') -Encoding utf8
+} finally { Pop-Location }
diff --git a/scripts/qualify-firmament-mechanical-frontend.ps1 b/scripts/qualify-firmament-mechanical-frontend.ps1
new file mode 100644
index 00000000..a722ef5d
--- /dev/null
+++ b/scripts/qualify-firmament-mechanical-frontend.ps1
@@ -0,0 +1,51 @@
+param(
+ [string]$OutputDirectory = 'artifacts/local/mechanical-frontend-migration',
+ [string]$BaselineDirectory = 'artifacts/local/mechanical-frontend-migration/before'
+)
+$ErrorActionPreference = 'Stop'
+$repo = Split-Path $PSScriptRoot -Parent
+$cli = Join-Path $repo 'Aetheris.CLI/bin/Release/net10.0/aetheris.dll'
+Push-Location $repo
+try {
+ $afterDirectory = Join-Path $OutputDirectory 'after'
+ New-Item -ItemType Directory -Force $afterDirectory | Out-Null
+ $baselineManifest = Join-Path $BaselineDirectory 'summary.json'
+ if (Test-Path -LiteralPath $baselineManifest) {
+ $baseline = Get-Content -LiteralPath $baselineManifest -Raw | ConvertFrom-Json
+ } else {
+ # The versioned release evidence retains the hashes when ignored pre-change
+ # STEP artifacts are unavailable (for example, in a fresh checkout).
+ $evidence = Get-Content 'docs/release/FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.evidence.json' -Raw | ConvertFrom-Json
+ $baseline = foreach ($case in $evidence.geometryComparisons) {
+ [pscustomobject]@{ source = $case.source; step = $case.artifactName; exit = $case.beforeExit; sha256 = $case.beforeSha256 }
+ }
+ }
+ $comparison = foreach ($case in $baseline) {
+ $name = [IO.Path]::GetFileName($case.step)
+ $step = Join-Path $afterDirectory $name
+ & dotnet $cli build $case.source --output $step --json | Set-Content (Join-Path $afterDirectory "$name.json") -Encoding utf8
+ $exitCode = $LASTEXITCODE
+ $hash = if ($exitCode -eq 0) { (Get-FileHash -LiteralPath $step -Algorithm SHA256).Hash.ToLowerInvariant() } else { $null }
+ [pscustomobject]@{ source = $case.source; beforeExit = $case.exit; afterExit = $exitCode; beforeSha256 = $case.sha256; afterSha256 = $hash; identical = $case.sha256 -eq $hash -and $exitCode -eq $case.exit }
+ }
+ $comparison | ConvertTo-Json -Depth 8 | Set-Content (Join-Path $OutputDirectory 'geometry-comparison.json') -Encoding utf8
+ $witnesses = @(
+ @{ path = 'fixtures/Regression/FrontendX0/unknown-compose-statement.firmament'; accepted = $false },
+ @{ path = 'fixtures/Regression/FrontendX0/unknown-boundary-field.firmament'; accepted = $false },
+ @{ path = 'fixtures/Regression/FrontendX1/slot-route-perturbation.firmament'; accepted = $true },
+ @{ path = 'fixtures/Regression/CanonicalGeometry/profile-chamfer-reflex-junction-top.firmament'; accepted = $true }
+ )
+ $admission = foreach ($case in $witnesses) {
+ $name = [IO.Path]::GetFileNameWithoutExtension($case.path)
+ & dotnet $cli validate $case.path --explain --json | Set-Content (Join-Path $afterDirectory "$name-validate.json") -Encoding utf8
+ $validateExit = $LASTEXITCODE
+ & dotnet $cli build $case.path --output (Join-Path $afterDirectory "$name.step") --json | Set-Content (Join-Path $afterDirectory "$name-build.json") -Encoding utf8
+ $buildExit = $LASTEXITCODE
+ [pscustomobject]@{ source = $case.path; expectedAccepted = $case.accepted; validateExit = $validateExit; buildExit = $buildExit; consistent = $validateExit -eq $buildExit -and (($buildExit -eq 0) -eq $case.accepted) }
+ }
+ $admission | ConvertTo-Json -Depth 8 | Set-Content (Join-Path $OutputDirectory 'admission-comparison.json') -Encoding utf8
+ $changed = @($comparison | Where-Object { -not $_.identical })
+ $contradictions = @($admission | Where-Object { -not $_.consistent })
+ Write-Output "Geometry: $($comparison.Count - $changed.Count)/$($comparison.Count) identical STEP hashes; admission: $($admission.Count - $contradictions.Count)/$($admission.Count) consistent."
+ if ($changed.Count -gt 0 -or $contradictions.Count -gt 0) { throw 'Mechanical frontend qualification failed; inspect the JSON evidence.' }
+} finally { Pop-Location }