Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Refactor humanoid deformation and pose workflows

Yuechen Li7051f060c4dc
diff --git a/Aetheris.CLI.Tests/RemainingDomainAdmissionCliTests.cs b/Aetheris.CLI.Tests/RemainingDomainAdmissionCliTests.cs
new file mode 100644
index 00000000..5eaa9594
--- /dev/null
+++ b/Aetheris.CLI.Tests/RemainingDomainAdmissionCliTests.cs
@@ -0,0 +1,46 @@
+using System.Text.Json;
+namespace Aetheris.CLI.Tests;
+public sealed class RemainingDomainAdmissionCliTests
+{
+ [Theory]
+ [InlineData("Structural/simple-structural-frame.firmament","UnifiedStructural","valid")]
+ [InlineData("Sculpting/sculpt-base-housing.firmament","UnifiedSculpting","valid")]
+ [InlineData("FEA/cantilever.firmament","UnifiedAnalysis","bound-not-solved")]
+ [InlineData("Drawings/bearing-block-production-drawing.firmament","UnifiedDrawing","valid")]
+ public void ValidationUsesTheActualDomainAdmissionLevel(string relative,string route,string status)
+ {
+ var output=new StringWriter();var error=new StringWriter();Assert.Equal(0,CliRunner.Run(["validate",Fixture(relative),"--json","--explain"],output,error));Assert.Empty(error.ToString());
+ using var json=JsonDocument.Parse(output.ToString());var report=json.RootElement.GetProperty("firmamentV2Validation");
+ Assert.Equal(status,report.GetProperty("status").GetString());Assert.Equal(route,report.GetProperty("parserRoute").GetString());
+ }
+ [Theory]
+ [InlineData("Structural/simple-structural-frame.firmament")]
+ [InlineData("Sculpting/sculpt-base-housing.firmament")]
+ [InlineData("FEA/cantilever.firmament")]
+ [InlineData("PlasticShell/plastic-shell-basic.firmament")]
+ public void ValidateAndBuildRejectOmittedIntentWithStructuredDiagnostics(string relative)
+ {
+ var directory=Path.Combine(Root(),"artifacts","local","remaining-domain-tests",Guid.NewGuid().ToString("N"));Directory.CreateDirectory(directory);
+ var source=File.ReadAllText(Fixture(relative));var at=source.IndexOf('{')+1;var path=Path.Combine(directory,"unknown.firmament");File.WriteAllText(path,source.Insert(at,"\nFillet Lost { radius: 1mm }\n"));
+ foreach(var command in new[]{"validate","build"})
+ {
+ var output=new StringWriter();var error=new StringWriter();
+ Assert.Equal(1,CliRunner.Run(command=="build"?[command,path,"--out",Path.Combine(directory,"model.step"),"--json"]:[command,path,"--json"],output,error));
+ using var json=JsonDocument.Parse(output.ToString());var root=json.RootElement;
+ if(root.TryGetProperty("firmamentV2Validation",out var validation))root=validation;
+ else if(root.TryGetProperty("plasticShellValidation",out var plastic))root=plastic;
+ var diagnostics=root.GetProperty("diagnostics");Assert.NotEmpty(diagnostics.EnumerateArray());
+ Assert.All(diagnostics.EnumerateArray(),d=>Assert.Equal(JsonValueKind.Object,d.ValueKind));
+ }
+ Assert.False(File.Exists(Path.Combine(directory,"model.step")));
+ }
+ [Fact]
+ public void NormalBuildDispatchesAnalysisToItsRealSolver()
+ {
+ var directory=Path.Combine(Root(),"artifacts","local","remaining-domain-tests",Guid.NewGuid().ToString("N"));var output=new StringWriter();var error=new StringWriter();
+ Assert.Equal(0,CliRunner.Run(["build",Fixture("FEA/cantilever.firmament"),"--out",directory,"--json"],output,error));
+ Assert.True(File.Exists(Path.Combine(directory,"analysis-ir.json")));Assert.True(File.Exists(Path.Combine(directory,"native-results.json")));
+ }
+ private static string Fixture(string path)=>Path.Combine(Root(),"fixtures","Canonical",path);
+ private static string Root(){var d=new DirectoryInfo(AppContext.BaseDirectory);while(d is not null&&!File.Exists(Path.Combine(d.FullName,"Aetheris.slnx")))d=d.Parent;return d!.FullName;}
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index b99d1f30..149f72b6 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -493,6 +493,18 @@ public static class CliRunner
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))
+ {
+ 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);
+ if(json)stdout.WriteLine(JsonSerializer.Serialize(new {command="build",success=false,diagnostics=new[]{diagnostic}},JsonOptions));
+ else stderr.WriteLine($"{sourcePath}:{diagnostic.Line}:{diagnostic.Column}: {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");
+ return 1;
+ }
+ if(FirmamentDrawingCompiler.IsDrawingSource(source))
+ 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))
+ 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))
{ 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))
@@ -787,19 +799,26 @@ public static class CliRunner
return 0;
}
+ private static void WriteFrontendDiagnostics(IEnumerable<FirmamentV2ValidationDiagnostic> diagnostics,TextWriter writer)
+ {
+ foreach(var d in diagnostics)writer.WriteLine($"{d.SourceFile}:{d.Line}:{d.Column}: {d.Severity} {d.Code}: {d.Message}");
+ }
+
private static int RunSculptingBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)
{
var compile = SculptingAuthoring.CompileFile(sourcePath);
+ var sourceText=File.ReadAllText(sourcePath);
+ var presented=SculptingAuthoring.KernelDiagnostics(compile).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,sourceText)).ToArray();
if (!compile.IsSuccess || compile.OutputState is null)
{
- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "Sculpting", diagnostics = compile.Diagnostics }, JsonOptions));
- else { stderr.WriteLine("Build failed:"); foreach (var diagnostic in compile.Diagnostics) stderr.WriteLine($"- [Error] {diagnostic.Code}: {diagnostic.Message}"); }
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "Sculpting", diagnostics = presented }, JsonOptions));
+ else { stderr.WriteLine("Build failed:"); WriteFrontendDiagnostics(presented,stderr); }
return 1;
}
var exportClock = Stopwatch.StartNew(); var export = SculptStepExporter.Export(compile.OutputState, compile.ModelName); exportClock.Stop();
if (!export.IsSuccess || export.Step is null)
{
- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "Sculpting", diagnostics = export.Diagnostics, surfaceInventory = export.Inventory }, JsonOptions));
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "Sculpting", diagnostics = SculptingAuthoring.KernelDiagnostics(compile with {Diagnostics=export.Diagnostics}).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,sourceText)).ToArray(), surfaceInventory = export.Inventory }, JsonOptions));
else foreach (var diagnostic in export.Diagnostics) stderr.WriteLine($"- [Error] {diagnostic.Code}: {diagnostic.Message}");
return 1;
}
@@ -823,7 +842,7 @@ public static class CliRunner
command = "build", success = true, input = Path.GetFullPath(sourcePath), output, domain = "Sculpting", model = compile.ModelName,
state = DescribeSculptState(compile.OutputState), states = compile.States.Values.Select(DescribeSculptState), geometricDelta = compile.OutputState.Delta,
validationEvidence = compile.OutputState.ValidationEvidence, surfacePatches = compile.OutputState.SurfacePatches, blendJudgment = compile.OutputState.BlendJudgment, surfaceInventory = export.Inventory, rationalNurbs = export.Inventory.RationalNurbs,
- deltaArtifact = deltaPath, timingsMilliseconds = compile.Timings with { StepExportMilliseconds = exportClock.Elapsed.TotalMilliseconds }, diagnostics = compile.Diagnostics
+ deltaArtifact = deltaPath, timingsMilliseconds = compile.Timings with { StepExportMilliseconds = exportClock.Elapsed.TotalMilliseconds }, diagnostics = presented
}, JsonOptions));
else
{
@@ -842,23 +861,25 @@ public static class CliRunner
private static int RunPlasticShellBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)
{
var compile = PlasticShellFirmament.CompileFile(sourcePath);
+ var sourceText=File.ReadAllText(sourcePath);
+ var presented=PlasticShellFirmament.KernelDiagnostics(compile).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,sourceText)).ToArray();
if (!compile.IsSuccess || compile.State is null)
{
- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "PlasticShell", diagnostics = compile.Diagnostics }, JsonOptions));
- else { stderr.WriteLine("Build failed:"); foreach (var diagnostic in compile.Diagnostics) stderr.WriteLine($"- [{diagnostic.Severity}] {diagnostic.Code}: {diagnostic.Message}"); }
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "PlasticShell", diagnostics = presented }, JsonOptions));
+ else { stderr.WriteLine("Build failed:"); WriteFrontendDiagnostics(presented,stderr); }
return 1;
}
var export = PlasticShellStepExporter.Export(compile.State, compile.ModelName);
if (!export.IsSuccess || export.Step is null)
{
- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "PlasticShell", diagnostics = export.Diagnostics, surfaceInventory = export.Inventory }, JsonOptions));
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "PlasticShell", diagnostics = PlasticShellFirmament.KernelDiagnostics(compile with {Diagnostics=export.Diagnostics}).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,sourceText)).ToArray(), surfaceInventory = export.Inventory }, JsonOptions));
else foreach (var diagnostic in export.Diagnostics) stderr.WriteLine($"- [{diagnostic.Severity}] {diagnostic.Code}: {diagnostic.Message}");
return 1;
}
var output = Path.GetFullPath(outPath ?? Path.ChangeExtension(sourcePath, ".step")); Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.WriteAllText(output, export.Step);
var evidencePath = Path.ChangeExtension(output, ".plastic-shell.json");
File.WriteAllText(evidencePath, JsonSerializer.Serialize(new { compile.ModelName, compile.State.Intent, compile.State.StateId, compile.State.Delta, compile.State.Evidence, surfaceInventory = export.Inventory, productBoundary = new { bodies = compile.State.Body.Topology.Bodies.Count(), shells = compile.State.Body.Topology.Shells.Count(), rationalProductSurfaces = export.Inventory.RationalProductSurfaces } }, JsonOptions));
- var report = new { command = "build", success = true, input = Path.GetFullPath(sourcePath), output, evidence = evidencePath, domain = "PlasticShell", model = compile.ModelName, plasticShell = compile.State.Intent, state = compile.State.StateId, geometricDelta = compile.State.Delta, manufacturingEvidence = compile.State.Evidence, surfaceInventory = export.Inventory, rationalProductSurfaces = export.Inventory.RationalProductSurfaces, diagnostics = compile.Diagnostics };
+ var report = new { command = "build", success = true, input = Path.GetFullPath(sourcePath), output, evidence = evidencePath, domain = "PlasticShell", model = compile.ModelName, plasticShell = compile.State.Intent, state = compile.State.StateId, geometricDelta = compile.State.Delta, manufacturingEvidence = compile.State.Evidence, surfaceInventory = export.Inventory, rationalProductSurfaces = export.Inventory.RationalProductSurfaces, diagnostics = presented };
if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));
else { stdout.WriteLine($"Built {Path.GetFileName(sourcePath)}"); stdout.WriteLine($"STEP: {output}"); stdout.WriteLine($"PlasticShell: {compile.State.Intent.PlasticShellId}; wall {compile.State.Evidence.WallThickness.Minimum:G6}..{compile.State.Evidence.WallThickness.Maximum:G6} mm; selected ribs {compile.State.Evidence.RibNetwork?.SelectedCandidate ?? "none"}"); stdout.WriteLine($"Manufacturing evidence: {evidencePath}"); }
return 0;
@@ -1158,8 +1179,8 @@ Model CanonicalPanel {
var result = FirmamentDrawingCompiler.Compile(source, output);
if (!result.IsSuccess)
{
- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, diagnostics = result.Diagnostics }, JsonOptions));
- else foreach (var diagnostic in result.Diagnostics) stderr.WriteLine(diagnostic);
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, diagnostics = result.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,source,File.Exists(source)?File.ReadAllText(source):null)).ToArray() }, JsonOptions));
+ else WriteFrontendDiagnostics(result.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,source,File.Exists(source)?File.ReadAllText(source):null)),stderr);
return 1;
}
var artifacts = result.Artifacts!;
@@ -1198,10 +1219,10 @@ Model CanonicalPanel {
command = "fea",
success = false,
input,
- diagnostics = compiled.Diagnostics.Select(diagnostic => new { diagnostic.Code, severity = diagnostic.Severity.ToString(), diagnostic.Message })
+ diagnostics = FirmamentAnalysisCompiler.KernelDiagnostics(compiled).Select(d=>FirmamentBuildAdmissionValidation.Present(d,input,File.ReadAllText(input))).ToArray()
}, JsonOptions));
else
- foreach (var diagnostic in compiled.Diagnostics) stderr.WriteLine($"{diagnostic.Code}: {diagnostic.Message}");
+ WriteFrontendDiagnostics(FirmamentAnalysisCompiler.KernelDiagnostics(compiled).Select(d=>FirmamentBuildAdmissionValidation.Present(d,input,File.ReadAllText(input))),stderr);
return 1;
}
if(latticeOverride is { } requestedLattice)compiled=compiled with{Analysis=compiled.Analysis with{Lattice=new Aetheris.Continuum.Lattice.LatticeSpec(compiled.Analysis.Body.ContinuumRegion.Bounds,requestedLattice.X,requestedLattice.Y,requestedLattice.Z)}};
@@ -1461,7 +1482,7 @@ Model CanonicalPanel {
{
var plastic = PlasticShellFirmament.Compile(source, fullPath);
var plasticReport = new { command = "inspect", success = plastic.IsSuccess, input = fullPath, domain = "PlasticShell", model = plastic.ModelName,
- plasticShell = plastic.Intent, state = plastic.State?.StateId, geometricDelta = plastic.State?.Delta, manufacturingEvidence = plastic.State?.Evidence, diagnostics = plastic.Diagnostics };
+ plasticShell = plastic.Intent, state = plastic.State?.StateId, geometricDelta = plastic.State?.Delta, manufacturingEvidence = plastic.State?.Evidence, diagnostics = PlasticShellFirmament.KernelDiagnostics(plastic).Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)).ToArray() };
if (json) stdout.WriteLine(JsonSerializer.Serialize(plasticReport, JsonOptions));
else if (plastic.IsSuccess && plastic.State is { } state)
{
@@ -1469,18 +1490,18 @@ Model CanonicalPanel {
if (state.Evidence.RibNetwork is { } ribs)
foreach (var candidate in ribs.Candidates) stdout.WriteLine($" {candidate.CandidateId}: eligible={candidate.Eligible}; support={candidate.Metrics.SupportProxy:F6}; flow={candidate.Metrics.FlowCompatibility:F6}; sink={candidate.Metrics.SinkProxy:F6}; length={candidate.Metrics.RibLength:F6}; complexity={candidate.Metrics.Complexity:F6}; utility={candidate.Metrics.Utility:F6}");
}
- else foreach (var diagnostic in plastic.Diagnostics) stderr.WriteLine($"error: {diagnostic.Code}: {diagnostic.Message}");
+ else WriteFrontendDiagnostics(PlasticShellFirmament.KernelDiagnostics(plastic).Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)),stderr);
return plastic.IsSuccess ? 0 : 1;
}
if (SculptingAuthoring.IsSculptingSource(source))
{
- var sculpt = SculptingAuthoring.Compile(source);
+ var sculpt = SculptingAuthoring.Compile(source,fullPath);
var sculptReport = new { command = "inspect", success = sculpt.IsSuccess, input = fullPath, domain = "Sculpting", model = sculpt.ModelName,
states = sculpt.States.Values.Select(state => new { state = DescribeSculptState(state), geometricDelta = state.Delta, validationEvidence = state.ValidationEvidence }),
- outputState = sculpt.OutputState?.StateId, timingsMilliseconds = sculpt.Timings, diagnostics = sculpt.Diagnostics };
+ outputState = sculpt.OutputState?.StateId, timingsMilliseconds = sculpt.Timings, diagnostics = SculptingAuthoring.KernelDiagnostics(sculpt).Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)).ToArray() };
if (json) stdout.WriteLine(JsonSerializer.Serialize(sculptReport, JsonOptions));
else if (sculpt.IsSuccess) { stdout.WriteLine($"Sculpting model {sculpt.ModelName}: {sculpt.States.Count} immutable states; output {sculpt.OutputState!.AuthoredName} ({sculpt.OutputState.StateId})"); foreach (var state in sculpt.States.Values) stdout.WriteLine($"State {state.AuthoredName}: {state.StateId} <- {state.PredecessorStateId?.Value ?? "<initial>"}"); }
- else foreach (var diagnostic in sculpt.Diagnostics) stderr.WriteLine($"error: {diagnostic.Code}: {diagnostic.Message}");
+ else WriteFrontendDiagnostics(SculptingAuthoring.KernelDiagnostics(sculpt).Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)),stderr);
return sculpt.IsSuccess ? 0 : 1;
}
if (PipingAuthoring.IsPipingSource(source))
@@ -1494,9 +1515,9 @@ Model CanonicalPanel {
if (StructuralAuthoring.IsStructuralSource(source))
{
var structural = StructuralAuthoring.Compile(source, fullPath);
- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "inspect", success = structural.IsSuccess, input = fullPath, domain = "Structural", structural = structural.Report, diagnostics = structural.Diagnostics }, JsonOptions));
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "inspect", success = structural.IsSuccess, input = fullPath, domain = "Structural", structural = structural.Report, diagnostics = structural.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)).ToArray() }, JsonOptions));
else if (structural.IsSuccess && structural.Report is { } structuralReport) stdout.WriteLine($"Structure {structuralReport.Structure}: {structuralReport.Members.Count} members, {structuralReport.Joints.Count} joints, {structuralReport.Welds.Count} welds, {structuralReport.CutList.Count} cut-list groups");
- else foreach (var diagnostic in structural.Diagnostics) stderr.WriteLine($"error: {diagnostic}");
+ else WriteFrontendDiagnostics(structural.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)),stderr);
return structural.IsSuccess ? 0 : 1;
}
if (frontend.Schema == FirmamentFrontendSchema.SectionChain)
@@ -2378,6 +2399,29 @@ 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))
+ {
+ var output=Path.GetFullPath(Path.Combine("artifacts","local","drawing-validation",Guid.NewGuid().ToString("N")));
+ try
+ {
+ var drawing=FirmamentDrawingCompiler.Compile(sourcePath,output);
+ var diagnostics=drawing.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,validationSource)).ToArray();
+ var payload=new {source=sourcePath,status=drawing.IsSuccess?"valid":"invalid",domain="Drawing",validationLevel=drawing.IsSuccess?"Built":"BuildRejected",parserRoute="UnifiedDrawing",diagnostics};
+ if(json)stdout.WriteLine(JsonSerializer.Serialize(new {firmamentV2Validation=payload},JsonOptions));
+ else {stdout.WriteLine(drawing.IsSuccess?"Drawing admitted.":"Drawing rejected.");foreach(var d in diagnostics)stderr.WriteLine($"{d.SourceFile}:{d.Line}:{d.Column}: {d.Severity} {d.Code}: {d.Message}");}
+ return drawing.IsSuccess?0:1;
+ }
+ finally {if(Directory.Exists(output))Directory.Delete(output,true);}
+ }
+ if (FirmamentAnalysisCompiler.IsAnalysisSource(validationSource))
+ {
+ var analysis=FirmamentAnalysisCompiler.Compile(frontend.Source,Path.GetFullPath(sourcePath),Path.GetDirectoryName(Path.GetFullPath(sourcePath)));
+ var diagnostics=FirmamentAnalysisCompiler.KernelDiagnostics(analysis).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,validationSource)).ToArray();
+ var payload=new {source=sourcePath,status=analysis.IsSuccess?"bound-not-solved":"invalid",domain="Analysis",validationLevel=analysis.IsSuccess?"BoundNotSolved":"BindingRejected",parserRoute="UnifiedAnalysis",diagnostics};
+ if(json)stdout.WriteLine(JsonSerializer.Serialize(new {firmamentV2Validation=payload},JsonOptions));
+ 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)
|| frontend.Schema == FirmamentFrontendSchema.Garment)
return GarmentCommand.Run(["inspect", sourcePath, .. (json ? new[] { "--json" } : Array.Empty<string>())], stdout, stderr);
@@ -2411,17 +2455,17 @@ Model CanonicalPanel {
if (PlasticShellFirmament.LooksLikePlasticShell(validationSource))
{
var plastic = PlasticShellFirmament.Compile(validationSource, Path.GetFullPath(sourcePath));
- var payload = new { source = sourcePath, status = plastic.IsSuccess ? "valid" : "invalid", domain = "PlasticShell", summary = new { fatalDiagnosticCount = plastic.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Error), warningDiagnosticCount = plastic.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Warning), gates = plastic.Intent?.Gates.Count ?? 0, standoffs = plastic.Intent?.Standoffs.Count ?? 0, ejectors = plastic.Intent?.Ejectors.Count ?? 0, ribCandidates = plastic.State?.Evidence.RibNetwork?.Candidates.Count ?? 0 }, diagnostics = plastic.Diagnostics };
+ var payload = new { source = sourcePath, status = plastic.IsSuccess ? "valid" : "invalid", domain = "PlasticShell", summary = new { fatalDiagnosticCount = plastic.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Error), warningDiagnosticCount = plastic.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Warning), gates = plastic.Intent?.Gates.Count ?? 0, standoffs = plastic.Intent?.Standoffs.Count ?? 0, ejectors = plastic.Intent?.Ejectors.Count ?? 0, ribCandidates = plastic.State?.Evidence.RibNetwork?.Candidates.Count ?? 0 }, diagnostics = PlasticShellFirmament.KernelDiagnostics(plastic).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,authoredValidationSource)).ToArray() };
if (json) stdout.WriteLine(JsonSerializer.Serialize(new { plasticShellValidation = payload }, JsonOptions));
- else stdout.WriteLine($"PlasticShell validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, {payload.summary.warningDiagnosticCount} warning)");
+ 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))
{
- var sculpt = SculptingAuthoring.Compile(validationSource);
- var payload = new { source = sourcePath, status = sculpt.IsSuccess ? "valid" : "invalid", domain = "Sculpting", summary = new { fatalDiagnosticCount = sculpt.Diagnostics.Count, warningDiagnosticCount = 0, states = sculpt.States.Count }, diagnostics = sculpt.Diagnostics };
+ var sculpt = SculptingAuthoring.Compile(validationSource,Path.GetFullPath(sourcePath));
+ var payload = new { source = sourcePath, status = sculpt.IsSuccess ? "valid" : "invalid", domain = "Sculpting", validationLevel=sculpt.IsSuccess?"Built":"BuildRejected", parserRoute="UnifiedSculpting", summary = new { fatalDiagnosticCount = sculpt.Diagnostics.Count, warningDiagnosticCount = 0, states = sculpt.States.Count }, diagnostics = SculptingAuthoring.KernelDiagnostics(sculpt).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,authoredValidationSource)).ToArray() };
if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
- else stdout.WriteLine($"Firmament V2 Sculpting validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");
+ 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+"))
@@ -2447,9 +2491,9 @@ Model CanonicalPanel {
if (StructuralAuthoring.IsStructuralSource(validationSource))
{
var structural = StructuralAuthoring.Compile(validationSource, Path.GetFullPath(sourcePath));
- var payload = new { source = sourcePath, status = structural.IsSuccess ? "valid" : "invalid", domain = "Structural", summary = new { fatalDiagnosticCount = structural.Diagnostics.Count, warningDiagnosticCount = 0, members = structural.Report?.Members.Count ?? 0, joints = structural.Report?.Joints.Count ?? 0 }, diagnostics = structural.Diagnostics };
+ var payload = new { source = sourcePath, status = structural.IsSuccess ? "valid" : "invalid", domain = "Structural", validationLevel=structural.IsSuccess?"Built":"BuildRejected", parserRoute="UnifiedStructural", summary = new { fatalDiagnosticCount = structural.Diagnostics.Count, warningDiagnosticCount = 0, members = structural.Report?.Members.Count ?? 0, joints = structural.Report?.Joints.Count ?? 0 }, diagnostics = structural.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,authoredValidationSource)).ToArray() };
if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
- else stdout.WriteLine($"Firmament V2 Structural validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");
+ 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)
diff --git a/Aetheris.Collaboration.Tests/Aetheris.Collaboration.Tests.csproj b/Aetheris.Collaboration.Tests/Aetheris.Collaboration.Tests.csproj
index 0a958b29..718bf5f4 100644
--- a/Aetheris.Collaboration.Tests/Aetheris.Collaboration.Tests.csproj
+++ b/Aetheris.Collaboration.Tests/Aetheris.Collaboration.Tests.csproj
@@ -2,6 +2,7 @@
<PropertyGroup><TargetFramework>net10.0</TargetFramework><IsPackable>false</IsPackable></PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Aetheris.Collaboration\Aetheris.Collaboration.csproj" />
+ <ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
diff --git a/Aetheris.Collaboration.Tests/ReviewCompilerTests.cs b/Aetheris.Collaboration.Tests/ReviewCompilerTests.cs
index fbc95c0a..dea1619e 100644
--- a/Aetheris.Collaboration.Tests/ReviewCompilerTests.cs
+++ b/Aetheris.Collaboration.Tests/ReviewCompilerTests.cs
@@ -14,6 +14,27 @@ Review DFM-004 {
}
""";
+ [Theory]
+ [InlineData("unknownIntent: true;")]
+ [InlineData("Fillet Lost { radius: 1mm }")]
+ [InlineData("status: Open;")]
+ public void ReviewCannotDiscardUnknownOrDuplicateIntent(string intent)
+ {
+ var at=Source.IndexOf('{')+1;var result=FirmamentReviewCompiler.Compile(Source.Insert(at,intent),"review.firmament");
+ Assert.False(result.IsSuccess);Assert.NotEmpty(result.Diagnostics);
+ Assert.Contains(result.SourceDiagnostics,d=>d.Span.Start>0 && d.Span.Length>0);
+ }
+
+ [Fact]
+ public void QuotedReviewTextPreservesEmbeddedSemicolons()
+ {
+ const string text="Accepted; this review does not mutate PMI.";
+ var source=Source.Replace("Accepted for the next authoritative revision.",text,StringComparison.Ordinal);
+ var result=FirmamentReviewCompiler.Compile(source,"review.firmament");
+ Assert.True(result.IsSuccess,string.Join(";",result.Diagnostics));
+ Assert.Equal(text,result.Review!.Threads.Single().Entries.Single(e=>e.Kind==ReviewEntryKind.Resolution).Text);
+ }
+
[Fact]
public void CompilesTypedThreadAndProposalWithoutMutatingCurrentValue()
{
diff --git a/Aetheris.Collaboration/ReviewIr.cs b/Aetheris.Collaboration/ReviewIr.cs
index f8bca9a8..289b4282 100644
--- a/Aetheris.Collaboration/ReviewIr.cs
+++ b/Aetheris.Collaboration/ReviewIr.cs
@@ -54,4 +54,8 @@ public sealed record ReviewCompilationResult(
bool IsSuccess,
ReviewIr? Review,
IReadOnlyList<string> Diagnostics,
- IReadOnlyList<(int Start, int Length)> SourceRanges);
+ IReadOnlyList<(int Start, int Length)> SourceRanges)
+{
+ public IReadOnlyList<ReviewSourceDiagnostic> SourceDiagnostics { get; init; } = [];
+}
+public sealed record ReviewSourceDiagnostic(string Code,string Message,Aetheris.Semantics.SemanticSourceSpan Span);
diff --git a/Aetheris.FEA.Tests/AnalysisAstAdmissionTests.cs b/Aetheris.FEA.Tests/AnalysisAstAdmissionTests.cs
new file mode 100644
index 00000000..564d6ab4
--- /dev/null
+++ b/Aetheris.FEA.Tests/AnalysisAstAdmissionTests.cs
@@ -0,0 +1,39 @@
+using Aetheris.FEA.Firmament;
+namespace Aetheris.FEA.Tests;
+public sealed class AnalysisAstAdmissionTests
+{
+ [Theory]
+ [InlineData("heigth: 1mm")]
+ [InlineData("Fillet Lost { radius: 1mm }")]
+ [InlineData("lattice: [4,2,1]; Lattice: [4,2,1]")]
+ public void UnknownAndDuplicateAnalysisIntentRejects(string intent)
+ {
+ var source=Source();var at=source.IndexOf("Analysis LinearElastic",StringComparison.Ordinal);at=source.IndexOf('{',at)+1;
+ var result=FirmamentAnalysisCompiler.Compile(source.Insert(at,intent+";"),"beam.firmament");
+ Assert.False(result.IsSuccess);Assert.Contains(result.Diagnostics,d=>d.Provenance is {Length:>0});
+ }
+ [Fact]
+ public void ExplicitEmptySettingsDoNotBecomeDefaults()
+ {
+ var source=Source();
+ Assert.Contains("Lattice: [12, 2, 2]",source);Assert.Contains("Components: [X, Y, Z]",source);
+ Assert.False(FirmamentAnalysisCompiler.Compile(source.Replace("Lattice: [12, 2, 2]","lattice: []",StringComparison.Ordinal)).IsSuccess);
+ Assert.False(FirmamentAnalysisCompiler.Compile(source.Replace("Components: [X, Y, Z]","components: []",StringComparison.Ordinal)).IsSuccess);
+ }
+ [Fact]
+ public void InvalidMaterialValueReturnsDiagnosticInsteadOfThrowing()
+ {
+ var source=Source().Replace("Material: Standard.Materials.Aluminum.6061_T6","Material Test { youngsModulus: 200GPa; poissonRatio: typo }",StringComparison.Ordinal);
+ // Preserve catalogue-independent evidence even when the canonical material name changes.
+ if(source==Source())source=Source().Replace("Material: Standard.Materials.Steel.S235JR","Material Test { youngsModulus: 200GPa; poissonRatio: typo }",StringComparison.Ordinal);
+ var result=FirmamentAnalysisCompiler.Compile(source,"beam.firmament");
+ Assert.False(result.IsSuccess);Assert.Contains(result.Diagnostics,d=>d.Code.Contains("poisson",StringComparison.Ordinal));
+ }
+ [Fact]
+ public void AnalysisCannotFallBackAroundMalformedV2Geometry()
+ {
+ var source=Source().Replace("Box Beam {","Box Beam { heigth: 2mm;",StringComparison.Ordinal);
+ var result=FirmamentAnalysisCompiler.Compile(source,"beam.firmament");Assert.False(result.IsSuccess);Assert.Null(result.Analysis);
+ }
+ private static string Source(){var d=new DirectoryInfo(AppContext.BaseDirectory);while(d is not null&&!File.Exists(Path.Combine(d.FullName,"Aetheris.slnx")))d=d.Parent;return File.ReadAllText(Path.Combine(d!.FullName,"fixtures","Canonical","FEA","cantilever.firmament"));}
+}
diff --git a/Aetheris.FEA/Firmament/FirmamentAnalysisCompiler.cs b/Aetheris.FEA/Firmament/FirmamentAnalysisCompiler.cs
index 838a5bec..a8eab4e0 100644
--- a/Aetheris.FEA/Firmament/FirmamentAnalysisCompiler.cs
+++ b/Aetheris.FEA/Firmament/FirmamentAnalysisCompiler.cs
@@ -1,4 +1,6 @@
using System.Globalization;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Scope = Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxScope;
using System.Text.RegularExpressions;
using Aetheris.Continuum.Cir;
using Aetheris.Continuum.Lattice;
@@ -28,19 +30,40 @@ public sealed record FirmamentAnalysisCompilation(LinearElasticAnalysisIr? Analy
/// <summary>Firmament analysis-intent compiler. Geometry, materials and selections are fully resolved before solver execution.</summary>
public static class FirmamentAnalysisCompiler
{
- private static readonly Regex Header=new(@"\banalysis\s+LinearElastic\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{",RegexOptions.CultureInvariant|RegexOptions.IgnoreCase);
+ public static IReadOnlyList<Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic> KernelDiagnostics(FirmamentAnalysisCompilation compilation) =>
+ compilation.Diagnostics.Select(d=>new Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic(
+ Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
+ d.Severity==AnalysisDiagnosticSeverity.Error?Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error:Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Warning,
+ d.Code+": "+d.Message,"Firmament.Analysis")
+ {OriginalSourceSpan=d.Provenance is {Length:>0} span?new(span.Start,span.Length):null}).ToArray();
+ public static bool IsAnalysisSource(string source) => source.Contains("LinearElastic", StringComparison.Ordinal)
+ && FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d => d.Type.Name.Text == "LinearElastic" && d.Modifiers.Any(m=>m.Name.Text is "Analysis" or "analysis"));
public static FirmamentAnalysisCompilation Compile(string source,string? sourcePath=null,string? sourceDirectory=null,IReadOnlyDictionary<string,FirmamentAnalysisResource>? resources=null,IMaterialResolver? materialResolver=null)
{
- var started=System.Diagnostics.Stopwatch.GetTimestamp();var diagnostics=new List<AnalysisDiagnostic>();var match=Header.Match(source);
- if(!match.Success)return Done(null,[Error("firmament-analysis-missing","No 'Analysis LinearElastic' declaration was found.",sourcePath)],started);
- var open=source.IndexOf('{',match.Index);var close=MatchingBrace(source,open);if(close<0)return Done(null,[Error("firmament-analysis-malformed","Analysis block has no closing brace.",sourcePath)],started);
- var block=source[(open+1)..close];var analysisSpan=new AnalysisProvenance(sourcePath??"<memory>",match.Index,close-match.Index+1,match.Value);
- var stripped=source.Remove(match.Index,close-match.Index+1);
+ var started=System.Diagnostics.Stopwatch.GetTimestamp();var diagnostics=new List<AnalysisDiagnostic>();
+ var binding=new FirmamentDomainBinding(source,sourcePath??"<memory>","LinearElastic",new HashSet<string>(StringComparer.Ordinal));
+ diagnostics.AddRange(binding.Diagnostics.Select(d=>new AnalysisDiagnostic(d.Code,AnalysisDiagnosticSeverity.Error,d.Message,
+ new(sourcePath??"<memory>",d.SourceSpan?.Start??0,d.SourceSpan?.Length??0,d.Target??"analysis admission"))));
+ if(diagnostics.Count>0)return Done(null,diagnostics,started);
+ source=binding.Source;
+ var declarations=FirmamentSyntaxTraversal.Declarations(binding.Document).ToArray();
+ var analyses=declarations.Where(d=>d.Type.Name.Text=="LinearElastic" && d.Modifiers.Any(m=>m.Name.Text is "Analysis" or "analysis")).ToArray();
+ if(analyses.Length!=1)return Done(null,[Error("firmament-analysis-cardinality","Exactly one Analysis LinearElastic declaration is required.",sourcePath)],started);
+ var declaration=analyses[0];
+ var block=new Scope(declaration,source,sourcePath??"<memory>",binding.Nominal,binding.OriginalSpan).AllowModifier("Analysis").AllowModifier("analysis");
+ var open=0;
+ var analysisSpan=new AnalysisProvenance(sourcePath??"<memory>",declaration.Span.Start,declaration.Span.Length,"Analysis LinearElastic "+declaration.Name?.Text);
+ var chars=source.ToCharArray();for(var i=declaration.Span.Start;i<declaration.Span.Start+declaration.Span.Length;i++)if(chars[i] is not ('\r' or '\n'))chars[i]=' ';
+ var stripped=new string(chars);
var modeText=Scalar(block,"mode")??nameof(AnalysisMode.ProductionSolid);
- if(!Enum.TryParse<AnalysisMode>(modeText,true,out var mode)){diagnostics.Add(Error("fea-analysis-mode-invalid",$"Analysis mode '{modeText}' is unsupported.",sourcePath));return Done(null,diagnostics,started);}
+ if((!Enum.TryParse<AnalysisMode>(modeText,true,out var mode)||!Enum.IsDefined(mode))){diagnostics.Add(Error("fea-analysis-mode-invalid",$"Analysis mode '{modeText}' is unsupported.",sourcePath));return Done(null,diagnostics,started);}
var bodyExpression=Scalar(block,"body")??string.Empty;
- var inlineCall=Regex.Match(bodyExpression,@"^(?:inlineSTEP|InlineStep)\s*\(\s*""(?<path>[^""]+)""\s*\)$",RegexOptions.CultureInvariant);
- var bodyName=inlineCall.Success?"body":bodyExpression;var resourceName=(Scalar(block,"bodyResource")??string.Empty).TrimStart('$');
+ var bodyValue=block.Take("Body");
+ var inlineCall=bodyValue as CallSyntax;
+ var inlinePath=inlineCall is {Arguments.Count:1} && FirmamentSyntaxValues.Reference(inlineCall.Target) is "inlineSTEP" or "InlineStep"
+ && inlineCall.Arguments[0].Name is null && inlineCall.Arguments[0].Value is LiteralSyntax {Kind:LiteralKind.String}
+ ? FirmamentSyntaxValues.Reference(inlineCall.Arguments[0].Value):null;
+ var bodyName=inlinePath is not null?"body":bodyExpression;var resourceName=(Scalar(block,"bodyResource")??string.Empty).TrimStart('$');
IContinuumRegion? region=null;string sourceKind;string? resourceHash=null;string? brepBodyId=null;string bodyId;IReadOnlyDictionary<string,string> semanticFaceIds=new Dictionary<string,string>();var namedRegions=new Dictionary<string,SemanticValue>(StringComparer.Ordinal);MidsurfacePatchGraph? midsurfacePatchGraph=null;SheetMetalPartIr? sheetMetalPart=null;
var sourceParse=FirmamentV2Parser.Parse(stripped,sourceDirectory);var directInline=sourceParse.Document?.Solids.SingleOrDefault(item=>item.Name==bodyName)?.InlineStep;
if(SheetMetalFirmament.LooksLikeSheetMetal(stripped))
@@ -58,8 +81,9 @@ public static class FirmamentAnalysisCompiler
var maxR=combined.Max(x=>x.Max.X-x.Min.X);var maxS=combined.Max(x=>x.Max.Y-x.Min.Y);
region=new AxisAlignedBoxRegion(new RegionId(bodyId+":sheetmetal-analysis-projection"),new(new(0,0,-1),new(maxR,maxS,1)));
}
- else if(resourceName.Length>0||directInline is not null||inlineCall.Success)
+ else if(resourceName.Length>0||directInline is not null||inlinePath is not null)
{
+ if(!sourceParse.IsSuccess && !AdmitResourceDocument(binding,source,sourcePath,declaration,diagnostics))return Done(null,diagnostics,started);
bodyId=bodyName.Length>0?bodyName:resourceName;sourceKind="InlineStep";
FirmamentAnalysisResource resource;
if(resourceName.Length>0)
@@ -81,7 +105,7 @@ public static class FirmamentAnalysisCompiler
}
else
{
- var relativePath=inlineCall.Groups["path"].Value;
+ var relativePath=inlinePath!;
var normalizedPath=Path.GetFullPath(relativePath,sourceDirectory??Directory.GetCurrentDirectory());
if(!File.Exists(normalizedPath)){diagnostics.Add(Error("firmament-analysis-inline-step-file-missing",$"InlineStep analysis file was not found: {normalizedPath}",sourcePath));return Done(null,diagnostics,started);}
var stepText=File.ReadAllText(normalizedPath);var imported=Step242Importer.ImportBody(stepText);
@@ -97,13 +121,13 @@ public static class FirmamentAnalysisCompiler
if(resource.Body.Topology.Faces.Count()==6&&resource.Body.Bindings.FaceBindings.All(binding=>resource.Body.Geometry.GetSurface(binding.SurfaceGeometryId).Kind==SurfaceGeometryKind.Plane))
{
var faceIds=new Dictionary<string,string>(StringComparer.Ordinal);
- foreach(var binding in resource.Body.Bindings.FaceBindings)
+ foreach(var faceBinding in resource.Body.Bindings.FaceBindings)
{
- var plane=resource.Body.Geometry.GetSurface(binding.SurfaceGeometryId).Plane!.Value;var n=plane.Normal.ToVector();
+ var plane=resource.Body.Geometry.GetSurface(faceBinding.SurfaceGeometryId).Plane!.Value;var n=plane.Normal.ToVector();
var token=double.Abs(n.X)>0.9?(double.Abs(plane.Origin.X-rawMin.X)<double.Abs(plane.Origin.X-rawMax.X)?"x-min":"x-max")
:double.Abs(n.Y)>0.9?(double.Abs(plane.Origin.Y-rawMin.Y)<double.Abs(plane.Origin.Y-rawMax.Y)?"y-min":"y-max")
:(double.Abs(plane.Origin.Z-rawMin.Z)<double.Abs(plane.Origin.Z-rawMax.Z)?"z-min":"z-max");
- faceIds[token]=binding.FaceId.Value.ToString(CultureInfo.InvariantCulture);
+ faceIds[token]=faceBinding.FaceId.Value.ToString(CultureInfo.InvariantCulture);
}
region=new ExactBrepBoxContinuumRegion(new RegionId(bodyId+":imported-box-cir"),size.X,size.Y,size.Z,Transform3D.CreateTranslation(center),faceIds);
semanticFaceIds=faceIds;
@@ -122,20 +146,27 @@ public static class FirmamentAnalysisCompiler
else
{
var parse=FirmamentV2Parser.Parse(stripped,sourceDirectory);
- var parsedBox=parse.Document?.Solids.SingleOrDefault(item=>item.Name==bodyName)?.Box;
- var units=parse.Document?.Units??Regex.Match(stripped,@"\bunits\s*:?\s*(?<u>[A-Za-z]+)",RegexOptions.CultureInvariant|RegexOptions.IgnoreCase).Groups["u"].Value;
+ var parsedSolid=parse.Document?.Solids.SingleOrDefault(item=>item.Name==bodyName);
+ var parsedBox=parsedSolid?.Box;
+ if(parsedSolid is not null && (parsedSolid.ConstructionPolicy!=FirmamentV2ConstructionPolicy.Solid || parsedSolid.Hollow is not null))
+ return Done(null,[Error("firmament-analysis-native-feature-unsupported","Native analysis cannot replace a hollow body with a filled Box. Analyze the exported STEP body.",sourcePath)],started);
+ var units=parse.Document?.Units??declarations.SelectMany(d=>d.Body?.Statements.OfType<FieldSyntax>()??[]).Where(f=>FirmamentSyntaxFields.SameField(f.Name.Text,"Units")).Select(f=>FirmamentSyntaxValues.Reference(f.Value)).FirstOrDefault()??"";
double[] sizeRaw;
if(parsedBox is not null)sizeRaw=parsedBox.Size.ToArray();
else
{
- var boxHeader=Regex.Match(stripped,$@"\bsolid\s+{Regex.Escape(bodyName)}\s*:\s*Box\s*\{{",RegexOptions.CultureInvariant|RegexOptions.IgnoreCase);
- if(!boxHeader.Success){diagnostics.Add(Error("firmament-analysis-body-unsupported",$"Body '{bodyName}' is not a Firmament Box/box-with-hole solid.",sourcePath));return Done(null,diagnostics,started);}
- var boxOpen=stripped.IndexOf('{',boxHeader.Index);var boxClose=MatchingBrace(stripped,boxOpen);sizeRaw=Numbers(Scalar(stripped[(boxOpen+1)..boxClose],"size"));
+ var legacyBoxes=declarations.Where(d=>d.Type.Name.Text=="solid" && d.Name?.Text==bodyName && FirmamentSyntaxValues.Reference(d.Annotation)=="Box").ToArray();
+ if(legacyBoxes.Length!=1){diagnostics.Add(Error("firmament-analysis-body-unsupported",$"Body '{bodyName}' is not an admitted Box body.",sourcePath));return Done(null,diagnostics,started);}
+ var boxScope=new Scope(legacyBoxes[0] with {Annotation=null},source,sourcePath??"<memory>",binding.Nominal,binding.OriginalSpan);
+ sizeRaw=Numbers(boxScope.Take("Size"));
+ diagnostics.AddRange(boxScope.CompleteTree().Select(d=>new AnalysisDiagnostic(d.Code,AnalysisDiagnosticSeverity.Error,d.Message,analysisSpan)));
}
if(sizeRaw.Length!=3){diagnostics.Add(Error("firmament-analysis-body-size-invalid",$"Body '{bodyName}' requires three Box dimensions.",sourcePath));return Done(null,diagnostics,started);}
var scale=UnitScale(units);if(scale is null){diagnostics.Add(Error("firmament-analysis-length-unit-unsupported",$"Analysis body length unit '{units}' is unsupported; use mm, cm, or m.",sourcePath));return Done(null,diagnostics,started);}
var size=sizeRaw.Select(value=>value*scale.Value).ToArray();var bounds=new BoundingBox3D(new(0,0,0),new(size[0],size[1],size[2]));
- var modify=Regex.Match(stripped,$@"\bmodify\s+{Regex.Escape(bodyName)}\s*\{{",RegexOptions.CultureInvariant|RegexOptions.IgnoreCase);double? holeRadius=null;
+ var legacyModify=declarations.Where(d=>d.Type.Name.Text=="modify" && d.Name?.Text==bodyName).ToArray();double? holeRadius=null;
+ var legacy = declarations.Any(d=>d.Type.Name.Text=="solid" && FirmamentSyntaxValues.Reference(d.Annotation)=="Box");
+ if(legacy && !AdmitLegacyGeometry(binding.Document,source,sourcePath,bodyName,declaration,diagnostics))return Done(null,diagnostics,started);
Point3D? holeCenter = null;
var modifications = parse.Document?.ModifyBlocks?.Where(item => item.TargetSolid == bodyName).ToArray() ?? [];
var semanticHoles = modifications.SelectMany(item => item.SemanticHoles).ToArray();
@@ -161,9 +192,20 @@ public static class FirmamentAnalysisCompiler
|| holeCenter.Value.Y - holeRadius <= 0 || holeCenter.Value.Y + holeRadius >= size[1])
return Done(null, [Error("firmament-analysis-native-hole-outside", "The analysis hole must remain strictly inside the Box's XY boundary.", sourcePath)], started);
}
- else if(modify.Success){var modifyOpen=stripped.IndexOf('{',modify.Index);var modifyClose=MatchingBrace(stripped,modifyOpen);var radiusMatch=Regex.Match(stripped[(modifyOpen+1)..modifyClose],@"\bradius\s*:\s*(?<v>[-+0-9.eE]+)",RegexOptions.CultureInvariant);if(radiusMatch.Success)holeRadius=Number(radiusMatch.Groups["v"].Value)*scale.Value;}
+ else if(legacyModify.Length>0)
+ {
+ var cuts=legacyModify.SelectMany(d=>FirmamentSyntaxTraversal.Declarations(d)).Where(d=>d.Type.Name.Text=="cut" && d.Name?.Text=="Cylinder").ToArray();
+ if(cuts.Length!=1)return Done(null,[Error("firmament-analysis-native-feature-unsupported","Legacy native analysis admits exactly one through-cylinder cut.",sourcePath)],started);
+ var cutScope=new Scope(cuts[0],source,sourcePath??"<memory>");var radius=cutScope.Take("Radius");var through=cutScope.Take("Through");
+ if(!Face(through,"-Z"))cutScope.Invalid("Through","Legacy analysis cut must reach face(-Z).");
+ if(!FirmamentSyntaxValues.TryMeasure(radius,"",out var r)||!double.IsFinite(r)||r<=0)cutScope.Invalid("Radius");
+ holeRadius=r*scale.Value;
+ diagnostics.AddRange(cutScope.CompleteTree().Select(d=>new AnalysisDiagnostic(d.Code,AnalysisDiagnosticSeverity.Error,d.Message,analysisSpan)));
+ }
+ if(semanticHoles.Length==0 && modifications.Length>0)return Done(null,[Error("firmament-analysis-native-feature-unsupported","Native analysis cannot omit Modify features; analyze exported STEP for this feature combination.",sourcePath)],started);
region=holeRadius is null?new AxisAlignedBoxRegion(new RegionId(bodyName+":cir"),bounds):new BlockWithCylindricalHoleRegion(new RegionId(bodyName+":cir"),bounds,holeRadius.Value,holeCenter);
- if(!parse.IsSuccess) diagnostics.Add(new("firmament-analysis-geometry-parser-fallback",AnalysisDiagnosticSeverity.Warning,"The bounded analysis body recognizer admitted Box/through-cylinder syntax while the general geometry parser reported: "+string.Join(",",parse.Diagnostics),analysisSpan));
+ if(!parse.IsSuccess && !legacy)
+ return Done(null,parse.Diagnostics.Select(code=>Error(code,"Native V2 geometry must pass normal frontend admission; no analysis fallback is permitted.",sourcePath)).ToArray(),started);
bodyId=bodyName;sourceKind="FirmamentNative";
}
var materialBlock=Nested(block,"material",out var materialName,out var materialStart);
@@ -179,7 +221,7 @@ public static class FirmamentAnalysisCompiler
else
{
materialReference=materialReference!.Trim();
- var referenceOffset=block.IndexOf(materialReference,StringComparison.Ordinal);var materialProv=new AnalysisProvenance(sourcePath??"<memory>",open+1+referenceOffset,materialReference.Length,"material: "+materialReference);
+ var referenceOffset=(block.Declaration.Body?.Statements.OfType<FieldSyntax>().FirstOrDefault(f=>FirmamentSyntaxFields.SameField(f.Name.Text,"Material"))?.Value.Span.Start??block.Start)-1;var materialProv=new AnalysisProvenance(sourcePath??"<memory>",open+1+referenceOffset,materialReference.Length,"material: "+materialReference);
var materialLookup=sheetMetalPart is null?materialReference:NativeSheetMetalMaterialReference(materialReference);var resolution=(materialResolver??new MaterialResolver()).Resolve(materialLookup);
if(!resolution.IsSuccess)
{
@@ -210,14 +252,16 @@ public static class FirmamentAnalysisCompiler
var constraints=new List<DisplacementConstraintIr>();
foreach(var nested in NestedAll(block,"Fixed"))
{
- var path=Scalar(nested.Body,"region")??"";var components=Components(Scalar(nested.Body,"components"));if(components.Count==0)components=[DisplacementComponent.X,DisplacementComponent.Y,DisplacementComponent.Z];var prov=new AnalysisProvenance(sourcePath??"<memory>",open+nested.Start,nested.Length,"fixed "+nested.Name);
+ var path=Scalar(nested.Body,"region")??"";var componentText=Scalar(nested.Body,"components");var components=Components(componentText,diagnostics,sourcePath);
+ if(componentText is null)components=[DisplacementComponent.X,DisplacementComponent.Y,DisplacementComponent.Z];
+ else if(components.Count==0)diagnostics.Add(Error("fea-displacement-component-empty","Fixed components must name at least one of X, Y or Z; omit the field for all three.",sourcePath));var prov=new AnalysisProvenance(sourcePath??"<memory>",open+nested.Start,nested.Length,"fixed "+nested.Name);
var normalized=NormalizeRegion(path,prov);if(normalized.Diagnostic is not null){diagnostics.Add(normalized.Diagnostic);continue;}
constraints.Add(new(nested.Name,normalized.Region!,components,new(0,0,0),prov));
}
var loads=new List<BoundaryLoadIr>();
foreach(var keyword in new[]{("Traction",BoundaryLoadKind.Traction),("Force",BoundaryLoadKind.ResultantForce),("Pressure",BoundaryLoadKind.Pressure)})foreach(var nested in NestedAll(block,keyword.Item1))
{
- var path=Scalar(nested.Body,"region")??"";var prov=new AnalysisProvenance(sourcePath??"<memory>",open+nested.Start,nested.Length,keyword.Item1+" "+nested.Name);var vector=Vector(Scalar(nested.Body,"vector"),keyword.Item2==BoundaryLoadKind.ResultantForce);var pressure=keyword.Item2==BoundaryLoadKind.Pressure?Stress(Scalar(nested.Body,"value")):0;
+ var path=Scalar(nested.Body,"region")??"";var prov=new AnalysisProvenance(sourcePath??"<memory>",open+nested.Start,nested.Length,keyword.Item1+" "+nested.Name);var vector=keyword.Item2==BoundaryLoadKind.Pressure?Vector3D.Zero:Vector(Scalar(nested.Body,"vector"),keyword.Item2==BoundaryLoadKind.ResultantForce);var pressure=keyword.Item2==BoundaryLoadKind.Pressure?Stress(Scalar(nested.Body,"value")):0;
var normalized=NormalizeRegion(path,prov);if(normalized.Diagnostic is not null){diagnostics.Add(normalized.Diagnostic);continue;}
var distribution=keyword.Item2 switch{BoundaryLoadKind.ResultantForce=>LoadDistributionPolicy.TotalResultantOverSelectedArea,BoundaryLoadKind.Traction=>LoadDistributionPolicy.TractionPerUnitArea,_=>LoadDistributionPolicy.PressureNormalToSurface};
loads.Add(new(nested.Name,keyword.Item2,normalized.Region!,vector,pressure,prov,distribution));
@@ -228,22 +272,22 @@ public static class FirmamentAnalysisCompiler
var prov=new AnalysisProvenance(sourcePath??"<memory>",open+nested.Start,nested.Length,"BodyForce "+nested.Name);
bodyForces.Add(new(nested.Name,Acceleration(Scalar(nested.Body,"acceleration")),prov));
}
- var latticeValues=Numbers(Scalar(block,"lattice"));
- if(latticeValues.Length is not (0 or 3)||latticeValues.Any(value=>!double.IsInteger(value)||value<1)){diagnostics.Add(Error("fea-invalid-lattice-dimensions","Lattice must contain exactly three positive integer dimensions.",sourcePath));return Done(null,diagnostics,started);}
+ var latticeExpression=block.Take("Lattice");var latticeValues=Numbers(latticeExpression);
+ if(latticeExpression is not null && latticeValues.Length!=3 ||latticeValues.Any(value=>!double.IsInteger(value)||value<1||value>int.MaxValue)){diagnostics.Add(Error("fea-invalid-lattice-dimensions","Lattice must contain exactly three positive integer dimensions.",sourcePath));return Done(null,diagnostics,started);}
var lattice=latticeValues.Length==3?new LatticeSpec(region.Bounds,(int)latticeValues[0],(int)latticeValues[1],(int)latticeValues[2]):new LatticeSpec(region.Bounds,12,6,2);
ExperimentalShellSettings? shellSettings=null;
if(mode==AnalysisMode.ExperimentalShell)
{
var thicknessText=Scalar(block,"thickness");
if(string.IsNullOrWhiteSpace(thicknessText)&&sheetMetalPart is null){diagnostics.Add(Error("thinwall-thickness-missing","ExperimentalShell requires an explicit Thickness for synthetic/native Box geometry in X0.",sourcePath));return Done(null,diagnostics,started);}
- var masterValues=Numbers(Scalar(block,"masterGrid"));
- if(masterValues.Length!=2||masterValues.Any(value=>!double.IsInteger(value)||value<1)){diagnostics.Add(Error("thinwall-master-grid-invalid","ExperimentalShell MasterGrid must contain exactly two positive integer dimensions.",sourcePath));return Done(null,diagnostics,started);}
+ var masterValues=Numbers(block.Take("MasterGrid"));
+ if(masterValues.Length!=2||masterValues.Any(value=>!double.IsInteger(value)||value<1||value>int.MaxValue)){diagnostics.Add(Error("thinwall-master-grid-invalid","ExperimentalShell MasterGrid must contain exactly two positive integer dimensions.",sourcePath));return Done(null,diagnostics,started);}
var orderText=Scalar(block,"order");var order=OptionalInteger(orderText,3);
var alphaText=Scalar(block,"alphaFictitious");var alpha=string.IsNullOrWhiteSpace(alphaText)?1e-12:ScalarNumber(alphaText);
var depthText=Scalar(block,"maxSubdivisionDepth");var depth=OptionalInteger(depthText,4);
var quadratureText=Scalar(block,"quadratureOrder");int? quadrature=string.IsNullOrWhiteSpace(quadratureText)?null:OptionalInteger(quadratureText,int.MinValue);
var mapText=Scalar(block,"geometryMap")??nameof(ThinWallGeometryMapKind.Flat);
- if(!Enum.TryParse<ThinWallGeometryMapKind>(mapText,true,out var map)){diagnostics.Add(Error("thinwall-geometry-unsupported",$"ExperimentalShell geometry map '{mapText}' is unsupported.",sourcePath));return Done(null,diagnostics,started);}
+ if((!Enum.TryParse<ThinWallGeometryMapKind>(mapText,true,out var map)||!Enum.IsDefined(map))){diagnostics.Add(Error("thinwall-geometry-unsupported",$"ExperimentalShell geometry map '{mapText}' is unsupported.",sourcePath));return Done(null,diagnostics,started);}
var radiusText=Scalar(block,"cylinderRadius");var angleText=Scalar(block,"cylinderAngle");
var resolvedThickness=sheetMetalPart is null?Length(thicknessText):sheetMetalPart.Thickness*.001;
shellSettings=new ExperimentalShellSettings(resolvedThickness,order,(int)masterValues[0],(int)masterValues[1],alpha,depth,quadrature,map,
@@ -255,29 +299,92 @@ public static class FirmamentAnalysisCompiler
if(sheetMetalPart is not null&&!string.IsNullOrWhiteSpace(thicknessText)&&double.Abs(Length(thicknessText)-sourceThickness)>double.Max(1e-12,sourceThickness*1e-9))
diagnostics.Add(Error("thinwall-thickness-source-mismatch",$"Analysis Thickness must not override native SheetMetal thickness {sourceThickness:R} m.",sourcePath));
}
- var requested=new HashSet<AnalysisResultField>();foreach(var item in (Scalar(block,"results")??"Displacement,Strain,Stress,ReactionForce").Trim('[',']').Split(',',StringSplitOptions.RemoveEmptyEntries|StringSplitOptions.TrimEntries)){if(Enum.TryParse<AnalysisResultField>(item,true,out var field))requested.Add(field);else diagnostics.Add(Error("fea-invalid-result-request",$"Analysis result '{item}' is unsupported.",sourcePath));}
+ var requested=new HashSet<AnalysisResultField>();foreach(var item in (Scalar(block,"results")??"Displacement,Strain,Stress,ReactionForce").Trim('[',']').Split(',',StringSplitOptions.RemoveEmptyEntries|StringSplitOptions.TrimEntries)){if(Enum.TryParse<AnalysisResultField>(item,true,out var field)&&Enum.IsDefined(field))requested.Add(field);else diagnostics.Add(Error("fea-invalid-result-request",$"Analysis result '{item}' is unsupported.",sourcePath));}
if(requested.Count==0){diagnostics.Add(Error("fea-invalid-result-request","Analysis must request at least one supported result field.",sourcePath));return Done(null,diagnostics,started);}
- var bodyProv=new AnalysisProvenance(sourcePath??"<memory>",match.Index,match.Length,"body "+bodyId,ExactBrepFaceId:brepBodyId);var ir=new LinearElasticAnalysisIr(match.Groups["name"].Value,AnalysisKind.LinearStaticElasticity,new(bodyId,sourceKind,region,brepBodyId,resourceHash,bodyProv),[material],constraints,loads,requested,lattice,analysisSpan,mode,shellSettings,midsurfacePatchGraph,bodyForces);
+ var bodyProv=new AnalysisProvenance(sourcePath??"<memory>",declaration.Span.Start,declaration.Span.Length,"body "+bodyId,ExactBrepFaceId:brepBodyId);var ir=new LinearElasticAnalysisIr(declaration.Name!.Text,AnalysisKind.LinearStaticElasticity,new(bodyId,sourceKind,region,brepBodyId,resourceHash,bodyProv),[material],constraints,loads,requested,lattice,analysisSpan,mode,shellSettings,midsurfacePatchGraph,bodyForces);
+ diagnostics.AddRange(block.CompleteTree().Select(d=>new AnalysisDiagnostic(d.Code,AnalysisDiagnosticSeverity.Error,d.Message,
+ new(sourcePath??"<memory>",d.SourceSpan?.Start??0,d.SourceSpan?.Length??0,d.Target??"analysis binding"))));
diagnostics.AddRange(AnalysisIrValidator.Validate(ir));return Done(ir,diagnostics,started);
}
- private sealed record NestedBlock(string Name,string Body,int Start,int Length);
- private static IEnumerable<NestedBlock> NestedAll(string source,string keyword){var regex=new Regex($@"\b{Regex.Escape(keyword)}\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{{",RegexOptions.CultureInvariant|RegexOptions.IgnoreCase);foreach(Match m in regex.Matches(source)){var open=source.IndexOf('{',m.Index);var close=MatchingBrace(source,open);if(close>open)yield return new(m.Groups["name"].Value,source[(open+1)..close],m.Index,close-m.Index+1);}}
- private static string? Nested(string source,string keyword,out string name,out int start){var item=NestedAll(source,keyword).FirstOrDefault();name=item?.Name??"";start=item?.Start??0;return item?.Body;}
- private static string? Scalar(string source,string name){var m=Regex.Match(source,$@"(?m)^\s*{Regex.Escape(name)}\s*:\s*(?<value>[^\r\n}}]+)",RegexOptions.CultureInvariant|RegexOptions.IgnoreCase);return m.Success?m.Groups["value"].Value.Trim():null;}
- private static int MatchingBrace(string source,int open){var depth=0;for(var i=open;i<source.Length;i++){if(source[i]=='{')depth++;else if(source[i]=='}'&&--depth==0)return i;}return-1;}
+ private sealed record NestedBlock(string Name,Scope Body,int Start,int Length);
+ // Explicit compatibility production. It never retries a failed V2 document by scanning text.
+ private static bool Face(ExpressionSyntax? expression,string axis) => expression is CallSyntax call
+ && FirmamentSyntaxValues.Reference(call.Target)=="face" && call.Arguments.Count==1
+ && call.Arguments[0].Name is null && FirmamentSyntaxValues.Reference(call.Arguments[0].Value)==axis;
+ private static bool AdmitResourceDocument(FirmamentDomainBinding binding,string source,string? path,DeclarationSyntax analysis,List<AnalysisDiagnostic> diagnostics)
+ {
+ var document=new DeclarationSyntax(new(new("document",binding.Document.Span),[],binding.Document.Span),null,[],[],null,null,[],null,new(binding.Document.Statements,binding.Document.Span),false,binding.Document.Span);
+ var root=new Scope(document,source,path??"<memory>",binding.Nominal,binding.OriginalSpan);
+ var models=root.Children("Model").Concat(root.Children("model")).ToArray();
+ if(models.Length>1){diagnostics.Add(Error("firmament-analysis-resource-owner-invalid","Use one Model for an imported-resource analysis.",path));return false;}
+ foreach(var scope in new[]{root}.Concat(models))
+ {
+ scope.Take("Units");
+ foreach(var item in scope.Declaration.Body?.Statements??[])
+ if(ReferenceEquals(item,analysis) || item is DeclarationSyntax data && binding.OwnsData(data))scope.Consume(item);
+ }
+ diagnostics.AddRange(root.CompleteTree().Select(d=>new AnalysisDiagnostic(d.Code,AnalysisDiagnosticSeverity.Error,d.Message,new(path??"<memory>",d.SourceSpan?.Start??0,d.SourceSpan?.Length??0,"analysis resource document"))));
+ return diagnostics.All(d=>d.Severity!=AnalysisDiagnosticSeverity.Error);
+ }
+
+ private static bool AdmitLegacyGeometry(DocumentSyntax document,string source,string? path,string body,DeclarationSyntax analysis,List<AnalysisDiagnostic> diagnostics)
+ {
+ var models=document.Statements.OfType<DeclarationSyntax>().Where(d=>d.Type.Name.Text is "model" or "Model").ToArray();
+ if(models.Length!=1 || document.Statements.Count!=1){diagnostics.Add(Error("firmament-analysis-legacy-document-unsupported","Legacy analysis requires one model containing one Box and its bounded through cut.",path));return false;}
+ var root=new Scope(models[0],source,path??"<memory>");root.Take("Units");root.Consume(analysis);
+ var solids=root.Children("solid");
+ if(solids.Count!=1 || solids[0].Name!=body || FirmamentSyntaxValues.Reference(solids[0].Declaration.Annotation)!="Box")
+ diagnostics.Add(Error("firmament-analysis-legacy-body-unsupported","Legacy analysis admits exactly one solid body: Box.",path));
+ foreach(var solid in solids){solid.AdmitAnnotation();solid.Take("Size");}
+ foreach(var modify in root.Children("modify"))
+ {
+ if(modify.Name!=body)modify.Invalid("target","Modify must target the analysis body.");
+ var regions=modify.Children("region");if(regions.Count!=1)modify.Invalid("region","Exactly one face-local through cut is supported.");
+ foreach(var region in regions)
+ {
+ if(region.Declaration.Clauses.Count!=1 || region.Declaration.Clauses[0].Kind!=ClauseKind.On || !Face(region.Declaration.Clauses[0].Value,"+Z"))
+ region.Invalid("on","Legacy analysis region must be on face(+Z).");
+ region.AdmitPlacement();
+ var cuts=region.Children("cut");if(cuts.Count!=1 || cuts[0].Name!="Cylinder")region.Invalid("cut");
+ foreach(var cut in cuts){cut.Take("Radius");if(!Face(cut.Take("Through"),"-Z"))cut.Invalid("Through");}
+ }
+ }
+ diagnostics.AddRange(root.CompleteTree().Select(d=>new AnalysisDiagnostic(d.Code,AnalysisDiagnosticSeverity.Error,d.Message,new(path??"<memory>",d.SourceSpan?.Start??0,d.SourceSpan?.Length??0,"legacy analysis geometry"))));
+ return diagnostics.All(d=>d.Severity!=AnalysisDiagnosticSeverity.Error);
+ }
+
+ private static IEnumerable<NestedBlock> NestedAll(Scope scope,string keyword)=>scope.Children(keyword,legacyCase:true).Select(s=>new NestedBlock(s.Name,s,s.Start,s.Length));
+ private static Scope? Nested(Scope scope,string keyword,out string name,out int start)
+ {
+ var matches=scope.Children(keyword,legacyCase:true);name=matches.FirstOrDefault()?.Name??"";start=matches.FirstOrDefault()?.Start??0;
+ if(matches.Count>1)scope.Invalid(keyword,"Only one nested declaration of this kind is admitted.");
+ return matches.Count==1?matches[0]:null;
+ }
+ private static string? Scalar(Scope scope,string name)=>scope.Raw(name);
private static double? UnitScale(string unit)=>unit.ToLowerInvariant() switch{"m"=>1,"cm"=>.01,"mm"=>.001,_=>null};
- private static double Number(string? text)=>double.Parse(text??"NaN",NumberStyles.Float,CultureInfo.InvariantCulture);
+ private static double Number(string? text)=>double.TryParse(text,NumberStyles.Float,CultureInfo.InvariantCulture,out var value)?value:double.NaN;
private static double ScalarNumber(string? text)=>double.TryParse(text,NumberStyles.Float,CultureInfo.InvariantCulture,out var value)?value:double.NaN;
private static int OptionalInteger(string? text,int defaultValue){if(string.IsNullOrWhiteSpace(text))return defaultValue;var value=ScalarNumber(text);return double.IsInteger(value)&&value>=int.MinValue&&value<=int.MaxValue?(int)value:int.MinValue;}
private static double Length(string? text){if(text is null)return double.NaN;var m=Regex.Match(text,@"^(?<v>[-+0-9.eE]+)\s*(?<u>mm|cm|m)$",RegexOptions.IgnoreCase);if(!m.Success)return double.NaN;return Number(m.Groups["v"].Value)*(UnitScale(m.Groups["u"].Value)??double.NaN);}
private static double Angle(string? text){if(text is null)return double.NaN;var m=Regex.Match(text,@"^(?<v>[-+0-9.eE]+)\s*(?<u>deg|rad)$",RegexOptions.IgnoreCase);if(!m.Success)return double.NaN;var value=Number(m.Groups["v"].Value);return m.Groups["u"].Value.Equals("deg",StringComparison.OrdinalIgnoreCase)?value*double.Pi/180:value;}
private static double Stress(string? text){if(text is null)return double.NaN;var m=Regex.Match(text,@"^(?<v>[-+0-9.eE]+)\s*(?<u>GPa|MPa|kPa|Pa)$",RegexOptions.IgnoreCase);if(!m.Success)return double.NaN;var v=Number(m.Groups["v"].Value);return v*(m.Groups["u"].Value.ToLowerInvariant() switch{"gpa"=>1e9,"mpa"=>1e6,"kpa"=>1e3,_=>1});}
private static double? Density(string? text){if(string.IsNullOrWhiteSpace(text))return null;var m=Regex.Match(text,@"^(?<v>[-+0-9.eE]+)\s*kg/m3$",RegexOptions.IgnoreCase);return m.Success?Number(m.Groups["v"].Value):double.NaN;}
- private static double[] Numbers(string? text)=>Regex.Matches(text??"",@"[-+0-9.eE]+").Select(m=>Number(m.Value)).ToArray();
+ private static double[] Numbers(ExpressionSyntax? value)
+ {
+ if(value is null)return [];
+ return FirmamentSyntaxValues.Vector(value,"",out var values)&&values.All(double.IsFinite)?values:[double.NaN];
+ }
private static Vector3D Vector(string? text,bool force){var parts=(text??"").Trim('[',']').Split(',',StringSplitOptions.TrimEntries);if(parts.Length!=3)return new(double.NaN,double.NaN,double.NaN);double Parse(string p){var m=Regex.Match(p,@"^(?<v>[-+0-9.eE]+)\s*(?<u>N|Pa)$",RegexOptions.IgnoreCase);return m.Success&&((force&&m.Groups["u"].Value.Equals("N",StringComparison.OrdinalIgnoreCase))||(!force&&m.Groups["u"].Value.Equals("Pa",StringComparison.OrdinalIgnoreCase)))?Number(m.Groups["v"].Value):double.NaN;}return new(Parse(parts[0]),Parse(parts[1]),Parse(parts[2]));}
private static Vector3D Acceleration(string? text){var parts=(text??"").Trim('[',']').Split(',',StringSplitOptions.TrimEntries);if(parts.Length!=3)return new(double.NaN,double.NaN,double.NaN);double Parse(string p){var m=Regex.Match(p,@"^(?<v>[-+0-9.eE]+)\s*m/s(?:\^?2|²)$",RegexOptions.IgnoreCase);return m.Success?Number(m.Groups["v"].Value):double.NaN;}return new(Parse(parts[0]),Parse(parts[1]),Parse(parts[2]));}
- private static HashSet<DisplacementComponent> Components(string? text){var result=new HashSet<DisplacementComponent>();foreach(var item in (text??"").Trim('[',']').Split(',',StringSplitOptions.RemoveEmptyEntries|StringSplitOptions.TrimEntries))if(Enum.TryParse<DisplacementComponent>(item,true,out var value))result.Add(value);return result;}
+ private static HashSet<DisplacementComponent> Components(string? text,List<AnalysisDiagnostic> diagnostics,string? source)
+ {
+ var result=new HashSet<DisplacementComponent>();
+ foreach(var item in (text??"").Trim('[',']').Split(',',StringSplitOptions.RemoveEmptyEntries|StringSplitOptions.TrimEntries))
+ if(Enum.TryParse<DisplacementComponent>(item,true,out var value)&&Enum.IsDefined(value))result.Add(value);
+ else diagnostics.Add(Error("fea-displacement-component-unsupported",$"Unknown displacement component '{item}'; use X, Y or Z.",source));
+ return result;
+ }
private static bool TryPatchEdge(string token,out MidsurfacePatchEdge edge)=>Enum.TryParse(token.Replace("-minimum","Minimum",StringComparison.OrdinalIgnoreCase).Replace("-maximum","Maximum",StringComparison.OrdinalIgnoreCase).Replace("-min","Minimum",StringComparison.OrdinalIgnoreCase).Replace("-max","Maximum",StringComparison.OrdinalIgnoreCase),true,out edge);
private static string NativeSheetMetalMaterialReference(string reference)
{
diff --git a/Aetheris.Kernel.Firmament.Tests/DrawingM0BTests.cs b/Aetheris.Kernel.Firmament.Tests/DrawingM0BTests.cs
index d2069b2c..a798ece5 100644
--- a/Aetheris.Kernel.Firmament.Tests/DrawingM0BTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/DrawingM0BTests.cs
@@ -75,14 +75,15 @@ public sealed class DrawingM0BTests
}
[Theory]
- [InlineData("Revision: 1.1.0", "Revision: 01.1.0", FirmamentDrawingCompiler.DrawingRevisionInvalid)]
- [InlineData("Date: 2026-08-10", "Date: 2026-02-30", FirmamentDrawingCompiler.DrawingDateInvalid)]
- public void DrawingInfo_RejectsInvalidVersionAndDate(string before, string after, string diagnostic)
+ [InlineData("Revision: 1.1.0", "Revision: 01.1.0", "Revision")]
+ [InlineData("Date: 2026-08-10", "Date: 2026-02-30", "Date")]
+ public void DrawingInfo_RejectsInvalidVersionAndDate(string before, string after, string field)
{
using var temporary = new TemporaryDirectory(); var source = File.ReadAllText(Fixture()).Replace(before, after, StringComparison.Ordinal);
var path = Path.Combine(temporary.Path, "invalid-metadata.firmament"); File.WriteAllText(path, source);
var result = FirmamentDrawingCompiler.Compile(path, Path.Combine(temporary.Path, "out"));
- Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, item => item.StartsWith(diagnostic, StringComparison.Ordinal));
+ Assert.False(result.IsSuccess); Assert.Null(result.Artifacts);
+ Assert.Contains(result.Diagnostics,item=>item.StartsWith("firmament-template-record-field-type-mismatch:",StringComparison.Ordinal) && item.Contains("."+field+":",StringComparison.Ordinal));
}
[Fact]
@@ -95,7 +96,8 @@ public sealed class DrawingM0BTests
var path = Path.Combine(temporary.Path, "missing-author.firmament"); File.WriteAllText(path, source);
var result = FirmamentDrawingCompiler.Compile(path, Path.Combine(temporary.Path, "out"));
Assert.False(result.IsSuccess);
- Assert.Contains(result.Diagnostics, item => item.StartsWith(FirmamentDrawingCompiler.DrawingMetadataRequiredFieldMissing, StringComparison.Ordinal));
+ Assert.Null(result.Artifacts);
+ Assert.Contains(result.Diagnostics, item => item.StartsWith("firmament-template-record-missing-field:", StringComparison.Ordinal) && item.EndsWith(":Author",StringComparison.Ordinal));
}
[Fact]
diff --git a/Aetheris.Kernel.Firmament.Tests/RemainingDomainAstTests.cs b/Aetheris.Kernel.Firmament.Tests/RemainingDomainAstTests.cs
new file mode 100644
index 00000000..fd0db39a
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/RemainingDomainAstTests.cs
@@ -0,0 +1,93 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Structural;
+using Aetheris.Kernel.Firmament.Drawing;
+using Aetheris.Surfacing;
+using Aetheris.Collaboration;
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class RemainingDomainAstTests
+{
+ [Theory]
+ [InlineData("heigth: 2mm")]
+ [InlineData("Fillet Lost { radius: 1mm }")]
+ [InlineData("on: XZ")]
+ public void StructuralCannotIgnoreFieldsOrChildren(string intent)
+ {
+ var source=Read("Structural/simple-structural-frame.firmament");
+ var offset=source.IndexOf("Structure ",StringComparison.Ordinal);offset=source.IndexOf('{',offset)+1;
+ var result=StructuralAuthoring.Compile(source.Insert(offset,"\n"+intent+"\n"),"structural.firmament");
+ Assert.False(result.IsSuccess);Assert.Null(result.StepText);
+ Assert.Contains(result.FrontendDiagnostics,d=>d.SourceSpan is not null && d.SourceFile=="structural.firmament");
+ Assert.False(FirmamentBuildAndExport.CompileSource(source.Insert(offset,intent)).IsSuccess);
+ }
+ [Theory]
+ [InlineData("heigth: 2mm")]
+ [InlineData("Fillet Lost { radius: 1mm }")]
+ public void SculptingCannotIgnoreIntent(string intent)
+ {
+ var source=Read("Sculpting/sculpt-base-housing.firmament");
+ var at=source.IndexOf("BodyState ",StringComparison.Ordinal);at=source.IndexOf('{',at)+1;
+ var result=SculptingAuthoring.Compile(source.Insert(at,intent+";"),"housing.firmament");
+ Assert.False(result.IsSuccess);Assert.Contains(result.Diagnostics,d=>d.SourceSpan is not null && d.SourceFile=="housing.firmament");
+ }
+ [Fact]
+ public void SculptingHeaderPlacementCannotSilentlyChangeThePlane()
+ {
+ var source=Read("Sculpting/sculpt-base-housing.firmament");
+ var at=source.IndexOf("BodyState ",StringComparison.Ordinal);at=source.IndexOf('{',at);
+ var result=SculptingAuthoring.Compile(source.Insert(at,"on XZ "),"housing.firmament");
+ Assert.False(result.IsSuccess);Assert.Contains(result.Diagnostics,d=>d.Code=="firmament-v2-placement-unsupported");
+ }
+ [Fact]
+ public void StructuralAndSculptingFieldAliasesRetainExactGeometryAndStableIdentity()
+ {
+ var source=Read("Structural/simple-structural-frame.firmament");
+ var first=StructuralAuthoring.Compile(source);var second=StructuralAuthoring.Compile(source.Replace("Width:","width:",StringComparison.Ordinal));
+ Assert.True(first.IsSuccess);Assert.True(second.IsSuccess,string.Join(";",second.Diagnostics));Assert.Equal(first.StepText,second.StepText);
+ var sculpt=Read("Sculpting/sculpt-base-housing.firmament");
+ var a=SculptingAuthoring.Compile(sculpt);var b=SculptingAuthoring.Compile(sculpt.Replace("Size:","size:",StringComparison.Ordinal));
+ Assert.True(a.IsSuccess);Assert.True(b.IsSuccess);Assert.Equal(a.OutputState!.StateId,b.OutputState!.StateId);
+ Assert.Equal(SculptStepExporter.Export(a.OutputState,a.ModelName).Step,SculptStepExporter.Export(b.OutputState,b.ModelName).Step);
+ }
+ [Fact]
+ public void ScopedStructuralTableSchemaCannotBeBypassed()
+ {
+ var source=Read("Structural/welded-workbench.firmament");
+ var at=source.IndexOf("Record StructuralMemberRow",StringComparison.Ordinal);at=source.IndexOf('{',at)+1;
+ var result=StructuralAuthoring.Compile(source.Insert(at,"extraIntent: String;"));
+ Assert.False(result.IsSuccess);Assert.Contains(result.Diagnostics,d=>d.StartsWith("firmament-template-table-missing-column",StringComparison.Ordinal));
+ }
+ [Theory]
+ [InlineData("Orientation: Landscape","orientation: Diagonal")]
+ [InlineData("Direction: +Z","direction: [0,0,0]")]
+ [InlineData("HiddenLines: VisibleOnly","hiddenLines: Gibberish")]
+ [InlineData("PMI: []","pmi: []; heigth: 2mm")]
+ [InlineData("Source: Item","source: Item; Source: Item")]
+ public void DrawingUnknownOrInvalidIntentRejectsBeforeArtifacts(string before,string after)
+ {
+ var directory=Path.Combine(Root(),"artifacts","local","remaining-domain-tests",Guid.NewGuid().ToString("N"));Directory.CreateDirectory(directory);
+ var path=Path.Combine(directory,"drawing.firmament");File.WriteAllText(path,Read("Drawings/bearing-block-production-drawing.firmament").Replace(before,after,StringComparison.Ordinal));
+ var result=FirmamentDrawingCompiler.Compile(path,directory);Assert.False(result.IsSuccess);Assert.Null(result.Artifacts);Assert.Empty(Directory.GetFiles(directory,"*.pdf"));
+ }
+ [Fact]
+ public void DrawingAcronymsHaveOneModernSpellingAndKeepHistoricalAliases()
+ {
+ Assert.Equal("pmi",FirmamentSourceSpelling.PreferredField("PMI"));Assert.Equal("bom",FirmamentSourceSpelling.PreferredField("BOM"));Assert.Equal("uvBounds",FirmamentSourceSpelling.PreferredField("UVBounds"));
+ Assert.True(Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxFields.SameField("pMI","PMI"));
+ Assert.True(Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxFields.SameField("pmi","PMI"));
+ }
+ [Fact]
+ public void SculptingEditorAnalysisReportsSyntaxWithoutClaimingEngineeringAdmission()
+ {
+ var source=Read("Sculpting/sculpt-base-housing.firmament");
+ var report=FirmamentLanguageAnalysisService.Analyze(source,"housing.firmament","1");
+ Assert.DoesNotContain(report.Diagnostics,d=>d.Severity=="error");
+ Assert.Contains(report.Diagnostics,d=>d.Code=="firmament-language-domain-context-required" && d.Start>0);
+ var broken=source[..source.LastIndexOf('}')];
+ var errors=FirmamentLanguageAnalysisService.Analyze(broken,"housing.firmament","2");
+ Assert.Contains(errors.Diagnostics,d=>d.Code.StartsWith("firmament-syntax-",StringComparison.Ordinal) && d.Severity=="error");
+ }
+
+ private static string Read(string path)=>File.ReadAllText(Path.Combine(Root(),"fixtures","Canonical",path));
+ private static string Root(){var d=new DirectoryInfo(AppContext.BaseDirectory);while(d is not null&&!File.Exists(Path.Combine(d.FullName,"Aetheris.slnx")))d=d.Parent;return d!.FullName;}
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/SurfX2BlendBoundaryTests.cs b/Aetheris.Kernel.Firmament.Tests/SurfX2BlendBoundaryTests.cs
index bca23a42..32e7c125 100644
--- a/Aetheris.Kernel.Firmament.Tests/SurfX2BlendBoundaryTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/SurfX2BlendBoundaryTests.cs
@@ -77,7 +77,11 @@ public sealed class SurfX2BlendBoundaryTests
[Fact]
public void RequiredG2FailsWhenDegreeGateLeavesOnlyG1()
{
- var result = SculptingAuthoring.CompileFile(Fixture("Invalid", "Sculpting", "surf-x2-g2-unsatisfied.firmament"));
+ var source=File.ReadAllText(Fixture("Invalid", "Sculpting", "surf-x2-g2-unsatisfied.firmament"));
+ // Preserve the historical accidental diff marker as invalid-source evidence.
+ Assert.StartsWith("+Model",source);
+ Assert.Contains(SculptingAuthoring.Compile(source).Diagnostics,d=>d.Code=="firmament-syntax-statement");
+ var result = SculptingAuthoring.Compile(source[1..]);
Assert.False(result.IsSuccess);
Assert.Contains(result.Diagnostics, item => item.Code == "surf-blend-no-eligible-candidates");
}
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingIr.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingIr.cs
index d047d64c..d2dc7c51 100644
--- a/Aetheris.Kernel.Firmament/Drawing/DrawingIr.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingIr.cs
@@ -211,4 +211,8 @@ public sealed record DrawingCompileArtifacts(
public sealed record DrawingCompileResult(
bool IsSuccess,
DrawingCompileArtifacts? Artifacts,
- IReadOnlyList<string> Diagnostics);
+ IReadOnlyList<string> Diagnostics)
+{
+ public IReadOnlyList<FirmamentV2.FirmamentV2ValidationDiagnostic> FrontendDiagnostics { get; init; } = [];
+ public IReadOnlyList<Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic> KernelDiagnostics()=>FirmamentV2.FirmamentDomainDiagnostics.Present(Diagnostics,FrontendDiagnostics,"Firmament.Drawing");
+}
diff --git a/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingCompiler.cs b/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingCompiler.cs
index 9ea70893..618d699f 100644
--- a/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingCompiler.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingCompiler.cs
@@ -9,13 +9,14 @@ using Aetheris.Kernel.Core.Step242;
using Aetheris.Kernel.Firmament.Assembly;
using Aetheris.Kernel.Firmament.FirmamentV2;
using Aetheris.Semantics;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using Aetheris.Collaboration;
namespace Aetheris.Kernel.Firmament.Drawing;
/// <summary>Drawing M0B compiler. Part and Assembly products share one DrawingIR and sibling
/// SVG/React/PDF presentation contract. Assembly occurrences remain independently projected.</summary>
-public static class FirmamentDrawingCompiler
+public static partial class FirmamentDrawingCompiler
{
public const string DrawingMissing = "drawing-missing-declaration";
public const string DrawingSourceUnknown = "drawing-source-product-unknown";
@@ -34,15 +35,27 @@ public static class FirmamentDrawingCompiler
Converters = { new JsonStringEnumConverter() }
};
+ public static bool IsDrawingSource(string source)=>source.Contains("Drawing",StringComparison.Ordinal)
+ && FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d=>d.Type.Name.Text=="Drawing" && d.Modifiers.Count==0);
+
public static DrawingCompileResult Compile(string sourcePath, string outputDirectory)
+ {
+ var frontend=new List<FirmamentV2ValidationDiagnostic>();
+ return CompileCore(sourcePath,outputDirectory,frontend) with {FrontendDiagnostics=frontend};
+ }
+ private static DrawingCompileResult CompileCore(string sourcePath,string outputDirectory,List<FirmamentV2ValidationDiagnostic> frontend)
{
var fullSourcePath = Path.GetFullPath(sourcePath); var output = Path.GetFullPath(outputDirectory);
if (!File.Exists(fullSourcePath)) return Failure($"drawing-source-file-missing: {fullSourcePath}");
Directory.CreateDirectory(output);
- var source = File.ReadAllText(fullSourcePath, Encoding.UTF8).Replace("\r\n", "\n", StringComparison.Ordinal);
+ var source = File.ReadAllText(fullSourcePath, Encoding.UTF8);
var reviewScan = FirmamentReviewCompiler.Compile(source, fullSourcePath);
var drawingSourceText = FirmamentReviewCompiler.EraseDeclarations(source, reviewScan.SourceRanges);
- var parse = ParseDrawingLanguage(drawingSourceText);
+ var dataBinding=new FirmamentDataBinding(drawingSourceText);
+ if(dataBinding.Diagnostics.Count>0)return new(false,null,dataBinding.Diagnostics.Select(d=>d.Code+": "+d.Message).ToArray());
+ drawingSourceText=dataBinding.Source;
+ var parse = ParseDrawingLanguage(drawingSourceText,fullSourcePath,frontend);
+ for(var i=0;i<frontend.Count;i++)if(frontend[i].SourceSpan is {} span)frontend[i]=frontend[i] with {SourceSpan=dataBinding.OriginalSpan(span)};
if (parse.Diagnostics.Count > 0 || parse.Drawing is null) return new(false, null, parse.Diagnostics);
var drawingSource = parse.Drawing;
var metadataResult = ResolveMetadata(drawingSourceText, drawingSource);
@@ -57,7 +70,7 @@ public static class FirmamentDrawingCompiler
DrawingBomIr? bom = null;
var bomMilliseconds = 0d;
string sourceKind;
- var isAssembly = Regex.IsMatch(geometrySource, $@"\bAssembly\s+{Regex.Escape(drawingSource.Source)}\s*\{{", RegexOptions.CultureInvariant);
+ var isAssembly = FirmamentSyntaxParser.Parse(geometrySource).Document.Statements.OfType<DeclarationSyntax>().Any(d=>d.Type.Name.Text=="Assembly" && d.Name?.Text==drawingSource.Source);
if (isAssembly)
{
sourceKind = "Assembly";
@@ -101,6 +114,7 @@ public static class FirmamentDrawingCompiler
if (unknownPmi.Length > 0) return Failure($"{DrawingPmiUnknown}: {string.Join(", ", unknownPmi)}");
var reviewTargets = pmi.ToDictionary(pair => pair.Key, pair => ((string?)pair.Value.Display, (IReadOnlyList<string>)["PMI", "Dimensional"]), StringComparer.Ordinal);
var reviewResult = FirmamentReviewCompiler.Compile(source, fullSourcePath, reviewTargets);
+ frontend.AddRange(reviewResult.SourceDiagnostics.Select(d=>new FirmamentV2ValidationDiagnostic(d.Code,"error",d.Message){SourceFile=fullSourcePath,SourceSpan=new(d.Span.Start,d.Span.Length),Stage="Review binding"}));
if (!reviewResult.IsSuccess) return new(false, null, reviewResult.Diagnostics);
var conceptFailures = ValidateConcept(drawingSource, parse.Concept, metadata);
if (conceptFailures.Count > 0) return new(false, null, conceptFailures);
@@ -331,7 +345,7 @@ public static class FirmamentDrawingCompiler
var diagnostics = new List<string>(); var fields = new Dictionary<string, string>(StringComparer.Ordinal); string? provenance = null;
if (drawing.Metadata is not null)
{
- var records = ParseStaticRecords(source); if (!records.TryGetValue(drawing.Metadata, out var record)) return new(null, [$"{DrawingMetadataUnknown}: {drawing.Metadata}"]);
+ var records = ParseStaticRecords(source,diagnostics); if(diagnostics.Count>0)return new(null,diagnostics); if (!records.TryGetValue(drawing.Metadata, out var record)) return new(null, [$"{DrawingMetadataUnknown}: {drawing.Metadata}"]);
fields = new(record.Fields, StringComparer.Ordinal); provenance = record.Provenance;
var missing = new[] { "Company", "Author", "PartNumber", "Revision", "Date", "Description" }.Where(field => !fields.ContainsKey(field)).ToArray();
if (missing.Length > 0) diagnostics.Add($"{DrawingMetadataRequiredFieldMissing}: {drawing.Metadata}: {string.Join(",", missing)}");
@@ -347,81 +361,6 @@ public static class FirmamentDrawingCompiler
return new(metadata, diagnostics);
}
- private static Dictionary<string, StaticRecord> ParseStaticRecords(string source)
- {
- var result = new Dictionary<string, StaticRecord>(StringComparer.Ordinal);
- foreach (Match header in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\s*=\s*\k<type>\s*\{", RegexOptions.CultureInvariant))
- {
- var block = ReadBlock(source, source.IndexOf('{', header.Index)); if (block is null) continue;
- result[header.Groups["name"].Value] = new(ParseFields(block.Value.Body), "StaticRecord:" + header.Groups["name"].Value);
- }
- var pending = Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*(?::\s*[A-Za-z_]\w*)?\s*=\s*(?<base>[A-Za-z_]\w*)\s+with\s*\{", RegexOptions.CultureInvariant).Cast<Match>().ToList();
- while (pending.Count > 0)
- {
- var progressed = false;
- foreach (var item in pending.ToArray())
- {
- if (!result.TryGetValue(item.Groups["base"].Value, out var basis)) continue;
- var block = ReadBlock(source, source.IndexOf('{', item.Index)); if (block is null) { pending.Remove(item); continue; }
- var next = new Dictionary<string, string>(basis.Fields, StringComparer.Ordinal); foreach (var field in ParseFields(block.Value.Body)) next[field.Key] = field.Value;
- result[item.Groups["name"].Value] = new(next, basis.Provenance + "; derivedFrom:" + item.Groups["base"].Value + "; overrides:" + string.Join(",", ParseFields(block.Value.Body).Keys.Order(StringComparer.Ordinal)));
- pending.Remove(item); progressed = true;
- }
- if (!progressed) break;
- }
- return result;
- }
-
- private static Dictionary<string, string> ParseFields(string body) => Regex.Matches(body, "\\b(?<name>[A-Za-z_]\\w*)\\s*:\\s*(?<value>\"[^\"]*\"|\\d+\\.\\d+\\.\\d+|\\d{4}-\\d{2}-\\d{2}|[^;\\n}]+)", RegexOptions.CultureInvariant)
- .Cast<Match>().ToDictionary(match => match.Groups["name"].Value, match => match.Groups["value"].Value.Trim(), StringComparer.Ordinal);
-
- private static ParseResult ParseDrawingLanguage(string source)
- {
- var diagnostics = new List<string>(); var ranges = new List<(int Start, int Length)>(); ParsedConcept? concept = null;
- var conceptMatch = Regex.Match(source, @"\bConcept\s+Drawing\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
- if (conceptMatch.Success) { var block = ReadBlock(source, conceptMatch.Index + conceptMatch.Length - 1); if (block is null) diagnostics.Add("drawing-concept-malformed"); else { concept = new(conceptMatch.Groups["name"].Value, Regex.Matches(block.Value.Body, @"\bRequire\s+(?<name>[A-Za-z_]\w*)\s*;?").Select(item => item.Groups["name"].Value).ToArray()); ranges.Add((conceptMatch.Index, block.Value.End - conceptMatch.Index + 1)); } }
- ParsedTemplate? template = null;
- var templateMatch = Regex.Match(source, @"\bTemplate\s*<(?<parameters>[^>]+)>\s*Drawing\s+(?<name>[A-Za-z_]\w*)\s*(?::\s*(?<concept>[A-Za-z_]\w*))?\s*\{", RegexOptions.CultureInvariant);
- if (templateMatch.Success) { var block = ReadBlock(source, templateMatch.Index + templateMatch.Length - 1); if (block is null) diagnostics.Add("drawing-template-malformed"); else { var parameters = Regex.Matches(templateMatch.Groups["parameters"].Value, @"(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)").Cast<Match>().ToDictionary(item => item.Groups["name"].Value, item => item.Groups["type"].Value, StringComparer.Ordinal); template = new(templateMatch.Groups["name"].Value, parameters, templateMatch.Groups["concept"].Value, block.Value.Body); ranges.Add((templateMatch.Index, block.Value.End - templateMatch.Index + 1)); } }
- ParsedDrawing? drawing = null;
- var application = Regex.Match(source, @"\bDrawing\s+(?<name>[A-Za-z_]\w*)\s*=\s*(?<template>[A-Za-z_]\w*)\s*<(?<arguments>[^>]+)>\s*;?", RegexOptions.CultureInvariant);
- if (application.Success && template is not null)
- {
- var args = Regex.Matches(application.Groups["arguments"].Value, @"(?<name>[A-Za-z_]\w*)\s*:\s*(?<value>[A-Za-z_]\w*)").Cast<Match>().ToDictionary(item => item.Groups["name"].Value, item => item.Groups["value"].Value, StringComparer.Ordinal);
- if (application.Groups["template"].Value != template.Name) diagnostics.Add("drawing-template-unknown");
- else { var body = template.Body; foreach (var parameter in template.Parameters.Keys) if (args.TryGetValue(parameter, out var value)) body = Regex.Replace(body, $@"\b{Regex.Escape(parameter)}\b", value); drawing = ParseDrawingBody(application.Groups["name"].Value, template.Name, template.Concept, args.GetValueOrDefault("Product") ?? args.GetValueOrDefault("Item"), args.GetValueOrDefault("Metadata"), body, diagnostics); }
- ranges.Add((application.Index, application.Length));
- }
- else
- {
- var literal = Regex.Match(source, @"\bDrawing\s+(?<name>[A-Za-z_]\w*)\s*(?::\s*(?<concept>[A-Za-z_]\w*))?\s*\{", RegexOptions.CultureInvariant);
- if (literal.Success) { var block = ReadBlock(source, literal.Index + literal.Length - 1); if (block is not null) { drawing = ParseDrawingBody(literal.Groups["name"].Value, "Literal", literal.Groups["concept"].Value, null, null, block.Value.Body, diagnostics); ranges.Add((literal.Index, block.Value.End - literal.Index + 1)); } }
- }
- if (drawing is null && diagnostics.Count == 0) diagnostics.Add(DrawingMissing); return new(drawing, concept, ranges, diagnostics);
- }
-
- private static ParsedDrawing ParseDrawingBody(string name, string template, string concept, string? product, string? metadata, string body, List<string> diagnostics)
- {
- string? Field(string field) => Regex.Match(body, $@"\b{Regex.Escape(field)}\s*:\s*(?<value>[^;\n}}]+)") is { Success: true } match ? TrimValue(match.Groups["value"].Value) : null;
- var source = product ?? Field("Source"); if (string.IsNullOrWhiteSpace(source)) diagnostics.Add("drawing-source-required");
- var views = new List<ParsedView>();
- foreach (Match match in Regex.Matches(body, @"\bView\s+(?<name>[A-Za-z_]\w*)\s*\{"))
- {
- var block = ReadBlock(body, match.Index + match.Length - 1); if (block is null) continue;
- var directionMatch = Regex.Match(block.Value.Body, @"\bDirection\s*:\s*(?<direction>\[[^\]]+\]|[+-][XYZ])"); if (!directionMatch.Success) { diagnostics.Add("drawing-view-direction-required:" + match.Groups["name"].Value); continue; }
- var direction = ParseDirection(directionMatch.Groups["direction"].Value); var projection = Regex.IsMatch(block.Value.Body, @"\bProjection\s*:\s*Isometric") || direction.Count(value => Math.Abs(value) > 1e-12) > 1 ? DrawingProjectionKind.Isometric : DrawingProjectionKind.Orthographic;
- var hidden = Regex.IsMatch(block.Value.Body, @"\bHiddenLines\s*:\s*VisibleAndHidden") ? DrawingHiddenLinePolicy.VisibleAndHidden : DrawingHiddenLinePolicy.VisibleOnly;
- var assignedMatch = Regex.Match(block.Value.Body, @"\bPMI\s*:\s*\[(?<items>[^\]]*)\]", RegexOptions.IgnoreCase); var assigned = assignedMatch.Success ? assignedMatch.Groups["items"].Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) : [];
- views.Add(new(match.Groups["name"].Value, direction, projection, hidden, assigned));
- }
- if (views.Count == 0) diagnostics.Add(DrawingViewMissing);
- var notesMatch = Regex.Match(body, @"\bNotes\s*:\s*\[(?<items>[^\]]*)\]"); var notes = notesMatch.Success ? Regex.Matches(notesMatch.Groups["items"].Value, "\"(?<text>[^\"]*)\"").Select(item => item.Groups["text"].Value).ToArray() : [];
- return new(name, template, concept, source ?? "", Field("Orientation") == "Portrait" ? DrawingPageOrientation.Portrait : DrawingPageOrientation.Landscape, views,
- Field("Title"), Field("PartNumber"), Field("Revision"), Field("Material"), Field("Table"), notes, metadata ?? Field("Metadata"), string.Equals(Field("BOM"), "true", StringComparison.OrdinalIgnoreCase));
- }
-
- private static IReadOnlyList<double> ParseDirection(string source) => source.Trim() switch { "+X" => [1, 0, 0], "-X" => [-1, 0, 0], "+Y" => [0, 1, 0], "-Y" => [0, -1, 0], "+Z" => [0, 0, 1], "-Z" => [0, 0, -1], _ => source.Trim().Trim('[', ']').Split(',', StringSplitOptions.TrimEntries).Select(value => double.Parse(value, CultureInfo.InvariantCulture)).ToArray() };
- private static (string Body, int End)? ReadBlock(string source, int open) { if (open < 0 || open >= source.Length || source[open] != '{') return null; var depth = 0; var quoted = false; for (var index = open; index < source.Length; index++) { if (source[index] == '"' && (index == 0 || source[index - 1] != '\\')) quoted = !quoted; if (quoted) continue; if (source[index] == '{') depth++; else if (source[index] == '}' && --depth == 0) return (source[(open + 1)..index], index); } return null; }
private static string EraseDrawingDeclarations(string source, IReadOnlyList<(int Start, int Length)> ranges) { var chars = source.ToCharArray(); foreach (var range in ranges) for (var index = range.Start; index < range.Start + range.Length; index++) if (chars[index] != '\n') chars[index] = ' '; return new(chars); }
private static string TrimValue(string value) => value.Trim().Trim('"');
private static string StableHash(string value) => HashBytes(Encoding.UTF8.GetBytes(value));
@@ -432,7 +371,6 @@ public static class FirmamentDrawingCompiler
private sealed record StaticRecord(IReadOnlyDictionary<string, string> Fields, string Provenance);
private sealed record MetadataResult(DrawingMetadataIr? Metadata, IReadOnlyList<string> Diagnostics);
private sealed record ParsedConcept(string Name, IReadOnlyList<string> Requirements);
- private sealed record ParsedTemplate(string Name, IReadOnlyDictionary<string, string> Parameters, string Concept, string Body);
private sealed record ParsedView(string Name, IReadOnlyList<double> Direction, DrawingProjectionKind Projection, DrawingHiddenLinePolicy HiddenLines, IReadOnlyList<string> Pmi);
private sealed record ParsedDrawing(string Name, string Template, string Concept, string Source, DrawingPageOrientation Orientation, IReadOnlyList<ParsedView> Views,
string? Title, string? PartNumber, string? Revision, string? Material, string? Table, IReadOnlyList<string> Notes, string? Metadata, bool Bom);
diff --git a/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingSyntax.cs b/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingSyntax.cs
new file mode 100644
index 00000000..64d9a876
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingSyntax.cs
@@ -0,0 +1,140 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Scope=Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxScope;
+namespace Aetheris.Kernel.Firmament.Drawing;
+
+public static partial class FirmamentDrawingCompiler
+{
+ private static Dictionary<string,StaticRecord> ParseStaticRecords(string source,List<string> diagnostics)
+ {
+ var values=new FirmamentCompileTimeValues(source);
+ var catalog=FirmamentV2TemplateExpansion.ReadDataCatalog(source,diagnostics,values,initialize:true);
+ diagnostics.AddRange(values.Diagnostics.Select(d=>d.Code+": "+d.Message));
+ return catalog.Records.ToDictionary(p=>p.Key,p=>new StaticRecord(
+ FirmamentV2TemplateExpansion.FlattenRecordFields(p.Value,catalog.Types,catalog.Records,diagnostics),p.Value.Provenance),StringComparer.Ordinal);
+ }
+
+ private static ParseResult ParseDrawingLanguage(string source,string sourceFile,List<FirmamentV2ValidationDiagnostic> frontend)
+ {
+ var syntax=FirmamentSyntaxParser.Parse(source,sourceFile);
+ frontend.AddRange(syntax.Diagnostics);
+ var diagnostics=syntax.Diagnostics.Select(d=>d.Code+": "+d.Message).ToList();
+ void Close(Scope scope){var located=scope.CompleteTree();frontend.AddRange(located);diagnostics.AddRange(located.Select(d=>d.Code+": "+d.Message));}
+ var ranges=new List<(int Start,int Length)>();
+ if(!syntax.IsSuccess)return new(null,null,ranges,diagnostics);
+ // Drawing declarations live at document or product scope, never inside an unrelated feature.
+ var declarations=syntax.Document.Statements.OfType<DeclarationSyntax>()
+ .SelectMany(d=>d.Type.Name.Text=="Model"?d.Body?.Statements.OfType<DeclarationSyntax>()??[]:[d]).ToArray();
+ var concepts=declarations.Where(d=>d.Type.Name.Text=="Drawing" && d.Modifiers.Any(m=>m.Name.Text=="Concept")).ToArray();
+ var templates=declarations.Where(d=>d.Type.Name.Text=="Drawing" && d.Modifiers.Any(m=>m.Name.Text=="Template")).ToArray();
+ var applications=declarations.Where(d=>d.Type.Name.Text=="Drawing" && d.Modifiers.Count==0).ToArray();
+ foreach(var d in concepts.Concat(templates).Concat(applications))ranges.Add((d.Span.Start,d.Span.Length));
+ if(applications.Length!=1){diagnostics.Add("drawing-declaration-cardinality: Exactly one Drawing product is required.");return new(null,null,ranges,diagnostics);}
+ var app=applications[0];var contract=FirmamentSyntaxValues.Reference(app.Annotation)??"";
+ var body=app;var templateName="Literal";var arguments=new Dictionary<string,ExpressionSyntax>(StringComparer.Ordinal);
+ if(app.Initializer is SpecializationSyntax specialization)
+ {
+ templateName=FirmamentSyntaxValues.Reference(specialization.Target)??"";
+ var candidates=templates.Where(t=>t.Name?.Text==templateName).ToArray();
+ if(candidates.Length!=1){diagnostics.Add("drawing-template-unknown: "+templateName);return new(null,null,ranges,diagnostics);}
+ body=candidates[0];contract=FirmamentSyntaxValues.Reference(body.Annotation)??"";
+ if(body.Modifiers.Count!=1){diagnostics.Add("drawing-template-header-invalid");return new(null,null,ranges,diagnostics);}
+ var parameters=body.Modifiers[0].Arguments;
+ if(parameters.Any(p=>p.Name is null || p.Default is not null) || parameters.Select(p=>p.Name!.Text).Distinct().Count()!=parameters.Count)
+ diagnostics.Add("drawing-template-parameter-invalid");
+ foreach(var argument in specialization.Arguments)
+ {
+ var key=argument.Name?.Text??"";
+ // Historical Product: argument names the unique Item: Product parameter.
+ if(key=="Product" && !parameters.Any(p=>p.Name?.Text==key))
+ {
+ var productParameters=parameters.Where(p=>FirmamentSyntaxValues.Reference(p.Value)=="Product").ToArray();
+ if(productParameters.Length==1)key=productParameters[0].Name?.Text??key;
+ }
+ if(!parameters.Any(p=>p.Name?.Text==key))diagnostics.Add("drawing-template-argument-unknown: "+key);
+ else if(!arguments.TryAdd(key,argument.Value))diagnostics.Add("drawing-template-argument-duplicate: "+key);
+ if(FirmamentSyntaxValues.Reference(argument.Value) is null || argument.Default is not null)diagnostics.Add("drawing-template-argument-invalid: "+key);
+ }
+ var catalog=FirmamentV2TemplateExpansion.ReadDataCatalog(source,diagnostics);
+ foreach(var p in parameters)
+ {
+ if(p.Name is not {} name)continue;
+ if(!arguments.TryGetValue(name.Text,out var value)){diagnostics.Add("drawing-template-argument-missing: "+name.Text);continue;}
+ var type=FirmamentSyntaxValues.Reference(p.Value);var argument=FirmamentSyntaxValues.Reference(value);
+ if(type=="Product")
+ {
+ if(!syntax.Document.Statements.OfType<DeclarationSyntax>().Any(d=>d.Name?.Text==argument && d.Type.Name.Text is "Assembly" or "Model"))diagnostics.Add("drawing-template-product-unknown: "+argument);
+ }
+ else if(type is null || !catalog.Types.ContainsKey(type) || argument is null || !catalog.Records.TryGetValue(argument,out var record) || record.TypeName!=type)
+ diagnostics.Add("drawing-template-record-type-mismatch: "+name.Text+": expected "+type);
+ }
+ var application=new Scope(app,source,sourceFile).AdmitInitializer();
+ Close(application);
+ }
+ else if(app.Initializer is not null)diagnostics.Add("drawing-initializer-invalid");
+ // Unused declarations are still closed; unsupported library templates cannot disappear.
+ if(templates.Any(t=>t!=body))diagnostics.Add("drawing-unused-template-unsupported: Keep one drawing prototype per compilation unit.");
+ var substitution=new FirmamentSyntaxSubstitution(arguments);
+ var scope=new Scope(body,source,sourceFile,substitution.Expression);
+ if(body!=app)scope.AllowModifier("Template");
+ if(body.Annotation is not null)scope.AdmitAnnotation();
+ var parsed=ParseDrawingBody(app.Name?.Text??"<unnamed>",templateName,contract,scope,diagnostics);
+ Close(scope);
+ ParsedConcept? concept=null;
+ if(contract.Length>0)
+ {
+ var matches=concepts.Where(c=>c.Name?.Text==contract).ToArray();
+ if(matches.Length!=1)diagnostics.Add("drawing-concept-unknown: "+contract);
+ else
+ {
+ var requirements=new List<string>();var owner=new Scope(matches[0],source,sourceFile).AllowModifier("Concept");
+ foreach(var requirement in owner.Children("Require"))
+ {
+ if(requirement.Name is not ("PrimaryView" or "ManufacturingPmi" or "Material" or "DesignTable" or "BOM" or "RevisionMetadata"))
+ requirement.Invalid("requirement","Unknown drawing policy requirement.");
+ requirements.Add(requirement.Name);
+ }
+ Close(owner);concept=new(contract,requirements);
+ }
+ }
+ if(concepts.Any(c=>c.Name?.Text!=contract))diagnostics.Add("drawing-unused-concept-unsupported: Keep one drawing policy per compilation unit.");
+ return new(parsed,concept,ranges,diagnostics);
+ }
+
+ private static ParsedDrawing ParseDrawingBody(string name,string template,string concept,Scope scope,List<string> diagnostics)
+ {
+ string? Field(string field)=>scope.Raw(field) is {} value?TrimValue(value):null;
+ var source=Field("Source");if(string.IsNullOrWhiteSpace(source))diagnostics.Add("drawing-source-required");
+ var orientation=Field("Orientation")??"Landscape";
+ if(orientation is not ("Portrait" or "Landscape"))scope.Invalid("Orientation");
+ var views=new List<ParsedView>();
+ foreach(var view in scope.Children("View"))
+ {
+ var value=view.Take("Direction");double[] direction=[];
+ var axis=FirmamentSyntaxValues.Reference(value);
+ direction=axis switch{"+X"=>[1,0,0],"-X"=>[-1,0,0],"+Y"=>[0,1,0],"-Y"=>[0,-1,0],"+Z"=>[0,0,1],"-Z"=>[0,0,-1],_=>[]};
+ if(direction.Length==0 && !FirmamentSyntaxValues.Vector(value,"",out direction))direction=[];
+ if(direction.Length!=3 || !direction.All(double.IsFinite) || direction.All(v=>v==0)){view.Invalid("Direction");continue;}
+ var projection=view.Word("Projection");
+ if(projection is not (null or "Orthographic" or "Isometric"))view.Invalid("Projection");
+ var hidden=view.Word("HiddenLines")??"VisibleOnly";
+ if(hidden is not ("VisibleOnly" or "VisibleAndHidden"))view.Invalid("HiddenLines");
+ var pmi=List(view,"PMI",false);
+ var kind=projection=="Isometric" || projection is null && direction.Count(v=>Math.Abs(v)>1e-12)>1?DrawingProjectionKind.Isometric:DrawingProjectionKind.Orthographic;
+ views.Add(new(view.Name,direction,kind,hidden=="VisibleAndHidden"?DrawingHiddenLinePolicy.VisibleAndHidden:DrawingHiddenLinePolicy.VisibleOnly,pmi));
+ }
+ if(views.Count==0)diagnostics.Add(DrawingViewMissing);
+ if(views.Select(v=>v.Name).Distinct().Count()!=views.Count)diagnostics.Add("drawing-view-duplicate");
+ var notes=List(scope,"Notes",true);var bom=Field("BOM");if(bom is not (null or "true" or "false"))scope.Invalid("BOM");
+ return new(name,template,concept,source??"",orientation=="Portrait"?DrawingPageOrientation.Portrait:DrawingPageOrientation.Landscape,views,
+ Field("Title"),Field("PartNumber"),Field("Revision"),Field("Material"),Field("Table"),notes,Field("Metadata"),bom=="true");
+ }
+ private static IReadOnlyList<string> List(Scope scope,string field,bool strings)
+ {
+ var expression=scope.Take(field);if(expression is null)return [];
+ if(expression is SequenceSyntax {Kind:SequenceKind.List} list && list.Items.All(i=>i.Name is null && i.Default is null
+ && (strings?i.Value is LiteralSyntax {Kind:LiteralKind.String}:FirmamentSyntaxValues.Reference(i.Value) is not null)))
+ return list.Items.Select(i=>FirmamentSyntaxValues.Reference(i.Value)!).ToArray();
+ scope.Invalid(field);return [];
+ }
+}
diff --git a/Aetheris.Collaboration/FirmamentReviewCompiler.cs b/Aetheris.Kernel.Firmament/Drawing/FirmamentReviewCompiler.cs
similarity index 51%
rename from Aetheris.Collaboration/FirmamentReviewCompiler.cs
rename to Aetheris.Kernel.Firmament/Drawing/FirmamentReviewCompiler.cs
index 679c1906..de725b3c 100644
--- a/Aetheris.Collaboration/FirmamentReviewCompiler.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/FirmamentReviewCompiler.cs
@@ -1,5 +1,6 @@
using System.Globalization;
using System.Text.RegularExpressions;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
namespace Aetheris.Collaboration;
@@ -19,59 +20,67 @@ public static partial class FirmamentReviewCompiler
IReadOnlyDictionary<string, (string? CurrentValue, IReadOnlyList<string> Capabilities)>? knownTargets = null)
{
var diagnostics = new List<string>();
+ var located=new List<ReviewSourceDiagnostic>();
+ void Add(string code,string message,FirmamentSyntaxScope owner,string? field=null)
+ {
+ var span=owner.Declaration.Body?.Statements.OfType<FieldSyntax>().FirstOrDefault(f=>field is not null && FirmamentSyntaxFields.SameField(f.Name.Text,field))?.Name.Span??owner.Span;
+ diagnostics.Add(code+": "+message);located.Add(new(code,message,new(sourcePath,span.Start,span.Length)));
+ }
var ranges = new List<(int, int)>();
var threads = new List<ReviewThreadIr>();
var identities = new HashSet<string>(StringComparer.Ordinal);
- foreach (Match match in ReviewStart().Matches(source))
+ var syntax=FirmamentSyntaxParser.Parse(source,sourcePath);
+ diagnostics.AddRange(syntax.Diagnostics.Select(d=>d.Code+": "+d.Message));
+ located.AddRange(syntax.Diagnostics.Where(d=>d.SourceSpan is not null).Select(d=>new ReviewSourceDiagnostic(d.Code,d.Message,new(sourcePath,d.SourceSpan!.Start,d.SourceSpan.Length))));
+ foreach (var declaration in syntax.Document.Statements.OfType<Aetheris.Kernel.Firmament.FirmamentV2.Syntax.DeclarationSyntax>()
+ .SelectMany(d=>d.Type.Name.Text=="Model"?d.Body?.Statements.OfType<DeclarationSyntax>()??[]:[d]).Where(d=>d.Type.Name.Text=="Review"))
{
- var open = source.IndexOf('{', match.Index + match.Length - 1);
- var close = FindClosingBrace(source, open);
- if (close < 0) { diagnostics.Add($"review-unclosed: {match.Groups[1].Value}"); continue; }
- ranges.Add((match.Index, close - match.Index + 1));
- var id = match.Groups[1].Value;
- if (!identities.Add(id)) diagnostics.Add($"{IdentityDuplicate}: {id}");
- var body = source[(open + 1)..close];
+ ranges.Add((declaration.Span.Start,declaration.Span.Length));
+ var id = declaration.Name?.Text??"<missing>";
+ var body=new FirmamentSyntaxScope(declaration,source,sourcePath);
+ if (!identities.Add(id)) Add(IdentityDuplicate,id,body);
var target = Field(body, "Target");
var statusText = Field(body, "Status") ?? "Open";
- if (target is null) { diagnostics.Add($"review-target-required: {id}"); continue; }
- if (!Enum.TryParse<ReviewStatus>(statusText, true, out var status)) diagnostics.Add($"review-status-invalid: {id}: {statusText}");
+ if (target is null) { Add("review-target-required",id,body); continue; }
+ if (!Enum.TryParse<ReviewStatus>(statusText, true, out var status)) Add("review-status-invalid",$"{id}: {statusText}",body,"Status");
var targetInfo = knownTargets?.GetValueOrDefault(target);
- if (knownTargets is not null && !knownTargets.ContainsKey(target)) diagnostics.Add($"{TargetUnknown}: {id}: {target}");
+ if (knownTargets is not null && !knownTargets.ContainsKey(target)) Add(TargetUnknown,$"{id}: {target}",body,"Target");
var entries = new List<ReviewEntryIr>();
var entryOrder = 0;
- foreach (Match entryMatch in EntryStart().Matches(body))
+ foreach (var entry in (declaration.Body?.Statements.OfType<DeclarationSyntax>()??[])
+ .Where(d=>d.Type.Name.Text is "Comment" or "Issue" or "Proposal" or "Resolution"))
{
- var entryOpen = body.IndexOf('{', entryMatch.Index + entryMatch.Length - 1);
- var entryClose = FindClosingBrace(body, entryOpen);
- if (entryClose < 0) { diagnostics.Add($"review-entry-unclosed: {id}"); continue; }
- var kind = Enum.Parse<ReviewEntryKind>(entryMatch.Groups[1].Value, true);
- var entryId = entryMatch.Groups[2].Success ? entryMatch.Groups[2].Value : $"{id}.{kind}.{entryOrder + 1}";
- if (!identities.Add(entryId)) diagnostics.Add($"{IdentityDuplicate}: {entryId}");
- var entryBody = body[(entryOpen + 1)..entryClose];
+ var entryBody=body.Children(entry.Type.Name.Text).Single(s=>ReferenceEquals(s.Declaration,entry));
+ var kind=Enum.Parse<ReviewEntryKind>(entry.Type.Name.Text);
+ var entryId=entry.Name?.Text??$"{id}.{kind}.{entryOrder+1}";
+ if (!identities.Add(entryId)) Add(IdentityDuplicate,entryId,entryBody);
var authorName = StringField(entryBody, "Author");
- if (string.IsNullOrWhiteSpace(authorName)) diagnostics.Add($"{AuthorRequired}: {entryId}");
+ if (string.IsNullOrWhiteSpace(authorName)) Add(AuthorRequired,entryId,entryBody,"Author");
var dateText = Field(entryBody, "Date");
- if (dateText is null) diagnostics.Add($"{DateRequired}: {entryId}");
- else if (!DateOnly.TryParseExact(dateText, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _)) diagnostics.Add($"{DateInvalid}: {entryId}: {dateText}");
+ if (dateText is null) Add(DateRequired,entryId,entryBody,"Date");
+ else if (!DateOnly.TryParseExact(dateText, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _)) Add(DateInvalid,$"{entryId}: {dateText}",entryBody,"Date");
_ = DateOnly.TryParseExact(dateText, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date);
- var text = StringField(entryBody, "Text") ?? StringField(entryBody, "Reason") ?? string.Empty;
+ var authoredText=StringField(entryBody,"Text");var reason=StringField(entryBody,"Reason");var text=authoredText??reason??string.Empty;
StructuredProposalIr? proposal = null;
if (kind == ReviewEntryKind.Proposal)
{
var property = Field(entryBody, "Property");
- var proposed = Field(entryBody, "Proposed") ?? Field(entryBody, "Tolerance");
+ var proposedValue=Field(entryBody,"Proposed");var tolerance=Field(entryBody,"Tolerance");var proposed=proposedValue??tolerance;
+ if(proposedValue is not null && tolerance is not null)entryBody.Invalid("Proposed","Use Proposed or its legacy Tolerance alias, not both.");
var current = Field(entryBody, "Current") ?? targetInfo?.CurrentValue;
var units = Field(entryBody, "Units") ?? UnitOf(proposed);
var currentUnit = UnitOf(current); var proposedUnit = UnitOf(proposed);
if (currentUnit is not null && proposedUnit is not null && !string.Equals(currentUnit, proposedUnit, StringComparison.OrdinalIgnoreCase))
- diagnostics.Add($"{UnitMismatch}: {entryId}: {currentUnit} vs {proposedUnit}");
+ Add(UnitMismatch,$"{entryId}: {currentUnit} vs {proposedUnit}",entryBody,"Proposed");
if (proposed is not null) proposal = new(property ?? "value", current, proposed, units, StringField(entryBody, "Reason"));
}
entries.Add(new(entryId, kind, new(authorName ?? "<missing>", StringField(entryBody, "Organization"), StringField(entryBody, "Email")), date, text, proposal, entryOrder++));
}
+ var closed=body.CompleteTree();diagnostics.AddRange(closed.Select(d=>d.Code+": "+d.Message));
+ located.AddRange(closed.Where(d=>d.SourceSpan is not null).Select(d=>new ReviewSourceDiagnostic(d.Code,d.Message,new(sourcePath,d.SourceSpan!.Start,d.SourceSpan.Length))));
threads.Add(new(id, new(target, sourcePath, targetInfo?.CurrentValue, targetInfo?.Capabilities ?? [], null), status, entries, $"{sourcePath}:Review {id}"));
}
- return new(diagnostics.Count == 0, new(threads), diagnostics, ranges);
+ return new(diagnostics.Count == 0, new(threads), diagnostics, ranges){SourceDiagnostics=located};
}
public static string EraseDeclarations(string source, IEnumerable<(int Start, int Length)> ranges)
@@ -82,25 +91,8 @@ public static partial class FirmamentReviewCompiler
return new(chars);
}
- private static int FindClosingBrace(string text, int open)
- {
- var depth = 0; var quoted = false; var escaped = false;
- for (var i = open; i < text.Length; i++)
- {
- var c = text[i];
- if (quoted) { if (escaped) escaped = false; else if (c == '\\') escaped = true; else if (c == '"') quoted = false; continue; }
- if (c == '"') { quoted = true; continue; }
- if (c == '{') depth++; else if (c == '}' && --depth == 0) return i;
- }
- return -1;
- }
-
- private static string? Field(string body, string name) => Regex.Match(body, $@"(?m)(?:^|;)\s*{Regex.Escape(name)}\s*:\s*([^;\r\n]+)", RegexOptions.CultureInvariant).Groups[1].Value.Trim() is { Length: > 0 } value ? value : null;
- private static string? StringField(string body, string name) { var value = Field(body, name); return value is not null && value.Length >= 2 && value[0] == '"' && value[^1] == '"' ? Regex.Unescape(value[1..^1]) : value; }
+ private static string? Field(FirmamentSyntaxScope body,string name)=>body.Raw(name);
+ private static string? StringField(FirmamentSyntaxScope body,string name)=>body.Word(name);
private static string? UnitOf(string? value) => value is null ? null : Regex.Match(value, @"(?i)(mm|cm|m|in|deg)\b").Groups[1].Value is { Length: > 0 } unit ? unit.ToLowerInvariant() : null;
- [GeneratedRegex(@"(?m)^\s*Review\s+([A-Za-z_][A-Za-z0-9_.-]*)\s*\{")]
- private static partial Regex ReviewStart();
- [GeneratedRegex(@"(?m)^\s*(Comment|Issue|Proposal|Resolution)(?:\s+([A-Za-z_][A-Za-z0-9_.-]*))?\s*\{")]
- private static partial Regex EntryStart();
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index ca4f6d9b..251c3c9f 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -67,8 +67,7 @@ public static class FirmamentBuildAndExport
{
var structural = StructuralAuthoring.Compile(sourceText, fullSourcePath);
if (!structural.IsSuccess || structural.StepText is null || structural.Report is null)
- return KernelResult<FirmamentBuildAndExportResult>.Failure(structural.Diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(
- Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "Structural.X2")).ToArray());
+ return KernelResult<FirmamentBuildAndExportResult>.Failure(structural.KernelDiagnostics());
var structuralOutputPath = string.IsNullOrWhiteSpace(outputPath) ? ResolveDefaultOutputPath(fullSourcePath) : Path.GetFullPath(outputPath);
Directory.CreateDirectory(Path.GetDirectoryName(structuralOutputPath)!);
File.WriteAllText(structuralOutputPath, structural.StepText, new UTF8Encoding(false));
@@ -142,8 +141,7 @@ public static class FirmamentBuildAndExport
var structural = StructuralAuthoring.Compile(normalized, sourceDirectory ?? "memory");
return structural.IsSuccess && structural.StepText is not null && structural.Report is not null
? KernelResult<FirmamentStepExportResult>.Success(new(structural.StepText, "structure:" + structural.Report.Structure, -1, "Assembly", "Structure", Structural: structural.Report))
- : KernelResult<FirmamentStepExportResult>.Failure(structural.Diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(
- Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "Structural.X2")).ToArray());
+ : KernelResult<FirmamentStepExportResult>.Failure(structural.KernelDiagnostics());
}
var library = FirmamentStandardLibraryResolver.Resolve(normalized, out var libraryDiagnostics);
if (library is null)
diff --git a/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs b/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs
index f0e74a5e..d90c6669 100644
--- a/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs
@@ -6,7 +6,7 @@ namespace Aetheris.Kernel.Firmament;
/// <summary>Program-level selection of an existing Firmament frontend. This is deliberately
/// not a second parser or semantic IR: it only makes the current parser boundary explicit.</summary>
-public enum FirmamentFrontendSchema { Mechanical, WireForm, Sweep, SectionChain, Garment, Piping }
+public enum FirmamentFrontendSchema { Mechanical, WireForm, Sweep, SectionChain, Garment, Piping, Structural, Sculpting, Analysis, PlasticShell }
public sealed record FirmamentFrontendSelection(FirmamentFrontendSchema? Schema, string Source, IReadOnlyList<string> Diagnostics)
{
@@ -22,7 +22,7 @@ public sealed record FirmamentFrontendSelection(FirmamentFrontendSchema? Schema,
public static class FirmamentFrontendSchemas
{
- public static readonly IReadOnlyList<string> Names = ["Mechanical", "WireForm", "Sweep", "SectionChain", "Garment", "Piping"];
+ public static readonly IReadOnlyList<string> Names = ["Mechanical", "WireForm", "Sweep", "SectionChain", "Garment", "Piping", "Structural", "Sculpting", "Analysis", "PlasticShell"];
public static FirmamentFrontendSelection Select(string source)
{
@@ -88,6 +88,10 @@ public static class FirmamentFrontendSchemas
}
private static FirmamentFrontendSchema? DetectDistinctFrontend(string source) =>
+ FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d=>d.Type.Name.Text=="LinearElastic" && d.Modifiers.Any(m=>m.Name.Text is "Analysis" or "analysis")) ? FirmamentFrontendSchema.Analysis :
+ FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d=>d.Type.Name.Text=="PlasticShell") ? FirmamentFrontendSchema.PlasticShell :
+ Structural.StructuralAuthoring.IsStructuralSource(source) ? FirmamentFrontendSchema.Structural :
+ Aetheris.Surfacing.SculptingAuthoring.IsSculptingSource(source) ? FirmamentFrontendSchema.Sculpting :
Piping.PipingAuthoring.IsPipingSource(source) ? FirmamentFrontendSchema.Piping :
Garment.GarmentAuthoring.HasRoot(source) ? FirmamentFrontendSchema.Garment :
WireFormAuthoring.IsWireFormSource(source) ? FirmamentFrontendSchema.WireForm :
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainBinding.cs
index 42ba3044..bb66293f 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainBinding.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainBinding.cs
@@ -18,11 +18,15 @@ public sealed class FirmamentDomainBinding
public IReadOnlyList<ConceptIrTemplateInstantiation> Instantiations { get; }
public IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics => errors.Concat(concepts.Diagnostics.Select(d=>d with
{ SourceFile=Document.SourceFile,SourceSpan=d.SourceSpan is {} span?OriginalSpan(span):null,
- LocationNote=IsExpanded?"Location identifies the original enclosing declaration; the check evaluated expanded values.":d.LocationNote })).ToArray();
+ LocationNote=IsExpanded?"Location identifies the original enclosing declaration; the check evaluated expanded values.":d.LocationNote })).DistinctBy(d=>(d.Code,d.SourceSpan,d.Message)).ToArray();
private readonly List<FirmamentV2ValidationDiagnostic> errors = [];
public FirmamentDomainBinding(string source, string sourceFile, string ownerType, IReadOnlySet<string> domainResults, string? originalSource=null)
{
+ originalSource ??= source;
+ var frontend=FirmamentFrontendSchemas.Select(source);
+ errors.AddRange(frontend.LocatedDiagnostics.Select(d=>d with {SourceFile=sourceFile}));
+ source=frontend.Source;
values = new(source);
var codes = new List<string>();
var expansion = FirmamentV2TemplateExpansion.Expand(source, codes, values);
@@ -63,6 +67,8 @@ public sealed class FirmamentDomainBinding
public bool OwnsConstruction(DeclarationSyntax declaration) => ClosedBoundary2Authoring.IsBoundaryType(declaration.Type.Name.Text)
|| ProfileAuthoringParser.OwnsConstructionGuide(declaration.Type.Name.Text);
public bool OwnsProfileData(DeclarationSyntax declaration) => ProfileAuthoringParser.OwnsDeclaration(declaration);
+ internal FirmamentV2TemplateExpansion.DataCatalog DataCatalog(List<string> diagnostics) => FirmamentV2TemplateExpansion.ReadDataCatalog(Source, diagnostics, values);
+ internal string DataName(string identity) => values.DataBindings.FirstOrDefault(d => d.Identity == identity)?.Name ?? identity;
public bool OwnsData(DeclarationSyntax declaration) => FirmamentDataBinding.NamespaceFor(declaration) is not null;
public FirmamentV2SourceSpan? OriginalSpan(FirmamentV2SourceSpan span)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainDiagnostics.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainDiagnostics.cs
new file mode 100644
index 00000000..22481e40
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainDiagnostics.cs
@@ -0,0 +1,18 @@
+using Aetheris.Kernel.Core.Diagnostics;
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>Retains compatibility messages while projecting located domain errors through the common CLI/SDK contract.</summary>
+public static class FirmamentDomainDiagnostics
+{
+ public static IReadOnlyList<KernelDiagnostic> Present(IReadOnlyList<string> messages,IReadOnlyList<FirmamentV2ValidationDiagnostic> frontend,string owner)
+ {
+ var spans=frontend.GroupBy(d=>d.Code.Split(':')[0]).ToDictionary(g=>g.Key,g=>new Queue<FirmamentV2ValidationDiagnostic>(g));
+ return messages.Select(message=>
+ {
+ var code=message.Split(':')[0];
+ var located=spans.TryGetValue(code,out var pending)&&pending.Count>0?pending.Dequeue():null;
+ return new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Error,located is null?message:code+": "+located.Message,owner)
+ {OriginalSourceSpan=located?.SourceSpan is {} span?new(span.Start,span.Length){LocationNote=located.LocationNote}:null};
+ }).ToArray();
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
index 5486edd5..3dd02e35 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
@@ -30,11 +30,18 @@ public static class FirmamentLanguageAnalysisService
{
ArgumentNullException.ThrowIfNull(source);
var lexemes = Lex(FirmamentSourceSpelling.Normalize(source));
- var documentSyntax = Syntax.FirmamentSyntaxParser.Parse(source).Document;
+ var syntaxReport = Syntax.FirmamentSyntaxParser.Parse(source,document);
+ var documentSyntax = syntaxReport.Document;
var hasConcreteRoot = documentSyntax.Statements.OfType<Syntax.DeclarationSyntax>().Any(d =>
d.Type.Name.Text is "Model" or "model" or "Struct" && !d.Modifiers.Any(m => m.Name.Text is "Template" or "Concept"));
var tokens = lexemes.Select((lexeme, index) => new FirmamentLanguageToken(
lexeme.Start, lexeme.Length, Classify(lexemes, index))).ToArray();
+ if(Structural.StructuralAuthoring.IsStructuralSource(source))
+ return new(document,revision,tokens,Structural.StructuralAuthoring.Analyze(source,document).Select(d=>
+ {
+ var located=FirmamentBuildAdmissionValidation.Present(d,document,source);
+ return new FirmamentLanguageDiagnostic(located.Severity,located.Code,located.Message,located.SourceSpan?.Start??0,located.SourceSpan?.Length??0);
+ }).ToArray());
if (Garment.GarmentAuthoring.HasRoot(source))
{
var garment = Garment.GarmentCompiler.Compile(source, document);
@@ -57,6 +64,16 @@ public static class FirmamentLanguageAnalysisService
var assembly = new AssemblyM0Parser().Parse(source, document);
return new(document, revision, tokens, assembly.Diagnostics.Select(d => new FirmamentLanguageDiagnostic(d.Severity == AssemblyDiagnosticSeverity.Error ? "error" : "information", d.Code, d.Message, 0, 0)).ToArray());
}
+ if(Syntax.FirmamentSyntaxTraversal.Declarations(documentSyntax).FirstOrDefault(d=>d.Type.Name.Text is "PlasticShell" or "BodyState" or "SculptState"
+ || d.Type.Name.Text=="LinearElastic" && d.Modifiers.Any(m=>m.Name.Text is "Analysis" or "analysis")) is {} externalDomain)
+ {
+ // Editor analysis never materializes sculpt states or runs engineering.
+ // The owning compilation supplies semantic/capability diagnostics.
+ var messages=syntaxReport.Diagnostics.Select(d=>new FirmamentLanguageDiagnostic(d.Severity=="warning"?"warning":"error",d.Code,d.Message,d.SourceSpan?.Start??0,d.SourceSpan?.Length??0)).ToList();
+ if(syntaxReport.IsSuccess)messages.Add(new("information","firmament-language-domain-context-required",
+ "Shared syntax checked only. Use this domain's build/validate compiler for semantic, capability and geometry diagnostics.",externalDomain.Span.Start,externalDomain.Span.Length));
+ return new(document,revision,tokens,messages);
+ }
if (SectionChainAuthoringParser.IsSectionChainSource(source))
{
var section = SectionChainAuthoringParser.Compile(source, materialize: false);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs
index 3dac6004..4f2fa413 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs
@@ -17,7 +17,13 @@ public static class FirmamentSourceSpelling
["Include"] = "include", ["Expose"] = "expose", ["Bind"] = "bind", ["From"] = "from", ["To"] = "to"
};
- public static string PreferredField(string name) => name.Length == 0 ? name : char.ToLowerInvariant(name[0]) + name[1..];
+ public static string PreferredField(string name)
+ {
+ var count=0;while(count<name.Length && char.IsUpper(name[count]))count++;
+ if(count>1 && count<name.Length)count--;
+ if(count==0)return name;
+ return name[..count].ToLowerInvariant()+name[count..];
+ }
public static string Normalize(string source) => Rewrite(source, preferred: false);
public static string Prefer(string source) => Rewrite(source, preferred: true);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
index 92355028..0dfeea12 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
@@ -191,6 +191,12 @@ public static class FirmamentSyntaxParser
// Lowercase from was already a legal authored name. It becomes a link
// only after the declaration name, never a newly reserved identifier.
if (Current.Kind == SyntaxTokenKind.Identifier && !LineBreak && (Current.Text == "from" || !IsClause(Current.Text))) name = Identifier();
+ // Loss-aware STEP recovery uses quoted, externally supplied identities.
+ if (name is null && type.Name.Text is "RecoveredRegion" or "RecoveredBend" or "RecoveredCut" && Current.Kind==SyntaxTokenKind.String)
+ {
+ var token=Current;at++;
+ name=new(System.Text.Json.JsonSerializer.Deserialize<string>(token.Text)!,token.Span);
+ }
ExpressionSyntax? target = null;
if (type.Name.Text is "CornerProfile" or "EdgeProfile" && name is not null)
{
@@ -388,6 +394,11 @@ public static class FirmamentSyntaxParser
&& (t.Span.Start + t.Span.Length) == Current.Span.Start && t.Text.Count(c => c == '.') == 1)
{ at++; left = new LiteralSyntax(LiteralKind.Version, source[start..(Previous.Span.Start + Previous.Span.Length)], Span(start)); }
}
+ else if (Take("$"))
+ {
+ // Forge resource identity. Domain binding must still resolve it.
+ var resource=Identifier();left=new ReferenceSyntax(new("$"+resource.Text,Span(start)),Span(start));
+ }
else if (Take("#"))
{
if (Current.Kind != SyntaxTokenKind.Number || Current.Text.Any(c => !char.IsAsciiDigit(c)))
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxScope.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxScope.cs
new file mode 100644
index 00000000..d8baf755
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxScope.cs
@@ -0,0 +1,105 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.FirmamentInterop;
+using System.Globalization;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+/// <summary>Consumption of an existing declaration tree by its semantic owner.
+/// This is not a parser or a field schema. Owners take their fields/children,
+/// then close the tree; every remaining statement is an error.</summary>
+public sealed class FirmamentSyntaxScope
+{
+ private readonly string source;
+ private readonly string sourceFile;
+ private readonly Func<ExpressionSyntax, ExpressionSyntax>? bind;
+ private readonly Func<FirmamentV2SourceSpan, FirmamentV2SourceSpan?>? origin;
+ private readonly List<FirmamentSyntaxScope> scopes;
+ private readonly Dictionary<DeclarationSyntax, FirmamentSyntaxScope> children = [];
+ private readonly HashSet<StatementSyntax> consumed = [];
+ private readonly List<string> errors = [];
+ private readonly FirmamentSyntaxFields fields;
+ private readonly HashSet<string> modifiers = new(StringComparer.Ordinal);
+ private bool admitAnnotation;
+ private bool admitInitializer;
+ private bool admitPlacement;
+ public FirmamentSyntaxScope AdmitPlacement() { admitPlacement=true; return this; }
+ public FirmamentSyntaxScope AdmitAnnotation() { admitAnnotation=true; return this; }
+ public FirmamentSyntaxScope AdmitInitializer() { admitInitializer=true; return this; }
+ public DeclarationSyntax Declaration { get; }
+ public string Name => Declaration.Name?.Text ?? Declaration.Type.Name.Text;
+ public string Kind => Declaration.Type.Name.Text;
+ public FirmamentV2SourceSpan Span => Declaration.Span;
+ public int Start => Span.Start;
+ public int Length => Span.Length;
+ public FirmamentSyntaxScope Body => this;
+
+ public FirmamentSyntaxScope(DeclarationSyntax declaration, string source, string sourceFile = "memory",
+ Func<ExpressionSyntax, ExpressionSyntax>? bind = null,
+ Func<FirmamentV2SourceSpan, FirmamentV2SourceSpan?>? origin = null)
+ : this(declaration, source, sourceFile, bind, origin, []) { }
+
+ private FirmamentSyntaxScope(DeclarationSyntax declaration, string source, string sourceFile,
+ Func<ExpressionSyntax, ExpressionSyntax>? bind, Func<FirmamentV2SourceSpan, FirmamentV2SourceSpan?>? origin,
+ List<FirmamentSyntaxScope> scopes)
+ {
+ Declaration = declaration; this.source = source; this.sourceFile = sourceFile;
+ this.bind = bind; this.origin = origin; this.scopes = scopes; scopes.Add(this);
+ fields = new(declaration, errors, bind: bind);
+ }
+ public FirmamentSyntaxScope AllowModifier(string modifier) { modifiers.Add(modifier); return this; }
+ public IReadOnlyList<FirmamentSyntaxScope> Children(string kind, bool legacyCase = false)
+ {
+ var result = new List<FirmamentSyntaxScope>();
+ foreach (var child in Declaration.Body?.Statements.OfType<DeclarationSyntax>() ?? [])
+ {
+ if (!string.Equals(child.Type.Name.Text, kind, legacyCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) continue;
+ consumed.Add(child);
+ if (!children.TryGetValue(child, out var scope)) children[child] = scope = new(child, source, sourceFile, bind, origin, scopes);
+ result.Add(scope);
+ }
+ return result;
+ }
+ public void Consume(StatementSyntax statement) => consumed.Add(statement);
+ private static string Canonical(string name) => name.Length == 0 ? name : char.ToUpperInvariant(name[0]) + name[1..];
+ public ExpressionSyntax? Take(string name) => fields.Take(Canonical(name));
+ public IReadOnlyList<FieldSyntax> TakeAll(string name) => fields.TakeAll(Canonical(name)).Select(f=>f with { Value=bind?.Invoke(f.Value)??f.Value }).ToArray();
+ public string? Word(string name) => fields.Reference(Canonical(name));
+ public string? Raw(string name)
+ {
+ var authored = Declaration.Body?.Statements.OfType<FieldSyntax>().FirstOrDefault(f => FirmamentSyntaxFields.SameField(f.Name.Text, Canonical(name)));
+ var expression = Take(name);
+ if (expression is null) return null;
+ var text = FirmamentSyntaxWriter.Expression(expression);
+ if (authored is not null && text == FirmamentSyntaxWriter.Expression(authored.Value))
+ return source.Substring(authored.Value.Span.Start, authored.Value.Span.Length);
+ if (FirmamentNumericEvaluation.TryEvaluate(expression, out var number) && double.IsFinite(number.Number))
+ return number.Number.ToString("R", CultureInfo.InvariantCulture) + number.Unit;
+ return text;
+ }
+ public void Invalid(string name, string? message = null) => errors.Add($"firmament-v2-field-value-invalid:{Kind}:{name}" + (message is null ? "" : ": " + message));
+ public IReadOnlyList<FirmamentV2ValidationDiagnostic> CompleteTree()
+ {
+ var diagnostics = new List<FirmamentV2ValidationDiagnostic>();
+ foreach (var scope in scopes)
+ {
+ if (scope.Declaration.Type.Arguments.Count != 0 || scope.Declaration.HasParameterList
+ || scope.Declaration.Modifiers.Any(m => !scope.modifiers.Contains(m.Name.Text)))
+ scope.errors.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:{scope.Kind}:header");
+ scope.fields.Complete(scope.consumed, scope.admitAnnotation, scope.admitInitializer, scope.admitPlacement);
+ foreach (var code in scope.errors.Distinct(StringComparer.Ordinal))
+ {
+ var parts = code.Split(':');
+ var label = parts.Length > 2 ? parts[2] : "";
+ var field = scope.Declaration.Body?.Statements.OfType<FieldSyntax>().FirstOrDefault(f => FirmamentSyntaxFields.SameField(f.Name.Text, label));
+ var child = scope.Declaration.Body?.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d => d.Type.Name.Text == label);
+ var span = field?.Name.Span ?? child?.Span ?? scope.Span;
+ var mapped = origin?.Invoke(span) ?? (origin is null ? span : null);
+ var explanation=code.IndexOf(": ",StringComparison.Ordinal);
+ var message=FirmamentV2DiagnosticAdapter.MessageFor(code)+(explanation<0?"":" "+code[(explanation+2)..]);
+ diagnostics.Add(new(parts[0], "error", message, label, scope.Kind + " " + scope.Name)
+ { SourceFile = sourceFile, SourceSpan = mapped, IsOriginalSource = mapped is not null, Stage = "Binding",
+ LocationNote = mapped is null ? "Original-source provenance is unavailable after expansion." : mapped != span ? "Location identifies the original enclosing construct after compile-time expansion." : null });
+ }
+ }
+ return diagnostics;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs
index b323af24..2825e5f4 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs
@@ -92,15 +92,15 @@ public sealed class FirmamentSyntaxFields(DeclarationSyntax declaration, List<st
return value;
}
public bool Vector(string name, string unit, out double[] values) => FirmamentSyntaxValues.Vector(Take(name), unit, out values, implicitUnit);
- public void Complete()
+ public void Complete(IReadOnlySet<StatementSyntax>? consumedStatements = null, bool admitAnnotation = false, bool admitInitializer = false, bool admitPlacement = false)
{
- if (declaration.Occurrence || declaration.Parameters.Count > 0 || declaration.Annotation is not null || declaration.ResultType is not null || declaration.Initializer is not null)
+ if (declaration.Occurrence || declaration.Parameters.Count > 0 || (!admitAnnotation && declaration.Annotation is not null) || declaration.ResultType is not null || (!admitInitializer && declaration.Initializer is not null))
diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:{declaration.Type.Name.Text}:header");
- if (declaration.Clauses.Count > 0)
+ if (!admitPlacement && declaration.Clauses.Count > 0)
diagnostics.Add($"firmament-v2-placement-unsupported:{declaration.Type.Name.Text}:{declaration.Name?.Text}: This field-based construct does not admit header placement clauses; use its documented fields.");
foreach (var field in declaration.Body?.Statements.OfType<FieldSyntax>() ?? [])
if (!consumed.Contains(field)) diagnostics.Add($"{FirmamentV2Parser.CanonicalFieldUnknown}:{declaration.Type.Name.Text}:{field.Name.Text}");
- foreach (var statement in declaration.Body?.Statements.Where(s => s is not FieldSyntax) ?? [])
+ foreach (var statement in declaration.Body?.Statements.Where(s => s is not FieldSyntax && consumedStatements?.Contains(s) != true) ?? [])
diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:{declaration.Type.Name.Text}:{(statement as DeclarationSyntax)?.Type.Name.Text ?? "expression"}");
}
public static FirmamentSyntaxFields Object(ObjectSyntax value, string? name, List<string> diagnostics)
@@ -111,7 +111,8 @@ public sealed class FirmamentSyntaxFields(DeclarationSyntax declaration, List<st
return new(new(new(typeName, [], typeName.Span), value.Name ?? (name is null ? null : new(name, value.Span)),
[], [], null, null, [], null, value.Body, false, value.Span), diagnostics);
}
- public static bool SameField(string authored, string canonical) => authored == canonical || authored == FirmamentSourceSpelling.PreferredField(canonical);
+ public static bool SameField(string authored, string canonical) => authored == canonical || authored == FirmamentSourceSpelling.PreferredField(canonical)
+ || canonical.Length>0 && authored == char.ToLowerInvariant(canonical[0])+canonical[1..];
public IReadOnlyList<FirmamentV2AuthoredField> AuthoredFields => (declaration.Body?.Statements.OfType<FieldSyntax>() ?? [])
.Select(f => new FirmamentV2AuthoredField(f.Name.Text, f.Span, f.Value.Span)).ToArray();
}
diff --git a/Aetheris.Kernel.Firmament/Piping/PipingModels.cs b/Aetheris.Kernel.Firmament/Piping/PipingModels.cs
index 0781b426..6d51d2ef 100644
--- a/Aetheris.Kernel.Firmament/Piping/PipingModels.cs
+++ b/Aetheris.Kernel.Firmament/Piping/PipingModels.cs
@@ -121,15 +121,6 @@ public sealed record PipingCompilationResult(
public IReadOnlyList<Core.Diagnostics.KernelDiagnostic> KernelDiagnostics()
{
- var spans = FrontendDiagnostics.GroupBy(d => d.Code.Split(':')[0])
- .ToDictionary(g => g.Key, g => new Queue<FirmamentV2.FirmamentV2ValidationDiagnostic>(g));
- return Diagnostics.Select(message =>
- {
- var code = message.Split(':')[0];
- var located = spans.TryGetValue(code, out var pending) && pending.Count > 0 ? pending.Dequeue() : null;
- return new Core.Diagnostics.KernelDiagnostic(Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
- Core.Diagnostics.KernelDiagnosticSeverity.Error, located is null ? message : code + ": " + located.Message, "Firmament.Piping")
- { OriginalSourceSpan = located?.SourceSpan is { } span ? new(span.Start, span.Length) { LocationNote = located.LocationNote } : null };
- }).ToArray();
+ return FirmamentV2.FirmamentDomainDiagnostics.Present(Diagnostics, FrontendDiagnostics, "Firmament.Piping");
}
}
diff --git a/Aetheris.Kernel.Firmament/Structural/StructuralAuthoring.cs b/Aetheris.Kernel.Firmament/Structural/StructuralAuthoring.cs
index 5961fc5d..fa18e1b8 100644
--- a/Aetheris.Kernel.Firmament/Structural/StructuralAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/Structural/StructuralAuthoring.cs
@@ -2,7 +2,9 @@ using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
-using System.Text.RegularExpressions;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Block = Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxScope;
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Brep.Verification;
using Aetheris.Kernel.Core.Diagnostics;
@@ -53,7 +55,11 @@ public sealed record StructuralReport(
public sealed record StructuralMemberSummary(string StableId, string Path, string Section, string Material, double RawLengthMm, double FinishedLengthMm, string StartTreatment, string EndTreatment, double MassKilograms);
public sealed record StructuralCompilationResult(bool IsSuccess, string? StepText, StructuralReport? Report, IReadOnlyList<string> Diagnostics,
- IReadOnlyList<StructuralMemberIr>? RealizedMembers = null);
+ IReadOnlyList<StructuralMemberIr>? RealizedMembers = null)
+{
+ public IReadOnlyList<FirmamentV2ValidationDiagnostic> FrontendDiagnostics { get; init; } = [];
+ public IReadOnlyList<KernelDiagnostic> KernelDiagnostics() => FirmamentDomainDiagnostics.Present(Diagnostics,FrontendDiagnostics,"Firmament.Structural");
+}
public readonly record struct StructuralEndPlane(double CenterDepth, double XCoefficient, double YCoefficient, StructuralEndTreatmentIr Treatment);
/// <summary>
@@ -64,14 +70,19 @@ public readonly record struct StructuralEndPlane(double CenterDepth, double XCoe
public static class StructuralAuthoring
{
private const double Tol = 1e-7;
- public static bool IsStructuralSource(string source) => Regex.IsMatch(source, @"\bStructure\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant);
+ public static bool IsStructuralSource(string source) => source.Contains("Structure",StringComparison.Ordinal) && FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Any(d=>d.Type.Name.Text=="Structure");
public static StructuralCompilationResult Compile(string source, string sourceIdentity = "memory")
+ {
+ var frontend=new List<FirmamentV2ValidationDiagnostic>();
+ return CompileCore(source,sourceIdentity,frontend) with {FrontendDiagnostics=frontend};
+ }
+ private static StructuralCompilationResult CompileCore(string source,string sourceIdentity,List<FirmamentV2ValidationDiagnostic> frontend)
{
var total = System.Diagnostics.Stopwatch.StartNew();
var diagnostics = new List<string>();
var parseClock = System.Diagnostics.Stopwatch.StartNew();
- var parsed = Parse(source, sourceIdentity, diagnostics);
+ var parsed = Parse(source, sourceIdentity, diagnostics, frontend);
parseClock.Stop();
if (parsed is null) return new(false, null, null, diagnostics);
@@ -150,6 +161,13 @@ public static class StructuralAuthoring
return new(true, step.Value, report, [], realized);
}
+ public static IReadOnlyList<KernelDiagnostic> Analyze(string source,string sourceIdentity)
+ {
+ var messages=new List<string>();var frontend=new List<FirmamentV2ValidationDiagnostic>();
+ _=Parse(source,sourceIdentity,messages,frontend);
+ return FirmamentDomainDiagnostics.Present(messages,frontend,"Firmament.Structural");
+ }
+
public static string CutListJson(StructuralReport report) => JsonSerializer.Serialize(new
{
schema = "aetheris:structural-cut-list:x2", structure = report.Structure, units = new { length = "mm", mass = "kg" }, entries = report.CutList
@@ -158,16 +176,47 @@ public static class StructuralAuthoring
private sealed record Parsed(string Name, IReadOnlyList<StructuralNodeAir> Nodes, IReadOnlyList<StructuralPathAir> Paths, IReadOnlyList<StructuralSectionAir> Sections, IReadOnlyList<StructuralMemberAir> Members, IReadOnlyList<StructuralJointAir> Joints, IReadOnlyList<StructuralWeldAir> Welds, IReadOnlyDictionary<string, ResolvedMaterial> Materials);
private sealed record MemberEnds(StructuralEndPlane Start, StructuralEndPlane End);
- private static Parsed? Parse(string source, string sourceIdentity, List<string> d)
+ private static Parsed? Parse(string source, string sourceIdentity, List<string> d,List<FirmamentV2ValidationDiagnostic> frontend)
{
- var structure = Blocks(source, "Structure").SingleOrDefault();
- if (structure == default) { d.Add("structural-missing-structure: exactly one Structure block is required"); return null; }
- if (Blocks(source, "Structure").Count != 1) { d.Add("structural-multiple-structures-unsupported: X2 admits one Structure per model"); return null; }
- var nodes = Regex.Matches(structure.Body, @"\bNode\s+(?<n>[A-Za-z_]\w*)\s*=\s*\[(?<v>[^\]]+)\]\s*;", RegexOptions.CultureInvariant)
- .Select(m => new StructuralNodeAir($"structure:{structure.Name}:node:{m.Groups["n"].Value}", m.Groups["n"].Value, Point(Vector(m.Groups["v"].Value, d, "node:" + m.Groups["n"].Value)), sourceIdentity)).ToArray();
- var paths = Regex.Matches(structure.Body, @"\bPath\s+(?<n>[A-Za-z_]\w*)\s*:\s*(?<a>[A-Za-z_]\w*)\s*->\s*(?<b>[A-Za-z_]\w*)\s*;", RegexOptions.CultureInvariant)
- .Select(m => (Name:m.Groups["n"].Value, A:m.Groups["a"].Value, B:m.Groups["b"].Value)).ToArray();
- Duplicates(nodes.Select(x => x.Name), "node", d); Duplicates(paths.Select(x => x.Name), "path", d);
+ var binding=new FirmamentDomainBinding(source,sourceIdentity,"Structure",new HashSet<string>(StringComparer.Ordinal));
+ frontend.AddRange(binding.Diagnostics);
+ d.AddRange(binding.Diagnostics.Select(e=>e.Code+": "+e.Message));if(d.Count>0)return null;
+ source=binding.Source;
+ var document=new DeclarationSyntax(new(new("document",binding.Document.Span),[],binding.Document.Span),null,[],[],null,null,[],null,new(binding.Document.Statements,binding.Document.Span),false,binding.Document.Span);
+ var root=new Block(document,source,sourceIdentity,binding.Nominal,binding.OriginalSpan);
+ var scopes=new List<Block>{root};var owner=root;
+ while(true)
+ {
+ var wrappers=owner.Children("Model").Concat(owner.Children("Struct")).ToArray();
+ if(wrappers.Length==0)break;
+ if(wrappers.Length!=1){d.Add("structural-owner-cardinality: use one structural product owner; sibling products are not pooled");return null;}
+ owner=wrappers[0];scopes.Add(owner);
+ }
+ foreach(var scope in scopes)
+ {
+ var units=scope.Word("Units");if(units is not null && units!="mm")d.Add("structural-units-invalid: structural authoring uses millimetres");
+ foreach(var data in scope.Declaration.Body?.Statements.OfType<DeclarationSyntax>().Where(binding.OwnsData)??[])scope.Consume(data);
+ }
+ IReadOnlyList<Block> Blocks(string kind)=>owner.Children(kind);
+ var structures=Blocks("Structure");
+ if(structures.Count!=1){d.Add("structural-missing-structure: exactly one Structure is required");return null;}
+ var structure=structures[0];
+ var nodes=new List<StructuralNodeAir>();
+ foreach(var node in structure.Children("Node"))
+ {
+ structure.Consume(node.Declaration);
+ if(node.Declaration.Initializer is not {} value || !FirmamentSyntaxValues.Vector(binding.Nominal(value),"mm",out var v,"mm") || v.Length!=3 || !v.All(double.IsFinite))
+ d.Add("structural-vector-invalid:node:"+node.Name);
+ else nodes.Add(new($"structure:{structure.Name}:node:{node.Name}",node.Name,new(v[0],v[1],v[2]),sourceIdentity));
+ node.AdmitInitializer();
+ }
+ var paths=new List<(string Name,string A,string B)>();
+ foreach(var path in structure.Children("Path"))
+ if(path.Declaration.Annotation is BinarySyntax {Operator:BinaryOperator.Direction} arrow && FirmamentSyntaxValues.Reference(arrow.Left) is {} a && FirmamentSyntaxValues.Reference(arrow.Right) is {} b)
+ { paths.Add((path.Name,a,b)); path.AdmitAnnotation(); }
+ else d.Add("structural-path-invalid:"+path.Name);
+ Duplicates(nodes.Select(x=>x.Name),"node",d);Duplicates(paths.Select(x=>x.Name),"path",d);
+ if(d.Count>0)return null;
var nodeByName = nodes.ToDictionary(x => x.Name, StringComparer.Ordinal);
var pathAir = new List<StructuralPathAir>();
foreach (var p in paths)
@@ -177,14 +226,34 @@ public static class StructuralAuthoring
pathAir.Add(new($"structure:{structure.Name}:path:{p.Name}", p.Name, p.A, p.B, delta / delta.Length, delta.Length, sourceIdentity));
}
+ var catalog=binding.DataCatalog(d);if(d.Count>0)return null;var tableRows=new List<StructuralRow>();
+ IReadOnlyList<IReadOnlyDictionary<string,string>> TableRows(FirmamentDomainBinding context,string rowType,List<string> errors)
+ {
+ var result=new List<IReadOnlyDictionary<string,string>>();
+ foreach(var table in catalog.Tables.Values.Where(t=>context.DataName(t.RowType)==rowType))
+ {
+ var count=table.Columns.Values.FirstOrDefault().Length;
+ for(var i=0;i<count;i++)
+ {
+ var row=new StructuralRow(table.Name,table.Columns.ToDictionary(c=>c.Key,c=>c.Value[i],StringComparer.Ordinal));
+ tableRows.Add(row);result.Add(row);
+ }
+ }
+ return result;
+ }
var sections = new List<StructuralSectionAir>();
- foreach (var block in Blocks(source, "Section"))
+ foreach (var block in Blocks("Section"))
{
var kindText = Field(block.Body, "Kind");
if (kindText.StartsWith("Standard.Structural.", StringComparison.Ordinal)) kindText = kindText["Standard.Structural.".Length..];
- if (!Enum.TryParse<StructuralSectionKind>(kindText, out var kind)) { d.Add($"structural-section-kind-unsupported:{block.Name}: '{kindText}'"); continue; }
+ if ((!Enum.TryParse<StructuralSectionKind>(kindText, out var kind)||!Enum.IsDefined(kind))) { d.Add($"structural-section-kind-unsupported:{block.Name}: '{kindText}'"); continue; }
var width = LengthField(block.Body, kind == StructuralSectionKind.RoundTube || kind == StructuralSectionKind.RoundBar ? "Diameter" : "Width", d, block.Name);
var height = kind is StructuralSectionKind.SquareTube ? width : kind is StructuralSectionKind.RoundTube or StructuralSectionKind.RoundBar ? width : LengthField(block.Body, "Height", d, block.Name);
+ if(kind==StructuralSectionKind.SquareTube && block.Take("Height") is not null)
+ {
+ var declaredHeight=LengthField(block,"Height",d,block.Name);
+ if(Math.Abs(declaredHeight-width)>Tol)d.Add($"structural-square-section-height-invalid:{block.Name}: height must equal width; use RectangularTube for unequal dimensions");
+ }
var thickness = kind is StructuralSectionKind.FlatBar or StructuralSectionKind.RoundBar ? 0 : LengthField(block.Body, "Thickness", d, block.Name);
if (width <= 0 || height <= 0) d.Add($"structural-section-invalid-dimensions:{block.Name}: dimensions must be positive");
if (kind is StructuralSectionKind.SquareTube or StructuralSectionKind.RectangularTube or StructuralSectionKind.RoundTube && (thickness <= 0 || thickness * 2 >= Math.Min(width, height))) d.Add($"structural-section-wall-too-large:{block.Name}");
@@ -195,12 +264,13 @@ public static class StructuralAuthoring
var resolver = new MaterialResolver(); var materials = new Dictionary<string, ResolvedMaterial>(StringComparer.Ordinal);
var members = new List<StructuralMemberAir>();
- foreach (var block in Blocks(source, "Member"))
+ foreach (var block in Blocks("Member"))
{
AddMember(block.Name, Field(block.Body, "Path"), Field(block.Body, "Section"), Field(block.Body, "Material"), Field(block.Body, "Orientation", required:false));
}
- var defaultMaterial = Blocks(source,"StructuralDefaults").Select(x=>Field(x.Body,"Material",required:false)).FirstOrDefault(x=>!string.IsNullOrWhiteSpace(x)) ?? "";
- foreach (var row in TableRows(source, "StructuralMemberRow", d))
+ var defaults=Blocks("StructuralDefaults");if(defaults.Count>1)d.Add("structural-defaults-duplicate: only one default material block is admitted");
+ var defaultMaterial=defaults.Select(x=>Field(x.Body,"Material",required:false)).FirstOrDefault(x=>!string.IsNullOrWhiteSpace(x))??"";
+ foreach (var row in TableRows(binding, "StructuralMemberRow", d))
AddMember(Cell(row,"Name"),Cell(row,"Path"),Cell(row,"Section"),Cell(row,"Material",false) is var tableMaterial && tableMaterial.Length>0?tableMaterial:defaultMaterial,Cell(row,"Orientation",false));
void AddMember(string name,string path,string section,string materialValue,string orientationText)
{
@@ -218,20 +288,20 @@ public static class StructuralAuthoring
if (members.GroupBy(x => x.Path).Any(g => g.Count() != 1)) d.Add("structural-path-member-cardinality: each Path must have exactly one Member");
var joints = new List<StructuralJointAir>();
- foreach (var block in Blocks(source, "Joint"))
+ foreach (var block in Blocks("Joint"))
{
var endpoints = Field(block.Body, "Members").Trim('[',']').Split(',', StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries);
if (endpoints.Length != 2 || !TryEndpoint(endpoints[0], out var a, out var ae) || !TryEndpoint(endpoints[1], out var b, out var be)) { d.Add($"structural-joint-endpoints-invalid:{block.Name}: exactly two Member.Start/End references are required"); continue; }
AddJoint(block.Name,Field(block.Body,"Type"),a,ae,b,be,Field(block.Body,"Primary",required:false));
}
- foreach(var row in TableRows(source,"StructuralJointRow",d))
+ foreach(var row in TableRows(binding,"StructuralJointRow",d))
{
if(!Enum.TryParse<StructuralEnd>(Cell(row,"FirstEnd"),out var ae)||!Enum.TryParse<StructuralEnd>(Cell(row,"SecondEnd"),out var be)){d.Add($"structural-joint-endpoints-invalid:{Cell(row,"Name")}");continue;}
AddJoint(Cell(row,"Name"),Cell(row,"Type"),Cell(row,"FirstMember"),ae,Cell(row,"SecondMember"),be,Cell(row,"Primary",false));
}
void AddJoint(string name,string type,string a,StructuralEnd ae,string b,StructuralEnd be,string primary)
{
- if (!Enum.TryParse<StructuralJointKind>(type, out var kind)) { d.Add($"structural-joint-kind-unsupported:{name}: '{type}'"); return; }
+ if ((!Enum.TryParse<StructuralJointKind>(type, out var kind)||!Enum.IsDefined(kind))) { d.Add($"structural-joint-kind-unsupported:{name}: '{type}'"); return; }
if (!members.Any(x => x.Name == a) || !members.Any(x => x.Name == b)) { d.Add($"structural-joint-unknown-member:{name}"); return; }
if (string.IsNullOrEmpty(primary)) primary = a;
if (kind == StructuralJointKind.Butt && primary != a && primary != b) d.Add($"structural-butt-primary-invalid:{name}: Primary must name a participant");
@@ -247,16 +317,20 @@ public static class StructuralAuthoring
if (occupied.Length > 0) d.Add("structural-multiple-joints-at-end-unsupported: " + string.Join(", ", occupied));
var welds = new List<StructuralWeldAir>();
- foreach (var block in Blocks(source, "Weld"))
+ foreach (var block in Blocks("Weld"))
{
AddWeld(block.Name,Field(block.Body,"Joint"),Field(block.Body,"Type"),Field(block.Body,"Size"));
}
- foreach(var row in TableRows(source,"StructuralWeldRow",d))AddWeld(Cell(row,"Name"),Cell(row,"Joint"),Cell(row,"Type"),Cell(row,"Size"));
+ foreach(var row in TableRows(binding,"StructuralWeldRow",d))AddWeld(Cell(row,"Name"),Cell(row,"Joint"),Cell(row,"Type"),Cell(row,"Size"));
void AddWeld(string name,string joint,string type,string sizeText)
{
var size=ParseLength(sizeText,d,name+".Size");var j=joints.FirstOrDefault(x=>x.Name==joint);if(j is null)d.Add($"structural-weld-unknown-joint:{name}: '{joint}'");if(type!="Fillet")d.Add($"structural-weld-type-unsupported:{name}: X2 admits Fillet");welds.Add(new($"weld:{name}",name,"joint:"+joint,type,size,j is null?[]:[j.FirstMember,j.SecondMember]));
}
- return d.Count == 0 ? new(structure.Name, nodes, pathAir, sections, members, joints, welds, materials) : null;
+ if(members.Count==0)d.Add("structural-member-required: declare at least one material Member");
+ var closed=root.CompleteTree();frontend.AddRange(closed);d.AddRange(closed.Select(e=>e.Code+": "+e.Message));
+ foreach(var row in tableRows)foreach(var duplicate in row.DuplicateRoles)d.Add("structural-table-field-duplicate:"+row.Table+":"+duplicate);
+ foreach(var row in tableRows)foreach(var column in row.Unconsumed)d.Add($"structural-table-field-unconsumed:{row.Table}:{column}");
+ return d.Count == 0 ? new(structure.Name, nodes.ToArray(), pathAir, sections, members, joints, welds, materials) : null;
}
private static Dictionary<string, MemberEnds> ResolveJoints(Parsed p, List<string> d)
@@ -411,32 +485,51 @@ public static class StructuralAuthoring
var projected=hint-z.ToVector()*hint.Dot(z.ToVector()); if(!Direction3D.TryCreate(projected,out var y)){d.Add($"structural-member-orientation-parallel:{member}");return null;} var x=Direction3D.Create(y.ToVector().Cross(z.ToVector())); y=Direction3D.Create(z.ToVector().Cross(x.ToVector()));return(x,y);
}
private static bool TryEndpoint(string text,out string member,out StructuralEnd end){var parts=text.Split('.',StringSplitOptions.TrimEntries);member=parts.ElementAtOrDefault(0)??"";end=default;return parts.Length==2&&Enum.TryParse(parts[1],out end);}
- private static string Field(string body,string name,bool required=true){var m=Regex.Match(body,$@"\b{Regex.Escape(name)}\s*:\s*(?<v>[^;\r\n]+)\s*;",RegexOptions.CultureInvariant);return m.Success?m.Groups["v"].Value.Trim():required?"":"";}
- private static double LengthField(string body,string name,List<string>d,string owner)=>ParseLength(Field(body,name),d,owner+"."+name);
- private static double ParseLength(string value,List<string>d,string owner){var m=Regex.Match(value,@"^(?<n>[+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*mm$",RegexOptions.CultureInvariant);if(!m.Success||!double.TryParse(m.Groups["n"].Value,NumberStyles.Float,CultureInfo.InvariantCulture,out var n)){d.Add($"structural-length-invalid:{owner}: '{value}'");return 0;}return n;}
- private static Vector3D Orientation(string value,List<string>d,string owner)=>value.Trim().Trim('"') switch{"" or "Auto"=>Vector3D.Zero,"UpX"=>new(1,0,0),"UpY"=>new(0,1,0),"UpZ"=>new(0,0,1),var raw=>Vector(raw.Trim('[',']'),d,"orientation:"+owner)};
- private static Vector3D Vector(string value,List<string>d,string owner){var parts=value.Split(',',StringSplitOptions.TrimEntries);if(parts.Length!=3||parts.Any(x=>!TryScalar(x,out _))){d.Add($"structural-vector-invalid:{owner}: '{value}'");return Vector3D.Zero;}return new(Scalar(parts[0]),Scalar(parts[1]),Scalar(parts[2]));}
- private static bool TryScalar(string expression,out double value)
+ private static string Field(Block body,string name,bool required=true)
+ {
+ var value=body.Raw(name);if(value is null&&required)body.Invalid(name,"Required field is missing.");return value??"";
+ }
+ private static double LengthField(Block body,string name,List<string>d,string owner)=>ParseLength(Field(body,name),d,owner+"."+name);
+ private static double ParseLength(string text,List<string> diagnostics,string owner)
+ {
+ var expression=FirmamentSyntaxParser.ParseExpression(text);
+ if(expression.Diagnostics.Count==0 && FirmamentSyntaxValues.TryMeasure(expression.Expression,"mm",out var value) && double.IsFinite(value))return value;
+ diagnostics.Add($"structural-length-invalid:{owner}: '{text}' requires a millimetre length");return 0;
+ }
+ private static Vector3D Orientation(string value,List<string> diagnostics,string owner)=>value.Trim().Trim('"') switch
+ {
+ "" or "Auto"=>Vector3D.Zero,"UpX"=>new(1,0,0),"UpY"=>new(0,1,0),"UpZ"=>new(0,0,1),var raw=>Vector(raw,diagnostics,"orientation:"+owner)
+ };
+ private static Vector3D Vector(string text,List<string> diagnostics,string owner)
{
- value=0;var normalized=expression.Replace("mm",string.Empty,StringComparison.Ordinal).Trim();var tokens=Regex.Split(normalized,@"\s*([*/])\s*",RegexOptions.CultureInvariant).Where(x=>x.Length>0).ToArray();if(tokens.Length==0||!double.TryParse(tokens[0],NumberStyles.Float,CultureInfo.InvariantCulture,out value))return false;for(var i=1;i+1<tokens.Length;i+=2){if(!double.TryParse(tokens[i+1],NumberStyles.Float,CultureInfo.InvariantCulture,out var operand))return false;if(tokens[i]=="*")value*=operand;else if(tokens[i]=="/"&&Math.Abs(operand)>Tol)value/=operand;else return false;}return tokens.Length%2==1&&double.IsFinite(value);
+ var parsed=FirmamentSyntaxParser.ParseExpression(text);
+ if(parsed.Diagnostics.Count==0 && FirmamentSyntaxValues.Vector(parsed.Expression,"",out var values) && values.Length==3 && values.All(double.IsFinite))return new(values[0],values[1],values[2]);
+ diagnostics.Add($"structural-vector-invalid:{owner}: '{text}' requires three dimensionless components");return Vector3D.Zero;
}
- private static double Scalar(string expression){TryScalar(expression,out var value);return value;}
private static Point3D Point(Vector3D v)=>new(v.X,v.Y,v.Z);
private static void Duplicates(IEnumerable<string> values,string kind,List<string>d){foreach(var g in values.GroupBy(x=>x,StringComparer.Ordinal).Where(x=>x.Count()>1))d.Add($"structural-duplicate-{kind}:{g.Key}");}
private static long Q(double x)=>(long)Math.Round(x*1_000_000,MidpointRounding.AwayFromZero);
- private readonly record struct Block(string Name,string Body);
- private static string Cell(IReadOnlyDictionary<string,string> row,string name,bool required=true)=>row.TryGetValue(name,out var value)?value.Trim().Trim('"'):required?"":"";
- private static IReadOnlyList<IReadOnlyDictionary<string,string>> TableRows(string source,string rowType,List<string>d)
- {
- var rows=new List<IReadOnlyDictionary<string,string>>();var pattern=$@"\bStatic\s+Table\s+(?<name>[A-Za-z_]\w*)\s*:\s*{Regex.Escape(rowType)}(?:\s+Key\s*:\s*[A-Za-z_]\w*)?\s*\{{";
- foreach(Match match in Regex.Matches(source,pattern,RegexOptions.CultureInvariant)){var open=match.Index+match.Length-1;var close=Matching(source,open,'{','}');if(close<0){d.Add($"structural-table-malformed:{match.Groups["name"].Value}");continue;}var body=source[(open+1)..close];var columns=new Dictionary<string,string[]>(StringComparer.Ordinal);foreach(Match column in Regex.Matches(body,@"\b(?<name>[A-Za-z_]\w*)\s*:\s*\[",RegexOptions.CultureInvariant)){var arrayOpen=column.Index+column.Length-1;var arrayClose=Matching(body,arrayOpen,'[',']');if(arrayClose<0)continue;var values=body[(arrayOpen+1)..arrayClose].Split(',',StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries);columns[column.Groups["name"].Value]=values;}var lengths=columns.Values.Select(x=>x.Length).Distinct().ToArray();if(lengths.Length!=1){d.Add($"structural-table-unequal-column-length:{match.Groups["name"].Value}");continue;}for(var i=0;i<lengths[0];i++)rows.Add(columns.ToDictionary(x=>x.Key,x=>x.Value[i],StringComparer.Ordinal));}
- return rows;
- }
- private static int Matching(string source,int open,char opening,char closing){var depth=0;for(var i=open;i<source.Length;i++){if(source[i]==opening)depth++;else if(source[i]==closing&&--depth==0)return i;}return-1;}
- private static IReadOnlyList<Block> Blocks(string source,string keyword)
+ private static string Cell(IReadOnlyDictionary<string,string> row,string name,bool required=true)=>row.TryGetValue(name,out var value)?value.Trim().Trim('"'):"";
+ private sealed class StructuralRow(string table,IReadOnlyDictionary<string,string> values):IReadOnlyDictionary<string,string>
{
- var result=new List<Block>();foreach(Match m in Regex.Matches(source,$@"\b{keyword}\s+(?<n>[A-Za-z_]\w*)\s*\{{",RegexOptions.CultureInvariant)){var open=m.Index+m.Length-1;var depth=0;var close=-1;for(var i=open;i<source.Length;i++){if(source[i]=='{')depth++;else if(source[i]=='}'&&--depth==0){close=i;break;}}if(close>open)result.Add(new(m.Groups["n"].Value,source[(open+1)..close]));}return result;
+ private readonly HashSet<string> consumed=[];
+ public string Table=>table;
+ public HashSet<string> DuplicateRoles { get; }=[];
+ public IEnumerable<string> Unconsumed=>values.Keys.Where(k=>!consumed.Contains(k));
+ public string this[string key]=>TryGetValue(key,out var value)?value:throw new KeyNotFoundException(key);
+ public IEnumerable<string> Keys=>values.Keys;public IEnumerable<string> Values=>values.Values;public int Count=>values.Count;
+ public bool ContainsKey(string key)=>values.ContainsKey(key);
+ public bool TryGetValue(string key,out string value)
+ {
+ var matches=values.Keys.Where(k=>FirmamentSyntaxFields.SameField(k,key)).ToArray();
+ foreach(var name in matches)consumed.Add(name);
+ if(matches.Length>1)DuplicateRoles.Add(key);
+ if(matches.Length==1){value=values[matches[0]];return true;}value="";return false;
+ }
+ public IEnumerator<KeyValuePair<string,string>> GetEnumerator()=>values.GetEnumerator();
+ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()=>GetEnumerator();
}
+
}
internal static class StructuralMemberBrepEmitter
diff --git a/Aetheris.Surfacing/SculptingAuthoring.cs b/Aetheris.Kernel.Firmament/Surfacing/SculptingAuthoring.cs
similarity index 74%
rename from Aetheris.Surfacing/SculptingAuthoring.cs
rename to Aetheris.Kernel.Firmament/Surfacing/SculptingAuthoring.cs
index ff841b96..b0ce0c6a 100644
--- a/Aetheris.Surfacing/SculptingAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/Surfacing/SculptingAuthoring.cs
@@ -1,29 +1,40 @@
using System.Diagnostics;
using System.Globalization;
-using System.Text.RegularExpressions;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Block = Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxScope;
using Aetheris.Kernel.Core.Geometry.Surfaces;
using Aetheris.Kernel.Core.Math;
namespace Aetheris.Surfacing;
-public sealed record SculptingTimingEvidence(double BasePreparationMilliseconds, double OperationConstructionMilliseconds, double LocalityAndPreservationMilliseconds, double BrepValidationMilliseconds, double StepExportMilliseconds);
-public sealed record SculptingCompileResult(bool IsSuccess, string ModelName, BodyState? OutputState, IReadOnlyDictionary<string, BodyState> States, IReadOnlyList<SculptDiagnostic> Diagnostics, SculptingTimingEvidence Timings);
-
public static class SculptingAuthoring
{
- private static readonly Regex ModelHeader = new(@"\bModel\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
+ public static bool IsSculptingSource(string source) => (source.Contains("BodyState", StringComparison.Ordinal) || source.Contains("SculptState", StringComparison.Ordinal))
+ && FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d => d.Type.Name.Text is "BodyState" or "SculptState");
+ public static SculptingCompileResult CompileFile(string path) => Compile(File.ReadAllText(path), path);
- public static bool IsSculptingSource(string source) => Regex.IsMatch(source, @"\b(?:BodyState|SculptState)\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant);
- public static SculptingCompileResult CompileFile(string path) => Compile(File.ReadAllText(path));
+ public static IReadOnlyList<Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic> KernelDiagnostics(SculptingCompileResult result) =>
+ result.Diagnostics.Select(d=>new Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic(
+ Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
+ d.Code+": "+d.Message,"Firmament.Sculpting"){OriginalSourceSpan=d.SourceSpan}).ToArray();
- public static SculptingCompileResult Compile(string source)
+ public static SculptingCompileResult Compile(string source, string sourceFile = "memory")
{
var total = Stopwatch.StartNew(); var diagnostics = new List<SculptDiagnostic>(); var states = new Dictionary<string, BodyState>(StringComparer.Ordinal);
var patches = new Dictionary<string, BoundedSurfacePatch>(StringComparer.Ordinal);
var sectionChains = new Dictionary<string, SectionChain>(StringComparer.Ordinal);
- var model = ModelHeader.Match(source); if (!model.Success) return Fail("<unknown>", "sculpt-source-malformed", "Sculpting source requires 'Model Name { ... }'.");
- if (!Regex.IsMatch(source, @"\b[Uu]nits\s*:\s*mm\b", RegexOptions.CultureInvariant)) diagnostics.Add(new("sculpt-units-invalid", "SURF-X0 authoring requires millimetres."));
- foreach (var block in Blocks(source, "SurfacePatch"))
+ var binding = new FirmamentDomainBinding(source, sourceFile, "BodyState", new HashSet<string>(StringComparer.Ordinal));
+ diagnostics.AddRange(binding.Diagnostics.Select(d => Located(d)));
+ if (diagnostics.Count != 0) return new(false, "<unknown>", null, states, diagnostics, new(0,0,0,0,0));
+ var models = binding.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Model").ToArray();
+ if (models.Length != 1) return Fail("<unknown>", "sculpt-source-malformed", "Sculpting source requires exactly one Model.");
+ var model = new Block(models[0], binding.Source, sourceFile, binding.Nominal, binding.OriginalSpan);
+ foreach (var statement in binding.Document.Statements.Where(s => !ReferenceEquals(s, models[0])))
+ if (statement is not DeclarationSyntax data || !binding.OwnsData(data)) diagnostics.Add(new("sculpt-statement-unknown", "Unsupported statement outside the sculpting Model."));
+ foreach (var data in models[0].Body?.Statements.OfType<DeclarationSyntax>().Where(binding.OwnsData) ?? []) model.Consume(data);
+ if (model.Word("Units") != "mm") diagnostics.Add(new("sculpt-units-invalid", "Sculpting authoring requires units: mm."));
+ foreach (var block in Blocks(model, "SurfacePatch"))
{
var degree = NumberVector(block.Body, "Degree", 2, diagnostics); var domain = NumberVector(block.Body, "Domain", 4, diagnostics);
var knotsU = NumberVectorAny(block.Body, "KnotsU", diagnostics); var knotsV = NumberVectorAny(block.Body, "KnotsV", diagnostics);
@@ -44,7 +55,7 @@ public static class SculptingAuthoring
diagnostics.Add(new("surf-patch-invalid", $"SurfacePatch '{block.Name}' is invalid: {exception.Message}", block.Name));
}
}
- foreach (var block in Blocks(source, "SectionChain"))
+ foreach (var block in Blocks(model, "SectionChain"))
{
var chain = ParseSectionChain(block, diagnostics);
if (chain is null) continue;
@@ -57,7 +68,7 @@ public static class SculptingAuthoring
if (!sectionChains.TryAdd(block.Name, chain)) diagnostics.Add(new("section-chain-duplicate", $"SectionChain '{block.Name}' is declared more than once.", block.Name));
}
var baseClock = Stopwatch.StartNew();
- foreach (var block in Blocks(source, "BodyState"))
+ foreach (var block in Blocks(model, "BodyState"))
{
var errorsBefore = diagnostics.Count;
var size = Vector(block.Body, "Size", 3, diagnostics); var holes = ParseHoles(block.Body, diagnostics);
@@ -67,17 +78,17 @@ public static class SculptingAuthoring
else if (!states.TryAdd(block.Name, created.OutputState)) diagnostics.Add(new("sculpt-state-duplicate", $"BodyState '{block.Name}' is declared more than once."));
}
baseClock.Stop(); var opConstruction = TimeSpan.Zero; var verification = TimeSpan.Zero; var brep = TimeSpan.Zero;
- foreach (var block in Blocks(source, "SculptState"))
+ foreach (var block in Blocks(model, "SculptState"))
{
var operationClock = Stopwatch.StartNew();
var inputName = ScalarText(block.Body, "Input");
if (inputName is null || !states.TryGetValue(inputName, out var input)) { diagnostics.Add(new("sculpt-predecessor-unresolved", $"SculptState '{block.Name}' must name one previously accepted Input state.")); continue; }
- var operationBlock = Blocks(block.Body, "OffsetRegion").SingleOrDefault();
- var replaceBlock = Blocks(block.Body, "ReplaceRegion").SingleOrDefault();
- var blendBlock = Blocks(block.Body, "BlendBoundary").SingleOrDefault();
- var holeBlock = Blocks(block.Body, "HoleFeature").SingleOrDefault();
- var addChainBlock = Blocks(block.Body, "AddSectionChain").SingleOrDefault();
- var removeChainBlock = Blocks(block.Body, "RemoveSectionChain").SingleOrDefault();
+ var operationBlock = Single(block.Body, "OffsetRegion", diagnostics);
+ var replaceBlock = Single(block.Body, "ReplaceRegion", diagnostics);
+ var blendBlock = Single(block.Body, "BlendBoundary", diagnostics);
+ var holeBlock = Single(block.Body, "HoleFeature", diagnostics);
+ var addChainBlock = Single(block.Body, "AddSectionChain", diagnostics);
+ var removeChainBlock = Single(block.Body, "RemoveSectionChain", diagnostics);
if (new[] { operationBlock, replaceBlock, blendBlock, holeBlock, addChainBlock, removeChainBlock }.Count(x => x is not null) != 1) { diagnostics.Add(new("sculpt-operation-unsupported", $"SculptState '{block.Name}' requires exactly one OffsetRegion, ReplaceRegion, BlendBoundary, HoleFeature, AddSectionChain, or RemoveSectionChain operation.")); continue; }
if (addChainBlock is not null)
{
@@ -147,7 +158,9 @@ public static class SculptingAuthoring
if (blendBlock is not null)
{
var between = List(blendBlock.Body, "Between"); var regionName = ScalarText(blendBlock.Body, "Region") ?? string.Empty;
- var preferredText = ScalarText(blendBlock.Body, "Preferred") ?? ScalarText(blendBlock.Body, "Continuity") ?? "G2";
+ var preferredInput = ScalarText(blendBlock.Body, "Preferred"); var legacyContinuity = ScalarText(blendBlock.Body, "Continuity");
+ if (preferredInput is not null && legacyContinuity is not null) blendBlock.Invalid("Continuity", "Use preferred or the compatibility continuity field, not both.");
+ var preferredText = preferredInput ?? legacyContinuity ?? "G2";
var minimumText = ScalarText(blendBlock.Body, "Minimum") ?? preferredText;
var size = Vector(blendBlock.Body, "RegionSize", 2, diagnostics); var height = Length(blendBlock.Body, "Height", diagnostics);
var blendEnvelope = Vector(blendBlock.Body, "InfluenceEnvelope", 6, diagnostics);
@@ -186,17 +199,18 @@ public static class SculptingAuthoring
if (!result.IsSuccess || result.OutputState is null) diagnostics.AddRange(result.Diagnostics);
else if (!states.TryAdd(block.Name, result.OutputState)) diagnostics.Add(new("sculpt-state-duplicate", $"State '{block.Name}' is declared more than once."));
}
- var outputName = ScalarText(source, "Output");
+ var outputName = ScalarText(model, "Output");
BodyState? output = null;
if (outputName is null || !states.TryGetValue(outputName, out output)) diagnostics.Add(new("sculpt-output-unresolved", "Output must name one accepted BodyState or SculptState."));
+ diagnostics.AddRange(model.CompleteTree().Select(Located));
total.Stop();
- return new(diagnostics.Count == 0 && output is not null, model.Groups["name"].Value, output, states, diagnostics,
+ return new(diagnostics.Count == 0 && output is not null, model.Name, output, states, diagnostics,
new(baseClock.Elapsed.TotalMilliseconds, opConstruction.TotalMilliseconds, verification.TotalMilliseconds, brep.TotalMilliseconds, 0d));
SculptingCompileResult Fail(string name, string code, string message) => new(false, name, null, states, [new(code, message)], new(0, 0, 0, 0, 0));
}
- private static IReadOnlyList<HousingHole> ParseHoles(string body, List<SculptDiagnostic> diagnostics)
+ private static IReadOnlyList<HousingHole> ParseHoles(Block body, List<SculptDiagnostic> diagnostics)
{
var result = new List<HousingHole>();
foreach (var hole in Blocks(body, "Hole"))
@@ -237,46 +251,38 @@ public static class SculptingAuthoring
start, end, continuity);
}
- private static IReadOnlyList<Block> Blocks(string source, string keyword)
+ private static IReadOnlyList<Block> Blocks(Block scope, string kind) => scope.Children(kind);
+ private static Block? Single(Block scope, string kind, List<SculptDiagnostic> diagnostics)
{
- var result = new List<Block>(); var regex = new Regex($@"\b{Regex.Escape(keyword)}(?:\s+(?<name>[A-Za-z_]\w*))?\s*\{{", RegexOptions.CultureInvariant);
- for (var start = 0; start < source.Length;)
- {
- var match = regex.Match(source, start); if (!match.Success) break; var open = source.IndexOf('{', match.Index + match.Length - 1); var close = MatchingBrace(source, open);
- if (close < 0) break; result.Add(new(match.Groups["name"].Success ? match.Groups["name"].Value : keyword, source[(open + 1)..close])); start = close + 1;
- }
- return result;
+ var found = scope.Children(kind);
+ if (found.Count > 1) diagnostics.Add(new("sculpt-operation-cardinality", $"Only one {kind} is allowed per state.", scope.Name));
+ return found.Count == 1 ? found[0] : null;
}
- private static int MatchingBrace(string source, int open) { var depth = 0; var quoted = false; for (var i = open; i < source.Length; i++) { if (source[i] == '"' && (i == 0 || source[i - 1] != '\\')) quoted = !quoted; if (quoted) continue; if (source[i] == '{') depth++; else if (source[i] == '}' && --depth == 0) return i; } return -1; }
- // Alias only the first character of an owned field; authored values,
- // semantic paths and enum symbols remain case-sensitive.
- private static string FieldSpelling(string field) =>
- $"(?:{Regex.Escape(field)}|{Regex.Escape(char.ToLowerInvariant(field[0]) + field[1..])})";
- private static string? ScalarText(string body, string field) { var m = Regex.Match(body, $@"(?m)^\s*{FieldSpelling(field)}\s*:\s*(?<v>[A-Za-z_]\w*)\s*$", RegexOptions.CultureInvariant); return m.Success ? m.Groups["v"].Value : null; }
- private static int? Integer(string body, string field)
+ private static SculptDiagnostic Located(FirmamentV2ValidationDiagnostic d) => new(d.Code, d.Message, d.Target)
+ { SourceFile = d.SourceFile, SourceSpan = d.SourceSpan is {} span ? new(span.Start,span.Length) { LocationNote=d.LocationNote } : null };
+ private static string? ScalarText(Block body, string field) => body.Word(field);
+ private static int? Integer(Block body, string field)
{
- var match = Regex.Match(body, $@"(?m)^\s*{FieldSpelling(field)}\s*:\s*(?<v>\d+)\s*$", RegexOptions.CultureInvariant);
- return match.Success && int.TryParse(match.Groups["v"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out var value) ? value : null;
+ var value=body.Take(field); if(value is null)return null;
+ if(FirmamentSyntaxValues.TryMeasure(value,"",out var number) && double.IsFinite(number) && number>=0 && number<=int.MaxValue && number==Math.Truncate(number)) return (int)number;
+ body.Invalid(field); return null;
}
- private static double? Length(string body, string field, List<SculptDiagnostic> diagnostics)
+ private static double? Length(Block body, string field, List<SculptDiagnostic> diagnostics)
{
- var m = Regex.Match(body, $@"(?m)^\s*{FieldSpelling(field)}\s*:\s*(?<v>[-+]?\d+(?:\.\d+)?)mm\s*$", RegexOptions.CultureInvariant);
- if (m.Success) return double.Parse(m.Groups["v"].Value, CultureInfo.InvariantCulture); diagnostics.Add(new("sculpt-field-invalid", $"Field '{field}' requires a millimetre length.")); return null;
+ if(FirmamentSyntaxValues.TryMeasure(body.Take(field),"mm",out var value) && double.IsFinite(value))return value;
+ body.Invalid(field); diagnostics.Add(new("sculpt-field-invalid", $"Field '{field}' requires a millimetre length."));return null;
}
- private static double[]? Vector(string body, string field, int count, List<SculptDiagnostic> diagnostics)
+ private static double[]? Vector(Block body,string field,int count,List<SculptDiagnostic> diagnostics)
{
- var m = Regex.Match(body, $@"(?m)^\s*{FieldSpelling(field)}\s*:\s*\[(?<v>[^\]]+)\]\s*$", RegexOptions.CultureInvariant);
- if (m.Success)
- {
- var values = m.Groups["v"].Value.Split(',').Select(x => Regex.Match(x.Trim(), @"^(?<v>[-+]?\d+(?:\.\d+)?)mm$", RegexOptions.CultureInvariant)).ToArray();
- if (values.Length == count && values.All(x => x.Success)) return values.Select(x => double.Parse(x.Groups["v"].Value, CultureInfo.InvariantCulture)).ToArray();
- }
- diagnostics.Add(new("sculpt-field-invalid", $"Field '{field}' requires {count} comma-separated millimetre lengths.")); return null;
+ if(FirmamentSyntaxValues.Vector(body.Take(field),"mm",out var values) && values.Length==count && values.All(double.IsFinite))return values;
+ body.Invalid(field);diagnostics.Add(new("sculpt-field-invalid",$"Field '{field}' requires {count} millimetre lengths."));return null;
}
- private static IReadOnlyList<string> List(string body, string field)
+ private static IReadOnlyList<string> List(Block body,string field)
{
- var m = Regex.Match(body, $@"(?m)^\s*{FieldSpelling(field)}\s*:\s*\[(?<v>[^\]]*)\]\s*$", RegexOptions.CultureInvariant);
- return m.Success ? m.Groups["v"].Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) : [];
+ var value=body.Take(field); if(value is null)return [];
+ if(value is SequenceSyntax { Kind:SequenceKind.List } list && list.Items.All(i=>i.Name is null && i.Default is null && FirmamentSyntaxValues.Reference(i.Value) is not null))
+ return list.Items.Select(i=>FirmamentSyntaxValues.Reference(i.Value)!).ToArray();
+ body.Invalid(field);return [];
}
private static PreservationContract Preservation(string entity) => new(entity, entity == SculptedHousingFactory.MountingHolePattern ? PreservationMode.PatternPlacementAndDiameter : PreservationMode.ExactGeometry);
private static IReadOnlyList<SculptRequirement> ParseRequirements(IReadOnlyList<string> values, List<SculptDiagnostic> diagnostics)
@@ -286,36 +292,33 @@ public static class SculptingAuthoring
if (Enum.TryParse<SculptRequirement>(value, out var requirement)) parsed.Add(requirement); else diagnostics.Add(new("sculpt-requirement-unsupported", $"Requirement '{value}' is not supported."));
return parsed;
}
- private static double[]? NumberVector(string body, string field, int count, List<SculptDiagnostic> diagnostics)
+ private static double[]? NumberVector(Block body, string field, int count, List<SculptDiagnostic> diagnostics)
{
var values = NumberVectorAny(body, field, diagnostics); if (values is not null && values.Length == count) return values;
if (values is not null) diagnostics.Add(new("sculpt-field-invalid", $"Field '{field}' requires {count} dimensionless numbers.")); return null;
}
- private static double[]? NumberVectorAny(string body, string field, List<SculptDiagnostic> diagnostics)
+ private static double[]? NumberVectorAny(Block body,string field,List<SculptDiagnostic> diagnostics)
{
- var match = Regex.Match(body, $@"(?m)^\s*{FieldSpelling(field)}\s*:\s*\[(?<v>[^\]]+)\]\s*$", RegexOptions.CultureInvariant);
- if (!match.Success) { diagnostics.Add(new("sculpt-field-invalid", $"Field '{field}' requires a dimensionless number list.")); return null; }
- var tokens = match.Groups["v"].Value.Split(',', StringSplitOptions.TrimEntries); var values = new double[tokens.Length];
- for (var i = 0; i < tokens.Length; i++) if (!double.TryParse(tokens[i], NumberStyles.Float, CultureInfo.InvariantCulture, out values[i]))
- { diagnostics.Add(new("sculpt-field-invalid", $"Field '{field}' contains invalid number '{tokens[i]}'.")); return null; }
- return values;
+ if(FirmamentSyntaxValues.Vector(body.Take(field),"",out var values) && values.All(double.IsFinite))return values;
+ body.Invalid(field);diagnostics.Add(new("sculpt-field-invalid",$"Field '{field}' requires a dimensionless number list."));return null;
}
- private static IReadOnlyList<IReadOnlyList<Point3D>>? ControlRows(string body, List<SculptDiagnostic> diagnostics)
+ private static IReadOnlyList<IReadOnlyList<Point3D>>? ControlRows(Block body,List<SculptDiagnostic> diagnostics)
{
- var matches = Regex.Matches(body, @"(?m)^\s*ControlRow\s*:\s*\[(?<v>.*)\]\s*$", RegexOptions.CultureInvariant);
- var rows = new List<IReadOnlyList<Point3D>>();
- foreach (Match match in matches)
+ var rows=new List<IReadOnlyList<Point3D>>();
+ foreach(var field in body.TakeAll("ControlRow"))
{
- var points = new List<Point3D>();
- foreach (Match point in Regex.Matches(match.Groups["v"].Value, @"\[\s*(?<x>[-+]?\d+(?:\.\d+)?)mm\s*,\s*(?<y>[-+]?\d+(?:\.\d+)?)mm\s*,\s*(?<z>[-+]?\d+(?:\.\d+)?)mm\s*\]", RegexOptions.CultureInvariant))
- points.Add(new(double.Parse(point.Groups["x"].Value, CultureInfo.InvariantCulture), double.Parse(point.Groups["y"].Value, CultureInfo.InvariantCulture), double.Parse(point.Groups["z"].Value, CultureInfo.InvariantCulture)));
- if (points.Count == 0) { diagnostics.Add(new("surf-control-row-invalid", "Each ControlRow requires one or more [xmm, ymm, zmm] points.")); return null; }
+ if(field.Value is not SequenceSyntax {Kind:SequenceKind.List} row){body.Invalid("ControlRow");continue;}
+ var points=new List<Point3D>();
+ foreach(var item in row.Items)
+ if(item.Name is null && item.Default is null && FirmamentSyntaxValues.Vector(item.Value,"mm",out var p) && p.Length==3 && p.All(double.IsFinite))points.Add(new(p[0],p[1],p[2]));
+ else body.Invalid("ControlRow");
+ if(points.Count==0)body.Invalid("ControlRow");
rows.Add(points);
}
- if (rows.Count == 0) { diagnostics.Add(new("surf-control-net-required", "A non-rational SurfacePatch requires explicit ControlRow entries.")); return null; }
+ if(rows.Count==0){diagnostics.Add(new("surf-control-net-required","A non-rational SurfacePatch requires explicit controlRow entries."));return null;}
return rows;
}
- private static IReadOnlyList<PatchBoundaryCorrespondence>? ParseBoundaries(string body, List<SculptDiagnostic> diagnostics)
+ private static IReadOnlyList<PatchBoundaryCorrespondence>? ParseBoundaries(Block body, List<SculptDiagnostic> diagnostics)
{
var result = new List<PatchBoundaryCorrespondence>();
foreach (var block in Blocks(body, "Boundary"))
@@ -341,5 +344,4 @@ public static class SculptingAuthoring
}
return (multiplicities, values);
}
- private sealed record Block(string Name, string Body);
}
diff --git a/Aetheris.PlasticShell.Tests/PlasticShellAstAdmissionTests.cs b/Aetheris.PlasticShell.Tests/PlasticShellAstAdmissionTests.cs
new file mode 100644
index 00000000..0ef0065d
--- /dev/null
+++ b/Aetheris.PlasticShell.Tests/PlasticShellAstAdmissionTests.cs
@@ -0,0 +1,23 @@
+using Xunit;
+namespace Aetheris.PlasticShell.Tests;
+public sealed class PlasticShellAstAdmissionTests
+{
+ [Theory]
+ [InlineData("heigth: 3mm")]
+ [InlineData("Fillet Lost { radius: 1mm }")]
+ [InlineData("height: 1mm")]
+ public void UnconsumedOrDuplicateIntentCannotBuild(string intent)
+ {
+ var source=Source();var at=source.IndexOf("PlasticShell ",StringComparison.Ordinal);at=source.IndexOf('{',at)+1;
+ var result=PlasticShellFirmament.Compile(source.Insert(at,intent+";"),"shell.firmament");
+ Assert.False(result.IsSuccess);Assert.Null(result.State);Assert.Contains(result.Diagnostics,d=>d.SourceSpan is not null && d.SourceFile=="shell.firmament");
+ }
+ [Fact]
+ public void ModernAndHistoricalFieldsRetainTheSameManufacturedGeometry()
+ {
+ var source=Source();var a=PlasticShellFirmament.Compile(source);var b=PlasticShellFirmament.Compile(source.Replace("BottomRadius:","bottomRadius:",StringComparison.Ordinal));
+ Assert.True(a.IsSuccess);Assert.True(b.IsSuccess,string.Join(";",b.Diagnostics));
+ Assert.Equal(PlasticShellStepExporter.Export(a.State!,a.ModelName).Step,PlasticShellStepExporter.Export(b.State!,b.ModelName).Step);
+ }
+ private static string Source(){var d=new DirectoryInfo(AppContext.BaseDirectory);while(d is not null&&!File.Exists(Path.Combine(d.FullName,"Aetheris.slnx")))d=d.Parent;return File.ReadAllText(Path.Combine(d!.FullName,"fixtures","Canonical","PlasticShell","plastic-shell-basic.firmament"));}
+}
diff --git a/Aetheris.PlasticShell/Aetheris.PlasticShell.csproj b/Aetheris.PlasticShell/Aetheris.PlasticShell.csproj
index 2ae24a82..29d7f57a 100644
--- a/Aetheris.PlasticShell/Aetheris.PlasticShell.csproj
+++ b/Aetheris.PlasticShell/Aetheris.PlasticShell.csproj
@@ -8,6 +8,7 @@
<ItemGroup>
<ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" />
<ProjectReference Include="..\Aetheris.Modules\Aetheris.Modules.csproj" />
+ <ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />
<ProjectReference Include="..\Aetheris.Surfacing\Aetheris.Surfacing.csproj" />
</ItemGroup>
</Project>
diff --git a/Aetheris.PlasticShell/PlasticShellCompiler.cs b/Aetheris.PlasticShell/PlasticShellCompiler.cs
index 6cb13519..1e04f296 100644
--- a/Aetheris.PlasticShell/PlasticShellCompiler.cs
+++ b/Aetheris.PlasticShell/PlasticShellCompiler.cs
@@ -225,6 +225,8 @@ public static class PlasticShellCompiler
var ring = Enumerable.Range(0, s.Length).Select(i => Edge(s[i], s[(i + 1) % s.Length], "perimeter")).ToArray();
var chord = s.Where(v => v.StandoffId != fanRoot.StandoffId).Select(v => Edge(fanRoot, v, "fan")).ToArray();
var candidates = new[] { Candidate("perimeter-network", ring), Candidate("gate-oriented-fan", chord) };
+ foreach(var unknown in request.KeepOuts.Except(candidates.Select(c=>c.CandidateId),StringComparer.Ordinal))
+ diagnostics.Add(new(PlasticDiagnosticCodes.SourceInvalid,PlasticDiagnosticSeverity.Error,$"Unknown AutoRib keepOut '{unknown}'. Use an admitted candidate network identity.",request.RequestId));
var engineCandidates = candidates.Select((candidate, index) => new JudgmentCandidate<IReadOnlyDictionary<string, RibCandidateEvidence>>(
candidate.CandidateId, context => context[candidate.CandidateId].Eligible, context => context[candidate.CandidateId].Metrics.Utility,
context => string.Join("; ", context[candidate.CandidateId].RejectionReasons), index)).ToArray();
diff --git a/Aetheris.PlasticShell/PlasticShellFirmament.cs b/Aetheris.PlasticShell/PlasticShellFirmament.cs
index d5ae8f27..c23ba6a2 100644
--- a/Aetheris.PlasticShell/PlasticShellFirmament.cs
+++ b/Aetheris.PlasticShell/PlasticShellFirmament.cs
@@ -1,5 +1,7 @@
using System.Globalization;
-using System.Text.RegularExpressions;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Block=Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxScope;
using Aetheris.Kernel.Core.Math;
namespace Aetheris.PlasticShell;
@@ -7,22 +9,26 @@ namespace Aetheris.PlasticShell;
/// <summary>Module-owned manufacturing-first Firmament surface. It lowers to PlasticShellIr before any BRep operation.</summary>
public static class PlasticShellFirmament
{
- private static readonly RegexOptions Rx = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase;
-
- public static bool LooksLikePlasticShell(string? source) => source is not null && Regex.IsMatch(Strip(source), @"\bPlasticShell\s+[A-Za-z_]\w*\s*\{", Rx);
+ public static bool LooksLikePlasticShell(string? source) => source is not null && source.Contains("PlasticShell",StringComparison.Ordinal)
+ && FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d=>d.Type.Name.Text=="PlasticShell");
public static PlasticShellCompileResult CompileFile(string path) => Compile(File.ReadAllText(path), path);
public static PlasticShellCompileResult Compile(string source, string sourcePath = "authored.firmament")
{
ArgumentNullException.ThrowIfNull(source);
- var clean = Strip(source); var diagnostics = new List<PlasticDiagnostic>();
- var model = Regex.Match(clean, @"\bModel\s+(?<name>[A-Za-z_]\w*)\s*\{", Rx);
- if (!model.Success) return Fail("<unknown>", "PlasticShell source requires 'Model Name { ... }'.");
- var modelName = model.Groups["name"].Value;
- if (!Regex.IsMatch(clean, @"\bUnits\s*:\s*mm\b", Rx)) diagnostics.Add(new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, "PlasticShell X0 requires Units: mm."));
- var blocks = Blocks(clean, "PlasticShell").ToArray();
- if (blocks.Length != 1) diagnostics.Add(new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, "A bounded X0 source requires exactly one PlasticShell block."));
- if (diagnostics.Count > 0 || blocks.Length != 1) return new(false, modelName, null, null, diagnostics);
+ var diagnostics = new List<PlasticDiagnostic>();
+ var binding=new FirmamentDomainBinding(source,sourcePath,"PlasticShell",new HashSet<string>(StringComparer.Ordinal));
+ diagnostics.AddRange(binding.Diagnostics.Select(Located));
+ var models=binding.Document.Statements.OfType<DeclarationSyntax>().Where(d=>d.Type.Name.Text=="Model").ToArray();
+ if(models.Length!=1)return Fail("<unknown>","PlasticShell requires exactly one Model.");
+ var model=new Block(models[0],binding.Source,sourcePath,binding.Nominal,binding.OriginalSpan);var modelName=model.Name;
+ foreach(var statement in binding.Document.Statements.Where(s=>!ReferenceEquals(s,models[0])))
+ if(statement is not DeclarationSyntax data || !binding.OwnsData(data))diagnostics.Add(new(PlasticDiagnosticCodes.SourceInvalid,PlasticDiagnosticSeverity.Error,"Unsupported statement outside PlasticShell Model."));
+ foreach(var data in models[0].Body?.Statements.OfType<DeclarationSyntax>().Where(binding.OwnsData)??[])model.Consume(data);
+ if(model.Word("Units")!="mm")diagnostics.Add(new(PlasticDiagnosticCodes.SourceInvalid,PlasticDiagnosticSeverity.Error,"PlasticShell requires units: mm."));
+ var blocks=model.Children("PlasticShell").ToArray();
+ if(blocks.Length!=1)diagnostics.Add(new(PlasticDiagnosticCodes.SourceInvalid,PlasticDiagnosticSeverity.Error,"Exactly one PlasticShell is required."));
+ if(diagnostics.Count>0)return new(false,modelName,null,null,diagnostics);
var shell = blocks[0];
try
{
@@ -32,13 +38,13 @@ public static class PlasticShellFirmament
var material = Scalar(shell.Body, "Material") ?? "UnspecifiedPlastic";
var tooling = Direction(shell.Body, "ToolingDirection", diagnostics);
var minimumDraft = Angle(shell.Body, "MinimumDraftAngle", diagnostics);
- var wallBlock = Blocks(shell.Body, "WallPolicy").SingleOrDefault();
+ var wallBlock = Single(shell,"WallPolicy");
if (wallBlock is null) diagnostics.Add(new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, "PlasticShell requires WallPolicy."));
var nominal = wallBlock is null ? null : Length(wallBlock.Body, "NominalThickness", diagnostics);
var minimum = wallBlock is null ? null : Length(wallBlock.Body, "MinimumThickness", diagnostics);
var maximum = wallBlock is null ? null : Length(wallBlock.Body, "MaximumThickness", diagnostics);
var tolerance = wallBlock is null ? null : Length(wallBlock.Body, "ThicknessTolerance", diagnostics, allowZero: true);
- var partingBlock = Blocks(shell.Body, "PartingPlane").SingleOrDefault();
+ var partingBlock = Single(shell,"PartingPlane");
if (partingBlock is null) diagnostics.Add(new(PlasticDiagnosticCodes.InvalidParting, PlasticDiagnosticSeverity.Error, "PlasticShell X0 requires an explicit PartingPlane."));
var partingOrigin = partingBlock is null ? null : Point(partingBlock.Body, "Origin", diagnostics);
var partingNormal = partingBlock is null ? null : Direction(partingBlock.Body, "Normal", diagnostics);
@@ -46,10 +52,11 @@ public static class PlasticShellFirmament
var gates = Blocks(shell.Body, "Gate").Select(b => ParseGate(b, diagnostics)).Where(x => x is not null).Select(x => x!).ToArray();
var standoffs = Blocks(shell.Body, "Standoff").Select(b => ParseStandoff(b, diagnostics)).Where(x => x is not null).Select(x => x!).ToArray();
var ejectors = Blocks(shell.Body, "EjectorPin").Select(b => ParseEjector(b, diagnostics)).Where(x => x is not null).Select(x => x!).ToArray();
- var autoBlock = Blocks(shell.Body, "AutoRib").SingleOrDefault();
+ var autoBlock = Single(shell,"AutoRib");
var autoRib = autoBlock is null ? null : ParseAutoRib(autoBlock, diagnostics);
if (gates.Length == 0) diagnostics.Add(new(PlasticDiagnosticCodes.InvalidGate, PlasticDiagnosticSeverity.Error, "PlasticShell X0 requires at least one explicit Gate."));
if (ejectors.Length == 0) diagnostics.Add(new(PlasticDiagnosticCodes.EjectorNotCoreAccessible, PlasticDiagnosticSeverity.Error, "PlasticShell X0 policy requires at least one explicit EjectorPin."));
+ diagnostics.AddRange(model.CompleteTree().Select(Located));
if (diagnostics.Any(d => d.Severity == PlasticDiagnosticSeverity.Error) || bottomRadius is null || topRadius is null || height is null || tooling is null || minimumDraft is null || nominal is null || minimum is null || maximum is null || tolerance is null || partingOrigin is null || partingNormal is null)
return new(false, modelName, null, null, diagnostics);
var exteriorToken = preserved.FirstOrDefault(p => p is "ExteriorDesignSurface" or "ExteriorCrown");
@@ -73,7 +80,7 @@ public static class PlasticShellFirmament
{
var position = Point(b.Body, "Position", d); var target = Scalar(b.Body, "Target") ?? "TopAnnularRim"; var size = OptionalLength(b.Body, "Size", d);
var kindText = Scalar(b.Body, "Kind") ?? "Point";
- if (!Enum.TryParse<GateKind>(kindText, true, out var kind)) { d.Add(new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, $"Unknown Gate Kind '{kindText}'.", b.Name)); return null; }
+ if ((!Enum.TryParse<GateKind>(kindText, true, out var kind)||!Enum.IsDefined(kind))) { d.Add(new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, $"Unknown Gate Kind '{kindText}'.", b.Name)); return null; }
return position is null ? null : new(b.Name, position.Value, target, kind, size);
}
@@ -81,7 +88,7 @@ public static class PlasticShellFirmament
{
var p = Point(b.Body, "Position", d); var h = Length(b.Body, "Height", d); var od = Length(b.Body, "OuterDiameter", d); var hole = OptionalLength(b.Body, "HoleDiameter", d);
var intentText = Scalar(b.Body, "SupportIntent") ?? "Pcb";
- if (!Enum.TryParse<StandoffSupportIntent>(intentText, true, out var intent)) { d.Add(new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, $"Unknown Standoff SupportIntent '{intentText}'.", b.Name)); return null; }
+ if ((!Enum.TryParse<StandoffSupportIntent>(intentText, true, out var intent)||!Enum.IsDefined(intent))) { d.Add(new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, $"Unknown Standoff SupportIntent '{intentText}'.", b.Name)); return null; }
return p is null || h is null || od is null ? null : new(b.Name, p.Value, h.Value, od.Value, hole, intent);
}
@@ -94,51 +101,45 @@ public static class PlasticShellFirmament
private static PlasticAutoRibRequest? ParseAutoRib(Block b, ICollection<PlasticDiagnostic> d)
{
var supports = List(b.Body, "Support"); var gate = Scalar(b.Body, "Gate") ?? string.Empty; var keepouts = List(b.Body, "KeepOut");
- var policyBlock = Blocks(b.Body, "RibPolicy").SingleOrDefault();
+ var policyBlock = Single(b,"RibPolicy");
if (policyBlock is null) { d.Add(new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, "AutoRib requires RibPolicy.", b.Name)); return null; }
var ratio = Number(policyBlock.Body, "ThicknessRatio", d); var min = Length(policyBlock.Body, "MinimumHeight", d); var max = Length(policyBlock.Body, "MaximumHeight", d); var spacing = Length(policyBlock.Body, "MinimumSpacing", d); var draft = Angle(policyBlock.Body, "DraftAngle", d); var blend = Length(policyBlock.Body, "BaseBlendRadius", d, allowZero: true);
return ratio is null || min is null || max is null || spacing is null || draft is null || blend is null ? null : new(b.Name, supports, gate, keepouts, new(ratio.Value, min.Value, max.Value, spacing.Value, draft.Value, blend.Value));
}
- private static string Strip(string source) => Regex.Replace(source, @"//.*?$|#.*?$", string.Empty, RegexOptions.Multiline);
- private static string? Scalar(string body, string key) => Regex.Match(body, $@"\b{Regex.Escape(key)}\s*:\s*(?<v>[A-Za-z_][\w.:-]*)", Rx) is { Success: true } m ? m.Groups["v"].Value : null;
- private static double? Number(string body, string key, ICollection<PlasticDiagnostic> d) => Quantity(body, key, null, d, false);
- private static double? Length(string body, string key, ICollection<PlasticDiagnostic> d, bool allowZero = false) => Quantity(body, key, "mm", d, allowZero);
- private static double? Angle(string body, string key, ICollection<PlasticDiagnostic> d) => Quantity(body, key, "deg", d, true);
- private static double? OptionalLength(string body, string key, ICollection<PlasticDiagnostic> d) => Regex.IsMatch(body, $@"\b{Regex.Escape(key)}\s*:", Rx) ? Length(body, key, d) : null;
- private static double? Quantity(string body, string key, string? unit, ICollection<PlasticDiagnostic> d, bool allowZero)
- {
- var suffix = unit is null ? string.Empty : $@"\s*{unit}"; var m = Regex.Match(body, $@"\b{Regex.Escape(key)}\s*:\s*(?<v>[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)" + suffix + @"\s*;?", Rx);
- if (!m.Success || !double.TryParse(m.Groups["v"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) || !double.IsFinite(v) || (allowZero ? v < 0 : v <= 0)) { d.Add(new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, $"{key} requires a finite {(allowZero ? "non-negative" : "positive")} value{(unit is null ? string.Empty : " in " + unit)}.")); return null; }
- return v;
- }
- private static Point3D? Point(string body, string key, ICollection<PlasticDiagnostic> d) { var v = Vector(body, key, d); return v is null ? null : new(v[0], v[1], v[2]); }
- private static Direction3D? Direction(string body, string key, ICollection<PlasticDiagnostic> d)
+ private static PlasticDiagnostic Located(FirmamentV2ValidationDiagnostic d)=>new(d.Code,PlasticDiagnosticSeverity.Error,d.Message,d.Target){SourceFile=d.SourceFile,SourceSpan=d.SourceSpan is {} span?new(span.Start,span.Length){LocationNote=d.LocationNote}:null};
+ public static IReadOnlyList<Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic> KernelDiagnostics(PlasticShellCompileResult result)=>result.Diagnostics.Select(d=>new Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic(
+ Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,d.Severity switch {PlasticDiagnosticSeverity.Error=>Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,PlasticDiagnosticSeverity.Warning=>Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Warning,_=>Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Info},
+ d.Code+": "+d.Message,"Firmament.PlasticShell"){OriginalSourceSpan=d.SourceSpan}).ToArray();
+ private static Block? Single(Block owner,string kind){var children=owner.Children(kind);if(children.Count>1)owner.Invalid(kind,"Exactly one declaration is allowed.");return children.Count==1?children[0]:null;}
+ private static IEnumerable<Block> Blocks(Block body,string kind)=>body.Children(kind);
+ private static string? Scalar(Block body,string key)=>body.Word(key);
+ private static double? Number(Block body,string key,ICollection<PlasticDiagnostic> d)=>Quantity(body,key,"",d,false);
+ private static double? Length(Block body,string key,ICollection<PlasticDiagnostic> d,bool allowZero=false)=>Quantity(body,key,"mm",d,allowZero);
+ private static double? Angle(Block body,string key,ICollection<PlasticDiagnostic> d)=>Quantity(body,key,"deg",d,true);
+ private static double? OptionalLength(Block body,string key,ICollection<PlasticDiagnostic> d)=>body.Take(key) is null?null:Length(body,key,d);
+ private static double? Quantity(Block body,string key,string unit,ICollection<PlasticDiagnostic> d,bool allowZero)
{
- var v = Vector(body, key, d); if (v is null) return null;
- try { return Direction3D.Create(new Vector3D(v[0], v[1], v[2])); } catch (ArgumentException) { d.Add(new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, $"{key} must be a non-zero direction.")); return null; }
+ if(FirmamentSyntaxValues.TryMeasure(body.Take(key),unit,out var value) && double.IsFinite(value) && (allowZero?value>=0:value>0))return value;
+ body.Invalid(key,$"Expected a finite {(allowZero?"nonnegative":"positive")} {unit} value.");return null;
}
- private static double[]? Vector(string body, string key, ICollection<PlasticDiagnostic> d)
+ private static Point3D? Point(Block body,string key,ICollection<PlasticDiagnostic> d){var v=Vector(body,key,"mm");return v is null?null:new(v[0],v[1],v[2]);}
+ private static Direction3D? Direction(Block body,string key,ICollection<PlasticDiagnostic> d)
{
- var m = Regex.Match(body, $@"\b{Regex.Escape(key)}\s*:\s*\[(?<v>[^\]]+)\]", Rx); if (!m.Success) { d.Add(new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, $"{key} requires [x, y, z].")); return null; }
- var parts = m.Groups["v"].Value.Split(',').Select(x => double.TryParse(x.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? (double?)v : null).ToArray();
- if (parts.Length != 3 || parts.Any(x => x is null || !double.IsFinite(x.Value))) { d.Add(new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, $"{key} requires three finite numbers.")); return null; }
- return parts.Select(x => x!.Value).ToArray();
+ var v=Vector(body,key,"");if(v is null)return null;
+ try{return Direction3D.Create(new Vector3D(v[0],v[1],v[2]));}catch(ArgumentException){body.Invalid(key,"Direction must be nonzero.");return null;}
}
- private static IReadOnlyList<string> List(string body, string key)
+ private static double[]? Vector(Block body,string key,string unit)
{
- var m = Regex.Match(body, $@"\b{Regex.Escape(key)}\s*:\s*\[(?<v>[^\]]*)\]", Rx); return !m.Success ? [] : m.Groups["v"].Value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
+ if(FirmamentSyntaxValues.Vector(body.Take(key),unit,out var values,unit) && values.Length==3 && values.All(double.IsFinite))return values;
+ body.Invalid(key,"Expected three finite components.");return null;
}
- private static IEnumerable<Block> Blocks(string source, string keyword)
+ private static IReadOnlyList<string> List(Block body,string key)
{
- var matches = Regex.Matches(source, $@"\b{Regex.Escape(keyword)}(?:\s+(?<name>[A-Za-z_]\w*))?\s*\{{", Rx);
- foreach (Match match in matches)
- {
- var depth = 1; var i = match.Index + match.Length;
- for (; i < source.Length && depth > 0; i++) { if (source[i] == '{') depth++; else if (source[i] == '}') depth--; }
- if (depth == 0) yield return new(match.Groups["name"].Success ? match.Groups["name"].Value : keyword, source[(match.Index + match.Length)..(i - 1)]);
- }
+ var expression=body.Take(key);if(expression is null)return [];
+ string? Identity(ExpressionSyntax value)=>FirmamentSyntaxValues.Reference(value) ?? (key=="KeepOut" && value is BinarySyntax {Operator:BinaryOperator.Subtract} legacy && Identity(legacy.Left) is {} left && Identity(legacy.Right) is {} right?left+"-"+right:null);
+ if(expression is SequenceSyntax {Kind:SequenceKind.List} list && list.Items.All(i=>i.Name is null && i.Default is null && Identity(i.Value) is not null))return list.Items.Select(i=>Identity(i.Value)!).ToArray();
+ body.Invalid(key);return [];
}
- private static PlasticShellCompileResult Fail(string model, string message) => new(false, model, null, null, [new(PlasticDiagnosticCodes.SourceInvalid, PlasticDiagnosticSeverity.Error, message)]);
- private sealed record Block(string Name, string Body);
+ private static PlasticShellCompileResult Fail(string model,string message)=>new(false,model,null,null,[new(PlasticDiagnosticCodes.SourceInvalid,PlasticDiagnosticSeverity.Error,message)]);
}
diff --git a/Aetheris.PlasticShell/PlasticShellIr.cs b/Aetheris.PlasticShell/PlasticShellIr.cs
index 72471a89..6b8686c8 100644
--- a/Aetheris.PlasticShell/PlasticShellIr.cs
+++ b/Aetheris.PlasticShell/PlasticShellIr.cs
@@ -35,7 +35,11 @@ public static class PlasticDiagnosticCodes
public const string EjectorRibCollision = "plastic-shell-ejector-rib-collision";
}
-public sealed record PlasticDiagnostic(string Code, PlasticDiagnosticSeverity Severity, string Message, string? Entity = null);
+public sealed record PlasticDiagnostic(string Code, PlasticDiagnosticSeverity Severity, string Message, string? Entity = null)
+{
+ public string? SourceFile { get; init; }
+ public Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSourceSpan? SourceSpan { get; init; }
+}
public sealed record PlasticWallPolicy(double NominalThickness, double MinimumThickness, double MaximumThickness, double ThicknessTolerance);
public sealed record PlasticPartingPlane(string StableId, Point3D Origin, Direction3D Normal);
public sealed record PlasticGate(string GateId, Point3D Location, string TargetRegion, GateKind Kind, double? Size);
diff --git a/Aetheris.SheetMetal.Tests/RecoveryAstAdmissionTests.cs b/Aetheris.SheetMetal.Tests/RecoveryAstAdmissionTests.cs
new file mode 100644
index 00000000..41f33f35
--- /dev/null
+++ b/Aetheris.SheetMetal.Tests/RecoveryAstAdmissionTests.cs
@@ -0,0 +1,18 @@
+using Xunit;
+namespace Aetheris.SheetMetal.Tests;
+public sealed class RecoveryAstAdmissionTests
+{
+ [Theory]
+ [InlineData("heigth: 2mm;")]
+ [InlineData("Fillet Lost { radius: 1mm }")]
+ [InlineData("kFactor: 0.5;")]
+ public void RecoveredEvidenceCannotDropIntent(string intent)
+ {
+ var part=SheetMetalFirmament.CompileFile(Path.Combine(Root(),"fixtures","Canonical","SheetMetal","u-channel.firmament"));Assert.True(part.IsSuccess);
+ var source=SheetMetalManufacturingArtifacts.WriteRecoveredFirmament(part.Part!,"original.step");
+ var valid=SheetMetalFirmament.Compile(source,"recovered.firmament");Assert.True(valid.IsSuccess,string.Join(";",valid.Diagnostics));
+ var at=source.IndexOf('{')+1;var invalid=SheetMetalFirmament.Compile(source.Insert(at,intent),"recovered.firmament");
+ Assert.False(invalid.IsSuccess);Assert.Contains(invalid.Diagnostics,d=>d.SourceSpan is not null && d.SourceFile=="recovered.firmament");
+ }
+ private static string Root(){var d=new DirectoryInfo(AppContext.BaseDirectory);while(d is not null&&!File.Exists(Path.Combine(d.FullName,"Aetheris.slnx")))d=d.Parent;return d!.FullName;}
+}
diff --git a/Aetheris.SheetMetal/EnclosureProductM6.cs b/Aetheris.SheetMetal/EnclosureProductM6.cs
index afb34643..6d72d73e 100644
--- a/Aetheris.SheetMetal/EnclosureProductM6.cs
+++ b/Aetheris.SheetMetal/EnclosureProductM6.cs
@@ -5,6 +5,8 @@ using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Step242;
using Aetheris.Kernel.Firmament.Assembly;
using Aetheris.Semantics;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
namespace Aetheris.SheetMetal;
@@ -183,9 +185,12 @@ public static class EnclosureProductFamilies
&& !identity.StartsWith("RemovablePanLid<", StringComparison.Ordinal)) return null;
var resolved = ResolveProjectedRecord(identity, declarations ?? string.Empty);
concreteName = "Assembly" + (resolved.StartsWith("ElectronicsEnclosure", StringComparison.Ordinal) ? "Body" : "Lid");
- var partDeclarations = Regex.Replace(declarations ?? string.Empty, @"\bConcept\s+EnclosureProduct\s*\{[^}]*\}", string.Empty, RegexOptions.CultureInvariant);
- partDeclarations = Regex.Replace(partDeclarations, @"\bRecord\s+EnclosureProductSpec\s*\{[^}]*\}", string.Empty, RegexOptions.CultureInvariant);
- partDeclarations = Regex.Replace(partDeclarations, @"\bStatic\s+\w+\s*:\s*EnclosureProductSpec\s*=\s*EnclosureProductSpec\s*\{[^}]*\}", string.Empty, RegexOptions.CultureInvariant);
+ var partDeclarations=declarations??string.Empty;
+ var productDeclarations=FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(partDeclarations).Document)
+ .Where(d=>d.Type.Name.Text=="Concept" && d.Name?.Text=="EnclosureProduct"
+ || d.Type.Name.Text=="Record" && d.Name?.Text=="EnclosureProductSpec"
+ || d.Type.Name.Text=="Static" && FirmamentSyntaxValues.Reference(d.Annotation)=="EnclosureProductSpec").ToArray();
+ partDeclarations=Erase(partDeclarations,productDeclarations);
partDeclarations = SelectPartExtensions(partDeclarations, concreteName.EndsWith("Body", StringComparison.Ordinal) ? "Body" : "Lid", concreteName);
var concreteSource = partDeclarations + Environment.NewLine + $"SheetMetal {concreteName} = {resolved}" + Environment.NewLine;
var compiled = SheetMetalFirmament.Compile(concreteSource, sourceIdentity + "#" + concreteName);
@@ -255,33 +260,33 @@ public static class EnclosureProductFamilies
fit.NominalState, fit.VariationEnvelopeState, contributions);
}
- private static string ResolveProjectedRecord(string identity, string declarations)
+ private static string ResolveProjectedRecord(string identity,string declarations)
{
- var application = Regex.Match(identity, @"^(?<template>\w+)<Spec:\s*(?<outer>\w+)\.(?<field>\w+)>$", RegexOptions.CultureInvariant);
- if (!application.Success) return identity;
- var record = Regex.Match(declarations, $@"\bStatic\s+{Regex.Escape(application.Groups["outer"].Value)}\s*:\s*\w+\s*=\s*\w+\s*\{{(?<body>.*?)\}}", RegexOptions.Singleline | RegexOptions.CultureInvariant);
- var field = record.Success ? Regex.Match(record.Groups["body"].Value, $@"\b{Regex.Escape(application.Groups["field"].Value)}\s*:\s*(?<value>\w+)", RegexOptions.CultureInvariant) : Match.Empty;
- if (!field.Success) throw new InvalidOperationException($"Projected product Record argument '{application.Groups["outer"].Value}.{application.Groups["field"].Value}' could not be resolved.");
- return $"{application.Groups["template"].Value}<Spec: {field.Groups["value"].Value}>";
+ var syntax=FirmamentSyntaxParser.ParseExpression(identity);
+ if(syntax.Expression is not SpecializationSyntax {Arguments.Count:1} app || app.Arguments[0].Name?.Text!="Spec" || app.Arguments[0].Value is not MemberSyntax member)return identity;
+ var name=FirmamentSyntaxValues.Reference(member.Target);
+ var module=FirmamentTemplateHostBridge.InspectModule(declarations,out var errors);
+ if(errors.Count>0)throw new InvalidOperationException(string.Join("; ",errors));
+ var records=module.StaticRecords.Where(r=>r.Name==name).ToArray();
+ if(records.Length!=1 || !records[0].Fields.TryGetValue(member.Member.Text,out var value))
+ throw new InvalidOperationException($"Projected product Record argument '{name}.{member.Member.Text}' could not be resolved.");
+ return $"{FirmamentSyntaxValues.Reference(app.Target)}<Spec: {value}>";
}
-
- private static string SelectPartExtensions(string source, string semanticPartName, string concreteName)
+ private static string SelectPartExtensions(string source,string semanticPartName,string concreteName)
{
- var chars = source.ToCharArray(); var selected = new List<string>();
- foreach (Match header in Regex.Matches(source, @"\bExtend\s+SheetMetal\s+(?<name>\w+)\s*\{", RegexOptions.CultureInvariant))
+ var declarations=FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)
+ .Where(d=>d.Type.Name.Text=="SheetMetal" && d.Modifiers.Any(m=>m.Name.Text=="Extend")).ToArray();
+ var selected=declarations.Where(d=>d.Name?.Text==semanticPartName).Select(d=>
{
- var open = header.Index + header.Length - 1; var depth = 0; var close = -1;
- for (var index = open; index < source.Length; index++)
- {
- if (source[index] == '{') depth++;
- else if (source[index] == '}' && --depth == 0) { close = index; break; }
- }
- if (close < 0) continue;
- if (header.Groups["name"].Value == semanticPartName)
- selected.Add("Extend SheetMetal " + concreteName + source[(open - 1)..(close + 1)].TrimStart());
- Array.Fill(chars, ' ', header.Index, close - header.Index + 1);
- }
- return new string(chars) + Environment.NewLine + string.Join(Environment.NewLine, selected);
+ var name=d.Name!;
+ return source.Substring(d.Span.Start,d.Span.Length).Remove(name.Span.Start-d.Span.Start,name.Span.Length).Insert(name.Span.Start-d.Span.Start,concreteName);
+ });
+ return Erase(source,declarations)+Environment.NewLine+string.Join(Environment.NewLine,selected);
+ }
+ private static string Erase(string source,IEnumerable<DeclarationSyntax> declarations)
+ {
+ var chars=source.ToCharArray();foreach(var d in declarations)for(var i=d.Span.Start;i<d.Span.Start+d.Span.Length;i++)if(chars[i] is not ('\r' or '\n'))chars[i]=' ';
+ return new(chars);
}
private static string BuildSource(EnclosureProductSpec spec, string instanceName)
diff --git a/Aetheris.SheetMetal/ReconstructedSheetMetalFirmament.cs b/Aetheris.SheetMetal/ReconstructedSheetMetalFirmament.cs
index e02b1989..3eefda64 100644
--- a/Aetheris.SheetMetal/ReconstructedSheetMetalFirmament.cs
+++ b/Aetheris.SheetMetal/ReconstructedSheetMetalFirmament.cs
@@ -1,5 +1,6 @@
using System.Globalization;
-using System.Text.RegularExpressions;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using static Aetheris.SheetMetal.RecoverySyntax;
namespace Aetheris.SheetMetal;
@@ -10,53 +11,53 @@ namespace Aetheris.SheetMetal;
/// </summary>
internal static class ReconstructedSheetMetalFirmament
{
- private const RegexOptions Rx=RegexOptions.IgnoreCase|RegexOptions.CultureInvariant|RegexOptions.Singleline;
- private const string Number=@"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[Ee][+-]?[0-9]+)?";
- public static bool IsReconstructed(string source)=>Regex.IsMatch(source,@"\bIntent\s*:\s*Reconstructed\s*;",Rx);
+ public static bool IsReconstructed(string source)=>FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)
+ .Where(d=>d.Type.Name.Text=="SheetMetal").Any(d=>d.Body?.Statements.OfType<FieldSyntax>().Any(f=>FirmamentSyntaxFields.SameField(f.Name.Text,"Intent") && FirmamentSyntaxValues.Reference(f.Value)=="Reconstructed")==true
+ && d.Body.Statements.OfType<FieldSyntax>().Any(f=>FirmamentSyntaxFields.SameField(f.Name.Text,"EvidenceSource")));
public static SheetMetalAuthoringResult Compile(string source,string sourcePath)
{
- var header=Regex.Match(source,@"\bSheetMetal\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{",Rx);
- var evidenceMatch=Regex.Match(source,"\\bEvidenceSource\\s*:\\s*\"(?<v>[^\"]+)\"\\s*;",Rx);
- if(!header.Success||!evidenceMatch.Success)return Failure("Reconstructed Sheet Metal requires a header and EvidenceSource.");
- var directory=Path.GetDirectoryName(Path.GetFullPath(sourcePath))??Directory.GetCurrentDirectory();var evidencePath=Path.GetFullPath(Path.Combine(directory,evidenceMatch.Groups["v"].Value.Replace('/',Path.DirectorySeparatorChar)));
+ var root=Root(source,sourcePath,out var syntaxDiagnostics);if(root is null)return new(false,null,null,null,syntaxDiagnostics);
+ if(Token(root,"Intent")!="Reconstructed")return Failure("Expected intent: Reconstructed.");
+ var evidenceSource=Quoted(root,"EvidenceSource");if(evidenceSource is null)return Failure("Reconstructed Sheet Metal requires EvidenceSource.");
+ var directory=Path.GetDirectoryName(Path.GetFullPath(sourcePath))??Directory.GetCurrentDirectory();var evidencePath=Path.GetFullPath(Path.Combine(directory,evidenceSource.Replace('/',Path.DirectorySeparatorChar)));
if(!File.Exists(evidencePath))return Failure($"Reconstruction evidence was not found: {evidencePath}");
var evidence=RecoveredSheetMetalFirmament.Compile(File.ReadAllText(evidencePath),evidencePath);if(!evidence.IsSuccess||evidence.Part is null)return Failure("EvidenceSource did not compile as recovered Sheet Metal evidence.");
- var original=evidence.Part;if(!Scalar(source,"Thickness","mm",out var thickness)||thickness<=0)return Failure("Reconstructed Sheet Metal requires positive Thickness.");
- var k=Scalar(source,"KFactor",null,out var parsedK)?parsedK:original.FlatPatternPolicy.KFactor;if(k is <0 or >1)return Failure("KFactor must be between zero and one.");
+ var original=evidence.Part;if(!Scalar(root,"Thickness","mm",out var thickness)||thickness<=0)return Failure("Reconstructed Sheet Metal requires positive Thickness.");
+ var k=Scalar(root,"KFactor",null,out var parsedK)?parsedK:original.FlatPatternPolicy.KFactor;if(k is <0 or >1)return Failure("KFactor must be between zero and one.");
var regionMap=new Dictionary<string,string>(StringComparer.Ordinal);
- foreach(Match m in Regex.Matches(source,@"\bRegion\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{(?<body>.*?)\}",Rx))
+ foreach(var m in root.Children("Region"))
{
- var from=Quoted(m.Groups["body"].Value,"FromEvidence");if(from is null||original.Regions.All(r=>r.StableId!=from))return Failure($"Region '{m.Groups["name"].Value}' has invalid FromEvidence.");
- regionMap[from]=m.Groups["name"].Value;
+ var from=Quoted(m.Body,"FromEvidence");if(from is null||original.Regions.All(r=>r.StableId!=from))return Failure($"Region '{m.Name}' has invalid FromEvidence.");
+ if(!regionMap.TryAdd(from,m.Name) || regionMap.Values.Distinct(StringComparer.Ordinal).Count()!=regionMap.Count)return Failure("Reconstructed regions must map distinct evidence and names exactly once.");
}
if(regionMap.Count!=original.Regions.Count)return Failure($"Reconstruction must explicitly account for every recovered region ({regionMap.Count}/{original.Regions.Count}).");
- var baseName=Token(source,"BaseRegion");if(baseName is null||!regionMap.Values.Contains(baseName,StringComparer.Ordinal))return Failure("BaseRegion must name a reconstructed Region.");
+ var baseName=Token(root,"BaseRegion");if(baseName is null||!regionMap.Values.Contains(baseName,StringComparer.Ordinal))return Failure("BaseRegion must name a reconstructed Region.");
var regions=original.Regions.Select(r=>r with{StableId=regionMap[r.StableId],Source=r.Source with{SourceAuthority="forensic recovery evidence; reconstructed naming authority"},Evidence=r.Evidence.Concat([new(SheetEvidenceKind.Authored,"reconstructed-region",$"Engineer mapped recovered region '{r.StableId}' to '{regionMap[r.StableId]}'.",SourceFaceIds:r.Source.FaceIds)]).ToArray()}).ToArray();
- var bends=new List<SheetBendIr>();
- foreach(Match m in Regex.Matches(source,@"\bBend\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{(?<body>.*?)\}",Rx))
+ var bends=new List<SheetBendIr>();var mappedBends=new HashSet<string>(StringComparer.Ordinal);
+ foreach(var m in root.Children("Bend"))
{
- var body=m.Groups["body"].Value;var from=Quoted(body,"FromEvidence");var originalBend=original.Bends.SingleOrDefault(b=>b.StableId==from);if(originalBend is null)return Failure($"Bend '{m.Groups["name"].Value}' has invalid FromEvidence.");
- if(!Scalar(body,"Angle","deg",out var angle)||!Scalar(body,"InsideRadius","mm",out var radius))return Failure($"Bend '{m.Groups["name"].Value}' requires accepted Angle and InsideRadius.");
- bends.Add(originalBend with{StableId=m.Groups["name"].Value,BendAngleRadians=angle*Math.PI/180d,InsideRadius=radius,Thickness=thickness,AdjacentRegionA=regionMap[originalBend.AdjacentRegionA],AdjacentRegionB=regionMap[originalBend.AdjacentRegionB],NeutralAxisPolicy=SheetNeutralAxisPolicy.KFactorPolicy(k),Source=originalBend.Source with{SourceAuthority="forensic recovery evidence; reconstructed dimension authority"},Evidence=originalBend.Evidence.Concat([new(SheetEvidenceKind.Authored,"accepted-reconstruction-nominal","Engineer explicitly accepted bend angle/radius values.")]).ToArray()});
+ var body=m.Body;var from=Quoted(body,"FromEvidence");var originalBend=original.Bends.SingleOrDefault(b=>b.StableId==from);if(originalBend is null)return Failure($"Bend '{m.Name}' has invalid FromEvidence.");
+ if(!mappedBends.Add(from!) || bends.Any(b=>b.StableId==m.Name))return Failure("Reconstructed bends must map distinct evidence and names exactly once.");
+ if(!Scalar(body,"Angle","deg",out var angle)||!Scalar(body,"InsideRadius","mm",out var radius))return Failure($"Bend '{m.Name}' requires accepted Angle and InsideRadius.");
+ bends.Add(originalBend with{StableId=m.Name,BendAngleRadians=angle*Math.PI/180d,InsideRadius=radius,Thickness=thickness,AdjacentRegionA=regionMap[originalBend.AdjacentRegionA],AdjacentRegionB=regionMap[originalBend.AdjacentRegionB],NeutralAxisPolicy=SheetNeutralAxisPolicy.KFactorPolicy(k),Source=originalBend.Source with{SourceAuthority="forensic recovery evidence; reconstructed dimension authority"},Evidence=originalBend.Evidence.Concat([new(SheetEvidenceKind.Authored,"accepted-reconstruction-nominal","Engineer explicitly accepted bend angle/radius values.")]).ToArray()});
}
if(bends.Count!=original.Bends.Count)return Failure($"Reconstruction must explicitly account for every recovered bend ({bends.Count}/{original.Bends.Count}).");
- var cuts=new List<SheetFeatureIr>();
- foreach(Match m in Regex.Matches(source,@"\bCut\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{(?<body>.*?)\}",Rx))
+ var cuts=new List<SheetFeatureIr>();var mappedCuts=new HashSet<string>(StringComparer.Ordinal);
+ foreach(var m in root.Children("Cut"))
{
- var body=m.Groups["body"].Value;var from=Quoted(body,"FromEvidence");var originalCut=original.Features.SingleOrDefault(f=>f.StableId==from);if(originalCut is null)return Failure($"Cut '{m.Groups["name"].Value}' has invalid FromEvidence.");
- cuts.Add(originalCut with{StableId=m.Groups["name"].Value,OwningRegionId=regionMap[originalCut.OwningRegionId],Source=originalCut.Source with{SourceAuthority="forensic recovery evidence; reconstructed feature authority"},Evidence=originalCut.Evidence.Concat([new(SheetEvidenceKind.Authored,"reconstructed-cut",$"Engineer grouped/named recovered cut '{originalCut.StableId}'.")]).ToArray()});
+ var body=m.Body;var from=Quoted(body,"FromEvidence");var originalCut=original.Features.SingleOrDefault(f=>f.StableId==from);if(originalCut is null)return Failure($"Cut '{m.Name}' has invalid FromEvidence.");
+ if(!mappedCuts.Add(from!) || cuts.Any(c=>c.StableId==m.Name))return Failure("Reconstructed cuts must map distinct evidence and names exactly once.");
+ cuts.Add(originalCut with{StableId=m.Name,OwningRegionId=regionMap[originalCut.OwningRegionId],Source=originalCut.Source with{SourceAuthority="forensic recovery evidence; reconstructed feature authority"},Evidence=originalCut.Evidence.Concat([new(SheetEvidenceKind.Authored,"reconstructed-cut",$"Engineer grouped/named recovered cut '{originalCut.StableId}'.")]).ToArray()});
}
if(cuts.Count!=original.Features.Count)return Failure($"Reconstruction must explicitly account for every recovered cut ({cuts.Count}/{original.Features.Count}).");
- var part=new SheetMetalPartIr($"sheetmetal-{header.Groups["name"].Value}",thickness,original.Material,baseName,regions,bends,cuts,new(k),SheetMetalRecognitionStatus.Partial,"Reconstructed engineer/LLM-authored interpretation linked to immutable recovered evidence.",[new(SheetEvidenceKind.Authored,"reconstructed-intent","Naming, grouping, and nominal choices are explicit human/LLM engineering authority; geometry bindings remain forensic evidence."),new(SheetEvidenceKind.Authored,"accepted-thickness-nominal","Measured recovery thickness was explicitly nominalized.",thickness,Math.Abs(thickness-original.Thickness))],[],original.FormedBody);
+ var closed=Close(root);if(closed.Count>0)return new(false,null,null,null,closed);
+ var part=new SheetMetalPartIr($"sheetmetal-{root.Name}",thickness,original.Material,baseName,regions,bends,cuts,new(k),SheetMetalRecognitionStatus.Partial,"Reconstructed engineer/LLM-authored interpretation linked to immutable recovered evidence.",[new(SheetEvidenceKind.Authored,"reconstructed-intent","Naming, grouping, and nominal choices are explicit human/LLM engineering authority; geometry bindings remain forensic evidence."),new(SheetEvidenceKind.Authored,"accepted-thickness-nominal","Measured recovery thickness was explicitly nominalized.",thickness,Math.Abs(thickness-original.Thickness))],[],original.FormedBody);
var flat=SheetMetalFlattener.Flatten(part);return new(flat.Status==FlatPatternStatus.Unsupported?false:true,null,part,flat,flat.Diagnostics);
}
- private static bool Scalar(string text,string name,string? unit,out double value){var suffix=unit is null?"":@"\s*"+Regex.Escape(unit);var m=Regex.Match(text,@"\b"+Regex.Escape(name)+@"\s*:\s*(?<v>"+Number+")"+suffix+@"\s*;",Rx);value=m.Success?double.Parse(m.Groups["v"].Value,NumberStyles.Float,CultureInfo.InvariantCulture):0;return m.Success;}
- private static string? Quoted(string text,string name){var m=Regex.Match(text,"\\b"+Regex.Escape(name)+"\\s*:\\s*\"(?<v>[^\"]+)\"\\s*;",Rx);return m.Success?m.Groups["v"].Value:null;}
- private static string? Token(string text,string name){var m=Regex.Match(text,@"\b"+Regex.Escape(name)+@"\s*:\s*(?<v>[A-Za-z_][A-Za-z0-9_]*)\s*;",Rx);return m.Success?m.Groups["v"].Value:null;}
private static SheetMetalAuthoringResult Failure(string message)=>new(false,null,null,null,[new("sheetmetal-firmament-reconstruction-invalid",SheetMetalDiagnosticSeverity.Error,message)]);
}
diff --git a/Aetheris.SheetMetal/RecoveredSheetMetalFirmament.cs b/Aetheris.SheetMetal/RecoveredSheetMetalFirmament.cs
index b1c710dc..dbb7258f 100644
--- a/Aetheris.SheetMetal/RecoveredSheetMetalFirmament.cs
+++ b/Aetheris.SheetMetal/RecoveredSheetMetalFirmament.cs
@@ -1,5 +1,6 @@
using System.Globalization;
-using System.Text.RegularExpressions;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using static Aetheris.SheetMetal.RecoverySyntax;
using Aetheris.Kernel.Core.Math;
using Aetheris.Surfacing;
@@ -8,26 +9,24 @@ namespace Aetheris.SheetMetal;
/// <summary>Reader for the explicit, loss-aware recovered Sheet Metal Firmament form.</summary>
internal static class RecoveredSheetMetalFirmament
{
- private const RegexOptions Rx = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Singleline;
- private const string Number = @"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[Ee][+-]?[0-9]+)?";
-
- public static bool IsRecovered(string source) => Regex.IsMatch(source, "\\bRecoveredRegion\\s+\"", Rx);
+ public static bool IsRecovered(string source)=>FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d=>d.Type.Name.Text=="RecoveredRegion");
public static SheetMetalAuthoringResult Compile(string source, string sourcePath)
{
- var header = Regex.Match(source, @"\bSheetMetal\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", Rx);
- if (!header.Success || !Scalar(source, "Thickness", "mm", out var thickness) || thickness <= 0)
- return Failure("Recovered Sheet Metal requires a valid header and positive Thickness.");
- var k = Scalar(source, "KFactor", null, out var parsedK) ? parsedK : .5;
+ var root=Root(source,sourcePath,out var syntaxDiagnostics);
+ if(root is null)return new(false,null,null,null,syntaxDiagnostics);
+ root.Take("RecoverySource");
+ if(!Scalar(root,"Thickness","mm",out var thickness)||thickness<=0)return Failure("Recovered Sheet Metal requires positive Thickness.");
+ var k = Scalar(root, "KFactor", null, out var parsedK) ? parsedK : .5;
if (k is < 0 or > 1) return Failure("Recovered Sheet Metal KFactor must be between 0 and 1.");
- var baseRegion = Quoted(source, "BaseRegion"); if (baseRegion is null) return Failure("Recovered Sheet Metal requires BaseRegion.");
- var statusText = Token(source, "RecoveryStatus") ?? nameof(SheetMetalRecognitionStatus.Partial);
+ var baseRegion = Quoted(root, "BaseRegion"); if (baseRegion is null) return Failure("Recovered Sheet Metal requires BaseRegion.");
+ var statusText = Token(root, "RecoveryStatus") ?? nameof(SheetMetalRecognitionStatus.Partial);
if (!Enum.TryParse<SheetMetalRecognitionStatus>(statusText, true, out var status)) return Failure($"Unknown RecoveryStatus '{statusText}'.");
var regions = new List<SheetRegionIr>();
- foreach (Match block in Regex.Matches(source, "\\bRecoveredRegion\\s+\"(?<id>[^\"]+)\"\\s*\\{(?<body>.*?)\\}", Rx))
+ foreach (var block in root.Children("RecoveredRegion"))
{
- var id = block.Groups["id"].Value; var body = block.Groups["body"].Value; var kindText = Token(body, "Kind");
+ var id = block.Name; var body = block.Body; var kindText = Token(body, "Kind");
if (!Enum.TryParse<SheetRegionKind>(kindText, true, out var kind)) return Failure($"RecoveredRegion '{id}' has invalid Kind.");
Scalar(body, "Area", "mm2", out var area); var faces = IntList(body, "SourceFaces"); var boundary = Points(body, "Boundary");
SheetPlaneReference? plane = null; SheetCylinderReference? cylinder = null;
@@ -49,55 +48,36 @@ internal static class RecoveredSheetMetalFirmament
if (regions.Count == 0 || regions.All(r => r.StableId != baseRegion)) return Failure("Recovered Sheet Metal BaseRegion does not name a declared region.");
var bends = new List<SheetBendIr>();
- foreach (Match block in Regex.Matches(source, "\\bRecoveredBend\\s+\"(?<id>[^\"]+)\"\\s*\\{(?<body>.*?)\\}", Rx))
+ foreach (var block in root.Children("RecoveredBend"))
{
- var id = block.Groups["id"].Value; var body = block.Groups["body"].Value;
+ var id = block.Name; var body = block.Body;
if (!Point(body, "AxisOrigin", true, out var origin) || !Vector(body, "AxisDirection", out var axis) || !Scalar(body, "Angle", "deg", out var angle) || !Scalar(body, "InsideRadius", "mm", out var radius))
return Failure($"Recovered bend '{id}' is missing axis, angle, or radius.");
var between = StringList(body, "Between"); if (between.Count != 2 || between.Any(x => regions.All(r => r.StableId != x))) return Failure($"Recovered bend '{id}' must connect two declared regions.");
- if (!Enum.TryParse<SheetBendDirection>(Token(body, "Direction"), true, out var direction)) direction = SheetBendDirection.Unknown;
+ var directionText=Token(body,"Direction");
+ if (!Enum.TryParse<SheetBendDirection>(directionText, true, out var direction)){direction=SheetBendDirection.Unknown;if(directionText is not null)body.Invalid("Direction");}
var faces = IntList(body, "SourceFaces"); bends.Add(new(id, origin, axis, angle * Math.PI / 180d, radius, thickness, direction, between[0], between[1], SheetNeutralAxisPolicy.KFactorPolicy(k),
new("Firmament recovered declaration", "recovered STEP semantics", faces, [], sourcePath), [new(SheetEvidenceKind.Authored, "recovered-bend", "Axis, radius, direction, and region adjacency serialized explicitly.", SourceFaceIds: faces)]));
}
var cuts = new List<SheetFeatureIr>();
- foreach (Match block in Regex.Matches(source, "\\bRecoveredCut\\s+\"(?<id>[^\"]+)\"\\s*\\{(?<body>.*?)\\}", Rx))
+ foreach (var block in root.Children("RecoveredCut"))
{
- var id = block.Groups["id"].Value; var body = block.Groups["body"].Value;
+ var id = block.Name; var body = block.Body;
if (!Enum.TryParse<SheetFeatureKind>(Token(body, "Kind"), true, out var kind)) return Failure($"Recovered cut '{id}' has invalid Kind.");
var owner = Quoted(body, "On"); if (owner is null || regions.All(r => r.StableId != owner) || !Point(body, "Center", true, out var center)) return Failure($"Recovered cut '{id}' has invalid owner or center.");
var diameter = Scalar(body, "Diameter", "mm", out var d) ? d : (double?)null; var faces = IntList(body, "SourceFaces");
cuts.Add(new(id, kind, owner, center, diameter, Points(body, "Boundary"), new("Firmament recovered declaration", "recovered STEP semantics", faces, [], sourcePath),
[new(SheetEvidenceKind.Authored, "recovered-cut", "Cut classification and reference boundary serialized explicitly.", diameter, SourceFaceIds: faces)]));
}
- var part = new SheetMetalPartIr(header.Groups["name"].Value, thickness, null, baseRegion, regions, bends, cuts, new(k), status,
+ if(regions.Select(r=>r.StableId).Distinct().Count()!=regions.Count || bends.Select(b=>b.StableId).Distinct().Count()!=bends.Count || cuts.Select(c=>c.StableId).Distinct().Count()!=cuts.Count)
+ return Failure("Recovered identities must be unique within each region, bend and cut family.");
+ var closed=Close(root);if(closed.Count>0)return new(false,null,null,null,closed);
+ var part = new SheetMetalPartIr(root.Name, thickness, null, baseRegion, regions, bends, cuts, new(k), status,
"Firmament recovered Sheet Metal semantics", [new(SheetEvidenceKind.Authored, "recovered-intent", "Loss-aware semantic recovery source; original STEP remains authoritative geometry.")], [], null);
var flat = SheetMetalFlattener.Flatten(part, new(k));
return new(flat.Status == FlatPatternStatus.Unsupported ? false : true, null, part, flat, flat.Diagnostics);
}
- private static bool Scalar(string text, string name, string? unit, out double value)
- {
- var suffix = unit is null ? "" : @"\s*" + Regex.Escape(unit); var match = Regex.Match(text, @"\b" + Regex.Escape(name) + @"\s*:\s*(?<v>" + Number + ")" + suffix + @"\s*;", Rx);
- value = match.Success ? double.Parse(match.Groups["v"].Value, NumberStyles.Float, CultureInfo.InvariantCulture) : 0; return match.Success;
- }
- private static bool Point(string text, string name, bool units, out Point3D value) { var tuple = Tuple(text, name, units); value = tuple is null ? default : new(tuple.Value.X, tuple.Value.Y, tuple.Value.Z); return tuple is not null; }
- private static bool Vector(string text, string name, out Vector3D value) { var tuple = Tuple(text, name, false); value = tuple is null ? default : new(tuple.Value.X, tuple.Value.Y, tuple.Value.Z); return tuple is not null; }
- private static (double X, double Y, double Z)? Tuple(string text, string name, bool units)
- {
- var u = units ? @"\s*mm" : ""; var m = Regex.Match(text, @"\b" + Regex.Escape(name) + @"\s*:\s*\(\s*(?<x>" + Number + ")" + u + @"\s*,\s*(?<y>" + Number + ")" + u + @"\s*,\s*(?<z>" + Number + ")" + u + @"\s*\)\s*;", Rx);
- return m.Success ? (N(m, "x"), N(m, "y"), N(m, "z")) : null;
- }
- private static IReadOnlyList<Point3D> Points(string text, string name)
- {
- var list = Regex.Match(text, @"\b" + Regex.Escape(name) + @"\s*:\s*\[(?<v>.*?)\]\s*;", Rx); if (!list.Success) return [];
- return Regex.Matches(list.Groups["v"].Value, @"\(\s*(?<x>" + Number + @")\s*mm\s*,\s*(?<y>" + Number + @")\s*mm\s*,\s*(?<z>" + Number + @")\s*mm\s*\)", Rx).Cast<Match>().Select(m => new Point3D(N(m, "x"), N(m, "y"), N(m, "z"))).ToArray();
- }
- private static IReadOnlyList<int> IntList(string text, string name) { var m = Regex.Match(text, @"\b" + Regex.Escape(name) + @"\s*:\s*\[(?<v>.*?)\]\s*;", Rx); return m.Success ? Regex.Matches(m.Groups["v"].Value, @"\d+").Select(x => int.Parse(x.Value, CultureInfo.InvariantCulture)).ToArray() : []; }
- private static IReadOnlyList<string> StringList(string text, string name) { var m = Regex.Match(text, @"\b" + Regex.Escape(name) + @"\s*:\s*\[(?<v>.*?)\]\s*;", Rx); return m.Success ? Regex.Matches(m.Groups["v"].Value, "\"(?<v>[^\"]+)\"").Cast<Match>().Select(x => x.Groups["v"].Value).ToArray() : []; }
- private static string? Quoted(string text, string name) { var m = Regex.Match(text, @"\b" + Regex.Escape(name) + "\\s*:\\s*\"(?<v>[^\"]+)\"\\s*;", Rx); return m.Success ? m.Groups["v"].Value : null; }
- private static string? Token(string text, string name) { var m = Regex.Match(text, @"\b" + Regex.Escape(name) + @"\s*:\s*(?<v>[A-Za-z_][A-Za-z0-9_]*)\s*;", Rx); return m.Success ? m.Groups["v"].Value : null; }
- private static bool Bool(string text, string name, bool fallback) => bool.TryParse(Token(text, name), out var value) ? value : fallback;
- private static double N(Match m, string group) => double.Parse(m.Groups[group].Value, NumberStyles.Float, CultureInfo.InvariantCulture);
private static SheetMetalAuthoringResult Failure(string message) => new(false, null, null, null, [new("sheetmetal-firmament-recovery-invalid", SheetMetalDiagnosticSeverity.Error, message)]);
}
diff --git a/Aetheris.SheetMetal/RecoverySyntax.cs b/Aetheris.SheetMetal/RecoverySyntax.cs
new file mode 100644
index 00000000..e1c32826
--- /dev/null
+++ b/Aetheris.SheetMetal/RecoverySyntax.cs
@@ -0,0 +1,64 @@
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Scope=Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxScope;
+namespace Aetheris.SheetMetal;
+internal static class RecoverySyntax
+{
+ internal static Scope? Root(string source,string path,out IReadOnlyList<SheetMetalDiagnostic> diagnostics)
+ {
+ var syntax=FirmamentSyntaxParser.Parse(source,path);
+ var errors=syntax.Diagnostics.Select(d=>new SheetMetalDiagnostic(d.Code,SheetMetalDiagnosticSeverity.Error,d.Message){SourceFile=d.SourceFile,SourceSpan=d.SourceSpan,Context=d.Target,LocationNote=d.LocationNote}).ToList();
+ var roots=syntax.Document.Statements.OfType<DeclarationSyntax>().Where(d=>d.Type.Name.Text=="SheetMetal").ToArray();
+ if(roots.Length!=1 || syntax.Document.Statements.Count!=1)errors.Add(new("sheetmetal-recovery-document-invalid",SheetMetalDiagnosticSeverity.Error,"Recovered/reconstructed source requires exactly one SheetMetal declaration."));
+ diagnostics=errors;return errors.Count==0?new(roots[0],source,path):null;
+ }
+ internal static string? Token(Scope scope,string field)=>scope.Word(field);
+ internal static string? Quoted(Scope scope,string field)
+ {
+ var value=scope.Take(field);if(value is LiteralSyntax {Kind:LiteralKind.String})return FirmamentSyntaxValues.Reference(value);
+ if(value is not null)scope.Invalid(field,"Expected a quoted identity.");return null;
+ }
+ internal static bool Scalar(Scope scope,string field,string? unit,out double value)
+ {
+ var expression=scope.Take(field);value=0;if(expression is null)return false;
+ // Area is serialized recovery evidence, not a new general dimensional algebra.
+ if(unit=="mm2" && expression is QuantitySyntax {Unit.Text:"mm2"} area)expression=area.Value;
+ if(FirmamentSyntaxValues.TryMeasure(expression,unit=="mm2"?"":unit??"",out value) && double.IsFinite(value))return true;
+ scope.Invalid(field);return false;
+ }
+ private static ExpressionSyntax? VectorExpression(ExpressionSyntax? expression)=>expression is SequenceSyntax {Kind:SequenceKind.Tuple} tuple?tuple with {Kind=SequenceKind.List}:expression;
+ private static bool Components(ExpressionSyntax? expression,string unit,out double[] values)=>FirmamentSyntaxValues.Vector(VectorExpression(expression),unit,out values) && values.Length==3 && values.All(double.IsFinite);
+ internal static bool Point(Scope scope,string field,bool units,out Point3D value)
+ {
+ var expression=scope.Take(field);value=default;if(Components(expression,units?"mm":"",out var v)){value=new(v[0],v[1],v[2]);return true;}
+ if(expression is not null)scope.Invalid(field);return false;
+ }
+ internal static bool Vector(Scope scope,string field,out Vector3D value){var valid=Point(scope,field,false,out var p);value=new(p.X,p.Y,p.Z);return valid;}
+ internal static IReadOnlyList<Point3D> Points(Scope scope,string field)
+ {
+ var expression=scope.Take(field);if(expression is null)return [];
+ if(expression is not SequenceSyntax {Kind:SequenceKind.List} list){scope.Invalid(field);return [];}
+ var result=new List<Point3D>();
+ foreach(var item in list.Items)if(item.Name is null && item.Default is null && Components(item.Value,"mm",out var v))result.Add(new(v[0],v[1],v[2]));else scope.Invalid(field);
+ return result;
+ }
+ internal static IReadOnlyList<int> IntList(Scope scope,string field)
+ {
+ var expression=scope.Take(field);if(expression is null)return [];
+ if(FirmamentSyntaxValues.Vector(expression,"",out var values) && values.All(v=>double.IsFinite(v)&&v>=0&&v<=int.MaxValue&&v==Math.Truncate(v)))return values.Select(v=>(int)v).ToArray();
+ scope.Invalid(field);return [];
+ }
+ internal static IReadOnlyList<string> StringList(Scope scope,string field)
+ {
+ var expression=scope.Take(field);if(expression is null)return [];
+ if(expression is SequenceSyntax {Kind:SequenceKind.List} list && list.Items.All(i=>i.Name is null && i.Default is null && i.Value is LiteralSyntax {Kind:LiteralKind.String}))return list.Items.Select(i=>FirmamentSyntaxValues.Reference(i.Value)!).ToArray();
+ scope.Invalid(field);return [];
+ }
+ internal static bool Bool(Scope scope,string field,bool fallback)
+ {
+ var expression=scope.Take(field);if(expression is null)return fallback;
+ if(expression is LiteralSyntax {Kind:LiteralKind.Boolean} boolean && bool.TryParse(boolean.Raw,out var value))return value;
+ scope.Invalid(field);return fallback;
+ }
+ internal static IReadOnlyList<SheetMetalDiagnostic> Close(Scope root)=>root.CompleteTree().Select(d=>new SheetMetalDiagnostic(d.Code,SheetMetalDiagnosticSeverity.Error,d.Message){SourceFile=d.SourceFile,SourceSpan=d.SourceSpan,Context=d.Target,LocationNote=d.LocationNote}).ToArray();
+}
diff --git a/Aetheris.SheetMetal/SheetMetalFirmament.cs b/Aetheris.SheetMetal/SheetMetalFirmament.cs
index 3d6deb77..935221b8 100644
--- a/Aetheris.SheetMetal/SheetMetalFirmament.cs
+++ b/Aetheris.SheetMetal/SheetMetalFirmament.cs
@@ -76,7 +76,7 @@ public static class SheetMetalFirmament
foreach(var token in FirmamentSyntaxParser.Parse(source).Document.Tokens.Where(t=>t.Kind==SyntaxTokenKind.Comment))
for(var i=token.Span.Start;i<token.Span.Start+token.Span.Length;i++)if(cleanChars[i] is not ('\r' or '\n'))cleanChars[i]=' ';
var clean=new string(cleanChars);
- if(ReconstructedSheetMetalFirmament.IsReconstructed(clean)&&Regex.IsMatch(clean,@"\bEvidenceSource\s*:",Rx))return ReconstructedSheetMetalFirmament.Compile(clean,sourcePath);
+ if(ReconstructedSheetMetalFirmament.IsReconstructed(clean))return ReconstructedSheetMetalFirmament.Compile(clean,sourcePath);
if(RecoveredSheetMetalFirmament.IsRecovered(clean))return RecoveredSheetMetalFirmament.Compile(clean,sourcePath);
var result=AuthoredSheetMetalCompiler.Compile(clean,sourcePath,originalSource);
return result;
diff --git a/Aetheris.Surfacing/SculptingAuthoringResults.cs b/Aetheris.Surfacing/SculptingAuthoringResults.cs
new file mode 100644
index 00000000..1b79b84b
--- /dev/null
+++ b/Aetheris.Surfacing/SculptingAuthoringResults.cs
@@ -0,0 +1,5 @@
+namespace Aetheris.Surfacing;
+
+public sealed record SculptingTimingEvidence(double BasePreparationMilliseconds, double OperationConstructionMilliseconds, double LocalityAndPreservationMilliseconds, double BrepValidationMilliseconds, double StepExportMilliseconds);
+public sealed record SculptingCompileResult(bool IsSuccess, string ModelName, BodyState? OutputState, IReadOnlyDictionary<string, BodyState> States, IReadOnlyList<SculptDiagnostic> Diagnostics, SculptingTimingEvidence Timings);
+
diff --git a/Aetheris.Surfacing/SculptingState.cs b/Aetheris.Surfacing/SculptingState.cs
index 8c8c50bb..81c0ffde 100644
--- a/Aetheris.Surfacing/SculptingState.cs
+++ b/Aetheris.Surfacing/SculptingState.cs
@@ -284,7 +284,12 @@ public sealed record RemoveSectionChainOperation(
public string Canonical => $"{StableId}|{Chain.StableId}|{SectionChainCanonical.Fingerprint(Chain)}|{string.Join(',', SupportRegions)}|{string.Join(',', MayModify.Order(StringComparer.Ordinal))}|{InfluenceEnvelope.MinX:R},{InfluenceEnvelope.MinY:R},{InfluenceEnvelope.MinZ:R},{InfluenceEnvelope.MaxX:R},{InfluenceEnvelope.MaxY:R},{InfluenceEnvelope.MaxZ:R}|{string.Join(',', Preserves.OrderBy(item => item.EntityId, StringComparer.Ordinal).Select(item => $"{item.EntityId}:{item.Mode}"))}|{string.Join(',', Requirements.Order())}";
}
-public sealed record SculptDiagnostic(string Code, string Message, string? Entity = null);
+public sealed record SculptDiagnostic(string Code, string Message, string? Entity = null)
+{
+ public string Severity => "error";
+ public string? SourceFile { get; init; }
+ public Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSourceSpan? SourceSpan { get; init; }
+}
public sealed record SculptResult(bool IsSuccess, BodyState? OutputState, GeometricDelta? Delta, IReadOnlyList<SculptValidationEvidence> Evidence, IReadOnlyList<SculptDiagnostic> Diagnostics)
{
public static SculptResult Failure(IEnumerable<SculptDiagnostic> diagnostics, IEnumerable<SculptValidationEvidence>? evidence = null)
diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
index 24df23cb..a053c326 100644
--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
@@ -410,7 +410,7 @@ compiler-honesty failure. This does not close X2.
| CORPUS-02: Sheet boundaries | Applied | Shared Rect2 Profiles replace legacy rectangular boundaries without changing Slot geometry. Points and anchors use ordinary constructor calls. |
| CORPUS-03: Implicit Base identity | Fixed | Permit `base: profile` through the shared Base Profile binder. Preserve implicit region/bend IDs; a named Base is a distinct identity choice. Original source/geometry witnesses remain under Compatibility. |
| CORPUS-04: Relative assembly placement | Fixed | Use Parent for relative placement. Child-owned mates do not drive their containing occurrence; retain competing-authority rejection on the actual owner. |
-| CORPUS-05: Surfacing casing/crash | Fixed, AST migration remains | Existing owner reads first-character field aliases and stops before construction after bad mounting data. A shared structural parse is not proof this independent reader is migrated. |
+| CORPUS-05: Surfacing casing/crash | Fixed; production AST admission migrated 2026-10-18 | Existing owner reads first-character field aliases and stops before construction after bad mounting data. A shared structural parse is not proof this independent reader is migrated. |
| CORPUS-06: Inner-loop segment identity | Fixed source | Give inner segments explicit aliases; preserve 4160 mm3 intended volume. |
| CORPUS-07: SurfaceCoil supports | Separate semantic/capability prerequisite | Preserve centerline-only witnesses outside Canonical. Define nonmaterial analytic support binding before admitting support solids plus wire output; never erase material implicitly. |
| CORPUS-08: Fixture qualification levels | Applied | Qualify modules through real consumers; inspect gear interfaces; record missing garment bodies separately. Solver-invalid and DFM-warning specimens are not syntax failures. Preserve the now-valid Rect2 TraceLoop specimen and use an open Line2 for the actual negative. |
@@ -420,3 +420,14 @@ compiler-honesty failure. This does not close X2.
No additional fatality allowlist, source macro system or parallel frontend was
introduced. No decision above grants missing geometry or blanket X2 acceptance.
+
+
+## Remaining-domain AST follow-up (2026-10-18)
+
+The [production migration and inconsistency register](FIRMAMENT-REMAINING-DOMAIN-AST-2026-10-18.md)
+records Structural, Sculpting/BodyState, Analysis, PlasticShell, Drawing/Review,
+and recovered/evidence-linked SheetMetal ownership. This supersedes the
+CORPUS-05 independent-reader qualification above. Unknown intent closes at the
+actual AST owner; no shadow-only admission path was added. DOMAIN-01 through
+DOMAIN-13 preserve the remaining semantic, expansion, units, provenance and
+metadata decisions. This does not mark X2 or separate geometry work complete.
diff --git a/docs/development/FIRMAMENT-REMAINING-DOMAIN-AST-2026-10-18.md b/docs/development/FIRMAMENT-REMAINING-DOMAIN-AST-2026-10-18.md
new file mode 100644
index 00000000..012b32b6
--- /dev/null
+++ b/docs/development/FIRMAMENT-REMAINING-DOMAIN-AST-2026-10-18.md
@@ -0,0 +1,230 @@
+# Remaining Firmament domain frontends — 2026-10-18
+
+## Purpose and qualification boundary
+
+This follows the [Piping migration](FIRMAMENT-PIPING-AST-ADMISSION-2026-10.md).
+The work replaces independent authoring scanners with production consumption of
+`FirmamentSyntaxParser` trees. It is not another shadow milestone and does not
+claim that all of X2's semantic design work is finished.
+
+The organizing model remains: Model owns an artifact; Struct defines reusable
+construction; Feature is a typed recipe; Pattern is finite compile-time
+repetition. A shared syntax tree does not turn domain-specific engineering
+operations into interchangeable types.
+
+## Production ownership changes
+
+| Family | Former authority | Current authority and preserved lowerer |
+| --- | --- | --- |
+| Structural | Whole-source block, Node/Path and Table regex readers | Direct AST scopes; shared Record/Static/Table catalogue; existing member AIR, joint resolution, interfaces, cut lists and AP242 assembly generation. |
+| Sculpting / BodyState | Independent block/field/control-net scanner | AST state/operation/SurfacePatch/Station scopes and shared values; existing sculptors, construction-state replay, continuity judgments and STEP exporter. |
+| Analysis | Regex Analysis blocks plus fallback Box/cut scanning after geometry parse failure | AST Analysis owner, shared values, normal native geometry admission and an explicit closed legacy production; existing CIR, material/selection binding and solver. |
+| PlasticShell | Case-insensitive block/quantity scanner | AST Model/shell/manufacturing scopes and shared values; existing manufacturing policies, candidate judgment and exact realization. |
+| Drawing | Regex Concept/Template/application/View readers; parameter text replacement; independent Static/with reader | AST declarations and expression substitution; shared typed Record catalogue; existing product compilation, projection, layout, PDF/SVG/PPTX generation. |
+| Review | Independent Review/entry block scanner | AST Review/entry scopes; existing immutable ReviewIR and proposal semantics. |
+| Recovered / evidence-linked reconstructed SheetMetal | Independent serialized-form scanners | Explicit AST productions, including quoted external identities and recovery tuples; unchanged recovery IR, evidence mapping and flattener. |
+| SheetMetal enclosure product adapter | Regex schema stripping, Record projection and Extend extraction | AST declaration spans and existing typed host Record inspection; unchanged assembly/materialization behavior. |
+
+`FirmamentSyntaxScope` is a per-compilation consumption cursor over existing
+nodes and `FirmamentSyntaxFields`, not a parser, second schema or diagnostic
+allowlist. Owners take actual fields/children and close the tree. Unexpected
+headers, unknown fields/statements and duplicate aliases reject. Local readers
+validate types, cardinality and capability before using defaults. There is no
+new whole-document regex dispatch or source macro system.
+
+The Surfacing and Collaboration libraries sit below Kernel.Firmament in the
+project graph. Their Firmament authoring classes now live in Kernel.Firmament,
+retaining their namespaces. Geometry algorithms and neutral result/ReviewIR
+contracts stay below it. This preserves repository source consumers; compiled
+external consumers of those moved classes must rebuild against Kernel.Firmament.
+Binary type forwarding back to it would introduce a dependency cycle. PlasticShell
+can reference Kernel.Firmament directly without a cycle.
+
+## Honesty findings and repairs
+
+| Finding | Reproduction / disposition |
+| --- | --- |
+| Canonical FEA solves via `fea` but normal `validate` rejects it through the mechanical owner | Confirmed before migration. Normal validation now uses UnifiedAnalysis and reports BoundNotSolved; normal build uses the same compiler and existing solver. |
+| Native Analysis could recover from failed V2 geometry parsing by scanning a Box/radius out of source | Removed. Failed V2 geometry is not admitted by a text fallback. The legacy AST production closes the Model, solid, modify, region and cut scopes and validates the opposed Z faces. Imported-resource analyses close their own document when no native body is declared. |
+| Structural tables had their own string-based schema reader | Replaced by the shared checked catalogue and scoped data identities. Missing/mistyped/extra columns and unconsumed role columns reject; duplicate role aliases reject. Invalid tables stop before indexing columns. |
+| Unknown model/domain statements or fields could disappear | Closed local AST scopes reject them. Focused tests assert rejection and absence of output, not just error sentences. |
+| Drawing enums could silently choose defaults for unknown values | Explicit Orientation, Projection, HiddenLines, BOM and nonzero finite direction validation. Invalid values reject before drawing artifacts. An explicit Orthographic projection now controls the mode; an absent projection retains the established direction-based inference. |
+| A semicolon inside quoted Review text truncated the remaining message | Confirmed by the canonical drawing's Resolution text. AST string reading preserves the complete authored message. This is an intentional ReviewIR content repair; the production drawing geometry/PDF/PPTX remain unchanged. |
+| Drawing specialization used word replacement and did not check arguments | Bound AST expression substitution; unknown, duplicate, missing and mistyped arguments reject. Shared Record checking preserves explanatory schema failures. |
+| Duplicate singleton declarations could throw through SingleOrDefault | Explicit cardinality diagnostics for the migrated owners. |
+| Invalid optional recovery values could become defaults | Authored malformed values retain an error; defaults apply only when absent. Duplicate recovery/evidence mappings reject. |
+| AutoRib unrecognized keepOut identities had no effect | Candidate owner validates names against the actual generated candidate set. Legacy unquoted hyphenated identities remain admitted; quote them in new source. |
+| Forge workbench disappeared under nested Model/Struct wrappers | A single wrapper chain is consumed structurally; material declarations belong to its innermost product. Sibling products are not pooled. Shared data still binds lexically. |
+| A surfacing negative fixture starts with `+Model` | Classified as malformed source, not a lost geometry capability. Preserve the original. The regression asserts its syntax rejection and separately tests the intended G2 degree gate after removing the accidental marker in memory. The locality fixture with the same prefix remains invalid. |
+| Native reconstructed SheetMetal and evidence-linked reconstruction both use intent: Reconstructed | Disambiguate by the existing EvidenceSource field in the AST. Native authored reconstruction still uses its established owner. |
+
+## Admission and diagnostics
+
+- Structural and Sculpting validation report the actual UnifiedStructural /
+ UnifiedSculpting route and run their engineering owner. Analysis reports
+ UnifiedAnalysis with `status: bound-not-solved` and `validationLevel:
+ BoundNotSolved`; successful binding is not a solver-convergence claim.
+- Drawing validation/build also select its actual product owner. Validation
+ exercises drawing compilation in an isolated generated-output directory and
+ removes that directory afterward. `drawing compile` remains available.
+- Analysis/Drawing build output is an artifact directory. A `.step` output path
+ rejects explicitly; export a separate geometry source when STEP is wanted.
+- Domain diagnostic strings remain on existing .NET result contracts where
+ necessary. Structured frontend diagnostics preserve code, message, owner,
+ source file and original AST spans. The shared adapter projects them through
+ the existing CLI/SDK presentation contract. Legacy lowerer errors without
+ exact provenance keep the disclosed enclosing-document location. Drawing
+ metadata errors now retain the shared `firmament-template-record-*` /
+ `firmament-template-with-*` codes when Record admission rejects before Drawing
+ policy checks. The old Drawing-only codes still describe inline metadata
+ checks; a Record failure is not relabeled or suppressed to satisfy a legacy
+ message assertion.
+- The language service consumes Structural binding without materialization.
+ Sculpting, FEA and PlasticShell editor analysis reports shared syntax and an
+ explicit compile-context requirement. It never builds sculpt geometry on
+ keystrokes or claims that syntax proves engineering admission. Their build /
+ validate owners supply the semantic/capability diagnostics. Assembly and Scene
+ retain routing precedence. No Helios-only validator was introduced.
+- Optional schemas added to the existing selector: Structural, Sculpting,
+ PlasticShell and Analysis. Explicit incompatible schemas reject.
+
+## Spelling and compatibility decisions
+
+PascalCase names constructs/types; camelCase names compiler fields. Acronym
+fields prefer `pmi`, `bom`, `uvBounds`, rather than first-letter-only `pMI`,
+`bOM`, `uVBounds`. The old acronym spellings remain aliases in the common field
+reader. Authored Record members, named generic arguments, published symbols,
+external identities and enum choices keep their declared case.
+
+Existing canonical domain fixtures retain their historical field aliases in
+this pass; the syntax guide and introductory domain examples use modern fields.
+Some formatter owner vocabularies still need consolidation. Formatting is not
+admission and must not rename user Record members. No geometry baseline was
+regenerated merely to obtain a passing comparison.
+
+The Drawing adapter retains its historical `Product:` application argument as
+an alias for the unique `Item: Product` parameter. New code should name the
+actual declared parameter. Drawing's bounded prototype surface still rejects
+unused/ambiguous policy or prototype declarations; it is not a general-purpose
+module Template binder.
+
+## Remaining language inconsistencies and decisions
+
+| ID | Evidence / inconsistency | Disposition / next owner |
+| --- | --- | --- |
+| DOMAIN-01 | Compact BodyState SectionChain uses Station/origin/size and implicit frame axes; standalone SectionChain uses explicit Section/Profile/Loft frames. | AST migration complete for both. Design a shared section representation before merging semantic lowering. Do not rename one grammar into the other or change existing frames. |
+| DOMAIN-02 | BodyState sounds general, but its constructor is the qualified housing-with-holes witness. | Separate capability boundary. Document explicitly; define a generic body-state import/constructor contract before broadening. |
+| DOMAIN-03 | Concept Drawing contains a finite list of policy requirements; ordinary Concept is a predicate/structural contract. | Preserve and validate the bounded policy vocabulary. A unified policy-as-predicate design is semantic consolidation work. |
+| DOMAIN-04 | Drawing Template has Product/Metadata parameters and a historical Product argument alias, unlike ordinary product Templates. | Explicit compatibility adapter over AST with nominal Record checks. Consolidate with the general Template binder before promising general defaults, nesting or arbitrary constraints here. |
+| DOMAIN-05 | StructuralMemberRow / StructuralJointRow / StructuralWeldRow names select catalogue roles. Paths and Node references also use legacy annotation syntax. | Preserve qualified role contracts and identities. A typed collection/role declaration needs a reviewed surface; no speculative new syntax in this pass. |
+| DOMAIN-06 | Structural Node positions accept the established implicit-mm list convention; most modern geometry fields require explicit lengths. FEA lowers to SI and native analysis uses its established [0,size] frame. | Preserve geometry and document owner rules. Do not silently recenter physics or extend unit algebra. |
+| DOMAIN-07 | Shared scalar algebra covers lengths/angles/time; FEA has physical literal conversions for stress, density, force and acceleration. Recovery also serializes area evidence. | AST owns expression boundaries; existing physical converters retain unit policy. General derived-dimensional algebra is a separate semantic change. |
+| DOMAIN-08 | Review proposal units still use bounded legacy comparison; Review does not mutate authoritative PMI. | Preserve contract. A typed proposal value model is a semantic follow-up, not a license to claim general dimensional checking. |
+| DOMAIN-09 | Complete source maps through include/Template expansion remain incomplete. | Preserve available original spans; otherwise disclose enclosing/generated context. Do not claim exact locations where unavailable. |
+| DOMAIN-10 | Some older Template/profile rendering still transports admitted bodies as text and has source-based local-name rewriting. Serialized V1 remains explicit compatibility. | These are not a new frontend route. Scope-aware AST expansion and removal of the remaining transport rewrites still belong to X2; parser migration alone does not close that debt. |
+| DOMAIN-11 | Formatter/completion metadata coverage differs across domain owners; Sculpting/FEA/PlasticShell language service needs compile context. | Track metadata/host integration separately. Compiler admission remains authority; no inferred UI validation. |
+| DOMAIN-12 | Different product kinds produce different artifacts and validation levels. Some module-specific validation branches still run their owner even when the common --parse-only flag is present. | Explicit CLI dispatch/levels above report work actually performed; no unqualified parsed-is-valid claim. Drawing/Analysis --out means directory, not STEP. A uniform per-owner parse-only option contract remains CLI work; the current Built/BoundNotSolved reports are not a promise of a cheap syntax-only pass. |
+| DOMAIN-13 | Shared Record/Static/Table binding is available in the migrated domains, but common standalone Concept/Require statements are not admitted at every Structural/Sculpting/PlasticShell product scope. | They reject explicitly rather than disappearing. A consistent requirement/contract projection across domain owners still needs semantic consolidation; do not infer it from shared syntax. |
+
+No decision requires a user choice to finish this bounded migration. The listed
+semantic reconciliations need designs and qualification; none is represented as
+already implemented. Existing geometry/kernel capability limits remain limits.
+
+## Qualification evidence
+
+Evidence is under ignored `artifacts/local/remaining-domain-ast/`.
+The initial clean source revision was `d20df8ed268ff71518bb7e4a4aa581e45556eb5e`.
+Before-source copies and artifacts were captured before their owners changed:
+3 FEA cases, 7 Structural cases, 10 Sculpting cases, 6 BodyState cases, 7
+PlasticShell cases and the canonical production drawing.
+
+| Gate | Result | Evidence |
+| --- | --- | --- |
+| Release solution build, .NET SDK 10.0.401 | Passed; 0 errors, 30 warnings retained in log | `release-build.log` |
+| Fast kernel lane | 1,076 passed | `qualified-fast.log` |
+| Complete solution regression | 5,464 passed, 0 failed, 0 skipped across 20 nonempty assemblies | `release-full.log`, `test-summary.json` |
+| Canonical owner/consumer qualification | 296 owner operations + 69 consumed modules + 4 expected external-body boundaries = 369 sources | `canonical/qualification.json` |
+| Historical domain admission/STEP hashes | 37/37 matched | `domain-parity/comparison.json` |
+| Claude X4 source corpus | 32/32 passed; no case/golden edits | `x4.log` |
+| Sheet profile and semantic corpora | 26/26 and 29/29; formed/flat parity retained | `sheet-profile.log`, `sheet-semantic.log` |
+| Fresh Structural/Sculpting/BodyState/PlasticShell STEP | 30/30 byte-identical | `parity.json` |
+| FEA analysis IR and native numerical evidence | 3/3 semantically identical after excluding actual runtime/setup timing fields | `parity.json` |
+| Production drawing PDF/SVG/PPTX | 3/3 byte-identical | `parity.json` |
+| Drawing IR | All other fields identical after excluding timing and the two documented metadata/text repairs below | `parity.json` |
+| Unknown AutoRib network | Validate/build both reject; text includes source, code and explanation; no STEP emitted | `text-diagnostic.json`, `text-diagnostic.txt` |
+| Runtime hosts / storage | No dotnet, testhost, VBCSCompiler or aetheris process remained after checks; this task's evidence occupied 140.8 MiB, with 201.0 GiB free on C: at the final sample | Final process/disk inventory |
+
+The solution also visits the FrictionLab test project, which currently discovers
+no tests; it is not counted as a passing test assembly. Qualification is local
+Windows/.NET/CLI evidence. No remote CI run or native/browser Helios interaction
+is claimed. Frozen Zig was not run: neither its compiler nor its infrastructure
+changed.
+
+The shared Static receipt prefix is now `StaticRecord` rather than
+`StaticRecord:AsterDrawingDefaults`; the named Static identity, derived-from
+reference and overrides remain available. Separately, the original Resolution
+string was truncated at its embedded semicolon by the old scanner. The complete
+new Review text is checked against the unchanged authored source, not a newly
+recorded golden. Review content is intentionally repaired; production drawing
+geometry/layout and PDF/SVG/PPTX hashes stay exact. Comparison retains both old
+and new receipts/text in `parity.json`. FEA comparisons exclude `runtime`,
+`performance`, `authoritySetup` and `constraintAndStabilizationSetup`, all timing
+measurements, and retain the analysis, materials, selections, lattice, loads,
+solver convergence/residuals, equilibrium, stress/displacement, energy and Abaqus
+checks.
+
+Useful reproduction commands (run serially from the repository):
+
+```powershell
+dotnet build Aetheris.slnx -c Release -m:1 -nr:false -p:UseSharedCompilation=false
+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter "Category!=SlowCorpus"
+dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1
+./scripts/Test-CanonicalFixtures.ps1 -NoBuild
+./scripts/qualify-firmament-domain-frontend.ps1
+python fixtures/Regression/FrontendX4/run.py
+python fixtures/Regression/SheetMetalSyntax/run.py
+python fixtures/Regression/SheetMetalSemantics/run.py
+```
+
+## Code-quality review and next semantic work
+
+The review checked scope closure, duplicate aliases, nested product ownership,
+unknown enum/default handling, propagation of messages/spans, explicit legacy
+geometry admission, shared data binding, V1 isolation and state lifetime. Piping
+and Structural now share the diagnostic-string compatibility adapter rather
+than duplicating it. New scope state is per compilation; no parser-global mutable
+state, fatality-code allowlist, source macro system or new regex recognition was
+added. Retained regex use in the migrated code is limited to existing physical
+literal/STEP/identifier or presentation conversions, not independent Firmament
+block/field readers. `git diff --check` passes.
+
+A final runtime review removed a potential editor regression: Sculpting editor
+analysis must not run full state compilation on every keystroke. Its language
+service path now reports shared syntax and an explicit compile-context notice;
+real build/validate returns the engineering diagnostics. Tests cover both this
+boundary and malformed-source syntax markers.
+
+The next semantic work is concrete:
+
+1. Replace the remaining admitted-body text transport/local-name rewriting in
+ `FirmamentV2TemplateExpansion.RenderOutput` with scope-aware AST expansion,
+ preserving public member paths, source origins and existing specialization
+ identities. This is expansion debt, not another parser/shadow milestone.
+2. Define one domain semantic-value projection so common Concept/Require checks
+ can bind domain entities consistently; Structural/Sculpting/PlasticShell
+ currently reject unsupported requirement placements explicitly.
+3. Reconcile the two section representations, typed structural collection roles
+ and domain metadata/formatter coverage using those semantic contracts. Keep
+ the unit and geometry boundaries in DOMAIN-01 through DOMAIN-13 explicit.
+
+## Verdict
+
+**Success for this production domain-reader migration.** The remaining audited
+independent domain readers now consume the unified AST, known ignored intent and
+fallback paths reject, normal validation/build use their actual owners, and the
+qualified geometry remains unchanged. The canonical corpus, full regression and
+parity gates pass.
+
+**X2 semantic consolidation remains open.** The thirteen decisions above identify
+specific language/expansion/metadata work; this report does not claim that a
+shared parser alone makes every domain syntax or semantic contract uniform.
diff --git a/docs/public/firmament/fea.md b/docs/public/firmament/fea.md
index 3d0a04f7..a0931127 100644
--- a/docs/public/firmament/fea.md
+++ b/docs/public/firmament/fea.md
@@ -5,29 +5,29 @@ Preview 3's production FEA path is `Analysis LinearElastic` with the `LinearElas
Run the qualified aluminum cantilever:
```powershell
-aetheris fea fixtures/Canonical/FEA/cantilever.firmament --out-dir artifacts/cantilever --json
+aetheris fea fixtures/Canonical/FEA/cantilever.firmament --out-dir artifacts/local/cantilever --json
```
The complete canonical shape is:
```firmament
Model CantileverWitness {
- Units: mm
- Box Beam { Size: [120mm, 20mm, 20mm] }
+ units: mm
+ Box Beam { size: [120mm, 20mm, 20mm] }
Analysis LinearElastic Cantilever {
- Body: Beam
- Material: Standard.Materials.Aluminum.6061_T6
+ body: Beam
+ material: Standard.Materials.Aluminum.6061_T6
Fixed Root {
- Region: Beam.face(-X)
- Components: [X, Y, Z]
+ region: Beam.face(-X)
+ components: [X, Y, Z]
}
Force Tip {
- Region: Beam.face(+X)
- Vector: [0N, -100N, 0N]
+ region: Beam.face(+X)
+ vector: [0N, -100N, 0N]
}
- Results: [Displacement, Strain, Stress, ReactionForce]
- Lattice: [12, 2, 2]
+ results: [Displacement, Strain, Stress, ReactionForce]
+ lattice: [12, 2, 2]
}
}
```
@@ -40,7 +40,7 @@ Native selectors preserve the body identifier: the example uses `Beam.face(-X)`
Native Box analysis also consumes one canonical face-local `Hole<Shaft>` with `On: +Z` or `On: -Z` and `End: ThroughAll`. The analysis compiler uses the parsed diameter and center, so the opening removes occupied material. It maps the Box-centered CAD coordinates into the existing native analysis `[0, Size]` coordinate frame. Multiple semantic holes, side holes, counterbores, blind holes, construction-plane placements, and mixed hole/edge-finish modifications require the exported STEP analysis route and fail with `firmament-analysis-native-feature-unsupported` in this native lane. The complete [investor plate witness](../../../fixtures/InvestorPitch/loaded-plate-native.firmament) exercises this path.
-The `build` command consumes geometry sources, while `fea` consumes sources containing `Analysis`. For a shared geometry and analysis demonstration, export the geometry file first and analyze that exact file with `inlineSTEP`; the report records the geometry hash. See [the reproducible investor demonstration](../investor-pitch.md).
+`validate` binds an Analysis through its production AST owner and reports `BoundNotSolved`, not unqualified geometry/solver success. `build` recognizes the same Analysis source and runs the existing solver; its `--out` is an analysis artifact directory. `fea --out-dir` remains supported. Unknown settings, malformed geometry, unsupported native features and unresolved selections reject before solving. Solver convergence still requires execution. For a shared geometry and analysis demonstration, export the geometry file first and analyze that exact file with `inlineSTEP`; the report records the geometry hash. See [the reproducible investor demonstration](../investor-pitch.md).
## Experimental thin-wall analysis of native Sheet Metal
diff --git a/docs/public/firmament/plastic-shell.md b/docs/public/firmament/plastic-shell.md
index 0485fe67..a12b084f 100644
--- a/docs/public/firmament/plastic-shell.md
+++ b/docs/public/firmament/plastic-shell.md
@@ -1,5 +1,14 @@
# PlasticShell
+The authoring reader consumes the unified AST. Prefer camelCase fields;
+historical PascalCase fields remain aliases. Unknown statements, fields,
+duplicate aliases and unsupported placements reject before manufacturing.
+An optional `schema PlasticShell` selects the same owner. Compile-time data
+uses the shared Record/Static/Template binder. For AutoRib `keepOut`, quote
+network identities such as `"perimeter-network"` and `"gate-oriented-fan"`;
+the historical unquoted hyphenated forms remain bounded compatibility aliases.
+Unknown network names reject instead of having no effect.
+
`PlasticShell` is Aetheris's manufacturing-first domain for injection-molded product definitions. Wall thickness, tooling direction, parting, and reinforcement intent live in the domain model rather than as a sequence of cleanup features.
```firmament
diff --git a/docs/public/firmament/sculpting.md b/docs/public/firmament/sculpting.md
index 969ec7dd..e0602a3e 100644
--- a/docs/public/firmament/sculpting.md
+++ b/docs/public/firmament/sculpting.md
@@ -1,5 +1,14 @@
# Bounded mathematical sculpting and patch replacement
+Authoring uses the shared AST and compile-time value binder, with camelCase
+fields and historical PascalCase aliases. A single Model owns its states,
+SurfacePatch and compact SectionChain declarations and selects one `output`.
+Unknown statements/fields, duplicate singleton operations and unsupported header
+placements reject. `schema Sculpting` is optional. The current `BodyState`
+constructor remains the bounded housing witness with explicit holes; it is not
+a general arbitrary-body constructor. Its compact Station-based SectionChain
+form remains distinct from the framed Profile-based SectionChain frontend.
+
SURF-X0 supports bounded mathematical sculpting and locality-preserving region modification. SURF-X1 adds direct rectangular patch replacement. SURF-X1a closes the trim path for the admitted housing: qualified surface intersections derive the outer boundary, face-local pcurves qualify every trim, circular inner loops preserve openings, and an imported `ADVANCED_FACE` can receive a bounded support-surface graft. SURF-X2 adds a qualified two-support crown-to-planar-shoulder `BlendBoundary` that generates and deterministically judges exact non-rational polynomial candidates. This is not full general surfacing.
Sculpting is a lower-authority escape hatch for geometry that an engineering feature such as `Boss`, `Pocket`, `Hole`, `Sweep`, `Fillet`, or `Chamfer` cannot express. Prefer those features whenever they carry the intended engineering meaning.
diff --git a/docs/public/firmament/structural.md b/docs/public/firmament/structural.md
index bcd11b89..5f2d37be 100644
--- a/docs/public/firmament/structural.md
+++ b/docs/public/firmament/structural.md
@@ -1,6 +1,6 @@
# Structural members and weldments
-Aetheris X2 authors a weldment as a semantic structure, not as a Boolean union of intersecting solids:
+Firmament authors a weldment as a semantic structure, not as a Boolean union of intersecting solids:
```text
Structure → Member AIR → Joint resolution → Assembly Interfaces → finished members → AP242 Assembly + Cut List
@@ -8,6 +8,14 @@ Structure → Member AIR → Joint resolution → Assembly Interfaces → finish
The bounded X2 workflow supports explicit 3D nodes, straight paths, constant structural sections, member orientation, catalog material resolution, two-member butt and polygonal miter joints, fillet-weld requirements, and deterministic JSON cut lists. Curved members, tube coping, three-member miters, connection design, weld sizing, and structural FEA are future work.
+The shared AST admits a standalone Structural document or one nested `Model`/`Struct`
+owner chain, optionally selected with `schema Structural`. `Structure` owns its
+Nodes and Paths; Section, Member, Joint, Weld, Record and Static Table declarations
+are peers in the enclosing product scope. Nested names do not become global.
+Use camelCase compiler fields; historical PascalCase aliases remain supported.
+Unknown/duplicate fields and statements reject. Table schemas and values use the
+same checked Record/Static binder as other Firmament products.
+
## 1. Author the structure graph
Nodes are structurally meaningful locations. Paths retain stable identity, endpoints, direction, length, and source provenance.
@@ -28,20 +36,20 @@ X2 paths are straight segments and every path has exactly one Member assignment.
Section geometry and material identity are separate. X2 admits `Standard.Structural.SquareTube`, `RectangularTube`, `RoundTube`, `Angle`, `FlatBar`, and `RoundBar`.
-Tube sections are genuinely hollow. Square/rectangular tube fields are `Width`, optional `Height`, and `Thickness`; round sections use `Diameter`; angles use `Width`, `Height`, and `Thickness`.
+Tube sections are genuinely hollow. Square tubes use `width` and `thickness`; an optional `height` must equal `width`. Rectangular tubes require `width`, `height` and `thickness`; round sections use `diameter`; angles use `width`, `height`, and `thickness`.
```firmament
Section RHS {
- Kind: Standard.Structural.SquareTube;
- Width: 40mm;
- Thickness: 3mm;
+ kind: Standard.Structural.SquareTube;
+ width: 40mm;
+ thickness: 3mm;
}
Member Horizontal {
- Path: Horizontal;
- Section: RHS;
- Material: Standard.Materials.Steel.ASTM_A36;
- Orientation: [0,0,1];
+ path: Horizontal;
+ section: RHS;
+ material: Standard.Materials.Steel.ASTM_A36;
+ orientation: [0,0,1];
}
```
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index ad99e126..150d4ba0 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -48,6 +48,16 @@ Normal mechanical validation performs engineering compilation in memory.
`--explain` adds developer information about admission and the chosen frontend.
See [diagnostics](../reference/diagnostics.md) for interpreting failures.
+Analysis is a deliberate exception to a geometry-only validation claim:
+`validate` binds its geometry, material, selections and analysis settings and
+reports `BoundNotSolved` (`status: "bound-not-solved"`). `build` runs the same
+analysis compiler and the existing solver, writing analysis artifacts to the
+`--out` directory. `fea --out-dir` remains the dedicated spelling. Static binding
+does not promise solver convergence. Drawing sources also dispatch through their production owner in `validate` and
+`build`; `drawing compile --out-dir` remains available. Their output is a
+manufacturing drawing artifact directory. Passing a `.step` output path to an
+Analysis or Drawing build rejects explicitly; export the geometry source separately.
+
## How to read the language
The useful organizing analogy is `Model` as a class-like artifact owner, `Struct`
@@ -899,9 +909,13 @@ remain within the selected domain; it cannot change the schema after admission.
| `SectionChain` | [Framed section chains](section-chains.md). |
| `Garment` | [Panels, stitch interfaces and fitting](garments.md). |
| `Piping` | [Ports, connections and routing](piping.md). |
+| `Structural` | [Nodes, straight members and weldments](structural.md). |
+| `Sculpting` | [Immutable body and surfacing states](sculpting.md). |
+| `PlasticShell` | [Molded shell manufacturing intent](plastic-shell.md). |
+| `Analysis` | [Linear-elastic analysis](fea.md). |
This selector does not list every Firmament root or product domain. Assembly,
-Scene, SheetMetal and structural sources have their own entry forms. Piping
+Scene, SheetMetal and Drawing have their own entry forms. Piping
uses its documented Model/PipingSystem form, optionally with `schema Piping`.
Do not invent `schema Assembly` or wrap arbitrary domain declarations in a Model.
@@ -1095,6 +1109,21 @@ Validate the consuming artifact after formatting.
## Current language seams
+Structural, Sculpting, PlasticShell, Analysis, Drawing and Review now consume
+the same recursive-descent syntax tree as ordinary mechanical source. Their
+semantic owners retain distinct engineering capabilities and close their own
+statement/field scopes. Unknown fields, duplicate aliases, unknown statements
+and unsupported header placements reject; shared parsing does not make every
+operation legal in every domain.
+
+Use `pmi` and `bom` for acronym fields. Historical `PMI`/`BOM` and the old
+first-letter-only `pMI`/`bOM` aliases remain admitted by the common field reader.
+Record member names remain authored, case-sensitive data; do not blindly change
+Drawing metadata members such as `PartNumber` or structural Table column names.
+Some older domain fixtures and domain-specific formatter vocabularies still use
+PascalCase field aliases. The compiler admits camelCase directly; formatting
+is not a semantic migration or an admission check.
+
The preferred style is more consistent than the grammar enforced by every
owner. Author-visible differences remain in casing, points/lists, Pattern
binders, terminators, root/scope rules, frame/selector types, and meanings of
@@ -1108,6 +1137,12 @@ described in the [implementation report](../../release/FIRMAMENT-DIRECTIVES-AND-
The [decision register](../../development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md)
preserves the original authoring audit and later migration dispositions.
+The [remaining-domain AST report](../../development/FIRMAMENT-REMAINING-DOMAIN-AST-2026-10-18.md)
+records scope, compatibility evidence and remaining semantic inconsistencies,
+including the two distinct SectionChain forms, Drawing policy Concepts, and
+Structural table-role conventions. These are explicit design follow-ups, not
+permission to silently discard source.
+
Use [supported features](../reference/supported-features.md) for capability
boundaries and the linked domain guides for detailed syntax. Proposals and
migration reports explain design/history; they do not grant source admission.