Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Support Profile values and bind sheet metal through syntax

Yuechen Liba81ffda0041
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
index 3f61fe85..05b61933 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
@@ -28,6 +28,7 @@ internal static class ClosedBoundary2Authoring
public static Result? Expand(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null)
{
+ source = ExpandProfileValues(source, diagnostics);
// Template bodies have local names and unbound dimensions. Their selected
// specializations pass through this lowering after ordinary template binding.
var templates = FirmamentV2TemplateExpansion.DeclarationSpans(source, diagnostics).ToList();
@@ -121,10 +122,55 @@ internal static class ClosedBoundary2Authoring
internal override ExpressionSyntax Expression(ExpressionSyntax expression) => values.NominalExpression(expression);
}
+ // A compact Profile value delegates to the existing boundary and immutable
+ // Profile owners. This is one AST production at the existing lowering seam.
+ private static string ExpandProfileValues(string source, List<string> diagnostics)
+ {
+ var syntax = FirmamentSyntaxParser.Parse(source).Document;
+ var changes = new List<(int Start, int Length, string Text)>();
+ var coveredUntil = -1;
+ foreach (var profile in FirmamentSyntaxTraversal.Declarations(syntax)
+ .Where(d => d.Type.Name.Text == "Profile" && d.Name is not null && d.Initializer is not null
+ // Specializations and historical Template calls belong to the
+ // existing Template owner, before compact value admission.
+ && d.Initializer is not (SpecializationSyntax or CallSyntax)
+ && !d.Modifiers.Any(m => m.Name.Text == "Template"))
+ .OrderBy(d => d.Span.Start).ThenByDescending(d => d.Span.Length))
+ {
+ if (profile.Span.Start < coveredUntil) continue;
+ coveredUntil = profile.Span.Start + profile.Span.Length;
+ if (profile.Body is not null || profile.Clauses.Count > 0 || profile.Modifiers.Count > 0
+ || profile.Parameters.Count > 0 || profile.HasParameterList || profile.Annotation is not null || profile.ResultType is not null || profile.Occurrence)
+ { diagnostics.Add(Prefix + "profile-value-header:" + profile.Name!.Text); continue; }
+ var name = profile.Name!.Text;
+ string replacement;
+ if (profile.Initializer is ObjectSyntax { Name: null, Type: ReferenceSyntax type } value && IsBoundaryType(type.Name.Text))
+ {
+ var boundaryName = name + "__Boundary";
+ if (FirmamentSyntaxTraversal.Declarations(syntax).Any(d => d.Name?.Text == boundaryName))
+ { diagnostics.Add(Prefix + "duplicate-name:" + boundaryName); continue; }
+ var boundary = new DeclarationSyntax(new(type.Name, [], type.Span), new(boundaryName, value.Span),
+ [], [], null, null, [], null, value.Body, false, value.Span);
+ replacement = FirmamentSyntaxWriter.Statement(boundary) + $"\nProfile {name} {{ From: {boundaryName}; }}";
+ }
+ else if (FirmamentSyntaxValues.Reference(profile.Initializer) is { } reference)
+ replacement = $"Profile {name} {{ From: {reference}; }}";
+ else
+ { diagnostics.Add(Prefix + "profile-value-unsupported:" + name); continue; }
+ changes.Add((profile.Span.Start, profile.Span.Length, replacement));
+ }
+ foreach (var change in changes.OrderByDescending(c => c.Start))
+ source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
+ return source;
+ }
+
+ private static bool IsBoundaryType(string type) => type is "Rect2" or "Square2" or "Circle2" or "Ellipse2" or "Slot2"
+ or "RoundedRect2" or "SmoothRoundedRect2" or "Triangle2" or "Polygon2" or "RegularPolygon2";
+
private static IEnumerable<DeclarationSyntax> BoundaryDeclarations(DocumentSyntax syntax) =>
FirmamentSyntaxTraversal.Declarations(syntax)
.Where(d => d.Name is not null && d.Body is not null && d.Modifiers.All(m => m.Name.Text == "Concept")
- && d.Type.Name.Text is "Rect2" or "Square2" or "Circle2" or "Ellipse2" or "Slot2" or "RoundedRect2" or "SmoothRoundedRect2" or "Triangle2" or "Polygon2" or "RegularPolygon2");
+ && IsBoundaryType(d.Type.Name.Text));
private static Shape? Bind(string source, DeclarationSyntax declaration, FirmamentSyntaxFields body, List<string> diagnostics)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
index 980eb53e..b7e50be2 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
@@ -14,7 +14,6 @@ public static class ProfileAuthoringParser
{
public const string SegmentEndpointMustReferenceNamedPoint = "ProfileSegmentEndpointMustReferenceNamedPoint";
private const double Tolerance = 1e-9;
- private static readonly Regex ConstructionPlaneDeclaration = new(@"\bConstruction\s+Plane\s+(?<name>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*\}", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex Segment = new(@"\bSegment\s+(?<n>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*From\s*:\s*(?<from>[\w.]+)\s*;?\s*To\s*:\s*(?<to>[\w.]+)(?:\s*;?\s*Sweep\s*:\s*(?<sweep>Clockwise|CounterClockwise))?", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex SpanHeader = new(@"\bSpan\s*<\s*(?<type>[A-Za-z_]\w*)\s*>\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
@@ -366,7 +365,7 @@ public static class ProfileAuthoringParser
var boundary = Property(body, "Boundary");
var planeDiagnostics = new List<string>();
var parentPlane = ResolveConstructionPlane(source, parent, planeDiagnostics);
- if (!ConstructionPlaneDeclaration.Matches(source).Cast<Match>().Any(match => match.Groups["name"].Value == parent) || parentPlane is null)
+ if (!ConstructionPlanes(source).Any(plane => plane.Name?.Text == parent) || parentPlane is null)
{ diagnostics.Add($"firmament-span-parent-not-found:{name}"); continue; }
if (boundary is null) { diagnostics.Add($"firmament-span-surface-boundary-open:{name}"); continue; }
var boundaryProfile = ResolveNamedProfile(source, boundary, out var boundaryDiagnostics);
@@ -1144,10 +1143,16 @@ public static class ProfileAuthoringParser
diagnostics.Add($"profile-guide-missing:{segment}:{trace}"); return null;
}
+ private static IEnumerable<DeclarationSyntax> ConstructionPlanes(string source) =>
+ SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)
+ .Where(d => d.Type.Name.Text == "Plane" && d.Modifiers.Any(m => m.Name.Text == "Construction"));
+
private static ConstructionPlane? ResolveConstructionPlane(string source, string? frame, List<string> diagnostics)
{
if (frame is null) return ConstructionPlane.WorldXY;
- var plane = ConstructionPlaneDeclaration.Matches(source).Cast<Match>().SingleOrDefault(x => x.Groups["name"].Value == frame);
+ var planes = ConstructionPlanes(source).Where(d => d.Name?.Text == frame).ToArray();
+ if (planes.Length > 1) { diagnostics.Add($"profile-frame-duplicate:{frame}"); return null; }
+ var plane = planes.SingleOrDefault();
if (plane is null)
{
if (frame == "XY") return ConstructionPlane.WorldXY;
@@ -1163,8 +1168,13 @@ public static class ProfileAuthoringParser
diagnostics.Add($"profile-frame-unresolved:{frame}:using must name a declared Concept Struct or Construction Plane.");
return null;
}
- if (!ConceptIrResolver.TryResolvePlane(source, plane.Groups["trace"].Value, out var conceptPlane, out var traceDiagnostic) || conceptPlane is null) { diagnostics.Add(traceDiagnostic ?? "ConstructionPlaneTraceMissing"); return null; }
- if (!ConstructionPlane.TryTrace("construction:" + frame, conceptPlane, $"offset:{plane.Index}", out var result, out var frameDiagnostic)) diagnostics.Add(frameDiagnostic ?? "ConstructionPlaneFrameInvalid");
+ var before = diagnostics.Count;
+ var fields = new FirmamentSyntaxFields(plane, diagnostics);
+ var trace = fields.Reference("Trace");
+ fields.Complete();
+ if (trace is null || diagnostics.Count > before) { diagnostics.Add($"profile-frame-trace-invalid:{frame}"); return null; }
+ if (!ConceptIrResolver.TryResolvePlane(source, trace, out var conceptPlane, out var traceDiagnostic) || conceptPlane is null) { diagnostics.Add(traceDiagnostic ?? "ConstructionPlaneTraceMissing"); return null; }
+ if (!ConstructionPlane.TryTrace("construction:" + frame, conceptPlane, $"offset:{plane.Span.Start}", out var result, out var frameDiagnostic)) diagnostics.Add(frameDiagnostic ?? "ConstructionPlaneFrameInvalid");
return result;
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs
index bb99e3eb..fa4fe989 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs
@@ -2,7 +2,7 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
/// <summary>Literal and bounded dimensional binding over syntax. This preserves the
/// existing profile evaluator's one-unit, dimension-0/1 arithmetic contract.</summary>
-internal static class FirmamentSyntaxValues
+public static class FirmamentSyntaxValues
{
public static string? Reference(ExpressionSyntax? value) => value switch
{
@@ -53,7 +53,7 @@ internal static class FirmamentSyntaxValues
/// <summary>Each semantic owner consumes its actual fields, then closes its scope.
/// No second field schema or spelling allowlist is maintained here.</summary>
-internal sealed class FirmamentSyntaxFields(DeclarationSyntax declaration, List<string> diagnostics, string? implicitUnit = null)
+public sealed class FirmamentSyntaxFields(DeclarationSyntax declaration, List<string> diagnostics, string? implicitUnit = null)
{
private readonly HashSet<FieldSyntax> consumed = [];
public DeclarationSyntax Declaration => declaration;
diff --git a/Aetheris.SheetMetal.Tests/SheetMetalUnifiedProfileTests.cs b/Aetheris.SheetMetal.Tests/SheetMetalUnifiedProfileTests.cs
new file mode 100644
index 00000000..8f3f67e9
--- /dev/null
+++ b/Aetheris.SheetMetal.Tests/SheetMetalUnifiedProfileTests.cs
@@ -0,0 +1,140 @@
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Materializer;
+using Xunit;
+
+namespace Aetheris.SheetMetal.Tests;
+
+public sealed class SheetMetalUnifiedProfileTests
+{
+ private static string Source(string file)
+ {
+ var directory = new DirectoryInfo(AppContext.BaseDirectory);
+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;
+ return File.ReadAllText(Path.Combine(directory!.FullName, "fixtures/Regression/SheetMetalSyntax", file + ".firmament"));
+ }
+
+ [Fact]
+ public void SharedCompactProfilePreservesFormedStepAndFlatMaterial()
+ {
+ var modern = SheetMetalFirmament.Compile(Source("modern-bracket"));
+ var legacy = SheetMetalFirmament.Compile(Source("legacy-bracket"));
+ Assert.True(modern.IsSuccess, string.Join("\n", modern.Diagnostics.Select(d => d.Message)));
+ Assert.True(legacy.IsSuccess, string.Join("\n", legacy.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(Step242Exporter.ExportBody(legacy.Part!.FormedBody!).Value, Step242Exporter.ExportBody(modern.Part!.FormedBody!).Value);
+ Assert.Equal(legacy.FlatPattern!.MaterialArea, modern.FlatPattern!.MaterialArea);
+ Assert.Equal(legacy.FlatPattern.Bounds, modern.FlatPattern.Bounds);
+ Assert.Equal(legacy.Part.Regions.Select(r => r.StableId), modern.Part.Regions.Select(r => r.StableId));
+ Assert.True(FirmamentBuildAndExport.CompileSource(Source("mechanical")).IsSuccess);
+ var profile = ProfileAuthoringParser.ResolveNamedProfile(Source("modern-bracket"), "blank", out var errors);
+ Assert.Empty(errors);
+ Assert.Equal(4000, ResolvedProfile2DValidator.Validate(profile!).SignedArea, 8);
+ }
+
+ [Fact]
+ public void ModernSlotHasExactRoundedGeometryAndLegacySlotStaysRectangular()
+ {
+ var source = Source("modern-bracket");
+ var flange = " Flange wall { from: deck.Rear; length: 30mm; angle: 90deg; insideRadius: 2mm; direction: Up }";
+ source = source.Replace(flange, "", StringComparison.Ordinal);
+ var rounded = SheetMetalFirmament.Compile(source.Replace("Rect2 { center: [0mm, 0mm]; size: [12mm, 6mm] }",
+ "Slot2 { center: [0mm, 0mm]; length: 12mm; width: 6mm }", StringComparison.Ordinal));
+ Assert.True(rounded.IsSuccess, string.Join("\n", rounded.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(4000 - (6 * 6 + Math.PI * 9), rounded.FlatPattern!.MaterialArea!.Value, 7);
+ Assert.Equal(2, Assert.Single(rounded.Part!.Features).ExactContour!.OuterLoop.Segments.Count(s => s.Geometry is LineArcCircularArc2D));
+ Assert.True(Step242Exporter.ExportBody(rounded.Part.FormedBody!).IsSuccess);
+ var legacy = SheetMetalFirmament.Compile(Source("legacy-bracket").Replace("Profile: Rectangle { Length: 12mm; Width: 6mm; }", "Profile: Slot { Length: 12mm; Width: 6mm; }", StringComparison.Ordinal));
+ var rectangular = SheetMetalFirmament.Compile(Source("legacy-bracket"));
+ Assert.True(legacy.IsSuccess);
+ Assert.Equal(rectangular.FlatPattern!.MaterialArea, legacy.FlatPattern!.MaterialArea);
+ }
+
+ [Theory]
+ [InlineData("size: [80mm, 50mm]", "szie: [80mm, 50mm]", "szie")]
+ [InlineData("profile: opening", "profile: missing", "missing")]
+ [InlineData("at: Point2(30mm, 20mm)", "at: Point2(30mm, 20mm); heigth: 2mm", "heigth")]
+ [InlineData("Base deck {", "Base deck on XZ {", "placement")]
+ [InlineData("Base deck {", "Base: Rectangle(1mm, 1mm); Base deck {", "one Base")]
+ [InlineData("Rect2 { center: [40mm, 25mm]; size: [80mm, 50mm] }", "Circle2 { center: [40mm, 25mm]; radius: 20mm }", "rectangular")]
+ [InlineData("Rect2 { center: [0mm, 0mm]; size: [12mm, 6mm] }", "Ellipse2 { center: [0mm, 0mm]; axisLengths: [12mm, 6mm] }", "ellipses")]
+ public void UnsupportedOrUnknownProfileIntentCannotBuild(string before, string after, string detail)
+ {
+ var result = SheetMetalFirmament.Compile(Source("modern-bracket").Replace(before, after, StringComparison.Ordinal));
+ Assert.False(result.IsSuccess);
+ Assert.Null(result.Part);
+ Assert.Contains(result.Diagnostics, d => d.Message.Contains(detail, StringComparison.OrdinalIgnoreCase));
+ }
+
+ [Fact]
+ public void ProfileOriginBecomesPhysicalBaseOriginRatherThanBeingRecentered()
+ {
+ var source = Source("modern-bracket").Replace("center: [40mm, 25mm]", "center: [50mm, 45mm]", StringComparison.Ordinal);
+ var result = SheetMetalFirmament.Compile(source);
+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(10, result.Spec!.Base.Origin.X);
+ Assert.Equal(20, result.Spec.Base.Origin.Y);
+ }
+
+ [Fact]
+ public void CompactProfileSpecializesThroughTheExistingTemplateOwner()
+ {
+ var source = Source("mechanical-template");
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics));
+ }
+
+ [Fact]
+ public void ReusedProfileGetsDistinctCutIdentitiesAndRetainsSourceProvenance()
+ {
+ var source = Source("modern-bracket").Replace("Cut port {", "Cut secondPort { on: deck; profile: opening; at: Point2(60mm, 20mm) }\n Cut port {", StringComparison.Ordinal);
+ var result = SheetMetalFirmament.Compile(source);
+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics.Select(d => d.Message)));
+ var segments = result.Part!.Features.SelectMany(f => f.ExactContour!.OuterLoop.Segments).ToArray();
+ Assert.Equal(8, segments.Select(s => s.StableId).Distinct(StringComparer.Ordinal).Count());
+ Assert.All(segments, s => Assert.NotNull(s.Provenance.TracedFrom));
+ }
+
+ [Fact]
+ public void XzProfileCannotSilentlyBecomeAnXySheetBase()
+ {
+ var result = SheetMetalFirmament.Compile(Source("unsupported-xz"));
+ Assert.False(result.IsSuccess);
+ Assert.Null(result.Part);
+ Assert.Contains(result.Diagnostics, d => d.Message.Contains("sheetmetal-profile-frame-unsupported", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void LegacyCircleCannotSilentlyDiscardRectangularDimensions()
+ {
+ var source = Source("legacy-bracket").Replace("Rectangle { Length: 12mm; Width: 6mm; }", "Circle { Diameter: 6mm; Width: 3mm; }", StringComparison.Ordinal);
+ var result = SheetMetalFirmament.Compile(source);
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics, d => d.Message.Contains("Width", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("Circle")]
+ [InlineData("Slot")]
+ [InlineData("Rectangle")]
+ public void DeclaredProfileNamesResolveBeforeLegacyShapeTags(string name)
+ {
+ var result = SheetMetalFirmament.Compile(Source("modern-bracket").Replace("opening", name, StringComparison.Ordinal));
+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics.Select(d => d.Message)));
+ Assert.NotNull(Assert.Single(result.Part!.Features).ExactContour);
+ }
+
+ [Theory]
+ [InlineData("Circle2 { center: [0mm, 0mm]; radius: 10mm }", 314.1592653589793)]
+ [InlineData("Slot2 { center: [0mm, 0mm]; length: 20mm; width: 8mm }", 146.2654824574367)]
+ [InlineData("RoundedRect2 { center: [0mm, 0mm]; size: [20mm, 10mm]; radius: 2mm }", 196.5663706143592)]
+ public void CompactMechanicalShapesUseTheirExistingExactArea(string shape, double expectedArea)
+ {
+ var source = Source("mechanical").Replace("Rect2 { center: [40mm, 25mm]; size: [80mm, 50mm] }", shape, StringComparison.Ordinal);
+ var profile = ProfileAuthoringParser.ResolveNamedProfile(source, "blank", out var diagnostics);
+ Assert.Empty(diagnostics);
+ Assert.Equal(expectedArea, ResolvedProfile2DValidator.Validate(profile!).SignedArea, 8);
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(built.IsSuccess, string.Join("\n", built.Diagnostics));
+ }
+}
diff --git a/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs b/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs
index a15690cd..e4dc1966 100644
--- a/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs
+++ b/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs
@@ -1,4 +1,3 @@
-using System.Globalization;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Brep;
@@ -11,6 +10,7 @@ using Aetheris.Kernel.Core.Topology;
using Aetheris.Kernel.Firmament.FirmamentV2;
using Aetheris.Kernel.Firmament.Materializer;
using Aetheris.Surfacing;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
namespace Aetheris.SheetMetal;
@@ -29,7 +29,10 @@ public sealed record AuthoredSheetTerminationSpec(
SheetBendTerminationTreatment Treatment,double? Setback=null,double? Depth=null,double? Radius=null);
public sealed record AuthoredSheetCutSpec(
string Name, string RegionName, SheetFeatureKind Kind, double X, double Y,
- double? Diameter, double? Width, double? Length, bool ExactCapsule = false);
+ double? Diameter, double? Width, double? Length, bool ExactCapsule = false)
+{
+ public ResolvedProfile2D? Profile { get; init; }
+}
public sealed record SheetMetalConstructionSpec(
string Name, double Thickness, string? Material, double KFactor, AuthoredSheetBaseSpec Base,
IReadOnlyList<AuthoredSheetFlangeSpec> Flanges, IReadOnlyList<AuthoredSheetCutSpec> Cuts,
@@ -48,14 +51,11 @@ public sealed record SheetMetalConstructionSpec(
internal static class AuthoredSheetMetalCompiler
{
private const RegexOptions Rx = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Singleline;
- private const string Number = @"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)";
public static SheetMetalAuthoringResult Compile(string source, string sourcePath)
{
var parseStarted=Stopwatch.GetTimestamp();
var diagnostics = new List<SheetMetalDiagnostic>();
- var header = Regex.Match(source, @"\bSheetMetal\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)(?:\s*:\s*(?<concept>[A-Za-z_][A-Za-z0-9_]*))?\s*\{", Rx);
- if (!header.Success) return Fail("Expected `SheetMetal <Name> { ... }`.");
var modelStyleHole = Regex.Match(source, @"\bHole\s*<\s*(?<variant>[A-Za-z_][A-Za-z0-9_]*)\s*>", Rx);
if (modelStyleHole.Success)
return Fail(
@@ -65,24 +65,54 @@ internal static class AuthoredSheetMetalCompiler
return Fail(
"Sheet Metal PMI does not use the Model-domain `Datum` record or axis-face targets. Add a `Manufacturing <Release> { ... }` block and declare `DatumFeature <Label> { Target: <named-sheet-region>; }` inside `Pmi`; for example, `DatumFeature A { Target: Base; }`.",
"sheetmetal-pmi-domain-syntax");
- if (!Scalar(source, "Thickness", "mm", out var thickness) || thickness <= 0)
+ var syntax = FirmamentSyntaxParser.Parse(source);
+ var syntaxErrors = new List<string>();
+ var owners = syntax.Document.Statements.OfType<DeclarationSyntax>()
+ .Where(d => d.Type.Name.Text == "SheetMetal" && d.Body is not null && d.Modifiers.Count == 0).ToArray();
+ if (owners.Length != 1) return Fail($"Expected one concrete SheetMetal document; found {owners.Length}.");
+ var owner = owners[0];
+ if (owner.Body is null || owner.Name is null) return Fail("Expected one named SheetMetal document.");
+ var documentName = owner.Name.Text;
+ // ProfileDelta and semantic-layout declarations retain their domain owners.
+ // Their syntax is admitted there; this owner closes its actual sheet body.
+ var bodyErrors = syntax.Diagnostics.Where(d => d.SourceSpan is { } span && span.Start >= owner.Span.Start
+ && span.Start < owner.Span.Start + owner.Span.Length).ToArray();
+ if (bodyErrors.Length > 0) return Fail(string.Join("\n", bodyErrors.Select(d => d.Message)), "sheetmetal-syntax-invalid");
+ var root = new FirmamentSyntaxFields(owner with { Annotation = null,
+ Body = owner.Body with { Statements = owner.Body.Statements.OfType<FieldSyntax>().Cast<StatementSyntax>().ToArray() } }, syntaxErrors);
+ if (!root.Measure("Thickness", "mm", out var thickness) || thickness <= 0)
return Fail("Thickness must be a positive millimetre value.");
- var material = Quoted(source, "Material");
- var k = Scalar(source, "KFactor", null, out var parsedK) ? parsedK : SheetMetalFlattenPolicy.Default.KFactor;
- if (k is < 0 or > 1) return Fail("KFactor must be between zero and one.");
-
- AuthoredSheetBaseSpec? baseSpec = null;
- var legacyBase = Regex.Match(source, $@"\bBase\s*:\s*Rectangle\s*\(\s*(?<w>{Number})\s*mm\s*,\s*(?<d>{Number})\s*mm\s*\)\s*;", Rx);
- if (legacyBase.Success) baseSpec = new("Base", Num(legacyBase, "w"), Num(legacyBase, "d"));
+ var material = root.Reference("Material");
+ var k = root.Number("KFactor", "", SheetMetalFlattenPolicy.Default.KFactor);
+ if (!double.IsFinite(k) || k is < 0 or > 1) return Fail("KFactor must be between zero and one.");
+ var legacyBaseValue = root.Take("Base");
+ var intent = root.Reference("Intent");
+ if (intent is not (null or "Authored" or "Reconstructed" or "Manufacturing")
+ && !syntax.Document.Statements.OfType<DeclarationSyntax>().Any(d => d.Type.Name.Text == "Struct"
+ && d.Modifiers.Any(m => m.Name.Text == "Concept") && d.Name?.Text == intent))
+ return Fail("Intent requires Authored, Reconstructed, Manufacturing or a declared Concept Struct layout.");
+ root.Complete();
+ foreach (var statement in owner.Body.Statements.Where(s => s is not FieldSyntax))
+ if (statement is not DeclarationSyntax declaration || !(declaration.Type.Name.Text is "Base" or "Flange" or "Hole" or "Cut" or "Manufacturing" or "Pmi"
+ || SheetMetalSemanticLayoutParser.OwnsDeclaration(declaration.Type.Name.Text)))
+ syntaxErrors.Add($"sheetmetal-statement-unknown: Unknown statement in SheetMetal '{owner.Name?.Text}': {(statement as DeclarationSyntax)?.Type.Name.Text ?? "expression"}.");
+ var legacyBase = legacyBaseValue is not null;
+ AuthoredSheetBaseSpec? baseSpec;
+ var bases = Blocks(source, "Base", syntaxErrors);
+ if (bases.Count > 1 || legacyBase && bases.Count > 0)
+ return Fail("Declare exactly one Base; do not combine the legacy Base field with a named Base.", "sheetmetal-base-duplicate");
+ if (legacyBaseValue is CallSyntax { Target: ReferenceSyntax { Name.Text: "Rectangle" }, Arguments.Count: 2 } rectangle
+ && rectangle.Arguments.All(a => a.Name is null && a.Default is null)
+ && FirmamentSyntaxValues.TryMeasure(rectangle.Arguments[0].Value, "mm", out var w)
+ && FirmamentSyntaxValues.TryMeasure(rectangle.Arguments[1].Value, "mm", out var d))
+ baseSpec = new("Base", w, d);
else
{
- var named = Blocks(source, "Base").SingleOrDefault();
- if (named is not null && Scalar(named.Body, "Width", "mm", out var width) &&
- (Scalar(named.Body, "Height", "mm", out var depth) || Scalar(named.Body, "Depth", "mm", out depth)))
- baseSpec = new AuthoredSheetBaseSpec(named.Name, width, depth) { Origin = Point3(named.Body, "Origin") ?? Point3D.Origin };
+ var named = bases.SingleOrDefault();
+ baseSpec = named is null ? null : SheetMetalProfileBinding.Base(source, named.Name, named.Fields, syntaxErrors);
}
if (baseSpec is null || baseSpec.Width <= 0 || baseSpec.Depth <= 0)
- return Fail("A positive rectangular base is required (`Base: Rectangle(w, d)` or named `Base <Name> { Profile: Rectangle { Width; Height; } }`).");
+ return Fail(syntaxErrors.Count > 0 ? string.Join("\n", syntaxErrors) : "A positive rectangular base Profile is required.", "sheetmetal-base-profile-invalid");
// Attachment paths are resolved fully by the semantic-layout pass after
// all region dimensions are known. This small pre-scan exists only so
@@ -101,14 +131,14 @@ internal static class AuthoredSheetMetalCompiler
}
var flanges = new List<AuthoredSheetFlangeSpec>();
- foreach (var block in Blocks(source, "Flange"))
+ foreach (var block in Blocks(source, "Flange", syntaxErrors))
{
- var from = Regex.Match(block.Body, @"\bFrom\s*:\s*(?<region>[A-Za-z_][A-Za-z0-9_]*)\.(?<edge>[A-Za-z_][A-Za-z0-9_]*)\s*;", Rx);
- var hasLength = Scalar(block.Body, "Length", "mm", out var length) || Scalar(block.Body, "Height", "mm", out length);
- var hasRadius = Scalar(block.Body, "InsideRadius", "mm", out var radius) || Scalar(block.Body, "Radius", "mm", out radius);
- if (!from.Success || !hasLength || !Scalar(block.Body, "Angle", "deg", out var degrees) || !hasRadius)
+ var from = Token(block, "From")?.Split('.');
+ var hasLength = Scalar(block, "Length", "mm", out var length) || Scalar(block, "Height", "mm", out length);
+ var hasRadius = Scalar(block, "InsideRadius", "mm", out var radius) || Scalar(block, "Radius", "mm", out radius);
+ if (from is not { Length: 2 } || !hasLength || !Scalar(block, "Angle", "deg", out var degrees) || !hasRadius)
return Fail($"Flange '{block.Name}' requires From, Length/Height, Angle, and InsideRadius/Radius.");
- var parentName=from.Groups["region"].Value;var authoredMember=from.Groups["edge"].Value;
+ var parentName=from[0];var authoredMember=from[1];
if(parentName.Equals(baseSpec.Name,StringComparison.OrdinalIgnoreCase)&&authoredMember.Equals("Center",StringComparison.OrdinalIgnoreCase))
return Fail($"`{parentName}.Center` has capability PointCapable; `Flange.From` requires FlangeAttachable SheetEdge. Available public edge members: Front, Right, Rear, Left.","sheetmetal-incompatible-edge-capability");
var available=parentName.Equals(baseSpec.Name,StringComparison.OrdinalIgnoreCase)?SheetMetalConceptPaths.AvailableMembers("SheetRegion.Rectangle"):SheetMetalConceptPaths.AvailableMembers("SheetFlange");
@@ -118,22 +148,27 @@ internal static class AuthoredSheetMetalCompiler
: new[]{"Outer","Top"}.Contains(authoredMember,StringComparer.OrdinalIgnoreCase);
if(isAttachmentPath)allowed=true;
if(!allowed)return Fail($"`{parentName}.{authoredMember}` is not a FlangeAttachable public member. Available public members: {string.Join(", ",available)}.","sheetmetal-concept-member-not-exposed");
- var direction = Token(block.Body, "Direction")?.Equals("Down", StringComparison.OrdinalIgnoreCase) == true ? SheetBendDirection.Down : SheetBendDirection.Up;
- var corner = Token(block.Body, "Corner")?.ToLowerInvariant() switch
+ var directionToken = Token(block, "Direction")?.ToLowerInvariant();
+ if (directionToken is not (null or "up" or "down")) return Fail($"Flange '{block.Name}' Direction requires Up or Down.", "sheetmetal-flange-direction-invalid");
+ var direction = directionToken == "down" ? SheetBendDirection.Down : SheetBendDirection.Up;
+ var cornerToken = Token(block, "Corner")?.ToLowerInvariant();
+ if (cornerToken is not (null or "open" or "miter" or "mitered" or "relief")) return Fail($"Flange '{block.Name}' Corner requires Open, Miter or Relief.", "sheetmetal-flange-corner-invalid");
+ var corner = cornerToken switch
{
"miter" or "mitered" => SheetCornerPolicy.Mitered,
"relief" => SheetCornerPolicy.Relief,
_ => SheetCornerPolicy.Open
};
- var reliefToken = Token(block.Body, "Relief")?.ToLowerInvariant();
+ var reliefToken = Token(block, "Relief")?.ToLowerInvariant();
+ if (reliefToken is not (null or "none" or "auto" or "rectangular" or "rectangle" or "round")) return Fail($"Flange '{block.Name}' Relief requires None, Auto, Rectangular or Round.", "sheetmetal-flange-relief-invalid");
var relief = reliefToken switch { "auto" => SheetReliefPolicy.Auto, "rectangular" or "rectangle" => SheetReliefPolicy.Rectangular, "round" => SheetReliefPolicy.Round, _ => SheetReliefPolicy.None };
- Scalar(block.Body, "ReliefWidth", "mm", out var reliefWidth);
- Scalar(block.Body, "ReliefDepth", "mm", out var reliefDepth);
- var hasSpan=Scalar(block.Body, "Span", "mm", out var spanLength);
- var hasSpanOffset=Scalar(block.Body, "SpanOffset", "mm", out var spanOffset);
+ Scalar(block, "ReliefWidth", "mm", out var reliefWidth);
+ Scalar(block, "ReliefDepth", "mm", out var reliefDepth);
+ var hasSpan=Scalar(block, "Span", "mm", out var spanLength);
+ var hasSpanOffset=Scalar(block, "SpanOffset", "mm", out var spanOffset);
AuthoredSheetTerminationSpec? Termination(string end)
{
- var token=Token(block.Body,$"{end}Termination");if(token is null)return null;
+ var token=Token(block,$"{end}Termination");if(token is null)return null;
var treatment=token.ToLowerInvariant() switch
{
"natural" or "none"=>SheetBendTerminationTreatment.Natural,
@@ -142,19 +177,20 @@ internal static class AuthoredSheetMetalCompiler
"auto"=>SheetBendTerminationTreatment.Auto,
_=>throw new FormatException($"Flange '{block.Name}' has unsupported {end}Termination '{token}'. Supported: Natural, Trimmed, Rounded, Auto.")
};
- Scalar(block.Body,$"{end}TerminationSetback","mm",out var setback);
- Scalar(block.Body,$"{end}TerminationDepth","mm",out var depth);
- Scalar(block.Body,$"{end}TerminationRadius","mm",out var terminationRadius);
+ Scalar(block,$"{end}TerminationSetback","mm",out var setback);
+ Scalar(block,$"{end}TerminationDepth","mm",out var depth);
+ Scalar(block,$"{end}TerminationRadius","mm",out var terminationRadius);
return new(treatment,setback>0?setback:null,depth>0?depth:null,terminationRadius>0?terminationRadius:null);
}
AuthoredSheetTerminationSpec? startTermination;AuthoredSheetTerminationSpec? endTermination;
try{startTermination=Termination("Start");endTermination=Termination("End");}
catch(FormatException ex){return Fail(ex.Message,"sheetmetal-bend-termination-treatment-invalid");}
if(radius<0||degrees is <=0 or >=180)return Fail($"Flange '{block.Name}' has an invalid radius or bend angle.");
- if(length<=radius+thickness)return Fail($"Flange '{block.Name}' length {length:G6} mm is not greater than inside radius + thickness ({radius+thickness:G6} mm). Increase `{block.Name}` Height/Length above {radius+thickness:G6} mm.",legacyBase.Success?"sheetmetal-firmament-invalid":SheetMetalDiagnosticCodes.FlangeBelowMinimum);
+ if(length<=radius+thickness)return Fail($"Flange '{block.Name}' length {length:G6} mm is not greater than inside radius + thickness ({radius+thickness:G6} mm). Increase `{block.Name}` Height/Length above {radius+thickness:G6} mm.",legacyBase?"sheetmetal-firmament-invalid":SheetMetalDiagnosticCodes.FlangeBelowMinimum);
if(hasSpan&&spanLength<=0)return Fail($"Flange '{block.Name}' Span must be positive when supplied.","sheetmetal-flange-span-invalid");
if(hasSpanOffset&&!hasSpan)return Fail($"Flange '{block.Name}' SpanOffset requires Span.","sheetmetal-flange-span-invalid");
if(isAttachmentPath&&(hasSpan||hasSpanOffset))return Fail($"Flange '{block.Name}' consumes bounded path '{parentName}.{authoredMember}'; put Span and SpanOffset on the AttachmentPath, not the flange.","sheetmetal-attachment-path-span-conflict");
+ block.Fields.Complete();
flanges.Add(new(block.Name, parentName, NormalizeEdge(authoredMember), length,
degrees * Math.PI / 180d, radius, direction, corner, relief,
reliefWidth > 0 ? reliefWidth : null, reliefDepth > 0 ? reliefDepth : null,
@@ -168,53 +204,42 @@ internal static class AuthoredSheetMetalCompiler
return Fail($"Multiple flanges target {duplicate.First().ParentRegion}.{duplicate.First().EdgeName}.", SheetMetalDiagnosticCodes.DuplicateFlange);
if (flanges.Select(f => f.Name).Append(baseSpec.Name).Distinct(StringComparer.OrdinalIgnoreCase).Count() != flanges.Count + 1)
return Fail("Base and flange names must be unique.", SheetMetalDiagnosticCodes.ImpossibleTopology);
- foreach(Match extension in Regex.Matches(source,@"\bExtend\s+SheetMetal\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{",Rx))
- if(!extension.Groups["name"].Value.Equals(header.Groups["name"].Value,StringComparison.Ordinal))
- return Fail($"Sheet Metal extension targets '{extension.Groups["name"].Value}', but the specialized part is '{header.Groups["name"].Value}'.","sheetmetal-extension-target-mismatch");
+ foreach (var extension in syntax.Document.Statements.OfType<DeclarationSyntax>()
+ .Where(d => d.Type.Name.Text == "SheetMetal" && d.Modifiers.Any(m => m.Name.Text == "Extend")))
+ if (extension.Name?.Text != documentName)
+ return Fail($"Sheet Metal extension targets '{extension.Name?.Text}', but the specialized part is '{documentName}'.", "sheetmetal-extension-target-mismatch");
var cuts = new List<AuthoredSheetCutSpec>();
- foreach (var block in Blocks(source, "Hole"))
+ foreach (var block in Blocks(source, "Hole", syntaxErrors))
{
- var on = Token(block.Body, "On");
- var at = Point(block.Body, "Center");
- if (on is null || at is null || !Scalar(block.Body, "Diameter", "mm", out var diameter) || diameter <= 0)
+ var on = Token(block, "On");
+ var at = Point(block, "Center");
+ if (on is null || at is null || !Scalar(block, "Diameter", "mm", out var diameter) || diameter <= 0)
return Fail($"Hole '{block.Name}' requires On, Center, and positive Diameter.");
+ block.Fields.Complete();
cuts.Add(new(block.Name, on, SheetFeatureKind.CircularHole, at.Value.X, at.Value.Y, diameter, null, null));
}
- foreach (var block in Blocks(source, "Cut"))
+ foreach (var block in Blocks(source, "Cut", syntaxErrors))
{
- var on = Token(block.Body, "On");
- var at = Point(block.Body, "At") ?? Point(block.Body, "Center");
- var circle = Regex.IsMatch(block.Body, @"\bProfile\s*:\s*Circle\b", Rx);
- var slot = Regex.IsMatch(block.Body, @"\bProfile\s*:\s*(?:Slot|Rectangle)\b", Rx);
- if (on is null || at is null || (!circle && !slot)) return Fail($"Cut '{block.Name}' requires On, At, and a Circle/Slot/Rectangle profile.");
- if (circle)
- {
- if (!Scalar(block.Body, "Diameter", "mm", out var diameter) || diameter <= 0) return Fail($"Cut '{block.Name}' requires positive Diameter.");
- cuts.Add(new(block.Name, on, SheetFeatureKind.CircularHole, at.Value.X, at.Value.Y, diameter, null, null));
- }
- else
- {
- if (!Scalar(block.Body, "Width", "mm", out var cutWidth) || !Scalar(block.Body, "Length", "mm", out var cutLength) || cutWidth <= 0 || cutLength <= 0)
- return Fail($"Cut '{block.Name}' requires positive Width and Length.");
- cuts.Add(new(block.Name, on, SheetFeatureKind.Slot, at.Value.X, at.Value.Y, null, cutWidth, cutLength));
- }
+ var cut = SheetMetalProfileBinding.Cut(source, block.Name, block.Fields, syntaxErrors);
+ if (cut is not null) cuts.Add(cut);
}
+ if (syntaxErrors.Count > 0) return Fail(string.Join("\n", syntaxErrors), "sheetmetal-authoring-invalid");
var semanticStarted=Stopwatch.GetTimestamp();
var semanticLayout=SheetMetalSemanticLayoutParser.Parse(source,baseSpec,flanges,cuts);
var semanticMs=Stopwatch.GetElapsedTime(semanticStarted).TotalMilliseconds;
if(!semanticLayout.IsSuccess)return new(false,null,null,null,semanticLayout.Diagnostics);
- var manufacturing = SheetMetalManufacturingParser.Parse(source, header.Groups["name"].Value, baseSpec, flanges, semanticLayout.Layout);
+ var manufacturing = SheetMetalManufacturingParser.Parse(source, documentName, baseSpec, flanges, semanticLayout.Layout);
if(!manufacturing.IsSuccess)return new(false,null,null,null,manufacturing.Diagnostics);
cuts.AddRange(semanticLayout.GeneratedCuts);
var duplicateCut=cuts.GroupBy(x=>x.Name,StringComparer.Ordinal).FirstOrDefault(x=>x.Count()>1);
if(duplicateCut is not null)return Fail($"Semantic feature path '{duplicateCut.Key}' is declared more than once.","sheetmetal-semantic-duplicate-feature");
- var authority = Regex.IsMatch(source, @"\bIntent\s*:\s*Reconstructed\s*;", Rx)
- ? SheetMetalProvenanceCategory.Reconstructed : SheetMetalProvenanceCategory.Authored;
- var concept=header.Groups["concept"].Success?header.Groups["concept"].Value:null;
- var spec = new SheetMetalConstructionSpec(header.Groups["name"].Value, thickness, material, k, baseSpec, flanges, cuts, authority, legacyBase.Success,concept)
+ var authority = intent == "Reconstructed" ? SheetMetalProvenanceCategory.Reconstructed : SheetMetalProvenanceCategory.Authored;
+ var concept = FirmamentSyntaxValues.Reference(owner.Annotation);
+ if (owner.Annotation is not null && concept is null) return Fail("SheetMetal requires a named Concept contract after ':'.");
+ var spec = new SheetMetalConstructionSpec(documentName, thickness, material, k, baseSpec, flanges, cuts, authority, legacyBase,concept)
{ SemanticLayout=semanticLayout.Layout, Manufacturing=manufacturing.Definition };
if(concept is not null&&SheetMetalConceptContracts.Validate(source,spec) is { } conformanceFailure)
return Fail(conformanceFailure.Message,conformanceFailure.Code);
@@ -228,38 +253,22 @@ internal static class AuthoredSheetMetalCompiler
new(false, null, null, null, [new(code, SheetMetalDiagnosticSeverity.Error, message)]);
}
- private sealed record Block(string Name, string Body);
- private static IReadOnlyList<Block> Blocks(string source, string keyword)
- {
- var result = new List<Block>();
- var matches = Regex.Matches(source, $@"\b{Regex.Escape(keyword)}\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{{", Rx);
- foreach (Match match in matches)
- {
- var open = source.IndexOf('{', match.Index); 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(match.Groups["name"].Value, source[(open + 1)..close]));
- }
- return result;
- }
- 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 ? Num(m, "v") : 0; return m.Success;
- }
- private static (double X, double Y)? Point(string text, string name)
- {
- var m = Regex.Match(text, $@"\b{Regex.Escape(name)}\s*:\s*\(\s*(?<x>{Number})\s*mm\s*,\s*(?<y>{Number})\s*mm\s*\)\s*;", Rx);
- return m.Success ? (Num(m, "x"), Num(m, "y")) : null;
- }
- private static Point3D? Point3(string text,string name)
+ private sealed record Block(string Name, string Body, FirmamentSyntaxFields Fields);
+ private static IReadOnlyList<Block> Blocks(string source, string keyword, List<string>? diagnostics = null) =>
+ FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)
+ .Where(d => d.Type.Name.Text == keyword && d.Name is not null && d.Body is not null)
+ .Select(d => new Block(d.Name!.Text, source.Substring(d.Body!.ContentSpan.Start, d.Body.ContentSpan.Length),
+ new(d, diagnostics ?? []))).ToArray();
+ private static bool Scalar(Block block, string name, string? unit, out double value)
{
- var m=Regex.Match(text,$@"\b{Regex.Escape(name)}\s*:\s*\(\s*(?<x>{Number})\s*mm\s*,\s*(?<y>{Number})\s*mm\s*,\s*(?<z>{Number})\s*mm\s*\)\s*;",Rx);
- return m.Success?new Point3D(Num(m,"x"),Num(m,"y"),Num(m,"z")):null;
+ value = 0;
+ var expression = block.Fields.Take(name);
+ if (expression is null) return false;
+ if (FirmamentSyntaxValues.TryMeasure(expression, unit ?? "", out value)) return true;
+ block.Fields.Invalid(name); return false;
}
- 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 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 double Num(Match m, string group) => double.Parse(m.Groups[group].Value, NumberStyles.Float, CultureInfo.InvariantCulture);
+ private static string? Token(Block block, string name) => block.Fields.Reference(name);
+ private static (double X, double Y)? Point(Block block, string name) => SheetMetalProfileBinding.Point(block.Fields.Take(name));
private static string NormalizeEdge(string edge) => edge.Equals("Top", StringComparison.OrdinalIgnoreCase) ? "Outer" : edge;
}
@@ -550,7 +559,26 @@ internal static class AuthoredSheetMetalLowering
return Failure($"Cut '{cut.Name}' reaches or crosses the boundary/bend zone of region '{cut.RegionName}'.",SheetMetalDiagnosticCodes.CutCrossesBend);
var center = plane.Origin + plane.UAxis * cut.X + plane.VAxis * cut.Y;
IReadOnlyList<Point3D> loop;PlanarContour2? exactFeature=null;
- if(cut.Kind==SheetFeatureKind.CircularHole)loop=[];
+ if (cut.Profile is { } profile)
+ {
+ exactFeature = PlanarContourKernel.FromResolvedProfile(profile, $"SheetMetal cut {cut.Name} from Profile {profile.Name}");
+ exactFeature = exactFeature with { StableId = cut.Name, OuterLoop = exactFeature.OuterLoop with
+ {
+ StableId = cut.Name + ".Outer",
+ Segments = exactFeature.OuterLoop.Segments.Select((segment, index) => segment with
+ {
+ StableId = $"{cut.Name}.Boundary{index}",
+ Provenance = segment.Provenance with { StableId = $"{cut.Name}.Boundary{index}", TracedFrom = segment.StableId }
+ }).ToArray()
+ } };
+ loop = profile.Loops[0].Segments.Select(segment => segment.Geometry switch
+ {
+ LineArcLineSegment2D line => line.Start,
+ LineArcCircularArc2D arc => (X: arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians), Y: arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians)),
+ _ => throw new InvalidOperationException("Unadmitted sheet cut profile.")
+ }).Select(p => plane.Origin + plane.UAxis * p.X + plane.VAxis * p.Y).ToArray();
+ }
+ else if(cut.Kind==SheetFeatureKind.CircularHole)loop=[];
else if(cut.Kind==SheetFeatureKind.Slot&&cut.ExactCapsule)
{
var capsule=Capsule(cut.Name,cut.X,cut.Y,cut.Length!.Value,cut.Width!.Value,plane);
diff --git a/Aetheris.SheetMetal/SheetMetalProfileBinding.cs b/Aetheris.SheetMetal/SheetMetalProfileBinding.cs
new file mode 100644
index 00000000..7cdfa847
--- /dev/null
+++ b/Aetheris.SheetMetal/SheetMetalProfileBinding.cs
@@ -0,0 +1,140 @@
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.SheetMetal;
+
+/// <summary>Sheet capability admission over the ordinary resolved Profile authority.</summary>
+internal static class SheetMetalProfileBinding
+{
+ private const double Tol = 1e-7;
+
+ internal static AuthoredSheetBaseSpec? Base(string source, string name, FirmamentSyntaxFields fields, List<string> errors)
+ {
+ var value = fields.Take("Profile");
+ var origin = fields.Take("Origin");
+ var offset = Vector3(origin) ?? Point3D.Origin;
+ if (origin is not null && Vector3(origin) is null) errors.Add($"sheetmetal-base-origin-invalid: Base '{name}' origin requires three Length coordinates.");
+ AuthoredSheetBaseSpec? result = null;
+ if (value is ObjectSyntax { Type: ReferenceSyntax { Name.Text: "Rectangle" } } legacy)
+ {
+ var dimensions = FirmamentSyntaxFields.Object(legacy, name, errors);
+ var width = dimensions.Number("Width", "mm");
+ var height = dimensions.Take("Height") ?? dimensions.Take("Depth");
+ if (FirmamentSyntaxValues.TryMeasure(height, "mm", out var depth)) result = new(name, width, depth) { Origin = offset };
+ dimensions.Complete();
+ }
+ else if (Resolve(source, value, errors) is { } profile)
+ {
+ var segments = profile.Loops.Single().Segments;
+ var bounds = Bounds(profile);
+ var lines = segments.Select(s => s.Geometry).OfType<LineArcLineSegment2D>().ToArray();
+ var corners = new[] { (bounds.MinX, bounds.MinY), (bounds.MaxX, bounds.MinY), (bounds.MaxX, bounds.MaxY), (bounds.MinX, bounds.MaxY) };
+ if (lines.Length == 4 && segments.Count == 4 && lines.All(l => Math.Abs(l.Start.X - l.End.X) < Tol || Math.Abs(l.Start.Y - l.End.Y) < Tol)
+ && corners.All(c => lines.Any(l => Distance(c, l.Start) < Tol)))
+ result = new(name, bounds.MaxX - bounds.MinX, bounds.MaxY - bounds.MinY)
+ { Origin = new(offset.X + bounds.MinX, offset.Y + bounds.MinY, offset.Z) };
+ else errors.Add($"sheetmetal-base-profile-unsupported: Base '{name}' requires one axis-aligned rectangular Profile; arbitrary blank boundaries are not admitted by the formed/flat lowerer.");
+ }
+ fields.Complete();
+ return result;
+ }
+
+ internal static AuthoredSheetCutSpec? Cut(string source, string name, FirmamentSyntaxFields fields, List<string> errors)
+ {
+ var on = fields.Word("On");
+ var atValue = fields.Take("At") ?? fields.Take("Center");
+ var at = atValue is null ? (X: 0d, Y: 0d) : Point(atValue);
+ var value = fields.Take("Profile");
+ if (on is null || at is null) { errors.Add($"sheetmetal-cut-placement-invalid: Cut '{name}' requires a named region and a valid Point2 offset."); return null; }
+
+ // Historical Slot/Rectangle cuts are rectangular. Preserve their exact
+ // interpretation; modern Slot2 reaches this owner as an analytic Profile.
+ var legacy = value is ObjectSyntax o ? FirmamentSyntaxValues.Reference(o.Type) : FirmamentSyntaxValues.Reference(value);
+ var namedProfile = value is not ObjectSyntax && FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)
+ .Any(d => d.Type.Name.Text == "Profile" && d.Name?.Text == legacy);
+ if (!namedProfile && (legacy is "Circle" or "Slot" or "Rectangle"))
+ {
+ if (atValue is null) { errors.Add($"sheetmetal-cut-placement-invalid: Legacy Cut '{name}' requires At or Center."); return null; }
+ var dimensions = value is ObjectSyntax obj ? FirmamentSyntaxFields.Object(obj, name, errors) : fields;
+ var diameter = legacy == "Circle" ? dimensions.Number("Diameter", "mm") : double.NaN;
+ var width = legacy != "Circle" ? dimensions.Number("Width", "mm") : double.NaN;
+ var length = legacy != "Circle" ? dimensions.Number("Length", "mm") : double.NaN;
+ if (!ReferenceEquals(dimensions, fields)) dimensions.Complete();
+ fields.Complete();
+ if (legacy == "Circle" && diameter > 0) return new(name, on, SheetFeatureKind.CircularHole, at.Value.X, at.Value.Y, diameter, null, null);
+ if (legacy != "Circle" && width > 0 && length > 0) return new(name, on, SheetFeatureKind.Slot, at.Value.X, at.Value.Y, null, width, length);
+ errors.Add($"sheetmetal-cut-profile-invalid: Cut '{name}' requires positive profile dimensions."); return null;
+ }
+ var resolved = Resolve(source, value, errors);
+ fields.Complete();
+ if (resolved is null) return null;
+ LineArcProfileCurve2D Move(LineArcProfileCurve2D curve) => curve switch
+ {
+ LineArcLineSegment2D l => new LineArcLineSegment2D((l.Start.X + at.Value.X, l.Start.Y + at.Value.Y), (l.End.X + at.Value.X, l.End.Y + at.Value.Y)),
+ LineArcCircularArc2D a => a with { Center = (a.Center.X + at.Value.X, a.Center.Y + at.Value.Y) },
+ LineArcFullCircle2D c => c with { Center = (c.Center.X + at.Value.X, c.Center.Y + at.Value.Y) },
+ _ => throw new InvalidOperationException("Profile capability was not admitted.")
+ };
+ var profile = resolved with { Loops = resolved.Loops.Select(l => l with { Segments = l.Segments.Select(s => s with { Geometry = Move(s.Geometry) }).ToArray() }).ToArray() };
+ if (profile.Loops[0].Segments is [ { Geometry: LineArcFullCircle2D circle } ])
+ return new(name, on, SheetFeatureKind.CircularHole, circle.Center.X, circle.Center.Y, circle.Radius * 2, null, null);
+ var box = Bounds(profile);
+ return new(name, on, SheetFeatureKind.ProfileHole, (box.MinX + box.MaxX) / 2, (box.MinY + box.MaxY) / 2,
+ null, box.MaxY - box.MinY, box.MaxX - box.MinX) { Profile = profile };
+ }
+
+ private static ResolvedProfile2D? Resolve(string source, ExpressionSyntax? value, List<string> errors)
+ {
+ var name = FirmamentSyntaxValues.Reference(value);
+ if (name is null) { errors.Add("sheetmetal-profile-reference-required: Declare a named Profile with Rect2, Circle2, Slot2 or an exact line/arc boundary, then reference it."); return null; }
+ var profile = ProfileAuthoringParser.ResolveNamedProfile(source, name, out var diagnostics);
+ errors.AddRange(diagnostics);
+ if (profile is null) return null;
+ var frame = profile.EffectiveConstructionPlane;
+ if (frame.Origin != Point3D.Origin || (frame.AxisX.ToVector() - new Vector3D(1, 0, 0)).Length > Tol
+ || (frame.AxisY.ToVector() - new Vector3D(0, 1, 0)).Length > Tol)
+ { errors.Add($"sheetmetal-profile-frame-unsupported: Profile '{name}' must be in local XY; use the Base origin or Cut at offset for placement."); return null; }
+ if (profile.Loops.Count != 1 || profile.Loops[0].Segments.Any(s => s.Geometry is not (LineArcLineSegment2D or LineArcCircularArc2D or LineArcFullCircle2D)))
+ { errors.Add($"sheetmetal-profile-capability-unsupported: Profile '{name}' requires one closed line/arc loop or a circle; islands, ellipses and splines are not admitted for sheet regions/cuts."); return null; }
+ return profile;
+ }
+
+ internal static (double X, double Y)? Point(ExpressionSyntax? value)
+ {
+ if (value is SequenceSyntax { Kind: SequenceKind.Tuple } tuple) value = tuple with { Kind = SequenceKind.List };
+ return FirmamentSyntaxValues.Vector(value, "mm", out var values) && values.Length == 2 ? (values[0], values[1]) : null;
+ }
+
+ private static Point3D? Vector3(ExpressionSyntax? value)
+ {
+ if (value is SequenceSyntax { Kind: SequenceKind.Tuple } tuple) value = tuple with { Kind = SequenceKind.List };
+ return FirmamentSyntaxValues.Vector(value, "mm", out var values) && values.Length == 3 ? new(values[0], values[1], values[2]) : null;
+ }
+
+ internal static (double MinX, double MinY, double MaxX, double MaxY) Bounds(ResolvedProfile2D profile)
+ {
+ var points = new List<(double X, double Y)>();
+ foreach (var s in profile.Loops[0].Segments)
+ switch (s.Geometry)
+ {
+ case LineArcLineSegment2D l: points.Add(l.Start); points.Add(l.End); break;
+ case LineArcFullCircle2D c: points.Add((c.Center.X - c.Radius, c.Center.Y - c.Radius)); points.Add((c.Center.X + c.Radius, c.Center.Y + c.Radius)); break;
+ case LineArcCircularArc2D a:
+ Add(a.StartAngleRadians); Add(a.StartAngleRadians + a.SweepAngleRadians);
+ for (var i = 0; i < 4; i++)
+ {
+ var angle = i * Math.PI / 2;
+ var delta = a.SweepAngleRadians >= 0 ? angle - a.StartAngleRadians : a.StartAngleRadians - angle;
+ delta = (delta % Math.Tau + Math.Tau) % Math.Tau;
+ if (delta <= Math.Abs(a.SweepAngleRadians) + Tol) Add(angle);
+ }
+ void Add(double angle) => points.Add((a.Center.X + a.Radius * Math.Cos(angle), a.Center.Y + a.Radius * Math.Sin(angle)));
+ break;
+ }
+ return (points.Min(p => p.X), points.Min(p => p.Y), points.Max(p => p.X), points.Max(p => p.Y));
+ }
+
+ private static double Distance((double X, double Y) a, (double X, double Y) b) => Math.Sqrt(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Y - b.Y, 2));
+}
diff --git a/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs b/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs
index f93a4dbf..2cd270e0 100644
--- a/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs
+++ b/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs
@@ -49,6 +49,8 @@ internal sealed record SheetMetalSemanticLayoutParseResult(
/// </summary>
internal static class SheetMetalSemanticLayoutParser
{
+ internal static bool OwnsDeclaration(string type) => type is "AttachmentPath" or "Datum" or "Tab" or "SteppedNotch"
+ or "CornerProfile" or "Pattern" or "Require" or "ProfileDelta";
private const RegexOptions Rx=RegexOptions.IgnoreCase|RegexOptions.CultureInvariant|RegexOptions.Singleline;
private const string Number=@"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)";
private sealed record Block(string Keyword,string Name,string Body,int Index,string? Struct);
diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
index d823f4d4..60a97a76 100644
--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
@@ -1,5 +1,15 @@
# October 2026 Firmament language decision register
+Shared Profile amendment (2026-10-16):
+[mechanical / sheet-metal reconciliation](FIRMAMENT-SHEET-METAL-SYNTAX-2026-10.md)
+admits compact `Profile name = Rect2/Circle2/Slot2 { ... }` through the existing
+boundary owner and lets native sheet Base/Cut consume named ordinary Profiles.
+Canonical camelCase fields retain PascalCase compatibility. Legacy sheet Slot
+cuts preserve rectangular geometry; modern Slot2 uses overall capsule length.
+Nonrectangular bases, non-XY sheet profiles and unsupported cut curves reject.
+Semantic-layout/manufacturing productions and the overloaded Intent compatibility
+field remain explicitly bounded follow-up work; no kernel capability is implied.
+
Compile-time choices amendment (2026-10-16):
[implementation and qualification](FIRMAMENT-COMPILE-TIME-CHOICES-RFC.md) supersedes
the earlier enum-Static/total-Match deferral for the qualified engineering value
diff --git a/docs/development/FIRMAMENT-SHEET-METAL-SYNTAX-2026-10.md b/docs/development/FIRMAMENT-SHEET-METAL-SYNTAX-2026-10.md
new file mode 100644
index 00000000..3d96404d
--- /dev/null
+++ b/docs/development/FIRMAMENT-SHEET-METAL-SYNTAX-2026-10.md
@@ -0,0 +1,131 @@
+# Firmament shared mechanical / sheet-metal Profile pass
+
+Date: 2026-10-16. Starting revision: `9c14bfbb`.
+
+## Decisions and result
+
+A Profile is a reusable exact material boundary, independent of the consumer.
+The modern compact spelling is `Profile blank = Rect2 { center: ...; size: ... }`.
+Existing explicit loops, named segments, pipelines and immutable boundary edits
+remain available. `Profile copy = blank` reuses the ordinary derived Profile owner.
+The compact form delegates to the existing closed-boundary field schema and
+Profile binder at their established AST-to-domain lowering seam; it does not add
+a new document parser route, numeric evaluator, sketch system or materializer.
+
+Sheet `Base deck { profile: blank }` and `Cut vent { profile: opening; on: deck;
+at: Point2(...) }` now resolve through the same named Profile API as mechanical
+Extrude. Base capability remains a single axis-aligned rectangle in local XY.
+Cut capability admits one exact line/arc loop or a circle. Unsupported frames,
+curves, inner islands and nonrectangular bases reject rather than becoming bounds
+or a default rectangle. Base minimum coordinates become physical origin; Cut
+coordinates are local to the named region and `at` adds a translation.
+
+New authoring uses PascalCase constructs/types/domain symbols, camelCase fields
+and authored names. PascalCase field aliases remain admitted. Base, Flange, Hole
+and Cut read fields from the shared AST and dimensional binder; their former
+regex scalar/tuple/field readers were removed. Newlines or semicolons separate
+these fields. Unknown fields and unsupported header placements close through the
+same field-consumption owner. Unknown sheet-body statements reject while known
+semantic-layout operations are delegated to their actual domain owner.
+
+The XZ witness uncovered a mechanical casing defect: `Construction Plane` tracing
+only read `Trace` with a regex. Its owner now reads `trace`/`Trace` through shared
+AST fields and rejects duplicates/unknown fields. A non-XY Profile remains a valid
+mechanical construction possibility, but cannot silently become an XY sheet base.
+
+## Compatibility evidence and decisions
+
+- Legacy rectangular bases and Circle/Rectangle/Slot cuts preserve interpretation.
+ The modern/legacy bracket pair has byte-identical formed STEP and matching flat
+ area/bounds. No geometry reference was rewritten.
+- Legacy sheet Cut `Slot` is rectangular. It is retained deliberately. Modern
+ `Slot2.length` means overall capsule length, matching mechanical construction;
+ rounded ends remain exact arcs in formed/flat geometry. Semantic-layout Slot
+ Patterns already had their own exact-capsule contract and keep it.
+- Named Profile declarations bind before legacy shape tags: a Profile named
+ Circle/Slot/Rectangle is a real named boundary, not an implicit old cut recipe.
+ Mixed legacy/named Base declarations and irrelevant dimensions on a Circle cut
+ reject instead of discarding one request.
+- `Extend SheetMetal` is an extension owner, not a second concrete document.
+ Existing product-family assemblies, manufacturing releases, attachments and
+ corner profiles remain part of the regression gate.
+- Reusing one Profile in two cuts gives each cut distinct boundary identities,
+ while tracing provenance back to the original Profile segments.
+- `Intent` historically accepts Authored/Reconstructed/Manufacturing tags or a
+ declared Concept Struct layout. Those legitimate meanings remain admitted;
+ unknown references reject. This pass does not redesign that overloaded field.
+- The kernel and the existing scalar evaluator are unchanged. Domain lowering
+ now transports the resolved exact contour into the already-existing sheet cut
+ path, instead of reconstructing a rounded shape from rectangular dimensions.
+
+## Qualification
+
+Focused sheet-metal suite: 119 passed, including 20 added profile tests. Tests
+cover formed STEP equality, exact rounded area, legacy Slot preservation, origin,
+repeated-cut identities/provenance, Template specialization, mechanical compact
+Circle2/Slot2/RoundedRect2, unknown fields, unresolved names, unsupported curves,
+header placement, conflicting Base declarations, irrelevant Circle dimensions,
+legacy-tag name collisions and the actual XZ frame witness. The existing six
+cubic-profile tests also pass: a full-suite failure exposed compact lowering
+intercepting Profile Template specialization, repaired by leaving specialization
+and historical call productions with the existing Template owner.
+
+The final CLI gate passes 26/26 cases: all 19 current canonical SheetMetal
+sources, five regression sources and both complete documentation examples. Every
+case has validate/build agreement; admitted sheet parts also flatten/export. The
+modern/legacy pair has identical formed STEP bytes and flat area/bounds;
+`cli/results.json`. The named Profile alias also builds through the CLI.
+
+The SDK build and all 14 transport tests pass. A real headless Edge WebAssembly
+worker builds a compact mechanical Profile, rejects its misspelled field with a
+structured source-located diagnostic, retains byte-identical last-valid STEP,
+and rebuilds valid source; `browser.json`. This does not claim a new Helios UI
+acceptance run or browser-native SheetMetal capability.
+
+The original FrontendX4 authoring gate passes 32/32, including the chimera and
+recorded geometry. The compile-time choices gate passes 57/57, with validate/build
+agreement and 29 byte-identical accepted/reference STEP pairs. No existing source
+specimen or geometry golden was rewritten.
+
+Final Release solution build: zero errors, 11 warnings; `final-build.log`.
+Fast Core lane: 1,076 passed; `fast.log`. Complete solution lane: 5,329 passed
+across 20 test projects, zero failures or skips; `full.log`. This includes all
+2,817 Firmament tests, 119 sheet-metal tests and seven Editable V8 tests. The
+FrictionLab project reports no tests available and is not counted as a passing
+project. No-build tests ran against the integrated Release build, serially with
+MSBuild node reuse/shared compilation disabled. Final process inventory has zero
+dotnet/testhost processes.
+
+Diff whitespace, changed-file UTF-8/newline and repository content-location checks
+pass. Review confirms no new document dispatch, regex parser, diagnostic-code
+allowlist or independent numeric evaluator. The new Profile production is a
+bounded AST lowering within the existing closed-boundary owner; specialization
+and call syntax remains with the Template owner. Generated logs, reports and STEP remain under ignored
+`artifacts/local/sheetmetal-syntax/`. Source witnesses and the CLI runner live in
+`fixtures/Regression/SheetMetalSyntax/`.
+
+## Remaining bounded work
+
+This is a closed-profile reconciliation pass, not a claim that every SheetMetal
+production is now a unified semantic frontend. Semantic-layout Pattern/Tab,
+AttachmentPath, CornerProfile, ProfileDelta, manufacturing/PMI and recovery
+adapters retain their existing domain-specific productions and terminators.
+Their deeper syntax migration should reuse their semantic owners, not broaden
+this pass into a second global rewrite. In particular, unification of arbitrary
+Profile islands or spline cuts requires capability qualification beyond syntax.
+
+SheetMetalDiagnostic still has the module's existing code/severity/message shape;
+complete original-source span projection through all older manufacturing and
+semantic adapters remains a separate diagnostic task. No new exact-location
+claim is made for those adapters. The build/validate gate uses the same module
+compiler, and the new capability errors identify the affected named construct.
+
+No additional user decision is required for the qualified surface.
+
+## Verdict
+
+**Success for this shared-profile pass.** Both engineering domains consume the
+same exact Profile authority; the modern compact syntax improves ordinary
+mechanical authoring, and native sheet Base/Cut admission preserves qualified
+geometry and compatibility. The limits above remain explicit follow-up work,
+not claims of an entirely migrated SheetMetal frontend.
diff --git a/docs/public/firmament/sheet-metal.md b/docs/public/firmament/sheet-metal.md
index 5d01d504..c7428494 100644
--- a/docs/public/firmament/sheet-metal.md
+++ b/docs/public/firmament/sheet-metal.md
@@ -2,39 +2,97 @@
Authored Sheet Metal uses a specialized semantic model: a base region, named flanges and bend strips, and cuts on named planar regions. It can emit formed STEP, thickness-bearing flat STEP, and flat SVG; it also carries material, K-factor, DFM, semantic layout, and manufacturing definitions on qualified routes.
+A closed boundary has the same `Profile` meaning in mechanical and sheet-metal
+construction. Use canonical 2D shapes for a compact boundary, or the ordinary
+`Loop`/`Segment`/pipeline forms for an authored boundary. The consuming operation
+then checks its own capabilities.
+
+**Complete file — a bracket with a reusable blank and rounded opening:**
+
```firmament
-SheetMetal MountingBracket {
- Thickness: 1.5mm;
- Material: "5052-H32 Aluminum";
- KFactor: 0.42;
- Base: Rectangle(80mm, 50mm);
-
- Flange Upright {
- From: Base.Rear;
- Length: 30mm;
- Angle: 90deg;
- InsideRadius: 2mm;
- Direction: Up;
- }
+Profile blank = Rect2 { center: [40mm, 25mm]; size: [80mm, 50mm] }
+Profile ventilation = Slot2 { center: [0mm, 0mm]; length: 12mm; width: 6mm }
- Hole Mount {
- On: Base;
- Center: (40mm, 20mm);
- Diameter: 8mm;
+SheetMetal MountingBracket {
+ thickness: 1.5mm
+ material: "5052-H32 Aluminum"
+ kFactor: 0.42
+ Base deck { profile: blank }
+ Flange upright {
+ from: deck.Rear
+ length: 30mm
+ angle: 90deg
+ insideRadius: 2mm
+ direction: Up
}
+ Cut vent { on: deck; profile: ventilation; at: Point2(40mm, 20mm) }
}
```
-Sheet Metal does not use a Model `Units` declaration in this authored route; dimensional fields carry explicit units. `Thickness`, `Material`, `KFactor`, and `Base` belong directly in the `SheetMetal` body, alongside `Flange` and `Hole` declarations.
+`Profile blank = Rect2 { ... }` is also admitted in a mechanical Model and consumed
+by `Extrude stock { profile: blank; from: 0mm; to: 1.5mm }`. The shape's existing
+field schema, closure checks and exact Profile lowerer remain authoritative.
+`Profile copy = blank` names an immutable derived boundary. Detailed boundary
+editing continues to use the ordinary `Profile { from: ... }` and `Replace` forms.
+There is no separate sheet-metal sketch language for new named boundaries.
+
+Use PascalCase for constructs/types and domain symbols (`Base`, `Rect2`, `Up`,
+`Rear`), camelCase for fields and authored value names. PascalCase field spellings
+remain compatible. Semicolons are optional in Base, Flange, Hole and Cut fields;
+newlines can separate fields. Older manufacturing/semantic-layout recipes retain
+their documented statement forms and terminators.
+
+### Coordinates and capability admission
+
+A Base currently admits one axis-aligned rectangular Profile in local XY. Its
+minimum corner becomes the physical base origin; it is not silently recentered.
+An optional Base `origin` adds a physical translation. A circle or arbitrary
+polygon cannot serve as this rectangular base merely because it has bounds.
+Non-axis-aligned or non-XY bases reject explicitly.
+
+A Cut admits one closed line/arc Profile or a circle. Its coordinates are local to
+its named sheet region. Optional `at: Point2(x, y)` adds a translation; without
+`at`, the authored Profile coordinates are used directly. Curves remain exact in
+the formed and flat contours. Inner islands, ellipses, splines and non-XY Profile
+frames are not admitted by this sheet cut owner. Crossing a region boundary or
+bend zone still rejects. Structural parsing alone does not admit a geometry
+capability.
+
+`Slot2.length` is the **overall** rounded-slot length, including its semicircular
+ends, exactly as in mechanical profiles. `Circle2` uses `radius`; `Rect2` uses
+`size`. This avoids the old sheet-specific dimension vocabulary for new Profiles.
+
+The sheet region's `Rear`/`Front` members are attachment semantics; a Profile's
+`Top`/`Bottom` members name its planar boundary. They are not global-axis aliases.
+Named regions, attachment paths, ProfileDelta programs and formed/flat identity
+remain useful sheet-metal concepts; ordinary Profile boundaries and edits now
+feed them through the shared boundary authority.
+
+### Compatibility
+
+Existing `Base: Rectangle(w, d)` and named
+`Base deck { Profile: Rectangle { Width: 80mm; Height: 50mm; }; }` retain their
+geometry. Legacy cuts using `Profile: Rectangle`, `Circle` or `Slot`, including
+inline dimensions and tuple placement, remain admitted. **Legacy `Slot` cuts are
+rectangular** in this route; they are not silently converted into capsules. Use a
+named `Profile` built with `Slot2` when a rounded slot is intended.
+
+Sheet Metal does not use a Model `units` declaration in this authored route;
+dimensional fields carry explicit units. `thickness`, `material`, `kFactor`, and
+the named Base belong directly in the `SheetMetal` body.
-[`l-bracket-with-hole.firmament`](../../../fixtures/Canonical/SheetMetal/l-bracket-with-hole.firmament) is the practical first example. Build the formed part and then flatten the same source:
+[`modern-bracket.firmament`](../../../fixtures/Regression/SheetMetalSyntax/modern-bracket.firmament)
+and its legacy reference qualify formed STEP parity. Build and flatten it:
```powershell
-aetheris build fixtures/Canonical/SheetMetal/l-bracket-with-hole.firmament --output artifacts/bracket-formed.step --json
-aetheris sheetmetal flatten fixtures/Canonical/SheetMetal/l-bracket-with-hole.firmament --step artifacts/bracket-flat.step --svg artifacts/bracket-flat.svg --json
+aetheris build fixtures/Regression/SheetMetalSyntax/modern-bracket.firmament --output artifacts/local/bracket-formed.step --json
+aetheris sheetmetal flatten fixtures/Regression/SheetMetalSyntax/modern-bracket.firmament --step artifacts/local/bracket-flat.step --svg artifacts/local/bracket-flat.svg --json
```
-[`profile-delta-tab-family.firmament`](../../../fixtures/Canonical/SheetMetal/profile-delta-tab-family.firmament) is the modern data-driven profile example: a finite Table selects `ProfileTabSpec`, `with` derives the shop variant, and the standard-library `ProfileDelta Tab` modifies the wall edge while preserving formed/flat semantic identity.
+[`profile-delta-tab-family.firmament`](../../../fixtures/Canonical/SheetMetal/profile-delta-tab-family.firmament)
+is the data-driven edge-edit example: a finite Table selects `ProfileTabSpec`,
+`with` derives the shop variant, and the standard-library `ProfileDelta Tab`
+modifies the wall edge while preserving formed/flat semantic identity.
Flat inspection distinguishes `MaterialArea` from `BoundingArea`. `MaterialArea` is exact line/arc integration of the final flat material contour after additive ProfileDelta regions, notches, holes, cutouts, and overlap clipping. `BoundingArea` is only the rectangular nesting envelope. If no validated exact blank contour exists, material area is reported as unavailable rather than reconstructed from feature bookkeeping.
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index eb3a02d7..ec9597f5 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -412,6 +412,26 @@ See [Templates](templates.md) for typed specialization.
Use a `Concept Struct` for design geometry, trace its named guides into a
`Profile`, then consume that Profile. The layout itself creates no material.
+A simple closed boundary can use a typed constructor directly:
+
+```firmament
+Model Plate {
+ units: mm
+ Profile outline = Rect2 { center: [0mm, 0mm]; size: [80mm, 50mm] }
+ Extrude stock { profile: outline; from: 0mm; to: 2mm }
+}
+```
+
+This compact form uses the same 2D shape fields and exact boundary binder as a
+named `Rect2`, `Circle2`, `Slot2` or other admitted constructor. It does not create
+a second profile representation. `Profile copy = outline` derives an immutable
+boundary from a named Profile or closed shape. Use the explicit loop form below
+when assembling segments, naming inner loops or choosing trace order.
+[Sheet Metal](sheet-metal.md) can consume the same named Profiles for its Base and
+Cut operations, subject to the sheet owner's rectangular-base and line/arc-cut
+capabilities. This brings compact sheet authoring to mechanical profiles while
+sharing closure, dimension and unknown-field checking.
+
**Complete file — a profile extruded from Z = 0 to 12mm:**
```firmament
diff --git a/fixtures/Regression/SheetMetalSyntax/README.md b/fixtures/Regression/SheetMetalSyntax/README.md
new file mode 100644
index 00000000..fb67aaa0
--- /dev/null
+++ b/fixtures/Regression/SheetMetalSyntax/README.md
@@ -0,0 +1,13 @@
+# Shared mechanical / sheet-metal Profile qualification
+
+Run `python fixtures/Regression/SheetMetalSyntax/run.py` after a Release CLI build.
+The runner validates, builds and flattens the current canonical sheet-metal corpus,
+the local shared-profile specimens, and the complete new documentation examples.
+It requires matching acceptance/rejection and byte-identical formed STEP plus flat
+area/bounds for the modern and legacy bracket pair. It never rewrites a fixture or
+a geometry reference. Output belongs in ignored `artifacts/local/sheetmetal-syntax/`.
+
+`unsupported-xz.firmament` must reject explicitly. New `Slot2` cuts are capsules;
+legacy sheet `Slot` cuts retain their rectangular geometry. Unit tests additionally
+check exact rounded area, retained region identities, reusable cut identities,
+Template specialization, unsupported curves and unknown-field admission.
diff --git a/fixtures/Regression/SheetMetalSyntax/legacy-bracket.firmament b/fixtures/Regression/SheetMetalSyntax/legacy-bracket.firmament
new file mode 100644
index 00000000..4b4f1a70
--- /dev/null
+++ b/fixtures/Regression/SheetMetalSyntax/legacy-bracket.firmament
@@ -0,0 +1,8 @@
+SheetMetal Bracket {
+ Thickness: 1.5mm;
+ Material: "5052-H32 Aluminum";
+ KFactor: 0.42;
+ Base deck { Profile: Rectangle { Width: 80mm; Height: 50mm; }; }
+ Flange wall { From: deck.Rear; Length: 30mm; Angle: 90deg; InsideRadius: 2mm; Direction: Up; }
+ Cut port { On: deck; Profile: Rectangle { Length: 12mm; Width: 6mm; }; At: (30mm, 20mm); }
+}
diff --git a/fixtures/Regression/SheetMetalSyntax/mechanical-template.firmament b/fixtures/Regression/SheetMetalSyntax/mechanical-template.firmament
new file mode 100644
index 00000000..a4f663d8
--- /dev/null
+++ b/fixtures/Regression/SheetMetalSyntax/mechanical-template.firmament
@@ -0,0 +1,6 @@
+Template<width: Length> Model PlateFamily {
+ units: mm
+ Profile blank = Rect2 { center: [0mm, 0mm]; size: [width, 20mm] }
+ Extrude stock { profile: blank; from: 0mm; to: 2mm }
+}
+Model Product = PlateFamily<width: 40mm>
diff --git a/fixtures/Regression/SheetMetalSyntax/mechanical.firmament b/fixtures/Regression/SheetMetalSyntax/mechanical.firmament
new file mode 100644
index 00000000..f711ca49
--- /dev/null
+++ b/fixtures/Regression/SheetMetalSyntax/mechanical.firmament
@@ -0,0 +1,5 @@
+Model Plate {
+ units: mm
+ Profile blank = Rect2 { center: [40mm, 25mm]; size: [80mm, 50mm] }
+ Extrude stock { profile: blank; from: 0mm; to: 1.5mm }
+}
diff --git a/fixtures/Regression/SheetMetalSyntax/modern-bracket.firmament b/fixtures/Regression/SheetMetalSyntax/modern-bracket.firmament
new file mode 100644
index 00000000..f8aef14b
--- /dev/null
+++ b/fixtures/Regression/SheetMetalSyntax/modern-bracket.firmament
@@ -0,0 +1,10 @@
+Profile blank = Rect2 { center: [40mm, 25mm]; size: [80mm, 50mm] }
+Profile opening = Rect2 { center: [0mm, 0mm]; size: [12mm, 6mm] }
+SheetMetal Bracket {
+ thickness: 1.5mm
+ material: "5052-H32 Aluminum"
+ kFactor: 0.42
+ Base deck { profile: blank }
+ Flange wall { from: deck.Rear; length: 30mm; angle: 90deg; insideRadius: 2mm; direction: Up }
+ Cut port { on: deck; profile: opening; at: Point2(30mm, 20mm) }
+}
diff --git a/fixtures/Regression/SheetMetalSyntax/run.py b/fixtures/Regression/SheetMetalSyntax/run.py
new file mode 100644
index 00000000..7460a409
--- /dev/null
+++ b/fixtures/Regression/SheetMetalSyntax/run.py
@@ -0,0 +1,69 @@
+"""Qualify shared Profile authoring through the repository CLI, without recording goldens."""
+import hashlib
+import json
+from pathlib import Path
+import re
+import subprocess
+
+
+def main():
+ root = Path(__file__).resolve().parent
+ repo = root.parents[2]
+ output = repo / "artifacts/local/sheetmetal-syntax/cli"
+ output.mkdir(parents=True, exist_ok=True)
+ cli = repo / "Aetheris.CLI/bin/Release/net10.0/aetheris.dll"
+
+ def invoke(*args):
+ result = subprocess.run(["dotnet", str(cli), *map(str, args), "--json"], cwd=repo,
+ capture_output=True, text=True, timeout=120)
+ try:
+ payload = json.loads(result.stdout)
+ except ValueError:
+ raise RuntimeError(result.stdout + result.stderr)
+ return result.returncode, payload
+
+ cases = [(p, True) for p in sorted((repo / "fixtures/Canonical/SheetMetal").glob("*.firmament"))]
+ cases += [(p, p.stem != "unsupported-xz") for p in sorted(root.glob("*.firmament"))]
+ for file, needle, name in [("docs/public/firmament/syntax.md", "Profile outline = Rect2", "doc-mechanical"),
+ ("docs/public/firmament/sheet-metal.md", "Profile ventilation = Slot2", "doc-sheetmetal")]:
+ blocks = re.findall(r"```firmament\s*\n(.*?)```", (repo / file).read_text(encoding="utf-8"), re.S)
+ source = next(b for b in blocks if needle in b)
+ path = output / (name + ".firmament")
+ path.write_text(source, encoding="utf-8")
+ cases.append((path, True))
+
+ rows = []
+ for index, (source, expected) in enumerate(cases):
+ label = source.stem
+ step = output / (str(index) + "-" + label + ".step")
+ validation_code, validation = invoke("validate", source)
+ build_code, build = invoke("build", source, "--output", step)
+ validated = validation_code == 0
+ built = build_code == 0 and build.get("success") is True
+ row = dict(source=str(source.relative_to(repo)), name=label, expected=expected,
+ validated=validated, built=built, passed=validated == built == expected)
+ if built:
+ row["stepSha256"] = hashlib.sha256(step.read_bytes()).hexdigest()
+ if built and (build.get("domain") == "SheetMetal"):
+ flat_code, flat = invoke("sheetmetal", "flatten", source, "--step", output / (str(index) + "-flat.step"))
+ row["passed"] &= flat_code == 0 and flat.get("success") is True
+ flat_pattern = flat.get("flatPattern", {})
+ if "materialArea" not in flat_pattern or "bounds" not in flat_pattern:
+ raise RuntimeError("Flat qualification omitted its metrics: " + str(flat))
+ row["flat"] = {key: flat_pattern[key] for key in ("materialArea", "bounds")}
+ build["flatQualification"] = flat
+ (output / (str(index) + "-" + label + ".json")).write_text(
+ json.dumps(dict(validation=validation, build=build), indent=2) + "\n", encoding="utf-8")
+ rows.append(row)
+ print(("PASS " if row["passed"] else "FAIL ") + label, flush=True)
+ by_name = {row["name"]: row for row in rows}
+ modern, legacy = by_name["modern-bracket"], by_name["legacy-bracket"]
+ parity = modern.get("stepSha256") == legacy.get("stepSha256") and modern.get("flat") == legacy.get("flat")
+ result = dict(cases=rows, formedStepAndFlatParity=parity)
+ (output / "results.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
+ print(f"{sum(row['passed'] for row in rows)}/{len(rows)} cases; formed STEP / flat parity: {parity}")
+ return 0 if parity and all(row["passed"] for row in rows) else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/fixtures/Regression/SheetMetalSyntax/unsupported-xz.firmament b/fixtures/Regression/SheetMetalSyntax/unsupported-xz.firmament
new file mode 100644
index 00000000..36070b45
--- /dev/null
+++ b/fixtures/Regression/SheetMetalSyntax/unsupported-xz.firmament
@@ -0,0 +1,7 @@
+Concept Struct Frames {
+ xz: Plane { origin: [0mm, 0mm, 0mm]; normal: [0, -1, 0]; up: [0, 0, 1] }
+}
+Construction Plane panelPlane { trace: Frames.xz }
+Rect2 boundary { center: [40mm, 25mm]; size: [80mm, 50mm] }
+Profile blank using panelPlane { Loop Outer { boundary.Bottom |> boundary.Right |> boundary.Top |> boundary.Left |> Close } }
+SheetMetal Bracket { thickness: 1.5mm; Base deck { profile: blank } }