Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add Firmament feature expansion and inspection metadata

Yuechen Lic857ddb5fc46
diff --git a/Aetheris.CLI.Tests/FeatureFunctionCliTests.cs b/Aetheris.CLI.Tests/FeatureFunctionCliTests.cs
new file mode 100644
index 00000000..a628549c
--- /dev/null
+++ b/Aetheris.CLI.Tests/FeatureFunctionCliTests.cs
@@ -0,0 +1,43 @@
+using System.Text.Json;
+using Aetheris.CLI;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class FeatureFunctionCliTests
+{
+ [Fact]
+ public void Inspect_ReportsFeatureDefinitionsInvocationsExpansionAndSemanticKind()
+ {
+ var output = new StringWriter(); var error = new StringWriter();
+ var exit = CliRunner.Run(["inspect", Fixture("Canonical/Feature/feature-with-derived-values.firmament"), "--json"], output, error);
+
+ Assert.Equal(0, exit);
+ Assert.Equal(string.Empty, error.ToString());
+ using var json = JsonDocument.Parse(output.ToString());
+ var root = json.RootElement;
+ Assert.Equal("M8Counterbore", root.GetProperty("featureDefinitions")[0].GetProperty("name").GetString());
+ Assert.Equal("M8Counterbore", root.GetProperty("featureInvocations")[0].GetProperty("generatedByFeature").GetString());
+ Assert.Equal("Hole<Counterbore>", root.GetProperty("featureInvocations")[0].GetProperty("expandedSemanticKind").GetString());
+ Assert.Equal(1, root.GetProperty("featureExpansion").GetProperty("definitionCount").GetInt32());
+ Assert.Equal(1, root.GetProperty("featureExpansion").GetProperty("invocationCount").GetInt32());
+ Assert.Equal("Hole<Counterbore> M8Counterbore__0", root.GetProperty("features")[0].GetString());
+ }
+
+ [Fact]
+ public void Validate_ReturnsFailureAndFatalTypedFeatureDiagnostic()
+ {
+ var output = new StringWriter(); var error = new StringWriter();
+ var exit = CliRunner.Run(["validate", Fixture("Invalid/Feature/wrong-argument-type.firmament"), "--json"], output, error);
+
+ Assert.Equal(1, exit);
+ using var json = JsonDocument.Parse(output.ToString());
+ var report = json.RootElement.GetProperty("firmamentV2Validation");
+ Assert.Equal("invalid", report.GetProperty("status").GetString());
+ Assert.Contains(report.GetProperty("diagnostics").EnumerateArray(), diagnostic =>
+ diagnostic.GetProperty("severity").GetString() == "fatal"
+ && diagnostic.GetProperty("code").GetString()!.StartsWith("firmament-feature-argument-type:MountHole:Center", StringComparison.Ordinal));
+ }
+
+ private static string Fixture(string relative) => Path.GetFullPath(Path.Combine(
+ AppContext.BaseDirectory, "../../../../fixtures", relative.Replace('/', Path.DirectorySeparatorChar)));
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index f560b289..086f9eaa 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -1495,6 +1495,25 @@ Model CanonicalPanel {
members = pair.Value.Members.OrderBy(member => member.Key, StringComparer.Ordinal).ToDictionary(member => member.Key, member => member.Value, StringComparer.Ordinal)
}, StringComparer.Ordinal)
}).ToArray() ?? [],
+ featureDefinitions = document?.FeatureDefinitions?.Select(definition => new
+ {
+ definition.Name,
+ parameters = definition.Parameters,
+ definition.ReturnType,
+ definition.Scope,
+ definition.Evaluation
+ }).ToArray() ?? [],
+ featureInvocations = document?.FeatureInvocations?.Select(invocation => new
+ {
+ invocation.Feature,
+ invocation.Ordinal,
+ invocation.Arguments,
+ invocation.ReturnType,
+ invocation.ExpandedSemanticKind,
+ invocation.GeneratedByFeature,
+ invocation.Status
+ }).ToArray() ?? [],
+ featureExpansion = document?.FeatureExpansion,
conceptPaths = ProfileAuthoringParser.InspectConceptPaths(inspectionSource),
semanticValues = semanticValues.OrderBy(value => value.StableIdentity, StringComparer.Ordinal).Select(SemanticValueDescriptor.From).ToArray(),
recognizedRegions = document?.RecognizedRegions?.Select(region => new
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2FeatureFunctionTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2FeatureFunctionTests.cs
new file mode 100644
index 00000000..ec0d1f59
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2FeatureFunctionTests.cs
@@ -0,0 +1,240 @@
+using Aetheris.Kernel.Core.Brep.Verification;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentV2FeatureFunctionTests
+{
+ [Fact]
+ public void CounterboreFeature_BindsNamedArgumentsDerivesValueAndPreservesProvenance()
+ {
+ var expansionDiagnostics = new List<string>();
+ var expansion = FirmamentV2FeatureExpansion.Expand(CounterboreSource, expansionDiagnostics);
+ var parse = FirmamentV2Parser.Parse(CounterboreSource);
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics) + Environment.NewLine + expansion?.Source);
+ var definition = Assert.Single(parse.Document!.FeatureDefinitions!);
+ Assert.Equal("M8Counterbore", definition.Name);
+ Assert.Equal("Hole<Counterbore>", definition.ReturnType);
+ Assert.Equal("PureTerminalReturn", definition.Evaluation);
+ var invocation = Assert.Single(parse.Document.FeatureInvocations!);
+ Assert.Equal("M8Counterbore", invocation.GeneratedByFeature);
+ Assert.Equal("Point2(0mm, 0mm)", invocation.Arguments["Center"]);
+ Assert.Equal(new FirmamentV2FeatureExpansionMetrics(1, 1, 1, "BoundedSourceOrder"), parse.Document.FeatureExpansion);
+ var hole = Assert.Single(parse.Document.ModifyBlocks!.Single().SemanticHoles);
+ Assert.Equal(FirmamentV2SemanticHoleVariant.Counterbore, hole.Variant);
+ Assert.Equal(14d, hole.CounterboreDiameter);
+ Assert.Equal(4d, hole.CounterboreDepth);
+ }
+
+ [Fact]
+ public void Feature_ComposesWithBoundedPatternWithoutAddingLoopSyntax()
+ {
+ var parse = FirmamentV2Parser.Parse("""
+ Feature MountHole(Center: Point3, Diameter: Length = 6mm) -> Hole<Shaft> {
+ return Hole<Shaft> {
+ On: Base.Top
+ Center: Center
+ Diameter: Diameter
+ End: ThroughAll
+ }
+ }
+ Concept Struct Design {
+ Bounds: Box3 {
+ Size: [60mm, 40mm, 10mm]
+ }
+ Points: Grid {
+ Within: Bounds.Face(+Z).Inset(8mm)
+ Columns: 2
+ Rows: 2
+ }
+ }
+ Struct Product {
+ Box Base { Bounds: Design.Bounds }
+ Modify Base {
+ Pattern Mounts {
+ Source: Design.Points
+ MountHole(Center: Item, Diameter: 6mm)
+ }
+ }
+ }
+ """);
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ Assert.Equal(4, parse.Document!.ModifyBlocks!.Single().SemanticHoles.Count);
+ Assert.Equal(4, Assert.Single(parse.Document.ConceptIr!.PatternExpansions!).Count);
+ Assert.Single(parse.Document.FeatureInvocations!);
+ }
+
+ [Fact]
+ public void NestedFeatureCall_IsFiniteAndTyped()
+ {
+ var source = CounterboreSource.Replace(
+ "Feature M8Counterbore(Center: Point2, CounterboreDepth: Length = 4mm) -> Hole<Counterbore> {",
+ "Feature CoreCounterbore(Center: Point2, CounterboreDepth: Length) -> Hole<Counterbore> {", StringComparison.Ordinal)
+ .Replace("M8Counterbore(Center: Point2(0mm, 0mm))",
+ "CoreCounterbore(Center: Point2(0mm, 0mm), CounterboreDepth: 4mm)", StringComparison.Ordinal);
+ source = source.Replace("Model FeatureCounterbore {", "Model FeatureCounterbore {\nFeature M8Counterbore(Center: Point2) -> Hole<Counterbore> { return CoreCounterbore(Center: Center, CounterboreDepth: 4mm) }", StringComparison.Ordinal)
+ .Replace("CoreCounterbore(Center: Point2(0mm, 0mm), CounterboreDepth: 4mm)", "M8Counterbore(Center: Point2(0mm, 0mm))", StringComparison.Ordinal);
+
+ var parse = FirmamentV2Parser.Parse(source);
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ Assert.Equal(2, parse.Document!.FeatureDefinitions!.Count);
+ Assert.Equal(["CoreCounterbore", "M8Counterbore"], parse.Document.FeatureInvocations!.Select(item => item.Feature).Order().ToArray());
+ }
+
+ [Theory]
+ [InlineData("return Hole<Shaft> { On: +Z Center: Center Diameter: 6mm End: ThroughAll }", "firmament-feature-return-type:Broken")]
+ [InlineData("let x: Length = 1mm", "firmament-feature-missing-return:Broken")]
+ [InlineData("if true return Hole<Counterbore> { }", "firmament-feature-control-flow-unsupported:if")]
+ [InlineData("for Item return Hole<Counterbore> { }", "firmament-feature-control-flow-unsupported:for")]
+ public void Feature_RejectsWrongReturnMissingReturnAndGeneralControlFlow(string body, string diagnostic)
+ {
+ var parse = FirmamentV2Parser.Parse($$"""
+ Model InvalidFeature {
+ Units: mm
+ Feature Broken(Center: Point2) -> Hole<Counterbore> { {{body}} }
+ Box Base { Size: [20mm, 20mm, 5mm] }
+ Modify Base { Broken([0mm, 0mm]) }
+ }
+ """);
+
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(parse.Diagnostics, item => item.StartsWith(diagnostic, StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void Feature_RejectsDirectAndIndirectRecursion()
+ {
+ var direct = FirmamentV2Parser.Parse("Feature A() -> Hole<Shaft> { return A() }");
+ Assert.Contains(direct.Diagnostics, item => item == "firmament-feature-recursion:A:A");
+ var indirect = FirmamentV2Parser.Parse("Feature A() -> Hole<Shaft> { return B() } Feature B() -> Hole<Shaft> { return A() }");
+ Assert.Contains(indirect.Diagnostics, item => item.StartsWith("firmament-feature-recursion:A:B:A", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void FeatureBuild_ExportsAndReimportsEnclosedGeometry()
+ {
+ var build = FirmamentBuildAndExport.CompileSource("schema Mechanical\n" + CounterboreSource);
+ Assert.True(build.IsSuccess, string.Join(Environment.NewLine, build.Diagnostics.Select(item => item.Message)));
+ var imported = Step242Importer.ImportBody(build.Value!.StepText);
+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(item => item.Message)));
+ Assert.True(BrepMassProperties.Evaluate(imported.Value!).IsEnclosed);
+ }
+
+ [Fact]
+ public void FeatureExpansion_HasExactGeometryAndStepParityWithTheConcreteProgram()
+ {
+ var feature = FirmamentBuildAndExport.CompileSource("schema Mechanical\n" + CounterboreSource);
+ var concrete = FirmamentBuildAndExport.CompileSource("""
+ schema Mechanical
+ Model FeatureCounterbore {
+ Units: mm
+ Box Plate { Size: [30mm, 20mm, 8mm] }
+ Modify Plate {
+ Hole<Counterbore> M8Counterbore__0 {
+ On: +Z
+ Center: Point2(0mm, 0mm)
+ Diameter: 8.5mm
+ CounterboreDiameter: 14mm
+ CounterboreDepth: 4mm
+ End: ThroughAll
+ }
+ }
+ }
+ """);
+
+ Assert.True(feature.IsSuccess);
+ Assert.True(concrete.IsSuccess);
+ Assert.Equal(concrete.Value!.StepText, feature.Value!.StepText);
+ var concreteFeatures = Assert.IsAssignableFrom<IReadOnlyList<FirmamentHoleFeatureReport>>(concrete.Value.Features);
+ var expandedFeatures = Assert.IsAssignableFrom<IReadOnlyList<FirmamentHoleFeatureReport>>(feature.Value.Features);
+ Assert.Equal(concreteFeatures.Single().Kind, expandedFeatures.Single().Kind);
+ Assert.Equal(concreteFeatures.Single().Diameter, expandedFeatures.Single().Diameter);
+ }
+
+ [Theory]
+ [InlineData("wrong-argument-type.firmament", "firmament-feature-argument-type")]
+ [InlineData("missing-argument.firmament", "firmament-feature-argument-count")]
+ [InlineData("extra-argument.firmament", "firmament-feature-argument-count")]
+ [InlineData("missing-return.firmament", "firmament-feature-missing-return")]
+ [InlineData("wrong-return-type.firmament", "firmament-feature-return-type")]
+ [InlineData("direct-recursion.firmament", "firmament-feature-recursion")]
+ [InlineData("indirect-recursion.firmament", "firmament-feature-recursion")]
+ [InlineData("unsupported-conditional.firmament", "firmament-feature-control-flow-unsupported")]
+ [InlineData("unsupported-loop.firmament", "firmament-feature-control-flow-unsupported")]
+ public void InvalidFeatureFixtures_ProduceSpecificTypedDiagnostics(string file, string diagnostic)
+ {
+ var source = File.ReadAllText(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,
+ "../../../../fixtures/Invalid/Feature", file)));
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(parse.Diagnostics, item => item.StartsWith(diagnostic, StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("WireForm")]
+ [InlineData("Sweep")]
+ [InlineData("SectionChain")]
+ public void Feature_X1IsExplicitlyMechanicalOnly(string schema)
+ {
+ var selection = FirmamentFrontendSchemas.Select($"schema {schema}\nFeature A() -> Hole<Shaft> {{ return Hole<Shaft> {{ }} }}");
+ Assert.False(selection.IsSuccess);
+ Assert.Equal($"firmament-feature-schema-unsupported:{schema}", Assert.Single(selection.Diagnostics));
+ }
+
+ [Fact]
+ public void Feature_CoexistsWithTemplateAndAProfileOfTheSameName()
+ {
+ var path = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,
+ "../../../../fixtures/Canonical/Feature/boss-pocket-feature.firmament"));
+ var source = File.ReadAllText(path)
+ .Replace("Feature RaisedPad", "Feature PadProfile", StringComparison.Ordinal)
+ .Replace("RaisedPad(Shape:", "PadProfile(Shape:", StringComparison.Ordinal)
+ .Replace(" Concept Struct Layout On XY", " Record LegacySpec { Center: Point2 }\n Template<spec: LegacySpec> LegacyMount { Hole<Shaft> Item { On: +Z Center: spec.Center Diameter: 4mm End: ThroughAll } }\n Concept Struct Layout On XY", StringComparison.Ordinal);
+ var selection = FirmamentFrontendSchemas.Select(source);
+
+ Assert.True(selection.IsSuccess);
+ var parse = FirmamentV2Parser.Parse(selection.Source);
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ Assert.Contains(parse.Document!.FeatureDefinitions!, item => item.Name == "PadProfile");
+ Assert.Contains(parse.Document.Profiles!, item => item.Name == "PadProfile");
+ Assert.Contains(parse.Document.StaticAuthoring!.Templates, item => item.Name == "LegacyMount");
+ }
+
+ [Fact]
+ public void Feature_ReportsUnknownCallsAndUnsupportedBodyTransformReturns()
+ {
+ var unknown = FirmamentV2Parser.Parse("""
+ Feature Known() -> Hole<Shaft> { return Hole<Shaft> { } }
+ Model UnknownCall { Units: mm Box Base { Size: [10mm, 10mm, 2mm] } Modify Base {
+ Missing()
+ } }
+ """);
+ Assert.Contains(unknown.Diagnostics, item => item == "firmament-feature-unknown:Missing");
+
+ var bodyTransform = FirmamentV2Parser.Parse("Feature Transform(Input: Body) -> Body { return Input }");
+ Assert.Contains(bodyTransform.Diagnostics, item => item == "firmament-feature-return-type:Transform:unsupported-Body");
+ }
+
+ private const string CounterboreSource = """
+ Model FeatureCounterbore {
+ Units: mm
+ Feature M8Counterbore(Center: Point2, CounterboreDepth: Length = 4mm) -> Hole<Counterbore> {
+ let CounterboreDiameter: Length = 8.5mm + 5.5mm
+ return Hole<Counterbore> {
+ On: +Z
+ Center: Center
+ Diameter: 8.5mm
+ CounterboreDiameter: CounterboreDiameter
+ CounterboreDepth: CounterboreDepth
+ End: ThroughAll
+ }
+ }
+ Box Plate { Size: [30mm, 20mm, 8mm] }
+ Modify Plate { M8Counterbore(Center: Point2(0mm, 0mm)) }
+ }
+ """;
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 8731ba89..939e0658 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -280,8 +280,14 @@ public static class FirmamentBuildAndExport
// parser admission alone is insufficient because the profile/composition
// materializers read source declarations directly.
var staticDiagnostics = new List<string>();
+ var featureExpansion = FirmamentV2FeatureExpansion.Expand(sourceText, staticDiagnostics);
+ if (featureExpansion is null)
+ {
+ return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
+ Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.FeatureExpansion")).ToArray());
+ }
var templateBindWatch = System.Diagnostics.Stopwatch.StartNew();
- var templateExpansion = FirmamentV2TemplateExpansion.Expand(sourceText, staticDiagnostics);
+ var templateExpansion = FirmamentV2TemplateExpansion.Expand(featureExpansion.Source, staticDiagnostics);
templateBindWatch.Stop();
if (templateExpansion is null)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs b/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs
index 8033b3bc..a1cdab57 100644
--- a/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs
@@ -33,6 +33,9 @@ public static class FirmamentFrontendSchemas
if (!Enum.TryParse<FirmamentFrontendSchema>(name, false, out var schema))
return new(null, source, [$"firmament-schema-unknown:{name}:available={string.Join(',', Names)}"]);
var normalized = source.Remove(declaration.Index, declaration.Length);
+ if (schema != FirmamentFrontendSchema.Mechanical
+ && Regex.IsMatch(normalized, @"\bFeature\s+[A-Za-z_]\w*\s*\(", RegexOptions.CultureInvariant))
+ return new(schema, normalized, [$"firmament-feature-schema-unsupported:{schema}"]);
var detected = DetectDistinctFrontend(normalized);
if (detected is not null && detected != schema)
return new(schema, normalized, [$"firmament-schema-mismatch:declared={schema}:source={detected}"]);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index cd5af1c5..673d8e01 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)
+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 FirmamentV2SolidBinding Solid => Solids[^1];
public FirmamentV2SideHoleIntent? SideHoleIntent => ModifyBlocks?.SelectMany(m => m.Regions.Select(r =>
@@ -103,6 +103,18 @@ public sealed record ImportedStepTopologyMap(IReadOnlyDictionary<string, string>
return false;
}
}
+
+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);
+public sealed record FirmamentV2FeatureInvocation(string Feature, int Ordinal, string ReturnType,
+ IReadOnlyDictionary<string, string> Arguments, FirmamentV2SourceSpan SourceSpan,
+ string ExpandedSemanticKind, string Status)
+{
+ public string GeneratedByFeature => Feature;
+}
+public sealed record FirmamentV2FeatureExpansionMetrics(int DefinitionCount, int InvocationCount,
+ int ExpandedSemanticNodeCount, string ExpansionOrder);
public sealed record FirmamentV2RecognizedRegion(string BodyName, string RegionName, string Kind, IReadOnlyList<string> FaceRefs, string Confidence, FirmamentV2RecognitionEvidence? Evidence = null, FirmamentV2SemanticProposal? Proposal = null)
{
public string TargetSource => $"{BodyName}.region(\"{RegionName}\")";
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs
new file mode 100644
index 00000000..1e54e3cb
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs
@@ -0,0 +1,408 @@
+using System.Collections.Immutable;
+using System.Globalization;
+using System.Text.RegularExpressions;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>
+/// Bounded, pure expansion for Firmament's function-like Feature declarations.
+/// Feature bodies are deliberately expression-only: immutable local derivations and one
+/// terminal return. Expansion produces ordinary semantic declarations before Feature AIR.
+/// </summary>
+internal static class FirmamentV2FeatureExpansion
+{
+ internal const string Prefix = "firmament-feature-";
+ internal const string DuplicateName = Prefix + "duplicate-name";
+ internal const string Unknown = Prefix + "unknown";
+ internal const string DuplicateParameter = Prefix + "duplicate-parameter";
+ internal const string InvalidParameter = Prefix + "invalid-parameter";
+ internal const string ArgumentCount = Prefix + "argument-count";
+ internal const string UnknownArgument = Prefix + "unknown-argument";
+ internal const string DuplicateArgument = Prefix + "duplicate-argument";
+ internal const string ArgumentType = Prefix + "argument-type";
+ internal const string MissingReturn = Prefix + "missing-return";
+ internal const string MultipleReturns = Prefix + "multiple-returns";
+ internal const string ReturnType = Prefix + "return-type";
+ internal const string ControlFlowUnsupported = Prefix + "control-flow-unsupported";
+ internal const string Recursion = Prefix + "recursion";
+ internal const string LocalType = Prefix + "local-type";
+ internal const string LocalDuplicate = Prefix + "local-duplicate";
+ internal const string UnsupportedBody = Prefix + "body-unsupported";
+
+ private sealed record Parameter(string Name, string Type, string? DefaultExpression, FirmamentV2SourceSpan Span);
+ private sealed record Declaration(string Name, ImmutableArray<Parameter> Parameters, string ReturnTypeName,
+ string ReturnExpression, ImmutableArray<Local> Locals, FirmamentV2SourceSpan Span);
+ private sealed record Local(string Name, string Type, string Expression);
+
+ internal sealed record Result(
+ string Source,
+ IReadOnlyList<FirmamentV2FeatureDefinition> Definitions,
+ IReadOnlyList<FirmamentV2FeatureInvocation> Invocations,
+ FirmamentV2FeatureExpansionMetrics Metrics);
+
+ public static Result? Expand(string source, List<string> diagnostics)
+ {
+ var declarations = ParseDeclarations(source, diagnostics);
+ var byName = declarations.ToDictionary(item => item.Name, StringComparer.Ordinal);
+ DetectCycles(declarations, byName, diagnostics);
+ if (declarations.Length > 0)
+ {
+ foreach (Match possibleCall in Regex.Matches(source, @"(?m)^\s*(?<name>[A-Za-z_]\w*)\s*\(", RegexOptions.CultureInvariant))
+ {
+ if (declarations.Any(item => possibleCall.Index >= item.Span.Start && possibleCall.Index < item.Span.Start + item.Span.Length)) continue;
+ var name = possibleCall.Groups["name"].Value;
+ if (!byName.ContainsKey(name)) diagnostics.Add(Unknown + ":" + name);
+ }
+ }
+ if (HasErrors(diagnostics)) return null;
+
+ var invocations = new List<FirmamentV2FeatureInvocation>();
+ var ordinal = 0;
+ string ExpandCall(Declaration declaration, string argumentText, FirmamentV2SourceSpan span,
+ IReadOnlyList<string> stack, bool patternContext)
+ {
+ var bound = Bind(declaration, argumentText, span.Start, diagnostics);
+ if (bound is null) return string.Empty;
+ var invocationOrdinal = ordinal++;
+ var environment = new Dictionary<string, string>(bound, StringComparer.Ordinal);
+ foreach (var local in declaration.Locals)
+ {
+ if (environment.ContainsKey(local.Name))
+ {
+ diagnostics.Add(LocalDuplicate + $":{declaration.Name}:{local.Name}");
+ return string.Empty;
+ }
+ var expression = Substitute(local.Expression, environment);
+ if (!TypeMatches(expression, local.Type))
+ {
+ diagnostics.Add(LocalType + $":{declaration.Name}:{local.Name}:expected-{local.Type}:actual-{DescribeType(expression)}");
+ return string.Empty;
+ }
+ environment[local.Name] = NormalizeExpression(expression, local.Type);
+ }
+
+ var returned = Substitute(declaration.ReturnExpression, environment).Trim();
+ var nested = Regex.Match(returned, @"^(?<name>[A-Za-z_]\w*)\s*\((?<args>[\s\S]*)\)$", RegexOptions.CultureInvariant);
+ string expanded;
+ string expandedKind;
+ if (nested.Success && byName.TryGetValue(nested.Groups["name"].Value, out var nestedDeclaration))
+ {
+ if (stack.Contains(nestedDeclaration.Name, StringComparer.Ordinal))
+ {
+ diagnostics.Add(Recursion + ":" + string.Join(":", stack.Append(nestedDeclaration.Name)));
+ return string.Empty;
+ }
+ if (!SameType(declaration.ReturnTypeName, nestedDeclaration.ReturnTypeName))
+ {
+ diagnostics.Add(ReturnType + $":{declaration.Name}:expected-{declaration.ReturnTypeName}:actual-{nestedDeclaration.ReturnTypeName}");
+ return string.Empty;
+ }
+ expanded = ExpandCall(nestedDeclaration, nested.Groups["args"].Value, span,
+ stack.Append(nestedDeclaration.Name).ToArray(), patternContext);
+ expandedKind = nestedDeclaration.ReturnTypeName;
+ }
+ else
+ {
+ var constructor = Regex.Match(returned,
+ @"^(?<kind>Hole\s*<\s*(?:Shaft|Counterbore|Countersink)\s*>|Boss|Pocket|EdgeFinish)\s*\{",
+ RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+ if (!constructor.Success)
+ {
+ diagnostics.Add(UnsupportedBody + ":" + declaration.Name);
+ return string.Empty;
+ }
+ var constructorOpen = returned.IndexOf('{', constructor.Index);
+ var constructorClose = Matching(returned, constructorOpen, '{', '}');
+ if (constructorClose < 0 || !string.IsNullOrWhiteSpace(returned[(constructorClose + 1)..]))
+ {
+ diagnostics.Add(UnsupportedBody + ":" + declaration.Name + ":return-must-be-terminal");
+ return string.Empty;
+ }
+ expandedKind = Regex.Replace(constructor.Groups["kind"].Value, @"\s+", string.Empty, RegexOptions.CultureInvariant);
+ if (!SameType(declaration.ReturnTypeName, expandedKind))
+ {
+ diagnostics.Add(ReturnType + $":{declaration.Name}:expected-{declaration.ReturnTypeName}:actual-{expandedKind}");
+ return string.Empty;
+ }
+ var generatedName = patternContext
+ ? PatternItemName(returned, declaration.Name, invocationOrdinal)
+ : declaration.Name + "__" + invocationOrdinal.ToString(CultureInfo.InvariantCulture);
+ expanded = returned.Insert(constructor.Index + constructor.Length - 1, " " + generatedName + " ");
+ }
+
+ invocations.Add(new(declaration.Name, invocationOrdinal, declaration.ReturnTypeName,
+ bound, span, expandedKind, "ExpandedBeforeFeatureAir"));
+ return expanded;
+ }
+
+ var changes = declarations.Select(item => (item.Span.Start, item.Span.Length, Text: string.Empty)).ToList();
+ var callSites = declarations.SelectMany(declaration =>
+ {
+ var callRegex = new Regex($@"\b{Regex.Escape(declaration.Name)}\s*\(", RegexOptions.CultureInvariant);
+ return callRegex.Matches(source).Cast<Match>()
+ .Where(call => !declarations.Any(item => call.Index >= item.Span.Start && call.Index < item.Span.Start + item.Span.Length))
+ .Select(call => (Declaration: declaration, Call: call));
+ }).OrderBy(item => item.Call.Index).ToArray();
+ foreach (var site in callSites)
+ {
+ var open = source.IndexOf('(', site.Call.Index); var close = Matching(source, open, '(', ')');
+ if (close < 0) { diagnostics.Add(ArgumentCount + ":" + site.Declaration.Name); continue; }
+ var span = new FirmamentV2SourceSpan(site.Call.Index, close - site.Call.Index + 1);
+ var patternContext = IsInsideBlock(source, site.Call.Index, "Pattern");
+ var expansion = ExpandCall(site.Declaration, source[(open + 1)..close], span, [site.Declaration.Name], patternContext);
+ if (expansion.Length > 0) changes.Add((span.Start, span.Length, expansion));
+ }
+ if (HasErrors(diagnostics)) return null;
+ foreach (var change in changes.OrderByDescending(item => item.Start))
+ source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
+
+ var definitions = declarations.Select(item => new FirmamentV2FeatureDefinition(item.Name,
+ item.Parameters.Select(parameter => new FirmamentV2FeatureParameter(parameter.Name, parameter.Type, parameter.DefaultExpression)).ToArray(),
+ item.ReturnTypeName, item.Span, "FileLocal", "PureTerminalReturn")).ToArray();
+ var orderedInvocations = invocations.OrderBy(item => item.Ordinal).ToArray();
+ return new(source, definitions, orderedInvocations,
+ new(definitions.Length, invocations.Count, invocations.Count, "BoundedSourceOrder"));
+ }
+
+ private static ImmutableArray<Declaration> ParseDeclarations(string source, List<string> diagnostics)
+ {
+ var result = ImmutableArray.CreateBuilder<Declaration>();
+ var names = new HashSet<string>(StringComparer.Ordinal);
+ foreach (Match header in Regex.Matches(source,
+ @"\bFeature\s+(?<name>[A-Za-z_]\w*)\s*\([^()]*\)\s*->\s*(?<return>[A-Za-z_]\w*(?:\s*<\s*[A-Za-z_]\w*\s*>)?)\s*\{",
+ RegexOptions.CultureInvariant))
+ {
+ var returnType = NormalizeType(header.Groups["return"].Value);
+ if (!Regex.IsMatch(returnType, @"^(?:Hole<(?:Shaft|Counterbore|Countersink)>|Boss|Pocket|EdgeFinish)$", RegexOptions.CultureInvariant))
+ diagnostics.Add(ReturnType + $":{header.Groups["name"].Value}:unsupported-{returnType}");
+ }
+ foreach (Match header in Regex.Matches(source,
+ @"\bFeature\s+(?<name>[A-Za-z_]\w*)\s*\((?<parameters>[^()]*)\)\s*->\s*(?<return>Hole\s*<\s*[A-Za-z_]\w*\s*>|Boss|Pocket|EdgeFinish)\s*\{",
+ RegexOptions.CultureInvariant))
+ {
+ var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}');
+ var name = header.Groups["name"].Value;
+ if (close < 0) { diagnostics.Add(MissingReturn + ":" + name); continue; }
+ if (!names.Add(name)) { diagnostics.Add(DuplicateName + ":" + name); continue; }
+ var parameters = ParseParameters(header.Groups["parameters"].Value, header.Groups["parameters"].Index, name, diagnostics);
+ var body = source[(open + 1)..close];
+ foreach (Match keyword in Regex.Matches(body, @"\b(if|else|while|for|foreach|switch|match|goto|throw|try|catch|var)\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
+ diagnostics.Add(ControlFlowUnsupported + ":" + keyword.Value.ToLowerInvariant());
+ var returns = Regex.Matches(body, @"\breturn\b", RegexOptions.CultureInvariant);
+ if (returns.Count == 0) { diagnostics.Add(MissingReturn + ":" + name); continue; }
+ if (returns.Count != 1) { diagnostics.Add(MultipleReturns + ":" + name); continue; }
+ var returnMatch = returns[0];
+ var returnExpression = body[(returnMatch.Index + returnMatch.Length)..].Trim();
+ if (returnExpression.EndsWith(';')) returnExpression = returnExpression[..^1].TrimEnd();
+ var beforeReturn = body[..returnMatch.Index];
+ var locals = ImmutableArray.CreateBuilder<Local>();
+ var consumed = new List<(int Start, int Length)>();
+ foreach (Match local in Regex.Matches(beforeReturn,
+ @"\blet\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\s*=\s*(?<expression>[^;\r\n]+)\s*;?",
+ RegexOptions.CultureInvariant))
+ {
+ locals.Add(new(local.Groups["name"].Value, local.Groups["type"].Value, local.Groups["expression"].Value.Trim()));
+ consumed.Add((local.Index, local.Length));
+ }
+ var residue = beforeReturn;
+ foreach (var item in consumed.OrderByDescending(item => item.Start)) residue = residue.Remove(item.Start, item.Length);
+ if (!string.IsNullOrWhiteSpace(residue)) diagnostics.Add(UnsupportedBody + ":" + name);
+ result.Add(new(name, parameters, NormalizeType(header.Groups["return"].Value),
+ returnExpression, locals.ToImmutable(), new(header.Index, close - header.Index + 1)));
+ }
+ return result.ToImmutable();
+ }
+
+ private static ImmutableArray<Parameter> ParseParameters(string text, int offset, string feature, List<string> diagnostics)
+ {
+ var result = ImmutableArray.CreateBuilder<Parameter>(); var names = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var (raw, start) in SplitTopLevel(text))
+ {
+ var match = Regex.Match(raw.Trim(), @"^(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)(?:\s*=\s*(?<default>.+))?$", RegexOptions.CultureInvariant);
+ if (!match.Success) { diagnostics.Add(InvalidParameter + ":" + feature + ":" + raw.Trim()); continue; }
+ var name = match.Groups["name"].Value;
+ if (!names.Add(name)) { diagnostics.Add(DuplicateParameter + ":" + feature + ":" + name); continue; }
+ result.Add(new(name, match.Groups["type"].Value,
+ match.Groups["default"].Success ? match.Groups["default"].Value.Trim() : null,
+ new(offset + start, raw.Length)));
+ }
+ return result.ToImmutable();
+ }
+
+ private static ImmutableDictionary<string, string>? Bind(Declaration declaration, string argumentText, int offset, List<string> diagnostics)
+ {
+ var supplied = new Dictionary<string, string>(StringComparer.Ordinal); var position = 0;
+ foreach (var (raw, _) in SplitTopLevel(argumentText))
+ {
+ var colon = TopLevelColon(raw); string name; string expression;
+ if (colon >= 0) { name = raw[..colon].Trim(); expression = raw[(colon + 1)..].Trim(); }
+ else
+ {
+ if (position >= declaration.Parameters.Length) { diagnostics.Add(ArgumentCount + ":" + declaration.Name); continue; }
+ name = declaration.Parameters[position++].Name; expression = raw.Trim();
+ }
+ if (!declaration.Parameters.Any(parameter => parameter.Name == name)) { diagnostics.Add(UnknownArgument + $":{declaration.Name}:{name}"); continue; }
+ if (!supplied.TryAdd(name, expression)) diagnostics.Add(DuplicateArgument + $":{declaration.Name}:{name}");
+ }
+ foreach (var parameter in declaration.Parameters)
+ if (!supplied.ContainsKey(parameter.Name))
+ {
+ if (parameter.DefaultExpression is null) diagnostics.Add(ArgumentCount + $":{declaration.Name}:missing-{parameter.Name}");
+ else supplied[parameter.Name] = Substitute(parameter.DefaultExpression, supplied);
+ }
+ foreach (var parameter in declaration.Parameters)
+ if (supplied.TryGetValue(parameter.Name, out var expression))
+ {
+ if (!TypeMatches(expression, parameter.Type))
+ diagnostics.Add(ArgumentType + $":{declaration.Name}:{parameter.Name}:expected-{parameter.Type}:actual-{DescribeType(expression)}:at-{offset}");
+ else supplied[parameter.Name] = NormalizeExpression(expression, parameter.Type);
+ }
+ return HasErrors(diagnostics) ? null : supplied.ToImmutableDictionary(StringComparer.Ordinal);
+ }
+
+ private static void DetectCycles(IEnumerable<Declaration> declarations, IReadOnlyDictionary<string, Declaration> byName, List<string> diagnostics)
+ {
+ foreach (var declaration in declarations)
+ {
+ var stack = new List<string>(); var complete = new HashSet<string>(StringComparer.Ordinal);
+ bool Visit(string name)
+ {
+ var at = stack.IndexOf(name);
+ if (at >= 0) { diagnostics.Add(Recursion + ":" + string.Join(":", stack.Skip(at).Append(name))); return true; }
+ if (!complete.Add(name)) return false;
+ stack.Add(name);
+ foreach (var target in byName.Keys.Where(candidate => Regex.IsMatch(byName[name].ReturnExpression, $@"^\s*{Regex.Escape(candidate)}\s*\(", RegexOptions.CultureInvariant)))
+ if (Visit(target)) return true;
+ stack.RemoveAt(stack.Count - 1); return false;
+ }
+ _ = Visit(declaration.Name);
+ }
+ }
+
+ private static string Substitute(string expression, IReadOnlyDictionary<string, string> values)
+ {
+ foreach (var pair in values.OrderByDescending(item => item.Key.Length))
+ expression = Regex.Replace(expression, $@"\b{Regex.Escape(pair.Key)}\b(?!\s*:)", _ => pair.Value, RegexOptions.CultureInvariant);
+ return expression;
+ }
+
+ private static bool TypeMatches(string expression, string type)
+ {
+ expression = expression.Trim(); type = NormalizeType(type);
+ if (type is "FaceId" or "EdgeId" or "Body") return false;
+ if (type == "Length") return TryEvaluateScalar(expression, out _, out var unit) && unit == "mm";
+ if (type == "Angle") return TryEvaluateScalar(expression, out _, out var unit) && unit == "deg";
+ if (type == "Int") return TryEvaluateScalar(expression, out var integer, out var intUnit) && intUnit.Length == 0 && integer == Math.Truncate(integer);
+ if (type == "Float") return TryEvaluateScalar(expression, out _, out var floatUnit) && floatUnit.Length == 0;
+ if (type == "Bool") return bool.TryParse(expression, out _);
+ if (type is "Point2" or "Point3")
+ {
+ var arity = type == "Point2" ? 2 : 3;
+ var match = Regex.Match(expression, @"^(?:Point[23]\s*\()?\s*\[?(?<body>[^\]\)]+)\]?\s*\)?$", RegexOptions.CultureInvariant);
+ return (match.Success && SplitTopLevel(match.Groups["body"].Value).Count == arity
+ && SplitTopLevel(match.Groups["body"].Value).All(item => TypeMatches(item.Text, "Length")))
+ || Regex.IsMatch(expression, @"^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?(?:\[\d+\])?$", RegexOptions.CultureInvariant);
+ }
+ // Semantic references and Concept-bound values retain their typed spelling for the owning frontend.
+ return Regex.IsMatch(expression, @"^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?(?:\[\d+\])?$", RegexOptions.CultureInvariant);
+ }
+
+ private static string NormalizeExpression(string expression, string type)
+ {
+ if (NormalizeType(type) is "Length" or "Angle" && TryEvaluateScalar(expression, out var value, out var unit))
+ return value.ToString("R", CultureInfo.InvariantCulture) + unit;
+ if (NormalizeType(type) is "Int" or "Float" && TryEvaluateScalar(expression, out value, out unit) && unit.Length == 0)
+ return value.ToString("R", CultureInfo.InvariantCulture);
+ if (NormalizeType(type) is "Point2" or "Point3")
+ {
+ var match = Regex.Match(expression.Trim(), @"^(?<prefix>Point[23]\s*\()?\s*(?<open>\[)?(?<body>[^\]\)]+)(?:\])?\s*(?:\))?$", RegexOptions.CultureInvariant);
+ if (match.Success)
+ {
+ var values = SplitTopLevel(match.Groups["body"].Value)
+ .Select(item => TryEvaluateScalar(item.Text, out var component, out var componentUnit)
+ ? component.ToString("R", CultureInfo.InvariantCulture) + componentUnit
+ : item.Text.Trim()).ToArray();
+ if (match.Groups["prefix"].Success) return NormalizeType(type) + "(" + string.Join(", ", values) + ")";
+ if (match.Groups["open"].Success) return "[" + string.Join(", ", values) + "]";
+ }
+ }
+ return expression.Trim();
+ }
+
+ private static bool TryEvaluateScalar(string expression, out double value, out string unit)
+ {
+ var parser = new ScalarParser(expression); return parser.TryParse(out value, out unit);
+ }
+
+ private sealed class ScalarParser(string text)
+ {
+ private int _at;
+ public bool TryParse(out double value, out string unit)
+ {
+ try { var result = Add(); White(); if (_at != text.Length || !double.IsFinite(result.Value)) throw new FormatException(); value = result.Value; unit = result.Unit; return true; }
+ catch { value = 0; unit = string.Empty; return false; }
+ }
+ private (double Value, string Unit) Add()
+ {
+ var left = Multiply();
+ while (true) { White(); if (!Take('+') && !Take('-')) return left; var op = text[_at - 1]; var right = Multiply(); if (left.Unit != right.Unit) throw new FormatException(); left = (op == '+' ? left.Value + right.Value : left.Value - right.Value, left.Unit); }
+ }
+ private (double Value, string Unit) Multiply()
+ {
+ var left = Atom();
+ while (true)
+ {
+ White(); if (!Take('*') && !Take('/')) return left; var op = text[_at - 1]; var right = Atom();
+ if (op == '*') { if (left.Unit.Length > 0 && right.Unit.Length > 0) throw new FormatException(); left = (left.Value * right.Value, left.Unit.Length > 0 ? left.Unit : right.Unit); }
+ else { if (right.Value == 0 || right.Unit.Length > 0) throw new FormatException(); left = (left.Value / right.Value, left.Unit); }
+ }
+ }
+ private (double Value, string Unit) Atom()
+ {
+ White(); if (Take('(')) { var value = Add(); White(); if (!Take(')')) throw new FormatException(); return value; }
+ var start = _at; if (_at < text.Length && (text[_at] == '+' || text[_at] == '-')) _at++;
+ while (_at < text.Length && (char.IsDigit(text[_at]) || text[_at] == '.')) _at++;
+ if (start == _at || !double.TryParse(text[start.._at], NumberStyles.Float, CultureInfo.InvariantCulture, out var number)) throw new FormatException();
+ var unit = text.AsSpan(_at).StartsWith("mm") ? "mm" : text.AsSpan(_at).StartsWith("deg") ? "deg" : string.Empty; _at += unit.Length; return (number, unit);
+ }
+ private void White() { while (_at < text.Length && char.IsWhiteSpace(text[_at])) _at++; }
+ private bool Take(char token) { if (_at >= text.Length || text[_at] != token) return false; _at++; return true; }
+ }
+
+ private static string DescribeType(string expression)
+ {
+ foreach (var type in new[] { "Length", "Angle", "Int", "Float", "Bool", "Point2", "Point3" }) if (TypeMatches(expression, type)) return type;
+ return "Unknown";
+ }
+ private static string NormalizeType(string type) => Regex.Replace(type, @"\s+", string.Empty, RegexOptions.CultureInvariant);
+ private static bool SameType(string left, string right) => string.Equals(NormalizeType(left), NormalizeType(right), StringComparison.OrdinalIgnoreCase);
+ private static bool HasErrors(IEnumerable<string> diagnostics) => diagnostics.Any(item => item.StartsWith(Prefix, StringComparison.Ordinal));
+ private static string PatternItemName(string returned, string feature, int ordinal)
+ {
+ var center = Regex.Match(returned, @"\bCenter\s*:\s*(?<item>[A-Za-z_]\w*)\b", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
+ return center.Success ? center.Groups["item"].Value : feature + "__" + ordinal.ToString(CultureInfo.InvariantCulture);
+ }
+ private static int TopLevelColon(string text)
+ {
+ var round = 0; var square = 0; var curly = 0;
+ for (var i = 0; i < text.Length; i++) { switch (text[i]) { case '(': round++; break; case ')': round--; break; case '[': square++; break; case ']': square--; break; case '{': curly++; break; case '}': curly--; break; case ':' when round == 0 && square == 0 && curly == 0: return i; } }
+ return -1;
+ }
+ private static List<(string Text, int Start)> SplitTopLevel(string text)
+ {
+ var result = new List<(string, int)>(); var start = 0; var round = 0; var square = 0; var curly = 0;
+ for (var i = 0; i < text.Length; i++)
+ {
+ switch (text[i]) { case '(': round++; break; case ')': round--; break; case '[': square++; break; case ']': square--; break; case '{': curly++; break; case '}': curly--; break; case ',' when round == 0 && square == 0 && curly == 0: result.Add((text[start..i], start)); start = i + 1; break; }
+ }
+ if (!string.IsNullOrWhiteSpace(text[start..])) result.Add((text[start..], start));
+ return result;
+ }
+ 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; }
+ private static bool IsInsideBlock(string source, int index, string kind)
+ {
+ foreach (Match header in Regex.Matches(source, $@"\b{Regex.Escape(kind)}\s+[A-Za-z_]\w*\s*\{{", RegexOptions.CultureInvariant))
+ { var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}'); if (header.Index < index && index < close) return true; }
+ return false;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 6cffd49d..1dec6f68 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -308,6 +308,19 @@ public static class FirmamentV2Parser
var v2AdmissionCandidate = IsV2AdmissionCandidate(source);
conceptCatalog ??= FirmamentV2ForgeConceptRegistry.Catalog;
+ // Feature is Firmament's bounded function-like abstraction. It is expanded once,
+ // before Template/static specialization, so every downstream command consumes the
+ // same concrete semantic declarations and no geometry callback can bypass AIR.
+ var featureExpansion = FirmamentV2FeatureExpansion.Expand(source, diagnostics);
+ if (featureExpansion is null)
+ {
+ diagnostics.Add("firmament-v2-parse-failed");
+ return FirmamentV2ParseResult.Failure(
+ diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray(),
+ FirmamentV2ParseDisposition.RecognizedInvalid);
+ }
+ source = featureExpansion.Source;
+
// Modern Template specialization owns typed Record binding. Run it while
// Record and scalar Static declarations still exist, then let canonical
// static authoring erase those compile-time declarations before AIR.
@@ -339,7 +352,9 @@ public static class FirmamentV2Parser
if (!panelCompilation.IsSuccess)
return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray());
var panelDocument = new FirmamentV2Document(panelCompilation.ModelName, "mm", [],
- TemplateInstantiations: templateExpansion.Instantiations, Panels: panelCompilation.Panels);
+ TemplateInstantiations: templateExpansion.Instantiations, Panels: panelCompilation.Panels,
+ FeatureDefinitions: featureExpansion.Definitions, FeatureInvocations: featureExpansion.Invocations,
+ FeatureExpansion: featureExpansion.Metrics);
return FirmamentV2ParseResult.Success(panelDocument, diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray());
}
@@ -359,7 +374,9 @@ public static class FirmamentV2Parser
: ParseCanonicalDocument(source, diagnostics, sourceDirectory));
if (parsed.Document is null) return parsed;
- return AttachVolumeAssertionsAndSymbols(parsed, source, canonicalStaticExpansion.Document, diagnostics);
+ return WithFeatureMetadata(
+ AttachVolumeAssertionsAndSymbols(parsed, source, canonicalStaticExpansion.Document, diagnostics),
+ featureExpansion);
}
if (Regex.IsMatch(source, @"\b(?:RoundedBox|Frustum|Box)\s*<\s*[A-Za-z_][A-Za-z0-9_]*\s*>\s+[A-Za-z_]", RegexOptions.CultureInvariant))
@@ -370,7 +387,9 @@ 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(AttachVolumeAssertionsAndSymbols(ParseConceptModelingDocument(RemoveCanonicalVolumeAssertions(source), diagnostics, templateExpansion.Instantiations), source, canonicalStaticExpansion.Document, diagnostics));
+ return Recognized(WithFeatureMetadata(
+ AttachVolumeAssertionsAndSymbols(ParseConceptModelingDocument(RemoveCanonicalVolumeAssertions(source), diagnostics, templateExpansion.Instantiations), source, canonicalStaticExpansion.Document, diagnostics),
+ featureExpansion));
if (Regex.IsMatch(source, @"^\s*Model\b", RegexOptions.CultureInvariant))
return Recognized(ParsePhase3ModelingDocument(source, diagnostics));
@@ -454,6 +473,21 @@ public static class FirmamentV2Parser
: FirmamentV2ParseDisposition.RecognizedInvalid
};
+ private static FirmamentV2ParseResult WithFeatureMetadata(
+ FirmamentV2ParseResult result,
+ FirmamentV2FeatureExpansion.Result expansion) =>
+ result.Document is null
+ ? result
+ : result with
+ {
+ Document = result.Document with
+ {
+ FeatureDefinitions = expansion.Definitions,
+ FeatureInvocations = expansion.Invocations,
+ FeatureExpansion = expansion.Metrics
+ }
+ };
+
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)
@@ -1973,7 +2007,7 @@ public static class FirmamentV2Parser
|| code.StartsWith(ConceptIrResolver.PointProjectionUnsupported, StringComparison.Ordinal)
|| code.StartsWith("firmament-static-", StringComparison.Ordinal);
- public static bool IsFatalDiagnosticCode(string code) => code.StartsWith("firmament-boss-", StringComparison.Ordinal) || code.StartsWith("firmament-pocket-", StringComparison.Ordinal) || code.StartsWith("feature-support-", StringComparison.Ordinal) || code.StartsWith("compose-role-cardinality:", StringComparison.Ordinal) || code.StartsWith(ModifyTargetNotBoundToActiveCompose, StringComparison.Ordinal) || code.StartsWith("firmament-v2-assert-volume-", StringComparison.Ordinal) || code.StartsWith(SemanticConstraintMalformed, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintUnsupported, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintDimensionMismatch, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintValidationFailed, StringComparison.Ordinal) || code.StartsWith(PmiProjectionUnknownRequire, StringComparison.Ordinal) || code.StartsWith(PmiProjectionUnsupportedKind, StringComparison.Ordinal) || code.StartsWith(PmiProjectedFieldMustNotOverrideSourceConstraint, StringComparison.Ordinal) || code.StartsWith(AssertVolumeKindUnsupported, StringComparison.Ordinal) || code.StartsWith(CanonicalDeclarationUnknown + ":", StringComparison.Ordinal) || code.StartsWith(CanonicalConstructNotYetSupported + ":", StringComparison.Ordinal) || code.StartsWith(EdgeFinishProfileComposeBoundaryUnsupported, StringComparison.Ordinal) || IsConceptFatalDiagnostic(code) || code is UnknownConstructionPolicy or PrimitiveDoesNotSatisfyHollowConstructible or WallThicknessRequired or WallThicknessMustBePositive or UnsupportedOpening or MultipleOpeningsNotSupported or Phase3EdgeFinishSyntaxInvalid or PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported or ConceptUnknownFamily or ConceptUnknownConcept or ConceptMissingRequiredField or ConceptUnknownField or ConceptDuplicateField or ConceptFieldTypeMismatch or ConceptInvalidTarget or ConceptDescriptorUnavailable or PmiDuplicateBlock or PmiDuplicateRecord or PmiDuplicateDatum or PmiUnknownRecordKind or PmiMissingRequiredField or PmiUnknownField or PmiDuplicateField or PmiInvalidTarget or PmiUnknownDatum or PmiDimensionTypeMismatch or PmiDimensionMissingTolerance or PmiToleranceTypeMismatch or StandaloneFillRegionRequired or UnsupportedStandaloneFillPattern or InvalidCellCount or CellSizeMustBePositive or StrutRadiusMustBePositive or NodeRadiusMustBePositive or MaterialBoundsMismatch or StandaloneFillMultipleUnsupported;
+ public static bool IsFatalDiagnosticCode(string code) => code.StartsWith(FirmamentV2FeatureExpansion.Prefix, StringComparison.Ordinal) || code.StartsWith("firmament-boss-", StringComparison.Ordinal) || code.StartsWith("firmament-pocket-", StringComparison.Ordinal) || code.StartsWith("feature-support-", StringComparison.Ordinal) || code.StartsWith("compose-role-cardinality:", StringComparison.Ordinal) || code.StartsWith(ModifyTargetNotBoundToActiveCompose, StringComparison.Ordinal) || code.StartsWith("firmament-v2-assert-volume-", StringComparison.Ordinal) || code.StartsWith(SemanticConstraintMalformed, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintUnsupported, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintDimensionMismatch, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintValidationFailed, StringComparison.Ordinal) || code.StartsWith(PmiProjectionUnknownRequire, StringComparison.Ordinal) || code.StartsWith(PmiProjectionUnsupportedKind, StringComparison.Ordinal) || code.StartsWith(PmiProjectedFieldMustNotOverrideSourceConstraint, StringComparison.Ordinal) || code.StartsWith(AssertVolumeKindUnsupported, StringComparison.Ordinal) || code.StartsWith(CanonicalDeclarationUnknown + ":", StringComparison.Ordinal) || code.StartsWith(CanonicalConstructNotYetSupported + ":", StringComparison.Ordinal) || code.StartsWith(EdgeFinishProfileComposeBoundaryUnsupported, StringComparison.Ordinal) || IsConceptFatalDiagnostic(code) || code is UnknownConstructionPolicy or PrimitiveDoesNotSatisfyHollowConstructible or WallThicknessRequired or WallThicknessMustBePositive or UnsupportedOpening or MultipleOpeningsNotSupported or Phase3EdgeFinishSyntaxInvalid or PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported or ConceptUnknownFamily or ConceptUnknownConcept or ConceptMissingRequiredField or ConceptUnknownField or ConceptDuplicateField or ConceptFieldTypeMismatch or ConceptInvalidTarget or ConceptDescriptorUnavailable or PmiDuplicateBlock or PmiDuplicateRecord or PmiDuplicateDatum or PmiUnknownRecordKind or PmiMissingRequiredField or PmiUnknownField or PmiDuplicateField or PmiInvalidTarget or PmiUnknownDatum or PmiDimensionTypeMismatch or PmiDimensionMissingTolerance or PmiToleranceTypeMismatch or StandaloneFillRegionRequired or UnsupportedStandaloneFillPattern or InvalidCellCount or CellSizeMustBePositive or StrutRadiusMustBePositive or NodeRadiusMustBePositive or MaterialBoundsMismatch or StandaloneFillMultipleUnsupported;
private static IReadOnlyList<FirmamentV2Exposure> ParseExposures(string body, List<string> diagnostics)
{
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index c052247b..13f5a82b 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -38,3 +38,92 @@ An untransformed `Box` stock is centered in X/Y with `Bottom` at Z=0 and `Top` a
Firmament admits declarations through typed semantic namespaces. Construction `Profile` names may coincide with `Boss` or `Pocket` feature names because feature `Profile:` references are explicitly typed; these identities remain distinct in structured inspection. Names may not otherwise shadow another declaration in the same semantic namespace.
Use `aetheris validate file.firmament --json` before building. Diagnostics are codes intended for automation plus short corrective messages. See [diagnostics](../reference/diagnostics.md).
+
+## Reusable semantic construction with Feature
+
+`Feature` is Firmament's function-like abstraction for reusable semantic construction. It accepts typed inputs and returns exactly one typed semantic output. Feature evaluation is pure, deterministic, file-local in X1, and expanded before Feature AIR; a definition does not materialize geometry until it is invoked.
+
+```firmament
+Feature M8Counterbore(Center: Point2, Depth: Length = 4mm) -> Hole<Counterbore> {
+ let CounterboreDiameter: Length = 8.5mm + 5.5mm
+ return Hole<Counterbore> {
+ On: +Z
+ Center: Center
+ Diameter: 8.5mm
+ CounterboreDiameter: CounterboreDiameter
+ CounterboreDepth: Depth
+ End: ThroughAll
+ }
+}
+
+Modify Plate {
+ M8Counterbore(Center: Point2(-20mm, 0mm))
+ M8Counterbore(Center: Point2(20mm, 0mm), Depth: 5mm)
+}
+```
+
+Parameters are strongly typed and calls may use positional or named arguments. Defaults are optional. A body contains immutable typed `let` derivations followed by one terminal `return`. A Feature may return `Hole<Shaft>`, `Hole<Counterbore>`, `Hole<Countersink>`, `Boss`, `Pocket`, or `EdgeFinish`, and may call another Feature with the same return type. Direct and indirect recursion are rejected. Feature names occupy the callable namespace, separate from typed construction declarations such as `Profile`.
+
+Firmament intentionally does not provide general runtime control flow. `if`/`else`, conditional expressions, `match` inside Feature, mutable variables, exceptions, and `for`/`while` loops are rejected. A Firmament program describes one deterministic engineering construction, not a runtime family of topologically unrelated outputs.
+
+Use each abstraction for its single role:
+
+| Construct | Role |
+| --- | --- |
+| `Feature` | Function-like reusable semantic construction. |
+| `Pattern` | Bounded finite geometric repetition; it is the loop substitute. |
+| `Template` | Compile-time product/configuration specialization; it is the structural branch substitute. |
+| `Concept` | Semantic contract or capability. |
+| `Record` / `Struct` | Typed data and semantic structure. |
+
+Feature composes with an existing bounded Pattern without exposing its internals:
+
+```firmament
+Feature MountHole(Center: Point3, Diameter: Length = 6mm) -> Hole<Shaft> {
+ return Hole<Shaft> {
+ On: Base.Top
+ Center: Center
+ Diameter: Diameter
+ End: ThroughAll
+ }
+}
+
+Concept Struct Design {
+ Bounds: Box3 { Size: [60mm, 40mm, 10mm] }
+ Points: Grid {
+ Within: Bounds.Face(+Z).Inset(8mm)
+ Columns: 2
+ Rows: 2
+ }
+}
+
+Pattern Mounts {
+ Source: Design.Points
+ MountHole(Center: Item)
+}
+```
+
+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.
+
+A Feature may return a call to another Feature with the same declared result type:
+
+```firmament
+Feature CoreCounterbore(Center: Point2, Depth: Length) -> Hole<Counterbore> {
+ return Hole<Counterbore> {
+ On: +Z
+ Center: Center
+ Diameter: 8.5mm
+ CounterboreDiameter: 14mm
+ CounterboreDepth: Depth
+ End: ThroughAll
+ }
+}
+
+Feature M8Counterbore(Center: Point2) -> Hole<Counterbore> {
+ return CoreCounterbore(Center: Center, Depth: 4mm)
+}
+```
+
+Structurally different edge finishes should be separate Features in X1—for example, `StandardChamfer` and `StandardFillet`. A caller may instead select a specialized product with Template where that owning Template grammar admits the returned construction. Feature itself cannot branch between them.
+
+For X1, Feature is supported by the `Mechanical` frontend. `WireForm`, `Sweep`, and `SectionChain` reject Feature declarations explicitly; shared cross-schema Feature IR and module/library packaging are deferred.
diff --git a/docs/release/LANG-FEATURE-X1.md b/docs/release/LANG-FEATURE-X1.md
new file mode 100644
index 00000000..557351d6
--- /dev/null
+++ b/docs/release/LANG-FEATURE-X1.md
@@ -0,0 +1,107 @@
+# LANG-FEATURE-X1 — pure Feature functions
+
+## Executive verdict
+
+**Accepted.** Firmament can express reusable typed semantic construction through deterministic Feature functions without adding general runtime control flow. Definitions lower to the existing semantic declaration grammar before Feature AIR; validation, inspection, build, and STEP export therefore consume the same admitted expansion.
+
+## Semantics
+
+- Parameters are ordered, strongly typed, and file-local. Calls accept positional or named arguments; trailing parameters may have typed defaults.
+- A body contains zero or more immutable typed `let` derivations and exactly one terminal `return`.
+- X1 return types are existing Mechanical semantic operations: `Hole<Shaft>`, `Hole<Counterbore>`, `Hole<Countersink>`, `Boss`, `Pocket`, and `EdgeFinish`.
+- Feature calls may call another Feature. A finite call graph is checked before expansion; direct and indirect cycles produce `firmament-feature-recursion:<A>:<B>:...`.
+- Expansion is pure source-to-semantic normalization. It reads no topology or global mutable state and does not materialize a definition by itself.
+- Invocations inside a `Modify`, `Compose`, or bounded `Pattern` retain authored order. Relative selectors are left in the returned operation and resolve against the current construction state at the invocation position.
+- Feature and ordinary construction declarations use distinct typed namespaces. Parameters and local bindings never enter the global symbol table.
+
+The supported control-flow boundary is deliberately narrow:
+
+| Supported | Unsupported |
+| --- | --- |
+| typed calls | `if` / `else` / ternary / `match` |
+| immutable typed derivation | mutable state or reassignment |
+| one terminal return | multiple or early returns |
+| bounded `Pattern` composition | `for`, `foreach`, or `while` |
+| `Template` specialization outside Feature | direct or indirect recursion |
+
+Firmament intentionally does not provide general runtime control flow. A program describes one deterministic engineering construction, not a runtime family of topologically unrelated outputs. Pattern owns finite repetition, Template owns compile-time specialization, Concept owns admissibility, and Feature owns reusable semantic transformation.
+
+## Existing Feature vocabulary
+
+Before X1, `Feature` was not a top-level callable keyword. It appeared as the `Feature:` field of schema-owned Pattern records and throughout the implementation as the engineering category / Feature AIR boundary. X1 unifies with that vocabulary: a Feature function returns an existing semantic feature or operation and expands before Feature AIR. It does not introduce a second unrelated geometry executor. Existing `Feature:` fields and persisted Template feature generators are unchanged.
+
+Body-to-Body functions were audited and not admitted. Current Mechanical use cases are cleaner as returned typed operations applied by the existing ConstructionState in source order. Multi-operation Feature groups are likewise deferred because the flagships do not justify a new tuple, list, or operation-group type.
+
+## Before and after
+
+The counterbore flagship replaces repeated seven-field declarations with a named call while retaining visible typed intent:
+
+```firmament
+// Before: repeat this block at every center.
+Hole<Counterbore> LeftMount {
+ On: +Z
+ Center: Point2(-20mm, 0mm)
+ Diameter: 8.5mm
+ CounterboreDiameter: 14mm
+ CounterboreDepth: 4mm
+ End: ThroughAll
+}
+
+// After: the shared dimensions live in one pure definition.
+M8Counterbore(Center: Point2(-20mm, 0mm))
+```
+
+For four mounting holes, the previous raw `Hole<Shaft>` body remains one Pattern element, but Feature gives that element a reusable typed identity:
+
+```firmament
+Pattern Mounts {
+ Source: Design.Points
+ MountHole(Center: Item)
+}
+```
+
+There is no `for`: Pattern still owns the finite four-element expansion. The canonical fixtures reduce duplicated dimensional fields while keeping operation kind, placement, and termination explicit. The counterbore before/after qualification produces byte-identical STEP when the concrete generated feature name is held equal; semantic kind and dimensions also match.
+
+| Flagship | Before | After | Duplicated call-site parameters | Semantic result |
+| --- | ---: | ---: | ---: | --- |
+| Two M8 counterbores | 16 construction lines | 11-line definition plus 2 one-line calls | 10 repeated fixed fields to 0 | Two typed `Hole<Counterbore>` operations |
+| Four-hole Pattern element | 9-line Pattern/raw-Hole call site | 4-line Pattern/Feature call site, plus one reusable definition | 4 operation fields at the Pattern site to 0 | Four typed `Hole<Shaft>` operations |
+
+The Pattern comparison separates reusable definition cost from call-site cost; Feature is justified by semantic naming and reuse, not by claiming every first use is shorter.
+
+## Inspection and diagnostics
+
+`aetheris inspect --json` reports `featureDefinitions`, `featureInvocations`, and deterministic `featureExpansion` counts, including parameter bindings, return type, expanded semantic kind, invocation ordinal, `generatedByFeature`, definition count, authored call count, and resulting pre-AIR node count. The resulting ordinary `features` inventory continues to report `Hole<Counterbore>`, `Hole<Shaft>`, or the other existing operation kind rather than an opaque function result.
+
+Typed diagnostics cover argument count/name/type, local type errors, missing or multiple returns, wrong return type, unsupported body/control-flow syntax, duplicate declarations/parameters, and recursion. Argument failures include Feature name, parameter, expected/actual type, and invocation offset.
+
+## Schema and library status
+
+X1 supports `schema Mechanical`. `WireForm`, `Sweep`, and `SectionChain` reject Feature declarations with `firmament-feature-schema-unsupported:<schema>`; shared cross-schema Feature IR is a follow-up, not implied support. Features are file-local. No Standard Library Feature was promoted because the flagships are application policy (`M8Counterbore`, mounting layout, and edge finish), not a stable universal library primitive.
+
+## Qualification
+
+Canonical fixtures:
+
+- `fixtures/Canonical/Feature/simple-hole-feature.firmament`
+- `fixtures/Canonical/Feature/feature-with-derived-values.firmament`
+- `fixtures/Canonical/Feature/feature-pattern.firmament`
+- `fixtures/Canonical/Feature/nested-feature-call.firmament`
+- `fixtures/Canonical/Feature/edge-finish-feature.firmament`
+- `fixtures/Canonical/Feature/boss-pocket-feature.firmament`
+
+Invalid fixtures cover wrong/missing/extra arguments, missing/wrong return, direct/indirect recursion, conditional syntax, and loop syntax under `fixtures/Invalid/Feature/`.
+
+The automated lane covers parse/bind, defaults, named arguments, local unit-aware arithmetic, nested calls, Pattern composition, recursion and control-flow rejection, typed diagnostics, structured provenance, STEP export/reimport, enclosed geometry, deterministic repeat behavior, and exact concrete-vs-Feature STEP parity. X1 performs a bounded linear scan plus finite call expansion; no runtime geometry work is added by definitions.
+
+Final local qualification:
+
+- Release solution build: passed with zero warnings and zero errors.
+- Feature-focused tests: 24 passed.
+- Full `Aetheris.Kernel.Firmament.Tests`: 1,330 passed.
+- Full `Aetheris.CLI.Tests`: 410 passed.
+- Canonical production qualification: all 147 fixtures passed, including all six Feature flagships.
+- Nine invalid Feature fixtures: all rejected by CLI validation with fatal typed diagnostics.
+- Freshly packed and isolated `Aetheris.CLI 2.0.0-preview.3`: validated and built the derived M8 counterbore fixture; STEP export/reimport evidence remained successful.
+- Fresh-author doctrine audit: all six expected boundaries were understood; the discovered M8-dimension, Pattern-source, Pattern-dialect, and nested-call documentation ambiguities were corrected in the public syntax guide.
+- Repository layout guard: passed (3,941 tracked files inspected).
diff --git a/fixtures/Canonical/Feature/boss-pocket-feature.firmament b/fixtures/Canonical/Feature/boss-pocket-feature.firmament
new file mode 100644
index 00000000..27224e78
--- /dev/null
+++ b/fixtures/Canonical/Feature/boss-pocket-feature.firmament
@@ -0,0 +1,40 @@
+schema Mechanical
+Model BossPocketFeature {
+ Units: mm
+ Feature RaisedPad(Shape: Profile, Height: Length) -> Boss {
+ return Boss { On: Top Profile: Shape Height: Height }
+ }
+ Feature Recess(Shape: Profile, Depth: Length, Floor: Length = 2mm) -> Pocket {
+ return Pocket { On: Top Profile: Shape Depth: Depth MinimumFloorThickness: Floor }
+ }
+ Concept Struct Layout On XY {
+ Rect2 Stock { Center: [0mm, 0mm] Size: [40mm, 24mm] }
+ Rect2 Pad { Center: [-10mm, 0mm] Size: [8mm, 8mm] }
+ Rect2 Cutout { Center: [10mm, 0mm] Size: [8mm, 8mm] }
+ }
+ Profile BaseProfile Using Layout { Loop Outer {
+ Segment Bottom { Trace: Stock.Bottom From: Stock.BottomLeft To: Stock.BottomRight }
+ Segment Right { Trace: Stock.Right From: Stock.BottomRight To: Stock.TopRight }
+ Segment Top { Trace: Stock.Top From: Stock.TopRight To: Stock.TopLeft }
+ Segment Left { Trace: Stock.Left From: Stock.TopLeft To: Stock.BottomLeft }
+ } }
+ Profile PadProfile Using Layout { Loop Outer {
+ Segment Bottom { Trace: Pad.Bottom From: Pad.BottomLeft To: Pad.BottomRight }
+ Segment Right { Trace: Pad.Right From: Pad.BottomRight To: Pad.TopRight }
+ Segment Top { Trace: Pad.Top From: Pad.TopRight To: Pad.TopLeft }
+ Segment Left { Trace: Pad.Left From: Pad.TopLeft To: Pad.BottomLeft }
+ } }
+ Profile CutoutProfile Using Layout { Loop Outer {
+ Segment Bottom { Trace: Cutout.Bottom From: Cutout.BottomLeft To: Cutout.BottomRight }
+ Segment Right { Trace: Cutout.Right From: Cutout.BottomRight To: Cutout.TopRight }
+ Segment Top { Trace: Cutout.Top From: Cutout.TopRight To: Cutout.TopLeft }
+ Segment Left { Trace: Cutout.Left From: Cutout.TopLeft To: Cutout.BottomLeft }
+ } }
+ Struct Product {
+ Compose Body {
+ Base Stock { Profile: BaseProfile From: 0mm To: 10mm Role: Stock }
+ RaisedPad(Shape: PadProfile, Height: 5mm)
+ Recess(Shape: CutoutProfile, Depth: 4mm)
+ }
+ }
+}
diff --git a/fixtures/Canonical/Feature/edge-finish-feature.firmament b/fixtures/Canonical/Feature/edge-finish-feature.firmament
new file mode 100644
index 00000000..8425741c
--- /dev/null
+++ b/fixtures/Canonical/Feature/edge-finish-feature.firmament
@@ -0,0 +1,12 @@
+schema Mechanical
+Model EdgeFinishFeature {
+ Units: mm
+ Feature StandardTopChamfer(Size: Length = 1mm) -> EdgeFinish {
+ return EdgeFinish { Face: +Z Target: Boundary Kind: Chamfer Distance: Size }
+ }
+ Box Plate { Size: [30mm, 20mm, 8mm] }
+ Modify Plate {
+ Hole<Shaft> Mount { On: +Z Center: Point2(0mm, 0mm) Diameter: 5mm End: ThroughAll }
+ StandardTopChamfer()
+ }
+}
diff --git a/fixtures/Canonical/Feature/feature-pattern.firmament b/fixtures/Canonical/Feature/feature-pattern.firmament
new file mode 100644
index 00000000..a6b669f8
--- /dev/null
+++ b/fixtures/Canonical/Feature/feature-pattern.firmament
@@ -0,0 +1,26 @@
+schema Mechanical
+Feature MountHole(Center: Point3, Diameter: Length = 6mm) -> Hole<Shaft> {
+ return Hole<Shaft> {
+ On: Base.Top
+ Center: Center
+ Diameter: Diameter
+ End: ThroughAll
+ }
+}
+Concept Struct Design {
+ Bounds: Box3 { Size: [60mm, 40mm, 10mm] }
+ Points: Grid {
+ Within: Bounds.Face(+Z).Inset(8mm)
+ Columns: 2
+ Rows: 2
+ }
+}
+Struct PatternPlate {
+ Box Base { Bounds: Design.Bounds }
+ Modify Base {
+ Pattern Mounts {
+ Source: Design.Points
+ MountHole(Center: Item)
+ }
+ }
+}
diff --git a/fixtures/Canonical/Feature/feature-with-derived-values.firmament b/fixtures/Canonical/Feature/feature-with-derived-values.firmament
new file mode 100644
index 00000000..f6541314
--- /dev/null
+++ b/fixtures/Canonical/Feature/feature-with-derived-values.firmament
@@ -0,0 +1,17 @@
+schema Mechanical
+Model DerivedCounterboreFeature {
+ Units: mm
+ Feature M8Counterbore(Center: Point2, Depth: Length = 4mm) -> Hole<Counterbore> {
+ let CounterboreDiameter: Length = 8.5mm + 5.5mm
+ return Hole<Counterbore> {
+ On: +Z
+ Center: Center
+ Diameter: 8.5mm
+ CounterboreDiameter: CounterboreDiameter
+ CounterboreDepth: Depth
+ End: ThroughAll
+ }
+ }
+ Box Plate { Size: [30mm, 20mm, 8mm] }
+ Modify Plate { M8Counterbore(Center: Point2(0mm, 0mm)) }
+}
diff --git a/fixtures/Canonical/Feature/nested-feature-call.firmament b/fixtures/Canonical/Feature/nested-feature-call.firmament
new file mode 100644
index 00000000..92b4ced1
--- /dev/null
+++ b/fixtures/Canonical/Feature/nested-feature-call.firmament
@@ -0,0 +1,19 @@
+schema Mechanical
+Model NestedFeatureCall {
+ Units: mm
+ Feature CoreCounterbore(Center: Point2, Depth: Length) -> Hole<Counterbore> {
+ return Hole<Counterbore> {
+ On: +Z
+ Center: Center
+ Diameter: 8.5mm
+ CounterboreDiameter: 14mm
+ CounterboreDepth: Depth
+ End: ThroughAll
+ }
+ }
+ Feature M8Counterbore(Center: Point2) -> Hole<Counterbore> {
+ return CoreCounterbore(Center: Center, Depth: 4mm)
+ }
+ Box Plate { Size: [30mm, 20mm, 8mm] }
+ Modify Plate { M8Counterbore(Center: Point2(0mm, 0mm)) }
+}
diff --git a/fixtures/Canonical/Feature/simple-hole-feature.firmament b/fixtures/Canonical/Feature/simple-hole-feature.firmament
new file mode 100644
index 00000000..29e6e12a
--- /dev/null
+++ b/fixtures/Canonical/Feature/simple-hole-feature.firmament
@@ -0,0 +1,17 @@
+schema Mechanical
+Model SimpleHoleFeature {
+ Units: mm
+ Feature MountHole(Center: Point2, Diameter: Length = 6mm) -> Hole<Shaft> {
+ return Hole<Shaft> {
+ On: +Z
+ Center: Center
+ Diameter: Diameter
+ End: ThroughAll
+ }
+ }
+ Box Plate { Size: [60mm, 30mm, 8mm] }
+ Modify Plate {
+ MountHole(Center: Point2(-18mm, 0mm))
+ MountHole(Center: Point2(18mm, 0mm))
+ }
+}
diff --git a/fixtures/Canonical/coverage.json b/fixtures/Canonical/coverage.json
index 0285e09d..fc5c26f1 100644
--- a/fixtures/Canonical/coverage.json
+++ b/fixtures/Canonical/coverage.json
@@ -28,6 +28,7 @@
"Material": "Materials/material-catalog-coupon.firmament",
"PMI": "PMI/multiple-hole-dimensions-with-chamfer.firmament",
"Template": "Templates/generic-mounting-plate.firmament",
+ "FeatureFunction": "Feature/feature-with-derived-values.firmament",
"SheetMetal": "SheetMetal/l-bracket-with-hole.firmament",
"FEA": "FEA/cantilever.firmament",
"inlineSTEP": "FEA/inline-step-cantilever.firmament",
diff --git a/fixtures/Canonical/qualification.json b/fixtures/Canonical/qualification.json
index 18d3b42a..c1315a0c 100644
--- a/fixtures/Canonical/qualification.json
+++ b/fixtures/Canonical/qualification.json
@@ -25,6 +25,8 @@
{ "path": "Primitives", "operation": "build-step" },
{ "path": "Profiles", "operation": "build-step" },
{ "path": "Features", "operation": "build-step" },
+ { "path": "Feature", "operation": "build-step" },
+ { "path": "Schema", "operation": "build-step" },
{ "path": "Patterns", "operation": "build-step" },
{ "path": "PMI", "operation": "build-step" },
{ "path": "Templates", "operation": "build-step" },
diff --git a/fixtures/Invalid/Feature/direct-recursion.firmament b/fixtures/Invalid/Feature/direct-recursion.firmament
new file mode 100644
index 00000000..c7d01785
--- /dev/null
+++ b/fixtures/Invalid/Feature/direct-recursion.firmament
@@ -0,0 +1 @@
+Feature A() -> Hole<Shaft> { return A() }
diff --git a/fixtures/Invalid/Feature/extra-argument.firmament b/fixtures/Invalid/Feature/extra-argument.firmament
new file mode 100644
index 00000000..80990023
--- /dev/null
+++ b/fixtures/Invalid/Feature/extra-argument.firmament
@@ -0,0 +1,2 @@
+Feature MountHole(Center: Point2) -> Hole<Shaft> { return Hole<Shaft> { On: +Z Center: Center Diameter: 6mm End: ThroughAll } }
+Model ExtraArgument { Units: mm Box Plate { Size: [20mm, 20mm, 5mm] } Modify Plate { MountHole(Point2(0mm, 0mm), 1mm) } }
diff --git a/fixtures/Invalid/Feature/indirect-recursion.firmament b/fixtures/Invalid/Feature/indirect-recursion.firmament
new file mode 100644
index 00000000..635710de
--- /dev/null
+++ b/fixtures/Invalid/Feature/indirect-recursion.firmament
@@ -0,0 +1,2 @@
+Feature A() -> Hole<Shaft> { return B() }
+Feature B() -> Hole<Shaft> { return A() }
diff --git a/fixtures/Invalid/Feature/missing-argument.firmament b/fixtures/Invalid/Feature/missing-argument.firmament
new file mode 100644
index 00000000..3210239b
--- /dev/null
+++ b/fixtures/Invalid/Feature/missing-argument.firmament
@@ -0,0 +1,2 @@
+Feature MountHole(Center: Point2) -> Hole<Shaft> { return Hole<Shaft> { On: +Z Center: Center Diameter: 6mm End: ThroughAll } }
+Model MissingArgument { Units: mm Box Plate { Size: [20mm, 20mm, 5mm] } Modify Plate { MountHole() } }
diff --git a/fixtures/Invalid/Feature/missing-return.firmament b/fixtures/Invalid/Feature/missing-return.firmament
new file mode 100644
index 00000000..647e17cd
--- /dev/null
+++ b/fixtures/Invalid/Feature/missing-return.firmament
@@ -0,0 +1 @@
+Feature Broken(Center: Point2) -> Hole<Shaft> { let Diameter: Length = 6mm }
diff --git a/fixtures/Invalid/Feature/unsupported-conditional.firmament b/fixtures/Invalid/Feature/unsupported-conditional.firmament
new file mode 100644
index 00000000..afa82c05
--- /dev/null
+++ b/fixtures/Invalid/Feature/unsupported-conditional.firmament
@@ -0,0 +1 @@
+Feature Broken() -> Hole<Shaft> { if true return Hole<Shaft> { On: +Z Center: Point2(0mm, 0mm) Diameter: 6mm End: ThroughAll } }
diff --git a/fixtures/Invalid/Feature/unsupported-loop.firmament b/fixtures/Invalid/Feature/unsupported-loop.firmament
new file mode 100644
index 00000000..b2092fb7
--- /dev/null
+++ b/fixtures/Invalid/Feature/unsupported-loop.firmament
@@ -0,0 +1 @@
+Feature Broken() -> Hole<Shaft> { for Item return Hole<Shaft> { On: +Z Center: Point2(0mm, 0mm) Diameter: 6mm End: ThroughAll } }
diff --git a/fixtures/Invalid/Feature/wrong-argument-type.firmament b/fixtures/Invalid/Feature/wrong-argument-type.firmament
new file mode 100644
index 00000000..20e11aef
--- /dev/null
+++ b/fixtures/Invalid/Feature/wrong-argument-type.firmament
@@ -0,0 +1,2 @@
+Feature MountHole(Center: Point2) -> Hole<Shaft> { return Hole<Shaft> { On: +Z Center: Center Diameter: 6mm End: ThroughAll } }
+Model WrongArgument { Units: mm Box Plate { Size: [20mm, 20mm, 5mm] } Modify Plate { MountHole(Center: 4mm) } }
diff --git a/fixtures/Invalid/Feature/wrong-return-type.firmament b/fixtures/Invalid/Feature/wrong-return-type.firmament
new file mode 100644
index 00000000..50e502e3
--- /dev/null
+++ b/fixtures/Invalid/Feature/wrong-return-type.firmament
@@ -0,0 +1,2 @@
+Feature Broken(Center: Point2) -> Hole<Counterbore> { return Hole<Shaft> { On: +Z Center: Center Diameter: 6mm End: ThroughAll } }
+Model WrongReturn { Units: mm Box Plate { Size: [20mm, 20mm, 5mm] } Modify Plate { Broken(Point2(0mm, 0mm)) } }