Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add typed record template expansion and exact coaxial export

Yuechen Li949da4449acf
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplateExpansionTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplateExpansionTests.cs
index ea1f0cb4..52d4d4a2 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplateExpansionTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplateExpansionTests.cs
@@ -4,6 +4,49 @@ namespace Aetheris.Kernel.Firmament.Tests;
public sealed class FirmamentV2TemplateExpansionTests
{
+ [Fact]
+ public void TypedRecordParameter_BindsStaticRecordMembersAndRequireBeforeAir()
+ {
+ var first = FirmamentV2Parser.Parse(WidgetSource("WidgetA"));
+ var second = FirmamentV2Parser.Parse(WidgetSource("WidgetA"));
+
+ Assert.True(first.IsSuccess, string.Join(Environment.NewLine, first.Diagnostics));
+ Assert.True(second.IsSuccess, string.Join(Environment.NewLine, second.Diagnostics));
+ var expansion = Assert.Single(first.Document!.ConceptIr!.TemplateInstantiations!);
+ var record = Assert.Single(expansion.RecordArguments!);
+ Assert.Equal("Spec", record.Key);
+ Assert.Equal("WidgetSpec", record.Value.RecordType);
+ Assert.Equal("TallWidget", record.Value.StaticValue);
+ Assert.Equal("25mm", record.Value.Members["Height"]);
+ Assert.Equal("StaticRecord", record.Value.Provenance);
+ Assert.Equal("Passed:40mm > 0mm && 25mm > 0mm", expansion.RequireResults!["Positive"]);
+ Assert.Equal(expansion.SpecializationIdentity, Assert.Single(second.Document!.ConceptIr!.TemplateInstantiations!).SpecializationIdentity);
+ Assert.Equal([40d, 20d, 25d], first.Document.Solid.Box!.Size);
+ Assert.DoesNotContain("Static", first.Document.ConceptIr.MaterializedStruct.SourceSpelling, StringComparison.Ordinal);
+ Assert.DoesNotContain("Template", first.Document.ConceptIr.MaterializedStruct.SourceSpelling, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void TypedRecordParameter_ReportsTypedBindingAndMemberDiagnostics()
+ {
+ var wrong = FirmamentV2Parser.Parse(WidgetSource("Bad").Replace("Spec: TallWidget", "Spec: OtherValue", StringComparison.Ordinal) + "\nRecord OtherSpec { Width: Length Height: Length Depth: Length }\nStatic OtherValue: OtherSpec = OtherSpec { Width: 1mm Height: 1mm Depth: 1mm }");
+ Assert.Contains(wrong.Diagnostics, d => d.StartsWith("firmament-template-record-argument-type-mismatch:Spec:expected-WidgetSpec:actual-OtherSpec", StringComparison.Ordinal));
+
+ var unknown = FirmamentV2Parser.Parse(WidgetSource("Bad").Replace("Spec: TallWidget", "Spec: Missing", StringComparison.Ordinal));
+ Assert.Contains(unknown.Diagnostics, d => d.StartsWith("firmament-template-unknown-static-record-value:Spec:Missing", StringComparison.Ordinal));
+
+ var collection = WidgetSource("Bad").Replace("Spec: TallWidget", "Spec: WidgetValues", StringComparison.Ordinal)
+ + "\nStatic WidgetValues: WidgetSpec[] = [WidgetSpec { Width: 40mm Height: 25mm Depth: 20mm }]";
+ var collectionParse = FirmamentV2Parser.Parse(collection);
+ Assert.Contains(collectionParse.Diagnostics, d => d.StartsWith("firmament-template-record-collection-scalar-mismatch:Spec", StringComparison.Ordinal));
+
+ var member = FirmamentV2Parser.Parse(WidgetSource("Bad").Replace("Spec.Height", "Spec.MissingHeight", StringComparison.Ordinal));
+ Assert.Contains(member.Diagnostics, d => d.StartsWith("firmament-template-unknown-record-member:Spec.MissingHeight", StringComparison.Ordinal));
+
+ var runtime = FirmamentV2Parser.Parse(WidgetSource("Bad").Replace("Spec: TallWidget", "Spec: RuntimeWidget", StringComparison.Ordinal) + "\nStruct RuntimeWidget { Box Runtime { Size: [1mm, 1mm, 1mm] } }");
+ Assert.Contains(runtime.Diagnostics, d => d.StartsWith("firmament-template-materialized-value-not-compile-time-record:Spec:RuntimeWidget", StringComparison.Ordinal));
+ }
+
[Theory]
[InlineData("CompactBracket", "60mm", "40mm", "20mm", "Compact", 60d, 40d, 20d)]
[InlineData("StandardBracket", "80mm", "50mm", "25mm", "Standard", 80d, 50d, 25d)]
@@ -130,4 +173,50 @@ public sealed class FirmamentV2TemplateExpansionTests
}
Struct {{instance}} = MountingBracket < TBody: Box, {{(width.Length == 0 ? string.Empty : "Width: " + width + ",")}} Depth: {{depth}}, Height: {{height}}, Variant: {{variant}} >
""";
+
+ private static string WidgetSource(string instance) => $$"""
+ Concept WidgetConcept {
+ Bounds: Box3
+ TopPlane: Plane
+ ChamferDistance: Length
+ }
+ Record WidgetSpec {
+ Width: Length
+ Height: Length
+ Depth: Length
+ }
+ Static TallWidget: WidgetSpec = WidgetSpec {
+ Width: 40mm
+ Height: 25mm
+ Depth: 20mm
+ }
+ Template < Spec: WidgetSpec >
+ Struct Widget: WidgetConcept {
+ Require Positive => Spec.Width > 0mm && Spec.Height > 0mm
+ Concept Struct Design: WidgetConcept {
+ Bounds: Box3 {
+ Size: [Spec.Width, Spec.Depth, Spec.Height]
+ }
+ TopPlane: Bounds.Face(+Z)
+ ChamferDistance: 1mm
+ }
+ Box Body {
+ Bounds: Design.Bounds
+ }
+ Modify Body {
+ EdgeFinish TopBreak {
+ Face: Design.TopPlane
+ Target: Boundary
+ Kind: Chamfer
+ Distance: Design.ChamferDistance
+ }
+ }
+ Expose {
+ Bounds: Design.Bounds
+ TopPlane: Body.Top
+ ChamferDistance: Design.ChamferDistance
+ }
+ }
+ Struct {{instance}} = Widget < Spec: TallWidget >
+ """;
}
diff --git a/Aetheris.Kernel.Firmament.Tests/HexBoltTemplateM2Tests.cs b/Aetheris.Kernel.Firmament.Tests/HexBoltTemplateM2Tests.cs
new file mode 100644
index 00000000..eb1258aa
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/HexBoltTemplateM2Tests.cs
@@ -0,0 +1,97 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.RegularExpressions;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Curves;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.StandardLibrary;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class HexBoltTemplateM2Tests
+{
+ private static string FixturePath => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../testdata/firmament/examples/hexbolt_template_m2.firmament"));
+
+ [Fact]
+ public void CanonicalTemplate_IsConceptConstrainedTypedRecordAuthoredAndHasNoStandardPartHook()
+ {
+ var source = File.ReadAllText(FixturePath);
+ Assert.DoesNotContain("StandardPart", source, StringComparison.Ordinal);
+ var parse = FirmamentV2Parser.Parse(source, Path.GetDirectoryName(FixturePath));
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ Assert.IsType<FirmamentV2ExactCoaxialPartRecord>(parse.Document!.Solid.Primitive);
+ var instance = Assert.Single(parse.Document.ConceptIr!.TemplateInstantiations!);
+ Assert.Equal("HexBolt", instance.Template);
+ Assert.Equal("ReferenceBolt", instance.Instance);
+ var spec = Assert.Single(instance.RecordArguments!).Value;
+ Assert.Equal("HexBoltSpec", spec.RecordType);
+ Assert.Equal("McMaster91180A151", spec.StaticValue);
+ Assert.Equal("Passed:22mm >= 0mm && 22mm <= 35mm", instance.RequireResults!["ThreadFits"]);
+ Assert.Equal("Valid", parse.Document.ConceptIr.MaterializedStruct.Conformance);
+ Assert.Equal("BoltConcept", Assert.Single(parse.Document.ConceptIr.MaterializedStruct.Satisfies));
+ }
+
+ [Theory]
+ [InlineData("McMaster91180A151", 8d, 35d)]
+ [InlineData("M10x50", 10d, 50d)]
+ [InlineData("Nonstandard825x375", 8.25d, 37.5d)]
+ public void SameTemplate_MaterializesReferenceStandardAndNonstandardExactBolts(string staticName, double diameter, double length)
+ {
+ var source = File.ReadAllText(FixturePath).Replace("Spec: McMaster91180A151", "Spec: " + staticName, StringComparison.Ordinal);
+ var tempSource = Path.Combine(Path.GetTempPath(), $"aetheris-hexbolt-m2-{Guid.NewGuid():N}.firmament");
+ var tempStep = Path.ChangeExtension(tempSource, ".step");
+ File.WriteAllText(tempSource, source);
+ try
+ {
+ var first = FirmamentBuildAndExport.Run(tempSource, tempStep);
+ var second = FirmamentBuildAndExport.Run(tempSource, tempStep);
+ Assert.True(first.IsSuccess, string.Join(Environment.NewLine, first.Diagnostics.Select(d => d.Message)));
+ Assert.True(second.IsSuccess, string.Join(Environment.NewLine, second.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(Hash(first.Value.Export.StepText), Hash(second.Value.Export.StepText));
+ Assert.DoesNotContain("B_SPLINE", first.Value.Export.StepText, StringComparison.Ordinal);
+ Assert.Equal(6, Regex.Matches(first.Value.Export.StepText, "HYPERBOLA\\(", RegexOptions.CultureInvariant).Count);
+ Assert.Equal(2, Regex.Matches(first.Value.Export.StepText, "CONICAL_SURFACE\\(", RegexOptions.CultureInvariant).Count);
+ var imported = Step242Importer.ImportBody(first.Value.Export.StepText);
+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics));
+ Assert.True(BrepExportPreflight.Validate(imported.Value).IsValid);
+ var xs = imported.Value.Topology.Vertices.Select(vertex => imported.Value.TryGetVertexPoint(vertex.Id, out var point) ? point.X : double.NaN).ToArray();
+ Assert.Equal(length, xs.Max(), 9);
+ Assert.Equal(diameter, double.Parse(first.Value.Export.StandardPart!.Parameters["NominalDiameter"][..^2], System.Globalization.CultureInfo.InvariantCulture), 9);
+ Assert.Contains(first.Value.Export.StandardPart.SemanticDescendants, item => item.StableId.EndsWith(".ThreadRegion", StringComparison.Ordinal));
+ }
+ finally
+ {
+ if (File.Exists(tempSource)) File.Delete(tempSource);
+ if (File.Exists(tempStep)) File.Delete(tempStep);
+ }
+ }
+
+ [Fact]
+ public void ReferenceTemplateAndM1Oracle_AgreeOnExactEngineeringInvariants()
+ {
+ var output = Path.Combine(Path.GetTempPath(), $"aetheris-hexbolt-m2-{Guid.NewGuid():N}.step");
+ try
+ {
+ var m2 = FirmamentBuildAndExport.Run(FixturePath, output);
+ Assert.True(m2.IsSuccess, string.Join(Environment.NewLine, m2.Diagnostics.Select(d => d.Message)));
+ var imported = Step242Importer.ImportBody(m2.Value.Export.StepText);
+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics));
+ var m1 = HexBoltBuilder.Create(McMasterHexBoltSpecs.Reference91180A151, "McMaster91180A151").Value;
+ var m1Imported = Step242Importer.ImportBody(Step242Exporter.ExportBody(m1.Body).Value).Value;
+ Assert.Equal(m1Imported.Topology.Vertices.Count(), imported.Value.Topology.Vertices.Count());
+ Assert.Equal(m1Imported.Topology.Edges.Count(), imported.Value.Topology.Edges.Count());
+ Assert.Equal(m1Imported.Topology.Faces.Count(), imported.Value.Topology.Faces.Count());
+ Assert.Equal(m1Imported.Geometry.Curves.Count(pair => pair.Value.Kind == CurveGeometryKind.Hyperbola3), imported.Value.Geometry.Curves.Count(pair => pair.Value.Kind == CurveGeometryKind.Hyperbola3));
+ foreach (var kind in new[] { SurfaceGeometryKind.Plane, SurfaceGeometryKind.Cylinder, SurfaceGeometryKind.Cone, SurfaceGeometryKind.Torus })
+ Assert.Equal(m1Imported.Geometry.Surfaces.Count(pair => pair.Value.Kind == kind), imported.Value.Geometry.Surfaces.Count(pair => pair.Value.Kind == kind));
+ Assert.Equal(m1.Semantics.Descendants.Select(item => item.StableId), m2.Value.Export.StandardPart!.SemanticDescendants.Select(item => item.StableId));
+ Assert.Equal(m1.DeterministicSignature, m2.Value.Export.StandardPart.DeterministicSignature);
+ }
+ finally { if (File.Exists(output)) File.Delete(output); }
+ }
+
+ private static string Hash(string text) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant();
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 05db532c..489af242 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -98,7 +98,13 @@ public static class FirmamentBuildAndExport
// parser admission alone is insufficient because the profile/composition
// materializers read source declarations directly.
var staticDiagnostics = new List<string>();
- var staticExpansion = CanonicalStaticAuthoring.Expand(sourceText, staticDiagnostics);
+ var templateExpansion = FirmamentV2TemplateExpansion.Expand(sourceText, staticDiagnostics);
+ if (templateExpansion 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.TemplateExpansion")).ToArray());
+ }
+ var staticExpansion = CanonicalStaticAuthoring.Expand(templateExpansion.Source, staticDiagnostics);
if (staticExpansion is null)
{
return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics
@@ -193,6 +199,11 @@ public static class FirmamentBuildAndExport
return roundedBoxExport;
}
+ if (TryExportV2ExactCoaxialPart(v2Parse.Document) is { } exactCoaxialExport)
+ {
+ return exactCoaxialExport;
+ }
+
if (TryExportV2StandardPart(v2Parse.Document) is { } standardPartExport)
{
return standardPartExport;
@@ -327,6 +338,25 @@ public static class FirmamentBuildAndExport
StandardPart: report));
}
+ private static KernelResult<FirmamentStepExportResult>? TryExportV2ExactCoaxialPart(FirmamentV2Document document)
+ {
+ if (document.Solids.Count != 1 || document.Solid.ExactCoaxialPart is not { } authored) return null;
+ var recipe = ExactCoaxialPartBuilder.Bind(authored.Parameters);
+ if (!recipe.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(recipe.Diagnostics);
+ var built = ExactCoaxialPartBuilder.Create(recipe.Value);
+ if (!built.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(built.Diagnostics);
+ var step = Step242Exporter.ExportBody(built.Value.Body);
+ if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
+ var instantiation = document.ConceptIr?.TemplateInstantiations?.SingleOrDefault();
+ var record = instantiation?.RecordArguments?.SingleOrDefault().Value;
+ var parameters = record?.Members ?? authored.Parameters;
+ var semantics = built.Value.Semantics.Descendants.Select(descendant => new FirmamentStandardPartSemanticReport(
+ descendant.StableId, descendant.Kind.ToString(), descendant.ParentStableId, descendant.Face?.Value, descendant.Metadata)).ToArray();
+ var report = new FirmamentStandardPartReport("ExactCoaxialPart", instantiation?.Template, built.Value.DeterministicSignature, parameters, semantics);
+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, built.Value.Semantics.BodyStableId, 0,
+ "template-exact-construction", "ExactCoaxialPart", ConceptIr: document.ConceptIr, StandardPart: report));
+ }
+
private static KernelResult<FirmamentStepExportResult> ExportComposedSemanticTopBoundaryChamfer(
string source, PrismaticProfileCompositionParseResult parsed, PrismaticSectionStackConstruction stack, PrismaticSectionStackEmissionResult emitted,
FirmamentV2Document? canonicalDocument)
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
index df3892c9..16a62c82 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
@@ -20,6 +20,7 @@ internal static class CanonicalStaticAuthoring
var names = new HashSet<string>(StringComparer.Ordinal);
var recordTypes = new List<FirmamentV2RecordTypeDecl>();
var arrays = new List<FirmamentV2StaticArrayDecl>();
+ var staticRecords = new List<FirmamentV2StaticRecordDecl>();
var templates = new List<Template>();
var patterns = new List<FirmamentV2CanonicalPatternDecl>();
var requires = new List<FirmamentV2RequireDecl>();
@@ -37,6 +38,22 @@ internal static class CanonicalStaticAuthoring
}
var recordByName = recordTypes.ToDictionary(x => x.Name, StringComparer.Ordinal);
+ foreach (Match header in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\s*=\s*(?<literal>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
+ {
+ var open = source.IndexOf('{', header.Index); var close = MatchPair(source, open, '{', '}');
+ var name = header.Groups["name"].Value; var type = header.Groups["type"].Value; var literalType = header.Groups["literal"].Value;
+ if (close < 0 || !recordByName.TryGetValue(type, out var record)) { diagnostics.Add(Prefix + "record-type-invalid:" + name); continue; }
+ if (!string.Equals(type, literalType, StringComparison.Ordinal)) { diagnostics.Add(Prefix + "record-literal-type-mismatch:" + name); continue; }
+ if (!names.Add(name)) { diagnostics.Add(FirmamentV2Parser.DuplicateName + ":Static:" + name); continue; }
+ var values = Fields(source[(open + 1)..close]);
+ var missing = record.Fields.Keys.Where(field => !values.ContainsKey(field)).ToArray();
+ var extra = values.Keys.Where(field => !record.Fields.ContainsKey(field)).ToArray();
+ if (missing.Length > 0) diagnostics.Add(Prefix + "record-missing-field:" + name + ":" + string.Join(",", missing));
+ if (extra.Length > 0) diagnostics.Add(Prefix + "record-extra-field:" + name + ":" + string.Join(",", extra));
+ staticRecords.Add(new(name, type, values, new(header.Index, close - header.Index + 1)));
+ changes.Add((header.Index, close - header.Index + 1, string.Empty));
+ }
+
foreach (Match header in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\[\]\s*=\s*\[", RegexOptions.CultureInvariant))
{
var open = source.IndexOf('[', header.Index + header.Value.LastIndexOf('[')); var close = MatchPair(source, open, '[', ']');
@@ -155,7 +172,7 @@ internal static class CanonicalStaticAuthoring
.Where(change => !erasures.Any(erase => erase.Start < change.Start && change.Start < erase.Start + erase.Length))
.OrderByDescending(change => change.Start))
source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
- return new(source, new(recordTypes, arrays, templates.Select(t => new FirmamentV2CanonicalTemplateDecl(t.Name, t.Type, t.Parameter, t.Body, t.Span)).ToArray(), patterns, requires, semanticConstraints, projections));
+ return new(source, new(recordTypes, arrays, templates.Select(t => new FirmamentV2CanonicalTemplateDecl(t.Name, t.Type, t.Parameter, t.Body, t.Span)).ToArray(), patterns, requires, semanticConstraints, projections, staticRecords));
}
private static string? Instantiate(Template template, IReadOnlyDictionary<string, string> values, string id, bool patterned, List<string> diagnostics)
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
index 78bc81ba..5f41d4bf 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
@@ -106,6 +106,12 @@ public sealed record ConceptIrStaticSelection(
FirmamentV2SourceSpan SourceSpan,
string Provenance);
public sealed record ConceptIrPatternExpansion(string Pattern, string Source, string ElementType, int Count, IReadOnlyList<string> GeneratedDeclarations, FirmamentV2SourceSpan SourceSpan, string Status = "ExpandedBeforeFeatureAir");
+public sealed record ConceptIrTemplateRecordArgument(
+ string RecordType,
+ string StaticValue,
+ IReadOnlyDictionary<string, string> Members,
+ FirmamentV2SourceSpan SourceSpan,
+ string Provenance);
/// <summary>Source-map-only evidence for a compile-time template expansion. This is deliberately not AIR.</summary>
public sealed record ConceptIrTemplateInstantiation(
string Template,
@@ -118,7 +124,9 @@ public sealed record ConceptIrTemplateInstantiation(
FirmamentV2SourceSpan TemplateSourceSpan,
FirmamentV2SourceSpan ApplicationSourceSpan,
string Status = "ExpandedBeforeFeatureAir",
- IReadOnlyDictionary<string, string>? SelectedMatchArms = null);
+ IReadOnlyDictionary<string, string>? SelectedMatchArms = null,
+ IReadOnlyDictionary<string, ConceptIrTemplateRecordArgument>? RecordArguments = null,
+ IReadOnlyDictionary<string, string>? RequireResults = null);
public sealed record ConceptIrDocument(
IReadOnlyList<ConceptIrDefinition> Concepts,
IReadOnlyList<ConceptIrStructInstance> Structs,
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 333d2942..435e3cdf 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -58,6 +58,7 @@ public sealed record FirmamentV2SolidBinding(string Name, string RecordType, Fir
public FirmamentV2RoundedBoxRecord? RoundedBox => Primitive as FirmamentV2RoundedBoxRecord;
public FirmamentV2InlineStepRecord? InlineStep => Primitive as FirmamentV2InlineStepRecord;
public FirmamentV2StandardPartRecord? StandardPart => Primitive as FirmamentV2StandardPartRecord;
+ public FirmamentV2ExactCoaxialPartRecord? ExactCoaxialPart => Primitive as FirmamentV2ExactCoaxialPartRecord;
}
public abstract record FirmamentV2PrimitiveRecord;
@@ -76,6 +77,9 @@ public sealed record FirmamentV2AdvancedMaterialRecord(string Kind) : FirmamentV
public sealed record FirmamentV2StandardPartRecord(
string Family,
IReadOnlyDictionary<string, string> Parameters) : FirmamentV2PrimitiveRecord;
+/// <summary>A bounded exact analytic construction recipe assembled from reusable
+/// regular-prism, coaxial cone, torus-blend, cylinder, and cone-frustum operations.</summary>
+public sealed record FirmamentV2ExactCoaxialPartRecord(IReadOnlyDictionary<string, string> Parameters) : FirmamentV2PrimitiveRecord;
public sealed record FirmamentV2InlineStepRecord(string SourcePath, string NormalizedPath, string ContentHash, bool CanonicalInput, string CanonicalEvidence, ImportedStepTopologyMap TopologyMap) : FirmamentV2PrimitiveRecord;
public sealed record ImportedStepTopologyMap(IReadOnlyDictionary<string, string> FaceEntityToFaceId, IReadOnlyDictionary<string, string> FaceIdToFaceEntity)
{
@@ -222,9 +226,10 @@ public sealed record FirmamentV2ProfileDecl(string Name, string Frame, double Fr
public sealed record FirmamentV2ComposeDecl(string Name, IReadOnlyList<string> Operations, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2SelectionDecl(string Name, string Target, string Source, string Requirement, FirmamentV2SourceSpan SourceSpan);
/// <summary>Normalized, erased-before-materialization evidence for canonical static authoring.</summary>
-public sealed record FirmamentV2StaticAuthoringDocument(IReadOnlyList<FirmamentV2RecordTypeDecl> RecordTypes, IReadOnlyList<FirmamentV2StaticArrayDecl> Arrays, IReadOnlyList<FirmamentV2CanonicalTemplateDecl> Templates, IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, IReadOnlyList<FirmamentV2RequireDecl> Requires, IReadOnlyList<FirmamentV2SemanticConstraint>? SemanticConstraints = null, IReadOnlyDictionary<string, FirmamentV2PmiProjection>? PmiProjections = null);
+public sealed record FirmamentV2StaticAuthoringDocument(IReadOnlyList<FirmamentV2RecordTypeDecl> RecordTypes, IReadOnlyList<FirmamentV2StaticArrayDecl> Arrays, IReadOnlyList<FirmamentV2CanonicalTemplateDecl> Templates, IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, IReadOnlyList<FirmamentV2RequireDecl> Requires, IReadOnlyList<FirmamentV2SemanticConstraint>? SemanticConstraints = null, IReadOnlyDictionary<string, FirmamentV2PmiProjection>? PmiProjections = null, IReadOnlyList<FirmamentV2StaticRecordDecl>? StaticRecords = null);
public sealed record FirmamentV2RecordTypeDecl(string Name, IReadOnlyDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2StaticArrayDecl(string Name, string ElementType, IReadOnlyList<IReadOnlyDictionary<string, string>> Elements, FirmamentV2SourceSpan SourceSpan);
+public sealed record FirmamentV2StaticRecordDecl(string Name, string RecordType, IReadOnlyDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2CanonicalTemplateDecl(string Name, string ParameterType, string ParameterName, string Body, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2CanonicalPatternDecl(string Name, string Source, string Template, int GeneratedCount, IReadOnlyList<string> GeneratedIds, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2RequireDecl(string Name, string Expression, bool Value, FirmamentV2SourceSpan SourceSpan, string? Provenance = null, string? Subject = null, string? Expected = null, string? ToleranceSource = null);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index e89985f4..4291b9d2 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -280,7 +280,7 @@ public static class FirmamentV2Parser
private static readonly Regex FillRegionHeaderRegex = new(@"\bregion\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex FillHeaderRegex = new(@"\bfill\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex CanonicalModelRegex = new(@"^\s*Model\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
- private static readonly Regex CanonicalPrimitiveHeaderRegex = new(@"\b(?<type>Box|Cylinder|RoundedBox|Frustum|StandardPart)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
+ private static readonly Regex CanonicalPrimitiveHeaderRegex = new(@"\b(?<type>Box|Cylinder|RoundedBox|Frustum|StandardPart|ExactCoaxialPart)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex CanonicalInlineStepHeaderRegex = new(@"\bInlineStep\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex CanonicalModifyHeaderRegex = new(@"\bModify\s+(?<target>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
// Match the declaration-shaped header first; variant admission belongs in the
@@ -306,15 +306,9 @@ public static class FirmamentV2Parser
var v2AdmissionCandidate = IsV2AdmissionCandidate(source);
conceptCatalog ??= FirmamentV2ForgeConceptRegistry.Catalog;
- var canonicalStaticExpansion = CanonicalStaticAuthoring.Expand(source, diagnostics);
- if (canonicalStaticExpansion is null)
- {
- diagnostics.Add("firmament-v2-parse-failed");
- return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray(),
- v2AdmissionCandidate ? FirmamentV2ParseDisposition.RecognizedInvalid : FirmamentV2ParseDisposition.NotRecognized);
- }
- source = canonicalStaticExpansion.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.
var templateExpansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics);
if (templateExpansion is null)
{
@@ -324,6 +318,15 @@ public static class FirmamentV2Parser
v2AdmissionCandidate ? FirmamentV2ParseDisposition.RecognizedInvalid : FirmamentV2ParseDisposition.NotRecognized);
}
source = templateExpansion.Source;
+
+ var canonicalStaticExpansion = CanonicalStaticAuthoring.Expand(source, diagnostics);
+ if (canonicalStaticExpansion is null)
+ {
+ diagnostics.Add("firmament-v2-parse-failed");
+ return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray(),
+ v2AdmissionCandidate ? FirmamentV2ParseDisposition.RecognizedInvalid : FirmamentV2ParseDisposition.NotRecognized);
+ }
+ source = canonicalStaticExpansion.Source;
v2AdmissionCandidate |= IsV2AdmissionCandidate(source);
// Canonical V2 is parsed as one document, before compatibility adapters. The
@@ -884,7 +887,7 @@ public static class FirmamentV2Parser
var known = new HashSet<string>(StringComparer.Ordinal)
{
- "Box", "Cylinder", "RoundedBox", "Frustum", "StandardPart", "Concept", "Struct", "Construction", "Profile", "Compose", "EdgeFinish",
+ "Box", "Cylinder", "RoundedBox", "Frustum", "StandardPart", "ExactCoaxialPart", "Concept", "Struct", "Construction", "Profile", "Compose", "EdgeFinish",
"Record", "Static", "Template", "Selection", "InlineStep", "Recognize", "Replace", "Pmi", "Modify", "Match", "Require", "Assert"
};
var compatibilityOnly = new HashSet<string>(StringComparer.Ordinal)
@@ -939,6 +942,9 @@ public static class FirmamentV2Parser
return CanonicalFailure(diagnostics, CanonicalDeclarationUnrecognized);
var adapterSource = Regex.Replace(body, @"(?m)^\s*Units\s*:\s*mm\s*$", string.Empty, RegexOptions.CultureInvariant);
+ if (TryParseExactCoaxialTemplateDocument(adapterSource, model.Groups["name"].Value, templateInstantiations, diagnostics, out var exactDocument))
+ return FirmamentV2ParseResult.Success(exactDocument!, diagnostics.Append("firmament-v2-exact-coaxial-template-parsed").Append("firmament-v2-parse-succeeded").Distinct(StringComparer.Ordinal).Order().ToArray());
+
if (PrismaticProfileCompositionParser.IsCompositionSource(adapterSource))
{
var composition = PrismaticProfileCompositionParser.Parse(adapterSource);
@@ -1053,6 +1059,59 @@ public static class FirmamentV2Parser
return FirmamentV2ParseResult.Success(normalized, diagnostics.Distinct(StringComparer.Ordinal).ToArray());
}
+ private static bool TryParseExactCoaxialTemplateDocument(string source, string modelName, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations,
+ List<string> diagnostics, out FirmamentV2Document? document)
+ {
+ document = null;
+ var primitive = Regex.Match(source, @"\bExactCoaxialPart\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
+ if (!primitive.Success) return false;
+ var open = source.IndexOf('{', primitive.Index); var close = FindMatchingBrace(source, open);
+ var materialized = Regex.Match(source, @"\bStruct\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<concept>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
+ if (close < 0 || !materialized.Success) { diagnostics.Add(CanonicalPrimitiveMalformed); return false; }
+ if (ParseCanonicalPrimitive("ExactCoaxialPart", source[(open + 1)..close], diagnostics) is not FirmamentV2ExactCoaxialPartRecord recipe)
+ { diagnostics.Add(CanonicalPrimitiveMalformed); return false; }
+
+ static string TextValue(string value) => value.Length >= 2 && value[0] == '"' && value[^1] == '"' ? value[1..^1] : value;
+ var instanceName = materialized.Groups["name"].Value; var conceptName = materialized.Groups["concept"].Value;
+ var conceptSpan = new FirmamentV2SourceSpan(materialized.Index, 0);
+ var conceptHeader = Regex.Match(source, $@"\bConcept\s+{Regex.Escape(conceptName)}\s*\{{", RegexOptions.CultureInvariant);
+ var conceptOpen = conceptHeader.Success ? source.IndexOf('{', conceptHeader.Index) : -1;
+ var conceptClose = conceptOpen >= 0 ? FindMatchingBrace(source, conceptOpen) : -1;
+ if (conceptClose < 0) { diagnostics.Add(ConceptUnknownConcept); return false; }
+ var requirements = Regex.Matches(source[(conceptOpen + 1)..conceptClose], @"(?m)^\s*(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\s*$", RegexOptions.CultureInvariant)
+ .Cast<Match>().ToDictionary(match => match.Groups["name"].Value,
+ match => new ConceptIrMemberRequirement(match.Groups["name"].Value, new(match.Groups["type"].Value), conceptSpan), StringComparer.Ordinal);
+ var materializedOpen = source.IndexOf('{', materialized.Index); var materializedClose = FindMatchingBrace(source, materializedOpen);
+ var materializedBody = source[(materializedOpen + 1)..materializedClose];
+ var expose = Regex.Match(materializedBody, @"\bExpose\s*\{(?<body>.*?)\}", RegexOptions.Singleline | RegexOptions.CultureInvariant);
+ if (!expose.Success) { diagnostics.Add(ConceptIrResolver.MissingMember + ":" + instanceName); return false; }
+ var exposedSources = Regex.Matches(expose.Groups["body"].Value, @"(?m)^\s*(?<name>[A-Za-z_]\w*)\s*:\s*(?<value>[^\r\n}]+?)\s*$", RegexOptions.CultureInvariant)
+ .Cast<Match>().ToDictionary(match => match.Groups["name"].Value, match => match.Groups["value"].Value.Trim(), StringComparer.Ordinal);
+ var values = new List<ConceptIrValue>(); var exposed = new List<ConceptIrSemanticMember>();
+ foreach (var requirement in requirements.Values)
+ {
+ if (!exposedSources.TryGetValue(requirement.Name, out var authored)) { diagnostics.Add(ConceptIrResolver.MissingMember + $":{instanceName}.{requirement.Name}"); return false; }
+ var stableId = $"template:{instanceName}.{requirement.Name}"; ConceptIrValue? value = requirement.Type.Name switch
+ {
+ "Length" when Regex.Match(authored, @"^(?<n>[-+]?\d+(?:\.\d+)?)mm$") is { Success: true } length => new ConceptIrLengthValue(stableId, double.Parse(length.Groups["n"].Value, CultureInfo.InvariantCulture), "mm", authored),
+ "Angle" when Regex.Match(authored, @"^(?<n>[-+]?\d+(?:\.\d+)?)deg$") is { Success: true } angle => new ConceptIrAngleValue(stableId, double.Parse(angle.Groups["n"].Value, CultureInfo.InvariantCulture), "deg", authored),
+ "String" when authored.Length >= 2 && authored[0] == '"' && authored[^1] == '"' => new ConceptIrStringValue(stableId, TextValue(authored), authored),
+ "Axis" when authored.EndsWith(".Axis", StringComparison.Ordinal) || authored == "+X" => new ConceptIrAxisValue(stableId, new(0d, 0d, 0d), new(1d, 0d, 0d), authored),
+ _ => null
+ };
+ if (value is null) { diagnostics.Add(ConceptIrResolver.TypeMismatch + $":{instanceName}.{requirement.Name}:expected-{requirement.Type}:actual-{authored}"); return false; }
+ values.Add(value);
+ exposed.Add(new(requirement.Name, requirement.Type, value, null, ConceptIrSemanticPhase.ConceptIr,
+ ConceptIrMaterializationCategory.CompileTimeValue, value.Provenance, conceptSpan, $"materialized:{instanceName}.exposed:{requirement.Name}"));
+ }
+ var ir = new ConceptIrDocument(
+ [new ConceptIrDefinition(conceptName, requirements, conceptSpan)], [], values,
+ new(instanceName, "Struct", [conceptName], new(materialized.Index, materializedClose - materialized.Index + 1), exposed, "Valid"), [],
+ TemplateInstantiations: templateInstantiations ?? []);
+ document = new FirmamentV2Document(modelName, "mm", [new FirmamentV2SolidBinding(primitive.Groups["name"].Value, "ExactCoaxialPart", recipe)], ConceptIr: ir);
+ return true;
+ }
+
private static IReadOnlyList<FirmamentV2SelectionDecl> ParseCanonicalSelections(string body, int offset, List<string> diagnostics)
{
var selections = new List<FirmamentV2SelectionDecl>();
@@ -1372,6 +1431,13 @@ public static class FirmamentV2Parser
if (family.Length >= 2 && family[0] == '"' && family[^1] == '"') family = family[1..^1];
return string.IsNullOrWhiteSpace(family) ? null : new FirmamentV2StandardPartRecord(family, fields);
}
+ FirmamentV2ExactCoaxialPartRecord? ExactCoaxialPart()
+ {
+ var matches = Regex.Matches(body, "\\b(?<name>[A-Za-z_]\\w*)\\s*:\\s*(?<value>\"[^\"]*\"|[A-Za-z_]\\w*|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?)", RegexOptions.CultureInvariant).Cast<Match>().ToArray();
+ var fields = matches.GroupBy(match => match.Groups["name"].Value, StringComparer.Ordinal).ToDictionary(group => group.Key, group => group.Last().Groups["value"].Value, StringComparer.Ordinal);
+ var required = new[] { "StableId", "Sides", "AcrossFlats", "AxialHeight", "FlatDiameter", "ConeAngle", "BlendRadius", "ShaftDiameter", "AxialLength", "EndChamferLength", "EndDiameter", "SemanticAxialRegionLength", "Designation", "Grade" };
+ return required.All(fields.ContainsKey) ? new(fields) : null;
+ }
return type switch
{
"Box" when Size() is { } size => new FirmamentV2BoxRecord(size, []),
@@ -1379,6 +1445,7 @@ public static class FirmamentV2Parser
"RoundedBox" when Size() is { } roundedSize && Number("CornerRadius") is var corner && double.IsFinite(corner) && corner < double.Min(roundedSize[0], roundedSize[1]) / 2d => new FirmamentV2RoundedBoxRecord(roundedSize, corner),
"Frustum" when Number("BottomRadius") is var bottom && Number("TopRadius") is var top && Number("Height") is var frustumHeight && double.IsFinite(bottom) && double.IsFinite(top) && double.IsFinite(frustumHeight) && double.Abs(bottom - top) > 1e-12d => new FirmamentV2FrustumRecord(bottom, top, frustumHeight),
"StandardPart" => StandardPart(),
+ "ExactCoaxialPart" => ExactCoaxialPart(),
_ => null
};
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
index f5bbff29..a94b8d7d 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
@@ -14,7 +14,10 @@ internal sealed record TemplateTypeParameterIr(string Name, string ConstraintCon
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 TemplateRecordTypeIr(string Name, ImmutableDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);
+internal sealed record TemplateStaticRecordIr(string Name, string TypeName, ImmutableDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);
+internal sealed record BoundTemplateRecordIr(string Parameter, string TypeName, string StaticName, ImmutableDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);
+internal sealed record BoundTemplateArguments(ImmutableDictionary<string, string> TypeArguments, ImmutableDictionary<string, string> ValueArguments, ImmutableDictionary<string, BoundTemplateRecordIr> RecordArguments, 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>
@@ -36,6 +39,13 @@ internal static class FirmamentV2TemplateExpansion
internal const string RequireNonBool = Prefix + "require-non-bool";
internal const string Recursive = Prefix + "recursive-specialization";
internal const string ApplicationCycle = Prefix + "application-cycle";
+ internal const string UnknownRecordType = Prefix + "unknown-record-parameter-type";
+ internal const string UnknownStaticRecord = Prefix + "unknown-static-record-value";
+ internal const string WrongRecordType = Prefix + "record-argument-type-mismatch";
+ internal const string RecordCollectionMismatch = Prefix + "record-collection-scalar-mismatch";
+ internal const string UnknownRecordMember = Prefix + "unknown-record-member";
+ internal const string MaterializedRecordArgument = Prefix + "materialized-value-not-compile-time-record";
+ internal const string UnsupportedRecordValue = Prefix + "unsupported-record-value-form";
internal sealed record Result(string Source, IReadOnlyList<ConceptIrTemplateInstantiation> Instantiations);
@@ -49,23 +59,29 @@ internal static class FirmamentV2TemplateExpansion
if (HasErrors(diagnostics)) return null;
var enums = ParseEnums(source);
+ var recordTypes = ParseRecordTypes(source, diagnostics);
+ var staticRecords = ParseStaticRecords(source, recordTypes, enums, diagnostics);
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);
+ var bound = Bind(template, application, source, enums, recordTypes, staticRecords, 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;
+ if (!ValidateRecordMembers(body, bound, diagnostics)) continue;
body = Substitute(body, bound);
- if (!EvaluateRequires(body, application.InstanceName, diagnostics)) continue;
+ if (!EvaluateRequires(body, application.InstanceName, diagnostics, out var requireResults)) continue;
body = RemoveRequires(body);
changes.Add((application.SourceSpan.Start, application.SourceSpan.Length, $"{template.TargetKind} {application.InstanceName}{template.HeaderTail} {{{body}}}"));
+ var recordArguments = bound.RecordArguments.ToDictionary(pair => pair.Key, pair => new ConceptIrTemplateRecordArgument(
+ pair.Value.TypeName, pair.Value.StaticName, pair.Value.Fields, pair.Value.SourceSpan, "StaticRecord"), StringComparer.Ordinal);
instantiations.Add(new(template.Name, application.InstanceName, bound.TypeArguments, bound.ValueArguments, bound.DefaultedArguments,
- specialization.SpecializationIdentity, specialization.GeneratedDeclarationPaths, template.SourceSpan, application.SourceSpan, SelectedMatchArms: selectedMatches));
+ specialization.SpecializationIdentity, specialization.GeneratedDeclarationPaths, template.SourceSpan, application.SourceSpan,
+ SelectedMatchArms: selectedMatches, RecordArguments: recordArguments, RequireResults: requireResults));
}
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);
@@ -129,11 +145,13 @@ internal static class FirmamentV2TemplateExpansion
return result.ToImmutable();
}
- private static BoundTemplateArguments? Bind(TemplateDeclarationIr template, TemplateApplicationIr application, string source, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums, List<string> diagnostics)
+ private static BoundTemplateArguments? Bind(TemplateDeclarationIr template, TemplateApplicationIr application, string source, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums,
+ IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes, IReadOnlyDictionary<string, TemplateStaticRecordIr> staticRecords, 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 types = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal); var values = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
+ var records = ImmutableDictionary.CreateBuilder<string, BoundTemplateRecordIr>(StringComparer.Ordinal); var defaults = ImmutableArray.CreateBuilder<string>();
var resolving = new List<string>();
string? Resolve(TemplateValueParameterIr p)
{
@@ -160,9 +178,36 @@ internal static class FirmamentV2TemplateExpansion
else if (!Satisfies(value, type.ConstraintConcept, source)) diagnostics.Add(ConstraintFailure + $":{type.Name}:{value}:{type.ConstraintConcept}");
types[type.Name] = value;
}
- else _ = Resolve((TemplateValueParameterIr)parameter);
+ else
+ {
+ var valueParameter = (TemplateValueParameterIr)parameter;
+ if (recordTypes.TryGetValue(valueParameter.TypeName, out var recordType)) BindRecord(valueParameter, recordType);
+ else if (IsBuiltInValueType(valueParameter.TypeName, enums)) _ = Resolve(valueParameter);
+ else diagnostics.Add(UnknownRecordType + $":{valueParameter.Name}:{valueParameter.TypeName}");
+ }
+ }
+ return HasErrors(diagnostics) ? null : new(types.ToImmutable(), values.ToImmutable(), records.ToImmutable(), defaults.ToImmutable());
+
+ void BindRecord(TemplateValueParameterIr parameter, TemplateRecordTypeIr recordType)
+ {
+ var expression = supplied.TryGetValue(parameter.Name, out var suppliedValue) ? suppliedValue : parameter.DefaultExpression;
+ if (expression is null) { diagnostics.Add(MissingArgument + ":" + parameter.Name); return; }
+ if (!supplied.ContainsKey(parameter.Name)) defaults.Add(parameter.Name);
+ if (Regex.IsMatch(source, $@"\bStatic\s+{Regex.Escape(expression)}\s*:\s*{Regex.Escape(recordType.Name)}\s*\[", RegexOptions.CultureInvariant))
+ { diagnostics.Add(RecordCollectionMismatch + $":{parameter.Name}:expected-{recordType.Name}:actual-collection"); return; }
+ if (staticRecords.TryGetValue(expression, out var staticRecord))
+ {
+ if (!string.Equals(staticRecord.TypeName, recordType.Name, StringComparison.Ordinal))
+ { diagnostics.Add(WrongRecordType + $":{parameter.Name}:expected-{recordType.Name}:actual-{staticRecord.TypeName}"); return; }
+ records[parameter.Name] = new(parameter.Name, recordType.Name, staticRecord.Name, staticRecord.Fields, staticRecord.SourceSpan);
+ values[parameter.Name] = staticRecord.Name;
+ return;
+ }
+ if (Regex.IsMatch(source, $@"\b(?:Struct|Model)\s+{Regex.Escape(expression)}\b", RegexOptions.CultureInvariant))
+ { diagnostics.Add(MaterializedRecordArgument + $":{parameter.Name}:{expression}"); return; }
+ if (Regex.IsMatch(expression, @"^[A-Za-z_]\w*$", RegexOptions.CultureInvariant)) diagnostics.Add(UnknownStaticRecord + $":{parameter.Name}:{expression}");
+ else diagnostics.Add(UnsupportedRecordValue + $":{parameter.Name}:{expression}");
}
- 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(
@@ -171,10 +216,53 @@ internal static class FirmamentV2TemplateExpansion
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),
+ "Angle" => Regex.IsMatch(value, @"^[-+]?[0-9]+(?:\.[0-9]+)?deg$", RegexOptions.CultureInvariant),
+ "String" => Regex.IsMatch(value, "^\"[^\"]*\"$", 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 IsBuiltInValueType(string type, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums) =>
+ type is "Length" or "Angle" or "String" or "int" or "float" or "bool" || enums.ContainsKey(type);
+
+ private static IReadOnlyDictionary<string, TemplateRecordTypeIr> ParseRecordTypes(string source, List<string> diagnostics)
+ {
+ var result = new Dictionary<string, TemplateRecordTypeIr>(StringComparer.Ordinal);
+ foreach (Match header in Regex.Matches(source, @"\bRecord\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
+ {
+ var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}');
+ if (close < 0) continue;
+ var fields = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
+ foreach (Match field in Regex.Matches(source[(open + 1)..close], @"\b(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)", RegexOptions.CultureInvariant))
+ fields[field.Groups["name"].Value] = field.Groups["type"].Value;
+ result[header.Groups["name"].Value] = new(header.Groups["name"].Value, fields.ToImmutable(), new(header.Index, close - header.Index + 1));
+ }
+ return result;
+ }
+
+ private static IReadOnlyDictionary<string, TemplateStaticRecordIr> ParseStaticRecords(string source, IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes,
+ IReadOnlyDictionary<string, ImmutableHashSet<string>> enums, List<string> diagnostics)
+ {
+ var result = new Dictionary<string, TemplateStaticRecordIr>(StringComparer.Ordinal);
+ foreach (Match header in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\s*=\s*(?<literal>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
+ {
+ var name = header.Groups["name"].Value; var typeName = header.Groups["type"].Value; var literalType = header.Groups["literal"].Value;
+ var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}');
+ if (close < 0 || !recordTypes.TryGetValue(typeName, out var recordType)) continue;
+ if (!string.Equals(typeName, literalType, StringComparison.Ordinal)) { diagnostics.Add(WrongRecordType + $":{name}:expected-{typeName}:actual-{literalType}"); continue; }
+ var fields = ParseRecordFields(source[(open + 1)..close]);
+ foreach (var missing in recordType.Fields.Keys.Where(field => !fields.ContainsKey(field))) diagnostics.Add(Prefix + "record-missing-field:" + name + ":" + missing);
+ foreach (var extra in fields.Keys.Where(field => !recordType.Fields.ContainsKey(field))) diagnostics.Add(Prefix + "record-extra-field:" + name + ":" + extra);
+ foreach (var field in fields.Where(field => recordType.Fields.TryGetValue(field.Key, out var expected) && !TypeMatches(field.Value, expected, enums)))
+ diagnostics.Add(Prefix + "record-field-type-mismatch:" + name + "." + field.Key + ":expected-" + recordType.Fields[field.Key] + ":actual-" + field.Value);
+ result[name] = new(name, typeName, fields.ToImmutableDictionary(StringComparer.Ordinal), new(header.Index, close - header.Index + 1));
+ }
+ return result;
+ }
+
+ private static Dictionary<string, string> ParseRecordFields(string body) => Regex.Matches(body,
+ "\\b(?<name>[A-Za-z_]\\w*)\\s*:\\s*(?<value>\"[^\"]*\"|(?:Point2|Point3|Vector2|Vector3|Axis)\\s*\\([^)]*\\)|[A-Za-z_]\\w*|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?)",
+ RegexOptions.CultureInvariant).Cast<Match>().ToDictionary(m => m.Groups["name"].Value, m => m.Groups["value"].Value, StringComparer.Ordinal);
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)
{
@@ -183,7 +271,24 @@ internal static class FirmamentV2TemplateExpansion
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 Substitute(string body, BoundTemplateArguments bound)
+ {
+ foreach (var record in bound.RecordArguments.Values)
+ {
+ foreach (var field in record.Fields)
+ body = Regex.Replace(body, $@"\b{Regex.Escape(record.Parameter)}\s*\.\s*{Regex.Escape(field.Key)}\b", _ => field.Value, RegexOptions.CultureInvariant);
+ }
+ return bound.TypeArguments.Concat(bound.ValueArguments.Where(pair => !bound.RecordArguments.ContainsKey(pair.Key)))
+ .Aggregate(body, (result, pair) => Regex.Replace(result, $@"\b{Regex.Escape(pair.Key)}\b", pair.Value));
+ }
+ private static bool ValidateRecordMembers(string body, BoundTemplateArguments bound, List<string> diagnostics)
+ {
+ foreach (var record in bound.RecordArguments.Values)
+ foreach (var member in Regex.Matches(body, $@"\b{Regex.Escape(record.Parameter)}\s*\.\s*(?<member>[A-Za-z_]\w*)", RegexOptions.CultureInvariant)
+ .Cast<Match>().Select(match => match.Groups["member"].Value).Distinct(StringComparer.Ordinal))
+ if (!record.Fields.ContainsKey(member)) diagnostics.Add(UnknownRecordMember + $":{record.Parameter}.{member}:record-{record.TypeName}");
+ return !HasErrors(diagnostics);
+ }
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.
@@ -223,13 +328,17 @@ internal static class FirmamentV2TemplateExpansion
if (end < 0 || end > enclosingClose) end = enclosingClose;
return body[start..end].Trim();
}
- private static bool EvaluateRequires(string body, string instance, List<string> diagnostics)
+ private static bool EvaluateRequires(string body, string instance, List<string> diagnostics, out IReadOnlyDictionary<string, string> results)
{
+ var evidence = new Dictionary<string, string>(StringComparer.Ordinal);
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()}");
+ var name = require.Groups["name"].Value; var expression = require.Groups["expr"].Value.Trim();
+ if (!TryBool(expression, out var value)) { diagnostics.Add(RequireNonBool + ":" + name); evidence[name] = "Invalid:" + expression; }
+ else if (!value) { diagnostics.Add(RequireFailed + $":{instance}.{name}:{expression}"); evidence[name] = "Failed:" + expression; }
+ else evidence[name] = "Passed:" + expression;
}
+ results = evidence;
return !HasErrors(diagnostics);
}
private static bool TryBool(string expression, out bool result)
@@ -237,7 +346,7 @@ internal static class FirmamentV2TemplateExpansion
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);
+ var m = Regex.Match(clause, @"^(?<a>[-+]?[0-9]+(?:\.[0-9]+)?)(?<u>mm|deg)?\s*(?<op>>=|<=|>|<|==)\s*(?<b>[-+]?[0-9]+(?:\.[0-9]+)?)(?<u2>mm|deg)?$", 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 };
@@ -261,7 +370,8 @@ internal static class FirmamentV2TemplateExpansion
}
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));
+ var recordInput = args.RecordArguments.OrderBy(x => x.Key).SelectMany(x => x.Value.Fields.OrderBy(f => f.Key).Select(f => x.Key + "." + f.Key + "=" + f.Value));
+ var input = template.Name + "|" + application.InstanceName + "|" + string.Join("|", args.TypeArguments.Concat(args.ValueArguments).OrderBy(x => x.Key).Select(x => x.Key + "=" + x.Value).Concat(recordInput));
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();
diff --git a/Aetheris.Kernel.StandardLibrary/ExactCoaxialPart.cs b/Aetheris.Kernel.StandardLibrary/ExactCoaxialPart.cs
new file mode 100644
index 00000000..759f128f
--- /dev/null
+++ b/Aetheris.Kernel.StandardLibrary/ExactCoaxialPart.cs
@@ -0,0 +1,67 @@
+using System.Globalization;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Results;
+
+namespace Aetheris.Kernel.StandardLibrary;
+
+/// <summary>
+/// Domain-neutral bounded recipe for one connected coaxial analytic part made from
+/// a regular prism, an exact cone/plane trim, a toroidal transition, a cylindrical
+/// span, and a terminal conical frustum. The recipe is compiler machinery; names
+/// and engineering meaning are supplied by the Firmament Template.
+/// </summary>
+public sealed record ExactCoaxialPartRecipe(
+ string StableId,
+ int PolygonSides,
+ double AcrossFlats,
+ double PrismAxialHeight,
+ double TopFlatDiameter,
+ double TopConeAngleDegrees,
+ double BlendRadius,
+ double ShaftDiameter,
+ double AxialLength,
+ double EndChamferLength,
+ double EndDiameter,
+ double SemanticAxialRegionLength,
+ string SemanticDesignation,
+ string Grade);
+
+public static class ExactCoaxialPartBuilder
+{
+ public static KernelResult<HexBoltDefinition> Create(ExactCoaxialPartRecipe recipe)
+ {
+ if (recipe.PolygonSides != 6)
+ return KernelResult<HexBoltDefinition>.Failure([new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error,
+ "ExactCoaxialPart currently admits six-sided regular prisms; the construction node remains polygon-generic and diagnoses the bounded backend limit.", "ExactCoaxialPart.RegularPolygonPrism.Sides")]);
+ var spec = new HexBoltSpec(recipe.ShaftDiameter, recipe.AxialLength, recipe.AcrossFlats, recipe.PrismAxialHeight,
+ recipe.TopFlatDiameter, recipe.TopConeAngleDegrees, recipe.EndChamferLength, recipe.EndDiameter,
+ recipe.SemanticAxialRegionLength, recipe.SemanticDesignation, recipe.Grade, recipe.BlendRadius);
+ return HexBoltBuilder.Create(spec, recipe.StableId);
+ }
+
+ public static KernelResult<ExactCoaxialPartRecipe> Bind(IReadOnlyDictionary<string, string> fields)
+ {
+ string Text(string name) => Unquote(fields[name]);
+ bool Number(string name, string suffix, out double value)
+ {
+ value = double.NaN; var raw = fields.GetValueOrDefault(name, string.Empty);
+ return raw.EndsWith(suffix, StringComparison.Ordinal) && double.TryParse(raw[..^suffix.Length], NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);
+ }
+ var required = new[] { "StableId", "Sides", "AcrossFlats", "AxialHeight", "FlatDiameter", "ConeAngle", "BlendRadius", "ShaftDiameter", "AxialLength", "EndChamferLength", "EndDiameter", "SemanticAxialRegionLength", "Designation", "Grade" };
+ var missing = required.Where(name => !fields.ContainsKey(name)).ToArray();
+ if (missing.Length > 0) return Failure("missing-field:" + string.Join(",", missing));
+ if (!int.TryParse(fields["Sides"], NumberStyles.Integer, CultureInfo.InvariantCulture, out var sides)
+ || !Number("AcrossFlats", "mm", out var acrossFlats) || !Number("AxialHeight", "mm", out var height)
+ || !Number("FlatDiameter", "mm", out var flat) || !Number("ConeAngle", "deg", out var angle)
+ || !Number("BlendRadius", "mm", out var blend) || !Number("ShaftDiameter", "mm", out var diameter)
+ || !Number("AxialLength", "mm", out var length) || !Number("EndChamferLength", "mm", out var endLength)
+ || !Number("EndDiameter", "mm", out var endDiameter) || !Number("SemanticAxialRegionLength", "mm", out var semanticLength))
+ return Failure("invalid-scalar");
+ return KernelResult<ExactCoaxialPartRecipe>.Success(new(Text("StableId"), sides, acrossFlats, height, flat, angle, blend, diameter, length,
+ endLength, endDiameter, semanticLength, Text("Designation"), Text("Grade")));
+ }
+
+ private static string Unquote(string value) => value.Length >= 2 && value[0] == '"' && value[^1] == '"' ? value[1..^1] : value;
+ private static KernelResult<ExactCoaxialPartRecipe> Failure(string detail) => KernelResult<ExactCoaxialPartRecipe>.Failure([
+ new KernelDiagnostic(KernelDiagnosticCode.InvalidArgument, KernelDiagnosticSeverity.Error, "Invalid ExactCoaxialPart recipe: " + detail, "ExactCoaxialPart.Binding")]);
+}
diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
index 54111003..e86e9229 100644
--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
@@ -892,6 +892,7 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
[InlineData("ctc-01-x3", "profile:CentralHex.Outer.SouthEast")]
[InlineData("ctc-01-x4", "hole:Ctc01PrismaticBlockoutX4.LeftTopMount")]
[InlineData("hexbolt-m1", "McMaster91180A151.Head.TopChamfer")]
+ [InlineData("hexbolt-m2", "McMaster91180A151.Head.TopChamfer")]
public async Task CadmataFixture_LoadsCompilerBodyAndPublishedCorrespondence(string fixtureId, string expectedEntityId)
{
var document = await CreateDocumentAsync("/api/v1/documents");
@@ -915,14 +916,20 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
public async Task CadmataHexBoltV2Fixture_PublishesTemplateParametersAndGeneratedFaceOwnership()
{
var document = await CreateDocumentAsync("/api/v1/documents");
- var response = await _client.PostAsync($"/api/v1/documents/{document.Data!.DocumentId}/cadmata/fixtures/hexbolt-m1", null);
+ var response = await _client.PostAsync($"/api/v1/documents/{document.Data!.DocumentId}/cadmata/fixtures/hexbolt-m2", null);
response.EnsureSuccessStatusCode();
var loaded = await response.Content.ReadFromJsonAsync<ApiResponseDto<CadmataFixtureLoadResponseDto>>();
Assert.True(loaded!.Success);
var entities = loaded.Data!.Visualization.Entities;
var instance = Assert.Single(entities, entity => entity.Kind == "TemplateInstance");
Assert.Equal("HexBolt", instance.Metadata!["template"]);
+ Assert.Equal("ReferenceBolt", instance.Metadata["instance"]);
+ Assert.Equal("HexBoltSpec", instance.Metadata["recordType"]);
+ Assert.Equal("McMaster91180A151", instance.Metadata["recordSource"]);
Assert.Equal("35mm", instance.Metadata["parameter.Length"]);
+ Assert.Equal("Length", instance.Metadata["parameterType.Length"]);
+ Assert.Equal("BoundStaticRecord", instance.Metadata["parameterStatus.Length"]);
+ Assert.StartsWith("Passed:", instance.Metadata["require.ThreadFits"], StringComparison.Ordinal);
var chamfer = Assert.Single(entities, entity => entity.StableId == "McMaster91180A151.Head.TopChamfer");
Assert.Equal(6, chamfer.Topology!.FaceIds!.Count);
Assert.All(chamfer.Topology.FaceIds!, faceId => Assert.Contains(entities, entity => entity.StableId == $"brep:face:{faceId}" && entity.ParentIds!.Any(parent => parent.StartsWith("McMaster91180A151.Head.TopChamfer.Face[", StringComparison.Ordinal))));
diff --git a/Aetheris.Server/Api/CadmataFixtureService.cs b/Aetheris.Server/Api/CadmataFixtureService.cs
index f358db20..a060b795 100644
--- a/Aetheris.Server/Api/CadmataFixtureService.cs
+++ b/Aetheris.Server/Api/CadmataFixtureService.cs
@@ -27,6 +27,7 @@ internal static class CadmataFixtureService
["profile-compose-l-bracket-counterbore-pmi"] = "fixtures/FirmamentV2/Canonical/valid/profile-compose-l-bracket-counterbore-pmi.firmament",
["pmi-projected-hole-diameter"] = "fixtures/FirmamentV2/Canonical/valid/pmi-projected-hole-diameter.firmament",
["hexbolt-m1"] = "testdata/firmament/examples/mcmaster_91180a151_threadless_hex_bolt.firmament",
+ ["hexbolt-m2"] = "testdata/firmament/examples/hexbolt_template_m2.firmament",
};
public static bool TryLoad(string fixtureId, DocumentSession document, out CadmataFixtureLoadResponseDto? response, out string error)
@@ -38,7 +39,7 @@ internal static class CadmataFixtureService
var source = File.ReadAllText(sourcePath);
if (fixtureId == "pmi-projected-hole-diameter")
return TryLoadProjectedPmiFixture(fixtureId, relative, sourcePath, source, document, out response, out error);
- if (fixtureId == "hexbolt-m1")
+ if (fixtureId is "hexbolt-m1" or "hexbolt-m2")
return TryLoadStandardPartFixture(fixtureId, relative, sourcePath, source, document, out response, out error);
BrepBody? body = null; SemanticTopologyCorrespondence? correspondence = null; IReadOnlyList<ResolvedProfile2D> profiles = []; IReadOnlyList<PrismaticShaftHoleFeature> shaftHoles = []; IReadOnlyList<PrismaticCapsuleSlotFeature> capsuleSlots = []; IReadOnlyList<PrismaticRoundedRectangleSlotFeature> roundedRectangleSlots = [];
var diagnostics = new List<string>(); SemanticHoleSourceInspectionEvidence? semanticHoleEvidence = null;
@@ -103,6 +104,8 @@ internal static class CadmataFixtureService
{
var entities = new List<CadmataVisualizationEntityDto>();
var descendants = report.SemanticDescendants;
+ var instantiation = document.ConceptIr?.TemplateInstantiations?.SingleOrDefault();
+ var recordArgument = instantiation?.RecordArguments?.SingleOrDefault();
foreach (var semantic in descendants)
{
var children = descendants.Where(candidate => candidate.ParentStableId == semantic.StableId).Select(candidate => candidate.StableId).ToArray();
@@ -114,9 +117,26 @@ internal static class CadmataFixtureService
["semanticKind"] = semantic.Kind,
["sourceForm"] = "FirmamentV2.Record/Static/Template"
};
+ if (instantiation is not null)
+ {
+ metadata["instance"] = instantiation.Instance;
+ metadata["specializationIdentity"] = instantiation.SpecializationIdentity;
+ metadata["recordParameter"] = recordArgument?.Key ?? string.Empty;
+ metadata["recordType"] = recordArgument?.Value.RecordType ?? string.Empty;
+ metadata["recordSource"] = recordArgument?.Value.StaticValue ?? string.Empty;
+ foreach (var require in instantiation.RequireResults ?? new Dictionary<string, string>()) metadata["require." + require.Key] = require.Value;
+ }
if (semantic.Metadata is not null) metadata["engineeringMetadata"] = semantic.Metadata;
if (semantic.Kind == "Part")
- foreach (var parameter in report.Parameters) metadata["parameter." + parameter.Key] = parameter.Value;
+ foreach (var parameter in report.Parameters)
+ {
+ metadata["parameter." + parameter.Key] = parameter.Value;
+ var recordType = recordArgument?.Value.RecordType;
+ var declared = document.StaticAuthoring?.RecordTypes.SingleOrDefault(type => type.Name == recordType)?.Fields.GetValueOrDefault(parameter.Key);
+ metadata["parameterType." + parameter.Key] = declared ?? "Unknown";
+ metadata["parameterSource." + parameter.Key] = recordArgument?.Value.StaticValue ?? "Authored";
+ metadata["parameterStatus." + parameter.Key] = instantiation?.DefaultedArguments.Contains(recordArgument?.Key ?? string.Empty) == true ? "Default" : "BoundStaticRecord";
+ }
entities.Add(new(
semantic.StableId,
semantic.Kind == "Part" ? "TemplateInstance" : semantic.Kind == "Region" ? "PartRegion" : "GeneratedFace",
@@ -131,7 +151,7 @@ internal static class CadmataFixtureService
children,
materialFaces.Length == 0 ? null : new CadmataTopologyDto(materialFaces),
null,
- "StandardLibrary.HexBoltBuilder",
+ report.Family == "ExactCoaxialPart" ? "Firmament.Template/ExactCoaxialPart" : "StandardLibrary.HexBoltBuilder",
null,
metadata));
}
@@ -147,7 +167,7 @@ internal static class CadmataFixtureService
["entityCount"] = entities.Count,
["faceCount"] = body.Topology.Faces.Count(),
["semanticDescendantCount"] = descendants.Count,
- ["templateCount"] = document.StaticAuthoring?.Templates.Count ?? 0
+ ["templateCount"] = document.ConceptIr?.TemplateInstantiations?.Count ?? document.StaticAuthoring?.Templates.Count ?? 0
});
}
diff --git a/aetheris.client/src/components/SemanticInspector.tsx b/aetheris.client/src/components/SemanticInspector.tsx
index 574d25ae..5be47193 100644
--- a/aetheris.client/src/components/SemanticInspector.tsx
+++ b/aetheris.client/src/components/SemanticInspector.tsx
@@ -1,4 +1,6 @@
import { matchKind } from "machinalayout/match";
+import { Table } from "machinalayout/table";
+import { useMemo } from "react";
import type { ReactNode } from "react";
import { PropertyTable, type PropertyRecord } from "./PropertyTable";
import { indexSemanticInspection, semanticTree, type SemanticTreeNode } from "../viewer/semanticInspection";
@@ -15,7 +17,21 @@ function BrepDetails({ entity, artifact }: { entity: CadmataEntity; artifact: Ca
const pmi = owners.flatMap((owner) => index.pmiByTarget.get(owner.stableId) ?? []).filter((item, position, all) => all.findIndex((candidate) => candidate.stableId === item.stableId) === position);
return <><PropertyTable id={`brep-${entity.stableId}`} rows={rows(entity)} /><p className="semantic-provenance"><strong>Semantic owner(s):</strong> {owners.length ? owners.map((owner) => `${owner.kind} ${owner.label}${owner.sourceSpan ? ` · ${owner.sourceSpan}` : ""}`).join("; ") : "None published"}<br /><strong>Associated PMI:</strong> {pmi.length ? pmi.map((item) => item.label).join(", ") : "None"}</p><p className="semantic-provenance">Advanced traceability: Aetheris topology IDs are shown above. STEP entity IDs are not yet published by this fixture channel.</p></>;
}
-function GenericDetails({ entity }: { entity: CadmataEntity }) { return <PropertyTable id={`semantic-${entity.stableId}`} rows={rows(entity)} />; }
+function TemplateParameterTable({ entity }: { entity: CadmataEntity }) {
+ const records = useMemo(() => {
+ const metadata = entity.metadata ?? {};
+ const names = Object.keys(metadata).filter((key) => key.startsWith("parameter.")).map((key) => key.slice("parameter.".length)).sort();
+ return Table.toObjects(Table.define({ id: `template-parameters-${entity.stableId}`, columns: {
+ parameter: names,
+ type: names.map((name) => String(metadata[`parameterType.${name}`] ?? "Unknown")),
+ value: names.map((name) => String(metadata[`parameter.${name}`] ?? "")),
+ source: names.map((name) => `${String(metadata[`parameterSource.${name}`] ?? "Authored")} · ${String(metadata[`parameterStatus.${name}`] ?? "Bound")}`),
+ } }));
+ }, [entity]);
+ if (!records.length) return null;
+ return <><h4>Template parameters</h4><table className="property-table"><thead><tr><th>Parameter</th><th>Type</th><th>Value</th><th>Source</th></tr></thead><tbody>{records.map((record) => <tr key={String(record.parameter)}><th scope="row">{record.parameter}</th><td>{record.type}</td><td>{record.value}</td><td>{record.source}</td></tr>)}</tbody></table></>;
+}
+function GenericDetails({ entity }: { entity: CadmataEntity }) { return <><PropertyTable id={`semantic-${entity.stableId}`} rows={rows(entity).filter((row) => !row.property.startsWith("parameter"))} />{entity.kind === "TemplateInstance" ? <TemplateParameterTable entity={entity} /> : null}</>; }
export function SemanticInspector({ artifact, selectedId, onSelect }: { artifact: CadmataVisualizationArtifact | null; selectedId: string | null; onSelect: (id: string) => void }) {
if (!artifact) return <p>Load a real Firmament fixture to inspect compiler-published semantic structure.</p>;
const entity = artifact.entities.find((candidate) => candidate.stableId === selectedId) ?? null;
diff --git a/docs/firmament/v2-canonical-authoring.md b/docs/firmament/v2-canonical-authoring.md
index 5eb26dc7..100128d8 100644
--- a/docs/firmament/v2-canonical-authoring.md
+++ b/docs/firmament/v2-canonical-authoring.md
@@ -159,6 +159,32 @@ selection result kind before materialization.
The current canonical static route admits typed records, static record arrays,
one typed Template parameter, Pattern expansion, and static Require checks.
+
+Templates may also consume a user-defined Record through a scalar Static value.
+This is the preferred pattern for parameter-rich engineering families:
+
+```firmament
+Record WidgetSpec { Width: Length Height: Length }
+Static StandardWidget: WidgetSpec = WidgetSpec { Width: 40mm Height: 25mm }
+
+Template < Spec: WidgetSpec >
+Struct Widget: WidgetConcept {
+ Require Positive => Spec.Width > 0mm && Spec.Height > 0mm
+ // construction uses Spec.Width and Spec.Height
+}
+
+Struct Example = Widget < Spec: StandardWidget >
+```
+
+Record member access and Require are resolved during deterministic
+specialization. The Record, Static value, Template, and Require are erased before
+Feature AIR, while TemplateInstance provenance remains inspectable. See
+[typed Record Template parameters](../preview2/firmament-template-record-parameters-m2.md)
+and the substantial [HexBolt Template](../preview2/hexbolt-template-m2.md).
+
+For new part families, prefer typed Record Templates plus generic construction
+capabilities. `StandardPart Family: HexBolt` remains the M1 compatibility and
+internal optimized/oracle route; it is no longer the preferred authoring model.
They erase to ordinary admitted declarations before material lowering.
```firmament
diff --git a/docs/preview2/firmament-template-record-parameters-m2.md b/docs/preview2/firmament-template-record-parameters-m2.md
new file mode 100644
index 00000000..2cf53dae
--- /dev/null
+++ b/docs/preview2/firmament-template-record-parameters-m2.md
@@ -0,0 +1,62 @@
+# Typed Record parameters for Firmament Templates (M2)
+
+## Gap audit
+
+Before M2, `Template <...> Struct ...` value parameters admitted only `Length`,
+numeric/bool scalars, and enums. Binding was scalar text substitution. The older
+canonical static lane understood `Record` declarations and `Static T[]` values,
+but erased them before modern Template specialization. It had no scalar
+`Static Name: T = T { ... }` IR. Consequently `Spec: HexBoltSpec` was treated as
+an unknown value type, `Spec.HeadHeight` had no typed authority, and Require
+could not evaluate record members.
+
+M2 makes modern Template specialization the owner of typed Record binding. It
+runs while Record and Static declarations are present; canonical static erasure
+then removes them before Feature AIR. This is the same Template system, not a
+parallel runtime or macro lane.
+
+## Authoring pattern
+
+```firmament
+Record WidgetSpec {
+ Width: Length
+ Height: Length
+}
+
+Static TallWidget: WidgetSpec = WidgetSpec {
+ Width: 40mm
+ Height: 25mm
+}
+
+Template < Spec: WidgetSpec >
+Struct Widget: WidgetConcept {
+ Require Positive => Spec.Width > 0mm && Spec.Height > 0mm
+ // ordinary declarations using Spec.Width and Spec.Height
+}
+
+Struct Example = Widget < Spec: TallWidget >
+```
+
+The binder resolves the declared Record type and scalar Static value, requires
+exact Record-type identity, validates all fields, resolves member expressions,
+and evaluates Require after member resolution. Direct record-literal arguments
+remain unsupported in M2; use a named Static value so provenance is stable.
+
+`ConceptIrTemplateInstantiation.RecordArguments` retains parameter name, Record
+type, Static value name, member values, source span, and provenance.
+`RequireResults` records passed/failed expression evidence. These records are
+source-map evidence only: Template, Static, Record values, Match, and Require are
+erased before Feature AIR.
+
+## Diagnostics
+
+M2 adds bounded typed diagnostics for unknown Record parameter types, unknown
+Static values, wrong Static Record types, collection-to-scalar mismatches,
+materialized values passed as compile-time arguments, unsupported value forms,
+unknown members, field type mismatches, and Require failure after member
+resolution. Existing parameter/default/constraint diagnostics are unchanged.
+
+The bolt-independent regression fixture in
+`FirmamentV2TemplateExpansionTests` proves binding, member access, Require,
+deterministic specialization, provenance, and rejection behavior.
+
diff --git a/docs/preview2/hexbolt-template-m2.md b/docs/preview2/hexbolt-template-m2.md
new file mode 100644
index 00000000..9bbb2013
--- /dev/null
+++ b/docs/preview2/hexbolt-template-m2.md
@@ -0,0 +1,106 @@
+# HexBolt as a Concept-constrained Firmament Template (M2)
+
+## Architectural transition
+
+M1 deliberately answered the geometry question first. `HexBoltSpec`,
+`HexBoltParameterBinding`, and `HexBoltBuilder` established an exact, deterministic
+AP242 oracle with a regular hex head, exact cone/plane hyperbola trims, toroidal
+under-head blend, cylindrical shank, and conical tip. M2 preserves that path.
+
+M2 moves family authoring to
+`testdata/firmament/examples/hexbolt_template_m2.firmament`. The canonical source
+declares `BoltConcept`, the family-specific `HexBoltSpec`, scalar Static records,
+and `Template < Spec: HexBoltSpec > Struct HexBolt: BoltConcept`. It contains no
+`StandardPart Family: HexBolt` dispatch.
+
+The doctrine is:
+
+- the compiler owns generic exact geometry machinery;
+- Templates own reusable engineering-family knowledge;
+- standards and presets are typed data;
+- generated instances are specializations, not stored part files.
+
+`BoltConcept` stays intentionally small: `NominalDiameter`, `Length`,
+`ThreadLength`, `ThreadDesignation`, and `Axis`. Hex-head construction dimensions
+remain in `HexBoltSpec`. Property class and thread designation remain semantic;
+the material thread region is cylindrical and no marking is engraved.
+
+## Reusable construction recipe
+
+The Template spells a bounded `ExactCoaxialPart` recipe from domain-neutral
+operations:
+
+- `RegularPolygonPrism` for the head;
+- `CoaxialConeTrim` with exact conic intersection;
+- `BoundedTorusBlend` with periodic support splitting;
+- `Cylinder` for the shaft/material thread region;
+- `CoaxialConeFrustum` for the end treatment;
+- `SemanticAxialRegion` and metadata publication.
+
+The current backend admits six polygon sides for this bounded recipe and reports
+other counts as unsupported. `ExactCoaxialPartBuilder` maps the generic recipe to
+the proven M1 analytic topology engine. Thus M1 remains both oracle and internal
+geometry implementation during M2, while the Firmament route no longer selects
+a HexBolt family hook. A later backend refactor can move the topology engine out
+of the M1-named facade without changing Firmament source.
+
+## Admission rules
+
+Template Require validates positive nominal/head dimensions, head width above
+shaft diameter, top flat inside the across-flats envelope, cone angle in
+`(0deg, 90deg)`, nonnegative blend radius, reduced tip diameter, tip length inside
+the axial length, and thread length in `[0, Length]`. `HexBoltBuilder.Validate`
+continues to enforce its stricter derived geometric checks (including cone-height
+and torus-radius admission) at the exact construction boundary. There is no
+constraint solver.
+
+## Dogfood and comparison
+
+The same Template source contains data for the McMaster 91180A151 M8 × 35
+reference, M10 × 50, and a deliberately nonstandard 8.25 × 37.5 mm bolt. Tests
+bind each Static record without changing geometry source.
+
+Their deterministic construction signatures are respectively
+`b2e86e279016f55625e074153f76561144dc7c3c85cbc943c3e3492a7e19acda`,
+`1922883929da993de801a7975727ff371b5e2dc002999c4d6c0907bb8387cf4e`,
+and `5c1b9bb6919de54f469d82c6d4febf7ad109cf520793ce88117c235ba0a1f828`.
+
+For the reference, M1 and M2 currently produce byte-identical STEP:
+
+| Evidence | M1 builder | M2 Template |
+|---|---:|---:|
+| SHA-256 | `7221a75bbf8d21a72080dede80d9253f65d66986419c224f0a8b50682dec1a85` | same |
+| Vertices / edges / faces | 26 / 44 / 21 | 26 / 44 / 21 |
+| Imported planes / cylinders / cones / tori | 9 / 2 / 8 / 2 | 9 / 2 / 8 / 2 |
+| Exact hyperbola trims | 6 | 6 |
+| STEP B-splines / NURBS | 0 | 0 |
+| Bodies / shells | 1 / 1 | 1 / 1 |
+| Structural assessment | enclosed manifold | enclosed manifold |
+| Semantic descendants | 29, same stable IDs | 29, same stable IDs |
+
+Aetheris verification reports bounds `[-5.3,-6.5,-7.50555349946514]` to
+`[35,6.5,7.50555349946514]`. Its deterministic triangulated sanity estimate is
+2501.457449 mm³ and is explicitly non-authoritative. FreeCAD 1.0 / OCCT imports
+one valid solid and one shell with 21 faces and reports 2526.679305 mm³. OCCT
+retains Plane, Cylinder, Cone, Torus, and all six Hyperbola curves. The emitted
+STEP contains no B-spline entity and required no healing.
+
+## Cadmata and TemplateInstance
+
+Cadmata fixture `hexbolt-m2` uses the generic `TemplateInstance` entity. It
+publishes Template, instance, specialization identity, Record parameter/type,
+Static source, Require evidence, and semantic descendants. The parameter table
+uses MachinaLayout Table and shows parameter, declared type, value, and
+Static/default status. There is no bolt-specific inspector.
+
+## Future fastener seam
+
+Socket-head, flat-head, round-head, and thumb-screw families should reuse
+`BoltConcept` and author their own typed specs and construction recipes. Stud and
+threaded-rod Templates can satisfy the same contract without a head recipe.
+`BoltHeadConcept` may become useful after multiple real heads expose common
+composition evidence. M2 intentionally does not introduce `Bolt<THead>` yet.
+
+The next milestone should be **P2-TEMPLATE-STANDARD-M1**: represent standards and
+presets as typed data bound to these Templates, without turning the generator
+into a lookup table.
diff --git a/testdata/firmament/examples/hexbolt_template_m2.firmament b/testdata/firmament/examples/hexbolt_template_m2.firmament
new file mode 100644
index 00000000..f38a49de
--- /dev/null
+++ b/testdata/firmament/examples/hexbolt_template_m2.firmament
@@ -0,0 +1,135 @@
+Model HexBoltTemplateM2 {
+ Units: mm
+
+ Concept BoltConcept {
+ NominalDiameter: Length
+ Length: Length
+ ThreadLength: Length
+ ThreadDesignation: String
+ Axis: Axis
+ }
+
+ Record HexBoltSpec {
+ StableId: String
+ NominalDiameter: Length
+ Length: Length
+ HeadAcrossFlats: Length
+ HeadHeight: Length
+ TopFlatDiameter: Length
+ TopChamferAngle: Angle
+ UnderHeadRadius: Length
+ TipChamferLength: Length
+ TipDiameter: Length
+ ThreadLength: Length
+ ThreadDesignation: String
+ PropertyClass: String
+ }
+
+ Static McMaster91180A151: HexBoltSpec = HexBoltSpec {
+ StableId: "McMaster91180A151"
+ NominalDiameter: 8mm
+ Length: 35mm
+ HeadAcrossFlats: 13mm
+ HeadHeight: 5.3mm
+ TopFlatDiameter: 12.35mm
+ TopChamferAngle: 25deg
+ UnderHeadRadius: 0.2mm
+ TipChamferLength: 0.9375mm
+ TipDiameter: 6.125mm
+ ThreadLength: 22mm
+ ThreadDesignation: "M8 x 1.25"
+ PropertyClass: "8.8"
+ }
+
+ Static M10x50: HexBoltSpec = HexBoltSpec {
+ StableId: "M10x50"
+ NominalDiameter: 10mm
+ Length: 50mm
+ HeadAcrossFlats: 17mm
+ HeadHeight: 6.4mm
+ TopFlatDiameter: 16mm
+ TopChamferAngle: 25deg
+ UnderHeadRadius: 0.2mm
+ TipChamferLength: 0.9375mm
+ TipDiameter: 8mm
+ ThreadLength: 26mm
+ ThreadDesignation: "M10 x 1.5"
+ PropertyClass: "8.8"
+ }
+
+ Static Nonstandard825x375: HexBoltSpec = HexBoltSpec {
+ StableId: "Nonstandard825x375"
+ NominalDiameter: 8.25mm
+ Length: 37.5mm
+ HeadAcrossFlats: 13.4mm
+ HeadHeight: 5.5mm
+ TopFlatDiameter: 12.7mm
+ TopChamferAngle: 25deg
+ UnderHeadRadius: 0.22mm
+ TipChamferLength: 1mm
+ TipDiameter: 6.3mm
+ ThreadLength: 23mm
+ ThreadDesignation: "M8.25 experimental"
+ PropertyClass: "8.8"
+ }
+
+ Template < Spec: HexBoltSpec >
+ Struct HexBolt: BoltConcept {
+ Require PositiveNominal => Spec.NominalDiameter > 0mm
+ Require HeadWiderThanShank => Spec.HeadAcrossFlats > Spec.NominalDiameter
+ Require TopFlatInsideHex => Spec.TopFlatDiameter < Spec.HeadAcrossFlats
+ Require PositiveHead => Spec.HeadHeight > 0mm
+ Require ConeAngleValid => Spec.TopChamferAngle > 0deg && Spec.TopChamferAngle < 90deg
+ Require BlendNonnegative => Spec.UnderHeadRadius >= 0mm
+ Require TipReducesDiameter => Spec.TipDiameter < Spec.NominalDiameter
+ Require TipFitsLength => Spec.TipChamferLength > 0mm && Spec.TipChamferLength < Spec.Length
+ Require ThreadFits => Spec.ThreadLength >= 0mm && Spec.ThreadLength <= Spec.Length
+
+ ExactCoaxialPart Body {
+ Axis: +X
+ RegularPolygonPrism Head {
+ Sides: 6
+ AcrossFlats: Spec.HeadAcrossFlats
+ AxialHeight: Spec.HeadHeight
+ }
+ CoaxialConeTrim TopTreatment {
+ FlatDiameter: Spec.TopFlatDiameter
+ ConeAngle: Spec.TopChamferAngle
+ IntersectionCurve: ExactConic
+ }
+ BoundedTorusBlend HeadToShaft {
+ BlendRadius: Spec.UnderHeadRadius
+ SplitPolicy: PeriodicHalfSupports
+ }
+ Cylinder Shaft {
+ ShaftDiameter: Spec.NominalDiameter
+ AxialLength: Spec.Length
+ }
+ CoaxialConeFrustum EndTreatment {
+ EndChamferLength: Spec.TipChamferLength
+ EndDiameter: Spec.TipDiameter
+ }
+ SemanticAxialRegion ThreadRegion {
+ SemanticAxialRegionLength: Spec.ThreadLength
+ Designation: Spec.ThreadDesignation
+ MaterialGeometry: Cylinder
+ }
+ Metadata {
+ StableId: Spec.StableId
+ Grade: Spec.PropertyClass
+ }
+ }
+
+ Expose {
+ NominalDiameter: Spec.NominalDiameter
+ Length: Spec.Length
+ ThreadLength: Spec.ThreadLength
+ ThreadDesignation: Spec.ThreadDesignation
+ Axis: Body.Axis
+ }
+ }
+
+ Struct ReferenceBolt = HexBolt <
+ Spec: McMaster91180A151
+ >
+}