Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add Concept matching and bounded pattern expansion

Yuechen Lie3115a2e5490
diff --git a/Aetheris.CLI.Tests/ConceptStepMatchTests.cs b/Aetheris.CLI.Tests/ConceptStepMatchTests.cs
new file mode 100644
index 00000000..487f84e1
--- /dev/null
+++ b/Aetheris.CLI.Tests/ConceptStepMatchTests.cs
@@ -0,0 +1,52 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class ConceptStepMatchTests
+{
+ [Fact]
+ public void Match_StandardBracket_ReportsTypedAnalyticEvidence()
+ {
+ var root = RepositoryRoot();
+ var step = BuildStandardStep(root);
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+ var exit = CliRunner.Run(["match", step, Path.Combine(root, "demos", "concept-step-match-standard.firmament"), "--json"], stdout, stderr);
+ Assert.Equal(0, exit);
+ using var json = JsonDocument.Parse(stdout.ToString());
+ var report = json.RootElement.GetProperty("conceptStepMatch");
+ Assert.Equal("Matched", report.GetProperty("status").GetString());
+ Assert.Equal(3, report.GetProperty("summary").GetProperty("matched").GetInt32());
+ Assert.Equal("DerivedAnalytic", report.GetProperty("members")[1].GetProperty("evidenceQuality").GetString());
+ }
+
+ [Fact]
+ public void Match_WrongBounds_IsConflicted_And_PartialConcept_RemainsUseful()
+ {
+ var root = RepositoryRoot(); var source = File.ReadAllText(Path.Combine(root, "demos", "concept-step-match-standard.firmament"));
+ var dir = Path.Combine(Path.GetTempPath(), "aetheris-match", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(dir);
+ var wrong = Path.Combine(dir, "wrong.firmament"); File.WriteAllText(wrong, source.Replace("Width: 80mm", "Width: 81mm", StringComparison.Ordinal));
+ var step = BuildStandardStep(root);
+ Assert.Equal(1, CliRunner.Run(["match", step, wrong, "--json"], new StringWriter(), new StringWriter()));
+ var partial = Path.Combine(dir, "partial.firmament");
+ // The full point-set declaration is retained for parser validity; omitting its role produces nonfatal evidence.
+ File.WriteAllText(partial, source.Replace("Match {\n MountPoints As HoleCenters {\n Diameter: 8.5mm\n Axis: +Z\n Kind: Through\n }\n}\n", string.Empty, StringComparison.Ordinal));
+ Assert.Equal(0, CliRunner.Run(["match", step, partial, "--json"], new StringWriter(), new StringWriter()));
+ }
+
+ private static string RepositoryRoot()
+ {
+ var directory = new DirectoryInfo(AppContext.BaseDirectory);
+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;
+ return Assert.IsType<DirectoryInfo>(directory).FullName;
+ }
+
+ private static string BuildStandardStep(string root)
+ {
+ var directory = Path.Combine(Path.GetTempPath(), "aetheris-match-step", Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(directory);
+ var step = Path.Combine(directory, "standard.step");
+ var output = new StringWriter(); var errors = new StringWriter();
+ Assert.Equal(0, CliRunner.Run(["build", Path.Combine(root, "demos", "concept-step-match-standard.firmament"), "--out", step, "--json"], output, errors));
+ return step;
+ }
+}
diff --git a/Aetheris.CLI.Tests/FirmamentV2TemplatePatternStepPipelineTests.cs b/Aetheris.CLI.Tests/FirmamentV2TemplatePatternStepPipelineTests.cs
new file mode 100644
index 00000000..dfe8259e
--- /dev/null
+++ b/Aetheris.CLI.Tests/FirmamentV2TemplatePatternStepPipelineTests.cs
@@ -0,0 +1,39 @@
+using System.Text.RegularExpressions;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class FirmamentV2TemplatePatternStepPipelineTests
+{
+ [Theory]
+ [InlineData("template-m4b-compact.firmament", 60d, 40d, 20d, 22d)]
+ [InlineData("template-m4b-standard.firmament", 80d, 50d, 25d, 30d)]
+ public void TemplatePattern_BuildsReimportsAndProducesExactTwoHoleGeometry(string fixtureName, double width, double depth, double height, double centerX)
+ {
+ var fixture = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../demos", fixtureName));
+ var stepPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".step");
+ var stdout = new StringWriter();
+ var stderr = new StringWriter();
+
+ var exit = CliRunner.Run(["build", fixture, "--out", stepPath, "--json"], stdout, stderr);
+
+ Assert.True(exit == 0, stderr.ToString());
+ var step = File.ReadAllText(stepPath);
+ var imported = Step242Importer.ImportBody(step);
+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(d => d.Message)));
+ var body = imported.Value;
+ Assert.Equal(2, body.Topology.Faces.Count(face => body.TryGetFaceSurface(face.Id, out var surface) && surface?.Kind == SurfaceGeometryKind.Cylinder));
+
+ var volume = StepAnalyzer.AnalyzeVolume(stepPath);
+ Assert.True(volume.Success);
+ Assert.True(volume.Exact);
+ Assert.Equal("analytic-box-minus-z-hole", volume.Method);
+ Assert.InRange(Math.Abs(volume.Volume - (width * depth * height - 2d * Math.PI * 4.25d * 4.25d * height)), 0d, 1e-8);
+ Assert.Contains("\"patternExpansions\"", stdout.ToString(), StringComparison.Ordinal);
+ Assert.Contains("\"resolvedPoint3\": [", stdout.ToString(), StringComparison.Ordinal);
+ Assert.Contains(centerX.ToString("0", System.Globalization.CultureInfo.InvariantCulture), stdout.ToString(), StringComparison.Ordinal);
+ Assert.Equal(2, Regex.Matches(step, "=\\s*CYLINDRICAL_SURFACE\\s*\\(", RegexOptions.CultureInvariant).Count);
+ }
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 7ec92c14..e647d495 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -108,7 +108,7 @@ public static class CliRunner
string? Error,
string? Classification = null,
int? RigidRootCount = null);
- private const string TopLevelUsage = "Usage: aetheris <build|validate|analyze|trace|canon|asm|experimental> <path> [options]";
+ private const string TopLevelUsage = "Usage: aetheris <build|validate|analyze|match|trace|canon|asm|experimental> <path> [options]";
private const string BuildUsage = "Usage: aetheris build <file.firmament> [--out <path>] [--json]";
private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--forge-pack <path>] [--json]";
private const string AnalyzeUsage = "Usage: aetheris analyze <file.step> [--face <id>] [--edge <id>] [--vertex <id>] [--json]";
@@ -116,6 +116,7 @@ public static class CliRunner
private const string AnalyzeSectionUsage = "Usage: aetheris analyze section <file.step> (--xy|--xz|--yz) --offset <value> --json";
private const string AnalyzeVolumeUsage = "Usage: aetheris analyze volume <file.step> [--approximate --resolution <N>] [--json]";
private const string AnalyzeCompareUsage = "Usage: aetheris analyze compare <reference.step> <candidate.step> [--approximate-volume --resolution <N>] [--json]";
+ private const string MatchUsage = "Usage: aetheris match <file.step> <concept.firmament> [--linear-tolerance <mm>] [--angular-tolerance <deg>] [--json]";
private const string TraceUsage = "Usage: aetheris trace (--case <name>|--fixture <path>) [--out-dir <dir>] [--json]";
private const string CanonUsage = "Usage: aetheris canon <file.step> --out <canonical.step> [--mode deterministic|production] [--json]";
private const string AsmExecUsage = "Usage: aetheris asm exec <file.firmasm> [--json]";
@@ -166,6 +167,7 @@ public static class CliRunner
"build" => RunBuild(args.Skip(1).ToArray(), stdout, stderr),
"validate" => RunValidate(args.Skip(1).ToArray(), stdout, stderr),
"analyze" => RunAnalyze(args.Skip(1).ToArray(), stdout, stderr),
+ "match" => RunMatch(args.Skip(1).ToArray(), stdout, stderr),
"trace" => RunTrace(args.Skip(1).ToArray(), stdout, stderr),
"canon" => RunCanon(args.Skip(1).ToArray(), stdout, stderr),
"asm" => RunAsm(args.Skip(1).ToArray(), stdout, stderr),
@@ -180,6 +182,28 @@ public static class CliRunner
}
}
+ private static int RunMatch(string[] args, TextWriter stdout, TextWriter stderr)
+ {
+ if (args.Length == 0 || IsHelpFlag(args[0]))
+ {
+ WriteMatchHelp(stdout);
+ return args.Length == 0 ? 1 : 0;
+ }
+ if (args.Length < 2 || args[0].StartsWith("-", StringComparison.Ordinal) || args[1].StartsWith("-", StringComparison.Ordinal)) { stderr.WriteLine(MatchUsage); return 1; }
+ var step = args[0]; var concept = args[1]; var json = false; var linear = 0.01d; var angular = 0.1d;
+ for (var i = 2; i < args.Length; i++)
+ {
+ if (args[i] == "--json") { json = true; continue; }
+ if (args[i] == "--linear-tolerance" && i + 1 < args.Length && double.TryParse(args[++i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out linear) && linear >= 0) continue;
+ if (args[i] == "--angular-tolerance" && i + 1 < args.Length && double.TryParse(args[++i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out angular) && angular >= 0) continue;
+ stderr.WriteLine($"Unknown or invalid match option '{args[i]}'."); stderr.WriteLine(MatchUsage); return 1;
+ }
+ var report = ConceptStepMatcher.Match(step, concept, new(linear, angular, linear));
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { conceptStepMatch = report }, JsonOptions));
+ else stdout.WriteLine($"{report.Status}: {report.ConceptStruct} against {step} ({report.Members.Count} members)");
+ return report.Status is ConceptStepOverallStatus.Conflicted or ConceptStepOverallStatus.InvalidConcept or ConceptStepOverallStatus.InvalidStep ? 1 : 0;
+ }
+
private static int RunBuild(string[] args, TextWriter stdout, TextWriter stderr)
{
if (args.Length == 0)
@@ -2284,6 +2308,7 @@ public static class CliRunner
stdout.WriteLine(" build Build a .firmament source file into STEP.");
stdout.WriteLine(" validate Validate Firmament V2 manufacturing intent and emit report JSON.");
stdout.WriteLine(" analyze Analyze STEP topology, geometry, map, and sections.");
+ stdout.WriteLine(" match Match a compile-time Concept Struct against observed STEP geometry.");
stdout.WriteLine(" trace Trace built-in AIR lowering cases through route, BRepPlan, STEP smoke, and CIR mirror.");
stdout.WriteLine(" canon Import and re-export STEP/AP242 as canonical STEP.");
stdout.WriteLine(" asm Execute/export .firmasm assembly IR using rigid world-space composition.");
@@ -2298,6 +2323,7 @@ public static class CliRunner
stdout.WriteLine(" aetheris validate fixtures/FirmamentV2/Language/valid/v2-phase1-validation-report.valid.firmfixture --json");
stdout.WriteLine(" aetheris analyze model.step");
stdout.WriteLine(" aetheris analyze model.step --json");
+ stdout.WriteLine(" aetheris match model.step concept.firmament --json");
stdout.WriteLine(" aetheris trace --case top-face-loop-chamfer");
stdout.WriteLine(" aetheris trace --fixture fixtures/Firmament/Chamfer/valid/top-face-loop-chamfer.valid.firmfixture");
stdout.WriteLine(" aetheris trace --case prismatic-section-transition --json");
@@ -2328,6 +2354,18 @@ public static class CliRunner
stdout.WriteLine(" aetheris build part.firmament --out part.step --json");
}
+ private static void WriteMatchHelp(TextWriter stdout)
+ {
+ stdout.WriteLine("Match a compile-time Concept Struct against observed STEP geometry.");
+ stdout.WriteLine("This does not reconstruct the original feature history.");
+ stdout.WriteLine();
+ stdout.WriteLine(MatchUsage);
+ stdout.WriteLine();
+ stdout.WriteLine("Supported M5 evidence: body bounds, analytic planar faces, cylindrical axes, and declared hole-center point sets.");
+ stdout.WriteLine("Use `Match { MountPoints As HoleCenters { Diameter: 8.5mm Axis: +Z Kind: Through } }` in the source for point-set hole matching.");
+ stdout.WriteLine("Matched and Partial exit 0; Conflicted or invalid input exits 1.");
+ }
+
private static void WriteValidateHelp(TextWriter stdout)
{
stdout.WriteLine(ValidateUsage);
diff --git a/Aetheris.CLI/ConceptStepMatcher.cs b/Aetheris.CLI/ConceptStepMatcher.cs
new file mode 100644
index 00000000..0c6e223d
--- /dev/null
+++ b/Aetheris.CLI/ConceptStepMatcher.cs
@@ -0,0 +1,162 @@
+using System.Globalization;
+using System.Text.RegularExpressions;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.CLI;
+
+/// <summary>Read-only, bounded comparison of resolved Concept IR against analytic STEP evidence.</summary>
+public enum ConceptStepMatchStatus { Matched, WithinTolerance, Candidate, Ambiguous, Conflicted, Missing, Unverifiable, Unsupported }
+public enum ConceptStepOverallStatus { Matched, Partial, Conflicted, InvalidConcept, InvalidStep, Unsupported }
+public enum ConceptStepEvidenceQuality { ExactAnalytic, DerivedAnalytic, TopologySupported, TessellatedApproximation, HeuristicCandidate, Unavailable }
+
+public sealed record ConceptStepTolerance(double LinearMm = 0.01, double AngularDegrees = 0.1, double DimensionMm = 0.01);
+public sealed record ConceptStepHoleRole(double? DiameterMm, ConceptIrVector3? Axis, string? Kind);
+public sealed record ConceptStepMatchRole(string Member, string Kind, ConceptStepHoleRole? Hole = null);
+public sealed record ConceptStepPlaneEvidence(int FaceId, Point3D Origin, Vector3D Normal);
+public sealed record ConceptStepHoleEvidence(int FaceId, Point3D Center, Vector3D Axis, double Radius, double MinExtent, double MaxExtent, bool Through);
+public sealed record ConceptStepEvidenceIndex(BoundingBox3D Bounds, IReadOnlyList<ConceptStepPlaneEvidence> Planes, IReadOnlyList<ConceptStepHoleEvidence> Cylinders);
+public sealed record ConceptStepMemberResult(string Name, string Kind, ConceptStepMatchStatus Status, object Expected, object? Observed, double? Deviation, double? AllowedTolerance, int CandidateCount, ConceptStepEvidenceQuality EvidenceQuality, string Provenance, string? Note = null);
+public sealed record ConceptStepMatchReport(ConceptStepOverallStatus Status, string ConceptStruct, string StepBody, ConceptStepTolerance Tolerances, object Summary, IReadOnlyList<ConceptStepMemberResult> Members, IReadOnlyList<string> Diagnostics);
+
+public static class ConceptStepMatcher
+{
+ private static readonly Regex HoleRole = new(@"(?<member>[A-Za-z_][A-Za-z0-9_]*)\s+As\s+HoleCenters\s*\{(?<body>.*?)\}", RegexOptions.Singleline | RegexOptions.CultureInvariant);
+ private static readonly Regex LengthField = new(@"\b(?<name>Diameter)\s*:\s*(?<value>[-+0-9.]+)mm", RegexOptions.CultureInvariant);
+ private static readonly Regex AxisField = new(@"\bAxis\s*:\s*(?<value>[+-][XYZ])", RegexOptions.CultureInvariant);
+ private static readonly Regex KindField = new(@"\bKind\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);
+
+ public static ConceptStepMatchReport Match(string stepPath, string conceptPath, ConceptStepTolerance? tolerances = null)
+ {
+ tolerances ??= new ConceptStepTolerance();
+ var source = File.ReadAllText(conceptPath);
+ var roles = ParseRoles(source);
+ var parse = FirmamentV2Parser.Parse(StripMatchBlocks(source));
+ if (!parse.IsSuccess || parse.Document?.ConceptIr is null)
+ return new(ConceptStepOverallStatus.InvalidConcept, "<unresolved>", "body-0", tolerances, new { }, [], parse.Diagnostics);
+
+ BrepBody body;
+ try
+ {
+ var imported = Step242Importer.ImportBody(File.ReadAllText(stepPath));
+ if (!imported.IsSuccess) return new(ConceptStepOverallStatus.InvalidStep, "<unresolved>", "body-0", tolerances, new { }, [], imported.Diagnostics.Select(d => d.Message).ToArray());
+ body = imported.Value;
+ }
+ catch (Exception ex) { return new(ConceptStepOverallStatus.InvalidStep, "<unresolved>", "body-0", tolerances, new { }, [], [ex.Message]); }
+
+ var evidence = BuildEvidence(body);
+ var instance = parse.Document.ConceptIr.Structs.SingleOrDefault();
+ if (instance is null) return new(ConceptStepOverallStatus.InvalidConcept, "<unresolved>", "body-0", tolerances, new { }, [], ["No Concept Struct was resolved."]);
+ var members = new List<ConceptStepMemberResult>();
+ foreach (var pair in instance.Members.OrderBy(p => p.Key, StringComparer.Ordinal))
+ {
+ var name = $"{instance.Name}.{pair.Key}";
+ roles.TryGetValue(pair.Key, out var role);
+ members.Add(MatchMember(name, pair.Value, role, evidence, tolerances));
+ }
+ var conflicted = members.Any(m => m.Status is ConceptStepMatchStatus.Conflicted or ConceptStepMatchStatus.Missing);
+ var full = members.All(m => m.Status is ConceptStepMatchStatus.Matched or ConceptStepMatchStatus.WithinTolerance);
+ var overall = conflicted ? ConceptStepOverallStatus.Conflicted : full ? ConceptStepOverallStatus.Matched : ConceptStepOverallStatus.Partial;
+ var summary = new { matched = members.Count(m => m.Status == ConceptStepMatchStatus.Matched), withinTolerance = members.Count(m => m.Status == ConceptStepMatchStatus.WithinTolerance), candidate = members.Count(m => m.Status == ConceptStepMatchStatus.Candidate), ambiguous = members.Count(m => m.Status == ConceptStepMatchStatus.Ambiguous), conflicted = members.Count(m => m.Status == ConceptStepMatchStatus.Conflicted), missing = members.Count(m => m.Status == ConceptStepMatchStatus.Missing), unverifiable = members.Count(m => m.Status == ConceptStepMatchStatus.Unverifiable), unsupported = members.Count(m => m.Status == ConceptStepMatchStatus.Unsupported) };
+ return new(overall, instance.Name, "body-0", tolerances, summary, members, ["STEP identifiers are diagnostic evidence only; they are not Firmament source contracts."]);
+ }
+
+ private static ConceptStepMemberResult MatchMember(string name, ConceptIrValue value, ConceptStepMatchRole? role, ConceptStepEvidenceIndex evidence, ConceptStepTolerance tol) => value switch
+ {
+ ConceptIrBox3Value box => MatchBox(name, box, evidence.Bounds, tol),
+ ConceptIrPlaneValue plane => MatchPlane(name, plane, evidence.Planes, tol),
+ ConceptIrAxisValue axis => MatchAxis(name, axis, evidence.Cylinders, tol),
+ ConceptIrPointSetValue points when role?.Kind == "HoleCenters" => MatchHolePoints(name, points, role.Hole!, evidence.Cylinders, tol),
+ ConceptIrPoint3Value => new(name, "Point3", ConceptStepMatchStatus.Unverifiable, value, null, null, null, 0, ConceptStepEvidenceQuality.Unavailable, value.Provenance, "Point3 requires an explicit semantic match role."),
+ ConceptIrPointSetValue => new(name, "Point3[]", ConceptStepMatchStatus.Unverifiable, value, null, null, null, 0, ConceptStepEvidenceQuality.Unavailable, value.Provenance, "Point3[] requires `Match { Member As HoleCenters { ... } }`."),
+ _ => new(name, value.Kind.ToString(), ConceptStepMatchStatus.Unsupported, value, null, null, null, 0, ConceptStepEvidenceQuality.Unavailable, value.Provenance, "This Concept value kind has no M5 STEP matcher.")
+ };
+
+ private static ConceptStepMemberResult MatchBox(string name, ConceptIrBox3Value expected, BoundingBox3D actual, ConceptStepTolerance tol)
+ {
+ var diffs = new[] { expected.Min.X - actual.Min.X, expected.Min.Y - actual.Min.Y, expected.Min.Z - actual.Min.Z, expected.Max.X - actual.Max.X, expected.Max.Y - actual.Max.Y, expected.Max.Z - actual.Max.Z };
+ var deviation = diffs.Max(Math.Abs);
+ var status = deviation <= tol.LinearMm ? (deviation == 0 ? ConceptStepMatchStatus.Matched : ConceptStepMatchStatus.WithinTolerance) : ConceptStepMatchStatus.Conflicted;
+ return new(name, "Box3", status, expected, new { min = actual.Min, max = actual.Max, size = new[] { actual.Max.X - actual.Min.X, actual.Max.Y - actual.Min.Y, actual.Max.Z - actual.Min.Z } }, deviation, tol.LinearMm, 1, ConceptStepEvidenceQuality.TopologySupported, expected.Provenance);
+ }
+
+ private static ConceptStepMemberResult MatchPlane(string name, ConceptIrPlaneValue expected, IReadOnlyList<ConceptStepPlaneEvidence> candidates, ConceptStepTolerance tol)
+ {
+ var matching = candidates.Select(p => new { Plane = p, angle = Angle(expected.Normal, p.Normal), offset = Math.Abs((p.Origin - ToPoint(expected.Origin)).Dot(Normalize(expected.Normal))) })
+ .Where(x => x.angle <= tol.AngularDegrees && x.offset <= tol.LinearMm).OrderBy(x => x.Plane.FaceId).ToArray();
+ if (matching.Length == 0) return new(name, "Plane", ConceptStepMatchStatus.Conflicted, expected, candidates.Select(p => new { p.FaceId, p.Origin, p.Normal }).ToArray(), null, tol.LinearMm, 0, ConceptStepEvidenceQuality.ExactAnalytic, expected.Provenance, "No coplanar analytic face.");
+ var status = matching.Length == 1 ? (matching[0].angle == 0 && matching[0].offset == 0 ? ConceptStepMatchStatus.Matched : ConceptStepMatchStatus.WithinTolerance) : ConceptStepMatchStatus.Ambiguous;
+ return new(name, "Plane", status, expected, new { faceIds = matching.Select(x => x.Plane.FaceId).ToArray(), normalDeviationDeg = matching[0].angle, offsetMm = matching[0].offset }, Math.Max(matching[0].angle, matching[0].offset), tol.LinearMm, matching.Length, ConceptStepEvidenceQuality.ExactAnalytic, expected.Provenance);
+ }
+
+ private static ConceptStepMemberResult MatchAxis(string name, ConceptIrAxisValue expected, IReadOnlyList<ConceptStepHoleEvidence> candidates, ConceptStepTolerance tol)
+ {
+ var matches = candidates.Select(c => new { C = c, angle = Angle(expected.Direction, c.Axis), distance = DistanceToAxis(ToPoint(expected.Origin), c.Center, c.Axis) }).Where(x => x.angle <= tol.AngularDegrees && x.distance <= tol.LinearMm).OrderBy(x => x.C.FaceId).ToArray();
+ if (matches.Length == 0) return new(name, "Axis", ConceptStepMatchStatus.Unverifiable, expected, null, null, tol.LinearMm, 0, ConceptStepEvidenceQuality.Unavailable, expected.Provenance, "No analytic cylindrical or revolution axis supports this reference axis.");
+ var status = matches.Length == 1 ? ConceptStepMatchStatus.Matched : ConceptStepMatchStatus.Ambiguous;
+ return new(name, "Axis", status, expected, new { faceIds = matches.Select(x => x.C.FaceId).ToArray(), reversedOrientationAllowed = true }, matches[0].distance, tol.LinearMm, matches.Length, ConceptStepEvidenceQuality.ExactAnalytic, expected.Provenance);
+ }
+
+ private static ConceptStepMemberResult MatchHolePoints(string name, ConceptIrPointSetValue expected, ConceptStepHoleRole role, IReadOnlyList<ConceptStepHoleEvidence> candidates, ConceptStepTolerance tol)
+ {
+ var usable = candidates.Where(c => (role.DiameterMm is null || Math.Abs(2 * c.Radius - role.DiameterMm.Value) <= tol.DimensionMm) && (role.Axis is null || Angle(role.Axis, c.Axis) <= tol.AngularDegrees) && (!string.Equals(role.Kind, "Through", StringComparison.OrdinalIgnoreCase) || c.Through)).OrderBy(c => c.FaceId).ToArray();
+ var assignments = new List<object>(); var max = 0d; var used = new HashSet<int>();
+ foreach (var point in expected.Points.OrderBy(p => p.Ordinal ?? int.MaxValue))
+ {
+ // A hole center declared on its entry plane is geometrically represented by the same cylinder axis,
+ // not necessarily by the surface placement origin (which may be at the opposite entry plane).
+ var ranked = usable.Where(c => !used.Contains(c.FaceId)).Select(c => new { C = c, d = DistanceToAxis(ToPoint(point.Point), c.Center, c.Axis) }).OrderBy(x => x.d).ThenBy(x => x.C.FaceId).ToArray();
+ if (ranked.Length == 0) return new(name, "Point3[]", ConceptStepMatchStatus.Conflicted, expected, assignments, null, tol.LinearMm, usable.Length, ConceptStepEvidenceQuality.DerivedAnalytic, expected.Provenance, "Insufficient distinct hole candidates.");
+ var best = ranked[0]; used.Add(best.C.FaceId); max = Math.Max(max, best.d); assignments.Add(new { ordinal = point.Ordinal, expected = point.Point, candidate = new { faceId = best.C.FaceId, center = best.C.Center, diameter = 2 * best.C.Radius, axis = best.C.Axis }, deviation = best.d });
+ }
+ var status = max <= tol.LinearMm && usable.Length == expected.Points.Count ? (max == 0 ? ConceptStepMatchStatus.Matched : ConceptStepMatchStatus.WithinTolerance) : max <= tol.LinearMm ? ConceptStepMatchStatus.Candidate : ConceptStepMatchStatus.Conflicted;
+ return new(name, "Point3[]", status, new { points = expected.Points.Select(p => p.Point).ToArray(), role }, assignments, max, tol.LinearMm, usable.Length, ConceptStepEvidenceQuality.DerivedAnalytic, expected.Provenance);
+ }
+
+ private static ConceptStepEvidenceIndex BuildEvidence(BrepBody body)
+ {
+ var vertices = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? (Point3D?)p : null).Where(p => p.HasValue).Select(p => p!.Value).ToArray();
+ if (vertices.Length == 0) throw new InvalidOperationException("STEP body has no vertex evidence for body bounds.");
+ var bounds = new BoundingBox3D(new(vertices.Min(p => p.X), vertices.Min(p => p.Y), vertices.Min(p => p.Z)), new(vertices.Max(p => p.X), vertices.Max(p => p.Y), vertices.Max(p => p.Z)));
+ var planes = new List<ConceptStepPlaneEvidence>(); var cylinders = new List<ConceptStepHoleEvidence>();
+ foreach (var face in body.Topology.Faces.OrderBy(f => f.Id.Value)) if (body.TryGetFaceSurfaceGeometry(face.Id, out var surface) && surface is not null)
+ {
+ if (surface.Kind == SurfaceGeometryKind.Plane && surface.Plane is PlaneSurface p) planes.Add(new(face.Id.Value, p.Origin, p.Normal.ToVector()));
+ if (surface.Kind == SurfaceGeometryKind.Cylinder && surface.Cylinder is CylinderSurface c)
+ {
+ var axis = c.Axis.ToVector(); var ts = vertices.Select(v => (v - c.Origin).Dot(axis)).ToArray(); var min = ts.Min(); var max = ts.Max();
+ var through = Math.Abs(min - MinOnAxis(bounds, c.Origin, axis)) <= 0.01 && Math.Abs(max - MaxOnAxis(bounds, c.Origin, axis)) <= 0.01;
+ cylinders.Add(new(face.Id.Value, c.Origin, axis, c.Radius, min, max, through));
+ }
+ }
+ return new(bounds, planes, cylinders);
+ }
+
+ private static Dictionary<string, ConceptStepMatchRole> ParseRoles(string source)
+ {
+ var roles = new Dictionary<string, ConceptStepMatchRole>(StringComparer.Ordinal);
+ foreach (Match match in HoleRole.Matches(source))
+ {
+ var body = match.Groups["body"].Value; var diameter = LengthField.Match(body); var axis = AxisField.Match(body); var kind = KindField.Match(body);
+ roles[match.Groups["member"].Value] = new(match.Groups["member"].Value, "HoleCenters", new(diameter.Success ? double.Parse(diameter.Groups["value"].Value, CultureInfo.InvariantCulture) : null, axis.Success ? Axis(axis.Groups["value"].Value) : null, kind.Success ? kind.Groups["value"].Value : null));
+ }
+ return roles;
+ }
+ private static string StripMatchBlocks(string source) { var result = source; foreach (Match m in Regex.Matches(source, @"\bMatch\s*\{")) { var open = source.IndexOf('{', m.Index); var close = BraceClose(source, open); if (close >= 0) result = result.Remove(open, close - open + 1).Insert(open, new string(' ', close - open + 1)); } return result; }
+ private static int BraceClose(string text, int open) { var d = 0; for (var i = open; i < text.Length; i++) { if (text[i] == '{') d++; else if (text[i] == '}' && --d == 0) return i; } return -1; }
+ private static ConceptIrVector3 Axis(string value) => value switch { "+X" => new(1, 0, 0), "-X" => new(-1, 0, 0), "+Y" => new(0, 1, 0), "-Y" => new(0, -1, 0), "+Z" => new(0, 0, 1), _ => new(0, 0, -1) };
+ private static Point3D ToPoint(ConceptIrPoint3 p) => new(p.X, p.Y, p.Z);
+ private static Vector3D Normalize(ConceptIrVector3 v) => Normalize(new Vector3D(v.X, v.Y, v.Z));
+ private static Vector3D Normalize(Vector3D v) { var l = Math.Sqrt(v.Dot(v)); return v * (1 / l); }
+ private static double Angle(ConceptIrVector3 a, Vector3D b) => Angle(new Vector3D(a.X, a.Y, a.Z), b);
+ private static double Angle(Vector3D a, Vector3D b) => Math.Acos(Math.Clamp(Math.Abs(Normalize(a).Dot(Normalize(b))), -1, 1)) * 180 / Math.PI;
+ private static double Distance(Point3D a, Point3D b) => Math.Sqrt((a - b).Dot(a - b));
+ private static double DistanceToAxis(Point3D p, Point3D origin, Vector3D axis) { var d = p - origin; var n = Normalize(axis); return Math.Sqrt((d - n * d.Dot(n)).Dot(d - n * d.Dot(n))); }
+ private static double MinOnAxis(BoundingBox3D b, Point3D origin, Vector3D axis) => Corners(b).Min(p => (p - origin).Dot(axis));
+ private static double MaxOnAxis(BoundingBox3D b, Point3D origin, Vector3D axis) => Corners(b).Max(p => (p - origin).Dot(axis));
+ private static IEnumerable<Point3D> Corners(BoundingBox3D b) { foreach (var x in new[] { b.Min.X, b.Max.X }) foreach (var y in new[] { b.Min.Y, b.Max.Y }) foreach (var z in new[] { b.Min.Z, b.Max.Z }) yield return new(x, y, z); }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplateExpansionTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplateExpansionTests.cs
new file mode 100644
index 00000000..ea1f0cb4
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplateExpansionTests.cs
@@ -0,0 +1,133 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentV2TemplateExpansionTests
+{
+ [Theory]
+ [InlineData("CompactBracket", "60mm", "40mm", "20mm", "Compact", 60d, 40d, 20d)]
+ [InlineData("StandardBracket", "80mm", "50mm", "25mm", "Standard", 80d, 50d, 25d)]
+ public void TemplateStruct_MonomorphizesBeforeConceptIrAndFeatureAir(string instance, string width, string depth, string height, string variant, double x, double y, double z)
+ {
+ var parse = FirmamentV2Parser.Parse(Source(instance, width, depth, height, variant));
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ var ir = Assert.IsType<ConceptIrDocument>(parse.Document!.ConceptIr);
+ var expansion = Assert.Single(ir.TemplateInstantiations!);
+ Assert.Equal("MountingBracket", expansion.Template);
+ Assert.Equal(instance, expansion.Instance);
+ Assert.Equal("Box", expansion.TypeArguments["TBody"]);
+ Assert.Equal(width, expansion.ValueArguments["Width"]);
+ Assert.Equal(variant, expansion.ValueArguments["Variant"]);
+ Assert.Equal("ExpandedBeforeFeatureAir", expansion.Status);
+ Assert.Contains(instance + "::Design", expansion.GeneratedDeclarations);
+ Assert.Equal("ErasedBeforeFeatureAir", ir.ErasureStatus);
+ Assert.Equal([x, y, z], parse.Document.Solid.Box!.Size);
+ Assert.DoesNotContain("Template", parse.Document.ConceptIr.MaterializedStruct.SourceSpelling, StringComparison.Ordinal);
+ Assert.Contains("firmament-template-expanded-before-feature-air", parse.Diagnostics);
+ Assert.Equal(variant, expansion.SelectedMatchArms!["Variant"]);
+ Assert.Empty(ir.StaticSelections!); // the selected Match was erased before Concept IR's static evaluator.
+ }
+
+ [Fact]
+ public void TemplateBinding_RejectsMissingUnknownMismatchConstraintAndRequire()
+ {
+ var missing = FirmamentV2Parser.Parse(Source("Bad", "", "40mm", "20mm", "Compact"));
+ Assert.Contains(missing.Diagnostics, d => d.StartsWith("firmament-template-missing-required-argument:Width", StringComparison.Ordinal));
+ var unknown = FirmamentV2Parser.Parse(Source("Bad", "60mm", "40mm", "20mm", "Compact").Replace("Variant: Compact", "Nope: Compact", StringComparison.Ordinal));
+ Assert.Contains(unknown.Diagnostics, d => d.StartsWith("firmament-template-unknown-argument:Nope", StringComparison.Ordinal));
+ var mismatch = FirmamentV2Parser.Parse(Source("Bad", "60", "40mm", "20mm", "Compact"));
+ Assert.Contains(mismatch.Diagnostics, d => d.StartsWith("firmament-template-value-argument-type-mismatch:Width", StringComparison.Ordinal));
+ var constraint = FirmamentV2Parser.Parse(Source("Bad", "60mm", "40mm", "20mm", "Compact").Replace("TBody: Box", "TBody: Sphere", StringComparison.Ordinal));
+ Assert.Contains(constraint.Diagnostics, d => d.StartsWith("firmament-template-type-argument-does-not-satisfy-concept:TBody", StringComparison.Ordinal));
+ var require = FirmamentV2Parser.Parse(Source("Bad", "0mm", "40mm", "20mm", "Compact"));
+ Assert.Contains(require.Diagnostics, d => d.StartsWith("firmament-template-require-failed:Bad.ValidDimensions", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void TemplateBinding_AppliesTypedEnumDefault()
+ {
+ var source = Source("DefaultBracket", "80mm", "50mm", "25mm", "Standard").Replace(", Variant: Standard", string.Empty, StringComparison.Ordinal);
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ var expansion = Assert.Single(parse.Document!.ConceptIr!.TemplateInstantiations!);
+ Assert.Equal("Standard", expansion.ValueArguments["Variant"]);
+ Assert.Contains("Variant", expansion.DefaultedArguments);
+ Assert.Equal("Standard", expansion.SelectedMatchArms!["Variant"]);
+ }
+
+ [Fact]
+ public void TemplateBinding_RejectsBadDefaultsDefaultCyclesNonBoolRequiresAndRecursiveSpecializations()
+ {
+ var badDefault = FirmamentV2Parser.Parse("""
+ Template < Width: Length = Nope > Struct A { }
+ Struct X = A <>
+ """);
+ Assert.Contains(badDefault.Diagnostics, d => d.StartsWith("firmament-template-default-value-type-mismatch:Width", StringComparison.Ordinal));
+ var defaultCycle = FirmamentV2Parser.Parse("""
+ Template < Width: Length = Depth, Depth: Length = Width > Struct A { }
+ Struct X = A <>
+ """);
+ Assert.Contains(defaultCycle.Diagnostics, d => d.StartsWith("firmament-template-default-dependency-cycle:Width -> Depth -> Width", StringComparison.Ordinal));
+ var nonBool = FirmamentV2Parser.Parse("""
+ Template < Width: Length > Struct A { Require Broken => Width }
+ Struct X = A < Width: 1mm >
+ """);
+ Assert.Contains(nonBool.Diagnostics, d => d.StartsWith("firmament-template-require-non-bool:Broken", StringComparison.Ordinal));
+ var recursive = FirmamentV2Parser.Parse("""
+ Template <> Struct A { Struct Nested = A <> }
+ Struct X = A <>
+ """);
+ Assert.Contains(recursive.Diagnostics, d => d.StartsWith("firmament-template-recursive-specialization:A -> A", StringComparison.Ordinal));
+ }
+
+ private static string Source(string instance, string width, string depth, string height, string variant) => $$"""
+ Concept MountingFrame {
+ Bounds: Box3
+ TopPlane: Plane
+ CenterAxis: Axis
+ ChamferDistance: Length
+ }
+ Concept PrismaticBody {
+ Bounds: Box3
+ TopPlane: Plane
+ }
+ Enum BracketVariant {
+ Compact
+ Standard
+ }
+ Template < type TBody satisfies PrismaticBody, Width: Length, Depth: Length, Height: Length, Variant: BracketVariant = Standard >
+ Struct MountingBracket: MountingFrame {
+ Require ValidDimensions => Width > 0mm && Depth > 0mm && Height > 0mm
+ Concept Struct Design: MountingFrame {
+ Bounds: Box3 {
+ Size: [Width, Depth, Height]
+ }
+ TopPlane: Bounds.Face(+Z)
+ CenterAxis: Bounds.Center.Axis(+Z)
+ ChamferDistance: Match Variant {
+ Compact => 1mm
+ Standard => 1.5mm
+ }
+ }
+ Box Base {
+ Bounds: Design.Bounds
+ }
+ Modify Base {
+ EdgeFinish TopBreak {
+ Face: Design.TopPlane
+ Target: Boundary
+ Kind: Chamfer
+ Distance: Design.ChamferDistance
+ }
+ }
+ Expose {
+ Bounds: Design.Bounds
+ TopPlane: Base.Top
+ CenterAxis: Design.CenterAxis
+ ChamferDistance: Design.ChamferDistance
+ }
+ }
+ Struct {{instance}} = MountingBracket < TBody: Box, {{(width.Length == 0 ? string.Empty : "Width: " + width + ",")}} Depth: {{depth}}, Height: {{height}}, Variant: {{variant}} >
+ """;
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplatePatternTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplatePatternTests.cs
new file mode 100644
index 00000000..bb07ab1d
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplatePatternTests.cs
@@ -0,0 +1,96 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+namespace Aetheris.Kernel.Firmament.Tests;
+public sealed class FirmamentV2TemplatePatternTests
+{
+ [Fact]
+ public void PersistedCompactTemplate_Parses()
+ {
+ var path = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../demos/template-m4b-compact.firmament"));
+ var parse = FirmamentV2Parser.Parse(File.ReadAllText(path));
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ }
+ [Fact]
+ public void Pattern_ExpandsGridToConcreteSemanticHoles()
+ {
+ var parse = FirmamentV2Parser.Parse("""
+ Concept Struct Design {
+ Bounds: Box3 {
+ Size: [60mm, 40mm, 20mm]
+ }
+ Top: Bounds.Face(+Z)
+ Points: Grid {
+ Within: Bounds.Face(+Z).Inset(8mm)
+ Columns: 2
+ Rows: 1
+ }
+ }
+ Struct Bracket {
+ Box Base {
+ Bounds: Design.Bounds
+ }
+ Modify Base {
+ Pattern MountHoles {
+ Source: Design.Points
+ Hole<Shaft> Item {
+ on: Base.Top
+ center: Item
+ diameter: 8.5mm
+ end: ThroughAll
+ }
+ }
+ }
+ }
+ """);
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ Assert.Equal(2, parse.Document!.ModifyBlocks!.Single().SemanticHoles.Count);
+ Assert.Equal(["MountHoles[0]", "MountHoles[1]"], parse.Document.ModifyBlocks.Single().SemanticHoles.Select(x => x.Name));
+ var expansion = Assert.Single(parse.Document.ConceptIr!.PatternExpansions!);
+ Assert.Equal(2, expansion.Count);
+ Assert.Equal("Point3", expansion.ElementType);
+ }
+
+ [Fact]
+ public void Pattern_RejectsNonStaticSourceAndUnboundItem()
+ {
+ var invalidSource = FirmamentV2Parser.Parse("""
+ Struct Bracket {
+ Box Base { Size: [60mm, 40mm, 20mm] }
+ Modify Base {
+ Pattern Holes {
+ Source: Base.Top
+ Hole<Shaft> Item { On: Base.Top Center: Item Diameter: 8.5mm End: ThroughAll }
+ }
+ }
+ }
+ """);
+ Assert.Contains(invalidSource.Diagnostics, d => d.StartsWith("firmament-pattern-source-not-static-point3-collection", StringComparison.Ordinal));
+
+ var unboundItem = FirmamentV2Parser.Parse("""
+ Concept Struct Design {
+ Bounds: Box3 {
+ Size: [60mm, 40mm, 20mm]
+ }
+ Points: Grid {
+ Within: Bounds.Face(+Z).Inset(8mm)
+ Columns: 2
+ Rows: 1
+ }
+ }
+ Struct Bracket {
+ Box Base { Bounds: Design.Bounds }
+ Modify Base {
+ Pattern Holes {
+ Source: Design.Points
+ Hole<Shaft> Item {
+ On: Base.Top
+ Center: Other
+ Diameter: 8.5mm
+ End: ThroughAll
+ }
+ }
+ }
+ }
+ """);
+ Assert.Contains(unboundItem.Diagnostics, d => d == "firmament-pattern-unbound-item");
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
index 68effa6e..f6c8ccff 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
@@ -103,6 +103,20 @@ public sealed record ConceptIrStaticSelection(
string? Result,
FirmamentV2SourceSpan SourceSpan,
string Provenance);
+public sealed record ConceptIrPatternExpansion(string Pattern, string Source, string ElementType, int Count, IReadOnlyList<string> GeneratedDeclarations, FirmamentV2SourceSpan SourceSpan, string Status = "ExpandedBeforeFeatureAir");
+/// <summary>Source-map-only evidence for a compile-time template expansion. This is deliberately not AIR.</summary>
+public sealed record ConceptIrTemplateInstantiation(
+ string Template,
+ string Instance,
+ IReadOnlyDictionary<string, string> TypeArguments,
+ IReadOnlyDictionary<string, string> ValueArguments,
+ IReadOnlyList<string> DefaultedArguments,
+ string SpecializationIdentity,
+ IReadOnlyList<string> GeneratedDeclarations,
+ FirmamentV2SourceSpan TemplateSourceSpan,
+ FirmamentV2SourceSpan ApplicationSourceSpan,
+ string Status = "ExpandedBeforeFeatureAir",
+ IReadOnlyDictionary<string, string>? SelectedMatchArms = null);
public sealed record ConceptIrDocument(
IReadOnlyList<ConceptIrDefinition> Concepts,
IReadOnlyList<ConceptIrStructInstance> Structs,
@@ -111,7 +125,9 @@ public sealed record ConceptIrDocument(
IReadOnlyList<ConceptIrBinding> Bindings,
string ErasureStatus = "ErasedBeforeFeatureAir",
IReadOnlyList<ConceptIrEnumDefinition>? Enums = null,
- IReadOnlyList<ConceptIrStaticSelection>? StaticSelections = null);
+ IReadOnlyList<ConceptIrStaticSelection>? StaticSelections = null,
+ IReadOnlyList<ConceptIrTemplateInstantiation>? TemplateInstantiations = null,
+ IReadOnlyList<ConceptIrPatternExpansion>? PatternExpansions = null);
internal sealed record ConceptPhase3Resolution(
string ModelName,
@@ -125,6 +141,8 @@ internal sealed record ConceptPhase3Resolution(
internal static class ConceptIrResolver
{
+ // Static expansion is deliberately bounded: Pattern is compile-time declaration generation, not iteration.
+ private const int MaxStaticPatternExpansion = 1024;
public const string MissingMember = "firmament-concept-missing-member";
public const string UnknownMember = "firmament-concept-unknown-member";
public const string TypeMismatch = "firmament-concept-type-mismatch";
@@ -158,6 +176,8 @@ internal static class ConceptIrResolver
public static ConceptPhase3Resolution? Resolve(string source, List<string> diagnostics)
{
+ // Match roles are compile-time conformance metadata. They deliberately do not lower to AIR.
+ source = StripMatchBlocks(source);
var enums = ParseEnums(source, diagnostics);
var definitions = ParseDefinitions(source, diagnostics);
var materializedMatches = MaterializedHeader.Matches(source).Cast<Match>()
@@ -274,6 +294,8 @@ internal static class ConceptIrResolver
var modifyBody = source[(modifyOpen + 1)..modifyClose];
var holes = ParseConceptHoles(modifyBody, modifyOpen + 1, box.Groups["name"].Value, resolvedBounds,
allInstances, materialized.Groups["name"].Value, bindings, diagnostics);
+ var patterns = ParseConceptPatterns(modifyBody, modifyOpen + 1, box.Groups["name"].Value, resolvedBounds, allInstances, materialized.Groups["name"].Value, bindings, diagnostics, out var patternHoles);
+ holes = holes.Concat(patternHoles).ToArray();
if (holes.Count == 0 && finishes.Count == 0) { diagnostics.Add(FirmamentV2Parser.Phase3EdgeFinishSyntaxInvalid); return null; }
var satisfiesMaterialized = materialized.Groups["concept"].Success ? new[] { materialized.Groups["concept"].Value } : [];
@@ -283,7 +305,7 @@ internal static class ConceptIrResolver
var conformance = satisfiesMaterialized.Length == 0 ? "NotDeclared" : diagnostics.Any(d => IsConformanceDiagnostic(d)) ? "Invalid" : "Valid";
var ir = new ConceptIrDocument(definitions, instanceList, resolved,
new(materialized.Groups["name"].Value, materialized.Groups["kind"].Value, satisfiesMaterialized, new(materialized.Index, materializedClose - materialized.Index + 1), exposed, conformance), bindings,
- Enums: enums, StaticSelections: staticSelections);
+ Enums: enums, StaticSelections: staticSelections, PatternExpansions: patterns);
var modifyBlock = new FirmamentV2ModifyBlock(modify.Groups["target"].Value, [], holes, finishes);
return new(materialized.Groups["name"].Value, materialized.Groups["kind"].Value, "mm", box.Groups["name"].Value, size, boundsProvenance,
modifyBlock, ir);
@@ -304,6 +326,7 @@ internal static class ConceptIrResolver
var headers = Regex.Matches(body, @"\bhole\s*<\s*(?<variant>[A-Za-z_][A-Za-z0-9_]*)\s*>\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
foreach (Match header in headers)
{
+ if (IsInsidePattern(body, header.Index)) continue;
if (!string.Equals(header.Groups["variant"].Value, "shaft", StringComparison.OrdinalIgnoreCase)) { diagnostics.Add(FirmamentV2Parser.HoleVariantUnknown); continue; }
var open = body.IndexOf('{', header.Index); var close = FindMatchingBrace(body, open);
if (close < 0) { diagnostics.Add(FirmamentV2Parser.RegionUnsupported); continue; }
@@ -349,6 +372,46 @@ internal static class ConceptIrResolver
return result;
}
+ private static IReadOnlyList<ConceptIrPatternExpansion> ParseConceptPatterns(string body, int bodyOffset, string boxName, ConceptIrBox3Value? bounds, IReadOnlyDictionary<string, ConceptIrStructInstance> instances, string materializedName, List<ConceptIrBinding> bindings, List<string> diagnostics, out IReadOnlyList<FirmamentV2SemanticHoleDecl> holes)
+ {
+ var reports = new List<ConceptIrPatternExpansion>(); var expanded = new List<FirmamentV2SemanticHoleDecl>();
+ var generatedPaths = new HashSet<string>(StringComparer.Ordinal);
+ foreach (Match pattern in Regex.Matches(body, @"\bPattern\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant))
+ {
+ var open = body.IndexOf('{', pattern.Index); var close = FindMatchingBrace(body, open);
+ if (close < 0) { diagnostics.Add("firmament-pattern-invalid-source"); continue; }
+ var patternBody = body[(open + 1)..close];
+ var source = FieldValue(patternBody, "Source");
+ var reference = Regex.Match(source, @"^(?<instance>[A-Za-z_][A-Za-z0-9_]*)\.(?<member>[A-Za-z_][A-Za-z0-9_]*)$", RegexOptions.CultureInvariant);
+ if (!reference.Success || !instances.TryGetValue(reference.Groups["instance"].Value, out var instance) || !instance.Members.TryGetValue(reference.Groups["member"].Value, out var member) || member is not ConceptIrPointSetValue points)
+ { diagnostics.Add("firmament-pattern-source-not-static-point3-collection:" + source); continue; }
+ if (points.Points.Count > MaxStaticPatternExpansion)
+ { diagnostics.Add("firmament-pattern-expansion-limit-exceeded:" + points.Points.Count.ToString(CultureInfo.InvariantCulture)); continue; }
+ var feature = Regex.Match(patternBody, @"\bHole\s*<\s*Shaft\s*>\s+(?<item>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
+ if (!feature.Success) { diagnostics.Add("firmament-pattern-element-type-mismatch"); continue; }
+ var featureOpen = patternBody.IndexOf('{', feature.Index); var featureClose = FindMatchingBrace(patternBody, featureOpen);
+ if (featureClose < 0) { diagnostics.Add("firmament-pattern-element-type-mismatch"); continue; }
+ var item = feature.Groups["item"].Value; var featureBody = patternBody[(featureOpen + 1)..featureClose];
+ if (!Regex.IsMatch(featureBody, $@"\bCenter\s*:\s*{Regex.Escape(item)}\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) { diagnostics.Add("firmament-pattern-unbound-item"); continue; }
+ var generatedNames = new List<string>();
+ for (var index = 0; index < points.Points.Count; index++)
+ {
+ var generatedName = pattern.Groups["name"].Value + "_" + index.ToString(CultureInfo.InvariantCulture);
+ var concreteBody = Regex.Replace(featureBody, $@"\b{Regex.Escape(item)}\b", source + "[" + index.ToString(CultureInfo.InvariantCulture) + "]");
+ var concrete = $"hole<Shaft> {generatedName} {{{concreteBody}}}";
+ var one = ParseConceptHoles(concrete, bodyOffset + open + featureOpen, boxName, bounds, instances, materializedName, bindings, diagnostics);
+ if (one.Count != 1) continue;
+ var readable = pattern.Groups["name"].Value + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
+ var generatedPath = materializedName + "::" + readable;
+ if (!generatedPaths.Add(generatedPath)) { diagnostics.Add("firmament-pattern-generated-declaration-collision:" + generatedPath); continue; }
+ expanded.Add(one[0] with { Name = readable }); generatedNames.Add(generatedPath);
+ }
+ reports.Add(new(materializedName + "::" + pattern.Groups["name"].Value, materializedName + "::" + source, "Point3", points.Points.Count, generatedNames, new(bodyOffset + pattern.Index, close - pattern.Index + 1)));
+ }
+ holes = expanded; return reports;
+ }
+
+
private static IReadOnlyList<ConceptIrSemanticMember> ParseExposedMembers(
string body,
int bodyOffset,
@@ -804,7 +867,8 @@ internal static class ConceptIrResolver
};
private static ConceptIrVector3 Vector(string axis) => axis switch { "+X" => new(1, 0, 0), "-X" => new(-1, 0, 0), "+Y" => new(0, 1, 0), "-Y" => new(0, -1, 0), "+Z" => new(0, 0, 1), "-Z" => new(0, 0, -1), _ => new(0, 0, 0) };
private static string AxisOf(ConceptIrVector3 v) => (v.X, v.Y, v.Z) switch { (1, 0, 0) => "+X", (-1, 0, 0) => "-X", (0, 1, 0) => "+Y", (0, -1, 0) => "-Y", (0, 0, 1) => "+Z", (0, 0, -1) => "-Z", _ => string.Empty };
- private static string FieldValue(string body, string name) { var m = Regex.Match(body, $@"\b{Regex.Escape(name)}\s*:\s*(?<value>[^\r\n}}]+)", RegexOptions.CultureInvariant); return m.Success ? m.Groups["value"].Value.Trim() : string.Empty; }
+ private static bool IsInsidePattern(string body, int index) => Regex.Matches(body, @"\bPattern\s+[A-Za-z_][A-Za-z0-9_]*\s*\{", RegexOptions.CultureInvariant).Cast<Match>().Any(p => { var close = FindMatchingBrace(body, body.IndexOf('{', p.Index)); return p.Index < index && close > index; });
+ private static string FieldValue(string body, string name) { var m = Regex.Match(body, $@"\b{Regex.Escape(name)}\s*:\s*(?<value>[^\r\n}}]+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); return m.Success ? m.Groups["value"].Value.Trim() : string.Empty; }
private static int IntField(string body, string name) => int.TryParse(FieldValue(body, name), NumberStyles.None, CultureInfo.InvariantCulture, out var value) ? value : -1;
private static double ParseLength(string source) { source = source.Trim(); return source.EndsWith("mm", StringComparison.Ordinal) && double.TryParse(source[..^2], NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : double.NaN; }
private static double ParseLengthOrUnitless(string source)
@@ -816,4 +880,14 @@ internal static class ConceptIrResolver
private static string Id(string provenance) => "concept:" + provenance;
private static bool IsPrecededByConcept(string source, int index) { var start = Math.Max(0, index - 10); return Regex.IsMatch(source[start..index], @"Concept\s+$", RegexOptions.CultureInvariant); }
private static int FindMatchingBrace(string source, int open) { if (open < 0 || open >= source.Length || source[open] != '{') return -1; var depth = 0; for (var i = open; i < source.Length; i++) { if (source[i] == '{') depth++; else if (source[i] == '}' && --depth == 0) return i; } return -1; }
+ private static string StripMatchBlocks(string source)
+ {
+ foreach (Match match in Regex.Matches(source, @"\bMatch\s*\{", RegexOptions.CultureInvariant).Cast<Match>().Reverse())
+ {
+ var open = source.IndexOf('{', match.Index);
+ var close = FindMatchingBrace(source, open);
+ if (close >= 0) source = source.Remove(open, close - open + 1).Insert(open, new string(' ', close - open + 1));
+ }
+ return source;
+ }
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 1e343cc4..ad5e1fe5 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -226,9 +226,17 @@ public static class FirmamentV2Parser
var source = StripLineComments(sourceText);
conceptCatalog ??= FirmamentV2ForgeConceptRegistry.Catalog;
+ var templateExpansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics);
+ if (templateExpansion is null)
+ {
+ diagnostics.Add("firmament-v2-parse-failed");
+ return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray());
+ }
+ source = templateExpansion.Source;
+
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 ParseConceptModelingDocument(source, diagnostics);
+ return ParseConceptModelingDocument(source, diagnostics, templateExpansion.Instantiations);
if (Regex.IsMatch(source, @"^\s*Model\b", RegexOptions.CultureInvariant))
return ParsePhase3ModelingDocument(source, diagnostics);
@@ -758,7 +766,7 @@ public static class FirmamentV2Parser
return FirmamentV2ParseResult.Success(document, diagnostics);
}
- private static FirmamentV2ParseResult ParseConceptModelingDocument(string source, List<string> diagnostics)
+ private static FirmamentV2ParseResult ParseConceptModelingDocument(string source, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations = null)
{
var resolution = ConceptIrResolver.Resolve(source, diagnostics);
if (resolution is null || diagnostics.Any(IsConceptFatalDiagnostic))
@@ -778,9 +786,10 @@ public static class FirmamentV2Parser
resolution.Units,
[solid],
[resolution.ModifyBlock],
- ConceptIr: resolution.ConceptIr);
+ ConceptIr: resolution.ConceptIr with { TemplateInstantiations = templateInstantiations ?? [] });
diagnostics.Add("firmament-concept-ir-resolved");
diagnostics.Add("firmament-concept-struct-erased-before-feature-air");
+ if ((templateInstantiations?.Count ?? 0) > 0) diagnostics.Add("firmament-template-expanded-before-feature-air");
if (resolution.ModifyBlock.EdgeFinishes?.Count > 0) diagnostics.Add("firmament-v2-phase3-edge-finish-parsed");
if (resolution.ModifyBlock.SemanticHoles.Count > 0) diagnostics.Add("firmament-concept-point3-semantic-holes-parsed");
diagnostics.Add("firmament-v2-parse-succeeded");
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
new file mode 100644
index 00000000..f5bbff29
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
@@ -0,0 +1,271 @@
+using System.Collections.Immutable;
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+// Immutable parser/binder IR. Source text is payload for the already-established declaration parser;
+// it is never an authority for parameter meaning after TemplateIrParser has built these nodes.
+internal sealed record TemplateDeclarationIr(string Name, string TargetKind, string HeaderTail, ImmutableArray<TemplateParameterIr> Parameters, string Body, FirmamentV2SourceSpan SourceSpan);
+internal abstract record TemplateParameterIr(string Name, FirmamentV2SourceSpan SourceSpan);
+internal sealed record TemplateTypeParameterIr(string Name, string ConstraintConcept, FirmamentV2SourceSpan SourceSpan) : TemplateParameterIr(Name, SourceSpan);
+internal sealed record TemplateValueParameterIr(string Name, string TypeName, string? DefaultExpression, FirmamentV2SourceSpan SourceSpan) : TemplateParameterIr(Name, SourceSpan);
+internal sealed record TemplateApplicationIr(string TargetKind, string InstanceName, string TemplateName, ImmutableArray<TemplateArgumentIr> Arguments, FirmamentV2SourceSpan SourceSpan);
+internal sealed record TemplateArgumentIr(string Name, string Expression, FirmamentV2SourceSpan SourceSpan);
+internal sealed record BoundTemplateArguments(ImmutableDictionary<string, string> TypeArguments, ImmutableDictionary<string, string> ValueArguments, ImmutableArray<string> DefaultedArguments);
+internal sealed record TemplateSpecializationIr(TemplateDeclarationIr Template, TemplateApplicationIr Application, BoundTemplateArguments Arguments, string SpecializationIdentity, ImmutableArray<string> GeneratedDeclarationPaths);
+
+/// <summary>Authoritative, finite template specialization phase. It produces concrete declarations only.</summary>
+internal static class FirmamentV2TemplateExpansion
+{
+ internal const string Prefix = "firmament-template-";
+ internal const string DuplicateName = Prefix + "duplicate-name";
+ internal const string DuplicateParameter = Prefix + "duplicate-parameter";
+ internal const string InvalidParameter = Prefix + "invalid-parameter-name";
+ internal const string MissingArgument = Prefix + "missing-required-argument";
+ internal const string UnknownArgument = Prefix + "unknown-argument";
+ internal const string DuplicateArgument = Prefix + "duplicate-argument";
+ internal const string TypeMismatch = Prefix + "value-argument-type-mismatch";
+ internal const string BadDefault = Prefix + "default-value-type-mismatch";
+ internal const string DefaultCycle = Prefix + "default-dependency-cycle";
+ internal const string UnknownConstraint = Prefix + "unknown-concept-constraint";
+ internal const string ConstraintFailure = Prefix + "type-argument-does-not-satisfy-concept";
+ internal const string RequireFailed = Prefix + "require-failed";
+ internal const string RequireNonBool = Prefix + "require-non-bool";
+ internal const string Recursive = Prefix + "recursive-specialization";
+ internal const string ApplicationCycle = Prefix + "application-cycle";
+
+ internal sealed record Result(string Source, IReadOnlyList<ConceptIrTemplateInstantiation> Instantiations);
+
+ public static Result? Expand(string source, List<string> diagnostics)
+ {
+ var declarations = ParseDeclarations(source, diagnostics);
+ if (declarations.Length == 0) return new(source, []);
+ var byName = declarations.ToDictionary(d => d.Name, StringComparer.Ordinal);
+ DetectTemplateCycles(declarations, byName, diagnostics);
+ var applications = ParseApplications(source, byName, diagnostics);
+ if (HasErrors(diagnostics)) return null;
+
+ var enums = ParseEnums(source);
+ var changes = declarations.Select(d => (d.SourceSpan.Start, d.SourceSpan.Length, Text: string.Empty)).ToList();
+ var instantiations = new List<ConceptIrTemplateInstantiation>();
+ foreach (var application in applications)
+ {
+ var template = byName[application.TemplateName];
+ if (!string.Equals(application.TargetKind, template.TargetKind, StringComparison.Ordinal)) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); continue; }
+ var bound = Bind(template, application, source, enums, diagnostics);
+ if (bound is null) continue;
+ var specialization = new TemplateSpecializationIr(template, application, bound, Identity(template, application, bound), GeneratedPaths(template.Body, application.InstanceName));
+ var body = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);
+ if (body is null) continue;
+ body = Substitute(body, bound);
+ if (!EvaluateRequires(body, application.InstanceName, diagnostics)) continue;
+ body = RemoveRequires(body);
+ changes.Add((application.SourceSpan.Start, application.SourceSpan.Length, $"{template.TargetKind} {application.InstanceName}{template.HeaderTail} {{{body}}}"));
+ instantiations.Add(new(template.Name, application.InstanceName, bound.TypeArguments, bound.ValueArguments, bound.DefaultedArguments,
+ specialization.SpecializationIdentity, specialization.GeneratedDeclarationPaths, template.SourceSpan, application.SourceSpan, SelectedMatchArms: selectedMatches));
+ }
+ if (HasErrors(diagnostics)) return null;
+ foreach (var change in changes.OrderByDescending(c => c.Start)) source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
+ return new(source, instantiations);
+ }
+
+ private static ImmutableArray<TemplateDeclarationIr> ParseDeclarations(string source, List<string> diagnostics)
+ {
+ var result = ImmutableArray.CreateBuilder<TemplateDeclarationIr>(); var names = new HashSet<string>(StringComparer.Ordinal);
+ foreach (Match start in Regex.Matches(source, @"\bTemplate\s*<", RegexOptions.CultureInvariant))
+ {
+ var open = source.IndexOf('<', start.Index); var close = Matching(source, open, '<', '>');
+ var header = close < 0 ? Match.Empty : Regex.Match(source[(close + 1)..], @"^\s*(?<kind>Concept\s+Struct|Struct|Model)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)(?<tail>\s*:\s*[A-Za-z_][A-Za-z0-9_]*)?\s*\{", RegexOptions.CultureInvariant);
+ if (close < 0 || !header.Success) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); continue; }
+ var brace = close + 1 + header.Index + header.Value.LastIndexOf('{'); var end = Matching(source, brace, '{', '}');
+ if (end < 0) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); continue; }
+ var name = header.Groups["name"].Value;
+ if (!names.Add(name)) { diagnostics.Add(DuplicateName + ":" + name); continue; }
+ var parameters = ParseParameters(source[(open + 1)..close], open + 1, diagnostics);
+ result.Add(new(name, header.Groups["kind"].Value, header.Groups["tail"].Value, parameters, source[(brace + 1)..end], new(start.Index, end - start.Index + 1)));
+ }
+ return result.ToImmutable();
+ }
+
+ private static ImmutableArray<TemplateParameterIr> ParseParameters(string text, int offset, List<string> diagnostics)
+ {
+ var result = ImmutableArray.CreateBuilder<TemplateParameterIr>(); var names = new HashSet<string>(StringComparer.Ordinal);
+ var cursor = 0;
+ foreach (var raw in text.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
+ {
+ var span = new FirmamentV2SourceSpan(offset + cursor, raw.Length); cursor += raw.Length + 1;
+ var type = Regex.Match(raw, @"^type\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s+satisfies\s+(?<concept>[A-Za-z_][A-Za-z0-9_]*)$", RegexOptions.CultureInvariant);
+ var value = Regex.Match(raw, @"^(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<type>[A-Za-z_][A-Za-z0-9_]*)(?:\s*=\s*(?<default>.+))?$", RegexOptions.CultureInvariant);
+ if (!type.Success && !value.Success) { diagnostics.Add(InvalidParameter + ":" + raw); continue; }
+ var name = type.Success ? type.Groups["name"].Value : value.Groups["name"].Value;
+ if (!names.Add(name)) { diagnostics.Add(DuplicateParameter + ":" + name); continue; }
+ result.Add(type.Success ? new TemplateTypeParameterIr(name, type.Groups["concept"].Value, span) : new TemplateValueParameterIr(name, value.Groups["type"].Value, value.Groups["default"].Success ? value.Groups["default"].Value.Trim() : null, span));
+ }
+ return result.ToImmutable();
+ }
+
+ private static ImmutableArray<TemplateApplicationIr> ParseApplications(string source, IReadOnlyDictionary<string, TemplateDeclarationIr> templates, List<string> diagnostics)
+ {
+ var result = ImmutableArray.CreateBuilder<TemplateApplicationIr>();
+ foreach (Match start in Regex.Matches(source, @"\b(?<kind>Concept\s+Struct|Struct|Model)\s+(?<instance>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?<template>[A-Za-z_][A-Za-z0-9_]*)\s*<", RegexOptions.CultureInvariant))
+ {
+ if (!templates.ContainsKey(start.Groups["template"].Value)) continue;
+ var open = source.IndexOf('<', start.Index); var close = Matching(source, open, '<', '>');
+ if (close < 0) { diagnostics.Add(MissingArgument); continue; }
+ var args = ImmutableArray.CreateBuilder<TemplateArgumentIr>(); var seen = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var raw in source[(open + 1)..close].Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
+ {
+ var parsed = Regex.Match(raw, @"^(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<value>.+)$", RegexOptions.CultureInvariant);
+ if (!parsed.Success) { diagnostics.Add(UnknownArgument + ":" + raw); continue; }
+ var name = parsed.Groups["name"].Value;
+ if (!seen.Add(name)) { diagnostics.Add(DuplicateArgument + ":" + name); continue; }
+ args.Add(new(name, parsed.Groups["value"].Value.Trim(), new(start.Index, close - start.Index + 1)));
+ }
+ result.Add(new(start.Groups["kind"].Value, start.Groups["instance"].Value, start.Groups["template"].Value, args.ToImmutable(), new(start.Index, close - start.Index + 1)));
+ }
+ return result.ToImmutable();
+ }
+
+ private static BoundTemplateArguments? Bind(TemplateDeclarationIr template, TemplateApplicationIr application, string source, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums, List<string> diagnostics)
+ {
+ var supplied = application.Arguments.ToDictionary(a => a.Name, a => a.Expression, StringComparer.Ordinal);
+ foreach (var unknown in supplied.Keys.Where(name => template.Parameters.All(p => p.Name != name))) diagnostics.Add(UnknownArgument + ":" + unknown);
+ var types = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal); var values = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal); var defaults = ImmutableArray.CreateBuilder<string>();
+ var resolving = new List<string>();
+ string? Resolve(TemplateValueParameterIr p)
+ {
+ if (values.TryGetValue(p.Name, out var existing)) return existing;
+ if (resolving.Contains(p.Name, StringComparer.Ordinal)) { diagnostics.Add(DefaultCycle + ":" + string.Join(" -> ", resolving.Append(p.Name))); return null; }
+ var expression = supplied.TryGetValue(p.Name, out var suppliedValue) ? suppliedValue : p.DefaultExpression;
+ if (expression is null) { diagnostics.Add(MissingArgument + ":" + p.Name); return null; }
+ resolving.Add(p.Name);
+ var referenced = template.Parameters.OfType<TemplateValueParameterIr>().SingleOrDefault(x => x.Name == expression);
+ var value = referenced is null ? expression : Resolve(referenced);
+ resolving.RemoveAt(resolving.Count - 1);
+ if (value is null) return null;
+ if (!TypeMatches(value, p.TypeName, enums)) { diagnostics.Add((supplied.ContainsKey(p.Name) ? TypeMismatch : BadDefault) + $":{p.Name}:expected-{p.TypeName}:actual-{value}"); return null; }
+ values[p.Name] = value;
+ if (!supplied.ContainsKey(p.Name)) defaults.Add(p.Name);
+ return value;
+ }
+ foreach (var parameter in template.Parameters)
+ {
+ if (parameter is TemplateTypeParameterIr type)
+ {
+ if (!supplied.TryGetValue(type.Name, out var value)) { diagnostics.Add(MissingArgument + ":" + type.Name); continue; }
+ if (!ConceptExists(type.ConstraintConcept, source)) diagnostics.Add(UnknownConstraint + ":" + type.ConstraintConcept);
+ else if (!Satisfies(value, type.ConstraintConcept, source)) diagnostics.Add(ConstraintFailure + $":{type.Name}:{value}:{type.ConstraintConcept}");
+ types[type.Name] = value;
+ }
+ else _ = Resolve((TemplateValueParameterIr)parameter);
+ }
+ return HasErrors(diagnostics) ? null : new(types.ToImmutable(), values.ToImmutable(), defaults.ToImmutable());
+ }
+
+ private static IReadOnlyDictionary<string, ImmutableHashSet<string>> ParseEnums(string source) => Regex.Matches(source, @"\bEnum\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{(?<body>.*?)\}", RegexOptions.Singleline | RegexOptions.CultureInvariant).Cast<Match>().ToDictionary(
+ m => m.Groups["name"].Value,
+ m => Regex.Matches(m.Groups["body"].Value, @"[A-Za-z_][A-Za-z0-9_]*", RegexOptions.CultureInvariant).Select(v => v.Value).ToImmutableHashSet(StringComparer.Ordinal), StringComparer.Ordinal);
+ private static bool TypeMatches(string value, string type, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums) => type switch
+ {
+ "Length" => Regex.IsMatch(value, @"^[-+]?[0-9]+(?:\.[0-9]+)?mm$", RegexOptions.CultureInvariant),
+ "int" => long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out _), "float" => double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out _), "bool" => value is "true" or "false",
+ _ when enums.TryGetValue(type, out var variants) => variants.Contains(value),
+ _ => false
+ };
+ private static bool ConceptExists(string concept, string source) => Regex.IsMatch(source, $@"\bConcept\s+{Regex.Escape(concept)}\s*\{{", RegexOptions.CultureInvariant);
+ private static bool Satisfies(string type, string concept, string source)
+ {
+ if (type != "Box") return Regex.IsMatch(source, $@"\bConcept\s+Struct\s+{Regex.Escape(type)}\s*:\s*{Regex.Escape(concept)}\s*\{{", RegexOptions.CultureInvariant);
+ var definition = Regex.Match(source, $@"\bConcept\s+{Regex.Escape(concept)}\s*\{{(?<body>.*?)\}}", RegexOptions.Singleline | RegexOptions.CultureInvariant);
+ var capabilities = new Dictionary<string, string>(StringComparer.Ordinal) { ["Bounds"] = "Box3", ["TopPlane"] = "Plane", ["CenterAxis"] = "Axis" };
+ return definition.Success && Regex.Matches(definition.Groups["body"].Value, @"(?m)^\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<kind>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant).Cast<Match>().All(m => capabilities.TryGetValue(m.Groups["name"].Value, out var actual) && actual == m.Groups["kind"].Value);
+ }
+ private static string Substitute(string body, BoundTemplateArguments bound) => bound.TypeArguments.Concat(bound.ValueArguments).Aggregate(body, (result, pair) => Regex.Replace(result, $@"\b{Regex.Escape(pair.Key)}\b", pair.Value));
+ private static string? ResolveTemplateMatches(string body, BoundTemplateArguments bound, List<string> diagnostics, out IReadOnlyDictionary<string, string> selectedMatches)
+ {
+ // Enum parameters are resolved here so M3's downstream Match evaluator receives only the selected value.
+ var selected = new Dictionary<string, string>(StringComparer.Ordinal);
+ while (true)
+ {
+ var match = Regex.Match(body, @"\bMatch\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1));
+ if (!match.Success) { selectedMatches = selected; return body; }
+ var name = match.Groups["name"].Value;
+ if (!bound.ValueArguments.TryGetValue(name, out var selectedArm)) { selectedMatches = selected; return body; }
+ var open = match.Index + match.Value.LastIndexOf('{'); var close = Matching(body, open, '{', '}');
+ if (close < 0) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); selectedMatches = selected; return null; }
+ var arm = Regex.Match(body[(open + 1)..close], $@"(?m)^\s*{Regex.Escape(selectedArm)}\s*=>\s*", RegexOptions.CultureInvariant);
+ if (!arm.Success) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); selectedMatches = selected; return null; }
+ var armValueStart = open + 1 + arm.Index + arm.Length;
+ var value = StaticMatchArmValue(body, armValueStart, close);
+ if (value is null) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); selectedMatches = selected; return null; }
+ selected[name] = selectedArm;
+ body = body.Remove(match.Index, close - match.Index + 1).Insert(match.Index, value);
+ }
+ }
+
+ // A Match arm may be a scalar static expression or a balanced spatial initializer such as Grid { ... }.
+ // Preserve the whole selected initializer; truncating at its first brace would leak malformed source downstream.
+ private static string? StaticMatchArmValue(string body, int start, int enclosingClose)
+ {
+ while (start < enclosingClose && char.IsWhiteSpace(body[start])) start++;
+ if (start >= enclosingClose) return null;
+ var initializer = Regex.Match(body[start..enclosingClose], @"^[A-Za-z_][A-Za-z0-9_]*\s*\{", RegexOptions.CultureInvariant);
+ if (initializer.Success)
+ {
+ var open = start + initializer.Value.LastIndexOf('{');
+ var close = Matching(body, open, '{', '}');
+ return close < 0 || close > enclosingClose ? null : body[start..(close + 1)].Trim();
+ }
+ var end = body.IndexOfAny(['\r', '\n'], start);
+ if (end < 0 || end > enclosingClose) end = enclosingClose;
+ return body[start..end].Trim();
+ }
+ private static bool EvaluateRequires(string body, string instance, List<string> diagnostics)
+ {
+ foreach (Match require in Regex.Matches(body, @"\bRequire\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*=>\s*(?<expr>[^\r\n}]+)", RegexOptions.CultureInvariant))
+ {
+ if (!TryBool(require.Groups["expr"].Value.Trim(), out var value)) diagnostics.Add(RequireNonBool + ":" + require.Groups["name"].Value);
+ else if (!value) diagnostics.Add(RequireFailed + $":{instance}.{require.Groups["name"].Value}:{require.Groups["expr"].Value.Trim()}");
+ }
+ return !HasErrors(diagnostics);
+ }
+ private static bool TryBool(string expression, out bool result)
+ {
+ result = true;
+ foreach (var clause in expression.Split("&&", StringSplitOptions.TrimEntries))
+ {
+ var m = Regex.Match(clause, @"^(?<a>[-+]?[0-9]+(?:\.[0-9]+)?)(?<u>mm)?\s*(?<op>>=|<=|>|<|==)\s*(?<b>[-+]?[0-9]+(?:\.[0-9]+)?)(?<u2>mm)?$", RegexOptions.CultureInvariant);
+ if (!m.Success || m.Groups["u"].Value != m.Groups["u2"].Value) return false;
+ var a = double.Parse(m.Groups["a"].Value, CultureInfo.InvariantCulture); var b = double.Parse(m.Groups["b"].Value, CultureInfo.InvariantCulture);
+ result &= m.Groups["op"].Value switch { ">" => a > b, "<" => a < b, ">=" => a >= b, "<=" => a <= b, _ => a == b };
+ }
+ return true;
+ }
+ private static void DetectTemplateCycles(IEnumerable<TemplateDeclarationIr> templates, IReadOnlyDictionary<string, TemplateDeclarationIr> byName, List<string> diagnostics)
+ {
+ foreach (var template in templates)
+ {
+ var stack = new List<string>(); var seen = new HashSet<string>(StringComparer.Ordinal);
+ bool Visit(string name)
+ {
+ var at = stack.IndexOf(name); if (at >= 0) { diagnostics.Add(Recursive + ":" + string.Join(" -> ", stack.Skip(at).Append(name))); return true; }
+ if (!seen.Add(name)) return false; stack.Add(name);
+ foreach (Match call in Regex.Matches(byName[name].Body, @"=\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*<", RegexOptions.CultureInvariant)) if (byName.ContainsKey(call.Groups["name"].Value) && Visit(call.Groups["name"].Value)) return true;
+ stack.RemoveAt(stack.Count - 1); return false;
+ }
+ _ = Visit(template.Name);
+ }
+ }
+ private static string Identity(TemplateDeclarationIr template, TemplateApplicationIr application, BoundTemplateArguments args)
+ {
+ var input = template.Name + "|" + application.InstanceName + "|" + string.Join("|", args.TypeArguments.Concat(args.ValueArguments).OrderBy(x => x.Key).Select(x => x.Key + "=" + x.Value));
+ return "template:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(input))).ToLowerInvariant()[..16];
+ }
+ private static ImmutableArray<string> GeneratedPaths(string body, string instance) => Regex.Matches(body, @"\b(?:Concept\s+Struct|Box|Modify|EdgeFinish)\s+(?<n>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant).Select(m => instance + "::" + m.Groups["n"].Value).Distinct().ToImmutableArray();
+ private static string RemoveRequires(string body) => Regex.Replace(body, @"(?m)^\s*Require\s+[A-Za-z_][A-Za-z0-9_]*\s*=>\s*[^\r\n}]+\s*$", string.Empty);
+ private static bool HasErrors(IEnumerable<string> diagnostics) => diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal));
+ private static int Matching(string source, int open, char begin, char end) { var depth = 0; for (var i = open; i < source.Length; i++) { if (source[i] == begin) depth++; else if (source[i] == end && --depth == 0) return i; } return -1; }
+}
diff --git a/demos/concept-step-match-standard.firmament b/demos/concept-step-match-standard.firmament
new file mode 100644
index 00000000..6431792a
--- /dev/null
+++ b/demos/concept-step-match-standard.firmament
@@ -0,0 +1,50 @@
+Enum BracketVariant {
+ Compact
+ Standard
+}
+
+Template < Width: Length, Depth: Length, Height: Length, Variant: BracketVariant, HoleDiameter: Length = 8.5mm >
+Struct MountingBracket {
+ Concept Struct Design {
+ Bounds: Box3 {
+ Size: [Width, Depth, Height]
+ }
+ TopPlane: Bounds.Face(+Z)
+ MountPoints: Match Variant {
+ Compact => Grid {
+ Within: Bounds.Face(+Z).Inset(8mm)
+ Columns: 2
+ Rows: 1
+ }
+ Standard => Grid {
+ Within: Bounds.Face(+Z).Inset(10mm)
+ Columns: 2
+ Rows: 1
+ }
+ }
+ }
+ Box Base {
+ Bounds: Design.Bounds
+ }
+ Modify Base {
+ Pattern MountHoles {
+ Source: Design.MountPoints
+ Hole<Shaft> Item {
+ on: Base.Top
+ center: Item
+ diameter: HoleDiameter
+ end: ThroughAll
+ }
+ }
+ }
+}
+
+Struct StandardBracket = MountingBracket < Width: 80mm, Depth: 50mm, Height: 25mm, Variant: Standard >
+
+Match {
+ MountPoints As HoleCenters {
+ Diameter: 8.5mm
+ Axis: +Z
+ Kind: Through
+ }
+}
diff --git a/demos/template-m4b-compact.firmament b/demos/template-m4b-compact.firmament
new file mode 100644
index 00000000..0940b546
--- /dev/null
+++ b/demos/template-m4b-compact.firmament
@@ -0,0 +1,42 @@
+Enum BracketVariant {
+ Compact
+ Standard
+}
+
+Template < Width: Length, Depth: Length, Height: Length, Variant: BracketVariant, HoleDiameter: Length = 8.5mm >
+Struct MountingBracket {
+ Concept Struct Design {
+ Bounds: Box3 {
+ Size: [Width, Depth, Height]
+ }
+ TopPlane: Bounds.Face(+Z)
+ MountPoints: Match Variant {
+ Compact => Grid {
+ Within: Bounds.Face(+Z).Inset(8mm)
+ Columns: 2
+ Rows: 1
+ }
+ Standard => Grid {
+ Within: Bounds.Face(+Z).Inset(10mm)
+ Columns: 2
+ Rows: 1
+ }
+ }
+ }
+ Box Base {
+ Bounds: Design.Bounds
+ }
+ Modify Base {
+ Pattern MountHoles {
+ Source: Design.MountPoints
+ Hole<Shaft> Item {
+ on: Base.Top
+ center: Item
+ diameter: HoleDiameter
+ end: ThroughAll
+ }
+ }
+ }
+}
+
+Struct CompactBracket = MountingBracket < Width: 60mm, Depth: 40mm, Height: 20mm, Variant: Compact >
diff --git a/demos/template-m4b-standard.firmament b/demos/template-m4b-standard.firmament
new file mode 100644
index 00000000..c7a7518d
--- /dev/null
+++ b/demos/template-m4b-standard.firmament
@@ -0,0 +1,42 @@
+Enum BracketVariant {
+ Compact
+ Standard
+}
+
+Template < Width: Length, Depth: Length, Height: Length, Variant: BracketVariant, HoleDiameter: Length = 8.5mm >
+Struct MountingBracket {
+ Concept Struct Design {
+ Bounds: Box3 {
+ Size: [Width, Depth, Height]
+ }
+ TopPlane: Bounds.Face(+Z)
+ MountPoints: Match Variant {
+ Compact => Grid {
+ Within: Bounds.Face(+Z).Inset(8mm)
+ Columns: 2
+ Rows: 1
+ }
+ Standard => Grid {
+ Within: Bounds.Face(+Z).Inset(10mm)
+ Columns: 2
+ Rows: 1
+ }
+ }
+ }
+ Box Base {
+ Bounds: Design.Bounds
+ }
+ Modify Base {
+ Pattern MountHoles {
+ Source: Design.MountPoints
+ Hole<Shaft> Item {
+ on: Base.Top
+ center: Item
+ diameter: HoleDiameter
+ end: ThroughAll
+ }
+ }
+ }
+}
+
+Struct StandardBracket = MountingBracket < Width: 80mm, Depth: 50mm, Height: 25mm, Variant: Standard >
diff --git a/docs/air-firmament-m4-templates.md b/docs/air-firmament-m4-templates.md
new file mode 100644
index 00000000..ac054912
--- /dev/null
+++ b/docs/air-firmament-m4-templates.md
@@ -0,0 +1,54 @@
+# Firmament M4B compile-time Templates and Patterns
+
+`Template` is a typed, compile-time declaration generator. M4A parses immutable Template IR, binds named static arguments, specializes deterministically, and expands to ordinary `Concept Struct`, `Struct`, or `Model` declarations before Concept IR and Feature AIR are built. It is not a runtime generic, a Forge plugin invocation, a macro text substitution system, or a constraint solver.
+
+```firmament
+Template <
+ type TBody satisfies PrismaticBody,
+ Width: Length,
+ Depth: Length,
+ Height: Length,
+ Variant: BracketVariant = Standard
+>
+Struct MountingBracket: MountingFrame { ... }
+
+Struct CompactBracket = MountingBracket <
+ TBody: Box, Width: 60mm, Depth: 40mm, Height: 20mm, Variant: Compact
+>
+```
+
+The authoritative IR contains declarations, type/value parameters, constraint Concept names, default expressions, applications, bound arguments, source spans, specialization identities, generated declaration paths, and erasure provenance. Arguments are named, checked for duplicates/unknown names, type-checked, and defaults are recorded in source-map provenance. Enum parameters are checked against the same `Enum` declarations used by static `Match`; an enum-bound `Match` is selected during specialization and recorded as provenance.
+
+`satisfies` is structural capability conformance; it is neither inheritance nor dynamic dispatch. The first materialization descriptor recognizes `Box` as the explicit prismatic capability provider. Other supplied types must be a `Concept Struct` declared to satisfy the requested Concept. Unknown constraint Concepts, missing arguments, invalid defaults, and default dependency cycles are deterministic diagnostics.
+
+`Require Name => expression` is evaluated after binding. Its supported M4A form is a finite conjunction of numeric comparisons with matching units; it validates declared invariants and never searches for values. A non-boolean value or false assertion is a compile-time diagnostic. Recursive template application graphs and recursive specializations are rejected with a readable chain.
+
+Each application gets a deterministic specialization identity and readable generated paths such as `CompactBracket::Design` and `CompactBracket::Base`. `ConceptIrTemplateInstantiation` is provenance only: it contains source spans, bindings, defaults, generated paths, and `ExpandedBeforeFeatureAir`. The expanded source alone reaches Concept IR, then Feature AIR. No executable Template, Pattern, Match, or Require node is retained in Feature AIR.
+
+M4A deliberately does not provide partial specialization, overload ranking, recursion, variadics, reflection, C# execution, or general scripting. Forge descriptors continue to describe external validation/DFM/PMI metadata; expanding a language Template never executes an assembly.
+
+## M4B: bounded Pattern expansion
+
+M4B completes the finite, typed generation half of the milestone. A `Pattern` lives in a specialized materialized declaration and consumes a statically resolved `Point3[]` Concept Struct member:
+
+```firmament
+Pattern MountHoles {
+ Source: Design.MountPoints
+ Hole<Shaft> Item {
+ On: Base.Top
+ Center: Item
+ Diameter: HoleDiameter
+ End: ThroughAll
+ }
+}
+```
+
+`Source` must resolve to a compile-time `Point3[]`; consequently `Item` is exactly `Point3`. The source is ordered, finite, and bounded to 1024 generated declarations. An empty source is valid and expands to zero declarations. Incompatible sources, missing `Center: Item`, unbound items, malformed feature templates, expansion-limit violations, and generated-name collisions are deterministic diagnostics.
+
+Expansion happens after template argument/default binding, `Require`, static `Match`, and Concept Struct spatial evaluation. It produces ordinary semantic hole declarations, one per source element, such as `CompactBracket::MountHoles[0]`. Their readable paths are backed by deterministic specialization, pattern path, point ordinal, and point stable-ID provenance. No runtime loop exists.
+
+The ordinary M2 semantic-hole route then receives each concrete `Point3`: Concept IR point value → resolved point placement → face-local placement → `AirHoleFeature`/composite materializer → BRep → AP242 STEP. Pattern, Template, Match, Require, and the item binding are source-map/report provenance only by Feature AIR time. `patternExpansions` in the existing build JSON records its count and generated paths.
+
+The persisted end-to-end proofs are [template-m4b-compact.firmament](../demos/template-m4b-compact.firmament) and [template-m4b-standard.firmament](../demos/template-m4b-standard.firmament). They use the same `MountingBracket` shape (duplicated only because Firmament source imports are not yet a language feature), specialize distinct dimensions/enum arms, expand two through holes, and reimport as enclosed manifold bodies with two cylindrical surfaces.
+
+M4 deliberately still excludes general `for`/`foreach`, mutation, recursive Templates/Patterns, partial specialization, variadics, overload ranking, reflection, runtime generics, arbitrary feature collection combinators, automatic hole/chamfer composition, and constraint solving. The next useful expansion is Concept-to-STEP matching evidence over generated semantic references, not general metaprogramming.
diff --git a/docs/concept-step-matching.md b/docs/concept-step-matching.md
new file mode 100644
index 00000000..e4cf8be7
--- /dev/null
+++ b/docs/concept-step-matching.md
@@ -0,0 +1,29 @@
+# Concept-to-STEP matching (M5)
+
+`aetheris match part.step concept.firmament --json` compares resolved compile-time Concept IR with bounded analytic evidence imported from STEP/AP242. It is read-only.
+
+> Aetheris does not reconstruct the original feature tree.
+>
+> It tests whether a declared semantic Concept Struct explains or conforms to the observed STEP artifact.
+
+The M5 matcher supports `Box3` body bounds, `Plane` analytic planar faces, `Axis` analytic cylindrical axes, and `Point3[]` declared as hole centers. A bare `Point3` is deliberately `Unverifiable`; vertices are not semantic evidence by default.
+
+Declare the semantic role separately from the value:
+
+```firmament
+Match {
+ MountPoints As HoleCenters {
+ Diameter: 8.5mm
+ Axis: +Z
+ Kind: Through
+ }
+}
+```
+
+The role is compile-time conformance metadata and never lowers to AIR/BRep. The engine uses deterministic nearest unused-candidate assignment for small point sets. Hole evidence comes from analytic cylindrical faces, with center, axis, radius, span, and a bounded through classification; it is `DerivedAnalytic`. Planes and cylinder axes are `ExactAnalytic`; body bounds are `TopologySupported` vertex evidence.
+
+Defaults are conservative: 0.01 mm linear/dimension and 0.1 degree angular tolerance. Override linear and angular tolerances with `--linear-tolerance` and `--angular-tolerance`. Every member result includes its measured deviation and allowed tolerance.
+
+Member statuses are `Matched`, `WithinTolerance`, `Candidate`, `Ambiguous`, `Conflicted`, `Missing`, `Unverifiable`, or `Unsupported`. Equivalent coplanar planar faces remain `Ambiguous`; the matcher never chooses one silently. Overall `Matched` means every requested contract matches, `Partial` means useful evidence exists without direct contradiction, and `Conflicted` means an expected required observation is contradicted. `Matched` and `Partial` exit 0; conflicts and invalid source/STEP exit 1.
+
+STEP face IDs may occur in diagnostic report evidence, but are not part of Firmament syntax or the language contract. This bounded evidence workflow supports partial semantic refactoring: a concept may specify only bounds and a plane, rather than reconstructing all historical features. It does not support freeform/tessellated proof, generic point roles, feature-tree reconstruction, or automatic rewriting.