Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add Set authoring and pattern expansion support

Yuechen Liaf3ee2f48a64
diff --git a/Aetheris.CLI.Tests/NamedSetCliTests.cs b/Aetheris.CLI.Tests/NamedSetCliTests.cs
new file mode 100644
index 00000000..c2092569
--- /dev/null
+++ b/Aetheris.CLI.Tests/NamedSetCliTests.cs
@@ -0,0 +1,42 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class NamedSetCliTests
+{
+ [Fact]
+ public void Inspect_ReportsNamedEntriesAndPatternAssociations()
+ {
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+ var exit = Aetheris.CLI.CliRunner.Run(["inspect", Fixture("Canonical", "Set", "mounting-points.firmament"), "--json"], stdout, stderr);
+
+ Assert.Equal(0, exit);
+ Assert.Equal(string.Empty, stderr.ToString());
+ using var json = JsonDocument.Parse(stdout.ToString());
+ var set = Assert.Single(json.RootElement.GetProperty("sets").EnumerateArray());
+ Assert.Equal("MountPoints", set.GetProperty("setId").GetString());
+ Assert.Equal("Point2", set.GetProperty("elementType").GetString());
+ Assert.Equal(4, set.GetProperty("count").GetInt32());
+ Assert.Equal(["LowerLeft", "LowerRight", "UpperLeft", "UpperRight"],
+ set.GetProperty("entries").EnumerateArray().Select(entry => entry.GetProperty("name").GetString()));
+ var polygon = Assert.Single(json.RootElement.GetProperty("polygons").EnumerateArray());
+ Assert.Equal("MountBoundaryShape", polygon.GetProperty("name").GetString());
+ Assert.Equal("Rhombus", polygon.GetProperty("variant").GetString());
+ Assert.Equal([90d, 64d], polygon.GetProperty("diagonals").EnumerateArray().Select(value => value.GetDouble()));
+ var pattern = Assert.Single(json.RootElement.GetProperty("patterns").EnumerateArray());
+ Assert.Equal("Mounts.UpperRight", pattern.GetProperty("associations")[3].GetProperty("generatedId").GetString());
+ }
+
+ [Fact]
+ public void Validate_OutsideEntryUsesNamedPatternIdentity()
+ {
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+ var exit = Aetheris.CLI.CliRunner.Run(["validate", Fixture("Invalid", "Set", "pattern-span-containment.firmament"), "--json"], stdout, stderr);
+
+ Assert.Equal(1, exit);
+ Assert.Contains("firmament-feature-footprint-outside-span:Mounts.UpperRight:MountingArea", stdout.ToString(), StringComparison.Ordinal);
+ }
+
+ private static string Fixture(params string[] parts) =>
+ Path.GetFullPath(Path.Combine([AppContext.BaseDirectory, "../../../../fixtures", .. parts]));
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 166a2829..33ccb004 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -1474,6 +1474,29 @@ Model CanonicalPanel {
columns = table.Columns,
table.SourceSpan
}).ToArray() ?? [],
+ sets = document?.StaticAuthoring?.Sets?.Select(set => new
+ {
+ setId = set.Name,
+ elementType = set.ElementType,
+ count = set.Entries.Count,
+ entries = set.Entries.Select(entry => new
+ {
+ entry.Name,
+ entry.Value,
+ entry.SourceOrder,
+ provenance = entry.Provenance
+ })
+ }).ToArray() ?? [],
+ polygons = document?.Polygons?.Select(polygon => new
+ {
+ polygon.Name,
+ polygon.Variant,
+ center = new[] { polygon.CenterX, polygon.CenterY },
+ diagonals = new[] { polygon.DiagonalX, polygon.DiagonalY },
+ polygon.GeneratedPoints,
+ polygon.GeneratedEdges,
+ polygon.SourceSpan
+ }).ToArray() ?? [],
patterns = document?.StaticAuthoring?.Patterns?.Select(pattern => new
{
pattern.Name,
@@ -1481,6 +1504,7 @@ Model CanonicalPanel {
generator = pattern.Template,
count = pattern.GeneratedCount,
generatedInstances = pattern.GeneratedIds,
+ associations = pattern.Associations,
distribution = "AuthoredSourceOrder",
status = "PreservedThroughFeatureAir;InstancesMaterializedAtBRepPlan"
}).ToArray() ?? [],
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2NamedSetTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2NamedSetTests.cs
new file mode 100644
index 00000000..f06854c2
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2NamedSetTests.cs
@@ -0,0 +1,161 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentV2NamedSetTests
+{
+ [Fact]
+ public void PointSet_PreservesNamesOrderValuesAndNamedAccess()
+ {
+ var parse = FirmamentV2Parser.Parse(File.ReadAllText(Fixture("Canonical", "Set", "named-point-access.firmament")));
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ var set = Assert.Single(parse.Document!.StaticAuthoring!.Sets!);
+ Assert.Equal("Point2", set.ElementType);
+ Assert.Equal(["South", "East", "North", "West"], set.Entries.Select(entry => entry.Name));
+ Assert.Equal([0, 1, 2, 3], set.Entries.Select(entry => entry.SourceOrder));
+ Assert.All(set.Entries, entry => Assert.True(entry.Provenance.Length > 0));
+ Assert.NotNull(parse.Document.Profiles);
+ }
+
+ [Fact]
+ public void RecordSet_FeedsExistingTemplatePatternWithNamedIdentities()
+ {
+ var parse = FirmamentV2Parser.Parse(File.ReadAllText(Fixture("Canonical", "Set", "record-payloads.firmament")));
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ var set = Assert.Single(parse.Document!.StaticAuthoring!.Sets!);
+ Assert.Equal("MountSpec", set.ElementType);
+ Assert.Equal("Point2(-20mm, 0mm)", set.Entries[0].RecordFields!["Center"]);
+ var pattern = Assert.Single(parse.Document.StaticAuthoring.Patterns);
+ Assert.Equal(["MountPattern.Left", "MountPattern.Right"], pattern.GeneratedIds);
+ Assert.Equal(["Left", "Right"], pattern.Associations!.Select(item => item.SourceEntry));
+ Assert.Equal(2, parse.Document.ModifyBlocks!.Single().SemanticHoles.Count);
+ }
+
+ [Fact]
+ public void SetPattern_MapsFeatureInSourceOrderAndRetainsEntryIdentity()
+ {
+ var source = File.ReadAllText(Fixture("Canonical", "Set", "pattern-feature-map.firmament"));
+ var expansionDiagnostics = new List<string>();
+ var featureExpansion = FirmamentV2FeatureExpansion.Expand(source, expansionDiagnostics);
+ Assert.NotNull(featureExpansion);
+ var staticDiagnostics = new List<string>();
+ var staticExpansion = CanonicalStaticAuthoring.Expand(featureExpansion.Source, staticDiagnostics);
+ Assert.NotNull(staticExpansion);
+ var first = FirmamentV2Parser.Parse(source);
+ var second = FirmamentV2Parser.Parse(source);
+
+ Assert.True(first.IsSuccess, string.Join(Environment.NewLine, first.Diagnostics) + Environment.NewLine + staticExpansion.Source);
+ Assert.True(second.IsSuccess, string.Join(Environment.NewLine, second.Diagnostics));
+ var pattern = Assert.Single(first.Document!.StaticAuthoring!.Patterns);
+ Assert.Equal(["Drills.First", "Drills.Second"], pattern.GeneratedIds);
+ Assert.Equal(["Drills_First", "Drills_Second"], first.Document.ModifyBlocks!.Single().SemanticHoles.Select(hole => hole.Name));
+ Assert.Equal(first.Document.ModifyBlocks!.Single().SemanticHoles.Select(hole => hole.Center), second.Document!.ModifyBlocks!.Single().SemanticHoles.Select(hole => hole.Center));
+ }
+
+ [Theory]
+ [InlineData("duplicate-entry-name.firmament", "firmament-v2-static-set-duplicate-entry:Points:A")]
+ [InlineData("wrong-element-type.firmament", "firmament-v2-static-set-entry-type-mismatch:Points:A:expected-Point2")]
+ [InlineData("invalid-pattern-target.firmament", "firmament-v2-static-pattern-source-invalid:Bad")]
+ public void InvalidSets_FailTyped(string file, string diagnostic)
+ {
+ var parse = FirmamentV2Parser.Parse(File.ReadAllText(Fixture("Invalid", "Set", file)));
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(parse.Diagnostics, item => item == diagnostic);
+ }
+
+ [Fact]
+ public void EmptySet_IsValidAndPatternProducesNoInstances()
+ {
+ var parse = FirmamentV2Parser.Parse("""
+ Model EmptySet {
+ Units: mm
+ Static Points: Set<Point2> { }
+ Box Base { Size: [20mm, 20mm, 2mm] }
+ Modify Base { Pattern None Over Points { point => Hole<Shaft> H { On: +Z Center: point Diameter: 2mm End: ThroughAll } } }
+ }
+ """);
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ Assert.Empty(Assert.Single(parse.Document!.StaticAuthoring!.Sets!).Entries);
+ Assert.Empty(Assert.Single(parse.Document.StaticAuthoring.Patterns).GeneratedIds);
+ }
+
+ [Fact]
+ public void ExistingArrayEnumAndMatchRemainValid()
+ {
+ var array = FirmamentV2Parser.Parse(File.ReadAllText(Fixture("Canonical", "Patterns", "record-array-hole-pattern.firmament")));
+ var modern = FirmamentV2Parser.Parse(File.ReadAllText(Fixture("Canonical", "Templates", "generic-mounting-plate.firmament")));
+ Assert.True(array.IsSuccess, string.Join(Environment.NewLine, array.Diagnostics));
+ Assert.True(modern.IsSuccess, string.Join(Environment.NewLine, modern.Diagnostics));
+ }
+
+ [Fact]
+ public void MountingSet_UsesExistingSpanContainmentAndExportsArrayParity()
+ {
+ var named = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture("Canonical", "Set", "mounting-points.firmament")));
+ var repeated = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture("Canonical", "Set", "mounting-points.firmament")));
+ var array = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture("Canonical", "Span", "plane-hole-support.firmament")));
+ var invalid = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture("Invalid", "Set", "pattern-span-containment.firmament")));
+
+ Assert.True(named.IsSuccess, string.Join(Environment.NewLine, named.Diagnostics.Select(item => item.Message)));
+ Assert.True(repeated.IsSuccess, string.Join(Environment.NewLine, repeated.Diagnostics.Select(item => item.Message)));
+ Assert.Equal(named.Value.StepText, repeated.Value.StepText);
+ Assert.True(array.IsSuccess, string.Join(Environment.NewLine, array.Diagnostics.Select(item => item.Message)));
+ Assert.Equal(array.Value.StepText, named.Value.StepText);
+ Assert.False(invalid.IsSuccess);
+ Assert.Contains(invalid.Diagnostics, item => item.Message.StartsWith("firmament-feature-footprint-outside-span:Mounts.UpperRight:MountingArea", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void Polygon2Rhombus_LowersToOrdinaryClosedProfileAndRetainsTypedMetadata()
+ {
+ var source = File.ReadAllText(Fixture("Canonical", "Set", "mounting-points.firmament"));
+ var expansionDiagnostics = new List<string>();
+ var expansion = Polygon2RhombusAuthoring.Expand(source, expansionDiagnostics);
+ Assert.NotNull(expansion);
+ var featureExpansion = FirmamentV2FeatureExpansion.Expand(expansion.Source, expansionDiagnostics);
+ Assert.NotNull(featureExpansion);
+ var templateExpansion = FirmamentV2TemplateExpansion.Expand(featureExpansion.Source, expansionDiagnostics);
+ Assert.NotNull(templateExpansion);
+ var staticExpansion = CanonicalStaticAuthoring.Expand(templateExpansion.Source, expansionDiagnostics);
+ Assert.NotNull(staticExpansion);
+ var composition = Aetheris.Kernel.Firmament.Materializer.PrismaticProfileCompositionParser.Parse(staticExpansion.Source);
+ Assert.True(composition.Feature is not null, string.Join(Environment.NewLine, composition.Diagnostics));
+ var parse = FirmamentV2Parser.Parse(source);
+ var profile = ProfileAuthoringParser.ResolveNamedProfile(source, "MountBoundary", out var diagnostics);
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics) + Environment.NewLine + staticExpansion.Source);
+ var polygon = Assert.Single(parse.Document!.Polygons!);
+ Assert.Equal("MountBoundaryShape", polygon.Name);
+ Assert.Equal("Rhombus", polygon.Variant);
+ Assert.Equal([0d, 0d, 90d, 64d], [polygon.CenterX, polygon.CenterY, polygon.DiagonalX, polygon.DiagonalY]);
+ Assert.Equal(4, polygon.GeneratedPoints.Count);
+ Assert.Equal(4, polygon.GeneratedEdges.Count);
+ Assert.Equal(FirmamentV2CanonicalSymbolKind.Polygon2, parse.Document.SymbolTable!.Resolve("MountBoundaryShape")!.Kind);
+ Assert.NotNull(profile);
+ Assert.Empty(diagnostics);
+ Assert.Equal(4, profile.Loops.Single().Segments.Count);
+ Assert.Equal(2880d, Math.Abs(Aetheris.Kernel.Firmament.Materializer.ResolvedProfile2DValidator.Validate(profile).SignedArea), 8);
+ }
+
+ [Theory]
+ [InlineData("Hexagon", "[90mm,64mm]", "firmament-polygon2-variant-unsupported:P:Hexagon")]
+ [InlineData("Rhombus", "[90mm,0mm]", "firmament-polygon2-invalid-geometry:P")]
+ public void Polygon2_InvalidClosedVariantOrGeometryFailsTyped(string variant, string diagonals, string diagnostic)
+ {
+ var parse = FirmamentV2Parser.Parse($$"""
+ Model InvalidPolygon {
+ Units: mm
+ Polygon2<{{variant}}> P { Center: [0mm,0mm]; Diagonals: {{diagonals}} }
+ Box Base { Size: [20mm,20mm,2mm] }
+ }
+ """);
+
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(diagnostic, parse.Diagnostics);
+ }
+
+ private static string Fixture(params string[] parts) =>
+ Path.GetFullPath(Path.Combine([AppContext.BaseDirectory, "../../../../fixtures", .. parts]));
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index d460eaf4..e20d95c6 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -189,7 +189,8 @@ public static class FirmamentBuildAndExport
pattern.Template,
pattern.GeneratedCount,
pattern.GeneratedIds,
- "FiniteStaticArray"))
+ pattern.Associations is null ? "FiniteStaticArray" : "NamedSetAuthoredSourceOrder",
+ Associations: pattern.Associations))
.OrderBy(pattern => pattern.Name, StringComparer.Ordinal)
.ToArray();
if (edgeFinishes.Length == 0 && patterns.Length == 0) return export;
diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
index a5319230..34951014 100644
--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
@@ -75,7 +75,8 @@ public sealed record FirmamentSemanticPatternReport(
int Count,
IReadOnlyList<string> GeneratedInstances,
string Distribution,
- string Status = "PreservedThroughFeatureAir;InstancesMaterializedAtBRepPlan");
+ string Status = "PreservedThroughFeatureAir;InstancesMaterializedAtBRepPlan",
+ IReadOnlyList<FirmamentV2.FirmamentV2PatternAssociation>? Associations = null);
public sealed record FirmamentSweepReport(
string Path,
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
index 6486e61c..46167e5d 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
@@ -8,6 +8,7 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;
internal static class CanonicalStaticAuthoring
{
internal const string Prefix = "firmament-v2-static-";
+ private const int MaxPatternExpansion = 1024;
internal sealed record Result(string Source, FirmamentV2StaticAuthoringDocument? Document);
private sealed record Template(string Name, string Type, string Parameter, string Body, FirmamentV2SourceSpan Span);
@@ -20,6 +21,7 @@ internal static class CanonicalStaticAuthoring
var names = new HashSet<string>(StringComparer.Ordinal);
var recordTypes = new List<FirmamentV2RecordTypeDecl>();
var arrays = new List<FirmamentV2StaticArrayDecl>();
+ var sets = new List<FirmamentV2StaticSetDecl>();
var staticRecords = new List<FirmamentV2StaticRecordDecl>();
var tables = new List<FirmamentV2StaticTableDecl>();
var templates = new List<Template>();
@@ -47,6 +49,24 @@ internal static class CanonicalStaticAuthoring
}
var recordByName = recordTypes.ToDictionary(x => x.Name, StringComparer.Ordinal);
+ foreach (Match nested in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*:\s*Set\s*<\s*Set\s*<", RegexOptions.CultureInvariant))
+ diagnostics.Add(Prefix + "set-element-type-unsupported:" + nested.Groups["name"].Value + ":nested-Set");
+
+ // Set<T> is a built-in finite value form, not a general generic or runtime collection.
+ // Entry order and names are retained as semantic evidence while values are erased before AIR.
+ foreach (Match header in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*:\s*Set\s*<\s*(?<type>[A-Za-z_]\w*)\s*>\s*\{", RegexOptions.CultureInvariant))
+ {
+ var open = source.IndexOf('{', header.Index); var close = MatchPair(source, open, '{', '}');
+ var name = header.Groups["name"].Value; var type = header.Groups["type"].Value;
+ if (close < 0) { diagnostics.Add(Prefix + "set-malformed:" + name); continue; }
+ if (!IsSupportedSetElementType(type, recordByName)) { diagnostics.Add(Prefix + "set-element-type-unsupported:" + name + ":" + type); continue; }
+ if (!names.Add(name)) { diagnostics.Add(FirmamentV2Parser.DuplicateName + ":Static:" + name); continue; }
+ var entries = ParseSetEntries(source, open + 1, close, name, type, recordByName, diagnostics);
+ sets.Add(new(name, type, entries, new(header.Index, close - header.Index + 1)));
+ changes.Add((header.Index, close - header.Index + 1, string.Empty));
+ }
+ var setByName = sets.ToDictionary(x => x.Name, StringComparer.Ordinal);
+
// Tables share Record typing with Static values, but intentionally preserve their
// columnar spelling for source inspection. The template binder has already checked
// cells and lookups before this phase erases the compile-time declaration.
@@ -110,6 +130,22 @@ internal static class CanonicalStaticAuthoring
}
var arrayByName = arrays.ToDictionary(x => x.Name, StringComparer.Ordinal);
+ // Named access is canonical. It substitutes the authored typed value (or a Record
+ // member) before Profile/Compose parsing; no public index operation is introduced.
+ foreach (var set in sets)
+ {
+ AddPointConsumerDeclarations(source, changes, set);
+ foreach (var entry in set.Entries)
+ {
+ if (entry.RecordFields is null)
+ AddSetValueSubstitutions(source, changes, set, entry);
+ else
+ foreach (var field in entry.RecordFields)
+ AddSubstitutions(source, changes, $@"\b{Regex.Escape(set.Name)}\s*\.\s*{Regex.Escape(entry.Name)}\s*\.\s*{Regex.Escape(field.Key)}\b", field.Value);
+ }
+ AddSubstitutions(source, changes, $@"\b{Regex.Escape(set.Name)}\s*\.\s*Count\b", set.Entries.Count.ToString(CultureInfo.InvariantCulture));
+ }
+
// Canonical finite feature Template: Template<Parameter: RecordType> Name { ... }.
// The former Template Name(RecordType parameter) spelling remains warning-free
// compatibility syntax for persisted Preview sources.
@@ -147,7 +183,13 @@ internal static class CanonicalStaticAuthoring
foreach (Match pattern in Regex.Matches(source, @"\bPattern\s+(?<name>[A-Za-z_]\w*)\s+Over\s+(?<array>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
{
var open = source.IndexOf('{', pattern.Index); var close = MatchPair(source, open, '{', '}');
- if (close < 0 || !arrayByName.TryGetValue(pattern.Groups["array"].Value, out var array)) { diagnostics.Add(Prefix + "pattern-source-invalid:" + pattern.Groups["name"].Value); continue; }
+ var sourceName = pattern.Groups["array"].Value;
+ if (close >= 0 && setByName.TryGetValue(sourceName, out var set))
+ {
+ ExpandSetPattern(source, pattern, open, close, set, templateByName, changes, patterns, diagnostics);
+ continue;
+ }
+ if (close < 0 || !arrayByName.TryGetValue(sourceName, out var array)) { diagnostics.Add(Prefix + "pattern-source-invalid:" + pattern.Groups["name"].Value); continue; }
var invocation = Regex.Match(source[(open + 1)..close], @"^(?:\s)*(?<template>[A-Za-z_]\w*)\s*(?:<\s*Current\s*>|\(\s*Current\s*\))\s*$", RegexOptions.CultureInvariant);
if (!invocation.Success || !templateByName.TryGetValue(invocation.Groups["template"].Value, out var template) || template.Type != array.ElementType) { diagnostics.Add(Prefix + "pattern-body-invalid:" + pattern.Groups["name"].Value); continue; }
var generated = new List<string>(); var output = new List<string>();
@@ -221,12 +263,148 @@ internal static class CanonicalStaticAuthoring
// A static declaration / Require is erased as a whole. Do not also apply a
// substitution nested inside that erased span: applying the nested edit first
// changes the parent span's offsets and corrupts the following declaration.
- var erasures = changes.Where(change => change.Text.Length == 0).ToArray();
+ var erasures = changes.Where(change => change.Text.Length == 0
+ || Regex.IsMatch(source.Substring(change.Start, Math.Min(change.Length, source.Length - change.Start)), @"^\s*(?:Static\s+\w+\s*:\s*Set\s*<|Pattern\s+\w+\s+Over\b)", RegexOptions.CultureInvariant)).ToArray();
foreach (var change in changes
.Where(change => !erasures.Any(erase => erase.Start < change.Start && change.Start < erase.Start + erase.Length))
.OrderByDescending(change => change.Start))
source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
- return new(source, new(recordTypes, arrays, templates.Select(t => new FirmamentV2CanonicalTemplateDecl(t.Name, t.Type, t.Parameter, t.Body, t.Span)).ToArray(), patterns, requires, semanticConstraints, projections, staticRecords, tables));
+ return new(source, new(recordTypes, arrays, templates.Select(t => new FirmamentV2CanonicalTemplateDecl(t.Name, t.Type, t.Parameter, t.Body, t.Span)).ToArray(), patterns, requires, semanticConstraints, projections, staticRecords, tables, sets));
+ }
+
+ private static IReadOnlyList<FirmamentV2StaticSetEntry> ParseSetEntries(string source, int start, int end, string setName, string elementType,
+ IReadOnlyDictionary<string, FirmamentV2RecordTypeDecl> recordTypes, List<string> diagnostics)
+ {
+ var body = source[start..end];
+ var headers = Regex.Matches(body, @"(?<![A-Za-z0-9_])(?<name>[A-Za-z_]\w*)\s*=>", RegexOptions.CultureInvariant).Cast<Match>().ToArray();
+ var result = new List<FirmamentV2StaticSetEntry>(); var names = new HashSet<string>(StringComparer.Ordinal);
+ for (var index = 0; index < headers.Length; index++)
+ {
+ var header = headers[index]; var entryName = header.Groups["name"].Value;
+ var valueStart = header.Index + header.Length; var valueEnd = index + 1 < headers.Length ? headers[index + 1].Index : body.Length;
+ var value = body[valueStart..valueEnd].Trim().TrimEnd(',', ';').Trim();
+ var span = new FirmamentV2SourceSpan(start + header.Index, valueEnd - header.Index);
+ if (!names.Add(entryName)) { diagnostics.Add(Prefix + "set-duplicate-entry:" + setName + ":" + entryName); continue; }
+ IReadOnlyDictionary<string, string>? fields = null;
+ if (recordTypes.TryGetValue(elementType, out var record))
+ {
+ var literal = Regex.Match(value, $@"^{Regex.Escape(elementType)}\s*\{{(?<body>[\s\S]*)\}}$", RegexOptions.CultureInvariant);
+ if (!literal.Success) { diagnostics.Add(Prefix + "set-entry-type-mismatch:" + setName + ":" + entryName + ":expected-" + elementType); continue; }
+ fields = Fields(literal.Groups["body"].Value);
+ var missing = record.Fields.Keys.Where(field => !fields.ContainsKey(field)).ToArray();
+ var extra = fields.Keys.Where(field => !record.Fields.ContainsKey(field)).ToArray();
+ if (missing.Length > 0) diagnostics.Add(Prefix + "record-missing-field:" + setName + "." + entryName + ":" + string.Join(",", missing));
+ if (extra.Length > 0) diagnostics.Add(Prefix + "record-extra-field:" + setName + "." + entryName + ":" + string.Join(",", extra));
+ foreach (var field in fields)
+ if (record.Fields.TryGetValue(field.Key, out var fieldType) && !ValueMatchesType(field.Value, fieldType))
+ diagnostics.Add(Prefix + "set-entry-field-type-mismatch:" + setName + ":" + entryName + ":" + field.Key + ":expected-" + fieldType);
+ }
+ else if (!ValueMatchesType(value, elementType))
+ { diagnostics.Add(Prefix + "set-entry-type-mismatch:" + setName + ":" + entryName + ":expected-" + elementType); continue; }
+ result.Add(new(entryName, value, index, span, fields));
+ }
+ return result;
+ }
+
+ private static void ExpandSetPattern(string source, Match pattern, int open, int close, FirmamentV2StaticSetDecl set,
+ IReadOnlyDictionary<string, Template> templates, List<(int Start, int Length, string Text)> changes,
+ List<FirmamentV2CanonicalPatternDecl> patterns, List<string> diagnostics)
+ {
+ var patternName = pattern.Groups["name"].Value;
+ if (set.Entries.Count > MaxPatternExpansion) { diagnostics.Add(Prefix + "pattern-expansion-limit:" + patternName + ":" + set.Entries.Count); return; }
+ var body = source[(open + 1)..close].Trim();
+ var arrow = Regex.Match(body, @"^(?<binder>[A-Za-z_]\w*)\s*=>\s*(?<mapping>[\s\S]+)$", RegexOptions.CultureInvariant);
+ if (!arrow.Success) { diagnostics.Add(Prefix + "pattern-body-invalid:" + patternName); return; }
+ var binder = arrow.Groups["binder"].Value; var mapping = arrow.Groups["mapping"].Value.Trim();
+ var output = new List<string>(); var generated = new List<string>(); var associations = new List<FirmamentV2PatternAssociation>();
+ foreach (var entry in set.Entries)
+ {
+ var semanticId = patternName + "." + entry.Name;
+ var materializedId = patternName + "_" + entry.Name;
+ string? declaration;
+ var templateCall = Regex.Match(mapping, @"^(?<template>[A-Za-z_]\w*)\s*(?:<\s*Current\s*>|\(\s*Current\s*\))$", RegexOptions.CultureInvariant);
+ if (templateCall.Success && templates.TryGetValue(templateCall.Groups["template"].Value, out var template) && entry.RecordFields is not null && template.Type == set.ElementType)
+ declaration = Instantiate(template, entry.RecordFields, materializedId, true, diagnostics);
+ else
+ {
+ declaration = mapping;
+ if (entry.RecordFields is not null)
+ foreach (var field in entry.RecordFields)
+ declaration = Regex.Replace(declaration, $@"\b{Regex.Escape(binder)}\s*\.\s*{Regex.Escape(field.Key)}\b", field.Value, RegexOptions.CultureInvariant);
+ else declaration = Regex.Replace(declaration, $@"\b{Regex.Escape(binder)}\b", entry.Value, RegexOptions.CultureInvariant);
+ var construction = Regex.Match(declaration, @"\b(?:Hole\s*<\s*(?:Shaft|Counterbore|Countersink)\s*>|Slot\s*<\s*(?:Capsule|RoundedRectangle)\s*>|Boss|Pocket|EdgeFinish)\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
+ if (!construction.Success) { diagnostics.Add(Prefix + "pattern-body-invalid:" + patternName); return; }
+ declaration = declaration.Remove(construction.Groups["name"].Index, construction.Groups["name"].Length).Insert(construction.Groups["name"].Index, materializedId);
+ var openingBrace = declaration.IndexOf('{', construction.Index);
+ declaration = declaration.Insert(openingBrace + 1, " PatternIdentity: " + semanticId + " ");
+ }
+ if (declaration is null) continue;
+ output.Add(declaration); generated.Add(semanticId);
+ associations.Add(new(semanticId, set.Name, entry.Name, entry.Value, entry.SourceOrder, entry.Provenance));
+ }
+ patterns.Add(new(patternName, set.Name, Regex.Match(mapping, @"^[A-Za-z_]\w*").Value, generated.Count, generated,
+ new(pattern.Index, close - pattern.Index + 1), associations));
+ changes.Add((pattern.Index, close - pattern.Index + 1, string.Join(Environment.NewLine, output)));
+ }
+
+ private static bool IsSupportedSetElementType(string type, IReadOnlyDictionary<string, FirmamentV2RecordTypeDecl> records) =>
+ type is "Point2" or "Point3" or "Vector2" or "Length" or "Angle" or "Int" or "Float" or "Bool" || records.ContainsKey(type);
+
+ private static bool ValueMatchesType(string value, string type)
+ {
+ value = value.Trim();
+ return type switch
+ {
+ "Point2" => Regex.IsMatch(value, @"^Point2\s*\(\s*[-+]?\d+(?:\.\d+)?mm\s*,\s*[-+]?\d+(?:\.\d+)?mm\s*\)$", RegexOptions.CultureInvariant),
+ "Point3" => Regex.IsMatch(value, @"^Point3\s*\(\s*[-+]?\d+(?:\.\d+)?mm\s*,\s*[-+]?\d+(?:\.\d+)?mm\s*,\s*[-+]?\d+(?:\.\d+)?mm\s*\)$", RegexOptions.CultureInvariant),
+ "Vector2" => Regex.IsMatch(value, @"^Vector2\s*\(\s*[-+]?\d+(?:\.\d+)?\s*,\s*[-+]?\d+(?:\.\d+)?\s*\)$", RegexOptions.CultureInvariant),
+ "Length" => Regex.IsMatch(value, @"^[-+]?\d+(?:\.\d+)?mm$", RegexOptions.CultureInvariant),
+ "Angle" => Regex.IsMatch(value, @"^[-+]?\d+(?:\.\d+)?deg$", RegexOptions.CultureInvariant),
+ "Int" => Regex.IsMatch(value, @"^[-+]?\d+$", RegexOptions.CultureInvariant),
+ "Float" => Regex.IsMatch(value, @"^[-+]?\d+(?:\.\d+)?$", RegexOptions.CultureInvariant),
+ "Bool" => value is "true" or "false",
+ _ => Regex.IsMatch(value, $@"^{Regex.Escape(type)}\s*\{{", RegexOptions.CultureInvariant)
+ };
+ }
+
+ private static void AddSubstitutions(string source, List<(int Start, int Length, string Text)> changes, string pattern, string replacement)
+ {
+ foreach (Match match in Regex.Matches(source, pattern, RegexOptions.CultureInvariant)) changes.Add((match.Index, match.Length, replacement));
+ }
+
+ private static void AddSetValueSubstitutions(string source, List<(int Start, int Length, string Text)> changes,
+ FirmamentV2StaticSetDecl set, FirmamentV2StaticSetEntry entry)
+ {
+ var pattern = $@"\b{Regex.Escape(set.Name)}\s*\.\s*{Regex.Escape(entry.Name)}\b";
+ foreach (Match match in Regex.Matches(source, pattern, RegexOptions.CultureInvariant))
+ {
+ var prefix = source[Math.Max(0, match.Index - 12)..match.Index];
+ var needsNamedPoint = set.ElementType == "Point2" && Regex.IsMatch(prefix, @"(?:From|To)\s*:\s*$", RegexOptions.CultureInvariant);
+ changes.Add((match.Index, match.Length, needsNamedPoint ? set.Name + "_" + entry.Name : entry.Value));
+ }
+ }
+
+ private static string PointDeclarations(string setName, string elementType, IReadOnlyList<FirmamentV2StaticSetEntry> entries)
+ {
+ if (elementType != "Point2") return string.Empty;
+ return string.Join(Environment.NewLine, entries.Select(entry =>
+ {
+ var match = Regex.Match(entry.Value, @"^Point2\s*\((?<body>[^)]+)\)$", RegexOptions.CultureInvariant);
+ return match.Success ? $"Point2 {setName}_{entry.Name} {{ Position: [{match.Groups["body"].Value}] }}" : string.Empty;
+ }));
+ }
+
+ private static void AddPointConsumerDeclarations(string source, List<(int Start, int Length, string Text)> changes, FirmamentV2StaticSetDecl set)
+ {
+ if (set.ElementType != "Point2" || !Regex.IsMatch(source,
+ $@"(?:From|To)\s*:\s*{Regex.Escape(set.Name)}\s*\.", RegexOptions.CultureInvariant)) return;
+ foreach (Match layout in Regex.Matches(source, @"\bConcept\s+Struct\s+[A-Za-z_]\w*(?:\s+On\s+[A-Za-z_]\w*)?\s*\{", RegexOptions.CultureInvariant))
+ {
+ var open = source.IndexOf('{', layout.Index); var close = MatchPair(source, open, '{', '}');
+ if (close < 0 || !Regex.IsMatch(source[(open + 1)..close], $@"(?:From|To)\s*:\s*{Regex.Escape(set.Name)}\s*\.", RegexOptions.CultureInvariant)) continue;
+ changes.Add((open + 1, 0, Environment.NewLine + PointDeclarations(set.Name, set.ElementType, set.Entries) + Environment.NewLine));
+ return;
+ }
}
private static string? Instantiate(Template template, IReadOnlyDictionary<string, string> values, string id, bool patterned, List<string> diagnostics)
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs
index 53381256..54e6084b 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs
@@ -9,6 +9,8 @@ public enum FirmamentV2CanonicalSymbolKind
{
Record,
StaticArray,
+ StaticSet,
+ Polygon2,
Template,
Pattern,
Require,
@@ -89,12 +91,14 @@ internal static class FirmamentV2CanonicalSymbolBinder
{
foreach (var record in staticAuthoring.RecordTypes) Add(record.Name, FirmamentV2CanonicalSymbolKind.Record, record.SourceSpan);
foreach (var array in staticAuthoring.Arrays) Add(array.Name, FirmamentV2CanonicalSymbolKind.StaticArray, array.SourceSpan);
+ foreach (var set in staticAuthoring.Sets ?? []) Add(set.Name, FirmamentV2CanonicalSymbolKind.StaticSet, set.SourceSpan);
foreach (var template in staticAuthoring.Templates) Add(template.Name, FirmamentV2CanonicalSymbolKind.Template, template.SourceSpan);
foreach (var pattern in staticAuthoring.Patterns) Add(pattern.Name, FirmamentV2CanonicalSymbolKind.Pattern, pattern.SourceSpan);
foreach (var require in staticAuthoring.Requires) Add(require.Name, FirmamentV2CanonicalSymbolKind.Require, require.SourceSpan);
}
foreach (var profile in document.Profiles ?? []) Add(profile.Name, FirmamentV2CanonicalSymbolKind.Profile, profile.SourceSpan);
+ foreach (var polygon in document.Polygons ?? []) Add(polygon.Name, FirmamentV2CanonicalSymbolKind.Polygon2, polygon.SourceSpan);
foreach (var compose in document.Composes ?? []) Add(compose.Name, FirmamentV2CanonicalSymbolKind.Compose, compose.SourceSpan);
foreach (var boss in document.Bosses ?? []) Add(boss.Name, FirmamentV2CanonicalSymbolKind.Boss, boss.SourceSpan);
foreach (var pocket in document.Pockets ?? []) Add(pocket.Name, FirmamentV2CanonicalSymbolKind.Pocket, pocket.SourceSpan);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 673d8e01..8daf6e32 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -3,7 +3,7 @@ using Aetheris.Surfacing;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
-public sealed record FirmamentV2Document(string ModelName, string Units, IReadOnlyList<FirmamentV2SolidBinding> Solids, IReadOnlyList<FirmamentV2ModifyBlock>? ModifyBlocks = null, IReadOnlyList<FirmamentV2TemplateDecl>? Templates = null, IReadOnlyList<FirmamentV2PmiDecl>? Pmi = null, IReadOnlyList<FirmamentV2RecognizedRegion>? RecognizedRegions = null, IReadOnlyList<FirmamentV2ReplacementDecl>? Replacements = null, IReadOnlyList<FirmamentV2LetDeclaration>? Lets = null, IReadOnlyList<FirmamentV2BoundLet>? BoundLets = null, IReadOnlyList<FirmamentV2LetRecordDeclaration>? LetRecords = null, IReadOnlyList<FirmamentV2BoundLetRecord>? BoundLetRecords = null, IReadOnlyList<FirmamentV2ManufacturingConceptDeclaration>? ManufacturingConcepts = null, IReadOnlyList<FirmamentV2FeatureConceptDeclaration>? FeatureConcepts = null, FirmamentV2PmiBlock? PmiBlock = null, FirmamentV2BoundPmiBlock? BoundPmi = null, ConceptIrDocument? ConceptIr = null, IReadOnlyList<FirmamentV2LatticeFillDecl>? LatticeFills = null, IReadOnlyList<FirmamentV2StandaloneLatticeFillDecl>? StandaloneLatticeFills = null, IReadOnlyList<FirmamentV2ProfileDecl>? Profiles = null, IReadOnlyList<FirmamentV2ComposeDecl>? Composes = null, IReadOnlyList<FirmamentV2SelectionDecl>? Selections = null, FirmamentV2StaticAuthoringDocument? StaticAuthoring = null, FirmamentV2CanonicalSymbolTable? SymbolTable = null, IReadOnlyList<FirmamentV2VolumeAssertion>? VolumeAssertions = null, IReadOnlyList<ConceptIrTemplateInstantiation>? TemplateInstantiations = null, IReadOnlyList<PanelIr>? Panels = null, IReadOnlyList<FirmamentV2BossDecl>? Bosses = null, IReadOnlyList<FirmamentV2PocketDecl>? Pockets = null, IReadOnlyList<FirmamentV2FeatureDefinition>? FeatureDefinitions = null, IReadOnlyList<FirmamentV2FeatureInvocation>? FeatureInvocations = null, FirmamentV2FeatureExpansionMetrics? FeatureExpansion = null)
+public sealed record FirmamentV2Document(string ModelName, string Units, IReadOnlyList<FirmamentV2SolidBinding> Solids, IReadOnlyList<FirmamentV2ModifyBlock>? ModifyBlocks = null, IReadOnlyList<FirmamentV2TemplateDecl>? Templates = null, IReadOnlyList<FirmamentV2PmiDecl>? Pmi = null, IReadOnlyList<FirmamentV2RecognizedRegion>? RecognizedRegions = null, IReadOnlyList<FirmamentV2ReplacementDecl>? Replacements = null, IReadOnlyList<FirmamentV2LetDeclaration>? Lets = null, IReadOnlyList<FirmamentV2BoundLet>? BoundLets = null, IReadOnlyList<FirmamentV2LetRecordDeclaration>? LetRecords = null, IReadOnlyList<FirmamentV2BoundLetRecord>? BoundLetRecords = null, IReadOnlyList<FirmamentV2ManufacturingConceptDeclaration>? ManufacturingConcepts = null, IReadOnlyList<FirmamentV2FeatureConceptDeclaration>? FeatureConcepts = null, FirmamentV2PmiBlock? PmiBlock = null, FirmamentV2BoundPmiBlock? BoundPmi = null, ConceptIrDocument? ConceptIr = null, IReadOnlyList<FirmamentV2LatticeFillDecl>? LatticeFills = null, IReadOnlyList<FirmamentV2StandaloneLatticeFillDecl>? StandaloneLatticeFills = null, IReadOnlyList<FirmamentV2ProfileDecl>? Profiles = null, IReadOnlyList<FirmamentV2ComposeDecl>? Composes = null, IReadOnlyList<FirmamentV2SelectionDecl>? Selections = null, FirmamentV2StaticAuthoringDocument? StaticAuthoring = null, FirmamentV2CanonicalSymbolTable? SymbolTable = null, IReadOnlyList<FirmamentV2VolumeAssertion>? VolumeAssertions = null, IReadOnlyList<ConceptIrTemplateInstantiation>? TemplateInstantiations = null, IReadOnlyList<PanelIr>? Panels = null, IReadOnlyList<FirmamentV2BossDecl>? Bosses = null, IReadOnlyList<FirmamentV2PocketDecl>? Pockets = null, IReadOnlyList<FirmamentV2FeatureDefinition>? FeatureDefinitions = null, IReadOnlyList<FirmamentV2FeatureInvocation>? FeatureInvocations = null, FirmamentV2FeatureExpansionMetrics? FeatureExpansion = null, IReadOnlyList<FirmamentV2Polygon2Decl>? Polygons = null)
{
public FirmamentV2SolidBinding Solid => Solids[^1];
public FirmamentV2SideHoleIntent? SideHoleIntent => ModifyBlocks?.SelectMany(m => m.Regions.Select(r =>
@@ -104,6 +104,18 @@ public sealed record ImportedStepTopologyMap(IReadOnlyDictionary<string, string>
}
}
+/// <summary>A closed, typed planar shape declaration retained across its lowering to ordinary guides.</summary>
+public sealed record FirmamentV2Polygon2Decl(
+ string Name,
+ string Variant,
+ double CenterX,
+ double CenterY,
+ double DiagonalX,
+ double DiagonalY,
+ IReadOnlyList<string> GeneratedPoints,
+ IReadOnlyList<string> GeneratedEdges,
+ FirmamentV2SourceSpan SourceSpan);
+
public sealed record FirmamentV2FeatureParameter(string Name, string Type, string? DefaultExpression = null);
public sealed record FirmamentV2FeatureDefinition(string Name, IReadOnlyList<FirmamentV2FeatureParameter> Parameters,
string ReturnType, FirmamentV2SourceSpan SourceSpan, string Scope, string Evaluation);
@@ -241,14 +253,18 @@ public sealed record FirmamentV2BossDecl(string Name, string Host, string On, st
public sealed record FirmamentV2PocketDecl(string Name, string Host, string On, string Profile, double Depth, double HostThickness, double RemainingFloor, double MinimumFloorThickness, string MinimumFloorPolicySource, string StableId, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2SelectionDecl(string Name, string Target, string Source, string Requirement, FirmamentV2SourceSpan SourceSpan);
/// <summary>Normalized, erased-before-materialization evidence for canonical static authoring.</summary>
-public sealed record FirmamentV2StaticAuthoringDocument(IReadOnlyList<FirmamentV2RecordTypeDecl> RecordTypes, IReadOnlyList<FirmamentV2StaticArrayDecl> Arrays, IReadOnlyList<FirmamentV2CanonicalTemplateDecl> Templates, IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, IReadOnlyList<FirmamentV2RequireDecl> Requires, IReadOnlyList<FirmamentV2SemanticConstraint>? SemanticConstraints = null, IReadOnlyDictionary<string, FirmamentV2PmiProjection>? PmiProjections = null, IReadOnlyList<FirmamentV2StaticRecordDecl>? StaticRecords = null, IReadOnlyList<FirmamentV2StaticTableDecl>? Tables = null);
+public sealed record FirmamentV2StaticAuthoringDocument(IReadOnlyList<FirmamentV2RecordTypeDecl> RecordTypes, IReadOnlyList<FirmamentV2StaticArrayDecl> Arrays, IReadOnlyList<FirmamentV2CanonicalTemplateDecl> Templates, IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, IReadOnlyList<FirmamentV2RequireDecl> Requires, IReadOnlyList<FirmamentV2SemanticConstraint>? SemanticConstraints = null, IReadOnlyDictionary<string, FirmamentV2PmiProjection>? PmiProjections = null, IReadOnlyList<FirmamentV2StaticRecordDecl>? StaticRecords = null, IReadOnlyList<FirmamentV2StaticTableDecl>? Tables = null, IReadOnlyList<FirmamentV2StaticSetDecl>? Sets = null);
public sealed record FirmamentV2RecordTypeDecl(string Name, IReadOnlyDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2StaticArrayDecl(string Name, string ElementType, IReadOnlyList<IReadOnlyDictionary<string, string>> Elements, FirmamentV2SourceSpan SourceSpan);
+/// <summary>A finite immutable source-ordered collection whose entry names are semantic identity.</summary>
+public sealed record FirmamentV2StaticSetDecl(string Name, string ElementType, IReadOnlyList<FirmamentV2StaticSetEntry> Entries, FirmamentV2SourceSpan SourceSpan);
+public sealed record FirmamentV2StaticSetEntry(string Name, string Value, int SourceOrder, FirmamentV2SourceSpan Provenance, IReadOnlyDictionary<string, string>? RecordFields = null);
public sealed record FirmamentV2StaticRecordDecl(string Name, string RecordType, IReadOnlyDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);
/// <summary>Columnar compile-time table evidence. Rows are created only on static lookup and never enter AIR.</summary>
public sealed record FirmamentV2StaticTableDecl(string Name, string RowType, string? KeyField, IReadOnlyDictionary<string, IReadOnlyList<string>> Columns, int RowCount, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2CanonicalTemplateDecl(string Name, string ParameterType, string ParameterName, string Body, FirmamentV2SourceSpan SourceSpan);
-public sealed record FirmamentV2CanonicalPatternDecl(string Name, string Source, string Template, int GeneratedCount, IReadOnlyList<string> GeneratedIds, FirmamentV2SourceSpan SourceSpan);
+public sealed record FirmamentV2CanonicalPatternDecl(string Name, string Source, string Template, int GeneratedCount, IReadOnlyList<string> GeneratedIds, FirmamentV2SourceSpan SourceSpan, IReadOnlyList<FirmamentV2PatternAssociation>? Associations = null);
+public sealed record FirmamentV2PatternAssociation(string GeneratedId, string SourceSet, string SourceEntry, string SourceValue, int ExpansionOrdinal, FirmamentV2SourceSpan Provenance);
public sealed record FirmamentV2RequireDecl(string Name, string Expression, bool Value, FirmamentV2SourceSpan SourceSpan, string? Provenance = null, string? Subject = null, string? Expected = null, string? ToleranceSource = null);
public sealed record FirmamentV2LatticeFillDecl(string Name, string Host, FirmamentV2FillRegionDecl Region, string Pattern, double CellSize, double StrutRadius, string BoundaryPolicy, FirmamentV2SourceSpan SourceSpan);
/// <summary>M9R's admitted standalone material body. It is intentionally distinct from the deferred host-replacement Fill.</summary>
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 75cb4531..c3b10177 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -305,6 +305,15 @@ public static class FirmamentV2Parser
sourceText=ProfileModificationTemplateLibrary.Source+Environment.NewLine+Regex.Replace(sourceText,@"\bUse\s+Profile\.Modifications\s*;",string.Empty,RegexOptions.CultureInvariant);
var diagnostics = new List<string> { "firmament-v2-parser-invoked" };
var source = StripLineComments(sourceText);
+ var polygonExpansion = Polygon2RhombusAuthoring.Expand(source, diagnostics);
+ if (polygonExpansion is null)
+ {
+ diagnostics.Add("firmament-v2-parse-failed");
+ return FirmamentV2ParseResult.Failure(
+ diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray(),
+ FirmamentV2ParseDisposition.RecognizedInvalid);
+ }
+ source = polygonExpansion.Source;
var pipelineContextDiagnostics = ProfileAuthoringParser.ValidatePipelineContexts(source);
if (pipelineContextDiagnostics.Count > 0)
{
@@ -363,7 +372,7 @@ public static class FirmamentV2Parser
var panelDocument = new FirmamentV2Document(panelCompilation.ModelName, "mm", [],
TemplateInstantiations: templateExpansion.Instantiations, Panels: panelCompilation.Panels,
FeatureDefinitions: featureExpansion.Definitions, FeatureInvocations: featureExpansion.Invocations,
- FeatureExpansion: featureExpansion.Metrics);
+ FeatureExpansion: featureExpansion.Metrics, Polygons: polygonExpansion.Polygons);
return FirmamentV2ParseResult.Success(panelDocument, diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray());
}
@@ -384,7 +393,7 @@ public static class FirmamentV2Parser
if (parsed.Document is null) return parsed;
return WithFeatureMetadata(
- AttachVolumeAssertionsAndSymbols(parsed, source, canonicalStaticExpansion.Document, diagnostics),
+ AttachVolumeAssertionsAndSymbols(WithPolygonMetadata(parsed, polygonExpansion), source, canonicalStaticExpansion.Document, diagnostics),
featureExpansion);
}
@@ -397,7 +406,7 @@ public static class FirmamentV2Parser
if (Regex.IsMatch(source, @"\bConcept\s+(?:Struct\s+)?[A-Za-z_]", RegexOptions.CultureInvariant)
|| Regex.IsMatch(source, @"\b(?:Struct|Model)\s+[A-Za-z_][A-Za-z0-9_]*\s*(?::\s*[A-Za-z_][A-Za-z0-9_]*)?\s*\{", RegexOptions.CultureInvariant))
return Recognized(WithFeatureMetadata(
- AttachVolumeAssertionsAndSymbols(ParseConceptModelingDocument(RemoveCanonicalVolumeAssertions(source), diagnostics, templateExpansion.Instantiations), source, canonicalStaticExpansion.Document, diagnostics),
+ AttachVolumeAssertionsAndSymbols(WithPolygonMetadata(ParseConceptModelingDocument(RemoveCanonicalVolumeAssertions(source), diagnostics, templateExpansion.Instantiations), polygonExpansion), source, canonicalStaticExpansion.Document, diagnostics),
featureExpansion));
if (Regex.IsMatch(source, @"^\s*Model\b", RegexOptions.CultureInvariant))
@@ -497,6 +506,13 @@ public static class FirmamentV2Parser
}
};
+ private static FirmamentV2ParseResult WithPolygonMetadata(
+ FirmamentV2ParseResult result,
+ Polygon2RhombusAuthoring.Result expansion) =>
+ result.Document is null
+ ? result
+ : result with { Document = result.Document with { Polygons = expansion.Polygons } };
+
private static bool IsV2AdmissionCandidate(string source) =>
ModelRegex.IsMatch(source)
|| Regex.IsMatch(source, @"^\s*model\s+[A-Za-z_][A-Za-z0-9_]*\b", RegexOptions.CultureInvariant)
@@ -1550,9 +1566,9 @@ public static class FirmamentV2Parser
var knownFields = variant switch
{
- FirmamentV2SemanticHoleVariant.Counterbore => new[] { "On", "Center", "Diameter", "CounterboreDiameter", "CounterboreDepth", "End" },
- FirmamentV2SemanticHoleVariant.Countersink => new[] { "On", "Center", "Diameter", "CountersinkDiameter", "CountersinkAngle", "End" },
- _ => new[] { "On", "Center", "Diameter", "End" }
+ FirmamentV2SemanticHoleVariant.Counterbore => new[] { "On", "Center", "Diameter", "CounterboreDiameter", "CounterboreDepth", "End", "PatternIdentity" },
+ FirmamentV2SemanticHoleVariant.Countersink => new[] { "On", "Center", "Diameter", "CountersinkDiameter", "CountersinkAngle", "End", "PatternIdentity" },
+ _ => new[] { "On", "Center", "Diameter", "End", "PatternIdentity" }
};
if (CanonicalBodyHasUnknownField(holeBody, knownFields))
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Polygon2RhombusAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Polygon2RhombusAuthoring.cs
new file mode 100644
index 00000000..e7714b21
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Polygon2RhombusAuthoring.cs
@@ -0,0 +1,84 @@
+using System.Globalization;
+using System.Text.RegularExpressions;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>
+/// Bounded source lowering for the built-in Polygon2&lt;Rhombus&gt; shape. The parameter is
+/// a closed shape variant, not a user-defined generic. Lowering reuses ordinary Point2,
+/// Line2, Profile pipeline, validation, and materialization paths.
+/// </summary>
+internal static class Polygon2RhombusAuthoring
+{
+ internal const string Prefix = "firmament-polygon2-";
+ internal sealed record Result(string Source, IReadOnlyList<FirmamentV2Polygon2Decl> Polygons);
+
+ public static Result? Expand(string source, List<string> diagnostics)
+ {
+ var changes = new List<(int Start, int Length, string Text)>();
+ var polygons = new List<FirmamentV2Polygon2Decl>();
+ var names = new HashSet<string>(StringComparer.Ordinal);
+ foreach (Match header in Regex.Matches(source,
+ @"\bPolygon2\s*<\s*(?<variant>[A-Za-z_]\w*)\s*>\s+(?<name>[A-Za-z_]\w*)\s*\{",
+ RegexOptions.CultureInvariant))
+ {
+ var open = source.IndexOf('{', header.Index); var close = Matching(source, open);
+ var name = header.Groups["name"].Value; var variant = header.Groups["variant"].Value;
+ if (close < 0) { diagnostics.Add(Prefix + "malformed:" + name); continue; }
+ if (!string.Equals(variant, "Rhombus", StringComparison.Ordinal)) { diagnostics.Add(Prefix + "variant-unsupported:" + name + ":" + variant); continue; }
+ if (!names.Add(name)) { diagnostics.Add(Prefix + "duplicate-name:" + name); continue; }
+ var body = source[(open + 1)..close];
+ var center = Regex.Match(body, @"\bCenter\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*(?:\]|\))", RegexOptions.CultureInvariant);
+ var diagonals = Regex.Match(body, @"\bDiagonals\s*:\s*\[\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*\]", RegexOptions.CultureInvariant);
+ if (!center.Success || !diagonals.Success
+ || !TryNumber(center, "x", out var centerX) || !TryNumber(center, "y", out var centerY)
+ || !TryNumber(diagonals, "x", out var diagonalX) || !TryNumber(diagonals, "y", out var diagonalY)
+ || diagonalX <= 0d || diagonalY <= 0d)
+ { diagnostics.Add(Prefix + "invalid-geometry:" + name); continue; }
+ var generatedPoints = new[] { name + "_South", name + "_East", name + "_North", name + "_West" };
+ var generatedEdges = new[] { name + "_SouthEast", name + "_EastNorth", name + "_NorthWest", name + "_WestSouth" };
+ changes.Add((header.Index, close - header.Index + 1, Lower(name, centerX, centerY, diagonalX, diagonalY)));
+ polygons.Add(new(name, "Rhombus", centerX, centerY, diagonalX, diagonalY, generatedPoints, generatedEdges,
+ new(header.Index, close - header.Index + 1)));
+ }
+ if (diagnostics.Any(item => item.StartsWith(Prefix, StringComparison.Ordinal))) return null;
+ foreach (var polygon in polygons)
+ {
+ var trace = $@"\b{Regex.Escape(polygon.Name)}\s*\|>\s*TraceLoop\b";
+ foreach (Match match in Regex.Matches(source, trace, RegexOptions.CultureInvariant))
+ changes.Add((match.Index, match.Length, string.Join(" |> ", polygon.GeneratedEdges) + " |> Close"));
+ }
+ var containers = changes.Where(change => change.Text.StartsWith("Point2 ", StringComparison.Ordinal)).ToArray();
+ foreach (var change in changes.Where(change => !containers.Any(container => container.Start < change.Start && change.Start < container.Start + container.Length)).OrderByDescending(change => change.Start))
+ source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
+ return new(source, polygons);
+ }
+
+ private static string Lower(string name, double x, double y, double dx, double dy)
+ {
+ static string N(double value) => value.ToString("R", CultureInfo.InvariantCulture) + "mm";
+ var south = (X: x, Y: y - dy / 2d); var east = (X: x + dx / 2d, Y: y);
+ var north = (X: x, Y: y + dy / 2d); var west = (X: x - dx / 2d, Y: y);
+ return $$"""
+ Point2 {{name}}_South { Position: [{{N(south.X)}}, {{N(south.Y)}}] }
+ Point2 {{name}}_East { Position: [{{N(east.X)}}, {{N(east.Y)}}] }
+ Point2 {{name}}_North { Position: [{{N(north.X)}}, {{N(north.Y)}}] }
+ Point2 {{name}}_West { Position: [{{N(west.X)}}, {{N(west.Y)}}] }
+ Line2 {{name}}_SouthEast { From: {{name}}_South; To: {{name}}_East }
+ Line2 {{name}}_EastNorth { From: {{name}}_East; To: {{name}}_North }
+ Line2 {{name}}_NorthWest { From: {{name}}_North; To: {{name}}_West }
+ Line2 {{name}}_WestSouth { From: {{name}}_West; To: {{name}}_South }
+ """;
+ }
+
+ private static bool TryNumber(Match match, string group, out double value) =>
+ double.TryParse(match.Groups[group].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);
+
+ private static int Matching(string source, int open)
+ {
+ var depth = 0;
+ for (var index = open; index < source.Length; index++)
+ { if (source[index] == '{') depth++; else if (source[index] == '}' && --depth == 0) return index; }
+ return -1;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
index fedf15c8..5c4eb30e 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
@@ -30,6 +30,7 @@ public static class ProfileAuthoringParser
{
ArgumentNullException.ThrowIfNull(source);
var diagnostics = new List<string>();
+ source = ExpandBuiltInPolygons(source, diagnostics);
var expansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics);
if (expansion is not null) source = expansion.Source;
var staticExpansion = CanonicalStaticAuthoring.Expand(source, diagnostics);
@@ -47,6 +48,7 @@ public static class ProfileAuthoringParser
ArgumentNullException.ThrowIfNull(source);
ArgumentException.ThrowIfNullOrWhiteSpace(profileName);
var diagnostics = new List<string>();
+ source = ExpandBuiltInPolygons(source, diagnostics);
var expansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics);
if (expansion is not null) source = expansion.Source;
var declaration = FindProfiles(source).FirstOrDefault(profile => profile.Name == profileName);
@@ -88,6 +90,7 @@ public static class ProfileAuthoringParser
ArgumentNullException.ThrowIfNull(source);
ArgumentException.ThrowIfNullOrWhiteSpace(pathName);
var diagnostics = new List<string>();
+ source = ExpandBuiltInPolygons(source, diagnostics);
var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
var guides = new Dictionary<string, LineArcProfileCurve2D>(StringComparer.Ordinal);
AddOrdinaryGuides(source, points, guides, diagnostics);
@@ -112,6 +115,7 @@ public static class ProfileAuthoringParser
public static IReadOnlyList<ConceptPathInspection> InspectConceptPaths(string source)
{
var diagnostics = new List<string>();
+ source = ExpandBuiltInPolygons(source, diagnostics);
var expansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics);
if (expansion is not null) source = expansion.Source;
var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
@@ -151,6 +155,7 @@ public static class ProfileAuthoringParser
public static (ResolvedProfile2D? Profile, double Height, IReadOnlyList<string> Diagnostics) Parse(string source)
{
var diagnostics = new List<string>();
+ source = ExpandBuiltInPolygons(source, diagnostics);
var profile = FindProfiles(source).FirstOrDefault();
if (profile is null)
return (null, 0, ["profile-source-missing-profile"]);
@@ -178,6 +183,7 @@ public static class ProfileAuthoringParser
{
// This is the canonical semantic-profile adapter used by Compose and SectionChain.
// Its historical name remains source-compatible; pipeline syntax is erased here too.
+ source = ExpandBuiltInPolygons(source, diagnostics);
var authoredProfiles = FindProfiles(source).Where(candidate => candidate.FromPath is not null || candidate.Body?.Contains("|>", StringComparison.Ordinal) == true).ToArray();
if (authoredProfiles.Length == 0) return new Dictionary<string, ResolvedProfile2D>();
var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
@@ -199,6 +205,9 @@ public static class ProfileAuthoringParser
return profiles;
}
+ private static string ExpandBuiltInPolygons(string source, List<string> diagnostics) =>
+ Polygon2RhombusAuthoring.Expand(source, diagnostics)?.Source ?? source;
+
internal static ConstructionPlane? ResolveNamedConstructionPlane(string source, string frame, List<string> diagnostics)
=> ResolveConstructionPlane(source, frame, diagnostics);
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
index 9b963331..29f9ced6 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
@@ -343,6 +343,8 @@ public static class PrismaticProfileCompositionParser
var name = header.Groups["n"].Value;
var body = Block(composeBody, header.Index + header.Length - 1);
if (body is null) { diagnostics.Add($"compose-hole-unclosed:{name}"); continue; }
+ var patternIdentityMatch = Regex.Match(body, @"\bPatternIdentity\s*:\s*(?<id>[A-Za-z_]\w*\.[A-Za-z_]\w*)", RegexOptions.CultureInvariant);
+ var diagnosticName = patternIdentityMatch.Success ? patternIdentityMatch.Groups["id"].Value : name;
var center = HoleCenter.Match(body); if (!center.Success) center = HolePoint2Center.Match(body);
var diameter = HoleDiameter.Match(body); var end = HoleEnd.Match(body); var role = HoleRole.Match(body);
var counterboreDiameter = HoleCounterboreDiameter.Match(body); var counterboreDepth = HoleCounterboreDepth.Match(body); var on = HoleOn.Match(body);
@@ -399,7 +401,7 @@ public static class PrismaticProfileCompositionParser
|| Math.Abs(supportSpan.ParentPlane.Origin.Z - materialTo) > 1e-7d)
{ diagnostics.Add($"firmament-feature-support-parent-mismatch:{name}:{supportSpan.SpanId}"); continue; }
if (!PlanarSpanContainment.ContainsCircle(supportSpan, counterboreX, counterboreY, boreDiameter / 2d, out var margin))
- { diagnostics.Add($"firmament-feature-footprint-outside-span:{name}:{supportSpan.SpanId}:center=[{counterboreX:R},{counterboreY:R}]:radius={boreDiameter / 2d:R}:margin={margin:R}"); continue; }
+ { diagnostics.Add($"firmament-feature-footprint-outside-span:{diagnosticName}:{supportSpan.SpanId}:center=[{counterboreX:R},{counterboreY:R}]:radius={boreDiameter / 2d:R}:margin={margin:R}"); continue; }
supportMargin = margin;
}
if (IntersectsExistingCircularCavity(shaftHoles, counterboreHoles, counterboreX, counterboreY, boreDiameter / 2d))
@@ -434,7 +436,7 @@ public static class PrismaticProfileCompositionParser
|| Math.Abs(shaftSupport.ParentPlane.Origin.Z - materialTo) > 1e-7d)
{ diagnostics.Add($"firmament-feature-support-parent-mismatch:{name}:{shaftSupport.SpanId}"); continue; }
if (!PlanarSpanContainment.ContainsCircle(shaftSupport, x, y, d / 2d, out var margin))
- { diagnostics.Add($"firmament-feature-footprint-outside-span:{name}:{shaftSupport.SpanId}:center=[{x:R},{y:R}]:radius={d / 2d:R}:margin={margin:R}"); continue; }
+ { diagnostics.Add($"firmament-feature-footprint-outside-span:{diagnosticName}:{shaftSupport.SpanId}:center=[{x:R},{y:R}]:radius={d / 2d:R}:margin={margin:R}"); continue; }
shaftSupportMargin = margin;
}
var holeProfile = CircleProfile(profileName, x, y, d / 2d, stableId, $"offset:{header.Index}");
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index 391a379f..ab545c11 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -76,6 +76,7 @@ Use each abstraction for its single role:
| `|>` | Finite semantic composition of compatible Profile/Path geometry. |
| `Concept` | Semantic contract or capability. |
| `Record` / `Struct` | Typed data and semantic structure. |
+| `Set<T>` | Finite immutable source-ordered data whose entries have stable names. |
Feature composes with an existing bounded Pattern without exposing its internals:
@@ -106,6 +107,50 @@ Pattern Mounts {
The two-column, two-row Grid is the explicit four-hole rectangular distribution. This semantic PointSet Pattern uses `Item`. The older `Pattern Name Over Records { Template<Current> }` form remains the record-array composition syntax for finite feature Templates; `Current` is the selected record. Feature functions do not replace that compatibility form.
+## Finite named sets and mapping
+
+`Set<T>` is a finite immutable collection of named typed values. Use it when entries have semantic identity and should be addressable by name; use `T[]` for an anonymous ordered sequence.
+
+```firmament
+Static MountPoints: Set<Point2> {
+ LowerLeft => Point2(-16mm, -9mm)
+ LowerRight => Point2(16mm, -9mm)
+ UpperLeft => Point2(-16mm, 9mm)
+ UpperRight => Point2(16mm, 9mm)
+}
+
+Pattern Mounts Over MountPoints {
+ point => M8Counterbore(Center: point)
+}
+```
+
+`MountPoints.LowerLeft` has type `Point2`; Record-valued entries compose naturally, for example `MountSpecs.Left.Center`. Set entry names are unique, values may be equal, and authored order is authoritative. An empty typed Set is valid and a Pattern over it produces zero instances. Inspection exposes the element type, cardinality, entries, source order, provenance, and generated associations.
+
+Inside a Set, `Name => Value` is a named association. Inside Pattern, `value => construction` maps every member of that finite Set to one semantic construction. Neither spelling is conditional control flow. Set has no mutation, indexing, filtering, sorting, `Map`, `Fold`, arbitrary keys, or runtime collection API, and Pattern retains the existing 1,024-instance safety bound.
+
+Choose among the closed data forms by meaning: a `Record` is one structured value; an `Enum` is one-of-N alternatives; `T[]` is anonymous ordered data; `Set<T>` is a dataset in which all N named entries exist simultaneously. Pattern performs finite construction mapping, Feature supplies a reusable semantic transformation, and `|>` composes finite compatible geometry. Match is unchanged.
+
+### Built-in closed polygons
+
+`Polygon2<Rhombus>` is the first bounded closed-polygon authoring form. A rhombus is specified by its center and full horizontal/vertical diagonal lengths:
+
+```firmament
+Concept Struct Layout On XY {
+ Polygon2<Rhombus> MountBoundaryShape {
+ Center: [0mm, 0mm]
+ Diagonals: [90mm, 64mm]
+ }
+}
+
+Profile MountBoundary Using Layout {
+ Loop Outer { MountBoundaryShape |> TraceLoop }
+}
+```
+
+This produces vertices at south, east, north, and west half-diagonal offsets and a counter-clockwise closed boundary. It lowers before pipeline validation to the ordinary typed `Point2`, `Line2`, and Profile path, so closure, orientation, Span containment, materialization, and STEP export keep their existing owners.
+
+The angle-bracket argument is a closed built-in shape variant, not a general generic or user-defined type. X1 admits only `Rhombus`; both diagonals must be finite positive lengths. It intentionally does not add arbitrary vertex arrays, `Connect`, a scene graph, or a second polygon materializer. Use `Rect2` when the four sides are axis-aligned; unequal horizontal and vertical rhombus diagonals do not describe that rectangle.
+
A Feature may return a call to another Feature with the same declared result type:
```firmament
diff --git a/docs/public/firmament/templates.md b/docs/public/firmament/templates.md
index cb6d683e..7690c264 100644
--- a/docs/public/firmament/templates.md
+++ b/docs/public/firmament/templates.md
@@ -77,7 +77,7 @@ This matrix describes the compiler today. It is not a roadmap.
## Records, `with`, Static, Tables, and Patterns
-`Record` defines grouped engineering-data shape. `Static` binds immutable compile-time data. `with` derives a new Record value by replacing checked fields; it is neither inheritance nor mutation. A keyed `Static Table` is finite engineering data, and a Table lookup produces a Record that can be passed to a Template. `Pattern ... Over` expands a finite static collection into admitted semantic features.
+`Record` defines grouped engineering-data shape. `Static` binds immutable compile-time data. `with` derives a new Record value by replacing checked fields; it is neither inheritance nor mutation. A keyed `Static Table` is finite engineering data, and a Table lookup produces a Record that can be passed to a Template. `Set<T>` is the source-ordered named form for finite immutable data; arrays remain the anonymous form. `Pattern ... Over` expands either compatible source through the existing finite semantic feature route.
```text
Record EnclosureSpec {
diff --git a/docs/public/getting-started.md b/docs/public/getting-started.md
index d1344df8..ed75eeef 100644
--- a/docs/public/getting-started.md
+++ b/docs/public/getting-started.md
@@ -37,6 +37,8 @@ aetheris view artifacts/mounting-block.step
[`record-array-hole-pattern.firmament`](../../fixtures/Canonical/Patterns/record-array-hole-pattern.firmament) demonstrates typed Records, a static array, a Template, and `Pattern ... Over`:
+When the elements need stable semantic names, use [`mounting-points.firmament`](../../fixtures/Canonical/Set/mounting-points.firmament): `Set<Point2>` preserves authored names and order, `MountPoints.UpperRight` addresses one value, and Pattern maps the complete finite set into construction.
+
```powershell
aetheris build fixtures/Canonical/Patterns/record-array-hole-pattern.firmament --output artifacts/pattern.step --json
```
diff --git a/docs/release/LANG-SET-X1.md b/docs/release/LANG-SET-X1.md
new file mode 100644
index 00000000..1ca8a25c
--- /dev/null
+++ b/docs/release/LANG-SET-X1.md
@@ -0,0 +1,85 @@
+# LANG-SET-X1 — finite named sets and Pattern mapping
+
+## Executive verdict
+
+Accepted. Firmament can express a finite named engineering dataset as `Set<T>`, refer to its entries by semantic name, and map every entry deterministically into existing semantic construction without Enum, Match, a general loop, or a second Pattern executor.
+
+## Before and after
+
+The mounting-point source previously needed an anonymous Record wrapper and numeric identity:
+
+```firmament
+Record MountSpec { Center: Point2 }
+Static Mounts: MountSpec[] = [
+ MountSpec { Center: Point2(-16mm, -9mm) }
+ MountSpec { Center: Point2(16mm, -9mm) }
+]
+Pattern MountPattern Over Mounts { M8Counterbore<Current> }
+```
+
+The named dataset now states its intent directly:
+
+```firmament
+Static MountPoints: Set<Point2> {
+ LowerLeft => Point2(-16mm, -9mm)
+ LowerRight => Point2(16mm, -9mm)
+ UpperLeft => Point2(-16mm, 9mm)
+ UpperRight => Point2(16mm, 9mm)
+}
+Pattern Mounts Over MountPoints {
+ point => M8Counterbore(Center: point)
+}
+```
+
+Likewise, four standalone `Point2 South/East/North/West` declarations can be one `Set<Point2>` when they are primarily one boundary dataset. `BoundaryPoints.South` and its peers bind as `Point2` values and can feed existing `Line2` definitions. Independently meaningful points should remain declarations; no mass migration is implied.
+
+The particular South/East/North/West coordinates form a rhombus with unequal 90 mm and 64 mm diagonals, not a `Rect2`; changing it to today's axis-aligned `Rect2 { Center; Size }` would change the support boundary. The point-plus-four-lines friction is now represented by the bounded `Polygon2<Rhombus> MountBoundaryShape { Center; Diagonals }` scaffold and consumed as `MountBoundaryShape |> TraceLoop`. It lowers to the existing Point2/Line2/Profile route. `Rhombus` is the only admitted closed variant; this is not general generics, an arbitrary polygon API, or a second geometry engine.
+
+## Audit and reused authority
+
+Before X1, `Static T[]` meant a finite immutable compile-time, source-ordered sequence of typed Record values. Canonical Pattern already enumerated those arrays, substituted `Current` through the existing finite Template expansion, and created numeric identities such as `MountPattern[0]`. Arrays preserved order and values but could not preserve author-facing element names. That forced Point2 values into one-field Records or repeated standalone point declarations.
+
+X1 reuses canonical static declaration erasure, Record field checking, Template instantiation, Feature expansion, concrete Feature AIR/material lowering, source-order handling, and the existing 1,024-instance Pattern bound. Set adds only named value evidence, named lookup, and association-aware Pattern expansion. No second executor or runtime collection exists.
+
+## Type and identity model
+
+| Construct | Meaning | Identity |
+| --- | --- | --- |
+| `T[]` | Anonymous homogeneous ordered values | Numeric position is compatibility bookkeeping. |
+| `Set<T>` | All named homogeneous values in one finite dataset | Entry name plus source order and provenance. |
+| `Record` | One structured value | Record type and named fields. |
+| `Enum` | One value selected from closed alternatives | Selected variant. |
+
+Every Set entry retains `Name`, typed `Value`, zero-based `SourceOrder`, and source-span `Provenance`. Pattern results use dotted semantic identities such as `Mounts.UpperRight`; material-safe declarations use the corresponding `Mounts_UpperRight` spelling. Pattern inspection retains source Set, source entry, source value, Pattern, and expansion ordinal.
+
+Names must be unique within a Set. Equal values under different names are legal. Empty `Set<T>` is valid and maps to zero instances. X1 admits file-level Static sets of `Point2`, `Point3`, `Vector2`, scalar built-ins, and declared Records in the Mechanical schema. Nested Sets, executable feature values, arbitrary collection algebra, and feature-local Sets are deferred/rejected.
+
+## Control-flow boundary
+
+Set plus Pattern does not add arbitrary iteration. Expansion cardinality is fully known from the authored Set and every entry is mapped in source order. There is no filter, conditional member enablement, mutation, indexing API, sorting, `Map`, `Reduce`, `Fold`, `for`, or `foreach`. Authors who need fewer constructed members author the intended Set.
+
+Inside Set, `Name => Value` means named association. Inside Pattern, `value => construction` means bounded mapping. Neither is Match or branch syntax. Existing arrays, Template, Enum, Match, Feature, Span, and `|>` semantics are unchanged.
+
+## Flagship evidence
+
+The canonical [`mounting-points.firmament`](../../fixtures/Canonical/Set/mounting-points.firmament) builds four counterbores through the ordinary Feature and profile-composition route. Each is checked independently against `Span<Plane> MountingArea`. Moving `UpperRight` outside produces `firmament-feature-footprint-outside-span:Mounts.UpperRight:MountingArea...`, retaining the Set entry identity rather than only an index.
+
+The Set and prior Record-array mounting sources export byte-identical STEP for equivalent geometry, even though the Set flagship now authors its support boundary as `Polygon2<Rhombus>` and the comparison fixture retains the explicit four-point/four-line boundary. Repeated Set export is deterministic. Structured CLI inspection reports Set element type, count, ordered entries/provenance, Pattern associations, and the typed Polygon variant with generated guide identities.
+
+## Compatibility and later burn-in
+
+The legacy `Static T[] = [...]` and `Pattern ... { Template<Current> }` forms remain valid. Later LANG-BURN replay should consider the `finish-pattern`, `pattern-finish`, `hexbolt`, and profile-compose mounting-plate cases: they contain anonymous Record arrays whose entries may benefit from names. They were not migrated in X1 because identity intent must be assessed case by case.
+
+## Validation
+
+The implementation is covered by focused parser/binder/lowering tests, typed invalid fixtures, named access, empty cardinality, source-order determinism, Record payload and Template coexistence, Feature mapping, Span containment identity, array/Enum/Match compatibility, and byte-identical STEP parity.
+
+The completed release gates are:
+
+- Release solution build: succeeded with zero warnings and zero errors.
+- Full Firmament suite: 1,378 passed.
+- Full CLI suite: 418 passed.
+- Canonical qualification: 160 fixtures passed, including all four Set fixtures and the `Polygon2<Rhombus>` flagship.
+- Packaged CLI: locally packed, installed as a .NET tool, and used to inspect the flagship successfully.
+- Public documentation links and repository layout guard: passed.
+- `git diff --check`: passed; Git reported only the repository's normal LF-to-CRLF working-copy notices.
diff --git a/fixtures/Canonical/Set/mounting-points.firmament b/fixtures/Canonical/Set/mounting-points.firmament
new file mode 100644
index 00000000..29c19860
--- /dev/null
+++ b/fixtures/Canonical/Set/mounting-points.firmament
@@ -0,0 +1,49 @@
+Model NamedMountingPoints {
+ Units: mm
+
+ Feature M8Counterbore(Center: Point2) -> Hole<Counterbore> {
+ return Hole<Counterbore> {
+ On: MountingArea
+ Center: Center
+ Diameter: 8mm
+ CounterboreDiameter: 16mm
+ CounterboreDepth: 3mm
+ End: ThroughAll
+ }
+ }
+
+ Static MountPoints: Set<Point2> {
+ LowerLeft => Point2(-16mm, -9mm)
+ LowerRight => Point2(16mm, -9mm)
+ UpperLeft => Point2(-16mm, 9mm)
+ UpperRight => Point2(16mm, 9mm)
+ }
+
+ Concept Struct Supports {
+ Top: Plane { Origin: [0mm,0mm,8mm]; Normal: [0,0,1]; Up: [0,1,0] }
+ }
+ Construction Plane TopSupport { Trace: Supports.Top }
+ Concept Struct Layout On XY {
+ Rect2 Stock { Center: [0mm,0mm]; Size: [100mm,80mm] }
+ Polygon2<Rhombus> MountBoundaryShape {
+ Center: [0mm,0mm]
+ Diagonals: [90mm,64mm]
+ }
+ }
+ Profile StockProfile Using Layout {
+ Loop Outer { Stock.Bottom |> Stock.Right |> Stock.Top |> Stock.Left |> Close }
+ }
+ Profile MountBoundary Using Layout {
+ Loop Outer { MountBoundaryShape |> TraceLoop }
+ }
+ Span<Plane> MountingArea { On: TopSupport; Boundary: MountBoundary }
+
+ Struct Part {
+ Compose Plate {
+ Base StockBody { Profile: StockProfile; From: 0mm; To: 8mm; Role: Stock }
+ Pattern Mounts Over MountPoints {
+ point => M8Counterbore(Center: point)
+ }
+ }
+ }
+}
diff --git a/fixtures/Canonical/Set/named-point-access.firmament b/fixtures/Canonical/Set/named-point-access.firmament
new file mode 100644
index 00000000..436817b4
--- /dev/null
+++ b/fixtures/Canonical/Set/named-point-access.firmament
@@ -0,0 +1,19 @@
+Model NamedPointAccess {
+ Units: mm
+ Static BoundaryPoints: Set<Point2> {
+ South => Point2(0mm, -32mm)
+ East => Point2(45mm, 0mm)
+ North => Point2(0mm, 32mm)
+ West => Point2(-45mm, 0mm)
+ }
+ Concept Struct Layout On XY {
+ Line2 SE { From: BoundaryPoints.South; To: BoundaryPoints.East }
+ Line2 EN { From: BoundaryPoints.East; To: BoundaryPoints.North }
+ Line2 NW { From: BoundaryPoints.North; To: BoundaryPoints.West }
+ Line2 WS { From: BoundaryPoints.West; To: BoundaryPoints.South }
+ }
+ Profile Boundary Using Layout {
+ Loop Outer { SE |> EN |> NW |> WS |> Close }
+ }
+ Struct PlateBody { Extrude Body { Profile: Boundary; From: 0mm; To: 4mm } }
+}
diff --git a/fixtures/Canonical/Set/pattern-feature-map.firmament b/fixtures/Canonical/Set/pattern-feature-map.firmament
new file mode 100644
index 00000000..c14d61ea
--- /dev/null
+++ b/fixtures/Canonical/Set/pattern-feature-map.firmament
@@ -0,0 +1,14 @@
+Model SetFeaturePattern {
+ Units: mm
+ Feature Drill(Center: Point2) -> Hole<Shaft> {
+ return Hole<Shaft> { On: +Z Center: Center Diameter: 6mm End: ThroughAll }
+ }
+ Static Points: Set<Point2> {
+ First => Point2(-12mm, 0mm)
+ Second => Point2(12mm, 0mm)
+ }
+ Box Base { Size: [50mm, 30mm, 8mm] }
+ Modify Base {
+ Pattern Drills Over Points { point => Drill(point) }
+ }
+}
diff --git a/fixtures/Canonical/Set/record-payloads.firmament b/fixtures/Canonical/Set/record-payloads.firmament
new file mode 100644
index 00000000..c57c0a46
--- /dev/null
+++ b/fixtures/Canonical/Set/record-payloads.firmament
@@ -0,0 +1,15 @@
+Model NamedRecordPayloads {
+ Units: mm
+ Record MountSpec { Center: Point2 Diameter: Length }
+ Static Mounts: Set<MountSpec> {
+ Left => MountSpec { Center: Point2(-20mm, 0mm) Diameter: 8mm }
+ Right => MountSpec { Center: Point2(20mm, 0mm) Diameter: 8mm }
+ }
+ Template<spec: MountSpec> MountHole {
+ Hole<Shaft> Mount { On: +Z Center: spec.Center Diameter: spec.Diameter End: ThroughAll }
+ }
+ Box Base { Size: [80mm, 40mm, 10mm] }
+ Modify Base {
+ Pattern MountPattern Over Mounts { spec => MountHole<Current> }
+ }
+}
diff --git a/fixtures/Canonical/coverage.json b/fixtures/Canonical/coverage.json
index fc5c26f1..3a20ec87 100644
--- a/fixtures/Canonical/coverage.json
+++ b/fixtures/Canonical/coverage.json
@@ -22,6 +22,7 @@
"Countersink": "Features/Holes/countersink.firmament",
"Slot": "Features/Slots/straight-slot.firmament",
"Pattern": "Patterns/record-array-hole-pattern.firmament",
+ "NamedSet": "Set/mounting-points.firmament",
"Chamfer": "Features/EdgeFinish/boundary-chamfer.firmament",
"Fillet": "Features/EdgeFinish/single-edge-fillet.firmament",
"RecordStaticTableWith": "Profiles/profile-delta-recess-extrusion.firmament",
@@ -55,6 +56,7 @@
"AutoRib": "PlasticShell/plastic-shell-enclosure.firmament",
"MaterializedStandoff": "PlasticShell/plastic-shell-materialized-standoff.firmament",
"MaterializedRib": "PlasticShell/plastic-shell-materialized-rib.firmament",
- "MoldedRibStandoffJunction": "PlasticShell/plastic-shell-rib-standoff-junction.firmament"
+ "MoldedRibStandoffJunction": "PlasticShell/plastic-shell-rib-standoff-junction.firmament",
+ "Polygon2Rhombus": "Set/mounting-points.firmament"
}
}
diff --git a/fixtures/Canonical/qualification.json b/fixtures/Canonical/qualification.json
index c1315a0c..365fb39b 100644
--- a/fixtures/Canonical/qualification.json
+++ b/fixtures/Canonical/qualification.json
@@ -28,6 +28,8 @@
{ "path": "Feature", "operation": "build-step" },
{ "path": "Schema", "operation": "build-step" },
{ "path": "Patterns", "operation": "build-step" },
+ { "path": "Set", "operation": "build-step" },
+ { "path": "Span", "operation": "build-step" },
{ "path": "PMI", "operation": "build-step" },
{ "path": "Templates", "operation": "build-step" },
{ "path": "Integration", "operation": "build-step" }
diff --git a/fixtures/Invalid/Set/duplicate-entry-name.firmament b/fixtures/Invalid/Set/duplicate-entry-name.firmament
new file mode 100644
index 00000000..646a1050
--- /dev/null
+++ b/fixtures/Invalid/Set/duplicate-entry-name.firmament
@@ -0,0 +1,8 @@
+Model DuplicateSetEntry {
+ Units: mm
+ Static Points: Set<Point2> {
+ A => Point2(0mm, 0mm)
+ A => Point2(10mm, 0mm)
+ }
+ Box Base { Size: [20mm, 20mm, 2mm] }
+}
diff --git a/fixtures/Invalid/Set/invalid-pattern-target.firmament b/fixtures/Invalid/Set/invalid-pattern-target.firmament
new file mode 100644
index 00000000..78d0cc8c
--- /dev/null
+++ b/fixtures/Invalid/Set/invalid-pattern-target.firmament
@@ -0,0 +1,6 @@
+Model InvalidSetPatternTarget {
+ Units: mm
+ Static Points: Set<Point2> { A => Point2(0mm, 0mm) }
+ Box Base { Size: [20mm, 20mm, 2mm] }
+ Modify Base { Pattern Bad Over Missing { point => Hole<Shaft> H { On: +Z Center: point Diameter: 2mm End: ThroughAll } } }
+}
diff --git a/fixtures/Invalid/Set/pattern-span-containment.firmament b/fixtures/Invalid/Set/pattern-span-containment.firmament
new file mode 100644
index 00000000..dfe6993a
--- /dev/null
+++ b/fixtures/Invalid/Set/pattern-span-containment.firmament
@@ -0,0 +1,25 @@
+Model SetPatternOutsideSpan {
+ Units: mm
+ Feature M8Counterbore(Center: Point2) -> Hole<Counterbore> {
+ return Hole<Counterbore> { On: MountingArea Center: Center Diameter: 8mm CounterboreDiameter: 16mm CounterboreDepth: 3mm End: ThroughAll }
+ }
+ Static MountPoints: Set<Point2> {
+ LowerLeft => Point2(-16mm, -9mm)
+ LowerRight => Point2(16mm, -9mm)
+ UpperLeft => Point2(-16mm, 9mm)
+ UpperRight => Point2(28mm, 9mm)
+ }
+ Concept Struct Supports { Top: Plane { Origin: [0mm,0mm,8mm]; Normal: [0,0,1]; Up: [0,1,0] } }
+ Construction Plane TopSupport { Trace: Supports.Top }
+ Concept Struct Layout On XY {
+ Rect2 Stock { Center: [0mm,0mm]; Size: [100mm,80mm] }
+ Polygon2<Rhombus> MountBoundaryShape { Center: [0mm,0mm]; Diagonals: [90mm,64mm] }
+ }
+ Profile StockProfile Using Layout { Loop Outer { Stock.Bottom |> Stock.Right |> Stock.Top |> Stock.Left |> Close } }
+ Profile MountBoundary Using Layout { Loop Outer { MountBoundaryShape |> TraceLoop } }
+ Span<Plane> MountingArea { On: TopSupport; Boundary: MountBoundary }
+ Struct Part { Compose Plate {
+ Base StockBody { Profile: StockProfile; From: 0mm; To: 8mm; Role: Stock }
+ Pattern Mounts Over MountPoints { point => M8Counterbore(Center: point) }
+ } }
+}
diff --git a/fixtures/Invalid/Set/wrong-element-type.firmament b/fixtures/Invalid/Set/wrong-element-type.firmament
new file mode 100644
index 00000000..171f5948
--- /dev/null
+++ b/fixtures/Invalid/Set/wrong-element-type.firmament
@@ -0,0 +1,7 @@
+Model WrongSetElementType {
+ Units: mm
+ Static Points: Set<Point2> {
+ A => 10mm
+ }
+ Box Base { Size: [20mm, 20mm, 2mm] }
+}