Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Validate gear interfaces and expand assembly inspection output

Yuechen Lie7134210f0f1
diff --git a/Aetheris.CLI.Tests/AssemblyGearBridgeX1CliTests.cs b/Aetheris.CLI.Tests/AssemblyGearBridgeX1CliTests.cs
new file mode 100644
index 00000000..8de69639
--- /dev/null
+++ b/Aetheris.CLI.Tests/AssemblyGearBridgeX1CliTests.cs
@@ -0,0 +1,49 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class AssemblyGearBridgeX1CliTests
+{
+ [Fact]
+ public void AssemblyInspectReportsTypedGearAuthorityAndDerivedCompatibility()
+ {
+ var path = Path.Combine(RepoRoot(), "fixtures", "Canonical", "AssemblyInterfaces", "exposed-gear-port.firmament");
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+ var exit = CliRunner.Run(["asm", "inspect", path], stdout, stderr);
+ Assert.Equal(0, exit);
+ Assert.Empty(stderr.ToString());
+ var text = stdout.ToString();
+ Assert.Contains("Interface<Gear>", text, StringComparison.Ordinal);
+ Assert.Contains("port=Register/Digit0/Output", text, StringComparison.Ordinal);
+ Assert.Contains("source=Register/Digit0/OutputGear", text, StringComparison.Ordinal);
+ Assert.Contains("ratio=2", text, StringComparison.Ordinal);
+ Assert.Contains("center expected=60mm actual=60mm", text, StringComparison.Ordinal);
+
+ stdout.GetStringBuilder().Clear();
+ exit = CliRunner.Run(["asm", "inspect", path, "--json"], stdout, stderr);
+ Assert.Equal(0, exit);
+ using var json = JsonDocument.Parse(stdout.ToString());
+ var transfer = json.RootElement.GetProperty("assemblyIr").GetProperty("mates").EnumerateArray()
+ .Single(item => item.GetProperty("name").GetString() == "Transfer");
+ Assert.Equal("compatible", transfer.GetProperty("gearResult").GetProperty("compatibilityStatus").GetString());
+ Assert.Equal(4.5d, transfer.GetProperty("gearResult").GetProperty("a").GetProperty("phaseDegrees").GetDouble());
+ }
+
+ [Fact]
+ public void AssemblyInspectReturnsExistingGearFailureForHierarchicalMismatch()
+ {
+ var path = Path.Combine(RepoRoot(), "fixtures", "Invalid", "AssemblyInterfaces", "gear-module-mismatch.firmament");
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+ var exit = CliRunner.Run(["asm", "inspect", path], stdout, stderr);
+ Assert.Equal(1, exit);
+ Assert.Contains("firmament-gear-interface-incompatible", stderr.ToString(), StringComparison.Ordinal);
+ Assert.Contains("module-mismatch", stderr.ToString(), StringComparison.Ordinal);
+ }
+
+ private static string RepoRoot()
+ {
+ var directory = new DirectoryInfo(AppContext.BaseDirectory);
+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;
+ return directory?.FullName ?? throw new DirectoryNotFoundException();
+ }
+}
diff --git a/Aetheris.CLI.Tests/AssemblyInterfaceX1CliTests.cs b/Aetheris.CLI.Tests/AssemblyInterfaceX1CliTests.cs
new file mode 100644
index 00000000..707be2d7
--- /dev/null
+++ b/Aetheris.CLI.Tests/AssemblyInterfaceX1CliTests.cs
@@ -0,0 +1,38 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class AssemblyInterfaceX1CliTests
+{
+ [Fact]
+ public void InspectReportsHierarchyExpansionDefinitionsAndDependencyManifest()
+ {
+ var path = Path.Combine(RepoRoot(), "fixtures", "Canonical", "AssemblyInterfaces", "machine.firmament");
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+ var exit = CliRunner.Run(["asm", "inspect", path], stdout, stderr);
+ Assert.Equal(0, exit);
+ Assert.Empty(stderr.ToString());
+ var text = stdout.ToString();
+ Assert.Contains("DifferenceEngineReadiness", text, StringComparison.Ordinal);
+ Assert.Contains("Interface<Axial>", text, StringComparison.Ordinal);
+ Assert.Contains("Expanded Mate AxisCoincident", text, StringComparison.Ordinal);
+ Assert.Contains("Shared definitions:", text, StringComparison.Ordinal);
+ Assert.Contains("DigitModule: occurrences=4", text, StringComparison.Ordinal);
+ Assert.Contains("Source dependencies:", text, StringComparison.Ordinal);
+
+ stdout.GetStringBuilder().Clear();
+ exit = CliRunner.Run(["asm", "inspect", path, "--json"], stdout, stderr);
+ Assert.Equal(0, exit);
+ using var json = JsonDocument.Parse(stdout.ToString());
+ var ir = json.RootElement.GetProperty("assemblyIr");
+ Assert.Equal(3, ir.GetProperty("sourceDependencies").GetArrayLength());
+ Assert.Equal(15, ir.GetProperty("instances").GetArrayLength());
+ }
+
+ private static string RepoRoot()
+ {
+ var directory = new DirectoryInfo(AppContext.BaseDirectory);
+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;
+ return directory?.FullName ?? throw new DirectoryNotFoundException();
+ }
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 7fc1a466..57a2d636 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -3837,6 +3837,7 @@ Model CanonicalPanel {
if (!File.Exists(path)) { stderr.WriteLine($"Assembly source '{path}' was not found."); return 1; }
var sourceText = File.ReadAllText(path);
var usesTemplateInstances = Regex.IsMatch(sourceText, @"<Part\s+[A-Za-z_]\w*\s*=\s*[A-Za-z_]\w*\s*<", RegexOptions.CultureInvariant);
+ var usesGearParts = GearAuthoring.ParseDefinitions(sourceText).Gears.Count > 0;
var usesSheetMetalParts = sourceText.Contains("Use SheetMetal.ProductFamilies", StringComparison.Ordinal);
AssemblyIr? assemblyIr;
AssemblyGeometryArtifactIr? geometryArtifact;
@@ -3852,7 +3853,7 @@ Model CanonicalPanel {
assemblyPerformance = document.Compilation.Performance;
success = document.IsSuccess;
}
- else if (usesTemplateInstances)
+ else if (usesTemplateInstances || usesGearParts)
{
var m1 = new AssemblyM1Pipeline().CompileFile(path, usesSheetMetalParts ? EnclosureProductFamilies.MaterializeAssemblyPart : null);
assemblyIr = m1.Ir;
@@ -3889,7 +3890,36 @@ Model CanonicalPanel {
stdout.WriteLine($"{new string(' ', (instance.Path.Segments.Count - 1) * 2)}- {instance.Path.Segments[^1]} [{instance.Kind}] = {instance.DefinitionIdentity}; placement={instance.PlacementAuthority}");
stdout.WriteLine("Mates:");
foreach (var mate in ir.Mates.Concat((ir.AssemblyDefinitions ?? []).SelectMany(definition => definition.LocalMates)).DistinctBy(mate => mate.StableId))
- stdout.WriteLine($"- {mate.Name}: {mate.InterfaceStableId} ({string.Join(", ", mate.Roles.Select(x => x.Role + "=" + x.ParticipantPath))})");
+ {
+ var definition = ir.Interfaces.Single(item => item.StableId == mate.InterfaceStableId);
+ stdout.WriteLine($"- {mate.Name}: Interface<{definition.Family}> {mate.InterfaceStableId} ({string.Join(", ", mate.Roles.Select(x => x.Role + "=" + x.ParticipantPath))}); status={mate.ValidationStatus}");
+ foreach (var constraint in definition.Requirements)
+ stdout.WriteLine($" Expanded Mate {constraint.Kind}: {constraint.FirstRole}.{constraint.FirstMember} -> {constraint.SecondRole}.{constraint.SecondMember}");
+ foreach (var requirement in mate.RequirementResults ?? [])
+ stdout.WriteLine($" Require {requirement.Name}: {requirement.Expression} ({requirement.Status})");
+ if (mate.GearResult is { } gear)
+ {
+ WriteGearEndpoint("A", gear.A);
+ WriteGearEndpoint("B", gear.B);
+ stdout.WriteLine($" Derived: ratio={gear.Ratio:G6}; rotation-sign={gear.RotationSign}; center expected={gear.ExpectedCenterDistanceMm:G6}mm actual={gear.ActualCenterDistanceMm:G6}mm; {gear.CompatibilityStatus}");
+ }
+ }
+ var definitions = ir.AssemblyDefinitions ?? [];
+ if (definitions.Count > 0)
+ {
+ stdout.WriteLine("Shared definitions:");
+ foreach (var definition in definitions.OrderBy(item => item.DefinitionIdentity, StringComparer.Ordinal))
+ {
+ var uses = ir.Instances.Count(item => item.DefinitionIdentity == definition.DefinitionIdentity);
+ stdout.WriteLine($"- {definition.DefinitionIdentity}: occurrences={uses}; local-instances={definition.LocalInstances.Count}; public=[{string.Join(",", definition.PublicSemantics.Select(item => item.ExposedName))}]");
+ }
+ }
+ if (ir.SourceDependencies is { Count: > 0 })
+ {
+ stdout.WriteLine("Source dependencies:");
+ foreach (var dependency in ir.SourceDependencies)
+ stdout.WriteLine($"- {(dependency.IsRoot ? "root" : "include")}: {dependency.Path}; sha256={dependency.Sha256}");
+ }
var datums = (ir.Datums ?? []).Concat((ir.AssemblyDefinitions ?? []).SelectMany(definition => definition.LocalDatums ?? []))
.DistinctBy(datum => datum.SemanticPath).OrderBy(datum => datum.SemanticPath, StringComparer.Ordinal).ToArray();
var rootDatums = datums.Where(datum => datum.SemanticPath.StartsWith(ir.Name + ".", StringComparison.Ordinal)).ToArray();
@@ -3943,6 +3973,9 @@ Model CanonicalPanel {
foreach (var diagnostic in assemblyDiagnostics) stderr.WriteLine($"{diagnostic.Code}: {diagnostic.Message}");
}
return success ? 0 : 1;
+
+ void WriteGearEndpoint(string role, GearEndpointIr endpoint) => stdout.WriteLine(
+ $" {role}: port={endpoint.ExposedPortPath}; source={endpoint.HierarchicalPath}; definition={endpoint.DefinitionIdentity}; occurrence={endpoint.OccurrenceIdentity}; family={endpoint.Family}; teeth={endpoint.Teeth}; module={endpoint.ModuleMm:G6}mm; pressure-angle={endpoint.PressureAngleDegrees:G6}deg; axis=[{string.Join(',', endpoint.Axis.Select(value => value.ToString("G6", System.Globalization.CultureInfo.InvariantCulture)))}]; phase={endpoint.PhaseDegrees:G6}deg");
}
private static int RunAsmExec(string[] args, TextWriter stdout, TextWriter stderr)
diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyGearBridgeX1Tests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyGearBridgeX1Tests.cs
new file mode 100644
index 00000000..5a67e1ca
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyGearBridgeX1Tests.cs
@@ -0,0 +1,282 @@
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Firmament.Tests.Assembly;
+
+public sealed class AssemblyGearBridgeX1Tests
+{
+ [Theory]
+ [InlineData("exposed-gear-port")]
+ [InlineData("gear-between-subassemblies")]
+ [InlineData("nested-register-gear")]
+ [InlineData("three-gear-train-hierarchical")]
+ [InlineData("bevel-subassembly-pair")]
+ public void CanonicalHierarchicalGearFixturesQualify(string name)
+ {
+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/Canonical/AssemblyInterfaces/{name}.firmament");
+ var result = new AssemblyM0Pipeline().CompileFile(path);
+ Assert.True(result.IsSuccess, Evidence(result));
+ Assert.All(result.Ir!.Mates, mate => Assert.Equal("valid", mate.ValidationStatus));
+ }
+
+ [Theory]
+ [InlineData("exposed-wrong-endpoint-type", "assembly-role-capability-mismatch")]
+ [InlineData("private-gear-access", "assembly-internal-member-hidden")]
+ [InlineData("gear-module-mismatch", "firmament-gear-interface-incompatible")]
+ [InlineData("gear-pressure-angle-mismatch", "firmament-gear-interface-incompatible")]
+ [InlineData("gear-center-distance-mismatch", "firmament-gear-interface-incompatible")]
+ [InlineData("gear-axis-mismatch", "firmament-gear-interface-incompatible")]
+ [InlineData("invalid-nested-gear-path", "assembly-expose-unresolved-path")]
+ public void InvalidHierarchicalGearFixturesFailTyped(string name, string code)
+ {
+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/Invalid/AssemblyInterfaces/{name}.firmament");
+ var result = new AssemblyM0Pipeline().CompileFile(path);
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics, item => item.Code == code);
+ }
+
+ [Fact]
+ public void ExposedGearPortsReuseGearAuthorityAcrossSharedSubassemblies()
+ {
+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/exposed-gear-port.firmament");
+ var result = new AssemblyM0Pipeline().CompileFile(path);
+
+ Assert.True(result.IsSuccess, Evidence(result));
+ var transfer = Assert.Single(result.Ir!.Mates, mate => mate.Name == "Transfer");
+ Assert.Equal("valid", transfer.ValidationStatus);
+ Assert.NotNull(transfer.GearResult);
+ Assert.Equal("compatible", transfer.GearResult!.CompatibilityStatus);
+ Assert.Equal(60d, transfer.GearResult.ExpectedCenterDistanceMm);
+ Assert.Equal(60d, transfer.GearResult.ActualCenterDistanceMm, 5);
+ Assert.Equal(2d, transfer.GearResult.Ratio);
+ Assert.Equal(-1, transfer.GearResult.RotationSign);
+ Assert.Equal("Register/Digit0/Output", transfer.GearResult.A.ExposedPortPath);
+ Assert.Equal("Register/Digit0/OutputGear", transfer.GearResult.A.HierarchicalPath);
+ Assert.Equal("Register/Digit1/Input", transfer.GearResult.B.ExposedPortPath);
+ Assert.Equal(4.5d, transfer.GearResult.A.PhaseDegrees);
+ Assert.Equal(2, result.Ir.Instances.Count(instance => instance.DefinitionIdentity == "DigitModule"));
+ Assert.Single(result.Ir.AssemblyDefinitions!, definition => definition.DefinitionIdentity == "DigitModule");
+ }
+
+ [Fact]
+ public void ExistingGearCompatibilityRejectsHierarchicalModulePressureCenterAxisAndTypeMismatches()
+ {
+ var module = CompilePair("Module: 1.5mm Teeth: 20 PressureAngle: 20deg", 35);
+ Assert.Contains(module.Diagnostics, item => item.Code == "firmament-gear-interface-incompatible" && item.Message.Contains("module-mismatch", StringComparison.Ordinal));
+
+ var pressure = CompilePair("Module: 2mm Teeth: 20 PressureAngle: 25deg", 40);
+ Assert.Contains(pressure.Diagnostics, item => item.Code == "firmament-gear-interface-incompatible" && item.Message.Contains("pressure-angle-mismatch", StringComparison.Ordinal));
+
+ var center = CompilePair("Module: 2mm Teeth: 20 PressureAngle: 20deg", 41);
+ Assert.Contains(center.Diagnostics, item => item.Code == "firmament-gear-interface-incompatible" && item.Message.Contains("center-distance-mismatch", StringComparison.Ordinal));
+
+ var axis = CompilePair("Module: 2mm Teeth: 20 PressureAngle: 20deg", 40,
+ "1,0,0,0, 0,0,1,0, 0,-1,0,0, 40,0,0,1");
+ Assert.Contains(axis.Diagnostics, item => item.Code == "firmament-gear-interface-incompatible" && item.Message.Contains("axis-relation-mismatch", StringComparison.Ordinal));
+
+ const string wrongType = """
+ Units: mm
+ SpurGear G { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+ Assembly Wrong {
+ <Assembly Wrong><Part Gear = G></Part><Part Shaft = Block> Semantic Port { Axis Axis = [0,0,0] -> [0,0,1]; } </Part></Assembly>
+ Anchor: Wrong.Gear;
+ Interface<Gear> Invalid { A: Wrong.Gear; B: Wrong.Shaft.Port; }
+ }
+ """;
+ var typed = new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(wrongType).Source!);
+ Assert.Contains(typed.Diagnostics, item => item.Code == AssemblyM0Compiler.CapabilityMismatch && item.Message.Contains("GearCapable", StringComparison.Ordinal));
+
+ var axialSource = wrongType.Replace("Interface<Gear> Invalid", "Interface<Axial> Invalid", StringComparison.Ordinal);
+ var coerced = new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(axialSource).Source!);
+ Assert.Contains(coerced.Diagnostics, item => item.Code == AssemblyM0Compiler.CapabilityMismatch && item.Message.Contains("not implicitly coerced", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void GearAxisAndPhaseSurviveTwoHierarchyLevels()
+ {
+ const string source = """
+ Units: mm
+ SpurGear G { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm Phase: 9deg }
+ Subassembly Digit {
+ <Assembly Digit><Part Wheel = G></Part></Assembly>
+ Anchor: Digit.Wheel;
+ Expose { Gear Port = Wheel; }
+ }
+ Subassembly Register {
+ <Assembly Register><Assembly Digit = Digit></Assembly></Assembly>
+ Anchor: Register.Digit.Port;
+ Expose { Gear Port = Digit.Port; }
+ }
+ Assembly Machine {
+ <Assembly Machine>
+ <Assembly A = Register></Assembly>
+ <Assembly B = Register>Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 40,0,0,1];</Assembly>
+ </Assembly>
+ Anchor: Machine.A.Port;
+ Interface<Gear> Transfer { A: Machine.A.Port; B: Machine.B.Port; }
+ }
+ """;
+ var result = new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(source).Source!);
+ Assert.True(result.IsSuccess, Evidence(result));
+ var gear = Assert.Single(result.Ir!.Mates).GearResult!;
+ Assert.Equal("Machine/A/Port", gear.A.ExposedPortPath);
+ Assert.Equal("Machine/A/Digit/Wheel", gear.A.HierarchicalPath);
+ Assert.Equal(9d, gear.A.PhaseDegrees);
+ Assert.Equal(new[] { 0d, 0d, 1d }, gear.A.Axis);
+ Assert.Equal(2, result.Ir.AssemblyDefinitions!.Count);
+ }
+
+ [Fact]
+ public void ExposedGearAxisUsesNestedOccurrenceRotation()
+ {
+ const string source = """
+ Units: mm
+ SpurGear G { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+ Subassembly Cell { <Assembly Cell><Part Gear = G></Part></Assembly> Anchor: Cell.Gear; Expose { Gear Port = Gear; } }
+ Assembly Rotated {
+ <Assembly Rotated>
+ <Assembly A = Cell>Placement ImportedOccurrence = [1,0,0,0, 0,0,1,0, 0,-1,0,0, 0,0,0,1];</Assembly>
+ <Assembly B = Cell>Placement ImportedOccurrence = [1,0,0,0, 0,0,1,0, 0,-1,0,0, 40,0,0,1];</Assembly>
+ </Assembly>
+ Interface<Gear> Mesh { A: Rotated.A.Port; B: Rotated.B.Port; }
+ }
+ """;
+ var result = new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(source).Source!);
+ Assert.True(result.IsSuccess, Evidence(result));
+ var gear = Assert.Single(result.Ir!.Mates).GearResult!;
+ Assert.Equal(new[] { 0d, -1d, 0d }, gear.A.Axis.Select(value => Math.Round(value, 6)).ToArray());
+ Assert.Equal(40d, gear.ActualCenterDistanceMm, 5);
+ }
+
+ [Fact]
+ public void OneGearDefinitionBacksOneHundredOccurrenceSpecificPorts()
+ {
+ var occurrences = string.Join(Environment.NewLine, Enumerable.Range(0, 100).Select(index =>
+ $"<Assembly D{index} = Digit>Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, {index * 50},0,0,1];</Assembly>"));
+ var source = $$"""
+ Units: mm
+ SpurGear G { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+ Subassembly Digit { <Assembly Digit><Part Wheel = G></Part></Assembly> Anchor: Digit.Wheel; Expose { Gear Port = Wheel; } }
+ Assembly Stress { <Assembly Stress>{{occurrences}}</Assembly> Anchor: Stress.D0.Port; }
+ """;
+ var first = new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(source).Source!);
+ var second = new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(source).Source!);
+ Assert.True(first.IsSuccess, Evidence(first));
+ Assert.Single(first.Ir!.AssemblyDefinitions!);
+ Assert.Equal(100, first.Ir.Instances.Count(item => item.DefinitionIdentity == "Digit"));
+ Assert.Equal(first.Ir.Instances.Select(item => item.StableId), second.Ir!.Instances.Select(item => item.StableId));
+ Assert.All(first.Ir.Instances.Where(item => item.DefinitionIdentity == "Digit"), item =>
+ Assert.True(item.SemanticRoot.ExposedMembers["Port"].Capabilities.Supports<Aetheris.Semantics.GearCapability>()));
+ }
+
+ [Fact]
+ public void GearGeometryUsesOrdinaryWholeTreeAp242LoweringDeterministically()
+ {
+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/exposed-gear-port.firmament");
+ var first = new AssemblyM1Pipeline().CompileFile(path);
+ var second = new AssemblyM1Pipeline().CompileFile(path);
+ Assert.True(first.IsSuccess, Evidence(first));
+ Assert.True(second.IsSuccess, Evidence(second));
+ Assert.Equal(2, first.Geometry!.Artifact.Definitions.Count);
+ Assert.Equal(4, first.Geometry.Artifact.Instances.Count);
+ Assert.Equal(first.Geometry.Artifact.DeterministicSha256, second.Geometry!.Artifact.DeterministicSha256);
+
+ var step = AssemblyIrAp242Exporter.Export(first);
+ Assert.True(step.IsSuccess, string.Join(Environment.NewLine, step.Diagnostics.Select(item => item.Message)));
+ var imported = Step242AssemblyImporter.Import(step.Value);
+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(item => item.Message)));
+ Assert.True(imported.Value.Occurrences.Count >= 4);
+ Assert.DoesNotContain(".step", File.ReadAllText(path), StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void PrivateGearCannotBeReachedAndAnExposedAliasIsTheSameAuthority()
+ {
+ const string source = """
+ Units: mm
+ SpurGear G { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+ Subassembly Cell { <Assembly Cell><Part Hidden = G></Part></Assembly> Anchor: Cell.Hidden; }
+ Assembly Machine {
+ <Assembly Machine><Assembly A = Cell></Assembly><Assembly B = Cell>Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 40,0,0,1];</Assembly></Assembly>
+ Anchor: Machine.A;
+ Interface<Gear> Illegal { A: Machine.A.Hidden; B: Machine.B.Hidden; }
+ }
+ """;
+ var result = new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(source).Source!);
+ Assert.Contains(result.Diagnostics, item => item.Code == "assembly-internal-member-hidden");
+
+ var exposed = new AssemblyM0Pipeline().CompileFile(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/exposed-gear-port.firmament"));
+ var transfer = Assert.Single(exposed.Ir!.Mates, mate => mate.Name == "Transfer").GearResult!;
+ var local = Assert.Single(exposed.Ir.AssemblyDefinitions!).LocalMates.Single(mate => mate.Name == "InternalMesh").GearResult!;
+ Assert.Equal(local.B.DefinitionIdentity, transfer.A.DefinitionIdentity);
+ Assert.Equal(local.B.PhaseDegrees, transfer.A.PhaseDegrees);
+ }
+
+ [Fact]
+ public void InternalSpurBevelMiterAndRatchetRemainOwnedByTheExistingEvaluator()
+ {
+ var internalPair = CompileFamilies(
+ "SpurGear A { Module: 1mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }",
+ "InternalSpurGear B { Module: 1mm Teeth: 60 PressureAngle: 20deg FaceWidth: 6mm OutsideDiameter: 65mm Phase: 3deg }",
+ "1,0,0,0, 0,1,0,0, 0,0,1,0, 20,0,0,1", "");
+ Assert.Equal("ExternalInternal", Assert.Single(internalPair.Ir!.Mates).GearResult!.Kind);
+ Assert.Equal(1, Assert.Single(internalPair.Ir.Mates).GearResult!.RotationSign);
+
+ var bevel = CompileFamilies(
+ "BevelGear A { Module: 1mm Teeth: 20 PressureAngle: 20deg FaceWidth: 5mm BoreDiameter: 5mm PitchConeAngle: 26.565051177deg }",
+ "BevelGear B { Module: 1mm Teeth: 40 PressureAngle: 20deg FaceWidth: 5mm BoreDiameter: 8mm PitchConeAngle: 63.434948823deg }",
+ "1,0,0,0, 0,0,1,0, 0,-1,0,0, 0,0,0,1", "ShaftAngle: 90deg");
+ Assert.True(bevel.IsSuccess, Evidence(bevel));
+ Assert.Equal("Bevel", Assert.Single(bevel.Ir!.Mates).GearResult!.Kind);
+
+ var miter = CompileFamilies(
+ "MiterGear A { Module: 1mm Teeth: 24 PressureAngle: 20deg FaceWidth: 5mm BoreDiameter: 5mm }",
+ "MiterGear B { Module: 1mm Teeth: 24 PressureAngle: 20deg FaceWidth: 5mm BoreDiameter: 5mm }",
+ "1,0,0,0, 0,0,1,0, 0,-1,0,0, 0,0,0,1", "ShaftAngle: 90deg");
+ Assert.True(miter.IsSuccess, Evidence(miter));
+
+ var ratchet = CompileFamilies(
+ "RatchetGear A { Teeth: 60 OutsideDiameter: 40mm FaceWidth: 6mm BoreDiameter: 10mm DriveFaceAngle: 0deg }",
+ "Pawl B { Width: 16mm Length: 38mm Thickness: 6mm PivotDiameter: 5mm NoseLength: 6mm EngagementAngle: 15deg }",
+ "1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1", "EngagementPhase: 2deg AllowedDirection: Clockwise");
+ Assert.True(ratchet.IsSuccess, Evidence(ratchet));
+ Assert.Equal("RatchetPawl", Assert.Single(ratchet.Ir!.Mates).GearResult!.Kind);
+ }
+
+ private static AssemblyCompilationResult CompilePair(string secondParameters, double x, string? matrix = null)
+ {
+ matrix ??= $"1,0,0,0, 0,1,0,0, 0,0,1,0, {x},0,0,1";
+ var source = $$"""
+ Units: mm
+ SpurGear A { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+ SpurGear B { {{secondParameters}} FaceWidth: 6mm BoreDiameter: 5mm }
+ Assembly Pair {
+ <Assembly Pair><Part A = A></Part><Part B = B>Placement ImportedOccurrence = [{{matrix}}];</Part></Assembly>
+ Anchor: Pair.A;
+ Interface<Gear> Mesh { A: Pair.A; B: Pair.B; }
+ }
+ """;
+ return new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(source).Source!);
+ }
+
+ private static AssemblyCompilationResult CompileFamilies(string first, string second, string matrix, string options)
+ {
+ var source = $$"""
+ Units: mm
+ {{first}}
+ {{second}}
+ Assembly Pair {
+ <Assembly Pair><Part A = A></Part><Part B = B>Placement ImportedOccurrence = [{{matrix}}];</Part></Assembly>
+ Anchor: Pair.A;
+ Interface<Gear> Mesh { A: Pair.A; B: Pair.B; {{options}} }
+ }
+ """;
+ return new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(source).Source!);
+ }
+
+ private static string Evidence(AssemblyCompilationResult result) =>
+ string.Join(Environment.NewLine, result.Diagnostics.Select(item => item.Code + ": " + item.Message));
+
+ private static string Evidence(AssemblyM1CompilationResult result) =>
+ string.Join(Environment.NewLine, result.Diagnostics.Select(item => item.Code + ": " + item.Message));
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyInterfaceX1Tests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyInterfaceX1Tests.cs
new file mode 100644
index 00000000..be21d34a
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyInterfaceX1Tests.cs
@@ -0,0 +1,161 @@
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Firmament.Tests.Assembly;
+
+public sealed class AssemblyInterfaceX1Tests
+{
+ [Fact]
+ public void MultiFileSubassembliesReuseDefinitionsExposePortsAndRetainHierarchy()
+ {
+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/machine.firmament");
+ var first = new AssemblyM0Pipeline().CompileFile(path);
+ var second = new AssemblyM0Pipeline().CompileFile(path);
+
+ Assert.True(first.IsSuccess, Evidence(first));
+ Assert.Equal(3, first.Ir!.SourceDependencies!.Count);
+ Assert.Equal(2, first.Ir.AssemblyDefinitions!.Count);
+ Assert.Equal(15, first.Ir.Instances.Count);
+ Assert.Equal(first.Ir.Instances.Select(item => item.StableId), second.Ir!.Instances.Select(item => item.StableId));
+ Assert.Equal(2, first.Ir.Instances.Count(item => item.DefinitionIdentity == "Register"));
+ Assert.Equal(4, first.Ir.Instances.Count(item => item.DefinitionIdentity == "DigitModule"));
+ Assert.Contains(first.Ir.Instances, item => item.Path.ToString() == "DifferenceEngineReadiness.RegisterB.Digit1.Shaft");
+ Assert.All(first.Ir.Instances.Where(item => item.DefinitionIdentity is "Register" or "DigitModule"), item => Assert.True(item.IsEncapsulatedDefinition));
+
+ var carry = Assert.Single(first.Ir.Mates);
+ Assert.Equal("RegisterCarry", carry.Name);
+ Assert.All(carry.Roles, role => Assert.DoesNotContain("Digit", role.ParticipantPath.ToString(), StringComparison.Ordinal));
+ Assert.Equal(MechanicalInterfaceFamily.Axial, first.Ir.Interfaces.Single(item => item.Name == "RegisterCarry").Family);
+
+ var register = first.Ir.AssemblyDefinitions.Single(item => item.DefinitionIdentity == "Register");
+ var custom = Assert.Single(register.LocalMates);
+ Assert.Equal(3, custom.ConstraintIds.Count);
+ Assert.Equal("passed", Assert.Single(custom.RequirementResults!).Status);
+ var digit = first.Ir.AssemblyDefinitions.Single(item => item.DefinitionIdentity == "DigitModule");
+ Assert.Equal(2, Assert.Single(digit.LocalMates).ConstraintIds.Count);
+ }
+
+ [Fact]
+ public void TypedFixedAxialAndRevoluteExpandThroughAtomicAuthority()
+ {
+ const string source = """
+ Assembly Typed {
+ <Assembly Typed>
+ <Part Fixed = Block> Semantic Mount { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; } </Part>
+ <Part Moving = Block> Semantic Mount { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; } </Part>
+ </Assembly>
+ Anchor: Typed.Fixed.Mount;
+ Interface<Fixed> Mount { A: Typed.Moving.Mount; B: Typed.Fixed.Mount; }
+ }
+ """;
+ var result = new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(source).Source!);
+ Assert.True(result.IsSuccess, Evidence(result));
+ var definition = Assert.Single(result.Ir!.Interfaces);
+ Assert.True(definition.CompilerOwnedExpansion);
+ Assert.Equal(MechanicalInterfaceFamily.Fixed, definition.Family);
+ Assert.Equal(PlacementConstraintKind.FrameCoincident, Assert.Single(result.Ir.PlacementConstraints).Kind);
+ }
+
+ [Fact]
+ public void FailedCustomRequirementNamesInterfaceAndRequirement()
+ {
+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Invalid/AssemblyInterfaces/failed-custom-require.firmament");
+ var result = new AssemblyM0Pipeline().CompileFile(path);
+ var diagnostic = Assert.Single(result.Diagnostics, item => item.Code == "assembly-interface-requirement-failed");
+ Assert.Contains("ImpossibleClearance", diagnostic.Message, StringComparison.Ordinal);
+ Assert.Contains("ClearancePositive", diagnostic.Message, StringComparison.Ordinal);
+ Assert.Equal("failed", Assert.Single(Assert.Single(result.Ir!.Mates).RequirementResults!).Status);
+ }
+
+ [Fact]
+ public void IncludedSubassemblyLowersWholeTreeOnceToSharedAp242Definition()
+ {
+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/executable-machine.firmament");
+ var compiled = new AssemblyM1Pipeline().CompileFile(path);
+ Assert.True(compiled.IsSuccess, string.Join(Environment.NewLine, compiled.Diagnostics.Select(item => item.Code + ": " + item.Message)));
+ Assert.Equal(2, compiled.Ir!.Instances.Count(item => item.DefinitionIdentity == "ExecutableCell"));
+ Assert.Single(compiled.Ir.AssemblyDefinitions!, item => item.DefinitionIdentity == "ExecutableCell");
+ Assert.Single(compiled.Geometry!.Artifact.Definitions);
+
+ var step = AssemblyIrAp242Exporter.Export(compiled);
+ Assert.True(step.IsSuccess, string.Join(Environment.NewLine, step.Diagnostics.Select(item => item.Message)));
+ var imported = Step242AssemblyImporter.Import(step.Value);
+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(item => item.Message)));
+ var cellDefinition = Assert.Single(imported.Value.Definitions, item => item.Geometry is null && item.Name == "ExecutableCell");
+ Assert.Equal(2, imported.Value.Occurrences.Count(item => item.DefinitionStableId == cellDefinition.StableId));
+ Assert.DoesNotContain(".step", File.ReadAllText(path), StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(".step", File.ReadAllText(Path.Combine(Path.GetDirectoryName(path)!, "executable-cell.firmament")), StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void ParentCannotCrossSubassemblyPrivateBoundary()
+ {
+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Invalid/AssemblyInterfaces/private-internal-access.firmament");
+ var result = new AssemblyM0Pipeline().CompileFile(path);
+ Assert.Contains(result.Diagnostics, item => item.Code == "assembly-internal-member-hidden");
+ }
+
+ [Fact]
+ public void IncludeFailuresAreTypedAndCyclesShowChain()
+ {
+ var directory = Path.Combine(Path.GetTempPath(), "aetheris-assembly-x1-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(directory);
+ try
+ {
+ var missing = Path.Combine(directory, "missing-root.firmament");
+ File.WriteAllText(missing, "Include \"absent.firmament\";\nAssembly Root { <Assembly Root></Assembly> }");
+ Assert.Contains(new AssemblyM0Parser().ParseFile(missing).Diagnostics, item => item.Code == "assembly-include-file-not-found");
+
+ var a = Path.Combine(directory, "a.firmament"); var b = Path.Combine(directory, "b.firmament");
+ File.WriteAllText(a, "Include \"b.firmament\";\nAssembly Root { <Assembly Root></Assembly> }");
+ File.WriteAllText(b, "Include \"a.firmament\";");
+ var cycle = Assert.Single(new AssemblyM0Parser().ParseFile(a).Diagnostics, item => item.Code == "assembly-include-cycle");
+ Assert.Contains("a.firmament -> b.firmament -> a.firmament", cycle.Message, StringComparison.OrdinalIgnoreCase);
+
+ var nested = Path.Combine(directory, "nested"); Directory.CreateDirectory(nested);
+ var outside = Path.Combine(directory, "outside.firmament"); File.WriteAllText(outside, "Subassembly Outside { <Assembly Outside></Assembly> }");
+ var escaping = Path.Combine(nested, "root.firmament"); File.WriteAllText(escaping, "Include \"../outside.firmament\";\nAssembly Root { <Assembly Root></Assembly> }");
+ Assert.Contains(new AssemblyM0Parser().ParseFile(escaping).Diagnostics, item => item.Code == "assembly-include-outside-root");
+
+ const string duplicate = """
+ Subassembly Same { <Assembly Same></Assembly> }
+ Subassembly Same { <Assembly Same></Assembly> }
+ Interface<Axial> Pair { }
+ Interface<Axial> Pair { }
+ Assembly Root { <Assembly Root></Assembly> }
+ """;
+ var duplicateDiagnostics = new AssemblyM0Parser().Parse(duplicate).Diagnostics;
+ Assert.Contains(duplicateDiagnostics, item => item.Code == "assembly-template-duplicate-definition");
+ Assert.Contains(duplicateDiagnostics, item => item.Code == "assembly-interface-duplicate-name");
+ }
+ finally { Directory.Delete(directory, true); }
+ }
+
+ [Fact]
+ public void OneDefinitionCanBackOneHundredDeterministicOccurrences()
+ {
+ var occurrences = string.Join(Environment.NewLine, Enumerable.Range(0, 100).Select(index => $"<Assembly Cell{index} = Cell></Assembly>"));
+ var mates = string.Join(Environment.NewLine, Enumerable.Range(1, 99).Select(index => $"Mate Link{index}: Chain {{ A: Stress.Cell{index}.Port; B: Stress.Cell{index - 1}.Port; }}"));
+ var source = $$"""
+ Subassembly Cell {
+ <Assembly Cell><Part Body = CellBody> Semantic Port { Axis Axis = [0,0,0] -> [0,0,1]; } </Part></Assembly>
+ Anchor: Cell.Body.Port;
+ Expose { Semantic Port = Body.Port; }
+ }
+ Interface<Axial> Chain { Role A requires AxisCapable; Role B requires AxisCapable; }
+ Assembly Stress {
+ <Assembly Stress>{{occurrences}}</Assembly>
+ Anchor: Stress.Cell0.Port;
+ {{mates}}
+ }
+ """;
+ var first = new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(source).Source!);
+ var second = new AssemblyM0Compiler().Compile(new AssemblyM0Parser().Parse(source).Source!);
+ Assert.True(first.IsSuccess, Evidence(first));
+ Assert.Single(first.Ir!.AssemblyDefinitions!);
+ Assert.Equal(100, first.Ir.Instances.Count(item => item.DefinitionIdentity == "Cell"));
+ Assert.Equal(first.Ir.Instances.Select(item => item.StableId), second.Ir!.Instances.Select(item => item.StableId));
+ }
+
+ private static string Evidence(AssemblyCompilationResult result) => string.Join(Environment.NewLine, result.Diagnostics.Select(item => item.Code + ": " + item.Message));
+}
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs
index 931ce18d..db1c0d2f 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs
@@ -1,6 +1,7 @@
using System.Diagnostics;
using System.Numerics;
using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Firmament.FirmamentV2;
using Aetheris.Semantics;
namespace Aetheris.Kernel.Firmament.Assembly;
@@ -32,6 +33,7 @@ public sealed class AssemblyM0Compiler
var mateWatch = Stopwatch.StartNew();
var mates = BindMates(source, interfaces, byPath, diagnostics);
+ mates = ValidateInterfaceRequirements(mates, interfaces, diagnostics);
var panelMateEvidence = ValidatePanelEdgeMates(mates, interfaces, instances, diagnostics);
mateWatch.Stop();
@@ -43,6 +45,7 @@ public sealed class AssemblyM0Compiler
{
ResolvedTransform = placements.First(x => x.InstanceStableId == instance.StableId).Transform
}).ToArray();
+ mates = ValidateGearInterfaces(mates, interfaces, instances, diagnostics);
placementWatch.Stop();
var graphWatch = Stopwatch.StartNew();
@@ -75,7 +78,7 @@ public sealed class AssemblyM0Compiler
.OrderBy(solution => solution.MateStableId, StringComparer.Ordinal).ToArray();
var ir = new AssemblyIr("aetheris/assembly-ir/m0", $"assembly:{source.Name}", source.Name,
instances.Single(x => x.ParentStableId is null).StableId, instances, source.Interfaces, mates,
- constraints, placements, relations, stackups, fits, diagnostics, assemblyDefinitions, panelMateEvidence, datums, datumSolutions);
+ constraints, placements, relations, stackups, fits, diagnostics, assemblyDefinitions, panelMateEvidence, datums, datumSolutions, source.SourceDependencies);
return new(ir, diagnostics, perf);
static string SemanticPath(AssemblyInstanceIr instance, SemanticValue value)
@@ -87,6 +90,27 @@ public sealed class AssemblyM0Compiler
}
}
+ private static IReadOnlyList<MateIr> ValidateInterfaceRequirements(IReadOnlyList<MateIr> mates,
+ IReadOnlyDictionary<string, InterfaceDefinition> interfaces, List<AssemblyDiagnostic> diagnostics)
+ {
+ return mates.Select(mate =>
+ {
+ var definition = interfaces.Values.Single(item => item.StableId == mate.InterfaceStableId);
+ var results = (definition.PredicateRequirements ?? []).Select(requirement =>
+ {
+ if (!requirement.Passed)
+ diagnostics.Add(new("assembly-interface-requirement-failed",
+ $"Interface '{definition.Name}' on Mate '{mate.Name}' failed Require '{requirement.Name}': {requirement.Expression}."));
+ return new InterfaceRequirementResultIr(requirement.Name, requirement.Expression, requirement.Passed ? "passed" : "failed");
+ }).ToArray();
+ return mate with
+ {
+ RequirementResults = results,
+ ValidationStatus = mate.ValidationStatus == "valid" && results.All(item => item.Status == "passed") ? "valid" : "invalid"
+ };
+ }).ToArray();
+ }
+
private static IReadOnlyList<AssemblyInstanceIr> BindInstances(AssemblySource source, List<AssemblyDiagnostic> diagnostics)
{
var pending = new List<(AssemblyMemberSource member, AssemblyPath path, string? parent)>();
@@ -115,9 +139,11 @@ public sealed class AssemblyM0Compiler
value.ExposedMembers.OrderBy(x => x.Key, StringComparer.Ordinal).Select(x => Clone(x.Value, semanticPath + "." + x.Key, x.Key)),
[.. value.Provenance, new("assembly-instance", path.ToString(), value.StableIdentity, SemanticSourceSpan.Generated(sourceIdentity))],
value.AuthoredSourceSpan, SemanticSourceSpan.Generated(sourceIdentity), exposedName);
- return new SemanticValue($"assembly-semantic:{path}", new(member.Kind.ToString()),
+ var endpoint = member.TypedEndpoint;
+ return new SemanticValue($"assembly-semantic:{path}", endpoint?.Type ?? new(member.Kind.ToString()),
+ endpoint?.Capabilities.Values, endpoint?.Bindings,
exposedMembers: member.ExposedSemantics.OrderBy(x => x.ExposedName, StringComparer.Ordinal).Select(x => Clone(x, x.ExposedName ?? x.StableIdentity, x.ExposedName)),
- provenance: [new("assembly-instance", path.ToString(), member.DefinitionIdentity, SemanticSourceSpan.Generated(sourceIdentity))],
+ provenance: [.. endpoint?.Provenance ?? [], new("assembly-instance", path.ToString(), member.DefinitionIdentity, SemanticSourceSpan.Generated(sourceIdentity))],
generatedSourceSpan: SemanticSourceSpan.Generated(sourceIdentity));
}
@@ -131,26 +157,33 @@ public sealed class AssemblyM0Compiler
{ diagnostics.Add(new("assembly-interface-unknown", $"Mate '{mate.Name}' references unknown Interface '{mate.InterfaceName}'.")); continue; }
var duplicate = mate.Roles.GroupBy(x => x.Role, StringComparer.Ordinal).FirstOrDefault(x => x.Count() > 1);
if (duplicate is not null) diagnostics.Add(new(DuplicateRole, $"Mate '{mate.Name}' assigns Role '{duplicate.Key}' more than once."));
+ var valid = duplicate is null;
var endpoints = new List<MateEndpointIr>();
foreach (var role in definition.Roles)
{
var assignment = mate.Roles.FirstOrDefault(x => x.Role == role.Name);
- if (assignment is null) { diagnostics.Add(new(MissingRole, $"Mate '{mate.Name}' is missing required Role '{role.Name}'.")); continue; }
+ if (assignment is null) { valid = false; diagnostics.Add(new(MissingRole, $"Mate '{mate.Name}' is missing required Role '{role.Name}'.")); continue; }
if (!TryResolve(assignment.Participant, byPath.Values, out var reference))
{
var boundary = EncapsulationBoundary(assignment.Participant, byPath.Values);
diagnostics.Add(boundary is null
? new(OutsideScope, $"Mate '{mate.Name}' Role '{role.Name}' participant '{assignment.Participant}' is not reachable in the Assembly tree.")
: new("assembly-internal-member-hidden", $"'{assignment.Participant}' crosses the private boundary of Assembly '{boundary.Path}'. Expose a semantic member from the Assembly if parent assemblies must depend on it."));
+ valid = false;
continue;
}
var missing = role.RequiredCapabilities.Where(c => !HasCapability(reference!.Value, c)).ToArray();
+ if (reference!.Value.Type.Name == "Gear" && definition.Family != MechanicalInterfaceFamily.Gear)
+ missing = [.. missing, $"endpoint type {definition.Family} (Gear is not implicitly coerced)"];
if (missing.Length > 0)
+ {
+ valid = false;
diagnostics.Add(new(CapabilityMismatch, $"Mate '{mate.Name}' Role '{role.Name}' participant '{assignment.Participant}' lacks: {string.Join(", ", missing)}."));
+ }
endpoints.Add(new(role.Name, assignment.Participant, reference!.Value.StableIdentity, role.RequiredCapabilities));
}
result.Add(new($"mate:{source.Name}:{mate.Name}", mate.Name, definition.StableId, endpoints, [],
- endpoints.Count == definition.Roles.Count ? "valid" : "invalid"));
+ valid && endpoints.Count == definition.Roles.Count ? "valid" : "invalid"));
}
return result;
}
@@ -158,6 +191,78 @@ public sealed class AssemblyM0Compiler
private static bool HasCapability(SemanticValue value, string capability) =>
value.Capabilities.Values.Any(x => string.Equals(x.Name, capability, StringComparison.Ordinal));
+ private static IReadOnlyList<MateIr> ValidateGearInterfaces(IReadOnlyList<MateIr> mates,
+ IReadOnlyDictionary<string, InterfaceDefinition> interfaces, IReadOnlyList<AssemblyInstanceIr> instances,
+ List<AssemblyDiagnostic> diagnostics)
+ {
+ var values = Flatten(instances.Select(instance => instance.SemanticRoot)).ToDictionary(value => value.StableIdentity, StringComparer.Ordinal);
+ return mates.Select(mate =>
+ {
+ var definition = interfaces.Values.Single(item => item.StableId == mate.InterfaceStableId);
+ if (definition.Family != MechanicalInterfaceFamily.Gear || mate.Roles.Count != 2) return mate;
+ var endpointA = mate.Roles.SingleOrDefault(role => role.Role == "A");
+ var endpointB = mate.Roles.SingleOrDefault(role => role.Role == "B");
+ if (endpointA is null || endpointB is null
+ || !values.TryGetValue(endpointA.ParticipantSemanticValueId, out var valueA)
+ || !values.TryGetValue(endpointB.ParticipantSemanticValueId, out var valueB)
+ || !valueA.TryBinding<TypedSemanticAuthorityBinding<GearAir>>(out var bindingA)
+ || !valueB.TryBinding<TypedSemanticAuthorityBinding<GearAir>>(out var bindingB)) return mate;
+
+ var options = definition.GearOptions ?? new(null, null, null);
+ var evaluated = GearAuthoring.EvaluateInterface(mate.Name, bindingA.Authority, bindingB.Authority,
+ options.ShaftAngleDegrees, options.EngagementPhaseDegrees, options.AllowedDirection,
+ new(0, 0));
+ var ownerA = OwnerInstance(valueA.StableIdentity, instances)!;
+ var ownerB = OwnerInstance(valueB.StableIdentity, instances)!;
+ var spatialA = Spatial(endpointA, ownerA, valueA, bindingA.Authority);
+ var spatialB = Spatial(endpointB, ownerB, valueB, bindingB.Authority);
+ var delta = new Vector3((float)(spatialB.Origin[0] - spatialA.Origin[0]), (float)(spatialB.Origin[1] - spatialA.Origin[1]), (float)(spatialB.Origin[2] - spatialA.Origin[2]));
+ var actualCenter = delta.Length();
+ var axisA = Vector3.Normalize(new((float)spatialA.Axis[0], (float)spatialA.Axis[1], (float)spatialA.Axis[2]));
+ var axisB = Vector3.Normalize(new((float)spatialB.Axis[0], (float)spatialB.Axis[1], (float)spatialB.Axis[2]));
+ var angle = Math.Acos(Math.Clamp(Math.Abs(Vector3.Dot(axisA, axisB)), -1f, 1f)) * 180d / Math.PI;
+ var rejection = evaluated.RejectionReasons.ToList();
+ var bevel = bindingA.Authority.Family is GearFamily.BevelGear or GearFamily.MiterGear
+ && bindingB.Authority.Family is GearFamily.BevelGear or GearFamily.MiterGear;
+ if (!bevel && evaluated.Kind != "RatchetPawl" && angle > 1e-5) rejection.Add("axis-relation-mismatch");
+ if (!bevel && evaluated.Kind != "RatchetPawl" && Math.Abs(Vector3.Dot(delta, axisA)) > 1e-5)
+ rejection.Add("axis-relation-mismatch");
+ if (bevel && evaluated.ShaftAngleDegrees is { } expectedAngle
+ && Math.Abs(angle - Math.Min(expectedAngle, 180d - expectedAngle)) > 1e-5) rejection.Add("axis-relation-mismatch");
+ var axisCross = Vector3.Cross(axisA, axisB);
+ if (bevel && axisCross.Length() > 1e-6f && Math.Abs(Vector3.Dot(delta, Vector3.Normalize(axisCross))) > 1e-5)
+ rejection.Add("axis-relation-mismatch");
+ if (evaluated.ExpectedCenterDistanceMm is { } expectedCenter && Math.Abs(actualCenter - expectedCenter) > 1e-5)
+ rejection.Add("center-distance-mismatch");
+ rejection = rejection.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList();
+ foreach (var reason in rejection)
+ diagnostics.Add(new("firmament-gear-interface-incompatible", $"Interface<Gear> '{mate.Name}' between '{spatialA.HierarchicalPath}' and '{spatialB.HierarchicalPath}' is incompatible: {reason}."));
+ var result = new GearInterfaceResultIr(spatialA, spatialB, evaluated.Kind, evaluated.Ratio, evaluated.RotationSign,
+ evaluated.AxisRelation, evaluated.ExpectedCenterDistanceMm, actualCenter, rejection.Count == 0 ? "compatible" : "incompatible", rejection);
+ return mate with { GearResult = result, ValidationStatus = mate.ValidationStatus == "valid" && rejection.Count == 0 ? "valid" : "invalid" };
+ }).ToArray();
+
+ static GearEndpointIr Spatial(MateEndpointIr endpoint, AssemblyInstanceIr owner, SemanticValue value, GearAir gear)
+ {
+ var matrix = owner.ResolvedTransform is null ? Matrix4x4.Identity : ToMatrix(owner.ResolvedTransform);
+ value.TryBinding<ExactAxisBinding>(out var localAxis);
+ var localOrigin = localAxis is null ? Vector3.Zero : new((float)localAxis.OriginX, (float)localAxis.OriginY, (float)localAxis.OriginZ);
+ var localDirection = localAxis is null ? new Vector3((float)gear.Axis[0], (float)gear.Axis[1], (float)gear.Axis[2])
+ : new((float)localAxis.DirectionX, (float)localAxis.DirectionY, (float)localAxis.DirectionZ);
+ var origin = Vector3.Transform(localOrigin, matrix);
+ var direction = Vector3.Normalize(Vector3.TransformNormal(localDirection, matrix));
+ var exposedPath = string.Join('/', endpoint.ParticipantPath.Segments);
+ var occurrenceSegments = bindingPath(value) is { Count: > 0 } relative ? owner.Path.Segments.Concat(relative).ToArray() : owner.Path.Segments.ToArray();
+ var hierarchyPath = string.Join('/', occurrenceSegments);
+ return new(exposedPath, hierarchyPath, gear.Name, "assembly-instance:" + string.Join('.', occurrenceSegments), gear.Family, gear.Teeth,
+ gear.ModuleMm, gear.PressureAngleDegrees, gear.PitchDiameterMm, gear.PhaseDegrees,
+ [origin.X, origin.Y, origin.Z], [direction.X, direction.Y, direction.Z]);
+
+ static IReadOnlyList<string>? bindingPath(SemanticValue semantic) =>
+ semantic.TryBinding<TypedSemanticAuthorityBinding<GearAir>>(out var binding) ? binding.RelativeOccurrencePath : null;
+ }
+ }
+
private static IReadOnlyList<PanelMateEvidenceIr> ValidatePanelEdgeMates(
IReadOnlyList<MateIr> mates,IReadOnlyDictionary<string,InterfaceDefinition> interfaces,
IReadOnlyList<AssemblyInstanceIr> instances,List<AssemblyDiagnostic> diagnostics)
@@ -446,11 +551,12 @@ public sealed class AssemblyM0Compiler
private static IReadOnlyList<DimensionalRelationIr> LowerAssemblyDefinitionRelations(AssemblySource source, IReadOnlyList<AssemblyInstanceIr> instances)
{
var definitions = source.Root.Flatten().Where(member => member.SolvedAssemblyDefinition is not null)
- .ToDictionary(member => member.Name, member => member.SolvedAssemblyDefinition!, StringComparer.Ordinal);
+ .Select(member => member.SolvedAssemblyDefinition!).DistinctBy(definition => definition.DefinitionIdentity)
+ .ToDictionary(definition => definition.DefinitionIdentity, StringComparer.Ordinal);
var result = new List<DimensionalRelationIr>();
foreach (var instance in instances.Where(item => item.IsEncapsulatedDefinition))
{
- if (!definitions.TryGetValue(instance.Path.Segments.Last(), out var definition)) continue;
+ if (!definitions.TryGetValue(instance.DefinitionIdentity, out var definition)) continue;
foreach (var relation in definition.PublicDimensionalRelations)
{
if (!instance.SemanticRoot.ExposedMembers.TryGetValue(relation.FromSemanticValueId, out var from)
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs
index 36c1bd43..a49613f1 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs
@@ -1,4 +1,5 @@
using Aetheris.Semantics;
+using Aetheris.Kernel.Firmament.FirmamentV2;
namespace Aetheris.Kernel.Firmament.Assembly;
@@ -8,6 +9,7 @@ public enum PlacementConstraintKind { AxisCoincident, AxisAligned, PlaneCoincide
public enum DatumOrientationRelation { SameDirection, OpposedDirection }
public enum PlacementStatus { Anchored, Resolved, Underconstrained, Overconstrained, Unresolved }
public enum PlacementAuthority { MateDerived, ImportedOccurrence, LegacyExplicit }
+public enum MechanicalInterfaceFamily { Custom, Fixed, Axial, Revolute, Gear }
public sealed record AssemblyDiagnostic(string Code, string Message, AssemblyDiagnosticSeverity Severity = AssemblyDiagnosticSeverity.Error);
public sealed record AssemblyPath(IReadOnlyList<string> Segments)
@@ -27,6 +29,7 @@ public sealed record ManufacturingVariationDefinition(double LinearToleranceMm,
double CoatingThicknessToleranceMm, double EngagementLengthMm);
public sealed record InterfaceFitDefinition(string ShaftRole, string ShaftDimension, string BoreRole, string BoreDimension,
double ClearanceScale = 1d, InterfaceClearancePolicyDefinition? Policy = null, ManufacturingVariationDefinition? Variation = null);
+public sealed record InterfacePredicateRequirementDefinition(string Name, string Expression, bool Passed);
public enum FitClassification { GuaranteedClearance, PossibleContact, PossibleInterference, GuaranteedInterference, Unknown }
public sealed record InterfaceDefinition(
string StableId, string Name, IReadOnlyList<InterfaceRoleDefinition> Roles,
@@ -36,7 +39,13 @@ public sealed record InterfaceDefinition(
SemanticSourceSpan? SourceSpan = null,
string? Continuity = null,
string EdgeCorrespondence = "OppositeDirections",
- double GapToleranceMm = 1e-6);
+ double GapToleranceMm = 1e-6,
+ MechanicalInterfaceFamily Family = MechanicalInterfaceFamily.Custom,
+ bool CompilerOwnedExpansion = false,
+ IReadOnlyList<InterfacePredicateRequirementDefinition>? PredicateRequirements = null,
+ GearInterfaceOptions? GearOptions = null);
+
+public sealed record GearInterfaceOptions(double? ShaftAngleDegrees, double? EngagementPhaseDegrees, string? AllowedDirection);
public sealed record AssemblyMemberSource(
string Name, AssemblyInstanceKind Kind, string DefinitionIdentity,
@@ -47,7 +56,8 @@ public sealed record AssemblyMemberSource(
AssemblyTransform? ExplicitTransform = null,
PlacementAuthority PlacementAuthority = PlacementAuthority.MateDerived,
bool IsEncapsulatedDefinition = false,
- AssemblyDefinitionIr? SolvedAssemblyDefinition = null);
+ AssemblyDefinitionIr? SolvedAssemblyDefinition = null,
+ SemanticValue? TypedEndpoint = null);
/// <summary>A reusable, locally-authored Assembly product definition. Its children
/// remain product-visible, while only <see cref="AssemblyMemberSource.ExposedSemantics"/>
@@ -76,7 +86,10 @@ public sealed record AssemblySource(
IReadOnlyList<ToleranceStackupAssertSource> StackupAsserts,
string SourceIdentity,
string? DefinitionSource = null,
- IReadOnlyList<AssemblyDefinitionSource>? AssemblyDefinitions = null);
+ IReadOnlyList<AssemblyDefinitionSource>? AssemblyDefinitions = null,
+ IReadOnlyList<AssemblySourceDependencyIr>? SourceDependencies = null);
+
+public sealed record AssemblySourceDependencyIr(string Path, string Sha256, bool IsRoot);
public sealed record AssemblyTransform(double[] Matrix)
{
@@ -92,7 +105,18 @@ public sealed record AssemblyInstanceIr(
bool IsEncapsulatedDefinition = false);
public sealed record MateEndpointIr(string Role, AssemblyPath ParticipantPath, string ParticipantSemanticValueId, IReadOnlyList<string> RequiredCapabilities);
-public sealed record MateIr(string StableId, string Name, string InterfaceStableId, IReadOnlyList<MateEndpointIr> Roles, IReadOnlyList<string> ConstraintIds, string ValidationStatus);
+public sealed record InterfaceRequirementResultIr(string Name, string Expression, string Status);
+public sealed record GearEndpointIr(
+ string ExposedPortPath, string HierarchicalPath, string DefinitionIdentity, string OccurrenceIdentity,
+ GearFamily Family, int? Teeth, double? ModuleMm, double? PressureAngleDegrees,
+ double? PitchDiameterMm, double PhaseDegrees, double[] Origin, double[] Axis);
+public sealed record GearInterfaceResultIr(
+ GearEndpointIr A, GearEndpointIr B, string Kind, double? Ratio, int RotationSign,
+ string AxisRelation, double? ExpectedCenterDistanceMm, double ActualCenterDistanceMm,
+ string CompatibilityStatus, IReadOnlyList<string> RejectionReasons);
+public sealed record MateIr(string StableId, string Name, string InterfaceStableId, IReadOnlyList<MateEndpointIr> Roles, IReadOnlyList<string> ConstraintIds, string ValidationStatus,
+ IReadOnlyList<InterfaceRequirementResultIr>? RequirementResults = null,
+ GearInterfaceResultIr? GearResult = null);
public sealed record PanelMateEvidenceIr(string MateStableId,string FirstEdgeStableId,string SecondEdgeStableId,string Continuity,string Correspondence,double EndpointResidualMm,double G0ResidualMm,string Status);
public sealed record PlacementConstraintIr(
string StableId, PlacementConstraintKind Kind, string MateStableId,
@@ -160,7 +184,8 @@ public sealed record AssemblyIr(
IReadOnlyList<AssemblyDefinitionIr>? AssemblyDefinitions = null,
IReadOnlyList<PanelMateEvidenceIr>? PanelMateEvidence = null,
IReadOnlyList<AssemblyDatumIr>? Datums = null,
- IReadOnlyList<DatumMateSolutionIr>? DatumMateSolutions = null);
+ IReadOnlyList<DatumMateSolutionIr>? DatumMateSolutions = null,
+ IReadOnlyList<AssemblySourceDependencyIr>? SourceDependencies = null);
public sealed record AssemblyCompilationResult(AssemblyIr? Ir, IReadOnlyList<AssemblyDiagnostic> Diagnostics, AssemblyPerformanceIr? Performance = null)
{
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs
index a65ab83f..6dd22d3b 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs
@@ -1,6 +1,8 @@
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
+using System.Numerics;
+using Aetheris.Kernel.Firmament.FirmamentV2;
using Aetheris.Semantics;
namespace Aetheris.Kernel.Firmament.Assembly;
@@ -11,17 +13,49 @@ public sealed class AssemblyM0Parser
public sealed record ParseResult(AssemblySource? Source, IReadOnlyList<AssemblyDiagnostic> Diagnostics, double ElapsedMilliseconds)
{ public bool IsSuccess => Source is not null && Diagnostics.All(x => x.Severity != AssemblyDiagnosticSeverity.Error); }
- public ParseResult ParseFile(string path) => Parse(File.ReadAllText(path), Path.GetFullPath(path));
+ public ParseResult ParseFile(string path)
+ {
+ var fullPath = Path.GetFullPath(path);
+ var loadDiagnostics = new List<AssemblyDiagnostic>();
+ var dependencies = new List<AssemblySourceDependencyIr>();
+ var allowedRoot = FindAllowedSourceRoot(fullPath);
+ var source = LoadSourceGraph(fullPath, allowedRoot, [], dependencies, loadDiagnostics);
+ if (source is null) return new(null, loadDiagnostics, 0);
+ var parsed = Parse(source, fullPath);
+ var diagnostics = loadDiagnostics.Concat(parsed.Diagnostics).ToArray();
+ return new(parsed.Source is null ? null : parsed.Source with { SourceDependencies = dependencies }, diagnostics, parsed.ElapsedMilliseconds);
+ }
+
+ private static string FindAllowedSourceRoot(string path)
+ {
+ var directory = new DirectoryInfo(Path.GetDirectoryName(path)!);
+ while (directory is not null)
+ {
+ if (File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) return directory.FullName;
+ directory = directory.Parent;
+ }
+ return Path.GetDirectoryName(path)!;
+ }
public ParseResult Parse(string input, string sourceIdentity = "<memory>")
{
var watch = Stopwatch.StartNew();
var diagnostics = new List<AssemblyDiagnostic>();
var source = Regex.Replace(input, @"//[^\r\n]*", string.Empty);
+ // Subassembly is a first-class non-parameterized Assembly definition. It
+ // lowers through the existing, locally solved definition authority.
+ source = Regex.Replace(source, @"\bSubassembly\s+(?<name>[A-Za-z_]\w*)\s*\{",
+ "Template < __Unit: __Unit > Assembly ${name} {", RegexOptions.CultureInvariant);
+ var gearDocument = GearAuthoring.HasGearDefinitions(source)
+ ? GearAuthoring.ParseDefinitions(source)
+ : new GearAuthoringDocument("GearModel", [], [], []);
+ var gearAuthorities = gearDocument.Gears.ToDictionary(gear => gear.Name, StringComparer.Ordinal);
+ foreach (var diagnostic in gearDocument.Diagnostics.Where(item => item != GearAuthoring.Prefix + "declaration-missing"))
+ diagnostics.Add(new("assembly-" + diagnostic.Split(':')[0], diagnostic));
var concepts = ParseAssemblyConcepts(source, sourceIdentity, diagnostics);
var interfaces = ParseInterfaces(source, sourceIdentity, diagnostics);
var templateRanges = new List<(int Start, int Length)>();
- var assemblyDefinitions = ParseAssemblyDefinitions(source, sourceIdentity, interfaces, concepts, diagnostics, templateRanges);
+ var assemblyDefinitions = ParseAssemblyDefinitions(source, sourceIdentity, interfaces, concepts, gearAuthorities, diagnostics, templateRanges);
// Template-produced Assembly bodies are declarations, not exported roots.
// Blank them without changing offsets, then locate the single root Assembly.
var rootSearch = source.ToCharArray();
@@ -33,7 +67,7 @@ public sealed class AssemblyM0Parser
var body = BalancedBody(source, assemblyHeader.Index + assemblyHeader.Length - 1, diagnostics, "Assembly");
if (body is null) return Done(null);
var specializationCache = new Dictionary<string, AssemblyMemberSource>(StringComparer.Ordinal);
- var tree = ParseTree(body, sourceIdentity, diagnostics, assemblyDefinitions, interfaces, specializationCache);
+ var tree = ParseTree(body, sourceIdentity, diagnostics, assemblyDefinitions, interfaces, specializationCache, gearAuthorities);
if (tree is null) return Done(null);
var mates = ParseMates(body, sourceIdentity, diagnostics);
var relations = ParseRelations(body, diagnostics);
@@ -42,7 +76,8 @@ public sealed class AssemblyM0Parser
var anchor = anchorMatch.Success ? AssemblyPath.Parse(anchorMatch.Groups["path"].Value) : new AssemblyPath([tree.Name]);
var definitionBoundary = new[]
{
- Regex.Match(source, @"^[ \t]*Interface\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant | RegexOptions.Multiline),
+ Regex.Match(source, @"^[ \t]*Interface(?:\s*<[^>]+>)?\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant | RegexOptions.Multiline),
+ Regex.Match(source, @"^[ \t]*Template\s*<[^>]+>\s*Assembly\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant | RegexOptions.Multiline),
Regex.Match(source, @"^[ \t]*Assembly\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant | RegexOptions.Multiline)
}.Where(match => match.Success).Select(match => match.Index).DefaultIfEmpty(0).Min();
var declarationChars = source.ToCharArray();
@@ -55,6 +90,42 @@ public sealed class AssemblyM0Parser
ParseResult Done(AssemblySource? value) { watch.Stop(); return new(value, diagnostics, watch.Elapsed.TotalMilliseconds); }
}
+ private static string? LoadSourceGraph(string path, string allowedRoot, IReadOnlyList<string> stack,
+ List<AssemblySourceDependencyIr> dependencies, List<AssemblyDiagnostic> diagnostics)
+ {
+ var fullPath = Path.GetFullPath(path);
+ var rootPrefix = Path.TrimEndingDirectorySeparator(Path.GetFullPath(allowedRoot)) + Path.DirectorySeparatorChar;
+ if (!fullPath.StartsWith(rootPrefix, StringComparison.OrdinalIgnoreCase) && !string.Equals(fullPath, Path.TrimEndingDirectorySeparator(Path.GetFullPath(allowedRoot)), StringComparison.OrdinalIgnoreCase))
+ { diagnostics.Add(new("assembly-include-outside-root", $"Include '{path}' resolves outside allowed root '{allowedRoot}'.")); return null; }
+ var cycleAt = stack.ToList().FindIndex(item => string.Equals(item, fullPath, StringComparison.OrdinalIgnoreCase));
+ if (cycleAt >= 0)
+ {
+ var cycle = stack.Skip(cycleAt).Append(fullPath).Select(Path.GetFileName);
+ diagnostics.Add(new("assembly-include-cycle", $"Compile-time Include cycle: {string.Join(" -> ", cycle)}."));
+ return null;
+ }
+ if (!File.Exists(fullPath))
+ { diagnostics.Add(new("assembly-include-file-not-found", $"Included Firmament source '{fullPath}' was not found.")); return null; }
+ if (stack.Count > 0 && !string.Equals(Path.GetExtension(fullPath), ".firmament", StringComparison.OrdinalIgnoreCase))
+ { diagnostics.Add(new("assembly-include-extension-invalid", $"Compile-time Include '{fullPath}' must reference a .firmament semantic source file.")); return null; }
+ var text = File.ReadAllText(fullPath);
+ var hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(text)));
+ if (dependencies.Any(item => string.Equals(item.Path, fullPath, StringComparison.OrdinalIgnoreCase))) return string.Empty;
+ dependencies.Add(new(fullPath, hash, stack.Count == 0));
+ var declarations = new List<string>();
+ foreach (Match include in Regex.Matches(text, @"^[ \t]*Include\s+""(?<path>[^""]+)""\s*;", RegexOptions.CultureInvariant | RegexOptions.Multiline))
+ {
+ var relative = include.Groups["path"].Value;
+ var childPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(fullPath)!, relative));
+ var child = LoadSourceGraph(childPath, allowedRoot, [.. stack, fullPath], dependencies, diagnostics);
+ if (child is null) return null;
+ declarations.Add(child);
+ }
+ var local = Regex.Replace(text, @"^[ \t]*Include\s+""[^""]+""\s*;[ \t]*(?:\r?\n)?", string.Empty, RegexOptions.CultureInvariant | RegexOptions.Multiline);
+ declarations.Add(local);
+ return string.Join(Environment.NewLine, declarations);
+ }
+
private static IReadOnlyList<AssemblyConceptDefinition> ParseAssemblyConcepts(string source, string sourceIdentity, List<AssemblyDiagnostic> diagnostics)
{
var result = new List<AssemblyConceptDefinition>();
@@ -73,11 +144,12 @@ public sealed class AssemblyM0Parser
private static IReadOnlyList<InterfaceDefinition> ParseInterfaces(string source, string sourceIdentity, List<AssemblyDiagnostic> diagnostics)
{
var result = new List<InterfaceDefinition>();
- foreach (Match header in Regex.Matches(source, @"\bInterface\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
+ foreach (Match header in Regex.Matches(source, @"\bInterface(?:\s*<\s*(?<family>Custom|Fixed|Axial|Revolute|Gear)\s*>)?\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
{
var body = BalancedBody(source, header.Index + header.Length - 1, diagnostics, "Interface");
if (body is null) continue;
var name = header.Groups["name"].Value;
+ var family = header.Groups["family"].Success ? Enum.Parse<MechanicalInterfaceFamily>(header.Groups["family"].Value) : MechanicalInterfaceFamily.Custom;
var roles = Regex.Matches(body, @"\bRole\s+(?<name>[A-Za-z_]\w*)\s+requires\s+(?<caps>[A-Za-z, ]+)\s*;", RegexOptions.CultureInvariant)
.Select(m => new InterfaceRoleDefinition(m.Groups["name"].Value,
m.Groups["caps"].Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))).ToArray();
@@ -91,6 +163,11 @@ public sealed class AssemblyM0Parser
m.Groups["b"].Value, m.Groups["bm"].Success ? m.Groups["bm"].Value : ".", 0,
m.Groups["orientation"].Success ? Enum.Parse<DatumOrientationRelation>(m.Groups["orientation"].Value) : DatumOrientationRelation.SameDirection));
requirements = requirements.Concat(frameRequirements).ToArray();
+ var atomicRequirements = Regex.Matches(body, @"\bMate\s+(?<kind>AxisCoincident|AxisAligned|PlaneCoincident|PointCoincident|OffsetAlongAxis|FrameCoincident)\s+(?<a>A|B)\.(?<am>[A-Za-z_]\w*)\s+(?<b>A|B)\.(?<bm>[A-Za-z_]\w*)(?:\s+(?<offset>[-+]?\d+(?:\.\d+)?)mm)?\s*;", RegexOptions.CultureInvariant)
+ .Select(m => new InterfaceRequirementDefinition(Enum.Parse<PlacementConstraintKind>(m.Groups["kind"].Value),
+ m.Groups["a"].Value, m.Groups["am"].Value, m.Groups["b"].Value, m.Groups["bm"].Value,
+ m.Groups["offset"].Success ? Number(m.Groups["offset"].Value) : 0)).ToArray();
+ requirements = requirements.Concat(atomicRequirements).ToArray();
var fitMatch = Regex.Match(body, @"\bFit\s+(?<a>[A-Za-z_]\w*)\.(?<am>[A-Za-z_]\w*)\s+inside\s+(?<b>[A-Za-z_]\w*)\.(?<bm>[A-Za-z_]\w*)(?:\s+(?<perSide>per-side))?\s*;", RegexOptions.CultureInvariant);
var policyMatch = Regex.Match(body, @"\bClearancePolicy\s+Minimum\s+(?<min>[-+]?\d+(?:\.\d+)?)mm\s+Maximum\s+(?<max>[-+]?\d+(?:\.\d+)?)mm\s*;", RegexOptions.CultureInvariant);
var variationMatch = Regex.Match(body, @"\bVariation\s+Linear\s+(?<linear>\d+(?:\.\d+)?)mm\s+Thickness\s+(?<thickness>\d+(?:\.\d+)?)mm\s+BendAngle\s+(?<angle>\d+(?:\.\d+)?)deg\s+BendLocation\s+(?<location>\d+(?:\.\d+)?)mm\s+Coating\s+(?<coating>\d+(?:\.\d+)?)mm\s+CoatingTolerance\s+(?<coatingTol>\d+(?:\.\d+)?)mm\s+Engagement\s+(?<engagement>\d+(?:\.\d+)?)mm\s*;", RegexOptions.CultureInvariant);
@@ -102,14 +179,54 @@ public sealed class AssemblyM0Parser
fitMatch.Groups["perSide"].Success ? .5d : 1d, policy, variation) : null;
var free = Regex.Matches(body, @"\bAllow\s+(?<kind>rotation|translation):(?<axis>[A-Za-z-]+)\s*;", RegexOptions.CultureInvariant)
.Select(m => m.Groups["kind"].Value + ":" + m.Groups["axis"].Value).ToArray();
+ if (header.Groups["family"].Success && roles.Length == 0)
+ {
+ var capabilities = family switch
+ {
+ MechanicalInterfaceFamily.Fixed => new[] { "DatumFrameCapable" },
+ MechanicalInterfaceFamily.Revolute => new[] { "AxisCapable", "PlaneCapable" },
+ MechanicalInterfaceFamily.Axial => new[] { "AxisCapable" },
+ MechanicalInterfaceFamily.Gear => new[] { "GearCapable" },
+ _ => Array.Empty<string>()
+ };
+ roles = [new("A", capabilities), new("B", capabilities)];
+ }
+ if (header.Groups["family"].Success && requirements.Length == 0)
+ {
+ requirements = family switch
+ {
+ MechanicalInterfaceFamily.Fixed => [new(PlacementConstraintKind.FrameCoincident, "A", ".", "B", ".")],
+ MechanicalInterfaceFamily.Axial => [new(PlacementConstraintKind.AxisCoincident, "A", "Axis", "B", "Axis")],
+ MechanicalInterfaceFamily.Revolute => [new(PlacementConstraintKind.AxisCoincident, "A", "Axis", "B", "Axis"), new(PlacementConstraintKind.PlaneCoincident, "A", "Seat", "B", "Seat")],
+ _ => []
+ };
+ }
+ if (header.Groups["family"].Success && free.Length == 0)
+ free = family switch
+ {
+ MechanicalInterfaceFamily.Axial => ["translation:along-axis", "rotation:about-axis"],
+ MechanicalInterfaceFamily.Revolute => ["rotation:about-axis"],
+ _ => []
+ };
+ var predicates = Regex.Matches(body, @"\bRequire\s+(?<name>[A-Za-z_]\w*)\s*=>\s*(?<left>[-+]?\d+(?:\.\d+)?)mm\s*(?<op>>=|<=|>|<|==)\s*(?<right>[-+]?\d+(?:\.\d+)?)mm\s*;", RegexOptions.CultureInvariant)
+ .Select(m =>
+ {
+ var left = Number(m.Groups["left"].Value); var right = Number(m.Groups["right"].Value); var op = m.Groups["op"].Value;
+ var passed = op switch { ">" => left > right, "<" => left < right, ">=" => left >= right, "<=" => left <= right, "==" => Math.Abs(left - right) <= 1e-12, _ => false };
+ return new InterfacePredicateRequirementDefinition(m.Groups["name"].Value, $"{left:R}mm {op} {right:R}mm", passed);
+ }).ToArray();
var continuity = Regex.Match(body,@"\bContinuity\s*:\s*(?<value>G0|G1)\s*;",RegexOptions.CultureInvariant);
var correspondence = Regex.Match(body,@"\bCorrespondence\s*:\s*(?<value>OppositeDirections|SameDirection)\s*;",RegexOptions.CultureInvariant);
var gap = Regex.Match(body,@"\bGapTolerance\s*:\s*(?<value>[-+]?[0-9.]+)mm\s*;",RegexOptions.CultureInvariant);
- if (roles.Length == 0) diagnostics.Add(new("assembly-interface-no-roles", $"Interface '{name}' must define at least one Role."));
+ if (roles.Length == 0) diagnostics.Add(new("assembly-interface-no-roles", $"Interface '{name}' must define at least one Role or use a compiler-owned typed family."));
+ if (result.Any(item => item.Name == name)) { diagnostics.Add(new("assembly-interface-duplicate-name", $"Interface '{name}' is declared more than once.")); continue; }
+ var gearOptions = family == MechanicalInterfaceFamily.Gear
+ ? new GearInterfaceOptions(OptionalAngle(body, "ShaftAngle"), OptionalAngle(body, "EngagementPhase"), OptionalIdentifier(body, "AllowedDirection"))
+ : null;
result.Add(new($"interface:{name}", name, roles, requirements, fit, free, SemanticSourceSpan.Generated(sourceIdentity),
continuity.Success?continuity.Groups["value"].Value:null,
correspondence.Success?correspondence.Groups["value"].Value:"OppositeDirections",
- gap.Success?Number(gap.Groups["value"].Value):1e-6));
+ gap.Success?Number(gap.Groups["value"].Value):1e-6, family, header.Groups["family"].Success, predicates, gearOptions));
}
return result.OrderBy(x => x.Name, StringComparer.Ordinal).ToArray();
}
@@ -126,10 +243,12 @@ public sealed class AssemblyM0Parser
public PlacementAuthority PlacementAuthority { get; set; } = PlacementAuthority.MateDerived;
public bool IsEncapsulatedDefinition { get; set; }
public AssemblyDefinitionIr? SolvedAssemblyDefinition { get; set; }
+ public SemanticValue? TypedEndpoint { get; set; }
}
private static IReadOnlyList<AssemblyDefinitionSource> ParseAssemblyDefinitions(string source, string sourceIdentity,
IReadOnlyList<InterfaceDefinition> interfaces, IReadOnlyList<AssemblyConceptDefinition> concepts,
+ IReadOnlyDictionary<string, GearAir> gearAuthorities,
List<AssemblyDiagnostic> diagnostics, List<(int Start, int Length)> ranges)
{
var result = new List<AssemblyDefinitionSource>();
@@ -141,7 +260,7 @@ public sealed class AssemblyM0Parser
if (body is null) continue;
var close = template.Index + template.Length + body.Length + 1;
ranges.Add((template.Index, close - template.Index));
- var root = ParseTree(body, sourceIdentity, diagnostics);
+ var root = ParseTree(body, sourceIdentity, diagnostics, result, interfaces, new Dictionary<string, AssemblyMemberSource>(StringComparer.Ordinal), gearAuthorities);
if (root is null) continue;
var exposed = ParseAssemblyExposes(body, root, sourceIdentity, diagnostics);
root = root with { ExposedSemantics = exposed, IsEncapsulatedDefinition = true };
@@ -216,19 +335,26 @@ public sealed class AssemblyM0Parser
if (!header.Success) return [];
var block = BalancedBody(body, header.Index + header.Length - 1, diagnostics, "Assembly Expose") ?? string.Empty;
var result = new List<SemanticValue>();
- foreach (Match expose in Regex.Matches(block, @"\b(?:Semantic|Axis|Plane|Point|Dimension|DatumFrame)\s+(?<name>[A-Za-z_]\w*)\s*=\s*(?<path>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*;", RegexOptions.CultureInvariant))
+ foreach (Match expose in Regex.Matches(block, @"\b(?<type>Semantic|Axis|Plane|Point|Dimension|DatumFrame|Gear)\s+(?<name>[A-Za-z_]\w*)\s*=\s*(?<path>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*;", RegexOptions.CultureInvariant))
{
var alias = expose.Groups["name"].Value;
if (result.Any(value => value.ExposedName == alias)) { diagnostics.Add(new("assembly-expose-duplicate-name", $"Assembly Expose declares '{alias}' more than once.")); continue; }
var segments = expose.Groups["path"].Value.Split('.');
var child = root.Children.SingleOrDefault(item => item.Name == segments[0]);
- SemanticValue? value = child is null ? null : child.ExposedSemantics.SingleOrDefault(item => item.ExposedName == segments.ElementAtOrDefault(1));
+ SemanticValue? value = child is null ? null : segments.Length == 1 ? child.TypedEndpoint : child.ExposedSemantics.SingleOrDefault(item => item.ExposedName == segments[1]);
for (var i = 2; value is not null && i < segments.Length; i++) value = value.ExposedMembers.GetValueOrDefault(segments[i]);
if (value is null)
{
diagnostics.Add(new("assembly-expose-unresolved-path", $"Assembly Expose '{alias}' references nonexistent internal path '{expose.Groups["path"].Value}'."));
continue;
}
+ var expectedType = expose.Groups["type"].Value;
+ var semanticType = expectedType switch { "DatumFrame" => "AssemblyDatumFrame", "Dimension" => "Length", _ => expectedType };
+ if (expectedType != "Semantic" && !string.Equals(value.Type.Name, semanticType, StringComparison.Ordinal))
+ {
+ diagnostics.Add(new("assembly-expose-type-mismatch", $"Assembly Expose '{alias}' declares {expectedType} but '{expose.Groups["path"].Value}' is {value.Type}."));
+ continue;
+ }
result.Add(new SemanticValue(value.StableIdentity + ":expose:" + alias, value.Type, value.Capabilities.Values, value.Bindings,
value.ExposedMembers.Values, [.. value.Provenance, new("assembly-expose", alias, expose.Groups["path"].Value, SemanticSourceSpan.Generated(sourceIdentity))],
value.AuthoredSourceSpan, value.GeneratedSourceSpan, alias));
@@ -241,12 +367,14 @@ public sealed class AssemblyM0Parser
IDictionary<string, AssemblyMemberSource> specializationCache, string sourceIdentity, List<AssemblyDiagnostic> diagnostics)
{
var application = Regex.Match(identity, @"^(?<name>[A-Za-z_]\w*)\s*<\s*(?<parameter>[A-Za-z_]\w*)\s*:\s*(?<argument>[^>]+)\s*>$", RegexOptions.CultureInvariant);
- if (!application.Success) { diagnostics.Add(new("assembly-template-unresolved-definition", $"Assembly occurrence '{occurrenceName}' references unresolved definition '{identity}'.")); return null; }
- var definition = definitions.SingleOrDefault(item => item.Name == application.Groups["name"].Value);
- if (definition is null) { diagnostics.Add(new("assembly-template-unresolved-definition", $"Assembly Template '{application.Groups["name"].Value}' was not found.")); return null; }
- if (application.Groups["parameter"].Value != definition.ParameterName) { diagnostics.Add(new("assembly-template-argument-mismatch", $"Assembly Template '{definition.Name}' expects argument '{definition.ParameterName}'.")); return null; }
- var argument = application.Groups["argument"].Value.Trim();
- var specializationIdentity = NormalizeIdentity(identity);
+ var bareName = Regex.Match(identity, @"^(?<name>[A-Za-z_]\w*)$", RegexOptions.CultureInvariant);
+ var definitionName = application.Success ? application.Groups["name"].Value : bareName.Success ? bareName.Groups["name"].Value : string.Empty;
+ var definition = definitions.SingleOrDefault(item => item.Name == definitionName);
+ if (definition is null) { diagnostics.Add(new("assembly-template-unresolved-definition", $"Assembly definition '{definitionName}' was not found.")); return null; }
+ if (application.Success && application.Groups["parameter"].Value != definition.ParameterName) { diagnostics.Add(new("assembly-template-argument-mismatch", $"Assembly Template '{definition.Name}' expects argument '{definition.ParameterName}'.")); return null; }
+ if (!application.Success && definition.ParameterName != "__Unit") { diagnostics.Add(new("assembly-template-argument-mismatch", $"Parameterized Assembly Template '{definition.Name}' requires '{definition.ParameterName}: ...'.")); return null; }
+ var argument = application.Success ? application.Groups["argument"].Value.Trim() : "__Unit";
+ var specializationIdentity = application.Success ? NormalizeIdentity(identity) : definition.Name;
if (specializationCache.TryGetValue(specializationIdentity, out var cached))
return RenameOccurrence(cached, occurrenceName);
AssemblyMemberSource Replace(AssemblyMemberSource item) => item with
@@ -258,9 +386,9 @@ public sealed class AssemblyM0Parser
DefinitionIdentity = Regex.Replace(item.DefinitionIdentity, $@"(?<prefix>:\s*)\b{Regex.Escape(definition.ParameterName)}\b", "${prefix}" + argument),
Children = item.Children.Select(Replace).ToArray(),
Provenance = [.. item.Provenance ?? [], new("assembly-template-specialization", definition.Name, specializationIdentity, SemanticSourceSpan.Generated(sourceIdentity))],
- IsEncapsulatedDefinition = false
+ IsEncapsulatedDefinition = item.IsEncapsulatedDefinition
};
- var specializedRoot = Replace(definition.LocalRoot);
+ var specializedRoot = Replace(definition.LocalRoot) with { IsEncapsulatedDefinition = false };
var localSource = new AssemblySource(definition.Name, specializedRoot, interfaces, definition.LocalMates ?? [], definition.LocalAnchor ?? new([definition.Name]),
definition.LocalDimensionalRelations ?? [], definition.LocalStackupAsserts ?? [], sourceIdentity);
var watch = Stopwatch.StartNew();
@@ -302,9 +430,22 @@ public sealed class AssemblyM0Parser
var internalPath = exposed.Provenance.LastOrDefault(item => item.Stage == "assembly-expose")?.Evidence;
if (internalPath is null || !AssemblyM0Compiler.TryResolve(AssemblyPath.Parse(localIr.Name + "." + internalPath), localIr.Instances, out var reference)) return exposed;
var bindings = exposed.Bindings.Where(binding => binding is TolerancedDimensionBinding).ToList();
+ if (reference!.Value.TryBinding<TypedSemanticAuthorityBinding<GearAir>>(out var gear))
+ {
+ var owner = localIr.Instances.Where(instance => Flatten(instance.SemanticRoot).Any(value => value.StableIdentity == reference.Value.StableIdentity))
+ .OrderByDescending(instance => instance.Path.Segments.Count).First();
+ bindings.Add(gear with { RelativeOccurrencePath = [.. owner.Path.Segments.Skip(1), .. gear.RelativeOccurrencePath ?? []] });
+ }
try { bindings.Add(AssemblyWorldQuery.Resolve(localIr, reference!.Value.StableIdentity)); } catch (InvalidOperationException) { }
return new(exposed.StableIdentity, exposed.Type, exposed.Capabilities.Values, bindings, exposed.ExposedMembers.Values, exposed.Provenance,
exposed.AuthoredSourceSpan, SemanticSourceSpan.Generated(sourceIdentity), exposed.ExposedName);
+
+ static IEnumerable<SemanticValue> Flatten(SemanticValue value)
+ {
+ yield return value;
+ foreach (var child in value.ExposedMembers.Values)
+ foreach (var descendant in Flatten(child)) yield return descendant;
+ }
}
private static IReadOnlyList<DimensionalRelationIr> BuildPublicRelations(AssemblyDefinitionSource definition, string specializationIdentity,
@@ -352,7 +493,8 @@ public sealed class AssemblyM0Parser
private static AssemblyMemberSource? ParseTree(string body, string sourceIdentity, List<AssemblyDiagnostic> diagnostics,
IReadOnlyList<AssemblyDefinitionSource>? definitions = null, IReadOnlyList<InterfaceDefinition>? interfaces = null,
- IDictionary<string, AssemblyMemberSource>? specializationCache = null)
+ IDictionary<string, AssemblyMemberSource>? specializationCache = null,
+ IReadOnlyDictionary<string, GearAir>? gearAuthorities = null)
{
// One bounded generic argument list is admitted in a Part definition. The
// inner '>' belongs to the Firmament Template application, not the XML-like tag.
@@ -384,6 +526,7 @@ public sealed class AssemblyM0Parser
node.PlacementAuthority = instantiated.PlacementAuthority;
node.IsEncapsulatedDefinition = true;
node.SolvedAssemblyDefinition = instantiated.SolvedAssemblyDefinition;
+ node.TypedEndpoint = instantiated.TypedEndpoint;
}
}
if (stack.Count > 0) { node.Parent = stack.Peek().node; node.Parent.Children.Add(node); }
@@ -400,6 +543,12 @@ public sealed class AssemblyM0Parser
if (open.node.Kind is AssemblyInstanceKind.Part or AssemblyInstanceKind.Panel)
{
open.node.Semantics.AddRange(ParseSemantics(nodeBody, open.node.Definition, sourceIdentity, diagnostics));
+ if (open.node.Kind == AssemblyInstanceKind.Part && gearAuthorities?.GetValueOrDefault(open.node.Definition) is { } gear)
+ {
+ var endpoint = GearEndpoint(gear, sourceIdentity);
+ open.node.Semantics.Add(endpoint);
+ open.node.TypedEndpoint = endpoint;
+ }
}
var nestedTag = nodeBody.IndexOf('<');
var placementBody = open.node.Kind == AssemblyInstanceKind.Assembly && nestedTag >= 0 ? nodeBody[..nestedTag] : nodeBody;
@@ -422,18 +571,46 @@ public sealed class AssemblyM0Parser
if (root is null) diagnostics.Add(new("assembly-tree-missing", "Assembly body requires a nested <Assembly Name> product tree."));
AssemblyMemberSource Freeze(MutableNode node) => new(node.Name, node.Kind, node.Definition,
node.Children.Select(Freeze).ToArray(), node.Semantics, [], [new("assembly-source", node.Name, node.Definition, SemanticSourceSpan.Generated(sourceIdentity))],
- node.ExplicitTransform, node.PlacementAuthority, node.IsEncapsulatedDefinition, node.SolvedAssemblyDefinition);
+ node.ExplicitTransform, node.PlacementAuthority, node.IsEncapsulatedDefinition, node.SolvedAssemblyDefinition, node.TypedEndpoint);
return root is null ? null : Freeze(root);
MutableNode ToMutable(AssemblyMemberSource source)
{
- var mutable = new MutableNode(source.Name, source.Kind, source.DefinitionIdentity) { ExplicitTransform = source.ExplicitTransform, PlacementAuthority = source.PlacementAuthority, IsEncapsulatedDefinition = source.IsEncapsulatedDefinition, SolvedAssemblyDefinition = source.SolvedAssemblyDefinition };
+ var mutable = new MutableNode(source.Name, source.Kind, source.DefinitionIdentity) { ExplicitTransform = source.ExplicitTransform, PlacementAuthority = source.PlacementAuthority, IsEncapsulatedDefinition = source.IsEncapsulatedDefinition, SolvedAssemblyDefinition = source.SolvedAssemblyDefinition, TypedEndpoint = source.TypedEndpoint };
mutable.Semantics.AddRange(source.ExposedSemantics);
mutable.Children.AddRange(source.Children.Select(ToMutable));
return mutable;
}
}
+ private static SemanticValue GearEndpoint(GearAir gear, string sourceIdentity)
+ {
+ var id = "gear-definition:" + gear.Name;
+ var axis = new ExactAxisBinding(0, 0, 0, gear.Axis[0], gear.Axis[1], gear.Axis[2], id + ":axis");
+ var direction = Vector3.Normalize(new((float)gear.Axis[0], (float)gear.Axis[1], (float)gear.Axis[2]));
+ var x = Math.Abs(Vector3.Dot(direction, Vector3.UnitX)) < .9f ? Vector3.Normalize(Vector3.Cross(Vector3.UnitY, direction)) : Vector3.Normalize(Vector3.Cross(Vector3.UnitZ, direction));
+ var y = Vector3.Normalize(Vector3.Cross(direction, x));
+ var frame = new ExactDatumFrameBinding(0, 0, 0, x.X, x.Y, x.Z, y.X, y.Y, y.Z, direction.X, direction.Y, direction.Z, id + ":frame");
+ return new(id, new("Gear"), [new GearCapability(), new AxisCapability(), new DatumFrameCapability()],
+ [new TypedSemanticAuthorityBinding<GearAir>(new("Gear"), gear, id), axis, frame],
+ [new SemanticValue(id + ":Axis", new("Axis"), [new AxisCapability()], [axis], exposedName: "Axis"),
+ new SemanticValue(id + ":Frame", new("AssemblyDatumFrame"), [new DatumFrameCapability()], [frame], exposedName: "Frame")],
+ [new("gear-authority", gear.Name, gear.Family.ToString(), new(sourceIdentity, gear.SourceSpan.Start, gear.SourceSpan.Length))],
+ new(sourceIdentity, gear.SourceSpan.Start, gear.SourceSpan.Length), exposedName: "Gear");
+ }
+
+ private static double? OptionalAngle(string body, string name)
+ {
+ var match = Regex.Match(body, $@"\b{Regex.Escape(name)}\s*:\s*(?<value>[-+]?\d+(?:\.\d+)?)deg\s*;?", RegexOptions.CultureInvariant);
+ return match.Success ? Number(match.Groups["value"].Value) : null;
+ }
+
+ private static string? OptionalIdentifier(string body, string name)
+ {
+ var match = Regex.Match(body, $@"\b{Regex.Escape(name)}\s*:\s*(?<value>[A-Za-z_]\w*)\s*;?", RegexOptions.CultureInvariant);
+ return match.Success ? match.Groups["value"].Value : null;
+ }
+
private static IEnumerable<SemanticValue> ParseSemantics(string body, string definition, string sourceIdentity, List<AssemblyDiagnostic> diagnostics)
{
foreach (Match header in Regex.Matches(body, @"\bSemantic\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
@@ -499,6 +676,13 @@ public sealed class AssemblyM0Parser
.Select(m => new MateRoleAssignment(m.Groups["role"].Value, AssemblyPath.Parse(m.Groups["path"].Value))).ToArray();
result.Add(new(header.Groups["name"].Value, header.Groups["interface"].Value, roles, SemanticSourceSpan.Generated(sourceIdentity)));
}
+ foreach (Match header in Regex.Matches(body, @"\bInterface\s*<\s*(?<family>Custom|Fixed|Axial|Revolute|Gear)\s*>\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
+ {
+ var block = BalancedBody(body, header.Index + header.Length - 1, diagnostics, "typed Interface"); if (block is null || Regex.IsMatch(block, @"\bRole\s+", RegexOptions.CultureInvariant)) continue;
+ var roles = Regex.Matches(block, @"\b(?<role>A|B)\s*:\s*(?<path>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*;", RegexOptions.CultureInvariant)
+ .Select(m => new MateRoleAssignment(m.Groups["role"].Value, AssemblyPath.Parse(m.Groups["path"].Value))).ToArray();
+ if (roles.Length > 0) result.Add(new(header.Groups["name"].Value, header.Groups["name"].Value, roles, SemanticSourceSpan.Generated(sourceIdentity)));
+ }
return result;
}
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
index 9551aadd..dfdbdc31 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
@@ -59,6 +59,29 @@ internal static class AssemblyDefinitionMaterializer
{
public static MaterializedAssemblyDefinition? TryMaterialize(string definitionIdentity, string? definitionSource, string sourceIdentity, List<AssemblyDiagnostic> diagnostics)
{
+ if (!string.IsNullOrWhiteSpace(definitionSource))
+ {
+ var gearDocument = GearAuthoring.ParseDefinitions(definitionSource);
+ var gear = gearDocument.Gears.SingleOrDefault(candidate => string.Equals(candidate.Name, definitionIdentity, StringComparison.Ordinal));
+ if (gear is not null)
+ {
+ var materialization = GearAuthoring.Materialize(gear, out var gearDiagnostics);
+ if (materialization is null)
+ {
+ foreach (var diagnostic in gearDiagnostics)
+ diagnostics.Add(new("assembly-definition-materialization-failed", $"Gear definition '{definitionIdentity}' failed Gear-authoritative materialization: {diagnostic}"));
+ return null;
+ }
+ var step = Step242Exporter.ExportBody(materialization.Body);
+ var gearHash = step.IsSuccess
+ ? Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value)))
+ : Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(definitionIdentity)));
+ var gearStableId = "assembly-definition:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(definitionIdentity)))[..16];
+ var gearProvenance = new[] { new SemanticProvenance("gear-definition", definitionIdentity, "GearAuthoring.Materialize", SemanticSourceSpan.Generated(sourceIdentity)) };
+ return new(definitionIdentity, "gear:" + definitionIdentity, materialization.Body, [],
+ new(gearStableId, definitionIdentity, "gear:" + definitionIdentity, gearHash, Metrics(materialization.Body), gearProvenance));
+ }
+ }
var externalStep = System.Text.RegularExpressions.Regex.Match(definitionIdentity, "^ExternalStep<\\\"(?<path>[^\\\"]+)\\\">$", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
if (externalStep.Success)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/GearAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/GearAuthoring.cs
index 51d39e91..2f0f0667 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/GearAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/GearAuthoring.cs
@@ -111,6 +111,21 @@ public static class GearAuthoring
RegexOptions.CultureInvariant);
public static bool IsGearSource(string source) => Header.IsMatch(source) || InterfaceHeader.IsMatch(source);
+ public static bool HasGearDefinitions(string source) => Header.IsMatch(source);
+
+ /// <summary>Parses only the compiler-owned Gear declarations in a mixed-domain source.</summary>
+ public static GearAuthoringDocument ParseDefinitions(string source)
+ {
+ ArgumentNullException.ThrowIfNull(source);
+ var diagnostics = new List<string>();
+ var modelMatch = Regex.Match(source, @"\bModel\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
+ var modelName = modelMatch.Success ? modelMatch.Groups["name"].Value : "GearModel";
+ if (!Regex.IsMatch(source, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant))
+ diagnostics.Add(Prefix + "units-invalid:mm-required");
+ var gears = ParseGearDeclarations(source, diagnostics);
+ if (gears.Count == 0) diagnostics.Add(Prefix + "declaration-missing");
+ return new(modelName, gears, [], diagnostics.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray());
+ }
public static GearAuthoringDocument Parse(string source)
{
@@ -121,6 +136,28 @@ public static class GearAuthoring
if (!Regex.IsMatch(source, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant))
diagnostics.Add(Prefix + "units-invalid:mm-required");
+ var gears = ParseGearDeclarations(source, diagnostics);
+
+ var interfaces = new List<InterfaceAir<GearAir>>();
+ foreach (Match header in InterfaceHeader.Matches(source))
+ {
+ var open = source.IndexOf('{', header.Index); var close = MatchingBrace(source, open);
+ if (close < 0) { diagnostics.Add(Prefix + "interface-unclosed:" + header.Groups["name"].Value); continue; }
+ var body = source[(open + 1)..close]; var aName = Identifier(body, "A"); var bName = Identifier(body, "B");
+ if (aName is null || bName is null) { diagnostics.Add(Prefix + "interface-endpoint-missing:" + header.Groups["name"].Value); continue; }
+ var a = gears.SingleOrDefault(gear => gear.Name == aName); var b = gears.SingleOrDefault(gear => gear.Name == bName);
+ if (a is null || b is null) { diagnostics.Add(Prefix + "interface-endpoint-unresolved:" + header.Groups["name"].Value); continue; }
+ interfaces.Add(EvaluateInterface(header.Groups["name"].Value, a, b,
+ Angle(body, "ShaftAngle"), Angle(body, "EngagementPhase"), Identifier(body, "AllowedDirection"),
+ new(header.Index, close - header.Index + 1)));
+ }
+ diagnostics.AddRange(interfaces.Where(item => !item.Compatible).SelectMany(item => item.RejectionReasons.Select(reason => $"{Prefix}interface-incompatible:{item.Name}:{reason}")));
+ if (gears.Count == 0) diagnostics.Add(Prefix + "declaration-missing");
+ return new(modelName, gears, interfaces, diagnostics.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray());
+ }
+
+ private static List<GearAir> ParseGearDeclarations(string source, List<string> diagnostics)
+ {
var gears = new List<GearAir>();
foreach (Match header in Header.Matches(source))
{
@@ -148,23 +185,7 @@ public static class GearAuthoring
}
foreach (var duplicate in gears.GroupBy(gear => gear.Name, StringComparer.Ordinal).Where(group => group.Count() > 1))
diagnostics.Add(Prefix + "duplicate-identity:" + duplicate.Key);
-
- var interfaces = new List<InterfaceAir<GearAir>>();
- foreach (Match header in InterfaceHeader.Matches(source))
- {
- var open = source.IndexOf('{', header.Index); var close = MatchingBrace(source, open);
- if (close < 0) { diagnostics.Add(Prefix + "interface-unclosed:" + header.Groups["name"].Value); continue; }
- var body = source[(open + 1)..close]; var aName = Identifier(body, "A"); var bName = Identifier(body, "B");
- if (aName is null || bName is null) { diagnostics.Add(Prefix + "interface-endpoint-missing:" + header.Groups["name"].Value); continue; }
- var a = gears.SingleOrDefault(gear => gear.Name == aName); var b = gears.SingleOrDefault(gear => gear.Name == bName);
- if (a is null || b is null) { diagnostics.Add(Prefix + "interface-endpoint-unresolved:" + header.Groups["name"].Value); continue; }
- interfaces.Add(BindInterface(header.Groups["name"].Value, a, b,
- Angle(body, "ShaftAngle"), Angle(body, "EngagementPhase"), Identifier(body, "AllowedDirection"),
- new(header.Index, close - header.Index + 1)));
- }
- diagnostics.AddRange(interfaces.Where(item => !item.Compatible).SelectMany(item => item.RejectionReasons.Select(reason => $"{Prefix}interface-incompatible:{item.Name}:{reason}")));
- if (gears.Count == 0) diagnostics.Add(Prefix + "declaration-missing");
- return new(modelName, gears, interfaces, diagnostics.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray());
+ return gears;
}
public static GearMaterialization? Materialize(GearAir gear, out IReadOnlyList<string> diagnostics)
@@ -215,7 +236,7 @@ public static class GearAuthoring
toothIds);
}
- private static InterfaceAir<GearAir> BindInterface(string name, GearAir a, GearAir b, double? shaftAngle,
+ public static InterfaceAir<GearAir> EvaluateInterface(string name, GearAir a, GearAir b, double? shaftAngle,
double? engagementPhase, string? allowedDirection, FirmamentV2SourceSpan span)
{
var rejection = new List<string>();
diff --git a/Aetheris.Semantics/SemanticModel.cs b/Aetheris.Semantics/SemanticModel.cs
index 7cacae34..90f7eba2 100644
--- a/Aetheris.Semantics/SemanticModel.cs
+++ b/Aetheris.Semantics/SemanticModel.cs
@@ -38,6 +38,8 @@ public sealed record CurveCapability : ISemanticCapability { public string Name
public sealed record BoundaryEdgeCapability : ISemanticCapability { public string Name => "BoundaryEdgeCapable"; }
/// <summary>A fully oriented, authoring-stable rigid assembly datum.</summary>
public sealed record DatumFrameCapability : ISemanticCapability { public string Name => "DatumFrameCapable"; }
+/// <summary>A semantic endpoint backed by the owning gear-domain authority.</summary>
+public sealed record GearCapability : ISemanticCapability { public string Name => "GearCapable"; }
public sealed class SemanticCapabilitySet
{
@@ -56,6 +58,22 @@ public sealed class SemanticCapabilitySet
/// <summary>A bounded exact downstream representation. It is not a service locator.</summary>
public abstract record SemanticBinding(string Kind, string StableBindingIdentity);
+/// <summary>
+/// A compile-time typed reference to a producer-owned semantic authority. Hierarchical
+/// consumers may add an occurrence path, but never copy or reinterpret the authority.
+/// </summary>
+public interface ITypedSemanticAuthorityBinding
+{
+ SemanticType AuthorityType { get; }
+}
+
+public sealed record TypedSemanticAuthorityBinding<TAuthority>(
+ SemanticType AuthorityType,
+ TAuthority Authority,
+ string AuthorityStableId,
+ IReadOnlyList<string>? RelativeOccurrencePath = null)
+ : SemanticBinding("TypedSemanticAuthority<" + AuthorityType.Name + ">", AuthorityStableId), ITypedSemanticAuthorityBinding;
+
public sealed record ExactBrepBodyBinding(BrepBody Body, string BodyStableId)
: SemanticBinding("ExactBrepBody", BodyStableId);
@@ -241,6 +259,9 @@ public static class SemanticValueValidator
RequireBinding<CurveCapability, ExactCurveBinding>(value, diagnostics);
RequireBinding<BoundaryEdgeCapability, ExactCurveBinding>(value, diagnostics);
RequireBinding<DatumFrameCapability, ExactDatumFrameBinding>(value, diagnostics);
+ if (value.Capabilities.Supports<GearCapability>()
+ && !value.Bindings.OfType<ITypedSemanticAuthorityBinding>().Any(binding => binding.AuthorityType.Name == "Gear"))
+ diagnostics.Add(new(NoExactBinding, $"GearCapable on '{value.StableIdentity}' requires TypedSemanticAuthorityBinding<Gear>.", value.AuthoredSourceSpan));
RequireAnyExactBinding<ExactGeometryCapability>(value, diagnostics);
RequireAnyExactBinding<SelectableCapability>(value, diagnostics);
RequireBinding<ComposeOperandCapability, ExactProfileBinding>(value, diagnostics);
diff --git a/demos/Aetheris.EditableV8/Program.cs b/demos/Aetheris.EditableV8/Program.cs
index 1d0525a3..167fa8bc 100644
--- a/demos/Aetheris.EditableV8/Program.cs
+++ b/demos/Aetheris.EditableV8/Program.cs
@@ -351,11 +351,7 @@ public sealed class EngineAuthor(V8Spec spec)
Lower FrameCoincident Spring.Frame Stem.Frame SameDirection;
Fit Stem.Diameter inside Spring.ClearDiameter;
}
- Interface RegisteredSeat {
- Role Moving requires DatumFrameCapable;
- Role Fixed requires DatumFrameCapable;
- Lower FrameCoincident Moving Fixed SameDirection;
- }
+ Interface<Fixed> RegisteredSeat { }
Interface JournalBoreSeat {
Role Moving requires DatumFrameCapable, DimensionalCapable;
Role Fixed requires DatumFrameCapable, DimensionalCapable;
@@ -395,7 +391,9 @@ public sealed class EngineAuthor(V8Spec spec)
continue;
}
var contract = b.Kind == "Rod" ? "JournalBoreSeat" : b.Name.StartsWith("WristPin", StringComparison.Ordinal) && b.Cylinder > 0 ? "WristPinSeat" : "RegisteredSeat";
- text.AppendLine($"Mate Install{b.Name}: {contract} {{ Moving: {root}.{b.Name}.Mount; Fixed: {root}.{parent[b.Name]}.Seat{b.Name}; }}");
+ text.AppendLine(contract == "RegisteredSeat"
+ ? $"Mate Install{b.Name}: {contract} {{ A: {root}.{b.Name}.Mount; B: {root}.{parent[b.Name]}.Seat{b.Name}; }}"
+ : $"Mate Install{b.Name}: {contract} {{ Moving: {root}.{b.Name}.Mount; Fixed: {root}.{parent[b.Name]}.Seat{b.Name}; }}");
}
text.AppendLine("}");
return text.ToString();
diff --git a/docs/public/README.md b/docs/public/README.md
index 740001a7..90f731b9 100644
--- a/docs/public/README.md
+++ b/docs/public/README.md
@@ -4,7 +4,7 @@ This directory is the only authoritative in-repository guide to behavior shipped
Start with [Getting Started](getting-started.md), then use these guides:
-- Firmament: [overview](firmament/overview.md), [language style](firmament/language-style.md), [syntax](firmament/syntax.md), [geometry](firmament/geometry.md), [Gear Standard Library](firmament/gears.md), [closed 2D boundaries](firmament/boundaries.md), [bounded material offsets](firmament/material-offsets.md), [Revolve](firmament/revolve.md), [bounded mathematical sculpting](firmament/sculpting.md), [Section chains](firmament/section-chains.md), [PlasticShell](firmament/plastic-shell.md), [Circular Sweep](firmament/sweep.md), [Formed Wire](firmament/wire-form.md), [Structural members and weldments](firmament/structural.md), [Semantic piping and local autorouting](firmament/piping.md), [Paperclip Template](firmament/paperclip.md), [Templates](firmament/templates.md), [materials](firmament/materials.md), [PMI](firmament/pmi.md), [Sheet Metal](firmament/sheet-metal.md), [FEA](firmament/fea.md), and [STEP import](firmament/step-import.md)
+- Firmament: [overview](firmament/overview.md), [language style](firmament/language-style.md), [syntax](firmament/syntax.md), [geometry](firmament/geometry.md), [typed interfaces and reusable subassemblies](firmament/assemblies.md), [Gear Standard Library](firmament/gears.md), [closed 2D boundaries](firmament/boundaries.md), [bounded material offsets](firmament/material-offsets.md), [Revolve](firmament/revolve.md), [bounded mathematical sculpting](firmament/sculpting.md), [Section chains](firmament/section-chains.md), [PlasticShell](firmament/plastic-shell.md), [Circular Sweep](firmament/sweep.md), [Formed Wire](firmament/wire-form.md), [Structural members and weldments](firmament/structural.md), [Semantic piping and local autorouting](firmament/piping.md), [Paperclip Template](firmament/paperclip.md), [Templates](firmament/templates.md), [materials](firmament/materials.md), [PMI](firmament/pmi.md), [Sheet Metal](firmament/sheet-metal.md), [FEA](firmament/fea.md), and [STEP import](firmament/step-import.md)
- Non-manufacturing work: [Virtual Sculpture and Sol 1](virtual-sculpture.md)
- Standard Library: [product-family index, invocation, authoring, and compatibility](standard-library/README.md)
- Interoperability: [Forge Host Protocol v1](forge/interop.md)
diff --git a/docs/public/firmament/assemblies.md b/docs/public/firmament/assemblies.md
new file mode 100644
index 00000000..a22d781c
--- /dev/null
+++ b/docs/public/firmament/assemblies.md
@@ -0,0 +1,84 @@
+# Typed interfaces and reusable subassemblies
+
+Firmament assemblies have two independent structures: the product tree owns definition/occurrence identity, while the Interface graph owns mechanical relationships. Tree nesting never implies a Mate.
+
+`Concept<T>` describes truths that make one semantic object valid. `Interface<T>` describes truths that make several objects valid together. `Subassembly` is a reusable, locally solved Assembly definition. `Expose` names the small public semantic contract visible to a parent.
+
+## Compiler-owned interface families
+
+The Assembly profile admits this bounded matrix:
+
+| Interface | Expansion | Admitted motion | Status |
+|---|---|---|---|
+| `Interface<Fixed>` | `FrameCoincident` | none | qualified |
+| `Interface<Axial>` | `AxisCoincident` | translation along and rotation about the axis | qualified |
+| `Interface<Revolute>` | `AxisCoincident` + `PlaneCoincident` | rotation about the axis | qualified |
+| `Interface<Custom>` | authored atomic `Mate` lines and bounded numeric `Require` checks | explicitly authored | qualified escape hatch |
+| `Interface<Gear>` | the existing Gear evaluator plus occurrence-space axis and center-distance evidence | ideal ratio/sign metadata | qualified for direct and exposed hierarchical Gear endpoints |
+
+These are compiler-owned families, not user-defined generics. Atomic assembly relations remain the existing `AxisCoincident`, `AxisAligned`, `PlaneCoincident`, `PointCoincident`, `OffsetAlongAxis`, and `FrameCoincident` kinds. A typed family expands into those relations before the ordinary Assembly compiler runs.
+
+```firmament
+Interface<Revolute> ShaftBearing {
+ A: Module.Shaft.Joint;
+ B: Module.Bearing.Joint;
+}
+
+Interface<Custom> CarryLink {
+ A: Register.Digit1.Input;
+ B: Register.Digit0.Output;
+ Mate AxisCoincident A.Axis B.Axis;
+ Mate PlaneCoincident A.Seat B.Seat;
+ Require PositiveClearance => 1mm > 0mm;
+ Allow rotation:about-axis;
+}
+```
+
+`asm inspect` reports the typed Interface, its endpoint paths, expanded atomic Mates, requirement status, shared definition counts, the hierarchical occurrence tree, and the source dependency hashes. JSON inspection retains the same data structurally.
+
+## Multi-file subassemblies
+
+`Include` is compile-time semantic composition. Paths resolve relative to the including file and must remain under the repository source root (or, outside a checkout, the root document directory). Missing files and include cycles are typed errors. Duplicate Interface or Subassembly definitions are rejected; aliasing is not admitted in X1.
+
+```firmament
+Include "digit-module.firmament";
+
+Subassembly Register {
+ <Assembly Register>
+ <Assembly Digit0 = DigitModule></Assembly>
+ <Assembly Digit1 = DigitModule></Assembly>
+ </Assembly>
+ Anchor: Register.Digit0.Output;
+ Expose {
+ Semantic Input = Digit0.Input;
+ Semantic Output = Digit1.Output;
+ }
+}
+```
+
+Every occurrence has a stable hierarchical path, while repeated occurrences share one solved semantic definition. Internal child occurrences and semantic values are private across a Subassembly boundary. `Expose` aliases an internal semantic value; it does not copy geometry or mutate the shared definition.
+
+Semantic type survives hierarchy: `Expose` changes visibility, not type. A Gear endpoint therefore remains backed by the original Gear AIR—including family, teeth, module, pressure angle, pitch geometry, axis, and phase—while each occurrence contributes only its own placement and identity.
+
+```firmament
+Subassembly DigitModule {
+ <Assembly DigitModule><Part OutputGear = Wheel></Part></Assembly>
+ Anchor: DigitModule.OutputGear;
+ Expose { Gear Output = OutputGear; }
+}
+
+Interface<Gear> Transfer {
+ A: Machine.RegisterA.Output;
+ B: Machine.RegisterB.Input;
+}
+```
+
+The parent cannot name `OutputGear` unless the child exposes it. The exposed alias does not restate gear parameters, and `Interface<Gear>` invokes the same compatibility evaluator used by a direct gear pair. Inspection reports both the public port path and the occurrence-qualified source path.
+
+The executable example is [`fixtures/Canonical/AssemblyInterfaces/machine.firmament`](../../../fixtures/Canonical/AssemblyInterfaces/machine.firmament). It includes a Register definition, which includes a DigitModule definition; instantiates two Registers and four Digits; and connects the Registers only through `Input` and `Output`.
+
+The hierarchical Gear flagship is [`fixtures/Canonical/AssemblyInterfaces/exposed-gear-port.firmament`](../../../fixtures/Canonical/AssemblyInterfaces/exposed-gear-port.firmament); the two-level form is [`nested-register-gear.firmament`](../../../fixtures/Canonical/AssemblyInterfaces/nested-register-gear.firmament).
+
+Subassembly composition never exports a child STEP and imports it into its parent. Included definitions form one semantic source graph, the existing Assembly compiler solves the whole tree, and the existing AP242 exporter lowers the resulting hierarchy once when every leaf has executable geometry.
+
+Legacy JSON `.firmasm` remains a compatibility/import lane. Canonical reusable semantic authoring uses `.firmament`; the compatibility format does not gain runtime inclusion or become the design authority.
diff --git a/docs/public/firmament/examples/digit-module.firmament b/docs/public/firmament/examples/digit-module.firmament
new file mode 100644
index 00000000..772be2b1
--- /dev/null
+++ b/docs/public/firmament/examples/digit-module.firmament
@@ -0,0 +1,8 @@
+Units: mm
+SpurGear Wheel { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+Subassembly DigitModule {
+ <Assembly DigitModule><Part OutputGear = Wheel></Part></Assembly>
+ Anchor: DigitModule.OutputGear;
+ Expose { Gear Input = OutputGear; Gear Output = OutputGear; }
+}
+Assembly DigitModuleExample { <Assembly DigitModuleExample><Assembly Digit = DigitModule></Assembly></Assembly> Anchor: DigitModuleExample.Digit.Input; }
diff --git a/docs/public/firmament/examples/register.firmament b/docs/public/firmament/examples/register.firmament
new file mode 100644
index 00000000..7e9ed551
--- /dev/null
+++ b/docs/public/firmament/examples/register.firmament
@@ -0,0 +1,8 @@
+Units: mm
+SpurGear Wheel { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+Subassembly DigitModule { <Assembly DigitModule><Part Gear = Wheel></Part></Assembly> Anchor: DigitModule.Gear; Expose { Gear Input = Gear; Gear Output = Gear; } }
+Assembly Register {
+ <Assembly Register><Assembly Digit0 = DigitModule></Assembly><Assembly Digit1 = DigitModule>Placement ImportedOccurrence = [1,0,0,0,0,1,0,0,0,0,1,0,40,0,0,1];</Assembly></Assembly>
+ Anchor: Register.Digit0.Output;
+ Interface<Gear> Carry { A: Register.Digit0.Output; B: Register.Digit1.Input; }
+}
diff --git a/docs/public/firmament/gears.md b/docs/public/firmament/gears.md
index 3feb7381..f4fb5876 100644
--- a/docs/public/firmament/gears.md
+++ b/docs/public/firmament/gears.md
@@ -51,6 +51,21 @@ Interface<Gear> Indexing {
This relationship is ideal geometry and kinematics. It is not a contact, dynamics, torque, wear, or stress solver.
+## Gear ports in subassemblies
+
+A gear does not stop being a Gear inside a Subassembly. Expose it without copying its parameters, then use ordinary `Interface<Gear>` in the parent:
+
+```firmament
+Expose { Gear Output = OutputGear; }
+
+Interface<Gear> Transfer {
+ A: RegisterA.Output;
+ B: RegisterB.Input;
+}
+```
+
+The endpoint holds a typed reference to the existing Gear AIR. Definition-level dimensions and phase remain Gear-owned; the Assembly occurrence supplies the world transform. Module, pressure angle, family, ratio, rotation sign, bevel closure, and ratchet rules still come from the one Gear evaluator. Assembly adds only occurrence-space axis and actual center-distance validation.
+
## Parameters and boundaries
| Family | Status | Required | Optional | Boundary |
@@ -74,6 +89,7 @@ Gear AIR always carries an explicit axis. Omitted source uses `[0,0,1]`; X0 also
aetheris validate fixtures/Canonical/Gears/spur-basic.firmament --json
aetheris inspect fixtures/Canonical/GearInterfaces/spur-pair.firmament --json
aetheris build fixtures/Canonical/Gears/spur-basic.firmament --out artifacts/local/spur.step --json
+aetheris asm inspect fixtures/Canonical/AssemblyInterfaces/exposed-gear-port.firmament --json
```
`inspect` reports the authored and derived diameters, axis, phase, backlash, stable `Tooth0` through `ToothN-1` identities, and interface results. `build` adds topology and surface counts, involute approximation error, manifold STEP re-import evidence, and a SHA-256 digest. A build emits one gear body; use the typed interfaces as assembly/placement authority for trains rather than treating a multi-gear source as one fused solid.
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index e86e95e2..d5917018 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -32,7 +32,7 @@ Firmament-owned vocabulary is canonically PascalCase: declarations, semantic fea
Accepted lowercase or historical spellings remain compatibility inputs where they are cheap and unambiguous. They select the same semantic route and produce no style warning. Canonical documentation, snippets, and fixtures use only the preferred spelling; casing is not a type-system distinction.
-Canonical fields use a colon between name and value. Braces delimit declarations, brackets delimit lists, and semicolons are optional where the owning line/block grammar is unambiguous. `Model`, `SheetMetal`, `Analysis`/import, and Assembly retain domain-appropriate target grammars; the [target reference](../reference/targets.md) records the intentional distinctions.
+Canonical fields use a colon between name and value. Braces delimit declarations, brackets delimit lists, and semicolons are optional where the owning line/block grammar is unambiguous. `Model`, `SheetMetal`, `Analysis`/import, and Assembly retain domain-appropriate target grammars; the [target reference](../reference/targets.md) records the intentional distinctions. Assembly definitions may use compile-time `Include`, first-class `Subassembly`, typed `Interface<T>`, atomic `Mate`, and explicit `Expose`; see [typed interfaces and reusable subassemblies](assemblies.md).
Firmament V1 is compatibility history rather than canonical V2 authoring. Bodies embedded in `.firmfixture` entries marked future, not implemented, or invalid are corpus evidence and do not define the public language.
diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.md
index 7aa242f2..ebba1ea4 100644
--- a/docs/public/reference/supported-features.md
+++ b/docs/public/reference/supported-features.md
@@ -6,6 +6,7 @@
|---|---|---|
| Firmament V2 native primitives/profiles | Bounded | Named Box/Cylinder/Frustum/RoundedBox and admitted line/arc profile construction/composition |
| Gear Standard Library | Supported / bounded by family | Supported external/internal standard involute spur gears; bounded straight bevel/miter and ratchet/pawl; typed `Interface<Gear>` compatibility and ideal ratios; deterministic manifold AP242. No contact, dynamics, ratings, helical/worm, spiral-bevel, or qualified hub/keyway geometry. See the [gear guide](../firmament/gears.md). |
+| Assembly Interface bundles and Subassemblies | Supported / bounded | Compiler-owned `Fixed`, `Axial`, and `Revolute` expansion; explicit `Custom` atomic bundles; compile-time relative `Include`; reusable nested definitions; private-by-default internals; exposed semantic ports that preserve type, including Gear; stable hierarchical paths and dependency hashes. Include aliases are deferred. See [assemblies](../firmament/assemblies.md). |
| Bounded mathematical sculpting | Bounded (SURF-X3b subset) | Immutable single-predecessor `BodyState` reconstructed from versioned `BaseConstruction` plus typed replay operations; persistent `OffsetRegion`, `ReplaceRegion`, judged `BlendBoundary`, `HoleFeature`, east-attached `AddSectionChain`, and west/east through-duct `RemoveSectionChain`; atomic replay, semantic support invalidation, locality/preservation evidence, pcurves, AP242 associations, and rational-free STEP. General blend networks and arbitrary SectionChain supports remain unsupported. See the [sculpting guide](../firmament/sculpting.md). |
| Molded plastic shell | Bounded (MOLD-X0a) | First-class `PlasticShell` IR; exact drafted coaxial-frustum shell; analytic annular standoffs with retained core holes; constant-shell-thickness planar B-rep rib walls with flat tops; one closed product boundary; face-associated AP242 notes; and explicit zero-release-draft warning for constant-section vertical features. The retired polar height field is available only through the non-manufacturing experimental art command. Freeform exterior offsets and general junctions remain unsupported. See the [PlasticShell guide](../firmament/plastic-shell.md). |
| Virtual Sculpture | Bounded (ART-X0) | The explicit `Mode: Virtual` Sol 1 flagship: deterministic golden-angle/Fibonacci 3D lattice, analytic toroidal frame and eye, exact closed-body AP242 assembly, evidence/preview output, and zero rational product surfaces. This is not manufacturing geometry and does not extend Firmament engineering domains. See [Virtual Sculpture](../virtual-sculpture.md). |
diff --git a/docs/release/ASM-GEAR-BRIDGE-X1.md b/docs/release/ASM-GEAR-BRIDGE-X1.md
new file mode 100644
index 00000000..d634dc7d
--- /dev/null
+++ b/docs/release/ASM-GEAR-BRIDGE-X1.md
@@ -0,0 +1,98 @@
+# ASM-GEAR-BRIDGE-X1 — Gear interface endpoint unification
+
+## Executive verdict
+
+**Accepted.** First-class Gear semantics now cross Subassembly boundaries as typed exposed endpoints and participate in the existing `Interface<Gear>` authority. No gear parameter record, compatibility evaluator, geometry generator, assembly solver, or child-STEP linkage was duplicated.
+
+The Difference Engine assembly substrate is ready: a DigitModule/Register can expose Gear input/output ports through multiple hierarchy levels and connect them with ordinary `Interface<Gear>`. This milestone does not implement the Difference Engine itself.
+
+## Boundary audit
+
+1. `Interface<Gear>` consumed `GearAir` directly through `InterfaceAir<GearAir>`.
+2. It could not be exposed because Assembly admitted only `SemanticValue` endpoints, rejected Assembly-profile `Interface<Gear>`, and had no binding from a `SemanticValue` back to the owning `GearAir`.
+3. Assembly already represented explicitly authored axes and frames as semantic endpoints. The Gear AIR axis was definition data, but it was not projected as an Assembly endpoint and therefore did not receive occurrence transforms.
+4. Assembly does not require a `Semantic Joint` wrapper. Its Interface roles already consume semantic references and structural capabilities; wrapping Gear in a generic Joint would discard richer Gear authority.
+5. Type erasure occurred at the profile boundary: Gear parsing produced `GearAir`, while `ParseTree`, `InstanceScope`, `Expose`, and `BindPublicSemantic` carried only the Assembly semantic projection. No Gear binding survived that path.
+6. One shared abstraction is sufficient: `TypedSemanticAuthorityBinding<TAuthority>` retains the producer-owned authority and semantic type. The Gear specialization is `TypedSemanticAuthorityBinding<GearAir>`; there is no Assembly Gear metadata copy or adapter chain.
+
+## Endpoint authority
+
+The authority chain is:
+
+```text
+Gear declaration
+ -> GearAir (definition authority: family, teeth, module, pressure angle,
+ pitch geometry, axis, phase, pair-critical derived values)
+ -> TypedSemanticAuthorityBinding<GearAir> (typed reference, no copied fields)
+ -> Expose Gear Name = internal-path (visibility alias plus relative occurrence path)
+ -> occurrence transform (world origin/axis only)
+ -> GearAuthoring.EvaluateInterface (the existing Interface<Gear> evaluator)
+```
+
+`GearAuthoring.Parse` and hierarchical Assembly both call the same public `GearAuthoring.EvaluateInterface`. Module, pressure-angle, family, internal/external, bevel/miter, ratchet/pawl, ratio, and rotation-sign logic therefore remain single-owned. Assembly adds only the checks that cannot exist without occurrences: transformed axis relation and actual world-space center distance.
+
+`Expose` preserves semantic type. A Gear endpoint cannot be consumed as Axial/Revolute/Fixed by implicit coercion, and a non-Gear endpoint fails the `GearCapable` role.
+
+## Hierarchy evidence
+
+The canonical two-level fixture resolves:
+
+```text
+Machine/RegisterA/Output public port
+Machine/RegisterA/Digit/Gear source occurrence
+Machine/RegisterB/Input public port
+Machine/RegisterB/Digit/Gear source occurrence
+```
+
+The Register and DigitModule definitions are each solved once and reused by occurrences. A 100-occurrence test proves one Digit definition backs 100 occurrence-specific ports with deterministic identities. An unexposed child Gear remains unreachable and produces `assembly-internal-member-hidden`.
+
+The executable flagship reports `Register/Digit0/Output` as the port, `Register/Digit0/OutputGear` as its source, definition `OutputGear`, and occurrence `assembly-instance:Register.Digit0.OutputGear`. Phase `4.5deg` survives the alias.
+
+## Compatibility evidence
+
+The flagship pair is compatible:
+
+- A: 40-tooth module-2 spur Gear at `Register/Digit0/OutputGear`
+- B: 20-tooth module-2 spur Gear at `Register/Digit1/InputGear`
+- ratio: `2`
+- rotation sign: `-1`
+- expected/actual center distance: `60mm / 60mm`
+- transformed axes: parallel `[0,0,1]`
+
+Typed invalid fixtures preserve the existing Gear failure authority for module mismatch and pressure-angle mismatch. Assembly occurrence validation rejects wrong center distance and wrong axis relation with the same `firmament-gear-interface-incompatible` diagnostic family and full hierarchical paths. Separate fixtures reject a non-Gear endpoint, a private Gear, and an invalid nested exposed path.
+
+Internal/external spur, straight bevel, miter, and ratchet/pawl pairs all pass through the bridge and existing evaluator. Ratchet and Pawl remain in this endpoint only because GEAR-LIB-X0 already models their relationship in `Interface<Gear>`; no new involute assumptions were imposed on them.
+
+## Geometry and AP242
+
+Gear leaf definitions call `GearAuthoring.Materialize`. Assembly then follows its ordinary definition/occurrence execution and one whole-tree AP242 export. The flagship has two geometric Gear definitions and four leaf occurrences. No fixture names or imports a child STEP file.
+
+A fresh packaged CLI, run outside the repository against a copied flagship, produced identical AP242 twice:
+
+`BDA67B509EE722480DA0AFD37F3460634716D0C811AF130EF3265B2FBCAC079E`
+
+Reimport succeeded with two geometric definitions and six product occurrences (including hierarchy occurrences). Gear endpoint metadata remains compiler inspection data; STEP geometry and product structure use the existing deterministic AP242 path.
+
+## Validation
+
+- Release solution build: passed, zero warnings/errors.
+- Gear plus bridge focused tests: 28 passed.
+- Assembly focused tests: 100 passed.
+- CLI tests: 440 passed; public documentation qualification: 13 passed.
+- Editable V8 regression: 3 passed.
+- Bridge qualification: direct, exposed, nested, shared definition, phase, transformed axis, ratio/sign, center distance, internal spur, bevel, miter, ratchet/pawl, private access, endpoint type mismatch, seven invalid fixtures, 100 occurrences, deterministic M1/AP242, reimport, and no child STEP dependency passed.
+- Canonical qualification: all five new AssemblyInterfaces Gear fixtures passed. The corpus runner then stopped only on the pre-existing `Assembly/annular-pair.firmament` `LegacyExplicit` policy scan after all canonical operations themselves passed.
+- Full solution concurrent run: 3,520 passed and three unrelated timing-budget tests failed under contention (one recipe timing assertion and two display tessellation budgets). All five isolated theory/test cases passed immediately; focused CLI and Assembly suites are fully green.
+- Repository layout guard: passed (4,164 tracked files).
+- `git diff --check`: passed (line-ending notices only).
+
+## Public surface and limits
+
+Recommended syntax is only:
+
+```firmament
+Expose { Gear Output = OutputGear; }
+Interface<Gear> Transfer { A: RegisterA.Output; B: RegisterB.Input; }
+```
+
+No `Gear<T>`, general mate solver, contact mechanics, torque dynamics, hierarchy flattening, private-boundary bypass, or external semantic STEP round-trip was added.
diff --git a/docs/release/ASM-INTERFACE-X1.md b/docs/release/ASM-INTERFACE-X1.md
new file mode 100644
index 00000000..3ea25665
--- /dev/null
+++ b/docs/release/ASM-INTERFACE-X1.md
@@ -0,0 +1,101 @@
+# ASM-INTERFACE-X1 — typed interface bundles and hierarchical subassemblies
+
+## Executive verdict
+
+**Meaningful progression.** Firmament can now author multi-file, recursively nested reusable Subassemblies with private internals, explicit public semantic ports, stable definition/occurrence identity, deterministic paths, and typed `Fixed`, `Axial`, `Revolute`, and `Custom` relationship bundles. The motivating hierarchy and V8 regression pass through the real Assembly compiler, and an executable multi-file Subassembly lowers once to shared AP242 structure. Full acceptance is withheld because Gear-profile `Interface<Gear>` has not yet been bridged into Assembly-profile semantic endpoints, so the Difference-Engine witness cannot yet prove a Gear mesh inside a Subassembly.
+
+## Architecture audit
+
+1. `Interface<Gear>` existed before X1, but in `FirmamentV2/GearAuthoring`: it is compiler-owned and checks module, pressure angle, family, center distance, axis relation, ratio/sign, bevel closure, and ratchet direction/phase. It was not an `AssemblyM0` Interface.
+2. Atomic Assembly Mate semantics live in `InterfaceRequirementDefinition` and lower in `AssemblyM0Compiler.LowerConstraints` to `PlacementConstraintIr`.
+3. Assembly capability, endpoint, placement, fit, and tolerance Require checks live in `AssemblyM0Compiler`; Gear compatibility checks live in `GearAuthoring.BindInterface`.
+4. An untyped Interface already owned several `Lower` requirements and one fit policy. X1 makes the bundle boundary explicit and inspectable for typed families and `Custom`.
+5. A semantic tree already existed: Template-produced Assemblies had locally solved `AssemblyDefinitionIr`, nested instances, exposed semantics, and private-boundary enforcement. X1 adds a first-class non-parameterized `Subassembly` spelling and makes definitions reusable across files and nesting levels.
+6. Assembly lowering retains the tree in `AssemblyIr`. Geometry execution materializes shared leaf definitions, and AP242 lowering computes local occurrence transforms from the semantic tree; it does not Boolean-flatten before STEP.
+7. One Template definition could already back several occurrences. X1 applies the same cache and stable definition identity to bare Subassembly definitions; the 100-occurrence stress test verifies it.
+8. JSON `.firmasm` remains supported by `FirmamentAssemblyDocumentCompiler`/`FirmasmManifestLoader` with its deprecation diagnostic. It remains a compatibility/import format and does not define new Include or Subassembly semantics.
+
+## Interface family matrix
+
+| `Interface<T>` | Compiler-owned expansion | Atomic Mates | Requires | Qualified |
+|---|---|---|---|---|
+| Fixed | yes | FrameCoincident | exact DatumFrame capability | yes |
+| Axial | yes | AxisCoincident | exact Axis capability | yes |
+| Revolute | yes | AxisCoincident, PlaneCoincident | exact Axis and Plane capabilities | yes |
+| Custom | authored bundle | admitted existing atomic kinds | bounded named numeric length predicates | yes |
+| Gear | yes, Gear profile | Gear-specific compatibility/derived motion metadata | module, pressure angle, family, distance/cone/ratchet closure | not yet in Assembly profile |
+| Slider / Tangent / Bearing | none | none | none | deferred; current placement authority cannot represent them faithfully without speculative semantics |
+
+Inspection retains both levels. For `ShaftBearing`, the source Interface is `Revolute`; its local Mate reports two generated constraint IDs expanding to `AxisCoincident A.Axis -> B.Axis` and `PlaneCoincident A.Seat -> B.Seat`. `CarryLink` reports three authored atomic relations plus `PositiveClearance: 1mm > 0mm (passed)`.
+
+## Hierarchy and encapsulation witness
+
+The three-file fixture lowers to:
+
+```text
+DifferenceEngineReadiness
+ RegisterA = Register
+ Digit0 = DigitModule
+ Shaft
+ Bearing
+ Digit1 = DigitModule
+ Shaft
+ Bearing
+ RegisterB = Register
+ Digit0 = DigitModule
+ Shaft
+ Bearing
+ Digit1 = DigitModule
+ Shaft
+ Bearing
+```
+
+Evidence: 2 shared Subassembly definitions, 15 total tree instances, 2 Register occurrences, 4 DigitModule occurrences, four tree levels including the root, and 2 exposed ports per definition. The parent `RegisterCarry` Interface references only `RegisterA.Output` and `RegisterB.Input`. A fixture that reaches through `RegisterB.Digit0.Input` fails with `assembly-internal-member-hidden`.
+
+The source manifest records the root plus both included files and their SHA-256 identities. Includes are recursively expanded as immutable compiler input before the ordinary parser/compiler path; no child STEP file is generated or consumed. Missing files, cycles, paths outside the source root, duplicate Interfaces, and duplicate Subassembly definitions have typed diagnostics. Include aliasing is intentionally deferred.
+
+The separate executable two-file witness materializes one `CellBlock` leaf definition, instantiates one shared `ExecutableCell` Subassembly definition twice, exports five non-root AP242 occurrences with two definitions, and reimports the product structure successfully. Repository, repeat, and freshly packaged CLI exports all have SHA-256 `E02BEFE33E30BD57BB87AA8C1F38451AFA3CD52E647C24FF944F5BE3DFB903B4`. Neither source file names or consumes a child STEP artifact.
+
+## V8 before / after
+
+The bounded ENGINE-X0 burn-in replaces the generic fixed-frame definition:
+
+```firmament
+Interface RegisteredSeat {
+ Role Moving requires DatumFrameCapable;
+ Role Fixed requires DatumFrameCapable;
+ Lower FrameCoincident Moving Fixed SameDirection;
+}
+```
+
+with:
+
+```firmament
+Interface<Fixed> RegisteredSeat { }
+```
+
+This removes two repeated role declarations and the atomic lowering declaration from the generated source while preserving 170 Mates, 171 physical occurrences, 32 fit results, and all materialized residual checks in the focused real-path regression. Other bespoke V8 Interfaces remain explicit because their fit direction and winding semantics are not equivalent to `Fixed`, `Axial`, or `Revolute`.
+
+## Difference Engine readiness
+
+The upcoming machine can be split into source-level Register and Digit definitions, instantiated repeatedly without cloning definition IR, and connected through exposed ports. It no longer requires one monolithic Assembly file or child STEP round-trips.
+
+Remaining acceptance blockers are concrete:
+
+- bridge Gear-authored semantic endpoints and `Interface<Gear>` expansion into the Assembly IR without duplicating `GearAuthoring`;
+- bridge nested Subassembly definition identity into display-mesh definition records if future consumers need selectable assembly-level (not leaf-part) mesh nodes; current occurrence paths and parent IDs already survive;
+- add an explicit Include alias policy if same-named library definitions become a real consumer need;
+- preserve per-included-file declaration spans rather than only the dependency manifest plus root compilation identity.
+
+No general mate solver, dynamics/contact engine, runtime loader, arbitrary generic Interface family, or second Assembly executor was introduced.
+
+## Validation
+
+- Release solution build: passed with zero warnings and zero errors.
+- Focused Firmament Assembly/Gear suite: 100 passed; focused CLI Assembly/Gear suite: 16 passed.
+- ENGINE-X0 materialized assembly regression: passed with 170 Mates, 171 physical occurrences, 32 fits, and all exported geometry residuals passing.
+- X1 hierarchy, typed-family expansion, custom Require failure, private-boundary rejection, missing Include, cycle chain, whole-tree AP242 lowering/reimport, deterministic repeat, and 100-occurrence reuse: 7 passed.
+- Repository and freshly packed `Aetheris.CLI` inspection parity: both report success, 15 instances, 2 shared definitions, 3 source dependencies, and 3 Interfaces. Repository/repeat/package AP242 hashes match; packaged reimport reports 5 occurrences and 1 geometric leaf definition.
+- Full solution lane: 3,497 tests passed. Three pre-existing timing-budget tests failed while projects ran concurrently (one recipe microbenchmark and two display tessellation budgets); all six relevant theory/case reruns passed immediately in isolated serial project runs. The legacy-gated FrictionLab project exposed no tests.
+- Canonical fixture operations all executed successfully, but the policy scan still reports the pre-existing `Assembly/annular-pair.firmament` use of `LegacyExplicit`; X1 does not alter that compatibility fixture.
+- Repository layout guard and `git diff --check`: passed. Remote CI was not run.
diff --git a/fixtures/Canonical/AssemblyInterfaces/bevel-subassembly-pair.firmament b/fixtures/Canonical/AssemblyInterfaces/bevel-subassembly-pair.firmament
new file mode 100644
index 00000000..525536b9
--- /dev/null
+++ b/fixtures/Canonical/AssemblyInterfaces/bevel-subassembly-pair.firmament
@@ -0,0 +1,13 @@
+Units: mm
+BevelGear Pinion { Module: 1mm Teeth: 20 PressureAngle: 20deg FaceWidth: 5mm BoreDiameter: 5mm PitchConeAngle: 26.565051177deg }
+BevelGear Gear { Module: 1mm Teeth: 40 PressureAngle: 20deg FaceWidth: 5mm BoreDiameter: 8mm PitchConeAngle: 63.434948823deg }
+Subassembly BevelInput { <Assembly BevelInput><Part Gear = Pinion></Part></Assembly> Anchor: BevelInput.Gear; Expose { Gear Port = Gear; } }
+Subassembly BevelOutput { <Assembly BevelOutput><Part Gear = Gear></Part></Assembly> Anchor: BevelOutput.Gear; Expose { Gear Port = Gear; } }
+Assembly BevelBridge {
+ <Assembly BevelBridge>
+ <Assembly A = BevelInput></Assembly>
+ <Assembly B = BevelOutput>Placement ImportedOccurrence = [1,0,0,0, 0,0,1,0, 0,-1,0,0, 0,0,0,1];</Assembly>
+ </Assembly>
+ Anchor: BevelBridge.A.Port;
+ Interface<Gear> Mesh { A: BevelBridge.A.Port; B: BevelBridge.B.Port; ShaftAngle: 90deg }
+}
diff --git a/fixtures/Canonical/AssemblyInterfaces/digit-module.firmament b/fixtures/Canonical/AssemblyInterfaces/digit-module.firmament
new file mode 100644
index 00000000..a7ce7e9f
--- /dev/null
+++ b/fixtures/Canonical/AssemblyInterfaces/digit-module.firmament
@@ -0,0 +1,31 @@
+// Reusable leaf definition. Internal shaft/bearing details are private.
+Subassembly DigitModule {
+ <Assembly DigitModule>
+ <Part Shaft = DigitShaft>
+ Semantic Joint {
+ Axis Axis = [0,0,0] -> [0,0,1];
+ Plane Seat = [0,0,0] normal [0,0,1];
+ Point Locator = [0,0,0];
+ }
+ </Part>
+ <Part Bearing = DigitBearing>
+ Semantic Joint {
+ Axis Axis = [0,0,0] -> [0,0,1];
+ Plane Seat = [0,0,0] normal [0,0,1];
+ Point Locator = [0,0,0];
+ }
+ </Part>
+ </Assembly>
+
+ Anchor: DigitModule.Bearing.Joint;
+
+ Interface<Revolute> ShaftBearing {
+ A: DigitModule.Shaft.Joint;
+ B: DigitModule.Bearing.Joint;
+ }
+
+ Expose {
+ Semantic Input = Bearing.Joint;
+ Semantic Output = Shaft.Joint;
+ }
+}
diff --git a/fixtures/Canonical/AssemblyInterfaces/executable-cell.firmament b/fixtures/Canonical/AssemblyInterfaces/executable-cell.firmament
new file mode 100644
index 00000000..653b1415
--- /dev/null
+++ b/fixtures/Canonical/AssemblyInterfaces/executable-cell.firmament
@@ -0,0 +1,48 @@
+Concept CellBlockConcept {
+ Bounds: Box3
+ Axis: Axis
+ Seat: Plane
+ Base: Plane
+ Height: Length
+}
+
+Record CellBlockSpec { Width: Length Depth: Length Height: Length }
+Static CellBlockValue: CellBlockSpec = CellBlockSpec { Width: 10mm Depth: 10mm Height: 10mm }
+
+Template < Spec: CellBlockSpec >
+Struct CellBlock: CellBlockConcept {
+ Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.Height > 0mm
+ Concept Struct Design: CellBlockConcept {
+ Bounds: Box3 { Size: [Spec.Width, Spec.Depth, Spec.Height] }
+ Axis: Bounds.Center.Axis(+Z)
+ Seat: Bounds.Face(+Z)
+ Base: Bounds.Face(-Z)
+ Height: Spec.Height
+ }
+ Box Body { Bounds: Design.Bounds }
+ Modify Body {
+ EdgeFinish ProofBreak {
+ Face: Design.Seat
+ Target: Boundary
+ Kind: Chamfer
+ Distance: 1mm
+ }
+ }
+ Expose {
+ Bounds: Design.Bounds
+ Axis: Design.Axis
+ Seat: Design.Seat
+ Base: Design.Base
+ Height: Design.Height
+ }
+}
+
+Subassembly ExecutableCell {
+ <Assembly ExecutableCell>
+ <Part Body = CellBlock<Spec: CellBlockValue>>
+ Semantic Port { Axis Axis = [0,0,0] -> [0,0,1]; }
+ </Part>
+ </Assembly>
+ Anchor: ExecutableCell.Body.Port;
+ Expose { Semantic Port = Body.Port; }
+}
diff --git a/fixtures/Canonical/AssemblyInterfaces/executable-machine.firmament b/fixtures/Canonical/AssemblyInterfaces/executable-machine.firmament
new file mode 100644
index 00000000..79b483a0
--- /dev/null
+++ b/fixtures/Canonical/AssemblyInterfaces/executable-machine.firmament
@@ -0,0 +1,17 @@
+Include "executable-cell.firmament";
+
+Interface<Axial> InstallCell { Role A requires AxisCapable; Role B requires AxisCapable; }
+
+Assembly ExecutableMachine {
+ <Assembly ExecutableMachine>
+ <Part Frame = CellBlock<Spec: CellBlockValue>>
+ Semantic Left { Axis Axis = [-30,0,0] -> [0,0,1]; }
+ Semantic Right { Axis Axis = [30,0,0] -> [0,0,1]; }
+ </Part>
+ <Assembly CellA = ExecutableCell></Assembly>
+ <Assembly CellB = ExecutableCell></Assembly>
+ </Assembly>
+ Anchor: ExecutableMachine.Frame.Left;
+ Mate PlaceA: InstallCell { A: ExecutableMachine.CellA.Port; B: ExecutableMachine.Frame.Left; }
+ Mate PlaceB: InstallCell { A: ExecutableMachine.CellB.Port; B: ExecutableMachine.Frame.Right; }
+}
diff --git a/fixtures/Canonical/AssemblyInterfaces/exposed-gear-port.firmament b/fixtures/Canonical/AssemblyInterfaces/exposed-gear-port.firmament
new file mode 100644
index 00000000..9f11b9b3
--- /dev/null
+++ b/fixtures/Canonical/AssemblyInterfaces/exposed-gear-port.firmament
@@ -0,0 +1,41 @@
+Units: mm
+
+SpurGear InputGear {
+ Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 8mm BoreDiameter: 5mm Phase: 0deg
+}
+
+SpurGear OutputGear {
+ Module: 2mm Teeth: 40 PressureAngle: 20deg FaceWidth: 8mm BoreDiameter: 8mm Phase: 4.5deg
+}
+
+Subassembly DigitModule {
+ <Assembly DigitModule>
+ <Part InputGear = InputGear></Part>
+ <Part OutputGear = OutputGear>
+ Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 60,0,0,1];
+ </Part>
+ </Assembly>
+ Anchor: DigitModule.InputGear;
+ Interface<Gear> InternalMesh {
+ A: DigitModule.InputGear;
+ B: DigitModule.OutputGear;
+ }
+ Expose {
+ Gear Input = InputGear;
+ Gear Output = OutputGear;
+ }
+}
+
+Assembly Register {
+ <Assembly Register>
+ <Assembly Digit0 = DigitModule></Assembly>
+ <Assembly Digit1 = DigitModule>
+ Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 120,0,0,1];
+ </Assembly>
+ </Assembly>
+ Anchor: Register.Digit0.Output;
+ Interface<Gear> Transfer {
+ A: Register.Digit0.Output;
+ B: Register.Digit1.Input;
+ }
+}
diff --git a/fixtures/Canonical/AssemblyInterfaces/gear-between-subassemblies.firmament b/fixtures/Canonical/AssemblyInterfaces/gear-between-subassemblies.firmament
new file mode 100644
index 00000000..776687a9
--- /dev/null
+++ b/fixtures/Canonical/AssemblyInterfaces/gear-between-subassemblies.firmament
@@ -0,0 +1,15 @@
+Units: mm
+SpurGear Wheel { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm Phase: 3deg }
+Subassembly GearCell {
+ <Assembly GearCell><Part Wheel = Wheel></Part></Assembly>
+ Anchor: GearCell.Wheel;
+ Expose { Gear Port = Wheel; }
+}
+Assembly GearCells {
+ <Assembly GearCells>
+ <Assembly A = GearCell></Assembly>
+ <Assembly B = GearCell>Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 40,0,0,1];</Assembly>
+ </Assembly>
+ Anchor: GearCells.A.Port;
+ Interface<Gear> Transfer { A: GearCells.A.Port; B: GearCells.B.Port; }
+}
diff --git a/fixtures/Canonical/AssemblyInterfaces/machine.firmament b/fixtures/Canonical/AssemblyInterfaces/machine.firmament
new file mode 100644
index 00000000..5a3f6c13
--- /dev/null
+++ b/fixtures/Canonical/AssemblyInterfaces/machine.firmament
@@ -0,0 +1,16 @@
+Include "register.firmament";
+
+Assembly DifferenceEngineReadiness {
+ <Assembly DifferenceEngineReadiness>
+ <Assembly RegisterA = Register></Assembly>
+ <Assembly RegisterB = Register></Assembly>
+ </Assembly>
+
+ Anchor: DifferenceEngineReadiness.RegisterA.Output;
+
+ // The parent sees only public ports; no Digit or Shaft path crosses the boundary.
+ Interface<Axial> RegisterCarry {
+ A: DifferenceEngineReadiness.RegisterB.Input;
+ B: DifferenceEngineReadiness.RegisterA.Output;
+ }
+}
diff --git a/fixtures/Canonical/AssemblyInterfaces/nested-register-gear.firmament b/fixtures/Canonical/AssemblyInterfaces/nested-register-gear.firmament
new file mode 100644
index 00000000..464be0a4
--- /dev/null
+++ b/fixtures/Canonical/AssemblyInterfaces/nested-register-gear.firmament
@@ -0,0 +1,20 @@
+Units: mm
+SpurGear Wheel { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm Phase: 9deg }
+Subassembly DigitModule {
+ <Assembly DigitModule><Part Gear = Wheel></Part></Assembly>
+ Anchor: DigitModule.Gear;
+ Expose { Gear Input = Gear; Gear Output = Gear; }
+}
+Subassembly Register {
+ <Assembly Register><Assembly Digit = DigitModule></Assembly></Assembly>
+ Anchor: Register.Digit.Input;
+ Expose { Gear Input = Digit.Input; Gear Output = Digit.Output; }
+}
+Assembly Machine {
+ <Assembly Machine>
+ <Assembly RegisterA = Register></Assembly>
+ <Assembly RegisterB = Register>Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 40,0,0,1];</Assembly>
+ </Assembly>
+ Anchor: Machine.RegisterA.Output;
+ Interface<Gear> RegisterTransfer { A: Machine.RegisterA.Output; B: Machine.RegisterB.Input; }
+}
diff --git a/fixtures/Canonical/AssemblyInterfaces/register.firmament b/fixtures/Canonical/AssemblyInterfaces/register.firmament
new file mode 100644
index 00000000..1c0aee19
--- /dev/null
+++ b/fixtures/Canonical/AssemblyInterfaces/register.firmament
@@ -0,0 +1,26 @@
+Include "digit-module.firmament";
+
+// One definition contains two occurrences of the shared DigitModule definition.
+Subassembly Register {
+ <Assembly Register>
+ <Assembly Digit0 = DigitModule></Assembly>
+ <Assembly Digit1 = DigitModule></Assembly>
+ </Assembly>
+
+ Anchor: Register.Digit0.Output;
+
+ Interface<Custom> CarryLink {
+ A: Register.Digit1.Input;
+ B: Register.Digit0.Output;
+ Mate AxisCoincident A.Axis B.Axis;
+ Mate PlaneCoincident A.Seat B.Seat;
+ Mate PointCoincident A.Locator B.Locator;
+ Require PositiveClearance => 1mm > 0mm;
+ Allow rotation:about-axis;
+ }
+
+ Expose {
+ Semantic Input = Digit0.Input;
+ Semantic Output = Digit1.Output;
+ }
+}
diff --git a/fixtures/Canonical/AssemblyInterfaces/three-gear-train-hierarchical.firmament b/fixtures/Canonical/AssemblyInterfaces/three-gear-train-hierarchical.firmament
new file mode 100644
index 00000000..c3030d97
--- /dev/null
+++ b/fixtures/Canonical/AssemblyInterfaces/three-gear-train-hierarchical.firmament
@@ -0,0 +1,21 @@
+Units: mm
+SpurGear Driver { Module: 1mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+SpurGear Idler { Module: 1mm Teeth: 30 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm Phase: 6deg }
+SpurGear Output { Module: 1mm Teeth: 40 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+Subassembly InputStage {
+ <Assembly InputStage>
+ <Part Driver = Driver></Part>
+ <Part Idler = Idler>Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 25,0,0,1];</Part>
+ </Assembly>
+ Anchor: InputStage.Driver;
+ Interface<Gear> FirstMesh { A: InputStage.Driver; B: InputStage.Idler; }
+ Expose { Gear Output = Idler; }
+}
+Assembly GearTrain {
+ <Assembly GearTrain>
+ <Assembly Stage = InputStage></Assembly>
+ <Part Output = Output>Placement ImportedOccurrence = [1,0,0,0, 0,1,0,0, 0,0,1,0, 60,0,0,1];</Part>
+ </Assembly>
+ Anchor: GearTrain.Stage.Output;
+ Interface<Gear> SecondMesh { A: GearTrain.Stage.Output; B: GearTrain.Output; }
+}
diff --git a/fixtures/Canonical/qualification.json b/fixtures/Canonical/qualification.json
index d09723c5..b8eff0ca 100644
--- a/fixtures/Canonical/qualification.json
+++ b/fixtures/Canonical/qualification.json
@@ -10,6 +10,7 @@
],
"actions": [
{ "path": "Assembly", "operation": "assembly-inspect" },
+ { "path": "AssemblyInterfaces", "operation": "assembly-inspect" },
{ "path": "Drawings", "operation": "drawing-compile" },
{ "path": "FEA", "operation": "fea-solve" },
{ "path": "Materials", "operation": "fea-solve" },
diff --git a/fixtures/Invalid/AssemblyInterfaces/exposed-wrong-endpoint-type.firmament b/fixtures/Invalid/AssemblyInterfaces/exposed-wrong-endpoint-type.firmament
new file mode 100644
index 00000000..ef625842
--- /dev/null
+++ b/fixtures/Invalid/AssemblyInterfaces/exposed-wrong-endpoint-type.firmament
@@ -0,0 +1,7 @@
+Units: mm
+SpurGear G { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+Assembly WrongType {
+ <Assembly WrongType><Part Gear = G></Part><Part Shaft = Block>Semantic Port { Axis Axis = [0,0,0] -> [0,0,1]; }</Part></Assembly>
+ Anchor: WrongType.Gear;
+ Interface<Gear> Invalid { A: WrongType.Gear; B: WrongType.Shaft.Port; }
+}
diff --git a/fixtures/Invalid/AssemblyInterfaces/failed-custom-require.firmament b/fixtures/Invalid/AssemblyInterfaces/failed-custom-require.firmament
new file mode 100644
index 00000000..3067fbca
--- /dev/null
+++ b/fixtures/Invalid/AssemblyInterfaces/failed-custom-require.firmament
@@ -0,0 +1,19 @@
+Assembly FailedCustomRequire {
+ <Assembly FailedCustomRequire>
+ <Part A = Shaft>
+ Semantic Joint { Axis Axis = [0,0,0] -> [0,0,1]; }
+ </Part>
+ <Part B = Bearing>
+ Semantic Joint { Axis Axis = [0,0,0] -> [0,0,1]; }
+ </Part>
+ </Assembly>
+ Anchor: FailedCustomRequire.A.Joint;
+ Interface<Custom> ImpossibleClearance {
+ A: FailedCustomRequire.B.Joint;
+ B: FailedCustomRequire.A.Joint;
+ Mate AxisCoincident A.Axis B.Axis;
+ Require ClearancePositive => -1mm > 0mm;
+ Allow translation:along-axis;
+ Allow rotation:about-axis;
+ }
+}
diff --git a/fixtures/Invalid/AssemblyInterfaces/gear-axis-mismatch.firmament b/fixtures/Invalid/AssemblyInterfaces/gear-axis-mismatch.firmament
new file mode 100644
index 00000000..a668ed9a
--- /dev/null
+++ b/fixtures/Invalid/AssemblyInterfaces/gear-axis-mismatch.firmament
@@ -0,0 +1,4 @@
+Units: mm
+SpurGear A { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+SpurGear B { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+Assembly AxisMismatch { <Assembly AxisMismatch><Part A = A></Part><Part B = B>Placement ImportedOccurrence = [1,0,0,0,0,0,1,0,0,-1,0,0,40,0,0,1];</Part></Assembly> Anchor: AxisMismatch.A; Interface<Gear> Mesh { A: AxisMismatch.A; B: AxisMismatch.B; } }
diff --git a/fixtures/Invalid/AssemblyInterfaces/gear-center-distance-mismatch.firmament b/fixtures/Invalid/AssemblyInterfaces/gear-center-distance-mismatch.firmament
new file mode 100644
index 00000000..10d0bdd9
--- /dev/null
+++ b/fixtures/Invalid/AssemblyInterfaces/gear-center-distance-mismatch.firmament
@@ -0,0 +1,4 @@
+Units: mm
+SpurGear A { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+SpurGear B { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+Assembly CenterMismatch { <Assembly CenterMismatch><Part A = A></Part><Part B = B>Placement ImportedOccurrence = [1,0,0,0,0,1,0,0,0,0,1,0,41,0,0,1];</Part></Assembly> Anchor: CenterMismatch.A; Interface<Gear> Mesh { A: CenterMismatch.A; B: CenterMismatch.B; } }
diff --git a/fixtures/Invalid/AssemblyInterfaces/gear-module-mismatch.firmament b/fixtures/Invalid/AssemblyInterfaces/gear-module-mismatch.firmament
new file mode 100644
index 00000000..b60e53e0
--- /dev/null
+++ b/fixtures/Invalid/AssemblyInterfaces/gear-module-mismatch.firmament
@@ -0,0 +1,4 @@
+Units: mm
+SpurGear A { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+SpurGear B { Module: 1.5mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+Assembly ModuleMismatch { <Assembly ModuleMismatch><Part A = A></Part><Part B = B>Placement ImportedOccurrence = [1,0,0,0,0,1,0,0,0,0,1,0,35,0,0,1];</Part></Assembly> Anchor: ModuleMismatch.A; Interface<Gear> Mesh { A: ModuleMismatch.A; B: ModuleMismatch.B; } }
diff --git a/fixtures/Invalid/AssemblyInterfaces/gear-pressure-angle-mismatch.firmament b/fixtures/Invalid/AssemblyInterfaces/gear-pressure-angle-mismatch.firmament
new file mode 100644
index 00000000..1a798e06
--- /dev/null
+++ b/fixtures/Invalid/AssemblyInterfaces/gear-pressure-angle-mismatch.firmament
@@ -0,0 +1,4 @@
+Units: mm
+SpurGear A { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+SpurGear B { Module: 2mm Teeth: 20 PressureAngle: 25deg FaceWidth: 6mm BoreDiameter: 5mm }
+Assembly PressureMismatch { <Assembly PressureMismatch><Part A = A></Part><Part B = B>Placement ImportedOccurrence = [1,0,0,0,0,1,0,0,0,0,1,0,40,0,0,1];</Part></Assembly> Anchor: PressureMismatch.A; Interface<Gear> Mesh { A: PressureMismatch.A; B: PressureMismatch.B; } }
diff --git a/fixtures/Invalid/AssemblyInterfaces/invalid-nested-gear-path.firmament b/fixtures/Invalid/AssemblyInterfaces/invalid-nested-gear-path.firmament
new file mode 100644
index 00000000..ebc1716b
--- /dev/null
+++ b/fixtures/Invalid/AssemblyInterfaces/invalid-nested-gear-path.firmament
@@ -0,0 +1,8 @@
+Units: mm
+SpurGear G { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+Subassembly Cell {
+ <Assembly Cell><Part Gear = G></Part></Assembly>
+ Anchor: Cell.Gear;
+ Expose { Gear Missing = Gear.DoesNotExist; }
+}
+Assembly InvalidPath { <Assembly InvalidPath><Assembly Cell = Cell></Assembly></Assembly> }
diff --git a/fixtures/Invalid/AssemblyInterfaces/private-gear-access.firmament b/fixtures/Invalid/AssemblyInterfaces/private-gear-access.firmament
new file mode 100644
index 00000000..0813a257
--- /dev/null
+++ b/fixtures/Invalid/AssemblyInterfaces/private-gear-access.firmament
@@ -0,0 +1,8 @@
+Units: mm
+SpurGear G { Module: 2mm Teeth: 20 PressureAngle: 20deg FaceWidth: 6mm BoreDiameter: 5mm }
+Subassembly Cell { <Assembly Cell><Part Hidden = G></Part></Assembly> Anchor: Cell.Hidden; }
+Assembly PrivateAccess {
+ <Assembly PrivateAccess><Assembly A = Cell></Assembly><Assembly B = Cell></Assembly></Assembly>
+ Anchor: PrivateAccess.A;
+ Interface<Gear> Illegal { A: PrivateAccess.A.Hidden; B: PrivateAccess.B.Hidden; }
+}
diff --git a/fixtures/Invalid/AssemblyInterfaces/private-internal-access.firmament b/fixtures/Invalid/AssemblyInterfaces/private-internal-access.firmament
new file mode 100644
index 00000000..b1264651
--- /dev/null
+++ b/fixtures/Invalid/AssemblyInterfaces/private-internal-access.firmament
@@ -0,0 +1,13 @@
+Include "../../Canonical/AssemblyInterfaces/register.firmament";
+
+Assembly PrivateAccess {
+ <Assembly PrivateAccess>
+ <Assembly RegisterA = Register></Assembly>
+ <Assembly RegisterB = Register></Assembly>
+ </Assembly>
+ Anchor: PrivateAccess.RegisterA.Input;
+ Interface<Axial> InvalidPrivateReach {
+ A: PrivateAccess.RegisterB.Digit0.Input;
+ B: PrivateAccess.RegisterA.Output;
+ }
+}
diff --git a/tools/vscode-firmament/syntaxes/firmament.tmLanguage.json b/tools/vscode-firmament/syntaxes/firmament.tmLanguage.json
index 09bbde07..676c364c 100644
--- a/tools/vscode-firmament/syntaxes/firmament.tmLanguage.json
+++ b/tools/vscode-firmament/syntaxes/firmament.tmLanguage.json
@@ -49,7 +49,7 @@
},
{
"name": "keyword.declaration.firmament",
- "match": "\\b(?:Model|Units|Use|Enum|Box|Cylinder|Cone|Sphere|Torus|RoundedBox|Frustum|Concept|Struct|Construction|Plane|Path|Profile|ProfileDelta|Sweep|Compose|Boss|Pocket|AddOffset|RemoveOffset|Modify|Selection|Record|Static|Table|Template|Pattern|Match|Require|Pmi|Datum|HoleDiameter|Assert|InlineStep|Recognize|Replace|EdgeFinish|Hole|Slot|Region|Segment|Loop|Base|Extrude|SheetMetal|Flange|Analysis|Fixed|Force|Material|Results|Lattice)\\b"
+ "match": "\\b(?:Model|Units|Use|Include|Enum|Box|Cylinder|Cone|Sphere|Torus|RoundedBox|Frustum|Concept|Struct|Construction|Plane|Path|Profile|ProfileDelta|Sweep|Compose|Boss|Pocket|AddOffset|RemoveOffset|Modify|Selection|Record|Static|Table|Template|Pattern|Match|Require|Pmi|Datum|HoleDiameter|Assert|InlineStep|Recognize|Replace|EdgeFinish|Hole|Slot|Region|Segment|Loop|Base|Extrude|SheetMetal|Flange|Analysis|Assembly|Subassembly|Interface|Mate|Expose|Role|Lower|Allow|Anchor|Fixed|Force|Material|Results|Lattice)\\b"
},
{ "name": "keyword.control.firmament", "match": "\\b(?:with|With|From|Using|On|Over|As|Current|Key)\\b" }
]