Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Close discarded intent at frontend owners and align CLI admission
Yuechen Li807f05bc1f99
diff --git a/Aetheris.CLI.Tests/ReleaseAdmissionRegressionTests.cs b/Aetheris.CLI.Tests/ReleaseAdmissionRegressionTests.csnew file mode 100644index 00000000..e6b617c0--- /dev/null+++ b/Aetheris.CLI.Tests/ReleaseAdmissionRegressionTests.cs@@ -0,0 +1,111 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class ReleaseAdmissionRegressionTests+{+ [Theory]+ [InlineData("Learn/06-post-on-plate.firmament", "to: height }", "to: height; zzUnknownField: 1mm }")]+ [InlineData("Learn/06-post-on-plate.firmament", "Semantic Foot {", "Semantic Foot { zzUnknownField: 1mm;")]+ [InlineData("Learn/06-post-on-plate.firmament", "anchor: PostOnPlate.Plate;", "anchor: PostOnPlate.Plate; zzUnknownField: 1mm;")]+ [InlineData("SectionChain/explicit-sketch-ruled.firmament", "position: [2mm, -2mm]", "position: [2mm, -2deg]")]+ [InlineData("SectionChain/explicit-sketch-ruled.firmament", "Point2 B { position: [2mm, -2mm] }", "Point2 B { position: [2mm, -2mm]; zzUnknownField: 1mm }")]+ [InlineData("WireForm/straight-wire.firmament", "Straight Body {", "Straight Body { zzUnknownField: 1mm;")]+ [InlineData("WireForm/straight-wire.firmament", "StartFrame {", "StartFrame { zzUnknownField: 1mm;")]+ [InlineData("WireForm/straight-wire.firmament", "WireForm Wire {", "WireForm Wire { zzUnknownField: 1mm;")]+ [InlineData("WireForm/straight-wire.firmament", "Model StraightWire {", "Model StraightWire { zzUnknownField: 1mm;")]+ [InlineData("WireForm/straight-wire.firmament", "Tangent: [1, 0, 0]", "Tangent: [1mm, 0, 0]")]+ [InlineData("Assembly/annular-pair.firmament", "<Part First = Sleeve<R: 20mm>>", "<Part First = Sleeve<R: 20mm>> zzUnknownField: 1mm;")]+ [InlineData("Learn/06-post-on-plate.firmament", "expose {", "expose { zzUnknownField: 1mm;")]+ [InlineData("SectionChain/explicit-sketch-ruled.firmament", "Loop Outer {", "Loop Outer { zzUnknownField: 1mm;")]+ [InlineData("Span/line-pipeline.firmament", "Span<Line> MountingEdge {", "Span<Line> MountingEdge { zzUnknownField: 1mm;")]+ [InlineData("Features/EdgeFinish/single-edge-fillet.firmament", "Modify Body {", "Modify Body { zzUnknownField: 1mm;")]+ [InlineData("Offset/prism-pad.firmament", "AddOffset<Prism> LocalPad {", "AddOffset<Prism> LocalPad { zzUnknownField: 1mm;")]+ [InlineData("Offset/prism-pad.firmament", "Height: 3mm", "Height: 3mm; Axis: +Z; Along: -Z")]+ [InlineData("Offset/prism-pad.firmament", "Height: 3mm", "Height: 3mm; Axis: WrongDirection")]+ public void UnconsumedIntentAndWrongDimensionsRejectBothCommands(string fixture, string original, string replacement)+ {+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures/Canonical", fixture));+ Assert.Contains(original, source);+ var directory = Directory.CreateTempSubdirectory("aetheris-release-admission-").FullName;+ try+ {+ var path = Path.Combine(directory, "case.firmament");+ File.WriteAllText(path, source);+ Assert.Equal(0, Run("validate", path).Exit);+ Assert.Equal(0, Run("build", path, Path.Combine(directory, "control.step")).Exit);+ File.WriteAllText(path, source.Replace(original, replacement, StringComparison.Ordinal));+ var output = Path.Combine(directory, "invalid.step");+ foreach (var verb in new[] { "validate", "build" })+ {+ var result = Run(verb, path, output);+ Assert.NotEqual(0, result.Exit);+ Assert.False(File.Exists(output));+ Assert.DoesNotContain("Unhandled exception", result.Output);+ using var json = JsonDocument.Parse(result.Output);+ }+ }+ finally { Directory.Delete(directory, true); }+ }++ [Fact]+ public void NativeV2RootCaseAliasPreservesGeometryAndOwner()+ {+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures/Canonical/EquationCurves/circle.firmament"));+ var directory = Directory.CreateTempSubdirectory("aetheris-root-alias-").FullName;+ try+ {+ var path = Path.Combine(directory, "circle.firmament");+ var steps = new List<string>();+ foreach (var text in new[] { source, source.Replace("Model RoundPlate", "model RoundPlate") })+ {+ File.WriteAllText(path, text);+ Assert.Equal(0, Run("validate", path).Exit);+ var output = Path.Combine(directory, $"{steps.Count}.step");+ var build = Run("build", path, output);+ Assert.Equal(0, build.Exit);+ using var json = JsonDocument.Parse(build.Output);+ Assert.Equal("RoundPlate", json.RootElement.GetProperty("model").GetString());+ steps.Add(File.ReadAllText(output));+ }+ Assert.Equal(steps[0], steps[1]);+ }+ finally { Directory.Delete(directory, true); }+ }++ [Theory]+ [InlineData("build")]+ [InlineData("measure")]+ [InlineData("verify")]+ [InlineData("format")]+ [InlineData("lock")]+ [InlineData("mesh")]+ public void MissingInputRetainsStructuredActionableDiagnostic(string verb)+ {+ var missing = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".firmament");+ var result = Run(verb, missing);+ Assert.Equal(1, result.Exit);+ using var json = JsonDocument.Parse(result.Output);+ var diagnostic = json.RootElement.GetProperty("diagnostics")[0];+ Assert.Equal("source-file-not-found", diagnostic.GetProperty("code").GetString());+ Assert.Contains(missing, diagnostic.GetProperty("message").GetString());+ Assert.Equal(missing, diagnostic.GetProperty("sourceFile").GetString());+ Assert.Equal(JsonValueKind.Null, diagnostic.GetProperty("sourceSpan").ValueKind);+ }++ private static (int Exit, string Output) Run(string verb, string path, string? output = null)+ {+ var stdout = new StringWriter();+ var stderr = new StringWriter();+ var args = new List<string> { verb, path, "--json" };+ if (verb == "build" && output is not null) args.AddRange(["--out", output]);+ return (CliRunner.Run(args.ToArray(), stdout, stderr), stdout.ToString());+ }++ private static string Root()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ return directory?.FullName ?? throw new DirectoryNotFoundException();+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex f86c09e0..61acc091 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -260,6 +260,16 @@ public static class CliRunner_ => UnknownCommand(args[0], stderr)};}+ catch (FileNotFoundException ex)+ {+ var diagnostic = new FirmamentV2ValidationDiagnostic("source-file-not-found", "error",+ $"Source or referenced input file '{ex.FileName}' was not found. Check the path and the working directory.")+ { SourceFile = ex.FileName, Stage = "Input", LocationNote = "No source span is available because the file could not be opened." };+ if (args.Contains("--json", StringComparer.Ordinal))+ stdout.WriteLine(JsonSerializer.Serialize(new { command = args[0], success = false, diagnostics = new[] { diagnostic } }, JsonOptions));+ else stderr.WriteLine($"{ex.FileName}: error {diagnostic.Code}: {diagnostic.Message}");+ return 1;+ }catch (Exception ex){stderr.WriteLine(ex.Message);@@ -502,13 +512,16 @@ public static class CliRunner}}+ FirmamentCommandDomain? domain = null;if (File.Exists(sourcePath)){if (!DependencyLockCommand.Verify(sourcePath, locked, json, stdout, stderr, JsonOptions, "build")) return 1;var source = File.ReadAllText(sourcePath);var frontend = FirmamentFrontendSchemas.Select(source);if (!frontend.IsSuccess) return WriteFrontendRejection(frontend, source, sourcePath, "build", json, stdout, stderr);- if((FirmamentDrawingCompiler.IsDrawingSource(source)||FirmamentAnalysisCompiler.IsAnalysisSource(source)) && outPath is not null && Path.GetExtension(outPath).Equals(".step",StringComparison.OrdinalIgnoreCase))+ source = frontend.Source;+ domain = FirmamentCommandRouting.Select(source, sourcePath, frontend.Schema);+ if((domain == FirmamentCommandDomain.Drawing||domain == FirmamentCommandDomain.Analysis) && outPath is not null && Path.GetExtension(outPath).Equals(".step",StringComparison.OrdinalIgnoreCase)){var diagnostic=FirmamentBuildAdmissionValidation.Present(new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Error,"firmament-product-output-directory-required: Drawing and Analysis builds produce artifact directories. Use --out <directory>; export the geometry source separately for STEP.","Firmament.Build"),sourcePath,source);@@ -516,24 +529,24 @@ public static class CliRunnerelse stderr.WriteLine($"{sourcePath}:{diagnostic.Line}:{diagnostic.Column}: {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");return 1;}- if(FirmamentDrawingCompiler.IsDrawingSource(source))+ if(domain == FirmamentCommandDomain.Drawing)return RunDrawing(["compile",sourcePath,"--out-dir",outPath??Path.GetFullPath(Path.Combine("artifacts","local","drawing",Path.GetFileNameWithoutExtension(sourcePath))),..(json?new[]{"--json"}:[])],stdout,stderr);- if (FirmamentAnalysisCompiler.IsAnalysisSource(source))+ if (domain == FirmamentCommandDomain.Analysis)return RunFea([sourcePath,"--out-dir",outPath??Path.GetFullPath(Path.Combine("artifacts","local","analysis",Path.GetFileNameWithoutExtension(sourcePath))),..(json?new[]{"--json"}:[])],stdout,stderr);- if (Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.HasRoot(source))+ if (domain == FirmamentCommandDomain.Garment){ stderr.WriteLine("garment-step-export-unsupported: Fabric is a material-space surface; use garment build or garment drape."); return 1; }- if (Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(source))+ if (domain == FirmamentCommandDomain.Scene){ stderr.WriteLine("scene-step-export-unsupported: Scene is a spatial product; use scene export-usd or scene export-glb."); return 1; }- if (Path.GetExtension(sourcePath).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(source, sourcePath))+ if (domain == FirmamentCommandDomain.Assembly)return RunAsmExportAp242([sourcePath, "--out", outPath ?? Path.GetFullPath(Path.Combine("artifacts", "local", "build", Path.GetFileNameWithoutExtension(sourcePath) + ".step")), .. (json ? new[] { "--json" } : [])], stdout, stderr);- if (SectionChainAuthoringParser.IsSectionChainSource(source))+ if (domain == FirmamentCommandDomain.SectionChain)return RunSectionChain(["build", sourcePath, .. (outPath is null ? Array.Empty<string>() : ["--out", outPath]), .. (json ? new[] { "--json" } : [])], stdout, stderr);}- if (File.Exists(sourcePath) && PlasticShellFirmament.LooksLikePlasticShell(File.ReadAllText(sourcePath)))+ if (domain == FirmamentCommandDomain.PlasticShell)return RunPlasticShellBuild(sourcePath, outPath, json, stdout, stderr);- if (File.Exists(sourcePath) && SheetMetalFirmament.LooksLikeSheetMetal(File.ReadAllText(sourcePath)))+ if (domain == FirmamentCommandDomain.SheetMetal)return RunSheetMetalAuthoredBuild(sourcePath, outPath, json, stdout, stderr);- if (File.Exists(sourcePath) && SculptingAuthoring.IsSculptingSource(File.ReadAllText(sourcePath)))+ if (domain == FirmamentCommandDomain.Sculpting)return RunSculptingBuild(sourcePath, outPath, json, stdout, stderr);var build = FirmamentBuildAndExport.Run(sourcePath, outPath);@@ -2480,7 +2493,9 @@ Model CanonicalPanel {var authoredValidationSource = validationSource;var frontend = FirmamentFrontendSchemas.Select(validationSource);if (!frontend.IsSuccess) return WriteFrontendRejection(frontend, validationSource, sourcePath, "validate", json, stdout, stderr);- if(FirmamentDrawingCompiler.IsDrawingSource(validationSource))+ validationSource = frontend.Source;+ var domain = FirmamentCommandRouting.Select(validationSource, sourcePath, frontend.Schema);+ if(domain == FirmamentCommandDomain.Drawing){if (parseOnly) return RejectParseOnly("Drawing");var output=Path.GetFullPath(Path.Combine("artifacts","local","drawing-validation",Guid.NewGuid().ToString("N")));@@ -2495,7 +2510,7 @@ Model CanonicalPanel {}finally {if(Directory.Exists(output))Directory.Delete(output,true);}}- if (FirmamentAnalysisCompiler.IsAnalysisSource(validationSource))+ if (domain == FirmamentCommandDomain.Analysis){if (parseOnly) return RejectParseOnly("Analysis");var analysis=FirmamentAnalysisCompiler.Compile(frontend.Source,Path.GetFullPath(sourcePath),Path.GetDirectoryName(Path.GetFullPath(sourcePath)));@@ -2505,12 +2520,12 @@ Model CanonicalPanel {else {stdout.WriteLine(analysis.IsSuccess?"Analysis bound; solver execution has not been validated.":"Analysis rejected.");foreach(var d in diagnostics)stderr.WriteLine($"{d.SourceFile}:{d.Line}:{d.Column}: {d.Severity} {d.Code}: {d.Message}");}return analysis.IsSuccess?0:1;}- if (Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.HasRoot(validationSource)+ if (domain == FirmamentCommandDomain.Garment|| frontend.Schema == FirmamentFrontendSchema.Garment){if (parseOnly){- var garment = Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.Parse(validationSource, Path.GetFullPath(sourcePath));+ var garment = Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.Parse(authoredValidationSource, Path.GetFullPath(sourcePath));var diagnostics = garment.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, d.Code + ": " + d.Message, "Firmament.Garment"), sourcePath, validationSource)).ToArray();var payload = new { source = sourcePath, status = garment.IsSuccess ? "parsed-not-built" : "invalid", domain = "Garment",@@ -2521,7 +2536,7 @@ Model CanonicalPanel {}return GarmentCommand.Run(["inspect", sourcePath, .. (json ? new[] { "--json" } : Array.Empty<string>())], stdout, stderr);}- if (FirmamentLanguageAnalysisService.HasAssemblyRoot(validationSource, sourcePath))+ if (domain == FirmamentCommandDomain.Assembly){var sheetMetalAssembly = validationSource.Contains("Use SheetMetal.ProductFamilies", StringComparison.Ordinal);var parsedAssembly = parseOnly ? sheetMetalAssembly@@ -2536,7 +2551,7 @@ Model CanonicalPanel {else { stdout.WriteLine(validAssembly ? "Assembly admitted." : "Assembly rejected."); foreach(var d in payload.diagnostics) stderr.WriteLine(d.Code+": "+d.Message); }return validAssembly ? 0 : 1;}- if (Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(validationSource))+ if (domain == FirmamentCommandDomain.Scene){using var sceneSession = new Aetheris.Kernel.Firmament.Scene.FirmamentSceneSession();var parsedScene = parseOnly ? Aetheris.Kernel.Firmament.Scene.SceneAuthoring.Parse(validationSource,Path.GetFullPath(sourcePath)) : null;@@ -2548,7 +2563,7 @@ Model CanonicalPanel {return sceneValid ? 0 : 1;}validationSource = frontend.Source;- if (PlasticShellFirmament.LooksLikePlasticShell(validationSource))+ if (domain == FirmamentCommandDomain.PlasticShell){if (parseOnly) return RejectParseOnly("PlasticShell");var plastic = PlasticShellFirmament.Compile(validationSource, Path.GetFullPath(sourcePath));@@ -2557,7 +2572,7 @@ Model CanonicalPanel {else {stdout.WriteLine($"PlasticShell validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, {payload.summary.warningDiagnosticCount} warning)");WriteFrontendDiagnostics(payload.diagnostics,stderr);}return plastic.IsSuccess ? 0 : 1;}- if (SculptingAuthoring.IsSculptingSource(validationSource))+ if (domain == FirmamentCommandDomain.Sculpting){if (parseOnly) return RejectParseOnly("Sculpting");var sculpt = SculptingAuthoring.Compile(validationSource,Path.GetFullPath(sourcePath));@@ -2566,7 +2581,7 @@ Model CanonicalPanel {else {stdout.WriteLine($"Firmament V2 Sculpting validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");WriteFrontendDiagnostics(payload.diagnostics,stderr);}return sculpt.IsSuccess ? 0 : 1;}- if (PlateauAuthoring.IsSource(validationSource) && !System.Text.RegularExpressions.Regex.IsMatch(validationSource, @"\bAssembly\s+"))+ if (domain == FirmamentCommandDomain.Plateau){if (parseOnly) return RejectParseOnly("Plateau");var plateau = FirmamentBuildAndExport.CompileSource(validationSource, Path.GetDirectoryName(Path.GetFullPath(sourcePath)));@@ -2575,7 +2590,7 @@ Model CanonicalPanel {else stdout.WriteLine($"Plateau validation: {payload.status}");return plateau.IsSuccess ? 0 : 1;}- if (PipingAuthoring.IsPipingSource(validationSource))+ if (domain == FirmamentCommandDomain.Piping){if (parseOnly) return RejectParseOnly("Piping");var piping = PipingAuthoring.Compile(validationSource, Path.GetFullPath(sourcePath));@@ -2588,7 +2603,7 @@ Model CanonicalPanel {}return piping.IsSuccess ? 0 : 1;}- if (StructuralAuthoring.IsStructuralSource(validationSource))+ if (domain == FirmamentCommandDomain.Structural){if (parseOnly){@@ -2607,7 +2622,7 @@ Model CanonicalPanel {else {stdout.WriteLine($"Firmament V2 Structural validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");WriteFrontendDiagnostics(payload.diagnostics,stderr);}return structural.IsSuccess ? 0 : 1;}- if (frontend.Schema == FirmamentFrontendSchema.SectionChain)+ if (domain == FirmamentCommandDomain.SectionChain){var section = SectionChainAuthoringParser.CompileFile(sourcePath, materialize: !parseOnly);var diagnostics = section.Diagnostics.Select(message => FirmamentBuildAdmissionValidation.Present(new KernelDiagnostic(@@ -2619,7 +2634,7 @@ Model CanonicalPanel {else stdout.WriteLine($"Firmament V2 SectionChain validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");return section.IsSuccess ? 0 : 1;}- if (WireFormAuthoring.IsWireFormSource(validationSource))+ if (domain == FirmamentCommandDomain.WireForm){var wireSource = ExpandSweepInspectionSource(validationSource, out var expansionDiagnostics);var authored = wireSource is null ? null : WireFormAuthoring.Parse(wireSource);@@ -2645,7 +2660,7 @@ Model CanonicalPanel {}return valid ? 0 : 1;}- if (CircularSweepAuthoring.IsSweepSource(validationSource))+ if (domain == FirmamentCommandDomain.Sweep){var sweepSource = ExpandSweepInspectionSource(validationSource, out var sweepExpansionDiagnostics);var authored = sweepSource is null ? null : CircularSweepAuthoring.Parse(sweepSource);@@ -2672,7 +2687,7 @@ Model CanonicalPanel {}return valid ? 0 : 1;}- if(SheetMetalFirmament.LooksLikeSheetMetal(validationSource))+ if(domain == FirmamentCommandDomain.SheetMetal){var sheet=SheetMetalFirmament.Compile(validationSource,Path.GetFullPath(sourcePath));var status=sheet.IsSuccess?"valid":"invalid";diff --git a/Aetheris.CLI/FirmamentCommandRouting.cs b/Aetheris.CLI/FirmamentCommandRouting.csnew file mode 100644index 00000000..1ea68806--- /dev/null+++ b/Aetheris.CLI/FirmamentCommandRouting.cs@@ -0,0 +1,42 @@+using Aetheris.FEA.Firmament;+using Aetheris.Kernel.Firmament;+using Aetheris.Kernel.Firmament.Drawing;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Materializer;+using Aetheris.Kernel.Firmament.Piping;+using Aetheris.Kernel.Firmament.Structural;+using Aetheris.PlasticShell;+using Aetheris.SheetMetal;+using Aetheris.Surfacing;++namespace Aetheris.CLI;++internal enum FirmamentCommandDomain+{+ Mechanical, Drawing, Analysis, Garment, Assembly, Scene, PlasticShell,+ Sculpting, Plateau, Piping, Structural, SectionChain, WireForm, Sweep, SheetMetal+}++/// <summary>One command-level selection order. Parsing and capability admission+/// remain with the existing compiler/domain owners.</summary>+internal static class FirmamentCommandRouting+{+ public static FirmamentCommandDomain Select(string source, string path, FirmamentFrontendSchema? schema)+ {+ if (FirmamentDrawingCompiler.IsDrawingSource(source)) return FirmamentCommandDomain.Drawing;+ if (FirmamentAnalysisCompiler.IsAnalysisSource(source)) return FirmamentCommandDomain.Analysis;+ if (Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.HasRoot(source)) return FirmamentCommandDomain.Garment;+ if (Path.GetExtension(path).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(source, path)) return FirmamentCommandDomain.Assembly;+ if (Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(source)) return FirmamentCommandDomain.Scene;+ if (PlasticShellFirmament.LooksLikePlasticShell(source)) return FirmamentCommandDomain.PlasticShell;+ if (SculptingAuthoring.IsSculptingSource(source)) return FirmamentCommandDomain.Sculpting;+ if (PlateauAuthoring.IsSource(source)) return FirmamentCommandDomain.Plateau;+ if (PipingAuthoring.IsPipingSource(source)) return FirmamentCommandDomain.Piping;+ if (StructuralAuthoring.IsStructuralSource(source)) return FirmamentCommandDomain.Structural;+ if (schema == FirmamentFrontendSchema.SectionChain || SectionChainAuthoringParser.IsSectionChainSource(source)) return FirmamentCommandDomain.SectionChain;+ if (WireFormAuthoring.IsWireFormSource(source)) return FirmamentCommandDomain.WireForm;+ if (CircularSweepAuthoring.IsSweepSource(source)) return FirmamentCommandDomain.Sweep;+ if (SheetMetalFirmament.LooksLikeSheetMetal(source)) return FirmamentCommandDomain.SheetMetal;+ return FirmamentCommandDomain.Mechanical;+ }+}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyAppearanceAuthoring.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyAppearanceAuthoring.csindex 13f07578..779c407a 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyAppearanceAuthoring.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyAppearanceAuthoring.cs@@ -94,6 +94,8 @@ internal static class AssemblyAppearanceAuthoringreturn fields.Count == 1 ? new(fields[0].Groups["material"].Value, fields[0].Groups["look"].Success ? fields[0].Groups["look"].Value : null) : null;}+ internal static bool OwnsSelectionField(string name) => FirmamentV2.Syntax.FirmamentSyntaxFields.SameField(name, "Material");+internal static AssemblyIr Bind(AssemblyIr ir, AssemblyAppearanceCatalog? catalog, List<AssemblyDiagnostic> diagnostics){// Locally solved subassemblies retain selections until the root catalog binds them.diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.csindex 2d701f92..9d07f494 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs@@ -89,6 +89,27 @@ public sealed class AssemblyM0Parserif (!syntax.IsSuccess)return new(null, syntax.Diagnostics.Select(d => new AssemblyDiagnostic(d.Code, d.Message){ SourceSpan = d.SourceSpan is { } span ? new(sourceIdentity, span.Start, span.Length) : null }).ToArray(), watch.Elapsed.TotalMilliseconds);+ foreach (var declaration in FirmamentSyntaxTraversal.Declarations(syntax.Document))+ {+ if (declaration.Occurrence)+ foreach (var field in declaration.Body?.Statements.OfType<FieldSyntax>() ?? [])+ if (!AssemblyAppearanceAuthoring.OwnsSelectionField(field.Name.Text))+ diagnostics.Add(AssemblyInterfaceSyntax.Diagnostic("assembly-occurrence-field-unknown",+ $"Unknown field '{field.Name.Text}' on occurrence '{declaration.Name?.Text}'.", sourceIdentity, field.Name.Span));+ if (declaration.Type.Name.Text is "Assembly" or "Subassembly")+ {+ // Anchor is the field consumed by this owner. Product declarations,+ // mates, layouts and motion clauses have their own binders below.+ var fields = declaration.Body?.Statements.OfType<FieldSyntax>().ToArray() ?? [];+ foreach (var field in fields.Where(f => !FirmamentSyntaxFields.SameField(f.Name.Text, "Anchor") && !AssemblyPmiAuthoring.OwnsRootField(f.Name.Text)))+ diagnostics.Add(AssemblyInterfaceSyntax.Diagnostic("assembly-field-unknown",+ $"Unknown field '{field.Name.Text}' in {declaration.Type.Name.Text} '{declaration.Name?.Text}'.", sourceIdentity, field.Span));+ if (fields.Count(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Anchor")) > 1)+ diagnostics.Add(AssemblyInterfaceSyntax.Diagnostic("assembly-field-duplicate", "Anchor may be declared only once.", sourceIdentity, declaration.Span));+ }+ }+ AssemblyPublishedPorts.ValidatePublicationSyntax(syntax.Document, sourceIdentity, diagnostics);+ if (diagnostics.Count > 0) return new(null, diagnostics, watch.Elapsed.TotalMilliseconds);input = FirmamentSourceSpelling.Normalize(input);var blankcommentsPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("m0.blank-comments");var source = Regex.Replace(input, "\"(?:\\\\.|[^\"\\\\])*\"|//[^\\r\\n]*", m => m.Value.StartsWith('"') ? m.Value : new string(' ',m.Length));diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyPmiAuthoring.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyPmiAuthoring.csindex 1b25e993..d06cf964 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyPmiAuthoring.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyPmiAuthoring.cs@@ -1,5 +1,6 @@using System.Text.Json;using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.Core.Step242;using Aetheris.Semantics;@@ -25,6 +26,7 @@ public static class AssemblyPmiNoteDeclaration { }/// this seam only selects that data and binds annotation owners, without manufacturing geometry.</summary>internal static class AssemblyPmiAuthoring{+ internal static bool OwnsRootField(string name) => FirmamentSyntaxFields.SameField(name, "Provenance");internal static AssemblyAnnotations Parse(ref string source, string identity, List<AssemblyDiagnostic> diagnostics){var original = source;@@ -36,7 +38,7 @@ internal static class AssemblyPmiAuthoringvar notes = new List<AssemblyPmiNote>();AssemblyReleaseRecord? release = null;var fields = roots[0].Body!.Statements.OfType<Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FieldSyntax>()- .Where(f => f.Name.Text is "Provenance" or "provenance").ToArray();+ .Where(f => OwnsRootField(f.Name.Text)).ToArray();if (fields.Length > 1) Error("provenance-selection-invalid", "Select one release Record.", roots[0].Span);foreach (var selection in fields){diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.csindex c4f10853..e7269f3a 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyPublishedPorts.cs@@ -145,6 +145,7 @@ internal static class AssemblyPublishedPortsinternal static string Strip(string source, List<AssemblyDiagnostic> diagnostics){source = FirmamentSourceSpelling.Normalize(source);+ ValidatePublicationSyntax(FirmamentSyntaxParser.Parse(source).Document, "<part>", diagnostics);var chars = source.ToCharArray();foreach (Match expose in Regex.Matches(source,@"\bExpose\s*\{")){@@ -155,10 +156,35 @@ internal static class AssemblyPublishedPortsreturn new(chars);}+ internal static void ValidatePublicationSyntax(DocumentSyntax syntax, string identity, List<AssemblyDiagnostic> diagnostics)+ => ValidatePublicationSyntax(FirmamentSyntaxTraversal.Declarations(syntax), identity, diagnostics);++ internal static void ValidatePublicationSyntax(DeclarationSyntax syntax, string identity, List<AssemblyDiagnostic> diagnostics)+ => ValidatePublicationSyntax(FirmamentSyntaxTraversal.Declarations(syntax), identity, diagnostics);++ private static void ValidatePublicationSyntax(IEnumerable<DeclarationSyntax> declarations, string identity, List<AssemblyDiagnostic> diagnostics)+ {+ foreach (var declaration in declarations)+ {+ if (declaration.Type.Name.Text == "Semantic")+ foreach (var statement in declaration.Body?.Statements ?? [])+ if (statement is not DeclarationSyntax { Type.Name.Text: "Axis" or "Plane" or "Point" or "DatumFrame" or "Dimension" })+ diagnostics.Add(AssemblyInterfaceSyntax.Diagnostic(statement is DeclarationSyntax ? "assembly-semantic-unresolved-member" : "assembly-semantic-field-unknown",+ $"Unrecognized member in Semantic '{declaration.Name?.Text}'; publish a typed Axis, Plane, Point, DatumFrame or Dimension.", identity, statement.Span));+ if (declaration.Type.Name.Text == "Expose" && declaration.Body?.Statements.OfType<DeclarationSyntax>().Any(d => d.Type.Name.Text == "Semantic" && d.Body is not null) == true)+ foreach (var statement in declaration.Body.Statements)+ if (statement is not DeclarationSyntax { Type.Name.Text: "Semantic" })+ diagnostics.Add(AssemblyInterfaceSyntax.Diagnostic("assembly-port-publication-unknown",+ "This expose block publishes named Semantic blocks; unrecognized fields or statements cannot be discarded.", identity, statement.Span));+ }+ }+internal static IReadOnlyList<SemanticValue> Read(string source,string owner,string identity,string sourceIdentity,List<AssemblyDiagnostic> diagnostics,SectionChain? chain = null, bool includeWinding = false){source = FirmamentSourceSpelling.Normalize(source);+ ValidatePublicationSyntax(FirmamentSyntaxParser.Parse(source).Document, sourceIdentity, diagnostics);+ if (diagnostics.Count > 0) return [];var valueErrors = new List<string>();var valuesForPorts = new FirmamentCompileTimeValues(source);_ = FirmamentV2TemplateExpansion.ReadDataCatalog(source, valueErrors, valuesForPorts, initialize: true);diff --git a/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs b/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.csindex d90c6669..0038edd0 100644--- a/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs+++ b/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs@@ -27,6 +27,7 @@ public static class FirmamentFrontendSchemaspublic static FirmamentFrontendSelection Select(string source){ArgumentNullException.ThrowIfNull(source);+ source = FirmamentSourceSpelling.Normalize(source);if (!source.Contains("schema", StringComparison.Ordinal) && !FirmamentV2Parser.IsV2AdmissionCandidate(source)) return new(null, source, []);var syntax = FirmamentSyntaxParser.Parse(source);if (syntax.Diagnostics.FirstOrDefault(d => d.Code == "firmament-schema-malformed") is { SourceSpan: { } malformedSpan } malformed)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.csindex c04de321..6db711e5 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs@@ -457,7 +457,7 @@ internal static class CanonicalStaticAuthoring{var open = source.IndexOf('{', header.Index); var close = MatchPair(source, open, '{', '}');if (close < 0) { diagnostics.Add(FirmamentV2Parser.SemanticConstraintMalformed); continue; }- var fields = RequireFields(source[(open + 1)..close]);+ var fields = ClosedProjectionFields("Require", source[(open + 1)..close], diagnostics, "Actual", "Expected", "Tolerance");if (!fields.TryGetValue("Actual", out var actual) || !fields.TryGetValue("Expected", out var expected)){ diagnostics.Add(FirmamentV2Parser.SemanticConstraintMalformed); continue; }if (!TrySubject(actual, out var subject, out var property) || !TryLength(ResolveStaticValue(source, expected), out var nominal))@@ -710,8 +710,26 @@ internal static class CanonicalStaticAuthoring}private static Dictionary<string, string> Fields(string body) => Regex.Matches(body, "\\b(?<name>[A-Za-z_]\\w*)\\s*:\\s*(?<value>\"[^\"]*\"|(?:Point2|Point3|Vector2|PlusMinus)\\s*\\([^)]*\\)|\\d+\\.\\d+\\.\\d+|\\d{4}-\\d{2}-\\d{2}|[A-Za-z_]\\w*|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?)", RegexOptions.CultureInvariant).Cast<Match>().ToDictionary(m => m.Groups["name"].Value, m => m.Groups["value"].Value, StringComparer.Ordinal);- private static Dictionary<string, string> RequireFields(string body) => Regex.Matches(body, @"(?<name>[A-Za-z_]\w*)\s*:\s*(?<value>.*?)(?=\s+[A-Za-z_]\w*\s*:|$)", RegexOptions.CultureInvariant | RegexOptions.Singleline)- .Cast<Match>().ToDictionary(m => m.Groups["name"].Value, m => m.Groups["value"].Value.Trim(), StringComparer.Ordinal);+ private static Dictionary<string, string> ClosedProjectionFields(string kind, string body, List<string> diagnostics, params string[] consumed)+ {+ var parsed = FirmamentSyntaxParser.Parse(kind + " Entry {" + body + "}");+ var declaration = parsed.Document.Statements.OfType<DeclarationSyntax>().FirstOrDefault();+ if (!parsed.IsSuccess || declaration is null)+ {+ diagnostics.AddRange(parsed.Diagnostics.Select(d => d.Code + ": " + d.Message));+ return new(StringComparer.Ordinal);+ }+ // Ordinary PMI belongs to ParsePmi. Only From projections are erased by+ // this owner and therefore need consumption before that rewrite.+ if (kind != "Require" && declaration.Body?.Statements.OfType<FieldSyntax>()+ .Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "From")) != true) return new(StringComparer.Ordinal);+ var reader = new FirmamentSyntaxFields(declaration, diagnostics);+ var result = new Dictionary<string, string>(StringComparer.Ordinal);+ foreach (var name in consumed)+ if (reader.Take(name) is { } expression) result[name] = FirmamentSyntaxWriter.Expression(expression);+ reader.Complete();+ return result;+ }private static bool TrySubject(string text, out string subject, out string property){ var m = Regex.Match(text.Trim(), @"^(?<subject>[A-Za-z_]\w*)\.(?<property>Diameter)$", RegexOptions.CultureInvariant); subject = m.Groups["subject"].Value; property = m.Groups["property"].Value; return m.Success; }private static bool TryLength(string text, out FirmamentV2LiteralValue value)@@ -738,7 +756,8 @@ internal static class CanonicalStaticAuthoringforeach (Match entry in Regex.Matches(body, @"\b(?<kind>[A-Za-z_]\w*)\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant)){var entryOpen = outerOpen + 1 + body.IndexOf('{', entry.Index); var entryClose = MatchPair(source, entryOpen, '{', '}'); if (entryClose < 0) continue;- var fields = RequireFields(source[(entryOpen + 1)..entryClose]);+ var fields = ClosedProjectionFields(entry.Groups["kind"].Value, source[(entryOpen + 1)..entryClose], diagnostics,+ "From", "As", "DatumRefs", "Target", "Value", "Tolerance", "Dimension", "Diameter");if (!fields.TryGetValue("From", out var from)) continue;if (!fields.TryGetValue("As", out var asKind) || !string.Equals(asKind, "HoleDiameter", StringComparison.Ordinal) || !string.Equals(entry.Groups["kind"].Value, "HoleDiameter", StringComparison.Ordinal)) { diagnostics.Add(FirmamentV2Parser.PmiProjectionUnsupportedKind); continue; }if (fields.Keys.Any(key => key is "Target" or "Value" or "Tolerance" or "Dimension" or "Diameter")) { diagnostics.Add(FirmamentV2Parser.PmiProjectedFieldMustNotOverrideSourceConstraint); continue; }diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.csindex 4ba0b7d4..d34dc84e 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs@@ -547,7 +547,12 @@ internal static class ConceptIrResolvervar open = body.IndexOf('{', pattern.Index); var close = FindMatchingBrace(body, open);if (close < 0) { diagnostics.Add("firmament-pattern-invalid-source"); continue; }var patternBody = body[(open + 1)..close];- var source = FieldValue(patternBody, "Source");+ var patternSyntax = FirmamentSyntaxParser.Parse("Pattern " + pattern.Groups["name"].Value + " {" + patternBody + "}")+ .Document.Statements.OfType<DeclarationSyntax>().Single();+ var fields = new FirmamentSyntaxFields(patternSyntax, diagnostics);+ var source = fields.Take("Source") is { } sourceValue ? FirmamentSyntaxWriter.Expression(sourceValue) : "";+ var child = patternSyntax.Body?.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d => d.Type.Name.Text == "Hole");+ fields.Complete(child is null ? new HashSet<StatementSyntax>() : new HashSet<StatementSyntax> { child });var reference = Regex.Match(source, @"^(?<instance>[A-Za-z_][A-Za-z0-9_]*)\.(?<member>[A-Za-z_][A-Za-z0-9_]*)$", RegexOptions.CultureInvariant);if (!reference.Success || !instances.TryGetValue(reference.Groups["instance"].Value, out var instance) || !instance.Members.TryGetValue(reference.Groups["member"].Value, out var member) || member is not ConceptIrPointSetValue points){ diagnostics.Add("firmament-pattern-source-not-static-point3-collection:" + source); continue; }@@ -818,7 +823,17 @@ internal static class ConceptIrResolverexpression = expression.Trim();var provenance = $"{instanceName}.{target.Name}";if (expression.StartsWith(materializedName + ".", StringComparison.Ordinal)) { diagnostics.Add(MaterializedPhaseReference); return null; }- if (FirmamentSyntaxParser.ParseExpression(expression).Expression is MatchSyntax match) return EvaluateMatch(match, target);+ var syntax = FirmamentSyntaxParser.ParseExpression(expression).Expression;+ if (syntax is MatchSyntax match) return EvaluateMatch(match, target);+ if (syntax is ObjectSyntax spatial && FirmamentSyntaxValues.Reference(spatial.Type) is { } spatialType+ && SpatialFields.TryGetValue(spatialType, out var schema))+ {+ var before = diagnostics.Count;+ var fields = FirmamentSyntaxFields.Object(spatial, target.Name, diagnostics);+ foreach (var field in schema.Keys) fields.Take(field);+ fields.Complete();+ if (diagnostics.Count > before) return null;+ }var box = Regex.Match(expression, @"^Box3\s*\{(?<body>.*)\}$", RegexOptions.Singleline | RegexOptions.CultureInvariant);if (box.Success)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeChoices.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeChoices.csindex c5b1f349..8ae6c998 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeChoices.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeChoices.cs@@ -235,7 +235,7 @@ internal sealed partial class FirmamentCompileTimeValues{if (statement is not FieldSyntax f){ Fail(FirmamentV2Parser.ExpressionUnsupported, $"{objectType} requires named value fields.", statement.Span); continue; }- var name = spatialSchema.Keys.FirstOrDefault(k => FirmamentSyntaxFields.SameField(k, f.Name.Text));+ var name = spatialSchema.Keys.FirstOrDefault(k => FirmamentSyntaxFields.SameField(f.Name.Text, k));if (name is null) { Fail("firmament-v2-canonical-field-unknown", $"Unknown field '{f.Name.Text}' in {objectType}.", f.Name.Span); continue; }if (!seen.Add(name)) Fail("firmament-v2-field-duplicate", $"Duplicate field '{f.Name.Text}' in {objectType}.", f.Name.Span);var actual = TypeOf(f.Value, null, stack);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.csindex 66958d01..7822165d 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs@@ -66,6 +66,17 @@ public static class FirmamentSourceSpelling.Select(alias => tokens.LastOrDefault(t => t.Start < alias.Name.Span.Start && t.Start >= alias.Value.Span.Start + alias.Value.Span.Length && t.Text is "As" or "as")?.Start).Where(position => position.HasValue).Select(position => position!.Value).ToHashSet() : [];var output = new StringBuilder(source);+ // A lowercase root with native V2 contents is a case-only compatibility+ // alias. Historical solid/modify documents retain+ // their explicit compatibility grammar.+ foreach (var root in syntax.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "model" && d.Body is not null))+ {+ var legacy = root.Body!.Statements.Any(s => s is DeclarationSyntax d+ && d.Type.Name.Text is "solid" or "modify" or "region" or "cut");+ if (legacy) continue;+ var span = root.Type.Name.Span;+ output[span.Start] = 'M';+ }var scopes = new Stack<Scope>();var parentheses = 0;var angles = 0;diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.csindex 2aeb5262..83d77ed8 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs@@ -300,12 +300,24 @@ public static partial class FirmamentV2Parserprivate static FirmamentV2PrimitiveRecord? BindMechanicalPrimitive(FirmamentSyntaxFields f, List<string> diagnostics){var type = f.Declaration.Type.Name.Text;- double Length(string name) => f.Number(name, "mm");+ bool Representable(double value, string field)+ {+ if (!double.IsFinite(value)) return false;+ if (Math.BitIncrement(Math.Abs(value)) - Math.Abs(value) <= Aetheris.Kernel.Core.Numerics.ToleranceContext.Default.Linear) return true;+ diagnostics.Add($"firmament-dimension-precision-unsupported:{type}:{field}: The dimension is too large for the kernel's linear tolerance. Use a smaller model extent or a local coordinate frame.");+ return false;+ }+ double Length(string name)+ {+ var value = f.Number(name, "mm");+ return Representable(value, name) ? value : double.NaN;+ }double[]? Size(){if (!f.Vector("Size", "mm", out var values)) return null;if (values.Length != 3) { diagnostics.Add(BoxSizeArity); return null; }if (values.Any(v => v <= 0)) { diagnostics.Add(DegenerateDimension); return null; }+ if (values.Any(v => !Representable(v, "Size"))) return null;return values;}switch (type)@@ -576,17 +588,25 @@ public static partial class FirmamentV2Parsercase "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 "Extrude":+ ProfileAuthoringParser.ReadExtrudeFields(declaration, diagnostics); break;case "Profile" when declaration.Body is not null:- // A Profile body holds loops. Its readers look for Loop headers, so a- // field here would otherwise be dropped without a diagnostic.- // `From` is the derived-boundary form (`Profile copy { From: outline }`).- foreach (var profileField in declaration.Body.Statements.OfType<FieldSyntax>().Where(f => !FirmamentSyntaxFields.SameField(f.Name.Text, "From")))- diagnostics.Add($"{CanonicalFieldUnknown}:Profile:{profileField.Name.Text}");+ ProfileAuthoringParser.ValidateProfileBody(declaration, diagnostics);+ break;+ case "Modify":+ foreach (var item in declaration.Body?.Statements ?? [])+ if (item is FieldSyntax unknown) diagnostics.Add($"{CanonicalFieldUnknown}:Modify:{unknown.Name.Text}");+ else if (item is not DeclarationSyntax) diagnostics.Add(CanonicalModifyMalformed);+ break;+ case "Expose":+ var publications = new List<Assembly.AssemblyDiagnostic>();+ Assembly.AssemblyPublishedPorts.ValidatePublicationSyntax(declaration, "inline", publications);+ diagnostics.AddRange(publications.Select(d => d.Code + ": " + d.Message));break;case "Box" or "Cylinder" or "Cone" or "Sphere" or "Ellipsoid" or "Polyhedron" 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 "Template" or "template" or "Feature" or "Pattern" or "ProfileDelta" or "Selection" or "InlineStep" or "Recognize" or "Replace" or "Remove" or "Pmi" or "Modify" or "Match" or "Require" or "Assert" or "Thread":+ case "Plateau" or "Concept" or "Struct" or "Profile" or "Span" or "Compose" or "Boss" or "Pocket" or "AddOffset" or "RemoveOffset" or "EdgeFinish":+ case "Enum" or "Record" or "Template" or "template" or "Feature" or "Pattern" or "ProfileDelta" or "Selection" or "InlineStep" or "Recognize" or "Replace" or "Remove" or "Pmi" 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/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.csindex b472677b..7c1dcd71 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs@@ -59,6 +59,9 @@ public static class ProfileAuthoringParservar diagnostics = new List<string>();if (!visiting.Add(profileName)) { reportedDiagnostics = [$"concept-profile-dependency-cycle:{profileName}"]; return null; }source = ProfileModificationTemplateLibrary.ResolveImports(source);+ foreach (var authored in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)+ .Where(d => d.Type.Name.Text == "Profile" && d.Name?.Text == profileName))+ ValidateProfileBody(authored, diagnostics);source = ExpandBuiltInPolygons(source, diagnostics,scalars);var expansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics,scalars);if (expansion is not null) source = expansion.Source;@@ -337,6 +340,23 @@ public static class ProfileAuthoringParserreturn diagnostics;}+ internal static void ValidateProfileBody(DeclarationSyntax profile, List<string> diagnostics)+ {+ if (profile.Body is null) return;+ var fields = new FirmamentSyntaxFields(profile, diagnostics);+ fields.Take("From");+ fields.Complete(profile.Body.Statements.Where(s => s is ExpressionStatementSyntax+ || s is DeclarationSyntax d && (d.Type.Name.Text is "Loop" or "Segment" or "Replace" or "Apply"+ || ClosedBoundary2Authoring.IsBoundaryType(d.Type.Name.Text))).ToHashSet(), admitPlacement: true);+ foreach (var loop in profile.Body.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Loop"))+ {+ var loopFields = new FirmamentSyntaxFields(loop, diagnostics);+ loopFields.Take("From");+ loopFields.Complete((loop.Body?.Statements.Where(s => s is ExpressionStatementSyntax+ || s is DeclarationSyntax d && d.Type.Name.Text == "Segment") ?? []).ToHashSet(), admitPlacement: true);+ }+ }+private static IEnumerable<DeclarationSyntax> SourceDeclarations(IEnumerable<StatementSyntax> statements){foreach (var d in statements.OfType<DeclarationSyntax>())@@ -366,14 +386,19 @@ public static class ProfileAuthoringParserif (close < 0) { diagnostics.Add($"firmament-span-domain-invalid:{name}"); continue; }if (!names.Add(name) || guides.ContainsKey(name)) { diagnostics.Add($"firmament-span-duplicate:{name}"); continue; }var body = source[(open + 1)..close];- var parent = Property(body, "On");+ var spanSyntax = FirmamentSyntaxParser.Parse("Span " + name + " {" + body + "}").Document.Statements.OfType<DeclarationSyntax>().Single();+ var spanFields = new FirmamentSyntaxFields(spanSyntax, diagnostics);+ string? SpanField(string field) => spanFields.Take(field) is { } expression ? FirmamentSyntaxWriter.Expression(expression) : null;+ var parent = SpanField("On");if (parent is null) { diagnostics.Add($"firmament-span-parent-not-found:{name}"); continue; }// Plane spans are semantic surface views only in X1: a named, already-authored// Profile is their boundary authority. They intentionally do not create a face.if (type == "Plane"){- var boundary = Property(body, "Boundary");+ var boundary = SpanField("Boundary");+ var orientation = SpanField("Orientation") ?? "Forward";+ spanFields.Complete();var planeDiagnostics = new List<string>();var parentPlane = ResolveConstructionPlane(source, parent, planeDiagnostics);if (!ConstructionPlanes(source).Any(plane => plane.Name?.Text == parent) || parentPlane is null)@@ -397,7 +422,6 @@ public static class ProfileAuthoringParser(loop.IsOuter ? 1d : -1d) * Math.Abs(PrismaticSectionStackCompiler.ProfileArea(boundaryProfile with { Loops = [loop] })));if (!double.IsFinite(area) || area <= Tolerance) { diagnostics.Add($"firmament-span-surface-domain-invalid:{name}"); continue; }var normal = parentPlane.AxisZ.ToVector();- var orientation = string.Equals(Property(body, "Orientation"), "Reverse", StringComparison.Ordinal) ? "Reverse" : "Forward";var consumers = FindSpanConsumers(source, name);result.Add(new(name, type, parent, "Plane", $"Boundary:{boundary}", orientation, null, null, boundary, null,$"span:{name};parent:{parent};boundary:{boundary}", Area: area,@@ -411,15 +435,16 @@ public static class ProfileAuthoringParservar parentType = parentGeometry switch { LineArcLineSegment2D => "Line", LineArcFullCircle2D => "Arc", LineArcCircularArc2D => "Arc", _ => parentGeometry.GetType().Name };if ((type == "Line" && parentGeometry is not LineArcLineSegment2D) || (type == "Arc" && parentGeometry is not LineArcFullCircle2D and not LineArcCircularArc2D)){ diagnostics.Add($"firmament-span-type-invalid:{type}"); continue; }- var fromName = Property(body, "From"); var toName = Property(body, "To");+ var fromName = SpanField("From"); var toName = SpanField("To");+ var sweep = SpanField("Sweep") ?? "CounterClockwise";+ var reverse = string.Equals(SpanField("Orientation"), "Reverse", StringComparison.Ordinal);+ spanFields.Complete();if (fromName is null || toName is null || !points.TryGetValue(fromName, out var from) || !points.TryGetValue(toName, out var to)){ diagnostics.Add($"firmament-span-domain-invalid:{name}"); continue; }- var sweep = Property(body, "Sweep") ?? "CounterClockwise";var curve = SelectGuide(parentGeometry, from, to, sweep, name, parent, diagnostics);if (curve is null) continue;var length = CurveLength(curve);if (!double.IsFinite(length) || length <= Tolerance) { diagnostics.Add($"firmament-span-zero-length:{name}"); continue; }- var reverse = string.Equals(Property(body, "Orientation"), "Reverse", StringComparison.Ordinal);if (reverse) curve = Reverse(curve);var domain = curve switch{@@ -473,6 +498,13 @@ public static class ProfileAuthoringParser{ diagnostics.Add($"concept-path-header-invalid:{name}"); continue; }var content = declaration.Body.ContentSpan;var pathBody = source.Substring(content.Start, content.Length);+ var pathFields = new FirmamentSyntaxFields(declaration with { Modifiers = [] }, diagnostics);+ pathFields.Take("Start");+ pathFields.Take("Heading");+ var recognizedSteps = FindPathSteps(pathBody).Select(s => content.Start + s.Index).ToHashSet();+ var steps = declaration.Body.Statements.Where(s => s is DeclarationSyntax d && recognizedSteps.Contains(d.Span.Start)+ || s is ExpressionStatementSyntax).ToHashSet();+ pathFields.Complete(steps);if (!result.TryAdd(name, default!)) { diagnostics.Add($"concept-path-duplicate:{name}"); continue; }if (pathBody.Contains("|>", StringComparison.Ordinal)){@@ -774,6 +806,12 @@ public static class ProfileAuthoringParserAddPathLoop(loop.Groups["name"].Value, string.Equals(loop.Groups["name"].Value, "Outer", StringComparison.Ordinal), loop.Groups["path"].Value, profile, paths, loops, diagnostics);foreach (var loop in loopBlocks){+ var loopSyntax = FirmamentSyntaxParser.Parse("Loop " + loop.Match.Groups["name"].Value + " {" + loop.Body + "}")+ .Document.Statements.OfType<DeclarationSyntax>().Single();+ var loopFields = new FirmamentSyntaxFields(loopSyntax, diagnostics);+ loopFields.Take("From");+ loopFields.Complete((loopSyntax.Body?.Statements.Where(s => s is ExpressionStatementSyntax+ || s is DeclarationSyntax d && d.Type.Name.Text == "Segment") ?? []).ToHashSet());var loopName = loop.Match.Groups["name"].Value; var fromPath = loop.Match.Groups["path"].Success ? loop.Match.Groups["path"].Value : null;var fromInsideMatch = Regex.Match(loop.Body, @"^\s*From\s*:\s*(?<path>[A-Za-z_]\w*)\b", RegexOptions.CultureInvariant);var fromInside = fromInsideMatch.Success ? fromInsideMatch.Groups["path"].Value : null;@@ -1220,14 +1258,28 @@ public static class ProfileAuthoringParserreturn result;}+ internal static (ExpressionSyntax? Profile, ExpressionSyntax? From, ExpressionSyntax? To) ReadExtrudeFields(DeclarationSyntax declaration, List<string> diagnostics)+ {+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);+ var profile = fields.Take("Profile");+ var from = fields.Take("From");+ var to = fields.Take("To");+ fields.Complete();+ return (profile, from, to);+ }+private static (double Start, double End, double Height) ResolveExtrude(string source, string profileName, List<string> diagnostics){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();+ var fields = ReadExtrudeFields(d, diagnostics);+ if (FirmamentSyntaxValues.Reference(fields.Profile) != profileName) continue;+ if (!FirmamentSyntaxValues.TryMeasure(fields.From, "mm", out var start)+ || !FirmamentSyntaxValues.TryMeasure(fields.To, "mm", out var end))+ {+ diagnostics.Add($"profile-extrusion-length-required:{d.Name?.Text}: Extrude from/to must be lengths in mm, not angles or scalars.");+ continue;+ }if (!double.IsFinite(start) || !double.IsFinite(end)) break;return (start, end, Math.Abs(end - start));}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.csindex 472b825f..e93bd1f0 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs@@ -68,6 +68,8 @@ public static class SectionChainAuthoringParservar boundaries = ClosedBoundary2Authoring.Expand(source, diagnostics, values);if (boundaries is null || diagnostics.Count > 0) return new(false, null, null, diagnostics);source = boundaries.Source;+ diagnostics.AddRange(ProfileAuthoringParser.ValidateConstructionGuides(source, values.NominalExpression));+ if (diagnostics.Count > 0) return new(false, null, null, diagnostics);var staticSource = CanonicalStaticAuthoring.Expand(source, diagnostics, values);if (staticSource is null || diagnostics.Count > 0) return new(false, null, null, diagnostics);var inputs = values.MaterialInputs(staticSource.Source);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.csindex 16f4d93c..7c9838a6 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs@@ -405,7 +405,9 @@ public static class FirmamentSyntaxParser{var start = Current.Span.Start;ExpressionSyntax left;- if (Take("+") || Take("-") || Take("!") || Take("Reverse"))+ var reverseOperand = Peek(1).Kind != SyntaxTokenKind.End && Peek(1).Text is not ("}" or ";" or "," or ")" or "]")+ && Peek(2).Text != ":";+ if (Take("+") || Take("-") || Take("!") || Is("Reverse") && reverseOperand && 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));diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.csindex 772654be..673a978f 100644--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs@@ -497,13 +497,20 @@ public static class PrismaticProfileCompositionParserif (!string.Equals(toolFamily, "Prism", StringComparison.Ordinal)){ diagnostics.Add($"offset-tool-family-not-qualified:{name}:tool={toolFamily}:qualified=Prism"); continue; }- var targetMatch = OffsetTarget.Match(body);- var profileMatch = SemanticProfile.Match(body);- var supportMatch = SemanticSupport.Match(body);- var directionMatch = OffsetDirection.Match(body);- var heightMatch = BossHeight.Match(body);- var depthMatch = PocketDepth.Match(body);- var throughAll = OffsetThroughAll.IsMatch(body);+ var authored = operationsSyntax.Document.Statements.OfType<DeclarationSyntax>().Single(d => d.Name?.Text == name && d.Type.Name.Text == intentText);+ var fields = new FirmamentSyntaxFields(authored, diagnostics);+ var targetMatch = ReadFeatureField(fields, composeBody, OffsetTarget, "Target");+ var profileMatch = ReadFeatureField(fields, composeBody, SemanticProfile, "Profile");+ var supportMatch = ReadFeatureField(fields, composeBody, SemanticSupport, "On");+ var directions = new[] { "Along", "Axis", "Direction" }.Select(n => ReadFeatureField(fields, composeBody, OffsetDirection, n)).Where(m => m.Success).ToArray();+ var directionMatch = directions.FirstOrDefault() ?? Match.Empty;+ if (directions.Length > 1) diagnostics.Add($"offset-direction-conflict:{name}");+ var heightMatch = ReadFeatureField(fields, composeBody, BossHeight, "Height");+ var depthMatch = ReadFeatureField(fields, composeBody, PocketDepth, "Depth");+ var terminations = new[] { "Termination", "Extent" }.Select(n => ReadFeatureField(fields, composeBody, OffsetThroughAll, n)).Where(m => m.Success).ToArray();+ var throughAll = terminations.Length > 0;+ if (terminations.Length > 1) diagnostics.Add($"offset-termination-conflict:{name}");+ fields.Complete();if (!targetMatch.Success || !profileMatch.Success || !supportMatch.Success){ diagnostics.Add($"offset-missing-required-field:{name}:required=Target,On,Profile"); continue; }var target = targetMatch.Groups["value"].Value;diff --git a/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs b/Aetheris.Kernel.Firmament/Materializer/WireCoils.csindex 4de51a62..56370ef1 100644--- a/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs+++ b/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs@@ -25,16 +25,18 @@ internal static class WireCoilAuthoringinternal static KernelResult<WireAxisCoilAir> CreateAxis(string name, int ordinal, string body, WireState input, double diameter){- if (!Length(body, RadiusField, out var radius) || radius <= 0d) return FailAxis("wireform-coil-radius-invalid", name, "Radius must be finite and greater than zero.");- if (!Number(body, TurnsField, out var turns) || turns <= 0d) return FailAxis("wireform-coil-turns-invalid", name, "Turns must be finite and greater than zero.");- var hasPitch = Length(body, PitchField, out var pitch); var hasHeight = Length(body, HeightField, out var height);+ var fields = new WireFormFields("Helix", body);+ if (!Length(fields, RadiusField, out var radius) || radius <= 0d) return FailAxis("wireform-coil-radius-invalid", name, "Radius must be finite and greater than zero.");+ if (!Number(fields, TurnsField, out var turns) || turns <= 0d) return FailAxis("wireform-coil-turns-invalid", name, "Turns must be finite and greater than zero.");+ var hasPitch = Length(fields, PitchField, out var pitch); var hasHeight = Length(fields, HeightField, out var height);if (!hasPitch && !hasHeight) return FailAxis("wireform-coil-parameters-inconsistent", name, "Specify Turns and either Pitch or Height.");if (hasPitch && pitch <= 0d || hasHeight && height <= 0d) return FailAxis("wireform-coil-parameters-inconsistent", name, "Pitch and Height must be greater than zero.");if (!hasPitch) pitch = height / turns; else if (!hasHeight) height = pitch * turns;else if (Math.Abs(height - pitch * turns) > 1e-8 * Math.Max(1d, height))return FailAxis("wireform-coil-parameters-inconsistent", name, $"Height must equal Turns × Pitch ({turns * pitch:G12} mm).");- if (!Hand(body, out var hand)) return FailAxis("wireform-coil-handedness-invalid", name, "Handedness must be RightHanded or LeftHanded.");- if (!Phase(body, out var phase)) return FailAxis("wireform-coil-start-phase-invalid", name, "StartPhase must be a finite angle.");+ if (!Hand(fields, out var hand)) return FailAxis("wireform-coil-handedness-invalid", name, "Handedness must be RightHanded or LeftHanded.");+ if (!Phase(fields, out var phase)) return FailAxis("wireform-coil-start-phase-invalid", name, "StartPhase must be a finite angle.");+ if (fields.Complete() is { } fieldError) return FailAxis("wireform-fields-invalid", name, fieldError);var sign = hand == WireCoilHandedness.RightHanded ? 1d : -1d;var q = height / (2d * Math.PI * turns);var axis = Direction3D.Create(input.Tangent.ToVector() * q + input.Up.ToVector() * (sign * radius));@@ -53,19 +55,22 @@ internal static class WireCoilAuthoringinternal static KernelResult<WireSurfaceCoilAir> CreateSurface(string source, string name, int ordinal, string body, WireState input, double diameter){- var supportName = WireFormAuthoring.Property(body, "Surface") ?? WireFormAuthoring.Property(body, "Support");+ var fields = new WireFormFields("SurfaceCoil", body);+ var supportName = fields.Read("Surface") ?? fields.Read("Support");if (string.IsNullOrWhiteSpace(supportName)) return FailSurface("wireform-surfacecoil-support-unsupported", name, "Surface must name an authored Cylinder, Frustum, Cone, or Sphere.");var declaration = Regex.Match(source, $@"\b(?<kind>Cylinder|Frustum|Cone|Sphere)\s+{Regex.Escape(supportName.Trim())}\s*\{{", RegexOptions.CultureInvariant);if (!declaration.Success) return FailSurface("wireform-surfacecoil-support-unsupported", supportName.Trim(), "Only authored analytic Cylinder, Frustum/Cone, and Sphere supports are admitted.");var open = source.IndexOf('{', declaration.Index); var close = MatchingBrace(source, open);if (close < 0) return FailSurface("wireform-surfacecoil-support-unsupported", supportName.Trim(), "Support declaration is malformed.");- var supportBody = source[(open + 1)..close]; var kind = declaration.Groups["kind"].Value; if (kind == "Cone") kind = "Frustum";- if (!Number(body, "Turns", out var turns) || turns <= 0d) return FailSurface("wireform-coil-turns-invalid", name, "Turns must be finite and greater than zero.");- if (!Hand(body, out var hand)) return FailSurface("wireform-coil-handedness-invalid", name, "Handedness must be RightHanded or LeftHanded.");- if (!Phase(body, out var phase)) return FailSurface("wireform-coil-start-phase-invalid", name, "StartPhase must be a finite angle.");- var sideText = WireFormAuthoring.Property(body, "Side") ?? "Outside";+ var supportBody = source[(open + 1)..close];+ var supportFields = new WireFormFields(declaration.Groups["kind"].Value, supportBody);+ supportFields.Read("Role"); var kind = declaration.Groups["kind"].Value; if (kind == "Cone") kind = "Frustum";+ if (!Number(fields, "Turns", out var turns) || turns <= 0d) return FailSurface("wireform-coil-turns-invalid", name, "Turns must be finite and greater than zero.");+ if (!Hand(fields, out var hand)) return FailSurface("wireform-coil-handedness-invalid", name, "Handedness must be RightHanded or LeftHanded.");+ if (!Phase(fields, out var phase)) return FailSurface("wireform-coil-start-phase-invalid", name, "StartPhase must be a finite angle.");+ var sideText = fields.Read("Side") ?? "Outside";if (!Enum.TryParse<WireSurfaceSide>(sideText, false, out var side)) return FailSurface("wireform-surfacecoil-side-invalid", name, "Side must be Outside or Inside.");- var hasClearance = Length(body, "Clearance", out var clearance); var hasOffset = Length(body, "CenterlineOffset", out var offset);+ var hasClearance = Length(fields, "Clearance", out var clearance); var hasOffset = Length(fields, "CenterlineOffset", out var offset);if (hasClearance == hasOffset) return FailSurface("wireform-surfacecoil-offset-invalid", name, "Specify exactly one of Clearance or CenterlineOffset.");if (hasClearance && clearance < 0d || hasOffset && offset <= 0d) return FailSurface("wireform-surfacecoil-offset-invalid", name, "Clearance cannot be negative and CenterlineOffset must be positive.");if (hasClearance) offset = diameter / 2d + clearance; else clearance = offset - diameter / 2d;@@ -74,9 +79,9 @@ internal static class WireCoilAuthoringdouble r0, r1, supportHeight, pitch = 0d, startLat = 0d, endLat = 0d;if (kind == "Sphere"){- if (!Length(supportBody, "Radius", out r0) || r0 <= 0d) return FailSurface("wireform-surfacecoil-support-unsupported", supportName.Trim(), "Sphere Radius must be positive.");+ if (!Length(supportFields, "Radius", out r0) || r0 <= 0d) return FailSurface("wireform-surfacecoil-support-unsupported", supportName.Trim(), "Sphere Radius must be positive.");r1 = r0; supportHeight = 2d * r0;- if (!Angle(body, "StartLatitude", out startLat) || !Angle(body, "EndLatitude", out endLat)) return FailSurface("wireform-surfacecoil-pole-singularity", name, "Sphere winding requires StartLatitude and EndLatitude.");+ if (!Angle(fields, "StartLatitude", out startLat) || !Angle(fields, "EndLatitude", out endLat)) return FailSurface("wireform-surfacecoil-pole-singularity", name, "Sphere winding requires StartLatitude and EndLatitude.");if (Math.Abs(startLat) >= Math.PI / 2d - 1e-6 || Math.Abs(endLat) >= Math.PI / 2d - 1e-6)return FailSurface("wireform-surfacecoil-pole-singularity", name, "Latitude bounds must remain away from ±90 degrees.");var rho = side == WireSurfaceSide.Outside ? r0 + offset : r0 - offset;@@ -86,19 +91,21 @@ internal static class WireCoilAuthoring{if (kind == "Cylinder"){- if (!Length(supportBody, "Radius", out r0) || r0 <= 0d) return FailSurface("wireform-surfacecoil-support-unsupported", supportName.Trim(), "Cylinder Radius must be positive.");+ if (!Length(supportFields, "Radius", out r0) || r0 <= 0d) return FailSurface("wireform-surfacecoil-support-unsupported", supportName.Trim(), "Cylinder Radius must be positive.");r1 = r0;}else{- if (!Length(supportBody, "BottomRadius", out r0) || !Length(supportBody, "TopRadius", out r1) || r0 < 0d || r1 < 0d || r0 + r1 <= 0d)+ if (!Length(supportFields, "BottomRadius", out r0) || !Length(supportFields, "TopRadius", out r1) || r0 < 0d || r1 < 0d || r0 + r1 <= 0d)return FailSurface("wireform-surfacecoil-support-unsupported", supportName.Trim(), "Frustum requires nonnegative BottomRadius and TopRadius.");}- if (!Length(supportBody, "Height", out supportHeight) || supportHeight <= 0d) return FailSurface("wireform-surfacecoil-support-unsupported", supportName.Trim(), "Support Height must be positive.");- if (!Length(body, "AxialPitch", out pitch) && !Length(body, "Pitch", out pitch) || pitch <= 0d) return FailSurface("wireform-coil-parameters-inconsistent", name, "Cylinder/frustum winding requires positive AxialPitch.");+ if (!Length(supportFields, "Height", out supportHeight) || supportHeight <= 0d) return FailSurface("wireform-surfacecoil-support-unsupported", supportName.Trim(), "Support Height must be positive.");+ if (!Length(fields, "AxialPitch", out pitch) && !Length(fields, "Pitch", out pitch) || pitch <= 0d) return FailSurface("wireform-coil-parameters-inconsistent", name, "Cylinder/frustum winding requires positive AxialPitch.");if (turns * pitch > supportHeight + 1e-9) return FailSurface("wireform-surfacecoil-span-invalid", name, "Turns × AxialPitch exceeds support Height.");}+ if (supportFields.Complete() is { } supportError) return FailSurface("wireform-fields-invalid", name, supportError);+ if (fields.Complete() is { } fieldError) return FailSurface("wireform-fields-invalid", name, fieldError);var sign = hand == WireCoilHandedness.RightHanded ? 1d : -1d;Direction3D axis, radial, longitude, latitude; Point3D origin;if (kind == "Sphere")@@ -140,11 +147,11 @@ internal static class WireCoilAuthoringreturn KernelResult<WireSurfaceCoilAir>.Success(prototype with { LengthMm = length, MinimumSelfClearanceMm = self, Output = output });}- private static bool Length(string body, string name, out double value) => WireFormAuthoring.TryLength(WireFormAuthoring.Property(body, name), out value);- private static bool Angle(string body, string name, out double value) => WireFormAuthoring.TryAngle(WireFormAuthoring.Property(body, name), out value);- private static bool Number(string body, string name, out double value) => double.TryParse(WireFormAuthoring.Property(body, name), NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);- private static bool Hand(string body, out WireCoilHandedness hand) => Enum.TryParse(WireFormAuthoring.Property(body, HandednessField) ?? "RightHanded", false, out hand);- private static bool Phase(string body, out double phase) { var text = WireFormAuthoring.Property(body, StartPhaseField); if (text is null) { phase = 0d; return true; } return WireFormAuthoring.TryAngle(text, out phase); }+ private static bool Length(WireFormFields fields, string name, out double value) => WireFormAuthoring.TryLength(fields.Read(name), out value);+ private static bool Angle(WireFormFields fields, string name, out double value) => WireFormAuthoring.TryAngle(fields.Read(name), out value);+ private static bool Number(WireFormFields fields, string name, out double value) => double.TryParse(fields.Read(name), NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);+ private static bool Hand(WireFormFields fields, out WireCoilHandedness hand) => Enum.TryParse(fields.Read(HandednessField) ?? "RightHanded", false, out hand);+ private static bool Phase(WireFormFields fields, out double phase) { var text = fields.Read(StartPhaseField); if (text is null) { phase = 0d; return true; } return WireFormAuthoring.TryAngle(text, out phase); }private static int MatchingBrace(string source, int open) { var depth = 0; for (var i = open; i >= 0 && i < source.Length; i++) { if (source[i] == '{') depth++; else if (source[i] == '}' && --depth == 0) return i; } return -1; }private static Vector3D Rotate(Vector3D v, Vector3D a, double angle) => v * Math.Cos(angle) + WireFormAuthoring.Cross(a, v) * Math.Sin(angle) + a * (WireFormAuthoring.Dot(a, v) * (1d - Math.Cos(angle)));private static KernelResult<WireAxisCoilAir> FailAxis(string code, string name, string message) => KernelResult<WireAxisCoilAir>.Failure([Diagnostic($"{code}:{name}: {message}")]);diff --git a/Aetheris.Kernel.Firmament/Materializer/WireForm.cs b/Aetheris.Kernel.Firmament/Materializer/WireForm.csindex b894f737..9ad072b2 100644--- a/Aetheris.Kernel.Firmament/Materializer/WireForm.cs+++ b/Aetheris.Kernel.Firmament/Materializer/WireForm.cs@@ -9,6 +9,7 @@ using Aetheris.Kernel.Core.Numerics;using Aetheris.Kernel.Core.Results;using Aetheris.Kernel.Core.Topology;using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.StandardLibrary.Materials;namespace Aetheris.Kernel.Firmament.Materializer;@@ -137,15 +138,29 @@ public static class WireFormAuthoringpublic static bool IsWireFormSource(string source) => Declaration.IsMatch(source) || WireRouteAuthoring.IsSource(source);+ internal static void BindConstructionScope(DocumentSyntax syntax, string materialKind, List<string> diagnostics)+ {+ void Bind(IReadOnlyList<StatementSyntax> statements)+ {+ bool Wrapper(DeclarationSyntax d) => d.Type.Name.Text is "Model" or "Struct"+ && !d.Modifiers.Any(m => m.Name.Text is "Concept" or "Template");+ foreach (var wrapper in statements.OfType<DeclarationSyntax>().Where(Wrapper)) Bind(wrapper.Body?.Statements ?? []);+ FirmamentV2Parser.BindMechanicalScope(statements.Where(s => s is not DeclarationSyntax d+ || !(Wrapper(d) || d.Type.Name.Text == materialKind)).ToArray(), diagnostics);+ }+ Bind(syntax.Statements);+ }+public static KernelResult<WireFormFeatureAir> Parse(string source){ArgumentNullException.ThrowIfNull(source);- source = FirmamentV2.FirmamentSourceSpelling.Normalize(source);+ var frontend = FirmamentFrontendSchemas.Select(source);+ if (!frontend.IsSuccess) return Fail(frontend.Diagnostics[0].Split(':')[0], string.Join("; ", frontend.Diagnostics));+ source = frontend.Source;if (WireRouteAuthoring.IsSource(source)) return WireRouteAuthoring.Parse(source);var syntax = FirmamentV2.Syntax.FirmamentSyntaxParser.Parse(source);var scopeDiagnostics = new List<string>();- FirmamentV2.FirmamentV2Parser.BindMechanicalScope(FirmamentV2.Syntax.FirmamentSyntaxTraversal.Declarations(syntax.Document)- .Where(d => d.Type.Name.Text == "Static").Cast<FirmamentV2.Syntax.StatementSyntax>().ToArray(), scopeDiagnostics);+ BindConstructionScope(syntax.Document, "WireForm", scopeDiagnostics);if (scopeDiagnostics.Count > 0)return Fail(scopeDiagnostics[0].Split(':')[0], string.Join("; ", scopeDiagnostics));var declaration = Declaration.Match(source);@@ -155,24 +170,40 @@ public static class WireFormAuthoringvar name = declaration.Groups["name"].Value;if (close < 0) return Fail("wireform-declaration-malformed", $"WireForm '{name}' has no closing brace.");var body = source[(open + 1)..close];+ var wireFields = new WireFormFields("WireForm", body);+ var children = wireFields.Declaration.Body!.Statements.OfType<DeclarationSyntax>()+ .Where(d => d.Type.Name.Text is "StartFrame" or "Straight" or "Bend" or "Helix" or "AxisCoil" or "Coil" or "SurfaceCoil" or "Knot")+ .Cast<StatementSyntax>().ToHashSet();+ var startFrames = children.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "StartFrame").ToArray();+ if (startFrames.Length > 1) return Fail("wireform-start-frame-invalid", "Declare only one StartFrame.");+ // Direct Origin/Tangent/Up fields are an admitted historical spelling.+ // A block and direct fields together leave unconsumed fields and reject.+ var frameFields = wireFields;+ if (startFrames.Length == 1)+ {+ var frame = startFrames[0].Body!.ContentSpan;+ frameFields = new WireFormFields("StartFrame", ("WireForm {\n" + body + "\n}").Substring(frame.Start, frame.Length));+ }- if (!TryLength(Property(body, "Diameter"), out var diameter) || diameter <= 0d)+ if (!TryLength(wireFields.Read("Diameter"), out var diameter) || diameter <= 0d)return Fail("wireform-diameter-invalid", $"WireForm '{name}' Diameter must be a finite length greater than zero.");- var materialReference = (Property(body, "Material") ?? "Standard.Materials.StainlessSteel.304_Annealed").Trim('"');+ var materialReference = (wireFields.Read("Material") ?? "Standard.Materials.StainlessSteel.304_Annealed").Trim('"');var material = new MaterialResolver().Resolve(materialReference);if (!material.IsSuccess || material.Material is null)return Fail("wireform-material-unresolved", material.Message ?? $"Material '{materialReference}' could not be resolved.");- if (!TryVector(Property(body, "Origin"), out var origin))+ if (!TryVector(frameFields.Read("Origin"), out var origin, length: true))return Fail("wireform-start-frame-invalid", $"WireForm '{name}' requires StartFrame Origin: [x,y,z].");- if (!TryVector(Property(body, "Tangent"), out var tangentVector) || !TryDirection(tangentVector, out var tangent))+ if (!TryVector(frameFields.Read("Tangent"), out var tangentVector) || !TryDirection(tangentVector, out var tangent))return Fail("wireform-start-frame-invalid", $"WireForm '{name}' requires a nonzero StartFrame Tangent.");- if (!TryVector(Property(body, "Up"), out var upVector))+ if (!TryVector(frameFields.Read("Up"), out var upVector))return Fail("wireform-start-frame-invalid", $"WireForm '{name}' requires StartFrame Up.");var upRejected = upVector - tangent.ToVector() * Dot(upVector, tangent.ToVector());if (!TryDirection(upRejected, out var up))return Fail("wireform-start-frame-invalid", $"WireForm '{name}' Up must not be parallel to Tangent.");+ if (wireFields.Complete(children) is { } rootError) return Fail("wireform-fields-invalid", rootError);+ if (!ReferenceEquals(frameFields, wireFields) && frameFields.Complete() is { } frameError) return Fail("wireform-fields-invalid", frameError);var state = new WireState(new(origin.X, origin.Y, origin.Z), tangent, up, 0d);var operations = new List<WireFormOperationAir>();var provenance = new List<WireFormOperationProvenance>();@@ -183,14 +214,16 @@ public static class WireFormAuthoringif (operationClose < 0) return Fail("wireform-operation-malformed", $"Operation '{match.Groups["name"].Value}' has no closing brace.");var operationBody = body[(operationOpen + 1)..operationClose];var operationName = match.Groups["name"].Value;+ var operationFields = new WireFormFields(match.Groups["kind"].Value, operationBody);provenance.Add(new(operationName,new FirmamentV2SourceSpan(open + 1 + match.Index, operationClose - match.Index + 1),FirmamentV2Parser.ReadAuthoredFields(operationBody, open + 1 + operationOpen + 1)));var ordinal = operations.Count + 1;if (match.Groups["kind"].Value == "Straight"){- if (!TryLength(Property(operationBody, "Length"), out var length) || length <= 0d)+ if (!TryLength(operationFields.Read("Length"), out var length) || length <= 0d)return Fail("wireform-straight-length-invalid", $"{operationName}: Length must be finite and greater than zero.");+ if (operationFields.Complete() is { } straightError) return Fail("wireform-fields-invalid", straightError);var output = state with { Position = state.Position + state.Tangent.ToVector() * length, AccumulatedLengthMm = state.AccumulatedLengthMm + length };operations.Add(new WireStraightAir(operationName, ordinal, length, state, output));state = output;@@ -218,15 +251,16 @@ public static class WireFormAuthoringoperations.Add(knotResult.Value); state = knotResult.Value.Output; continue;}- if (!TryLength(Property(operationBody, "Radius"), out var radius) || radius <= 0d)+ if (!TryLength(operationFields.Read("Radius"), out var radius) || radius <= 0d)return Fail("wireform-bend-radius-invalid", $"{operationName}: centerline Radius must be finite and greater than zero.");if (radius <= diameter / 2d + ToleranceContext.Default.Linear)return Fail("wireform-bend-radius-invalid", $"{operationName}: centerline Radius {radius:G6} mm must exceed wire radius {diameter / 2d:G6} mm (geometric-only policy).");- if (!TryAngle(Property(operationBody, "Angle"), out var angle) || Math.Abs(angle) <= ToleranceContext.Default.Angular || Math.Abs(angle) > Math.PI + ToleranceContext.Default.Angular)+ if (!TryAngle(operationFields.Read("Angle"), out var angle) || Math.Abs(angle) <= ToleranceContext.Default.Angular || Math.Abs(angle) > Math.PI + ToleranceContext.Default.Angular)return Fail("wireform-bend-angle-invalid", $"{operationName}: Angle must be nonzero and no greater than 180 degrees in magnitude.");- var plane = Property(operationBody, "Plane") ?? "Up";+ var plane = operationFields.Read("Plane") ?? "Up";if (plane is not ("Up" or "Right"))return Fail("wireform-bend-plane-invalid", $"{operationName}: Plane must be Up or Right in the current local frame.");+ if (operationFields.Complete() is { } bendError) return Fail("wireform-fields-invalid", bendError);var authoredNormal = plane == "Up" ? state.Up : state.Right;var axis = angle >= 0d ? authoredNormal : Direction3D.Create(authoredNormal.ToVector() * -1d);var sweep = Math.Abs(angle);@@ -271,7 +305,7 @@ public static class WireFormAuthoringvar match = Regex.Match(text, $@"^(?<value>[-+.\deE]+){unit}$", RegexOptions.CultureInvariant);return match.Success && double.TryParse(match.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);}- private static bool TryVector(string? text, out Vector3D value)+ private static bool TryVector(string? text, out Vector3D value, bool length = false){value = default;if (text is null) return false;@@ -280,7 +314,7 @@ public static class WireFormAuthoringvar values = new double[3];for (var i = 0; i < 3; i++){- var token = parts[i].EndsWith("mm", StringComparison.Ordinal) ? parts[i][..^2] : parts[i];+ var token = length && parts[i].EndsWith("mm", StringComparison.Ordinal) ? parts[i][..^2] : parts[i];if (!double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out values[i]) || !double.IsFinite(values[i])) return false;}value = new(values[0], values[1], values[2]); return true;diff --git a/Aetheris.Kernel.Firmament/Materializer/WireFormFields.cs b/Aetheris.Kernel.Firmament/Materializer/WireFormFields.csnew file mode 100644index 00000000..a8f639a5--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/WireFormFields.cs@@ -0,0 +1,38 @@+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.Materializer;++/// <summary>Consumption at the wire operation owner; field vocabulary comes from+/// the reads performed by that owner, not a separate validation schema.</summary>+internal sealed class WireFormFields+{+ private readonly string source;+ private readonly FirmamentSyntaxFields fields;+ private readonly List<string> diagnostics = [];+ public DeclarationSyntax Declaration { get; }++ public WireFormFields(string kind, string body)+ {+ source = kind + " {\n" + body + "\n}";+ var syntax = FirmamentSyntaxParser.Parse(source);+ diagnostics.AddRange(syntax.Diagnostics.Select(d => d.Code + ": " + d.Message));+ // A malformed fragment must remain a diagnostic, including callers of+ // the direct API that have not passed document admission first.+ Declaration = syntax.Document.Statements.OfType<DeclarationSyntax>().FirstOrDefault()+ ?? FirmamentSyntaxParser.Parse(kind + " {}").Document.Statements.OfType<DeclarationSyntax>().Single();+ fields = new(Declaration, diagnostics);+ }++ public string? Read(string name)+ {+ var value = fields.Take(name);+ return value is null ? null : source.Substring(value.Span.Start, value.Span.Length);+ }++ public string? Complete(IReadOnlySet<StatementSyntax>? children = null)+ {+ fields.Complete(consumedStatements: children);+ return diagnostics.Count == 0 ? null : string.Join("; ", diagnostics.Select(d =>+ FirmamentV2.FirmamentInterop.FirmamentV2DiagnosticAdapter.FromParserDiagnosticCode(d).Message));+ }+}diff --git a/Aetheris.Kernel.Firmament/Materializer/WireKnots.cs b/Aetheris.Kernel.Firmament/Materializer/WireKnots.csindex 091a7c6c..46b037fb 100644--- a/Aetheris.Kernel.Firmament/Materializer/WireKnots.cs+++ b/Aetheris.Kernel.Firmament/Materializer/WireKnots.cs@@ -66,14 +66,15 @@ internal static class WireKnotAuthoringinternal static KernelResult<WireKnotPathAir> Create(string name, int ordinal, string body, WireState authoredFrame, double diameter){- var familyText = WireFormAuthoring.Property(body, "Family") ?? name;+ var fields = new WireFormFields("Knot", body);+ var familyText = fields.Read("Family") ?? name;if (!Enum.TryParse<WireKnotFamily>(familyText, false, out var family))return Fail("wireform-knot-parameters-invalid", name, "Family must be Trefoil, FigureEight, or TorusKnot.");- var handText = WireFormAuthoring.Property(body, "Handedness") ?? "RightHanded";+ var handText = fields.Read("Handedness") ?? "RightHanded";if (!Enum.TryParse<WireCoilHandedness>(handText, false, out var handedness))return Fail("wireform-knot-parameters-invalid", name, "Handedness must be RightHanded or LeftHanded.");var phase = 0d;- var phaseText = WireFormAuthoring.Property(body, "Phase") ?? WireFormAuthoring.Property(body, "StartPhase");+ var phaseText = fields.Read("Phase") ?? fields.Read("StartPhase");if (phaseText is not null && !WireFormAuthoring.TryAngle(phaseText, out phase))return Fail("wireform-knot-parameters-invalid", name, "Phase must be a finite angle.");@@ -81,20 +82,21 @@ internal static class WireKnotAuthoringdouble scale, major = 0d, minor = 0d;if (family == WireKnotFamily.TorusKnot){- if (!Integer(body, "P", out var pi) || !Integer(body, "Q", out var qi) || pi < 2 || qi < 2)+ if (!Integer(fields, "P", out var pi) || !Integer(fields, "Q", out var qi) || pi < 2 || qi < 2)return Fail("wireform-knot-parameters-invalid", name, "TorusKnot requires integers P >= 2 and Q >= 2.");if (Gcd(pi, qi) != 1)return Fail("wireform-knot-not-single-component", name, $"P={pi}, Q={qi} have gcd={Gcd(pi, qi)} and define a link, not one knot component.");- if (!Length(body, "MajorRadius", out major) || !Length(body, "MinorRadius", out minor) || major <= 0d || minor <= 0d || major <= minor)+ if (!Length(fields, "MajorRadius", out major) || !Length(fields, "MinorRadius", out minor) || major <= 0d || minor <= 0d || major <= minor)return Fail("wireform-knot-parameters-invalid", name, "TorusKnot requires MajorRadius > MinorRadius > 0.");p = pi; q = qi; scale = major;}else{- if (!Length(body, "Scale", out scale) || scale <= 0d)+ if (!Length(fields, "Scale", out scale) || scale <= 0d)return Fail("wireform-knot-scale-invalid", name, "Scale must be a finite positive length.");}+ if (fields.Complete() is { } fieldError) return Fail("wireform-fields-invalid", name, fieldError);var basisX = authoredFrame.Tangent;var basisZ = authoredFrame.Up;var basisY = Direction3D.Create(WireFormAuthoring.Cross(basisZ.ToVector(), basisX.ToVector()));@@ -117,8 +119,8 @@ internal static class WireKnotAuthoringreturn KernelResult<WireKnotPathAir>.Success(seed with { Qualification = qualification, FrameClosure = closure });}- private static bool Length(string body, string name, out double value) => WireFormAuthoring.TryLength(WireFormAuthoring.Property(body, name), out value);- private static bool Integer(string body, string name, out int value) => int.TryParse(WireFormAuthoring.Property(body, name), NumberStyles.Integer, CultureInfo.InvariantCulture, out value);+ private static bool Length(WireFormFields fields, string name, out double value) => WireFormAuthoring.TryLength(fields.Read(name), out value);+ private static bool Integer(WireFormFields fields, string name, out int value) => int.TryParse(fields.Read(name), NumberStyles.Integer, CultureInfo.InvariantCulture, out value);private static int Gcd(int a, int b) { while (b != 0) (a, b) = (b, a % b); return Math.Abs(a); }private static KernelResult<WireKnotPathAir> Fail(string code, string name, string message) => KernelResult<WireKnotPathAir>.Failure([new(Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Core.Diagnostics.KernelDiagnosticSeverity.Error,diff --git a/Aetheris.Kernel.Firmament/Materializer/WireRoute.cs b/Aetheris.Kernel.Firmament/Materializer/WireRoute.csindex c4732d07..d3980edc 100644--- a/Aetheris.Kernel.Firmament/Materializer/WireRoute.cs+++ b/Aetheris.Kernel.Firmament/Materializer/WireRoute.cs@@ -19,11 +19,12 @@ public static class WireRouteAuthoringpublic static KernelResult<WireFormFeatureAir> Parse(string source){- source = FirmamentV2.FirmamentSourceSpelling.Normalize(source);+ var frontend = FirmamentFrontendSchemas.Select(source);+ if (!frontend.IsSuccess) return Fail(frontend.Diagnostics[0].Split(':')[0], string.Join("; ", frontend.Diagnostics));+ source = frontend.Source;var syntax = FirmamentV2.Syntax.FirmamentSyntaxParser.Parse(source);var scopeDiagnostics = new List<string>();- FirmamentV2.FirmamentV2Parser.BindMechanicalScope(FirmamentV2.Syntax.FirmamentSyntaxTraversal.Declarations(syntax.Document)- .Where(d => d.Type.Name.Text == "Static").Cast<FirmamentV2.Syntax.StatementSyntax>().ToArray(), scopeDiagnostics);+ WireFormAuthoring.BindConstructionScope(syntax.Document, "WireRoute", scopeDiagnostics);if (scopeDiagnostics.Count > 0)return Fail(scopeDiagnostics[0].Split(':')[0], string.Join("; ", scopeDiagnostics));// Comments cannot contribute operations or fields.diff --git a/docs/public/reference/language/compatibility.md b/docs/public/reference/language/compatibility.mdindex 12bcd4f0..07927d0a 100644--- a/docs/public/reference/language/compatibility.md+++ b/docs/public/reference/language/compatibility.md@@ -7,9 +7,12 @@ read it; do not write it.## Firmament V1-Lowercase `model`, `units mm`, `solid name: Box`, `modify` and `hole<shaft>` are+The historical combination `model` with `units mm`, `solid name: Box`, `modify` and `hole<shaft>` areV1 forms, still accepted for compatibility. Bare lengths inherit millimetres only in the historical-primitive grammar that admits them. This is not a second preferred style.+primitive grammar and domain fields that admit them. Length fields in current+mechanical authoring require explicit units. Historical Piping, Structural,+SectionChain and Set positions may accept bare millimetres; WireForm Length+requires a unit. An explicit angle is never a substitute for a length. This is not a second preferred style.Historical immutable Box derivation uses`solid tall: stock with { size: [30, 24, 20] }`. Exposure uses@@ -23,6 +26,12 @@ The formatter preserves names, published members and numeric values. It doesnot migrate solid grammar into native declarations or prove a program builds.Validate the consuming artifact after formatting.+A lowercase `model` wrapping native V2 declarations is a case alias for `Model`;+it does not switch native source into the historical `solid` grammar. Constructs+use PascalCase, built-in fields use camelCase, and connectives such as `using`,+`as`, `on` and `with` use lowercase. Established aliases are normalized at syntax+positions, preserving user-defined names and engineering values.+## Known inconsistenciesFirmament's preferred style is more consistent than what every domain enforces.@@ -66,3 +75,13 @@ definition/use links the compiler has.If you find source that is silently ignored, or a documented form that does notbehave as described, that is a bug. Capability limits are listed in[supported features](../supported-features.md).++Reusable Templates and Features are recipes: material capability and value checks+run on their concrete specializations. An unused recipe does not prove a+supported materialization. Record members and Concept Struct publications are+authored data, not a fixed built-in field vocabulary. Unknown fields in a+materialized built-in construct are errors, including fields inside WireForm+operations, SectionChain guides, assembly occurrences and published Semantic+blocks. `validate --parse-only` reports a limited validation level; normal+validation performs the owning domain admission and required engineering+preflight, which can take time for swept or spline-heavy geometry.diff --git a/scripts/qualify-release-corpus.py b/scripts/qualify-release-corpus.pynew file mode 100644index 00000000..16b507b5--- /dev/null+++ b/scripts/qualify-release-corpus.py@@ -0,0 +1,55 @@+"""Record real CLI admission and emitted bytes; compare against a frozen baseline."""+import argparse+import hashlib+import json+from pathlib import Path+import subprocess+import time+++def run(args):+ root = Path(__file__).resolve().parents[1]+ output = args.output.resolve()+ output.mkdir(parents=True, exist_ok=False)+ sources = sorted(p for p in (root / 'fixtures/Canonical').rglob('*')+ if p.suffix in ('.firmament', '.firmasm', '.firmscene'))+ rows = []+ for i, source in enumerate(sources):+ relative = source.relative_to(root).as_posix()+ directory = output / source.relative_to(root / 'fixtures/Canonical')+ directory.mkdir(parents=True)+ row = {'source': relative}+ for verb in ('validate', 'build'):+ command = ['dotnet', str(args.cli.resolve()), verb, str(source), '--json']+ if verb == 'build':+ command += ['--out', str(directory / 'model.step')]+ start = time.monotonic()+ try:+ p = subprocess.run(command, capture_output=True, text=True, encoding='utf-8', timeout=120)+ (directory / (verb + '.json')).write_text(p.stdout, encoding='utf-8')+ (directory / (verb + '.stderr.txt')).write_text(p.stderr, encoding='utf-8')+ row[verb] = {'exit': p.returncode, 'seconds': round(time.monotonic() - start, 3)}+ except subprocess.TimeoutExpired:+ row[verb] = {'exit': 'timeout', 'seconds': 120}+ artifact = directory / 'model.step'+ row['sha256'] = hashlib.sha256(artifact.read_bytes()).hexdigest() if artifact.is_file() else None+ rows.append(row)+ (output / 'summary.json').write_text(json.dumps(rows, indent=2) + '\n', encoding='utf-8')+ print(f'{i+1}/{len(sources)} {relative}: {row["validate"]["exit"]}/{row["build"]["exit"]}', flush=True)+ if args.baseline:+ before = {r['source']: r for r in json.loads((args.baseline / 'summary.json').read_text())}+ differences = [r for r in rows if r['source'] not in before or+ any(r[k]['exit'] != before[r['source']][k]['exit'] for k in ('validate', 'build')) or+ r['sha256'] != before[r['source']]['sha256']]+ (output / 'differences.json').write_text(json.dumps(differences, indent=2) + '\n')+ print(f'{len(differences)} differences require explicit classification.')+ if any(r[v]['exit'] == 'timeout' for r in rows for v in ('validate', 'build')):+ raise SystemExit('Corpus timed out: qualification incomplete.')+++if __name__ == '__main__':+ p = argparse.ArgumentParser(description=__doc__)+ p.add_argument('--cli', type=Path, required=True)+ p.add_argument('--output', type=Path, required=True)+ p.add_argument('--baseline', type=Path)+ run(p.parse_args())diff --git a/test-support/ReleaseAdmissionProbe/Program.cs b/test-support/ReleaseAdmissionProbe/Program.csnew file mode 100644index 00000000..cfab890e--- /dev/null+++ b/test-support/ReleaseAdmissionProbe/Program.cs@@ -0,0 +1,65 @@+using System.Text.Json;+using Aetheris.CLI;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++if (args.Length is not (1 or 2)) throw new ArgumentException("Usage: ReleaseAdmissionProbe <evidence-directory> [previous-summary.json]");+var root = Directory.GetCurrentDirectory();+var output = Path.GetFullPath(args[0]);+Directory.CreateDirectory(output);+if (File.Exists(Path.Combine(output, "probes.jsonl"))) throw new ArgumentException("Use a fresh evidence directory.");+var replay = args.Length == 2 ? JsonDocument.Parse(File.ReadAllText(args[1])).RootElement.EnumerateArray()+ .Where(r => r.GetProperty("accepted").GetBoolean() && r.GetProperty("category").GetString() == "closed-authoring")+ .Select(r => (Path.GetFullPath(r.GetProperty("source").GetString()!), r.GetProperty("offset").GetInt32())).ToHashSet() : null;+var results = new List<object>();+var files = Directory.GetFiles(Path.Combine(root, "fixtures/Canonical"), "*", SearchOption.AllDirectories)+ .Where(p => Path.GetExtension(p) is ".firmament" or ".firmasm" or ".firmscene")+ .Where(p => !Path.GetFileName(p).StartsWith(".release-probe-", StringComparison.Ordinal)).Select(Path.GetFullPath).Order().ToArray();+foreach (var file in files)+{+ if (replay is not null && !replay.Any(r => r.Item1 == file)) continue;+ var source = File.ReadAllText(file);+ if (Validate(file).Exit != 0) continue;+ var syntax = FirmamentSyntaxParser.Parse(source).Document;+ var declarations = FirmamentSyntaxTraversal.Declarations(syntax).Where(d => d.Body is { Delimited: true }).ToArray();+ var candidates = declarations.Select(d => (Body: d.Body!, Owner: d.Type.Name.Text, Name: d.Name?.Text,+ Data: d.Type.Name.Text is "Record" or "Static" or "Table" || d.Type.Name.Text == "Struct" && d.Modifiers.Any(m => m.Name.Text == "Concept")))+ .Concat(FirmamentSyntaxTraversal.Expressions(syntax).OfType<ObjectSyntax>().Where(o => o.Body.Delimited)+ .Select(o => (Body: o.Body, Owner: FirmamentSyntaxValues.Reference(o.Type) ?? "object", Name: o.Name?.Text, Data: false)))+ .DistinctBy(c => c.Body.ContentSpan.Start);+ foreach (var candidate in candidates)+ {+ var position = candidate.Body.ContentSpan.Start;+ if (replay is not null && !replay.Contains((file, position))) continue;+ var mutant = source.Insert(position, " zzUnknownField: 3mm; ");+ // Real CLI include/resource resolution requires the original module directory.+ // Only evidence is retained; the temporary source is always removed.+ var path = Path.Combine(Path.GetDirectoryName(file)!, ".release-probe-" + Guid.NewGuid().ToString("N") + Path.GetExtension(file));+ try+ {+ File.WriteAllText(path, mutant);+ var result = Validate(path);+ var authoredData = candidate.Data;+ var template = declarations.Any(d => (d.Type.Name.Text == "Feature" || d.Modifiers.Any(m => m.Name.Text == "Template")) &&+ position >= d.Span.Start && position < d.Span.Start + d.Span.Length);+ var row = new { source = Path.GetRelativePath(root, file), owner = candidate.Owner,+ name = candidate.Name, offset = position, accepted = result.Exit == 0,+ category = authoredData ? "authored-data" : template ? "template-definition" : "closed-authoring",+ diagnostics = result.Exit == 0 ? null : result.Output };+ results.Add(row);+ File.AppendAllText(Path.Combine(output, "probes.jsonl"), JsonSerializer.Serialize(row) + "\n");+ if (result.Exit == 0 && !authoredData) Console.WriteLine($"ACCEPTED {row.source}:{position} {row.owner} {row.category}");+ }+ finally { File.Delete(path); }+ }+ Console.WriteLine($"Probed {Path.GetRelativePath(root, file)} ({results.Count} cases)");+}+if (replay is not null && results.Count == 0) throw new InvalidOperationException("Replay matched no specimens; qualification is incomplete.");+File.WriteAllText(Path.Combine(output, "summary.json"), JsonSerializer.Serialize(results, new JsonSerializerOptions { WriteIndented = true }));++static (int Exit, string Output) Validate(string path)+{+ var stdout = new StringWriter();+ var stderr = new StringWriter();+ var exit = CliRunner.Run(["validate", path, "--json"], stdout, stderr);+ return (exit, stdout.ToString() + stderr);+}diff --git a/test-support/ReleaseAdmissionProbe/ReleaseAdmissionProbe.csproj b/test-support/ReleaseAdmissionProbe/ReleaseAdmissionProbe.csprojnew file mode 100644index 00000000..47a2c27f--- /dev/null+++ b/test-support/ReleaseAdmissionProbe/ReleaseAdmissionProbe.csproj@@ -0,0 +1,4 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework></PropertyGroup>+ <ItemGroup><ProjectReference Include="../../Aetheris.CLI/Aetheris.CLI.csproj" /></ItemGroup>+</Project>