Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Validate builds and improve Firmament diagnostics

Yuechen Li03d85adeb759
diff --git a/Aetheris.CLI.Tests/FirmamentTypedToleranceCliTests.cs b/Aetheris.CLI.Tests/FirmamentTypedToleranceCliTests.cs
new file mode 100644
index 00000000..e51c2de7
--- /dev/null
+++ b/Aetheris.CLI.Tests/FirmamentTypedToleranceCliTests.cs
@@ -0,0 +1,88 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class FirmamentTypedToleranceCliTests
+{
+ private static string Root => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../.."));
+
+ [Theory]
+ [InlineData("unit-mismatch", "firmament-v2-tolerance-unit-mismatch")]
+ [InlineData("sweep-unconsumed", "firmament-v2-static-scalar-consumer-unsupported")]
+ [InlineData("wireform-unconsumed", "firmament-v2-static-scalar-consumer-unsupported")]
+ public void ValidateBuildAndParseOnlyRejectTheSameLocatedTypeError(string specimen, string code)
+ {
+ var source = Path.Combine(Root, "fixtures/Regression/TypedTolerances", specimen + ".firmament");
+ var destination = Path.Combine(Root, "artifacts/local/firmament-typed-tolerances", Guid.NewGuid() + ".step");
+ foreach (var command in new[] { "validate", "build", "parse-only" })
+ {
+ var output = new StringWriter(); var error = new StringWriter();
+ string[] arguments = command == "build" ? ["build", source, "--output", destination, "--json"]
+ : ["validate", source, "--json", .. (command == "parse-only" ? new[] { "--parse-only" } : [])];
+ Assert.Equal(1, CliRunner.Run(arguments, output, error));
+ using var json = JsonDocument.Parse(output.ToString());
+ var root = command == "build" ? json.RootElement : json.RootElement.GetProperty("firmamentV2Validation");
+ var diagnostic = Assert.Single(root.GetProperty("diagnostics").EnumerateArray(),
+ d => d.GetProperty("code").GetString() == code);
+ Assert.Equal(source, diagnostic.GetProperty("sourceFile").GetString());
+ Assert.True(diagnostic.GetProperty("line").GetInt32() > 0);
+ if (specimen == "unit-mismatch")
+ {
+ Assert.Equal(3, diagnostic.GetProperty("line").GetInt32());
+ Assert.Contains("mm", diagnostic.GetProperty("message").GetString());
+ }
+ Assert.False(File.Exists(destination));
+ }
+ }
+
+ [Fact]
+ public void NormalValidateAdmitsTheRealTypedPmiWitness()
+ {
+ var source = Path.Combine(Root, "fixtures/Canonical/PMI/typed-tolerance.firmament");
+ var output = new StringWriter(); var error = new StringWriter();
+ Assert.Equal(0, CliRunner.Run(["validate", source, "--json", "--explain"], output, error));
+ using var json = JsonDocument.Parse(output.ToString());
+ var report = json.RootElement.GetProperty("firmamentV2Validation");
+ Assert.Equal("Built", report.GetProperty("validationLevel").GetString());
+ Assert.Equal("valid", report.GetProperty("status").GetString());
+ }
+
+ [Fact]
+ public void SweepValidationIdentifiesItsActualBuildLevel()
+ {
+ var source = Path.Combine(Root, "fixtures/Canonical/Features/Sweep/circular-planar-path-sweep.firmament");
+ foreach (var parseOnly in new[] { true, false })
+ {
+ var output = new StringWriter(); var error = new StringWriter();
+ Assert.Equal(0, CliRunner.Run(["validate", source, "--json", .. (parseOnly ? new[] { "--parse-only" } : [])], output, error));
+ using var json = JsonDocument.Parse(output.ToString());
+ var report = json.RootElement.GetProperty("firmamentV2Validation");
+ Assert.Equal(parseOnly ? "ParsedNotBuilt" : "Built", report.GetProperty("validationLevel").GetString());
+ Assert.Equal("UnifiedSweep", report.GetProperty("parserRoute").GetString());
+ }
+ }
+
+ [Fact]
+ public void LegacyPmiCannotBypassTheSharedExportCapabilityGate()
+ {
+ var source = Path.Combine(Root, "fixtures/Regression/TypedTolerances/legacy-datum-reference.firmament");
+ var destination = Path.Combine(Root, "artifacts/local/firmament-typed-tolerances", Guid.NewGuid() + ".step");
+ foreach (var build in new[] { true, false })
+ {
+ var output = new StringWriter(); var error = new StringWriter();
+ Assert.Equal(1, CliRunner.Run(build ? ["build", source, "--output", destination, "--json"] : ["validate", source, "--json"], output, error));
+ using var json = JsonDocument.Parse(output.ToString());
+ var root = build ? json.RootElement : json.RootElement.GetProperty("firmamentV2Validation");
+ Assert.Contains(root.GetProperty("diagnostics").EnumerateArray(), d => d.GetProperty("code").GetString() == "firmament-v2-pmi-datum-reference-export-unsupported");
+ Assert.False(File.Exists(destination));
+ }
+ var parseOutput = new StringWriter(); var parseError = new StringWriter();
+ Assert.Equal(0, CliRunner.Run(["validate", source, "--parse-only", "--json"], parseOutput, parseError));
+ using var parsed = JsonDocument.Parse(parseOutput.ToString());
+ var report = parsed.RootElement.GetProperty("firmamentV2Validation");
+ Assert.Equal("ParsedNotBuilt", report.GetProperty("validationLevel").GetString());
+ Assert.Equal("parsed-not-built", report.GetProperty("status").GetString());
+ Assert.Contains(report.GetProperty("pmi").EnumerateArray(), p => p.GetProperty("exportSupport").GetString() == "deferred"
+ && p.GetProperty("reason").GetString()!.Contains("datum-reference-export-unsupported", StringComparison.Ordinal));
+ }
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index e6b968b8..3d511246 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -2428,25 +2428,53 @@ Model CanonicalPanel {
{
var wireSource = ExpandSweepInspectionSource(validationSource, out var expansionDiagnostics);
var authored = wireSource is null ? null : WireFormAuthoring.Parse(wireSource);
- var diagnostics = expansionDiagnostics.Concat(authored is null ? [] : authored.IsSuccess ? WireFormBRepMaterializer.Validate(authored.Value) : authored.Diagnostics.Select(item => item.Message)).ToArray();
- var valid = authored?.IsSuccess == true && diagnostics.Length == 0;
- var payload = new { source = sourcePath, status = valid ? "valid" : "invalid", domain = "WireForm",
+ var wireFailures = expansionDiagnostics.Concat(authored is null ? [] : authored.IsSuccess ? WireFormBRepMaterializer.Validate(authored.Value) : authored.Diagnostics.Select(item => item.Message)).ToList();
+ var valid = authored?.IsSuccess == true && wireFailures.Count == 0;
+ if (valid && !parseOnly)
+ {
+ var compilation = FirmamentBuildAndExport.CompileSource(validationSource, Path.GetDirectoryName(Path.GetFullPath(sourcePath)));
+ valid = compilation.IsSuccess;
+ if (!valid) wireFailures.AddRange(compilation.Diagnostics.Select(d => d.Message));
+ }
+ var diagnostics = wireFailures.Select(message => FirmamentBuildAdmissionValidation.Present(new KernelDiagnostic(
+ KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, "Firmament.WireForm"), sourcePath, validationSource)).ToArray();
+ var payload = new { source = sourcePath, status = valid ? (parseOnly ? "parsed-not-built" : "valid") : "invalid", domain = "WireForm",
+ validationLevel = valid ? (parseOnly ? "ParsedNotBuilt" : "Built") : "BuildRejected",
summary = new { fatalDiagnosticCount = diagnostics.Length, warningDiagnosticCount = 0, operationCount = authored?.IsSuccess == true ? authored.Value.Operations.Count : 0 }, diagnostics };
if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
- else stdout.WriteLine($"Firmament V2 WireForm validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");
+ else
+ {
+ stdout.WriteLine($"Firmament V2 WireForm validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");
+ foreach (var diagnostic in diagnostics)
+ stdout.WriteLine($"{diagnostic.SourceFile}:{diagnostic.Line}:{diagnostic.Column} {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");
+ }
return valid ? 0 : 1;
}
if (CircularSweepAuthoring.IsSweepSource(validationSource))
{
var sweepSource = ExpandSweepInspectionSource(validationSource, out var sweepExpansionDiagnostics);
var authored = sweepSource is null ? null : CircularSweepAuthoring.Parse(sweepSource);
- var sweepDiagnostics = sweepExpansionDiagnostics.Concat(authored is null ? [] : authored.IsSuccess ? CircularSweepBRepMaterializer.Validate(authored.Value) : authored.Diagnostics.Select(item => item.Message)).ToArray();
- var valid = authored?.IsSuccess == true && sweepDiagnostics.Length == 0;
- var payload = new { source = sourcePath, status = valid ? "valid" : "invalid", domain = "CircularSweep",
+ var sweepFailures = sweepExpansionDiagnostics.Concat(authored is null ? [] : authored.IsSuccess ? CircularSweepBRepMaterializer.Validate(authored.Value) : authored.Diagnostics.Select(item => item.Message)).ToList();
+ var valid = authored?.IsSuccess == true && sweepFailures.Count == 0;
+ if (valid && !parseOnly)
+ {
+ var compilation = FirmamentBuildAndExport.CompileSource(validationSource, Path.GetDirectoryName(Path.GetFullPath(sourcePath)));
+ valid = compilation.IsSuccess;
+ if (!valid) sweepFailures.AddRange(compilation.Diagnostics.Select(d => d.Message));
+ }
+ var sweepDiagnostics = sweepFailures.Select(message => FirmamentBuildAdmissionValidation.Present(new KernelDiagnostic(
+ KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, "Firmament.Sweep"), sourcePath, validationSource)).ToArray();
+ var payload = new { source = sourcePath, status = valid ? (parseOnly ? "parsed-not-built" : "valid") : "invalid", domain = "CircularSweep",
+ validationLevel = valid ? (parseOnly ? "ParsedNotBuilt" : "Built") : "BuildRejected", parserRoute = "UnifiedSweep",
summary = new { fatalDiagnosticCount = sweepDiagnostics.Length, warningDiagnosticCount = 0,
segmentCount = authored?.IsSuccess == true ? authored.Value.Path.Segments.Count : 0 }, diagnostics = sweepDiagnostics };
if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
- else stdout.WriteLine($"Firmament V2 Circular Sweep validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");
+ else
+ {
+ stdout.WriteLine($"Firmament V2 Circular Sweep validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");
+ foreach (var diagnostic in sweepDiagnostics)
+ stdout.WriteLine($"{diagnostic.SourceFile}:{diagnostic.Line}:{diagnostic.Column} {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");
+ }
return valid ? 0 : 1;
}
if(SheetMetalFirmament.LooksLikeSheetMetal(validationSource))
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentTypedToleranceTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentTypedToleranceTests.cs
new file mode 100644
index 00000000..5cbe659d
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentTypedToleranceTests.cs
@@ -0,0 +1,246 @@
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentTypedToleranceTests
+{
+ private static string Source => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/PMI/typed-tolerance.firmament"));
+
+ [Fact]
+ public void TypedValuesBindNominalGeometryAndProjectAllowanceToRealAp242()
+ {
+ var source = Source;
+ var syntax = FirmamentSyntaxParser.Parse(source);
+ Assert.True(syntax.IsSuccess, string.Join("\n", syntax.Diagnostics));
+ Assert.Equal(3, FirmamentSyntaxTraversal.Expressions(syntax.Document).OfType<ToleranceSyntax>().Count());
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.Equal("UnifiedMechanical", parsed.ParserRoute);
+ var values = parsed.Document!.BoundLets!.ToDictionary(v => v.Name);
+ var alias = values["inspectionDiameter"];
+ Assert.Equal(0.10, alias.Tolerance!.Plus);
+ Assert.Equal(0.05, alias.Tolerance.Minus);
+ Assert.Equal(FirmamentV2PrimitiveType.Angle, values["draft"].Tolerance!.Type);
+ Assert.Equal(40, parsed.Document.Solid.Box!.Size[0]);
+ Assert.Equal(8, Assert.Single(Assert.Single(parsed.Document.ModifyBlocks!).SemanticHoles).ShaftDiameter);
+ var compiled = FirmamentBuildAndExport.CompileSource(source, null);
+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics.Select(d => d.Message)));
+ var inspection = Step242SemanticPmiInspector.Inspect(compiled.Value.StepText);
+ Assert.True(inspection.Success, string.Join("\n", inspection.Diagnostics));
+ var callout = Assert.Single(inspection.Items, i => i.Kind == "Diameter");
+ Assert.Equal(8, callout.Value);
+ Assert.Equal(0.10, callout.TolerancePlus);
+ Assert.Equal(0.05, callout.ToleranceMinus);
+ Assert.NotEmpty(callout.GeometricFaceEntityIds);
+ var imported = Step242Importer.ImportBody(compiled.Value.StepText);
+ Assert.True(imported.IsSuccess);
+ Assert.Equal(7, imported.Value.Topology.Faces.Count());
+ }
+
+ [Fact]
+ public void ChangingToleranceDoesNotChangeNominalBrepOrCreateImplicitPmi()
+ {
+ var withoutPmi = Source[..Source.IndexOf(" Pmi", StringComparison.Ordinal)] + "}";
+ var changed = withoutPmi.Replace("tol 0.1mm", "tol 0.2mm").Replace("tol +0.10mm -0.05mm", "tol +0.20mm -0.15mm");
+ var before = FirmamentBuildAndExport.CompileSource(withoutPmi, null);
+ var after = FirmamentBuildAndExport.CompileSource(changed, null);
+ Assert.True(before.IsSuccess, string.Join("\n", before.Diagnostics.Select(d => d.Message)));
+ Assert.True(after.IsSuccess, string.Join("\n", after.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(before.Value.StepText, after.Value.StepText);
+ Assert.Equal(0, Step242SemanticPmiInspector.Inspect(after.Value.StepText).DimensionCount);
+ var literals = string.Join('\n', withoutPmi.Split('\n').Where(line => !line.TrimStart().StartsWith("Static ", StringComparison.Ordinal)))
+ .Replace("[plateWidth,", "[40mm,", StringComparison.Ordinal)
+ .Replace("diameter: drillDiameter", "diameter: 8mm", StringComparison.Ordinal);
+ var direct = FirmamentBuildAndExport.CompileSource(literals, null);
+ Assert.True(direct.IsSuccess, string.Join("\n", direct.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(before.Value.StepText, direct.Value.StepText);
+ }
+
+ [Theory]
+ [InlineData("Static x: Int = 4 tol 1", FirmamentV2Parser.ToleranceInvalidType)]
+ [InlineData("Static x: Length = 8mm tol 0.1deg", FirmamentV2Parser.ToleranceUnitMismatch)]
+ [InlineData("Static x: Length = 8mm tol -0.1mm", FirmamentV2Parser.ToleranceNegativeBilateral)]
+ [InlineData("Static x: Length = 8mm tol +0.1mm", FirmamentV2Parser.ToleranceMissingMinus)]
+ [InlineData("Static x: Length = missing tol 0.1mm", FirmamentV2Parser.ExpressionUnknownSymbol)]
+ [InlineData("Static x: Length = x tol 0.1mm", FirmamentV2Parser.ExpressionCycle)]
+ [InlineData("Static x: Length = 8mm / 0 tol 0.1mm", FirmamentV2Parser.ExpressionDivisionByZero)]
+ [InlineData("Static x: Int = 2147483647 + 1", "firmament-v2-static-scalar-out-of-range")]
+ [InlineData("Static x: Length = 1e308mm * 1e308 tol 0.1mm", "firmament-v2-static-scalar-nonfinite")]
+ public void InvalidTypedRequirementsRejectAdmissionAndBuildWithLocatedDiagnostics(string declaration, string code)
+ {
+ var source = "Model Invalid { units: mm " + declaration + "\n Box Body { size: [40mm,30mm,8mm] } }";
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.Contains(code, parsed.Diagnostics);
+ var diagnostic = Assert.Single(parsed.SyntaxDiagnostics, d => d.Code == code);
+ Assert.NotNull(diagnostic.SourceSpan);
+ Assert.False(string.IsNullOrWhiteSpace(diagnostic.Message));
+ Assert.False(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void InlineToleranceIsNotSilentlyDiscardedAndMalformedUnusedPathDoesNotPretendToBind()
+ {
+ var inline = "Model Inline { units: mm Box Body { size: [40mm tol 0.1mm, 30mm, 8mm] } }";
+ Assert.False(FirmamentBuildAndExport.CompileSource(inline, null).IsSuccess);
+ var path = "Model Bare { units: mm Box Body { size: [40mm,30mm,8mm] } Path ignored { } }";
+ var parsed = FirmamentV2Parser.Parse(path);
+ Assert.False(parsed.IsSuccess);
+ Assert.Contains(parsed.Diagnostics, d => d.StartsWith("concept-path-start-invalid", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void BarePathAndConceptPathHaveIdenticalGeometryAndPublishedMembers()
+ {
+ var legacy = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Profiles/concept-path-line-arc-profile.firmament"));
+ var canonical = legacy.Replace("Concept Path", "Path", StringComparison.Ordinal);
+ var before = FirmamentBuildAndExport.CompileSource(legacy, null);
+ var after = FirmamentBuildAndExport.CompileSource(canonical, null);
+ Assert.True(before.IsSuccess, string.Join("\n", before.Diagnostics.Select(d => d.Message)));
+ Assert.True(after.IsSuccess, string.Join("\n", after.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(before.Value.StepText, after.Value.StepText);
+ var path = ProfileAuthoringParser.ResolveConceptPath(canonical, "RoundedCorner", out var diagnostics);
+ Assert.NotNull(path);
+ Assert.Empty(diagnostics);
+ Assert.Equal(5, path.Segments.Count);
+ }
+
+ [Theory]
+ [InlineData("dimension: inspectionDiameter", "dimension: inspectionDiameter tolerance: 0.2mm", "firmament-v2-pmi-typed-dimension-override")]
+ [InlineData("diameter: drillDiameter end:", "diameter: 9mm end:", "firmament-v2-pmi-typed-dimension-unsatisfied")]
+ [InlineData("dimension: inspectionDiameter", "dimension: draft", FirmamentV2Parser.PmiDimensionTypeMismatch)]
+ [InlineData("Static inspectionDiameter: Length = drillDiameter", "Static inspectionDiameter: Length = -1mm tol 10mm", FirmamentV2Parser.PmiDiameterInvalid)]
+ public void ProjectionCannotOverrideOrMisrepresentTheTypedRequirement(string from, string to, string code)
+ {
+ var source = Source.Replace(from, to, StringComparison.Ordinal);
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.Contains(code, parsed.Diagnostics);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void ScalarArithmeticRetainsNominalPolicyAndAnExplicitResultTolerance()
+ {
+ const string source = """
+ Model Arithmetic {
+ units: mm
+ Static d: Length = 8mm tol 0.1mm
+ Static radius: Length = d / 2
+ Static larger: Length = d + 2mm tol 0.2mm
+ Box Body { size: [larger, 20mm, 8mm] }
+ }
+ """;
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var values = parsed.Document!.BoundLets!.ToDictionary(v => v.Name);
+ Assert.Null(values["radius"].Tolerance);
+ Assert.Equal(4, values["radius"].Value.NumericValue);
+ Assert.Equal(10, values["larger"].Value.NumericValue);
+ Assert.Equal(0.2, values["larger"].Tolerance!.Plus);
+ Assert.Contains(parsed.SyntaxDiagnostics, d => d.Code == FirmamentV2Parser.ToleranceDroppedThroughArithmetic && d.Severity == "warning");
+ Assert.Contains(FirmamentLanguageAnalysisService.Analyze(source, "arithmetic.firmament", "1").Diagnostics,
+ d => d.Code == FirmamentV2Parser.ToleranceDroppedThroughArithmetic && d.Severity == "warning");
+ Assert.True(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Theory]
+ [InlineData("fixtures/Canonical/Pipeline/open-path.firmament")]
+ [InlineData("fixtures/Canonical/Features/Sweep/circular-planar-path-sweep.firmament")]
+ public void BarePathPreservesSweepGeometryAcrossManualAndPipelineForms(string fixture)
+ {
+ var legacy = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(fixture));
+ var canonical = legacy.Replace("Concept Path", "Path", StringComparison.Ordinal);
+ var before = FirmamentBuildAndExport.CompileSource(legacy, null);
+ var after = FirmamentBuildAndExport.CompileSource(canonical, null);
+ Assert.True(before.IsSuccess, string.Join("\n", before.Diagnostics.Select(d => d.Message)));
+ Assert.True(after.IsSuccess, string.Join("\n", after.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(before.Value.StepText, after.Value.StepText);
+ }
+
+ [Theory]
+ [InlineData("fixtures/Canonical/Features/Sweep/circular-planar-path-sweep.firmament")]
+ [InlineData("fixtures/Canonical/WireForm/axis-coil.firmament")]
+ public void UnqualifiedScalarConsumersCannotSilentlyDiscardTheDeclaration(string fixture)
+ {
+ var sweep = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(fixture))
+ .Replace("Units: mm", "Units: mm\n Static unusedRequirement: Length = 8mm tol 0.1mm", StringComparison.Ordinal);
+ var result = FirmamentBuildAndExport.CompileSource(sweep, null);
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics, d => d.Message.Contains("static-scalar-consumer-unsupported", StringComparison.Ordinal));
+ var nested = "Model Nested { units: mm Struct Part { Static x: Length = 1mm tol 0.1mm Box Body { size: [40mm,30mm,8mm] } } }";
+ Assert.False(FirmamentBuildAndExport.CompileSource(nested, null).IsSuccess);
+ }
+
+ [Fact]
+ public void LanguageServiceUsesTheOriginalToleranceSpanAndCompilerMessage()
+ {
+ var source = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/TypedTolerances/unit-mismatch.firmament"));
+ var result = FirmamentLanguageAnalysisService.Analyze(source, "unit-mismatch.firmament", "1");
+ var error = Assert.Single(result.Diagnostics, d => d.Code == FirmamentV2Parser.ToleranceUnitMismatch);
+ Assert.Equal("tol 0.1deg", source.Substring(error.Start, error.Length));
+ Assert.Contains("mm", error.Message);
+ Assert.Equal("error", error.Severity);
+ }
+
+ [Fact]
+ public void InferredDimensionalValuesAndAliasesRetainTheTypedRequirement()
+ {
+ var source = Source.Replace("Static drillDiameter: Length =", "Static drillDiameter =", StringComparison.Ordinal)
+ .Replace("Static inspectionDiameter: Length =", "Static inspectionDiameter =", StringComparison.Ordinal);
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.Equal(FirmamentV2PrimitiveType.Length, parsed.Document!.BoundLets!.Single(v => v.Name == "inspectionDiameter").Type);
+ var compiled = FirmamentBuildAndExport.CompileSource(source, null);
+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics.Select(d => d.Message)));
+ var reference = FirmamentBuildAndExport.CompileSource(Source, null);
+ Assert.True(reference.IsSuccess);
+ Assert.Equal(reference.Value.StepText, compiled.Value.StepText);
+ }
+
+ [Theory]
+ [InlineData("typo: 1mm", "canonical-field-unknown")]
+ [InlineData("diameter: 2mm", "field-duplicate")]
+ public void SweepFieldAdmissionIsClosedByItsActualAstOwner(string extra, string expected)
+ {
+ var source = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Features/Sweep/circular-planar-path-sweep.firmament"))
+ .Replace("Diameter: 1.2mm", "Diameter: 1.2mm\n" + extra, StringComparison.Ordinal);
+ var compiled = FirmamentBuildAndExport.CompileSource(source, null);
+ Assert.False(compiled.IsSuccess);
+ Assert.Contains(compiled.Diagnostics, d => d.Message.Contains(expected, StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void CommentTriviaPreservesToleranceLocationsAndDoesNotTruncateStringValues()
+ {
+ var source = "// Original source coordinates matter.\n/* block comment */\n" +
+ File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/TypedTolerances/unit-mismatch.firmament"));
+ var parsed = FirmamentV2Parser.Parse(source);
+ var diagnostic = Assert.Single(parsed.SyntaxDiagnostics, d => d.Code == FirmamentV2Parser.ToleranceUnitMismatch);
+ Assert.Equal("tol 0.1deg", source.Substring(diagnostic.SourceSpan!.Start, diagnostic.SourceSpan.Length));
+ const string quoted = "Model Quoted { units: mm Static link: String = \"https://example.test/design\"\n Box Body { size: [40mm,30mm,8mm] } }";
+ var bound = FirmamentV2Parser.Parse(quoted);
+ Assert.True(bound.IsSuccess, string.Join("\n", bound.Diagnostics));
+ Assert.Equal("https://example.test/design", Assert.Single(bound.Document!.BoundLets!).Value.Value);
+ Assert.False(FirmamentBuildAndExport.CompileSource("Model Bad { units: mm Box Body { size: [40mm,30mm,8mm] } } /* unclosed", null).IsSuccess);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void EveryPmiSpellingRejectsDatumRelationshipsTheExporterCannotPreserve(bool typed)
+ {
+ var source = typed ? Source.Replace("dimension: inspectionDiameter", "dimension: inspectionDiameter datum: A", StringComparison.Ordinal)
+ : File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/TypedTolerances/legacy-datum-reference.firmament"));
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var report = FirmamentV2ValidationReportBuilder.Build(parsed, "datum-reference.firmament");
+ Assert.Contains(report.Pmi, p => p.Kind == "diameter" && p.ExportSupport == "deferred" && p.Reason!.Contains("datum-reference-export-unsupported", StringComparison.Ordinal));
+ Assert.Equal("invalid", FirmamentBuildAdmissionValidation.Admit(report, source).Status);
+ var compiled = FirmamentBuildAndExport.CompileSource(source, null);
+ Assert.False(compiled.IsSuccess);
+ Assert.Contains(compiled.Diagnostics, d => d.Message.Contains("firmament-v2-pmi-datum-reference-export-unsupported", StringComparison.Ordinal));
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/X1aSemanticClosureWitnessTests.cs b/Aetheris.Kernel.Firmament.Tests/X1aSemanticClosureWitnessTests.cs
index 996233ed..c1083ec1 100644
--- a/Aetheris.Kernel.Firmament.Tests/X1aSemanticClosureWitnessTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/X1aSemanticClosureWitnessTests.cs
@@ -124,7 +124,6 @@ public sealed class X1aSemanticClosureWitnessTests
Target: InnerHole
Value: 6mm
Tolerance: PlusMinus(0.05mm, 0.02mm)
- DatumRefs: [A]
}
}
}
@@ -142,6 +141,10 @@ public sealed class X1aSemanticClosureWitnessTests
Assert.True(inspection.Success, string.Join(Environment.NewLine, inspection.Diagnostics));
Assert.Equal(1, inspection.DatumCount);
Assert.Equal(1, inspection.DimensionCount);
+ var unsupported = FirmamentBuildAndExport.CompileSource(source.Replace(
+ "Tolerance: PlusMinus(0.05mm, 0.02mm)", "Tolerance: PlusMinus(0.05mm, 0.02mm) DatumRefs: [A]", StringComparison.Ordinal));
+ Assert.False(unsupported.IsSuccess);
+ Assert.Contains(unsupported.Diagnostics, d => d.Message.Contains("pmi-datum-reference-export-unsupported", StringComparison.Ordinal));
}
private static string Fixture(string relative) => Path.GetFullPath(Path.Combine(
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 66271c9e..1351863a 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -2650,17 +2650,23 @@ public static class FirmamentBuildAndExport
private static KernelResult<bool> ValidateV2PmiExportSupport(FirmamentV2Document document)
{
- var unsupported = document.PmiBlock?.Records.Where(r => r.Kind is not (FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter)).ToArray() ?? [];
- if (unsupported.Length == 0)
- {
- return KernelResult<bool>.Success(true);
- }
+ var bound = (document.BoundPmi?.Datums ?? []).Concat(document.BoundPmi?.Dimensions ?? [])
+ .Concat(document.BoundPmi?.Controls ?? []).ToDictionary(r => r.Name, StringComparer.Ordinal);
+ var unsupported = (document.PmiBlock?.Records ?? []).Select(r => V2PmiExportRejection(r.Kind, r.Name, bound.GetValueOrDefault(r.Name)))
+ .OfType<KernelDiagnostic>().ToArray();
+ return unsupported.Length == 0 ? KernelResult<bool>.Success(true) : KernelResult<bool>.Failure(unsupported);
+ }
- return KernelResult<bool>.Failure(unsupported.Select(r => new Kernel.Core.Diagnostics.KernelDiagnostic(
- Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
- Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
- $"firmament-v2-pmi-export-deferred: AP242 export for PMI record '{r.Name}' ({r.Kind.ToString().ToLowerInvariant()}) is deferred in V2 Phase 1 P2; supported export records are datum and diameter.",
- "FirmamentV2.PmiExport")).ToArray());
+ // The validation report and the actual exporter consult this same admission
+ // owner. A supported record kind does not imply every requested field exports.
+ internal static KernelDiagnostic? V2PmiExportRejection(FirmamentV2PmiKind kind, string name, FirmamentV2BoundPmiRecord? bound)
+ {
+ var message = kind is not (FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter)
+ ? $"firmament-v2-pmi-export-deferred: AP242 export for PMI record '{name}' ({kind.ToString().ToLowerInvariant()}) is deferred; supported export records are datum and diameter."
+ : kind == FirmamentV2PmiKind.HoleDiameter && bound?.DatumRefs.Count > 0
+ ? $"firmament-v2-pmi-datum-reference-export-unsupported: HoleDiameter '{name}' requests datum references that native size export cannot preserve. Export Datum separately; datum-referenced geometric controls require a qualified PMI capability."
+ : null;
+ return message is null ? null : new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, "FirmamentV2.PmiExport");
}
private static IReadOnlyList<Step242SemanticPmi> BuildV2SemanticPmi(
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs
index 2efa4f0d..0faec9e6 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs
@@ -22,7 +22,8 @@ public enum FirmamentV2CanonicalSymbolKind
Hole,
Slot,
Selection,
- Body
+ Body,
+ StaticValue
}
public sealed record FirmamentV2CanonicalSymbol(
@@ -98,6 +99,7 @@ internal static class FirmamentV2CanonicalSymbolBinder
foreach (var require in staticAuthoring.Requires) Add(require.Name, FirmamentV2CanonicalSymbolKind.Require, require.SourceSpan);
}
+ foreach (var value in document.Lets ?? []) Add(value.Name, FirmamentV2CanonicalSymbolKind.StaticValue, value.SourceSpan);
foreach (var profile in document.Profiles ?? []) Add(profile.Name, FirmamentV2CanonicalSymbolKind.Profile, profile.SourceSpan);
foreach (var polygon in document.Polygons ?? []) Add(polygon.Name, FirmamentV2CanonicalSymbolKind.Polygon2, polygon.SourceSpan);
foreach (var boundary in (document.Boundaries ?? []).Where(x => x.ShapeType != "Polygon2")) Add(boundary.Name, FirmamentV2CanonicalSymbolKind.ClosedBoundary2, boundary.SourceSpan);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs
index 1ab50ceb..c39f85ca 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs
@@ -13,7 +13,7 @@ public static class FirmamentBuildAdmissionValidation
var compilation = FirmamentBuildAndExport.CompileSource(source, sourceDirectory);
var diagnostics = report.Diagnostics.Concat(compilation.Diagnostics.Select(diagnostic =>
Present(diagnostic, report.Source, source))).Distinct().ToArray();
- var fatal = diagnostics.Count(diagnostic => diagnostic.Severity == "fatal");
+ var fatal = diagnostics.Count(diagnostic => diagnostic.Severity is "fatal" or "error");
return report with
{
Status = !compilation.IsSuccess || fatal > 0 ? "invalid" : report.Status,
@@ -34,10 +34,10 @@ public static class FirmamentBuildAdmissionValidation
? diagnostic.Message[..separator]
: diagnostic.Message.All(character => char.IsLetterOrDigit(character) || character is '-' or '_' or '.')
? diagnostic.Message : diagnostic.Code.ToString();
- if (source is not null && (code.StartsWith("firmament-schema-", StringComparison.Ordinal) || code.StartsWith("firmament-v2-directive-", StringComparison.Ordinal)))
+ if (source is not null)
{
var original = FirmamentV2Parser.Parse(source).SyntaxDiagnostics.FirstOrDefault(d => d.Code == code || d.Code.StartsWith(code + ":", StringComparison.Ordinal));
- if (original is not null) return original with { SourceFile = sourceFile };
+ if (original is not null) return Locate(original, source, sourceFile);
}
if (source is not null && code.StartsWith("firmament-syntax-", StringComparison.Ordinal))
{
@@ -61,7 +61,14 @@ public static class FirmamentBuildAdmissionValidation
public static FirmamentV2ValidationDiagnostic Locate(
FirmamentV2ValidationDiagnostic diagnostic, string? source, string sourceFile)
{
- if (diagnostic.SourceSpan is not null) return diagnostic with { SourceFile = sourceFile };
+ if (diagnostic.SourceSpan is { } span)
+ {
+ if (source is null) return diagnostic with { SourceFile = sourceFile };
+ var sourceLine = 1; var sourceColumn = 1;
+ for (var index = 0; index < Math.Min(span.Start, source.Length); index++)
+ if (source[index] == '\n') { sourceLine++; sourceColumn = 1; } else sourceColumn++;
+ return diagnostic with { SourceFile = sourceFile, Line = sourceLine, Column = sourceColumn };
+ }
if (source is null) return diagnostic with { SourceFile = sourceFile, LocationNote = "Original source is unavailable." };
var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(token => token.Shape != "comment").ToArray();
// Only these parser-owned diagnostics identify a specific original token.
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
index 14044314..506ac454 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
@@ -20,8 +20,8 @@ public sealed record FirmamentLanguageFormat(string Document, string Revision, s
public static class FirmamentLanguageAnalysisService
{
internal sealed record Lexeme(int Start, int Length, string Text, string Shape, string? Error = null);
- private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "With", "with", "Expose", "Include", "Subassembly", "Assembly", "Part", "Template", "Function", "Record", "Pattern", "Over", "Using", "As", "as", "Output"];
- private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Function", "Pattern", "Section", "SectionChain", "FrameTransform", "Points"];
+ private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "With", "with", "Expose", "Include", "Subassembly", "Assembly", "Part", "Template", "Function", "Record", "Pattern", "Over", "Using", "As", "as", "Output", "tol"];
+ private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Function", "Pattern", "Section", "SectionChain", "FrameTransform", "Points", "Path", "Semantic", "Enum"];
private static readonly HashSet<string> Types = ["Length", "Angle", "Float", "Int", "Bool", "Box3", "Plane", "Point2", "Point3"];
private static readonly HashSet<string> Choices = FirmamentSemanticSchemas.All
.SelectMany(construct => construct.Fields).SelectMany(field => field.Choices).ToHashSet(StringComparer.Ordinal);
@@ -67,11 +67,11 @@ public static class FirmamentLanguageAnalysisService
if (lexemes.Any(t => t.Shape == "identifier" && t.Text is "Template" or "Subassembly" or "Appearance" or "Material"))
return new(document, revision, tokens, [new("information", "firmament-language-project-context-required", "Declaration modules are validated in their consuming project.", 0, 0)]);
var parse = FirmamentV2Parser.Parse(source);
- var failures = parse.Diagnostics.Where(item => FirmamentV2Parser.IsFatalDiagnosticCode(item) ||
+ var failures = parse.Diagnostics.Where(item => FirmamentV2Parser.IsFatalDiagnosticCode(item) || parse.SyntaxDiagnostics.Any(d => d.Code == item && d.Severity == "warning") ||
item == "firmament-v2-parse-failed").Distinct(StringComparer.Ordinal).ToArray();
if (failures.Length > 1) failures = failures.Where(item => item != "firmament-v2-parse-failed").ToArray();
var diagnostics = failures.Select(item => parse.SyntaxDiagnostics.FirstOrDefault(d => d.Code == item) is { SourceSpan: { } span } located
- ? new FirmamentLanguageDiagnostic("error", located.Code, located.Message, span.Start, span.Length)
+ ? new FirmamentLanguageDiagnostic(located.Severity == "warning" ? "warning" : "error", located.Code, located.Message, span.Start, span.Length)
: LocateDiagnostic(source, lexemes, item)).ToArray();
return new(document, revision, tokens, diagnostics);
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 8fdf5294..491fed24 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -321,6 +321,7 @@ public sealed record FirmamentV2ParseResult(
/// <summary>Debug metadata, assigned where the existing parser route is selected.</summary>
public string? ParserRoute { get; init; }
public IReadOnlyList<FirmamentV2ValidationDiagnostic> SyntaxDiagnostics { get; init; } = [];
+ internal string? DiagnosticSource { get; init; }
internal string? OriginalSource { get; init; }
// Bound engineering inputs are retained for execution; a successful AST admission
// cannot be replaced by a different whole-document parser in the build path.
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
index 2f81735e..61628077 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
@@ -29,25 +29,37 @@ public static partial class FirmamentV2Parser
if (model.Clauses.Count > 0 || model.Type.Arguments.Count > 0)
return CanonicalFailure(diagnostics, "firmament-v2-mechanical-root-header-unsupported: Use the admitted Model/Struct header and declare placement in its owning construct.");
if (model.Annotation is not null)
+ {
+ if (syntax.Statements.Concat(model.Body.Statements).OfType<DeclarationSyntax>().Any(d => d.Type.Name.Text == "Static"))
+ return CanonicalFailure(diagnostics, "firmament-v2-static-scalar-consumer-unsupported: Concept-valued material construction requires its existing typed Template inputs.");
return ParseConceptModelingDocument(source, diagnostics, templateInstantiations);
- BindMechanicalScope(syntax.Statements.Where(s => !ReferenceEquals(s, model)).ToArray(), diagnostics);
- BindMechanicalScope(model.Body.Statements, diagnostics);
- if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
+ }
+ var outerStatements = syntax.Statements.Where(s => !ReferenceEquals(s, model)).ToArray();
+ var staticValues = BindStaticValues(syntax, model, source, diagnostics);
+ model = staticValues.Model;
+ BindMechanicalScope(outerStatements.Where(s => s is not DeclarationSyntax { Type.Name.Text: "Static" }).ToArray(), diagnostics);
+ BindMechanicalScope(model.Body!.Statements.Where(s => s is not DeclarationSyntax { Type.Name.Text: "Static" }).ToArray(), diagnostics);
+ if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed)
+ with { SyntaxDiagnostics = staticValues.Diagnostics };
var declarations = MechanicalDeclarations(model.Body.Statements).ToArray();
var primitives = declarations.Where(IsPrimitiveDeclaration).ToArray();
var constructions = declarations.Where(d => d.Type.Name.Text is "Compose" or "Extrude").ToArray();
var materialConstruction = constructions.Length > 0;
- if (constructions.Length > 1 && constructions.All(d => d.Type.Name.Text == "Extrude") && primitives.Length == 0)
- return BindMechanicalExtrusionStack(model, constructions, source, diagnostics);
- if (constructions.Length > 1 || materialConstruction && primitives.Length > 0)
- return CanonicalFailure(diagnostics, "firmament-v2-mechanical-material-owners-unsupported: Use one material body per mechanical document; use Assembly for separate parts.");
// Concept-valued stock retains its existing semantic resolver. Its actual
// declarations do not change the grammar of neighbouring nodes.
var semanticStock = declarations.Any(d => d.Type.Name.Text == "Modify" && d.Body?.Statements.OfType<DeclarationSyntax>().Any(f => f.Type.Name.Text == "Pattern") == true)
|| declarations.Any(d => d.Type.Name.Text == "Struct" && d.Annotation is not null)
|| declarations.Where(d => d.Type.Name.Text == "Modify").SelectMany(d => d.Body?.Statements.OfType<DeclarationSyntax>() ?? [])
.Any(d => d.Type.Name.Text == "Hole" && d.Body?.Statements.OfType<FieldSyntax>().Any(f => f.Name.Text == "From" || f.Name.Text == "On" && FirmamentSyntaxValues.Reference(f.Value) is not ("+X" or "-X" or "+Y" or "-Y" or "+Z" or "-Z")) == true);
- if (materialConstruction || semanticStock || primitives.Any(d => d.Body?.Statements.OfType<FieldSyntax>().Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Bounds")) == true))
+ var constructionConsumer = materialConstruction || semanticStock || primitives.Any(d => d.Body?.Statements.OfType<FieldSyntax>().Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Bounds")) == true);
+ if (staticValues.Values.Count > 0 && constructionConsumer)
+ return CanonicalFailure(diagnostics,
+ "firmament-v2-static-scalar-consumer-unsupported: Model Static scalars currently bind direct primitive and Modify fields; parameterize construction recipes with Template instead.");
+ if (constructions.Length > 1 && constructions.All(d => d.Type.Name.Text == "Extrude") && primitives.Length == 0)
+ return BindMechanicalExtrusionStack(model, constructions, source, diagnostics);
+ if (constructions.Length > 1 || materialConstruction && primitives.Length > 0)
+ return CanonicalFailure(diagnostics, "firmament-v2-mechanical-material-owners-unsupported: Use one material body per mechanical document; use Assembly for separate parts.");
+ if (constructionConsumer)
return BindMechanicalConstruction(source, model, diagnostics, templateInstantiations);
var units = model.Body.Statements.OfType<FieldSyntax>().Where(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Units")).ToArray();
@@ -57,6 +69,11 @@ public static partial class FirmamentV2Parser
_ = ProfileAuthoringParser.ResolveNamedProfile(source, profile.Name!.Text, out var profileDiagnostics);
diagnostics.AddRange(profileDiagnostics);
}
+ foreach (var path in declarations.Where(d => d.Type.Name.Text == "Path" && d.Name is not null))
+ {
+ _ = ProfileAuthoringParser.ResolveConceptPath(source, path.Name!.Text, out var pathDiagnostics);
+ diagnostics.AddRange(pathDiagnostics);
+ }
var solids = new Dictionary<string, FirmamentV2SolidBinding>(StringComparer.Ordinal);
foreach (var declaration in primitives)
{
@@ -115,11 +132,16 @@ public static partial class FirmamentV2Parser
var replacements = ParseCanonicalReplacements(bodyText, solids, recognized, diagnostics);
var selections = ParseCanonicalSelections(bodyText, model.Body.Span.Start + 1, diagnostics);
ValidateCanonicalSelectionSources(bodyText, selections, [], diagnostics);
- var (pmi, pmiBlock, boundPmi) = ParsePmi(source, solids, modifies, recognized, [], [], diagnostics);
- if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
- return FirmamentV2ParseResult.Success(new(model.Name.Text, "mm", solids.Values.ToArray(), modifies,
- Pmi: pmi, RecognizedRegions: recognized, Replacements: replacements, PmiBlock: pmiBlock, BoundPmi: boundPmi, Selections: selections),
- diagnostics.Append("firmament-v2-unified-canonical-parsed").Append("firmament-v2-parse-succeeded").Distinct(StringComparer.Ordinal).Order().ToArray());
+ var (pmi, pmiBlock, boundPmi) = ParsePmi(source, solids, modifies, recognized, staticValues.Values, [], diagnostics);
+ var pmiDiagnostics = ValidateStaticPmi(pmiBlock, boundPmi, modifies, staticValues.Values, diagnostics);
+ var locatedDiagnostics = staticValues.Diagnostics.Concat(pmiDiagnostics).ToArray();
+ if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed)
+ with { SyntaxDiagnostics = locatedDiagnostics };
+ return FirmamentV2ParseResult.Success(new(model.Name!.Text, "mm", solids.Values.ToArray(), modifies,
+ Pmi: pmi, RecognizedRegions: recognized, Replacements: replacements, PmiBlock: pmiBlock, BoundPmi: boundPmi, Selections: selections,
+ Lets: staticValues.Declarations, BoundLets: staticValues.Values),
+ diagnostics.Append("firmament-v2-unified-canonical-parsed").Append("firmament-v2-parse-succeeded").Distinct(StringComparer.Ordinal).Order().ToArray())
+ with { SyntaxDiagnostics = locatedDiagnostics };
}
// Multiple explicit extrusions are material requests, not alternative parser
@@ -354,7 +376,7 @@ public static partial class FirmamentV2Parser
Bind(syntax.Statements);
}
- private static void BindMechanicalScope(IReadOnlyList<StatementSyntax> statements, List<string> diagnostics)
+ internal static void BindMechanicalScope(IReadOnlyList<StatementSyntax> statements, List<string> diagnostics)
{
foreach (var statement in statements)
{
@@ -377,13 +399,15 @@ public static partial class FirmamentV2Parser
if (declaration.Modifiers.Any(m => m.Name.Text == "Assert")) continue;
switch (declaration.Type.Name.Text)
{
+ case "Static":
+ diagnostics.Add("firmament-v2-static-scalar-consumer-unsupported: This scope does not bind scalar Static values; use the owning domain's typed Template inputs."); break;
case "Struct" when declaration.Annotation is not null: break;
case "Struct" when !declaration.Modifiers.Any(m => m.Name.Text == "Concept"):
BindMechanicalScope(declaration.Body?.Statements ?? [], diagnostics); break;
case "Box" or "Cylinder" or "Cone" or "Sphere" or "Torus" or "RoundedBox" or "Frustum" or "StandardPart" or "ExactCoaxialPart":
case "Plane" or "Axis" or "Axis2" or "Point2" or "Line2" or "CubicBezier2" or "Rect2" or "Square2" or "Triangle2" or "Polygon2" or "RegularPolygon2" or "Circle2" or "Ellipse2" or "Ellipse2Guide" or "Slot2" or "RoundedRect2" or "SmoothRoundedRect2" or "Path":
case "Plateau" or "Concept" or "Struct" or "Profile" or "Span" or "Compose" or "Boss" or "Pocket" or "AddOffset" or "RemoveOffset" or "EdgeFinish" or "Extrude":
- case "Enum" or "Expose" or "Record" or "Static" or "Template" or "template" or "Feature" or "ProfileDelta" or "Selection" or "InlineStep" or "Recognize" or "Replace" or "Pmi" or "Modify" or "Match" or "Require" or "Assert" or "Thread":
+ case "Enum" or "Expose" or "Record" or "Template" or "template" or "Feature" or "ProfileDelta" or "Selection" or "InlineStep" or "Recognize" or "Replace" or "Pmi" or "Modify" or "Match" or "Require" or "Assert" or "Thread":
break;
case "Solid": diagnostics.Add(CanonicalConstructNotYetSupported + ":Solid"); break;
default: diagnostics.Add(CanonicalDeclarationUnrecognized); diagnostics.Add($"{CanonicalDeclarationUnknown}:{declaration.Type.Name.Text}"); break;
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index eb5097cb..e3a42caa 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -362,7 +362,10 @@ public static partial class FirmamentV2Parser
if (result.SyntaxDiagnostics.Count > 0)
{
var original = FirmamentSyntaxParser.Parse(originalSource);
+ var unchanged = result.DiagnosticSource is not null && string.Equals(result.DiagnosticSource,
+ MaskCommentTrivia(FirmamentSourceSpelling.Normalize(FirmamentFrontendSchemas.Select(originalSource).Source)), StringComparison.Ordinal);
result = result with { SyntaxDiagnostics = original.Diagnostics.Count > 0 ? original.Diagnostics
+ : unchanged ? result.SyntaxDiagnostics
: result.SyntaxDiagnostics.Select(d => d with { SourceSpan = null, Line = null, Column = null,
LocationNote = "The error occurs after expansion; original-source provenance is unavailable." }).ToArray() };
}
@@ -391,7 +394,7 @@ public static partial class FirmamentV2Parser
sourceText = FirmamentSourceSpelling.Normalize(sourceText);
sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);
var diagnostics = new List<string> { "firmament-v2-parser-invoked" };
- var source = StripLineComments(sourceText);
+ var source = MaskCommentTrivia(sourceText);
var authoredSyntax = FirmamentSyntaxParser.Parse(source);
if (MechanicalDeclarations(authoredSyntax.Document.Statements).Any(d => d.Type.Name.Text is "SectionChain" or "Loft"
&& !d.Modifiers.Any(m => m.Name.Text == "Template")))
@@ -544,7 +547,8 @@ public static partial class FirmamentV2Parser
if (!syntax.IsSuccess)
return FirmamentV2ParseResult.Failure(diagnostics.Concat(syntax.Diagnostics.Select(d => d.Code)).ToArray(), FirmamentV2ParseDisposition.RecognizedInvalid)
with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true, SyntaxDiagnostics = syntax.Diagnostics };
- var parsed = Recognized(BindMechanicalModel(syntax.Document, modelSyntax, source, diagnostics, sourceDirectory, templateExpansion.Instantiations));
+ var parsed = Recognized(BindMechanicalModel(syntax.Document, modelSyntax, source, diagnostics, sourceDirectory, templateExpansion.Instantiations))
+ with { DiagnosticSource = source };
if (parsed.Document is null) return parsed with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true };
if (domainDeclarations.Any(d => d.Type.Name.Text == "Plateau"))
{
@@ -716,15 +720,15 @@ public static partial class FirmamentV2Parser
{
type = text switch
{
- "int" => FirmamentV2PrimitiveType.Int,
- "float" => FirmamentV2PrimitiveType.Float,
- "length" => FirmamentV2PrimitiveType.Length,
- "angle" => FirmamentV2PrimitiveType.Angle,
- "string" => FirmamentV2PrimitiveType.String,
- "bool" => FirmamentV2PrimitiveType.Bool,
+ "int" or "Int" => FirmamentV2PrimitiveType.Int,
+ "float" or "Float" => FirmamentV2PrimitiveType.Float,
+ "length" or "Length" => FirmamentV2PrimitiveType.Length,
+ "angle" or "Angle" => FirmamentV2PrimitiveType.Angle,
+ "string" or "String" => FirmamentV2PrimitiveType.String,
+ "bool" or "Bool" => FirmamentV2PrimitiveType.Bool,
_ => default
};
- return text is "int" or "float" or "length" or "angle" or "string" or "bool";
+ return text is "int" or "float" or "length" or "angle" or "string" or "bool" or "Int" or "Float" or "Length" or "Angle" or "String" or "Bool";
}
private static FirmamentV2ValueExpression? ParseLetValueExpression(FirmamentV2PrimitiveType type, string literal, List<string> diagnostics)
@@ -944,7 +948,7 @@ public static partial class FirmamentV2Parser
return new(type.Value, val, new HashSet<string>(l.Dependencies.Concat(r.Dependencies), StringComparer.Ordinal), new(0, b.Source.Length), null, l.AliasTolerance is not null || r.AliasTolerance is not null || l.UsesTolerancedValueInArithmetic || r.UsesTolerancedValueInArithmetic);
}
private static bool IsZero(FirmamentV2LiteralValue v) => v.NumericValue is double d && d == 0d;
- private static FirmamentV2PrimitiveType? ResultType(FirmamentV2PrimitiveType a, string op, FirmamentV2PrimitiveType b) => op switch
+ internal static FirmamentV2PrimitiveType? ResultType(FirmamentV2PrimitiveType a, string op, FirmamentV2PrimitiveType b) => op switch
{
"+" or "-" when a == b && a is FirmamentV2PrimitiveType.Int or FirmamentV2PrimitiveType.Float or FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle => a,
"+" or "-" when IsNumeric(a) && IsNumeric(b) => FirmamentV2PrimitiveType.Float,
@@ -2491,6 +2495,7 @@ public static partial class FirmamentV2Parser
else if (Field(r,"diameter") is string legacy && TryParsePmiLength(NormalizePmiLengthLiteral(legacy), diagnostics, out var legacyLit)) dim=legacyLit;
if (Field(r,"tolerance") is string t && TryParseToleranceLiteral(NormalizePmiLengthLiteral(t), diagnostics, out var tol)) dimTol=tol;
if (dim is null) { diagnostics.Add(PmiDiameterInvalid); return false; }
+ if (r.Kind == FirmamentV2PmiKind.HoleDiameter && dim.NumericValue is <= 0) { diagnostics.Add(PmiDiameterInvalid); return false; }
if (dimTol is null && Field(r,"diameter") is null && Field(r,"value") is null) { diagnostics.Add(PmiDimensionMissingTolerance); return false; }
}
if (r.Kind is FirmamentV2PmiKind.Flatness or FirmamentV2PmiKind.Parallel or FirmamentV2PmiKind.Perpendicular or FirmamentV2PmiKind.Coplanar)
@@ -2499,7 +2504,7 @@ public static partial class FirmamentV2Parser
{ var d=Field(r,"datum"); if (d is null || !datums.Contains(d)) diagnostics.Add(PmiUnknownDatum); else datumRefs.Add(d); }
if (r.Kind == FirmamentV2PmiKind.HoleDiameter && Field(r,"datum") is string datum)
{ if (!datums.Contains(datum)) diagnostics.Add(PmiUnknownDatum); else datumRefs.Add(datum); }
- bound=new(r.Kind,r.Name,targets,dim,dimTol,ctlTol,datumRefs,r.SourceSpan, HoleWallTarget: wallTarget);
+ bound=new(r.Kind,r.Name,targets,dim,dimTol,ctlTol,datumRefs,r.SourceSpan, ProjectionSource: Field(r,"dimension"), HoleWallTarget: wallTarget);
return !diagnostics.Any(x => (x.StartsWith("firmament-v2-pmi-", StringComparison.Ordinal) && x is not PmiUnsupported)
|| x.StartsWith("firmament-v2-hole-wall-", StringComparison.Ordinal));
}
@@ -2598,9 +2603,15 @@ public static partial class FirmamentV2Parser
return expanded is not null;
}
- private static string StripLineComments(string sourceText) => string.Join('\n', sourceText.Split('\n').Select(line =>
+ private static string MaskCommentTrivia(string sourceText)
{
- var index = line.IndexOf("//", StringComparison.Ordinal);
- return index >= 0 ? line[..index] : line;
- }));
+ // Legacy semantic readers still need trivia erased. Use the shared lexer,
+ // preserving offsets and quoted // text; do not erase malformed tokens.
+ var text = sourceText.ToCharArray();
+ foreach (var comment in FirmamentLanguageAnalysisService.Lex(sourceText, lossless: true)
+ .Where(t => t.Shape == "comment" && t.Error is null))
+ for (var i = comment.Start; i < comment.Start + comment.Length; i++)
+ if (text[i] is not ('\r' or '\n')) text[i] = ' ';
+ return new(text);
+ }
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs
new file mode 100644
index 00000000..062f9f9f
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs
@@ -0,0 +1,230 @@
+using System.Globalization;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+public static partial class FirmamentV2Parser
+{
+ private sealed record StaticValueBinding(DeclarationSyntax Model,
+ IReadOnlyList<FirmamentV2LetDeclaration> Declarations, IReadOnlyList<FirmamentV2BoundLet> Values,
+ IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics);
+
+ // Static scalars share the existing typed dependency binder and tolerance IR.
+ // Only syntax is projected here; there is no text substitution or second evaluator.
+ private static StaticValueBinding BindStaticValues(DocumentSyntax syntax, DeclarationSyntax model, string source,
+ List<string> diagnostics)
+ {
+ var declarations = new List<FirmamentV2LetDeclaration>();
+ var located = new List<FirmamentV2ValidationDiagnostic>();
+ var scope = syntax.Statements.Where(s => !ReferenceEquals(s, model)).Concat(model.Body!.Statements).ToArray();
+ var names = scope.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text != "Static")
+ .Select(d => d.Name?.Text).OfType<string>().ToHashSet(StringComparer.Ordinal);
+ var statics = scope.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Static").ToArray();
+ void Error(string code, string message, FirmamentV2SourceSpan span, string? name = null)
+ {
+ diagnostics.Add(code);
+ located.Add(new(code, "error", message, Target: name) { SourceFile = syntax.SourceFile, SourceSpan = span });
+ }
+ foreach (var nested in MechanicalDeclarations(model.Body!.Statements).Where(d => d.Type.Name.Text == "Static" && !statics.Contains(d)))
+ Error("firmament-v2-static-scalar-scope-unsupported", "Declare scalar Static values directly in the Model or its module; nested construction scopes do not introduce scalar environments.", nested.Span, nested.Name?.Text);
+ FirmamentV2PrimitiveType? InferType(ExpressionSyntax? e, HashSet<string> visiting) => e switch
+ {
+ ToleranceSyntax t => InferType(t.Nominal, visiting),
+ QuantitySyntax { Unit.Text: "mm" } => FirmamentV2PrimitiveType.Length,
+ QuantitySyntax { Unit.Text: "deg" } => FirmamentV2PrimitiveType.Angle,
+ LiteralSyntax { Kind: LiteralKind.Boolean } => FirmamentV2PrimitiveType.Bool,
+ LiteralSyntax { Kind: LiteralKind.String } => FirmamentV2PrimitiveType.String,
+ LiteralSyntax { Kind: LiteralKind.Number } n => n.Raw.Contains('.') || n.Raw.Contains('e', StringComparison.OrdinalIgnoreCase) ? FirmamentV2PrimitiveType.Float : FirmamentV2PrimitiveType.Int,
+ UnarySyntax u => InferType(u.Operand, visiting),
+ SequenceSyntax { Kind: SequenceKind.Tuple, Items.Count: 1 } g => InferType(g.Items[0].Value, visiting),
+ ReferenceSyntax r when visiting.Count < 128 && visiting.Add(r.Name.Text) => InferReference(r.Name.Text, visiting),
+ BinarySyntax b when InferType(b.Left, new(visiting, StringComparer.Ordinal)) is { } l
+ && InferType(b.Right, new(visiting, StringComparer.Ordinal)) is { } r => ExpressionBinder.ResultType(l,
+ b.Operator switch { BinaryOperator.Add => "+", BinaryOperator.Subtract => "-", BinaryOperator.Multiply => "*", BinaryOperator.Divide => "/", _ => "" }, r),
+ _ => null
+ };
+ FirmamentV2PrimitiveType? InferReference(string name, HashSet<string> visiting)
+ {
+ var matches = statics.Where(d => d.Name?.Text == name).ToArray();
+ if (matches.Length != 1) return null;
+ var d = matches[0];
+ return d.Annotation is null ? InferType(d.Initializer, visiting)
+ : FirmamentSyntaxValues.Reference(d.Annotation) is { } annotation && TryParseLetType(annotation, out var t) ? t : null;
+ }
+ foreach (var d in statics)
+ {
+ var typeName = FirmamentSyntaxValues.Reference(d.Annotation);
+ var declared = typeName is not null && TryParseLetType(typeName, out var explicitType) ? explicitType
+ : d.Annotation is null ? InferType(d.Initializer, new(StringComparer.Ordinal)) : null;
+ if (d.Name is null || declared is not { } type
+ || d.Initializer is null || d.Body is not null || d.Modifiers.Count > 0 || d.Type.Arguments.Count > 0
+ || d.Parameters.Count > 0 || d.Clauses.Count > 0 || d.ResultType is not null || d.Occurrence)
+ {
+ Error("firmament-v2-static-scalar-declaration-invalid",
+ "Expected Static name: Length, Angle, Int, Float, Bool or String = compile-time expression, or an initializer with an inferable scalar type. Record and Set values use their documented declaration forms.", d.Span, d.Name?.Text);
+ continue;
+ }
+ if (!names.Add(d.Name.Text)) { Error(DuplicateName, $"Duplicate compile-time name '{d.Name.Text}'.", d.Span, d.Name.Text); continue; }
+ var valueSyntax = d.Initializer;
+ FirmamentV2Tolerance? tolerance = null;
+ if (valueSyntax is ToleranceSyntax t)
+ {
+ valueSyntax = t.Nominal;
+ if (type is not (FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle))
+ Error(ToleranceInvalidType, "tol requires a Length or Angle value.", t.ToleranceSpan, d.Name.Text);
+ else
+ {
+ var unit = type == FirmamentV2PrimitiveType.Length ? "mm" : "deg";
+ var asymmetric = t.Plus is UnarySyntax { Operator: UnaryOperator.Positive };
+ if (asymmetric && t.Minus is null)
+ Error(ToleranceMissingMinus, "A +upper tolerance requires -lower; use tol 0.1mm for a symmetric allowance.", t.ToleranceSpan, d.Name.Text);
+ else if (!FirmamentSyntaxValues.TryMeasure(t.Plus, unit, out var plus)
+ || t.Minus is not null && !FirmamentSyntaxValues.TryMeasure(t.Minus, unit, out _))
+ Error(ToleranceUnitMismatch, $"Tolerance must have the value's dimensional unit ({unit}).", t.ToleranceSpan, d.Name.Text);
+ else
+ {
+ var minus = t.Minus is null ? plus : FirmamentSyntaxValues.TryMeasure(t.Minus, unit, out var m) ? m : double.NaN;
+ if (plus < 0 || minus < 0)
+ Error(ToleranceNegativeBilateral, "Tolerance allowances must be finite nonnegative magnitudes; write tol +upper -lower.", t.ToleranceSpan, d.Name.Text);
+ else tolerance = new(asymmetric ? FirmamentV2ToleranceKind.Asymmetric : FirmamentV2ToleranceKind.Bilateral,
+ plus, minus, unit, type, t.ToleranceSpan);
+ }
+ }
+ }
+ if (ValueExpression(valueSyntax, type) is { } expression)
+ declarations.Add(new(d.Name.Text, type, expression, d.Span, tolerance));
+ else Error(ExpressionUnsupported, "Expected a typed literal, scalar reference or dimensional arithmetic; tol belongs at the end of a Static initializer.", valueSyntax.Span, d.Name.Text);
+ }
+
+ var before = diagnostics.Count;
+ var values = BindLets(declarations, [], [], diagnostics);
+ foreach (var value in values.Where(v => v.Value.NumericValue is { } n && !double.IsFinite(n)))
+ Error("firmament-v2-static-scalar-nonfinite", $"Compile-time value '{value.Name}' is not finite.", value.SourceSpan, value.Name);
+ foreach (var value in values.Where(v => v.Type == FirmamentV2PrimitiveType.Int && v.Value.NumericValue is { } n && (n < int.MinValue || n > int.MaxValue)))
+ Error("firmament-v2-static-scalar-out-of-range", $"Compile-time Int '{value.Name}' is outside the supported integer range.", value.SourceSpan, value.Name);
+ var unresolved = diagnostics.Skip(before).Contains(ExpressionUnknownSymbol)
+ ? statics.Where(d => d.Initializer is not null).SelectMany(d => FirmamentSyntaxTraversal.Expressions(d.Initializer!))
+ .OfType<ReferenceSyntax>().Where(r => declarations.All(d => d.Name != r.Name.Text)).ToArray() : [];
+ foreach (var code in diagnostics.Skip(before).Distinct().Where(code => !located.Any(d => d.Code == code)))
+ {
+ // Dependency errors may involve several declarations. Use the enclosing
+ // scope rather than inventing an exact failing token in the graph binder.
+ located.Add(new(code, code == ToleranceDroppedThroughArithmetic ? "warning" : "error", code switch
+ {
+ ToleranceDroppedThroughArithmetic => "Arithmetic computes a nominal value and does not propagate tolerances. Add an explicit tol allowance to the result when it is a requirement.",
+ ExpressionUnknownSymbol when unresolved.Length > 0 => "Unknown compile-time scalar reference: " + string.Join(", ", unresolved.Select(r => r.Name.Text).Distinct(StringComparer.Ordinal)) + ".",
+ ExpressionUnknownSymbol => "A referenced Static definition could not be bound. Resolve its preceding diagnostic.",
+ ExpressionCycle => "Compile-time scalar definitions contain a dependency cycle.",
+ ExpressionDivisionByZero => "Compile-time scalar arithmetic divides by zero.",
+ _ => "Compile-time scalar binding failed: " + code
+ }, Target: model.Name?.Text) { SourceFile = syntax.SourceFile,
+ SourceSpan = code == ExpressionUnknownSymbol && unresolved.Length == 1 ? unresolved[0].Span : model.Span,
+ LocationNote = code == ExpressionUnknownSymbol && unresolved.Length == 1 ? null : "Dependency binding reports the enclosing Model scope." });
+ }
+ var map = values.ToDictionary(v => v.Name, StringComparer.Ordinal);
+ ExpressionSyntax Nominal(ExpressionSyntax e) => e switch
+ {
+ ReferenceSyntax r when map.TryGetValue(r.Name.Text, out var value) => Literal(value, e.Span),
+ BinarySyntax b => b with { Left = Nominal(b.Left), Right = Nominal(b.Right) },
+ UnarySyntax u => u with { Operand = Nominal(u.Operand) },
+ QuantitySyntax q => q with { Value = Nominal(q.Value) },
+ SequenceSyntax s => s with { Items = s.Items.Select(a => a with { Value = Nominal(a.Value) }).ToArray() },
+ CallSyntax c => c with { Arguments = c.Arguments.Select(a => a with { Value = Nominal(a.Value) }).ToArray() },
+ ToleranceSyntax t => RejectInline(t),
+ _ => e
+ };
+ ExpressionSyntax RejectInline(ToleranceSyntax t)
+ {
+ Error(ToleranceUnsupported, "Declare a named Static value with tol, use its nominal value in geometry, then project it with Pmi dimension: name.", t.ToleranceSpan);
+ return t;
+ }
+ StatementSyntax Project(StatementSyntax s) => s switch
+ {
+ // These names belong to their semantic owners, not scalar lookup.
+ DeclarationSyntax { Type.Name.Text: "Static" or "Pmi" or "Concept" or "Feature" or "Template" } => s,
+ DeclarationSyntax d when d.Modifiers.Count == 0 => d with { Body = d.Body is null ? null : d.Body with { Statements = d.Body.Statements.Select(Project).ToArray() } },
+ FieldSyntax f => f with { Value = Nominal(f.Value) },
+ _ => s
+ };
+ var projected = (DeclarationSyntax)Project(model);
+ return new(projected, declarations, values, located);
+
+ FirmamentV2ValueExpression? ValueExpression(ExpressionSyntax e, FirmamentV2PrimitiveType expected)
+ {
+ var text = source.Substring(e.Span.Start, e.Span.Length);
+ if (e is ReferenceSyntax r) return new FirmamentV2IdentifierReferenceExpression(r.Name.Text, text);
+ if (e is SequenceSyntax { Kind: SequenceKind.Tuple, Items.Count: 1 } group) return ValueExpression(group.Items[0].Value, expected);
+ if (e is BinarySyntax b)
+ {
+ var op = b.Operator switch { BinaryOperator.Add => "+", BinaryOperator.Subtract => "-", BinaryOperator.Multiply => "*", BinaryOperator.Divide => "/", _ => null };
+ return op is not null && ValueExpression(b.Left, expected) is { } l && ValueExpression(b.Right, expected) is { } rgt
+ ? new FirmamentV2BinaryExpression(l, op, rgt, text) : null;
+ }
+ var unit = e is QuantitySyntax q ? q.Unit.Text : e is UnarySyntax { Operand: QuantitySyntax uq } ? uq.Unit.Text : "";
+ var inferred = unit switch { "mm" => FirmamentV2PrimitiveType.Length, "deg" => FirmamentV2PrimitiveType.Angle,
+ "" => expected is FirmamentV2PrimitiveType.String or FirmamentV2PrimitiveType.Bool ? expected
+ : text.Contains('.') || text.Contains('e', StringComparison.OrdinalIgnoreCase) ? FirmamentV2PrimitiveType.Float : FirmamentV2PrimitiveType.Int, _ => (FirmamentV2PrimitiveType?)null };
+ if (inferred is null) return null;
+ if (inferred is FirmamentV2PrimitiveType.String or FirmamentV2PrimitiveType.Bool)
+ {
+ if (e is not LiteralSyntax literal || literal.Kind != (inferred == FirmamentV2PrimitiveType.String ? LiteralKind.String : LiteralKind.Boolean)) return null;
+ try
+ {
+ object value = inferred == FirmamentV2PrimitiveType.String
+ ? System.Text.Json.JsonSerializer.Deserialize<string>(literal.Raw)!
+ : bool.Parse(literal.Raw);
+ return new FirmamentV2LiteralExpression(new(inferred.Value, value, Raw: literal.Raw));
+ }
+ catch (System.Text.Json.JsonException) { return null; }
+ }
+ if (!FirmamentSyntaxValues.TryMeasure(e, unit, out var n) || inferred == FirmamentV2PrimitiveType.Int && (n < int.MinValue || n > int.MaxValue || n != Math.Truncate(n))) return null;
+ // Float declarations admit integer-written constants, as legacy let did.
+ if (inferred == FirmamentV2PrimitiveType.Int && expected == FirmamentV2PrimitiveType.Float) inferred = expected;
+ return new FirmamentV2LiteralExpression(new(inferred.Value, inferred == FirmamentV2PrimitiveType.Int ? (object)(int)n : n, n, unit.Length == 0 ? null : unit, text));
+ }
+ }
+
+ private static ExpressionSyntax Literal(FirmamentV2BoundLet value, FirmamentV2SourceSpan span)
+ {
+ ExpressionSyntax literal = new LiteralSyntax(value.Type switch
+ {
+ FirmamentV2PrimitiveType.Bool => LiteralKind.Boolean,
+ FirmamentV2PrimitiveType.String => LiteralKind.String,
+ _ => LiteralKind.Number
+ }, value.Type switch
+ {
+ FirmamentV2PrimitiveType.Bool => (bool)value.Value.Value ? "true" : "false",
+ FirmamentV2PrimitiveType.String => System.Text.Json.JsonSerializer.Serialize(value.Value.Value),
+ _ => value.Value.NumericValue!.Value.ToString("R", CultureInfo.InvariantCulture)
+ }, span);
+ return value.Value.Unit is { } unit ? new QuantitySyntax(literal, new(unit, span), span) : literal;
+ }
+
+ private static IReadOnlyList<FirmamentV2ValidationDiagnostic> ValidateStaticPmi(FirmamentV2PmiBlock? block,
+ FirmamentV2BoundPmiBlock? bound, IReadOnlyList<FirmamentV2ModifyBlock> modifies,
+ IReadOnlyList<FirmamentV2BoundLet> values, List<string> diagnostics)
+ {
+ var result = new List<FirmamentV2ValidationDiagnostic>();
+ foreach (var record in block?.Records ?? [])
+ {
+ if (!record.Fields.TryGetValue("dimension", out var dimension)) continue;
+ var value = values.FirstOrDefault(v => v.Name == dimension.Source);
+ if (value?.Tolerance is null) continue; // Existing PMI type/admission errors remain authoritative.
+ void Error(string code, string message)
+ {
+ diagnostics.Add(code);
+ result.Add(new(code, "error", message, "dimension", record.Name) { SourceSpan = record.SourceSpan, Stage = "Binding" });
+ }
+ if (record.Fields.Keys.Any(k => k is "value" or "diameter" or "tolerance"))
+ Error("firmament-v2-pmi-typed-dimension-override", $"PMI '{record.Name}' projects '{value.Name}'; do not override its nominal value or tolerance. Declare a separate typed requirement instead.");
+ var resolved = bound?.Dimensions.FirstOrDefault(d => d.Name == record.Name);
+ var holeName = resolved?.HoleWallTarget?.HoleName ?? resolved?.Targets.FirstOrDefault();
+ var hole = modifies.SelectMany(m => m.SemanticHoles).FirstOrDefault(h => h.Name == holeName);
+ if (hole is null || value.Value.NumericValue is not { } nominal) continue;
+ var delta = hole.ShaftDiameter - nominal;
+ if (delta > value.Tolerance.Plus + 1e-9 || -delta > value.Tolerance.Minus + 1e-9)
+ Error("firmament-v2-pmi-typed-dimension-unsatisfied", $"Hole '{hole.Name}' has diameter {hole.ShaftDiameter:R}mm, outside '{value.Name}' ({nominal:R}mm +{value.Tolerance.Plus:R}mm -{value.Tolerance.Minus:R}mm).");
+ }
+ return result;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
index f6de891e..fbc358a1 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
@@ -62,10 +62,10 @@ public static class FirmamentV2ValidationReportBuilder
.Distinct()
.ToArray();
- if (!parse.IsSuccess && diagnostics.All(diagnostic => diagnostic.Severity != "fatal"))
+ if (!parse.IsSuccess && diagnostics.All(diagnostic => diagnostic.Severity is not ("fatal" or "error")))
diagnostics = [.. diagnostics, ToParserDiagnostic("firmament-v2-parse-failed")];
- var fatalCount = diagnostics.Count(diagnostic => diagnostic.Severity == "fatal");
+ var fatalCount = diagnostics.Count(diagnostic => diagnostic.Severity is "fatal" or "error");
var warningCount = diagnostics.Count(diagnostic => diagnostic.Severity == "warning");
var document = parse.Document;
var lets = document is null ? [] : BuildLets(document);
@@ -79,7 +79,7 @@ public static class FirmamentV2ValidationReportBuilder
.Distinct()
.Select(diagnostic => FirmamentBuildAdmissionValidation.Locate(diagnostic, sourceText ?? parse.OriginalSource, source))
.ToArray();
- fatalCount = diagnostics.Count(diagnostic => diagnostic.Severity == "fatal");
+ fatalCount = diagnostics.Count(diagnostic => diagnostic.Severity is "fatal" or "error");
warningCount = diagnostics.Count(diagnostic => diagnostic.Severity == "warning");
var supported = pmi.Count(record => record.ExportSupport is "supported" or "supported-when-target-resolves");
var deferred = pmi.Count(record => record.ExportSupport == "deferred");
@@ -225,7 +225,7 @@ public static class FirmamentV2ValidationReportBuilder
var itemDiagnostics = boundRecord is null
? diagnostics.Where(diagnostic => diagnostic.Code.StartsWith("firmament-v2-pmi-", StringComparison.Ordinal)).ToArray()
: [];
- var status = itemDiagnostics.Any(diagnostic => diagnostic.Severity == "fatal")
+ var status = itemDiagnostics.Any(diagnostic => diagnostic.Severity is "fatal" or "error")
? "invalid"
: exportSupport == "deferred"
? "export-deferred"
@@ -241,7 +241,7 @@ public static class FirmamentV2ValidationReportBuilder
boundRecord?.Targets ?? [],
boundRecord?.DatumRefs ?? [],
Dimension(boundRecord),
- exportSupport == "deferred" ? DeferredReason(record.Kind) : null,
+ exportSupport == "deferred" ? FirmamentBuildAndExport.V2PmiExportRejection(record.Kind, record.Name, boundRecord)?.Message : null,
itemDiagnostics,
record.Projection?.SourceRequireId,
constraint is null ? null : "dimensional-equality",
@@ -378,14 +378,9 @@ public static class FirmamentV2ValidationReportBuilder
private static string? Field(FirmamentV2PmiRecord record, string name) =>
record.Fields.TryGetValue(name, out var field) ? field.Source : null;
- private static string ExportSupport(FirmamentV2PmiKind kind, FirmamentV2BoundPmiRecord? boundRecord) => kind switch
- {
- FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter => boundRecord is null ? "supported-when-target-resolves" : "supported",
- _ => "deferred"
- };
-
- private static string DeferredReason(FirmamentV2PmiKind kind) =>
- $"AP242 lowering for {KindName(kind)} is not implemented in Phase 1 P1.";
+ private static string ExportSupport(FirmamentV2PmiKind kind, FirmamentV2BoundPmiRecord? boundRecord) =>
+ FirmamentBuildAndExport.V2PmiExportRejection(kind, boundRecord?.Name ?? "unbound", boundRecord) is not null
+ ? "deferred" : boundRecord is null ? "supported-when-target-resolves" : "supported";
private static readonly IReadOnlyDictionary<string, string> ExportMatrix = new Dictionary<string, string>(StringComparer.Ordinal)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
index 7ef332d4..ade87ed2 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
@@ -82,7 +82,7 @@ public static class ProfileAuthoringParser
{
var syntax = FirmamentSyntaxParser.Parse(source).Document;
var allowed = FirmamentSyntaxTraversal.Declarations(syntax).Where(d => d.Type.Name.Text == "Profile"
- || d.Type.Name.Text == "Path" && d.Modifiers.Any(m => m.Name.Text == "Concept"))
+ || d.Type.Name.Text == "Path")
.Select(d => d.Body?.Span).OfType<FirmamentV2SourceSpan>().ToArray();
return FirmamentSyntaxTraversal.Expressions(syntax).OfType<BinarySyntax>().Where(e => e.Operator == BinaryOperator.Pipeline)
.Where(e => !allowed.Any(span => e.Span.Start >= span.Start && e.Span.Start + e.Span.Length <= span.Start + span.Length))
@@ -433,13 +433,20 @@ public static class ProfileAuthoringParser
private static IReadOnlyDictionary<string, BoundPath> BindPaths(string source, Dictionary<string, (double X, double Y)> points, Dictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics)
{
var result = new Dictionary<string, BoundPath>(StringComparer.Ordinal);
- foreach (var block in FindBlocks(source, @"\bConcept\s+Path\s+(?<name>[A-Za-z_]\w*)\s*\{"))
+ foreach (var declaration in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)
+ .Where(d => d.Type.Name.Text == "Path"))
{
- var name = block.Match.Groups["name"].Value;
+ var name = declaration.Name?.Text ?? "<unnamed>";
+ if (declaration.Name is null || declaration.Body is null || declaration.Modifiers.Any(m => m.Name.Text != "Concept")
+ || declaration.Type.Arguments.Count > 0 || declaration.Parameters.Count > 0 || declaration.Annotation is not null
+ || declaration.Initializer is not null || declaration.ResultType is not null || declaration.Clauses.Count > 0)
+ { diagnostics.Add($"concept-path-header-invalid:{name}"); continue; }
+ var content = declaration.Body.ContentSpan;
+ var pathBody = source.Substring(content.Start, content.Length);
if (!result.TryAdd(name, default!)) { diagnostics.Add($"concept-path-duplicate:{name}"); continue; }
- if (block.Body.Contains("|>", StringComparison.Ordinal))
+ if (pathBody.Contains("|>", StringComparison.Ordinal))
{
- var pipelinePath = BindPathPipeline(name, block.Body, points, guides, diagnostics);
+ var pipelinePath = BindPathPipeline(name, pathBody, points, guides, diagnostics);
if (pipelinePath is not null)
{
result[name] = pipelinePath;
@@ -452,16 +459,16 @@ public static class ProfileAuthoringParser
}
continue;
}
- var startMatch = Regex.Match(block.Body, @"\bStart\s*:\s*Point2\s*\(\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*\)", RegexOptions.CultureInvariant);
+ var startMatch = Regex.Match(pathBody, @"\bStart\s*:\s*Point2\s*\(\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*\)", RegexOptions.CultureInvariant);
if (!startMatch.Success || !TryNumber(startMatch.Groups["x"].Value, out var sx) || !TryNumber(startMatch.Groups["y"].Value, out var sy)) { diagnostics.Add($"concept-path-start-invalid:{name}"); continue; }
var heading = 0d;
- var headingMatch = Regex.Match(block.Body, @"\bHeading\s*:\s*(?<value>[-+.\deE]+)deg", RegexOptions.CultureInvariant);
+ var headingMatch = Regex.Match(pathBody, @"\bHeading\s*:\s*(?<value>[-+.\deE]+)deg", RegexOptions.CultureInvariant);
if (headingMatch.Success && (!TryNumber(headingMatch.Groups["value"].Value, out heading) || !double.IsFinite(heading))) { diagnostics.Add($"concept-path-heading-invalid:{name}"); continue; }
var path = new BoundPath(name, (sx, sy), heading, []);
if (points.ContainsKey($"{name}.Start") || guides.ContainsKey(name)) { diagnostics.Add($"concept-path-name-collision:{name}"); continue; }
points[$"{name}.Start"] = path.Start;
var current = path.Start;
- foreach (var step in FindPathSteps(block.Body))
+ foreach (var step in FindPathSteps(pathBody))
{
if (path.Steps.Any(x => x.Name == step.Name)) { diagnostics.Add($"concept-path-duplicate-step:{name}:{step.Name}"); continue; }
var guideName = $"{name}.{step.Name}";
@@ -998,7 +1005,7 @@ public static class ProfileAuthoringParser
private static string MaskRecognizedProfileDeclarations(string body)
{
- var declarationPattern = @"\b(?:(?:Concept\s+)?(?:Point2|Line2|Rect2|Square2|Circle2|Ellipse2|Ellipse2Guide|Slot2|RoundedRect2|SmoothRoundedRect2)|(?:Triangle2|Polygon2|RegularPolygon2)\s*<[^>]+>|Concept\s+Path)\s+[A-Za-z_]\w*\s*\{";
+ var declarationPattern = @"\b(?:(?:Concept\s+)?(?:Point2|Line2|Rect2|Square2|Circle2|Ellipse2|Ellipse2Guide|Slot2|RoundedRect2|SmoothRoundedRect2|Path)|(?:Triangle2|Polygon2|RegularPolygon2)\s*<[^>]+>)\s+[A-Za-z_]\w*\s*\{";
var blocks = FindBlocks(body, declarationPattern).OrderByDescending(block => block.Match.Index).ToArray();
var characters = body.ToCharArray();
foreach (var block in blocks)
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs
index fbe7fccb..1023b0ea 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntax.cs
@@ -60,6 +60,7 @@ public sealed record MappingSyntax(IdentifierSyntax Key, StatementSyntax Value,
[JsonDerivedType(typeof(MemberSetSyntax), "memberSet")]
[JsonDerivedType(typeof(TypedValueSyntax), "typedValue")]
[JsonDerivedType(typeof(MatchSyntax), "match")]
+[JsonDerivedType(typeof(ToleranceSyntax), "tolerance")]
public abstract record ExpressionSyntax(FirmamentV2SourceSpan Span);
public sealed record ReferenceSyntax(IdentifierSyntax Name, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
public sealed record LiteralSyntax(LiteralKind Kind, string Raw, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
@@ -84,6 +85,9 @@ public sealed record MemberSetSyntax(ExpressionSyntax Target, IReadOnlyList<Argu
public sealed record TypedValueSyntax(ExpressionSyntax Type, ExpressionSyntax Value, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
public sealed record MatchArmSyntax(ExpressionSyntax Pattern, ExpressionSyntax Value, FirmamentV2SourceSpan Span);
public sealed record MatchSyntax(ExpressionSyntax Scrutinee, IReadOnlyList<MatchArmSyntax> Arms, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
+/// <summary>Compile-time dimensional requirement; it never changes nominal geometry.</summary>
+public sealed record ToleranceSyntax(ExpressionSyntax Nominal, ExpressionSyntax Plus, ExpressionSyntax? Minus,
+ FirmamentV2SourceSpan ToleranceSpan, FirmamentV2SourceSpan Span) : ExpressionSyntax(Span);
public sealed record DocumentSyntax(string SourceFile, IReadOnlyList<StatementSyntax> Statements,
IReadOnlyList<SyntaxToken> Tokens, FirmamentV2SourceSpan Span);
public sealed record SyntaxParseResult(DocumentSyntax Document, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics)
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxEvidence.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxEvidence.cs
index bcb49fff..f4dd0eea 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxEvidence.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxEvidence.cs
@@ -30,6 +30,7 @@ public static class FirmamentSyntaxEvidence
if (node is JsonObject obj)
{
obj.Remove("Span");
+ obj.Remove("ToleranceSpan");
foreach (var property in obj) RemoveSpans(property.Value);
}
else if (node is JsonArray array) foreach (var item in array) RemoveSpans(item);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
index c6baf4ec..67da21fa 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs
@@ -325,6 +325,18 @@ public static class FirmamentSyntaxParser
while (!End)
{
if (++suffixCount > MaxDepth) throw Fail("firmament-syntax-depth", $"Expression chain exceeds the bounded parser limit of {MaxDepth}.");
+ // tol binds below arithmetic: (nominal expression) tol allowance.
+ // A leading + selects the two-sided +upper -lower spelling.
+ if (minimum <= 5 && Take("tol"))
+ {
+ var toleranceStart = Previous.Span.Start;
+ var plus = Expression(80, allowObject: false);
+ ExpressionSyntax? minus = null;
+ if (plus is UnarySyntax { Operator: UnaryOperator.Positive } && Take("-"))
+ minus = Expression(80, allowObject: false);
+ left = new ToleranceSyntax(left, plus, minus, Span(toleranceStart), Span(start));
+ continue;
+ }
if (Take("As") || Take("as")) { left = new AliasSyntax(left, Identifier(), Span(start)); continue; }
if (Current.Text is "From" or "from" or "To" or "to" && Peek(1).Text != ":")
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxTraversal.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxTraversal.cs
index ae8df009..8f21febc 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxTraversal.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxTraversal.cs
@@ -29,6 +29,7 @@ public static class FirmamentSyntaxTraversal
BinarySyntax b => [b.Left, b.Right],
UnarySyntax u => [u.Operand],
QuantitySyntax q => [q.Value],
+ ToleranceSyntax t => new[] { t.Nominal, t.Plus, t.Minus }.OfType<ExpressionSyntax>(),
SequenceSyntax s => s.Items.Select(a => a.Value),
CallSyntax c => new[] { c.Target }.Concat(c.Arguments.Select(a => a.Value)),
SpecializationSyntax s => new[] { s.Target }.Concat(s.Arguments.Select(a => a.Value)),
@@ -84,6 +85,7 @@ public static class FirmamentSyntaxTraversal
MemberSyntax m => ExpressionBodies(m.Target),
IndexSyntax i => ExpressionBodies(i.Target).Concat(i.Index is null ? [] : ExpressionBodies(i.Index)),
QuantitySyntax q => ExpressionBodies(q.Value),
+ ToleranceSyntax t => ExpressionBodies(t.Nominal).Concat(ExpressionBodies(t.Plus)).Concat(t.Minus is null ? [] : ExpressionBodies(t.Minus)),
FrameSyntax f => ExpressionBodies(f.Origin).Concat(f.Axes.SelectMany(a => ExpressionBodies(a.Value))),
AliasSyntax a => ExpressionBodies(a.Value),
TraceSyntax t => ExpressionBodies(t.Source).Concat(t.From is null ? [] : ExpressionBodies(t.From)).Concat(t.To is null ? [] : ExpressionBodies(t.To)),
diff --git a/Aetheris.Kernel.Firmament/Materializer/CircularSweep.cs b/Aetheris.Kernel.Firmament/Materializer/CircularSweep.cs
index 6d9111f5..a105fa60 100644
--- a/Aetheris.Kernel.Firmament/Materializer/CircularSweep.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/CircularSweep.cs
@@ -1,7 +1,5 @@
-using System.Globalization;
using System.Security.Cryptography;
using System.Text;
-using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Geometry;
using Aetheris.Kernel.Core.Geometry.Curves;
@@ -11,6 +9,7 @@ using Aetheris.Kernel.Core.Numerics;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Topology;
using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using Aetheris.Kernel.StandardLibrary.Materials;
namespace Aetheris.Kernel.Firmament.Materializer;
@@ -40,34 +39,50 @@ public sealed record CircularSweepBuildResult(
/// <summary>Parser/binder for the public Sweep declaration. Path geometry remains owned by Concept Path.</summary>
public static class CircularSweepAuthoring
{
- private static readonly Regex Declaration = new(@"\bSweep\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);
-
- public static bool IsSweepSource(string source) => Declaration.IsMatch(source);
+ public static bool IsSweepSource(string source) => FirmamentV2Parser.MechanicalDeclarations(
+ FirmamentSyntaxParser.Parse(source).Document.Statements).Any(d => d.Type.Name.Text == "Sweep");
public static KernelResult<CircularSweepFeatureAir> Parse(string source)
{
ArgumentNullException.ThrowIfNull(source);
- var declaration = Declaration.Match(source);
- if (!declaration.Success) return Failure("firmament-sweep-declaration-missing", "No Sweep declaration was found.");
- var close = MatchingBrace(source, source.IndexOf('{', declaration.Index));
- if (close < 0) return Failure("firmament-sweep-declaration-malformed", $"Sweep '{declaration.Groups["name"].Value}' has no closing brace.");
- var body = source[(source.IndexOf('{', declaration.Index) + 1)..close];
- var name = declaration.Groups["name"].Value;
- var pathName = Property(body, "Path");
+ source = FirmamentSourceSpelling.Normalize(source);
+ var syntax = FirmamentSyntaxParser.Parse(source);
+ if (!syntax.IsSuccess) return Failure(syntax.Diagnostics[0].Code, syntax.Diagnostics[0].Message);
+ var diagnostics = new List<string>();
+ FirmamentV2Parser.BindMaterialDomainScope(syntax.Document, "Sweep", diagnostics);
+ if (diagnostics.Count > 0) return Failure(diagnostics[0].Split(':')[0], string.Join("; ", diagnostics));
+ var declarations = FirmamentV2Parser.MechanicalDeclarations(syntax.Document.Statements).ToArray();
+ var sweeps = declarations.Where(d => d.Type.Name.Text == "Sweep").ToArray();
+ if (sweeps.Length == 0) return Failure("firmament-sweep-declaration-missing", "No Sweep declaration was found.");
+ if (sweeps.Length != 1) return Failure("firmament-sweep-multiple-material-owners", "Use one Sweep per part; use Assembly for separate parts.");
+ if (declarations.Any(d => d.Type.Name.Text == "Pmi"))
+ return Failure("firmament-sweep-pmi-unsupported", "Sweep does not yet admit semantic PMI export; a Pmi block cannot be ignored.");
+ var declaration = sweeps[0];
+ if (declaration.Name is null || declaration.Body is null) return Failure("firmament-sweep-declaration-malformed", "Sweep requires a name and body.");
+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);
+ var name = declaration.Name.Text;
+ var pathName = fields.Word("Path");
+ var diameterValue = fields.Take("Diameter");
+ var materialValue = fields.Take("Material");
+ var gapValue = fields.Take("MinimumGap");
+ fields.Complete();
+ if (diagnostics.Count > 0) return Failure(diagnostics[0].Split(':')[0], string.Join("; ", diagnostics));
if (pathName is null) return Failure("firmament-sweep-path-missing", $"Sweep '{name}' requires Path.");
- var pathHeader = Regex.Match(source, $@"\bConcept\s+Path\s+{Regex.Escape(pathName)}(?:\s+On\s+(?<plane>[A-Za-z_]\w*))?\s*\{{", RegexOptions.CultureInvariant);
- if (pathHeader.Success && pathHeader.Groups["plane"].Success && !string.Equals(pathHeader.Groups["plane"].Value, "XY", StringComparison.Ordinal))
- return Failure("firmament-sweep-path-nonplanar", $"Sweep path '{pathName}' uses plane '{pathHeader.Groups["plane"].Value}'; X0 admits planar XY Concept Paths only.");
- if (pathHeader.Success)
+ var pathDeclaration = FirmamentSyntaxTraversal.Declarations(syntax.Document).FirstOrDefault(d => d.Type.Name.Text == "Path" && d.Name?.Text == pathName);
+ var plane = pathDeclaration?.Clauses.FirstOrDefault(c => c.Kind == ClauseKind.On);
+ if (plane is not null && FirmamentSyntaxValues.Reference(plane.Value) != "XY")
+ return Failure("firmament-sweep-path-nonplanar", $"Sweep path '{pathName}' uses an unsupported frame; this consumer admits planar XY Paths only.");
+ if (pathDeclaration?.Body is { } pathBody)
{
- var pathOpen = source.IndexOf('{', pathHeader.Index); var pathClose = MatchingBrace(source, pathOpen);
- if (pathClose > pathOpen && Regex.IsMatch(source[(pathOpen + 1)..pathClose], @"\b(?:Line|Arc)\s+[A-Za-z_]\w*\s*\{[^}]*\bFrom\s*:\s*Point2\s*\(", RegexOptions.CultureInvariant))
+ if (pathBody.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text is "Line" or "Arc")
+ .Any(d => d.Body?.Statements.OfType<FieldSyntax>().Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "From")
+ && f.Value is CallSyntax { Target: ReferenceSyntax { Name.Text: "Point2" } }) == true))
return Failure("firmament-sweep-path-disconnected", $"Sweep path '{pathName}' contains an explicit segment origin; Concept Path segments must continue from the preceding endpoint.");
}
- var diameterText = Property(body, "Diameter");
- if (!TryMillimeters(diameterText, out var diameter) || diameter <= 0d)
+ if (!FirmamentSyntaxValues.TryMeasure(diameterValue, "mm", out var diameter) || diameter <= 0d)
return Failure("firmament-sweep-section-invalid", $"Sweep '{name}' Diameter must be a finite length greater than zero.");
- var materialReference = (Property(body, "Material") ?? "Standard.Materials.StainlessSteel.304_Annealed").Trim('"');
+ var materialReference = materialValue is null ? "Standard.Materials.StainlessSteel.304_Annealed" : FirmamentSyntaxValues.Reference(materialValue);
+ if (materialReference is null) return Failure("firmament-sweep-material-unresolved", $"Sweep '{name}' Material must be a material reference or string.");
var path = ProfileAuthoringParser.ResolveConceptPath(source, pathName, out var pathDiagnostics);
if (path is null || pathDiagnostics.Count > 0)
return Failure(pathDiagnostics.Count == 0 ? "firmament-sweep-path-unresolved" : pathDiagnostics[0],
@@ -76,10 +91,9 @@ public static class CircularSweepAuthoring
if (!resolution.IsSuccess || resolution.Material is null)
return Failure("firmament-sweep-material-unresolved", resolution.Message ?? $"Material '{materialReference}' could not be resolved.");
double? minimumGap = null;
- var gapText = Property(body, "MinimumGap");
- if (gapText is not null)
+ if (gapValue is not null)
{
- if (!TryMillimeters(gapText, out var gap) || gap < 0d)
+ if (!FirmamentSyntaxValues.TryMeasure(gapValue, "mm", out var gap) || gap < 0d)
return Failure("firmament-sweep-minimum-gap-invalid", $"Sweep '{name}' MinimumGap must be a finite non-negative length.");
minimumGap = gap;
}
@@ -87,31 +101,6 @@ public static class CircularSweepAuthoring
resolution.Material, minimumGap, [path.StableId, "CircularSection", "PlanarXY", "ConstantSection"]));
}
- private static string? Property(string body, string name)
- {
- var match = Regex.Match(body, $@"\b{Regex.Escape(name)}\s*:\s*(?<value>[^;\r\n}}]+)", RegexOptions.CultureInvariant);
- return match.Success ? match.Groups["value"].Value.Trim() : null;
- }
-
- private static bool TryMillimeters(string? text, out double value)
- {
- value = default;
- if (text is null) return false;
- var match = Regex.Match(text, @"^(?<value>[-+.\deE]+)mm$", RegexOptions.CultureInvariant);
- return match.Success && double.TryParse(match.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);
- }
-
- private static int MatchingBrace(string source, int open)
- {
- var depth = 0;
- for (var i = open; i >= 0 && i < source.Length; i++)
- {
- if (source[i] == '{') depth++;
- else if (source[i] == '}' && --depth == 0) return i;
- }
- return -1;
- }
-
private static string PathMessage(string diagnostic)
{
var parts = diagnostic.Split(':');
diff --git a/Aetheris.Kernel.Firmament/Materializer/WireForm.cs b/Aetheris.Kernel.Firmament/Materializer/WireForm.cs
index 77466fc3..8cbfba1b 100644
--- a/Aetheris.Kernel.Firmament/Materializer/WireForm.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/WireForm.cs
@@ -142,6 +142,12 @@ public static class WireFormAuthoring
ArgumentNullException.ThrowIfNull(source);
source = FirmamentV2.FirmamentSourceSpelling.Normalize(source);
if (WireRouteAuthoring.IsSource(source)) return WireRouteAuthoring.Parse(source);
+ var syntax = FirmamentV2.Syntax.FirmamentSyntaxParser.Parse(source);
+ var scopeDiagnostics = new List<string>();
+ FirmamentV2.FirmamentV2Parser.BindMechanicalScope(FirmamentV2.Syntax.FirmamentSyntaxTraversal.Declarations(syntax.Document)
+ .Where(d => d.Type.Name.Text == "Static").Cast<FirmamentV2.Syntax.StatementSyntax>().ToArray(), scopeDiagnostics);
+ if (scopeDiagnostics.Count > 0)
+ return Fail(scopeDiagnostics[0].Split(':')[0], string.Join("; ", scopeDiagnostics));
var declaration = Declaration.Match(source);
if (!declaration.Success) return Fail("wireform-declaration-missing", "No WireForm declaration was found.");
var open = source.IndexOf('{', declaration.Index);
diff --git a/Aetheris.Kernel.Firmament/Materializer/WireRoute.cs b/Aetheris.Kernel.Firmament/Materializer/WireRoute.cs
index 412c3cde..c4732d07 100644
--- a/Aetheris.Kernel.Firmament/Materializer/WireRoute.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/WireRoute.cs
@@ -20,6 +20,12 @@ public static class WireRouteAuthoring
public static KernelResult<WireFormFeatureAir> Parse(string source)
{
source = FirmamentV2.FirmamentSourceSpelling.Normalize(source);
+ var syntax = FirmamentV2.Syntax.FirmamentSyntaxParser.Parse(source);
+ var scopeDiagnostics = new List<string>();
+ FirmamentV2.FirmamentV2Parser.BindMechanicalScope(FirmamentV2.Syntax.FirmamentSyntaxTraversal.Declarations(syntax.Document)
+ .Where(d => d.Type.Name.Text == "Static").Cast<FirmamentV2.Syntax.StatementSyntax>().ToArray(), scopeDiagnostics);
+ if (scopeDiagnostics.Count > 0)
+ return Fail(scopeDiagnostics[0].Split(':')[0], string.Join("; ", scopeDiagnostics));
// Comments cannot contribute operations or fields.
source = Regex.Replace(source, @"//[^\r\n]*", "");
var declarations = Declaration.Matches(source);
diff --git a/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament b/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament
index 0620fbd8..97b186f4 100644
--- a/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament
+++ b/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament
@@ -53,7 +53,6 @@ Model StandardProducts {
Target: MountSouthWest
Value: P.HoleDiameter
Tolerance: PlusMinus(0.10mm, 0.00mm)
- DatumRefs: [A]
}
}
}
@@ -95,7 +94,6 @@ Model StandardProducts {
Target: BearingBore
Value: P.BoreDiameter
Tolerance: PlusMinus(0.05mm, 0.02mm)
- DatumRefs: [A]
}
}
}
@@ -184,7 +182,6 @@ Model StandardProducts {
Target: Bore
Value: P.BoreDiameter
Tolerance: PlusMinus(0.10mm, 0.00mm)
- DatumRefs: [A]
}
}
}
diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
index 4dde84dc..280ada3f 100644
--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
@@ -1166,7 +1166,7 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
Assert.Contains("8", pmi.Metadata["nominal"]);
Assert.Contains("0.05", pmi.Metadata["tolerancePlus"]);
Assert.Contains("0.02", pmi.Metadata["toleranceMinus"]);
- Assert.Equal("A", pmi.Metadata["datumRefs"]);
+ Assert.Empty(pmi.Metadata["datumRefs"]);
}
private static string GetRepositoryPath(string relativePath)
diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
index 411cd108..8133275c 100644
--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
@@ -1,5 +1,14 @@
# October 2026 Firmament language decision register
+Typed-tolerance amendment: [qualification report](../release/FIRMAMENT-TYPED-TOLERANCES.md)
+adds typed scalar Static requirements to unified mechanical admission, retains
+nominal geometry, and explicitly projects selected Length requirements through
+native PMI to AP242. Diagnostic severity and original-source-span preservation
+gain coverage under #1–#4. Path spelling is reconciled under #17; Semantic,
+Region, Enum/Match and Set roles are now distinguished in the authoring guide.
+Template/Record/domain-wide tolerance propagation remains a technical follow-up,
+not a completed semantic consolidation or an implicit change to units doctrine.
+
Directive/casing follow-up: [implementation and qualification](../release/FIRMAMENT-DIRECTIVES-AND-CASING.md)
closes the syntax review's ignored-include and schema-formatting witnesses.
Recommendations #1–#4 gain directive admission and located structured CLI errors;
diff --git a/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md b/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md
index db3f8e4a..9645bbc7 100644
--- a/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md
+++ b/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md
@@ -5,6 +5,14 @@ repairs S01 (symmetry fields), S02 (Profile/mirror links), S14 and S15.
It also repairs S13's dense mirror/override witness; specialized semicolon rules
elsewhere are unchanged. Original observations below remain pre-repair evidence.
+Typed-tolerance follow-up: [implementation and qualification](../release/FIRMAMENT-TYPED-TOLERANCES.md)
+adds AST-owned dimensional Static values and explicit native PMI projection.
+It clarifies S16/S17's value/interface roles: Semantic publishes typed
+engineering interfaces, Path is a non-materialized ordered guide, and
+Enum/Match choose while Set/Pattern enumerate. Bare Path and Concept Path now
+share the same owner. This does not close the wider expression-position or
+domain-grammar differences recorded below.
+
## Purpose and boundary
This review accompanies the rewrite of [Writing Firmament](../public/firmament/syntax.md).
diff --git a/docs/public/firmament/pmi.md b/docs/public/firmament/pmi.md
index 4d3f0b5a..be82bcb8 100644
--- a/docs/public/firmament/pmi.md
+++ b/docs/public/firmament/pmi.md
@@ -2,7 +2,57 @@
Firmament concepts and explicit PMI lower into the semantic engineering model, STEP AP242 product-definition entities, and Cadmata's semantic presentation. PMI records are measurable requirements; annotations are engineer-authored notes. Camera or label orientation is presentation state, not the requirement.
-Preview 3's native Model export supports `Datum` plane records and toleranced `HoleDiameter` records. The diameter record targets a named shaft hole; on a counterbore it means the shaft `Diameter`, not `CounterboreDiameter`. Other parsed PMI kinds may be reported as deferred and cannot be silently omitted by a successful build.
+Native Model export supports `Datum` plane records and `HoleDiameter` records, including typed dimensional tolerances. The diameter record targets a named shaft hole; on a counterbore it means the shaft `diameter`, not `counterboreDiameter`. Other parsed PMI kinds may be reported as deferred and cannot be silently omitted by a successful build.
+
+## Project a compile-time tolerance
+
+Declare a requirement once, use its nominal value for construction, and select
+it explicitly with `dimension:` in PMI. The complete witness is
+[`typed-tolerance.firmament`](../../../fixtures/Canonical/PMI/typed-tolerance.firmament):
+
+```firmament
+Model TypedHole {
+ units: mm
+ Static drillDiameter: Length = 8mm tol +0.10mm -0.05mm
+ Box Body { size: [40mm, 30mm, 8mm] }
+ Modify Body {
+ Hole<Shaft> Mount {
+ on: +Z
+ center: Point2(0mm, 0mm)
+ diameter: drillDiameter
+ end: ThroughAll
+ }
+ }
+ Pmi {
+ HoleDiameter MountSize { target: Mount dimension: drillDiameter }
+ }
+}
+```
+
+The exported diameter is nominally 8 mm with upper allowance +0.10 mm and lower
+allowance −0.05 mm. `tol 0.1mm` supplies equal allowances on both sides. The
+typed value and allowance survive direct aliases; normal geometry uses only
+the nominal. Unprojected values generate no PMI. `dimension:` requires a
+toleranced Length; Angle values can be checked at compile time but are not a
+HoleDiameter target and do not grant angular PMI export. The scalar admission
+scope and arithmetic policy are in [syntax](syntax.md#typed-tolerances-and-pmi).
+
+HoleDiameter projection exports a size requirement attached to the hole wall.
+A Datum may be exported separately. A `datum:`/`DatumRefs:` relationship on a
+size record rejects normal compilation for every spelling, including legacy
+literal records: native size export cannot preserve that association.
+Parse-only analysis can bind it, but identifies the record as export-deferred
+at `ParsedNotBuilt`. Datum-referenced geometric controls need a separately
+qualified PMI capability. The shipped examples request independent datums and
+size dimensions; they no longer request a relationship that was never emitted.
+
+This is semantic product-definition PMI, recovered by `aetheris analyze`;
+graphical dimension-label placement is separate. Explicit `value:` and
+`tolerance: PlusMinus(upper, lower)` remain supported compatibility forms.
+Existing `Require`-based `from:` / `as:` projections continue to mean a checked
+semantic constraint, rather than an implicit export of all Static values.
+
+## Targets and inspection
For a simple `Hole<Shaft>` constructed in a Box, `face(H.Wall)` names the stable wall output of Hole `H`. It is a semantic role selector, independent of the current BRep face number. `HoleDiameter` accepts it as a target:
@@ -27,7 +77,7 @@ aetheris analyze artifacts/pmi.step --json
The build's `pmiExportEvidence` and the analyzer's `semanticPmi` are independent public evidence surfaces. Supported validate records and inspected AP242 records must agree at the semantic-record level; one record may lower to several STEP entities.
-Pattern-generated geometry may coexist with PMI, but Preview 3 does not publish a stable selector for individual generated pattern instances or quantity/repeated-feature PMI authoring.
+Pattern-generated geometry may coexist with PMI, but the native lane does not yet publish a stable selector for individual generated pattern instances or quantity/repeated-feature PMI authoring.
## Assembly release records and design notes
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index 592ab9f5..33fa24c8 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -65,6 +65,10 @@ mutation or general-purpose computation.
| `Feature` | A reusable recipe returning one typed semantic result. |
| `Template` | Typed compile-time specialization of a declared product or bounded feature recipe. |
| `Record` / `Static` | A data shape / an immutable compile-time binding. A Record is not a body. |
+| `Enum` / `Match` | A finite choice type / compile-time selection of one result. |
+| `Set<T>` | All named entries of type T, available together for finite repetition. |
+| `Semantic` | A named engineering interface containing published datums, axes, points or dimensions. |
+| `Path` | An ordered construction chain, open or closed; it creates no material. `Concept Path` is a compatibility spelling. |
| `Pattern` | Finite repetition of admitted construction over a declared source. |
| `Assembly` / `Scene` | Product occurrences and relations / spatial presentation. |
@@ -147,6 +151,103 @@ domain. `Static` and Feature-local `let` are scoped compile-time facilities;
there is no general `let`-anywhere rule. Scalar `Function` recipes are described
in [points and functions](concept-points-and-functions.md).
+### Typed tolerances and PMI
+
+A tolerance is a compile-time requirement attached to a dimensional value:
+
+```firmament
+Model TolerancedPlate {
+ units: mm
+ Static drillDiameter: Length = 8mm tol +0.10mm -0.05mm
+ Box Body { size: [40mm, 30mm, 8mm] }
+ Modify Body {
+ Hole<Shaft> Mount {
+ on: +Z
+ center: Point2(0mm, 0mm)
+ diameter: drillDiameter
+ end: ThroughAll
+ }
+ }
+ Pmi {
+ HoleDiameter MountSize { target: Mount dimension: drillDiameter }
+ }
+}
+```
+
+`tol 0.1mm` means ±0.1 mm. `tol +0.10mm -0.05mm` means upper and lower
+allowance magnitudes of 0.10 and 0.05 mm. Both must be finite, nonnegative and
+have the value's dimensional unit. `Length` uses mm and `Angle` uses deg in this
+scalar lane; tolerances on Int, Float, Bool or String reject. `tol` applies to
+the whole initializer, after arithmetic. Zero allowances are permitted.
+
+Geometry consumes the nominal value. `Pmi` explicitly projects the requirement
+into AP242; declaring a tolerance alone emits no manufacturing annotation and
+does not loosen kernel geometry tolerances. A direct Static alias preserves
+the allowance. Arithmetic produces a nominal value and warns if it drops an
+operand's allowance; supply a new explicit `tol` when the result is a new
+requirement. There is no inferred interval propagation or tolerance-stack
+certification in Model scalar arithmetic.
+
+Scalar Static values belong directly to the Model or its source module and
+currently feed direct primitive and Modify fields. The existing shorthand
+`Static width = 40mm` infers Length; an annotation makes engineering intent
+clearer. Profile/Compose recipes and
+other domain frontends retain their typed Template inputs; they do not acquire
+general scalar environments from this feature. Unsupported scalar consumers
+in the qualified construction, Sweep and wire lanes reject; this pass does not
+qualify arbitrary scalar environments in other domains. Inline field
+annotations such as `diameter: 8mm tol 0.1mm` reject; give
+the requirement a name. Angle allowances can be bound and inspected, but native
+Model angular PMI export is not yet admitted. See [PMI](pmi.md) for projection
+targets and export limits.
+
+### Contracts, semantic interfaces and construction geometry
+
+`Concept` describes what a construction must provide. `Concept Struct` supplies
+non-materialized design geometry or an implementation of that contract.
+`Semantic Name { ... }`, usually published through `Expose` or attached to an
+Assembly occurrence, groups engineering references that consumers can name.
+For example, a mount interface can publish a `DatumFrame` and a toleranced
+`Dimension`. It is not a second body, a free-form metadata bag, or a command to
+recognize arbitrary BRep faces. Published values retain their types and source
+identity. [Assembly authoring](assembly-authoring-foundation.md) explains the
+interface and placement rules. PMI selects requirements for export; Semantic
+alone does not export every member as PMI.
+
+Use `Path` for ordered guides and `Profile` for a closed planar material
+boundary. Both `Path Name { ... }` and the older `Concept Path Name { ... }`
+resolve through the same owner, with identical endpoints, segment identities
+and geometry. A path can remain open for a Sweep; a Profile made from it must
+satisfy the Profile's closure rules. Path does not imply a solid or a spatial
+volume.
+
+`Region` is not a general replacement for Struct, Profile or Semantic. Current
+mechanical compatibility syntax has the bounded lowercase
+`region sideHole on face(+X) { cut Cylinder { ... } }` operation inside
+`modify`; it is not a general native `Region` declaration. Prefer `Hole<Shaft>`
+for new hole construction. `Recognize` names a verified region of existing
+geometry. Sheet Metal's named planar regions and FEA's `Region:` selection
+fields are domain-owned uses of the word, with separate types and admission
+rules. See [Sheet Metal](sheet-metal.md) and [FEA](fea.md).
+
+### Choices versus collections
+
+`Enum` and `Match` remain useful; `Set<T>` does not supersede them:
+
+| Intent | Form | Compile-time meaning |
+| --- | --- | --- |
+| Choose Compact or Standard | `Enum SizeChoice { Compact Standard }` | Define alternatives; a typed parameter holds one case. |
+| Compute a value for the selected case | `Match choice { Compact => 1mm Standard => 2mm }` | Select one arm in an admitted Template/static expression position. |
+| Construct every mount | `Static mounts: Set<Point2> { ... }` and `Pattern` | Bind all entries; expand the recipe for each named entry. |
+
+Enum cases are tags, not coordinates or a collection of feature instances.
+Match is not a runtime branch or a general statement executor. Pattern repeats
+construction; it does not choose an enum case. Match support is bounded by its
+consumer: the Template binder supports typed choices, while Model scalar Static
+initializers currently admit literals, aliases and arithmetic. Do not infer
+general Match support from its presence in the syntax tree. See
+[Templates](templates.md) and the Pattern examples below.
+
## Constructing from a layout
Use a `Concept Struct` for design geometry, trace its named guides into a
@@ -184,7 +285,7 @@ orientation, falling back to a connectable direction after the opening stage.
`boundary |> TraceLoop` copies a whole closed guide and normalizes winding for
the target loop. Supported families include Rect2, Square2, RoundedRect2,
-Polygon2, RegularPolygon2, closed Concept Paths, Circle2 and Ellipse2. A full
+Polygon2, RegularPolygon2, closed Paths, Circle2 and Ellipse2. A full
circle or ellipse retains a single boundary segment; its traced identity derives
from the guide name, allowing distinct inner/outer guides.
@@ -203,7 +304,7 @@ guide from startPoint to endPoint as selectedEdge
After the opening stage, `guide to endPoint` uses the preceding endpoint as its
start. Endpoints must be named points on the guide. Circular spans use the same
form; `Reverse` selects the opposite traversal. `|>` is not a general map, filter,
-arithmetic or function-composition operator. A Concept Path may remain open;
+arithmetic or function-composition operator. A Path may remain open;
a material Profile must satisfy its boundary rules.
Closed boundaries should express their engineering shape. Use Rect2 for a
diff --git a/docs/public/firmament/templates.md b/docs/public/firmament/templates.md
index b03f71d6..6fd263fa 100644
--- a/docs/public/firmament/templates.md
+++ b/docs/public/firmament/templates.md
@@ -43,6 +43,27 @@ The older `Template MountHole(MountSpec spec)` and `MountHole(Current)` spelling
## Parameters
+`Enum` defines mutually exclusive parameter choices; `Match` computes the value
+for the selected choice during specialization. `Set<T>` instead contains all
+of its named entries at once, for iteration with Pattern. These constructs
+have different jobs and remain supported. See the working
+[`table-driven-mounting-plate.firmament`](../../../fixtures/Canonical/Templates/table-driven-mounting-plate.firmament)
+for enum-valued Record data, and [Writing Firmament](syntax.md#choices-versus-collections)
+for their language roles and bounded Match admission. An enum declaration does
+not itself generate one body per case.
+Each specialization must resolve a matching arm. This pass does not add a
+whole-enum exhaustiveness guarantee for unselected alternatives across all
+existing Match consumers.
+Enum values are admitted in typed Template parameters and Record fields. The
+primitive Model scalar Static lane does not yet bind standalone enum-valued
+constants; that is a binder-consolidation task, not a reason to replace choices
+with Set.
+
+Model scalar `Static` bindings can carry [typed tolerances](pmi.md#project-a-compile-time-tolerance).
+They do not implicitly extend Template argument evaluation, Record field
+initialization or every domain's scalar environment. A Template's declared
+parameter type and its owning binder still determine admitted values.
+
Value parameters use `Name: Type`. Defaults use `Name: Type = Value`. A real semantic/type parameter is explicit:
```text
diff --git a/docs/release/FIRMAMENT-TYPED-TOLERANCES.md b/docs/release/FIRMAMENT-TYPED-TOLERANCES.md
new file mode 100644
index 00000000..40d97eb4
--- /dev/null
+++ b/docs/release/FIRMAMENT-TYPED-TOLERANCES.md
@@ -0,0 +1,188 @@
+# Firmament typed tolerances and language roles
+
+## Contract
+
+`Static drillDiameter: Length = 8mm tol +0.10mm -0.05mm` is an immutable
+compile-time dimensional requirement. Geometry consumes 8 mm. A named PMI
+record with `dimension: drillDiameter` explicitly projects the nominal and
+allowances through the existing semantic AP242 exporter. Nothing is implicitly
+annotated. `tol 0.1mm` means symmetric allowances; Angle uses deg. Non-dimensional,
+negative, mismatched and nonfinite allowances reject.
+
+The qualified source is
+[`typed-tolerance.firmament`](../../fixtures/Canonical/PMI/typed-tolerance.firmament).
+The negative CLI witness is
+[`unit-mismatch.firmament`](../../fixtures/Regression/TypedTolerances/unit-mismatch.firmament).
+
+## Before and repair
+
+The previous tolerance IR and exporter already existed. Source inspection
+found `tol` bound only through lowercase let's text parser, while the unified
+mechanical binder supplied empty value environments to PMI. Scalar Static
+declarations had no consuming owner. Path's construction owner required
+`Concept Path`, even though mechanical recognition admitted bare Path.
+
+The shared recursive-descent AST now represents a tolerance suffix with its
+own span. Native Static scalars lower to the existing typed dependency binder
+and tolerance IR. Nominal values are projected into actual primitive/Modify
+AST fields; no source replacement pass or parser route is added. Remaining
+Static declarations in unsupported construction/domain scopes reject. The
+canonical symbol table includes scalar identities. A direct alias preserves
+the tolerance; arithmetic produces a nominal result, with the existing
+tolerance-drop warning unless the result supplies a fresh allowance.
+The existing `Static unused = 4mm` shorthand remains valid with inferred
+Length, and produces the same geometry as before. Integer overflow and
+nonfinite scalar results reject rather than entering geometry as wrapped values.
+
+Native typed PMI cannot override its source requirement's nominal or allowance.
+For direct named holes, the actual diameter must satisfy the projected
+requirement. Existing explicit Value/Tolerance and Require-based projections
+retain their separate admitted contracts. Lowercase let's compatibility reader
+remains for existing source; this pass does not claim to have migrated every
+remaining compatibility extension.
+
+AP242 inspection also confirmed an existing omission: the native size exporter
+has no datum-reference member, although legacy literal PMI can bind DatumRefs.
+The existing PMI export-admission gate now rejects that unsupported relationship
+for every spelling, including typed projection and legacy literal records. The
+validation report consults the same capability owner and identifies the record
+as export-deferred during parse-only analysis. Normal validate/build reject it.
+The witness exports Datum A independently and requests a hole-wall-associated
+size. No kernel operation or invented datum association is introduced.
+
+The preserved failing source is
+[`legacy-datum-reference.firmament`](../../fixtures/Regression/TypedTolerances/legacy-datum-reference.firmament).
+Before repair it requested `DatumRefs: [A]`, while AP242 reinspection returned
+an independent Datum A and a diameter with empty datumReferences. Nine shipped
+canonical/regression examples, three embedded standard-product recipes and the
+nested-template positive witness now omit the unimplemented field and retain
+their independent Datum records. The nested-template test preserves the bad
+request as a rejection check. Construction is unchanged.
+The actual future datum-referenced control remains a separate PMI capability,
+explicitly rejected until its semantics and exporter are qualified. Original
+build/inspection evidence is kept as `legacy-datum-build.json` and
+`legacy-datum-analysis.json` beside the run logs.
+
+Diagnostic propagation now retains spans when the bound diagnostic source is
+identical to the authored source after span-preserving spelling/schema handling.
+Expansion without a source map still discloses unavailable provenance. Both
+error and fatal severities count as admission failures. CLI build recovers
+structured compiler diagnostics without another diagnostic-code allowlist.
+The language service projects located errors and tolerance-drop warnings.
+The old line-substring comment stripper is replaced by shared-lexer trivia
+masking: offsets and line breaks survive, quoted URLs are not truncated, and
+malformed comment tokens remain visible to syntax admission. Native String
+constants decode their AST literal through the existing JSON string codec.
+
+The unsupported-consumer regression exposed a remaining Sweep text reader that
+ignored an unused scalar requirement. Sweep declaration/header fields now bind
+through the shared AST and existing field-consumption owner. Unknown/duplicate
+fields, multiple Sweeps and unsupported PMI cannot disappear. Its regex header,
+property and quantity readers are removed; its analytic geometry lowerer is
+unchanged. WireForm/WireRoute explicitly reject residual Static declarations
+through the shared statement owner. Their existing operation grammars and
+implicit-unit compatibility are retained; this is not a claim of complete
+WireForm AST migration. Sweep and WireForm CLI validation now use actual normal
+compilation for `Built`, distinguish `ParsedNotBuilt`, and present structured
+diagnostics instead of bare strings.
+
+## Language decisions
+
+| Construct | Decision |
+| --- | --- |
+| Static / tol | Canonical named compile-time requirement; PascalCase type, camelCase authored example names, lowercase tol. |
+| Pmi | Explicit semantic export selection; no automatic annotation of all toleranced values. |
+| Semantic | Typed, named engineering interface for published datums, axes, points and dimensions; not material construction or arbitrary metadata. |
+| Path | Preferred unqualified ordered guide declaration; Concept Path remains a compatibility spelling of the same owner. |
+| Profile | Closed planar material boundary consumed by extrusion or another feature; a Path can remain open. |
+| Region | Domain-specific selection/region vocabulary. The lowercase mechanical sideHole region/cut form remains narrow compatibility, not a universal native Region type. |
+| Enum | Mutually exclusive compile-time tags, especially typed Template choices. |
+| Match | Select one result in the consuming binder's admitted compile-time expression positions. |
+| Set / Pattern | All named entries / finite repetition over them; neither supersedes Enum or Match. |
+
+Manual and pipeline Paths now enter through shared AST declaration boundaries.
+Their established segment resolution, source identities and geometry lowerers
+are retained. Native unused malformed Paths are also checked rather than
+silently ignored.
+
+## Explicit boundaries
+
+Scalar Static environments currently belong to a mechanical Model/module and
+feed direct primitive/Modify fields. Other construction owners retain their
+existing typed Template inputs; unsupported scalar consumers fail explicitly.
+Inline field tol annotations are rejected with a named-Static repair. General
+Record-field tolerances, Template argument propagation, automatic interval
+arithmetic, angular PMI export and arbitrary distance/GD&T export are not
+implemented here. Assembly Dimension/stackup behavior is retained, not unified
+with Model scalar arithmetic. Match is not enabled in arbitrary scalar Static
+initializers merely because the syntax tree can represent it.
+
+These are technical qualification boundaries; no unresolved user syntax or
+engineering-policy choice is required to use the qualified lane.
+
+Match exhaustiveness across unselected enum alternatives remains a semantic
+consolidation follow-up. Each current specialization must resolve an admitted
+arm; the guide does not promise universal total matching.
+Standalone enum-valued scalar Static bindings likewise remain outside the
+primitive scalar binder; Enum values retain their existing Template/Record uses.
+
+## Code-quality review
+
+The pass reuses the shared lexer/AST, dependency/type binder, tolerance IR,
+field/statement consumption and AP242 exporter. No new parser route selection
+architecture, source macro system, independent expression evaluator, diagnostic
+fatality allowlist, global parser state or product-side validator is introduced.
+Sweep's obsolete regex readers are removed. The only expanded compatibility
+regex is the existing local Profile declaration mask recognizing bare Path.
+Legacy manual path-step and WireForm operation readers remain explicitly outside
+the completed AST field migration.
+
+## Evidence
+
+Qualification is recorded under ignored
+[`artifacts/local/firmament-typed-tolerances`](../../artifacts/local/firmament-typed-tolerances).
+
+| Check | Observed result |
+| --- | --- |
+| Release solution build | Passed; zero errors, existing nullable/analyzer/platform warnings remain. |
+| Focused compiler iteration | 490 passed, including V2 parsing, typed values, mechanical migration, paths, wires and language-service checks. |
+| Focused CLI iteration | 21 passed, including structured diagnostics, parse-only levels and documentation links. |
+| Core fast lane | 1,068 passed. |
+| Full solution lane | 4,810 passed across 20 test assemblies; zero failures/skips. |
+| Existing baseline STEP outputs | Ten byte-for-byte SHA-256 matches across symmetry, Profile links, Hole, Template and Set/Pattern specimens. |
+| Cleaned canonical PMI example | Byte-for-byte identical to its original STEP artifact: SHA-256 `9F2F24975267BF425D16A2ECDF863F4A94C0FAD172C932F9868BBB836BD46F5D`. |
+| Documentation | Seven complete examples from syntax, PMI and revolve guides compiled. |
+| Real repository CLI | Thirteen expected outcomes, including typed validate/build/analyze, invalid source, the preserved legacy-PMI failure, bolt, guitar, Industrial ATLAS, house, factory, Sheet Metal and existing PMI. |
+| Runtime hygiene | Serial build/test execution with node reuse disabled; final .NET/MSBuild/testhost inventory empty. |
+
+The typed witness reimports as one body with seven faces and bounds
+`[-20,-15,0]` to `[20,15,8]` mm. Semantic inspection recovers an 8 mm diameter,
+upper/lower allowance magnitudes 0.10/0.05 mm, and a nonempty BRep-face
+association. Changing only tolerance metadata without PMI leaves STEP bytes
+unchanged; replacing the compile-time references with their nominal literals
+also leaves STEP bytes unchanged. Parser and actual compilation reject the
+invalid type/unit/dependency cases; normal CLI validate/build agree on known
+capability failures. No separate live Helios UI session was run; language-service
+and server/Cadmata API projections are covered by the full .NET lane.
+
+The full gate was run after the Release solution build:
+
+```powershell
+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter "Category!=SlowCorpus"
+dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1
+```
+
+The existing FrictionLab test project has no discoverable tests; it contributes
+no cases to the totals. Logs preserve intermediate failures and their repairs,
+including inferred Static compatibility and the standard-library PMI cleanup.
+
+## Verdict
+
+**Success for this pass.** Typed tolerances bind through production unified
+mechanical admission and explicitly export real hole-size PMI with preserved
+allowances and a BRep face association. The discovered legacy datum-reference
+omission is closed by shared capability admission, rather than left as a
+spelling-dependent bypass. Geometry, source diagnostics and the named language
+roles have concrete regression witnesses. This does not declare every language
+family or the original global X0 checklist fully qualified. No outstanding user
+policy decision is needed for the typed-tolerance syntax.
diff --git a/fixtures/Canonical/Drawings/bearing-block-production-drawing.firmament b/fixtures/Canonical/Drawings/bearing-block-production-drawing.firmament
index 63d1bb9b..3ff152ee 100644
--- a/fixtures/Canonical/Drawings/bearing-block-production-drawing.firmament
+++ b/fixtures/Canonical/Drawings/bearing-block-production-drawing.firmament
@@ -35,7 +35,6 @@ Model BearingBlock {
HoleDiameter MountDiameter {
From: MountDiameterConstraint
As: HoleDiameter
- DatumRefs: [A]
}
}
diff --git a/fixtures/Canonical/Integration/machined-mounting-block.firmament b/fixtures/Canonical/Integration/machined-mounting-block.firmament
index 9f9ad5be..acd8197f 100644
--- a/fixtures/Canonical/Integration/machined-mounting-block.firmament
+++ b/fixtures/Canonical/Integration/machined-mounting-block.firmament
@@ -71,13 +71,11 @@ Model MachinedMountingBlock {
Target: ConnectorBore
Value: 6mm
Tolerance: PlusMinus(0.05mm, 0.02mm)
- DatumRefs: [A]
}
HoleDiameter MountNorthDiameter {
Target: MountNorth
Value: 6mm
Tolerance: PlusMinus(0.10mm, 0.00mm)
- DatumRefs: [A]
}
}
}
diff --git a/fixtures/Canonical/PMI/counterbore-shaft-diameter.firmament b/fixtures/Canonical/PMI/counterbore-shaft-diameter.firmament
index ee5f45dc..cd1585ea 100644
--- a/fixtures/Canonical/PMI/counterbore-shaft-diameter.firmament
+++ b/fixtures/Canonical/PMI/counterbore-shaft-diameter.firmament
@@ -61,7 +61,6 @@ Model ProfileComposeLBracketCounterborePmi {
Target: CounterboredMount
Value: 8mm
Tolerance: PlusMinus(0.05mm, 0.02mm)
- DatumRefs: [A]
}
}
}
diff --git a/fixtures/Canonical/PMI/hole-diameter-and-datum.firmament b/fixtures/Canonical/PMI/hole-diameter-and-datum.firmament
index 000cfc20..78496199 100644
--- a/fixtures/Canonical/PMI/hole-diameter-and-datum.firmament
+++ b/fixtures/Canonical/PMI/hole-diameter-and-datum.firmament
@@ -16,7 +16,6 @@ Model CanonicalPmiMount {
Target: Mount
Value: 8mm
Tolerance: PlusMinus(0.05mm, 0.02mm)
- DatumRefs: [A]
}
}
}
diff --git a/fixtures/Canonical/PMI/multiple-hole-dimensions-with-chamfer.firmament b/fixtures/Canonical/PMI/multiple-hole-dimensions-with-chamfer.firmament
index 3e348a96..7932367f 100644
--- a/fixtures/Canonical/PMI/multiple-hole-dimensions-with-chamfer.firmament
+++ b/fixtures/Canonical/PMI/multiple-hole-dimensions-with-chamfer.firmament
@@ -12,13 +12,11 @@ Model MountingPlate {
Target: MountLeft
Value: 8mm
Tolerance: PlusMinus(0.10mm, 0.00mm)
- DatumRefs: [A]
}
HoleDiameter MountRightDiameter {
Target: MountRight
Value: 8mm
Tolerance: PlusMinus(0.10mm, 0.00mm)
- DatumRefs: [A]
}
}
}
diff --git a/fixtures/Canonical/PMI/typed-tolerance.firmament b/fixtures/Canonical/PMI/typed-tolerance.firmament
new file mode 100644
index 00000000..a3aee7a0
--- /dev/null
+++ b/fixtures/Canonical/PMI/typed-tolerance.firmament
@@ -0,0 +1,16 @@
+// Typed manufacturing requirements are compile-time values. Geometry uses nominal values.
+Model TolerancedPlate {
+ units: mm
+ Static plateWidth: Length = 40mm tol 0.1mm
+ Static drillDiameter: Length = 8mm tol +0.10mm -0.05mm
+ Static inspectionDiameter: Length = drillDiameter
+ Static draft: Angle = 3deg tol 0.5deg
+ Box Body { size: [plateWidth, 30mm, 8mm] }
+ Modify Body {
+ Hole<Shaft> Mount { on: +Z center: Point2(0mm, 0mm) diameter: drillDiameter end: ThroughAll }
+ }
+ Pmi {
+ Datum A { target: face(+Z) }
+ HoleDiameter MountSize { target: Mount dimension: inspectionDiameter }
+ }
+}
diff --git a/fixtures/Canonical/Templates/nested-template-pmi.firmament b/fixtures/Canonical/Templates/nested-template-pmi.firmament
index 6933110c..797fb8ce 100644
--- a/fixtures/Canonical/Templates/nested-template-pmi.firmament
+++ b/fixtures/Canonical/Templates/nested-template-pmi.firmament
@@ -37,7 +37,6 @@ Model NestedTemplatePmi {
Target: Mount
Value: 6mm
Tolerance: PlusMinus(0.05mm, 0.02mm)
- DatumRefs: [A]
}
}
}
diff --git a/fixtures/Regression/CanonicalGeometry/a3-mounting-plate.firmament b/fixtures/Regression/CanonicalGeometry/a3-mounting-plate.firmament
index ddb0db33..62f9e9e7 100644
--- a/fixtures/Regression/CanonicalGeometry/a3-mounting-plate.firmament
+++ b/fixtures/Regression/CanonicalGeometry/a3-mounting-plate.firmament
@@ -17,7 +17,6 @@ Model A3MountingPlate {
Target: MountNorthWest
Value: 8mm
Tolerance: PlusMinus(0.10mm, 0.00mm)
- DatumRefs: [A]
}
}
}
diff --git a/fixtures/Regression/CanonicalGeometry/pmi-manual-vs-projected-equivalence.firmament b/fixtures/Regression/CanonicalGeometry/pmi-manual-vs-projected-equivalence.firmament
index 226d8524..78966d63 100644
--- a/fixtures/Regression/CanonicalGeometry/pmi-manual-vs-projected-equivalence.firmament
+++ b/fixtures/Regression/CanonicalGeometry/pmi-manual-vs-projected-equivalence.firmament
@@ -8,7 +8,7 @@ Model ManualProjectedEquivalence {
Require ProjectedDiameter { Actual: ProjectedMount.Diameter Expected: 8mm Tolerance: PlusMinus(0.05mm, 0.02mm) }
Pmi {
Datum A { Target: face(+Z) }
- HoleDiameter ManualCallout { Target: ManualMount Value: 8mm Tolerance: PlusMinus(0.05mm, 0.02mm) DatumRefs: [A] }
- HoleDiameter ProjectedCallout { From: ProjectedDiameter As: HoleDiameter DatumRefs: [A] }
+ HoleDiameter ManualCallout { Target: ManualMount Value: 8mm Tolerance: PlusMinus(0.05mm, 0.02mm) }
+ HoleDiameter ProjectedCallout { From: ProjectedDiameter As: HoleDiameter }
}
}
diff --git a/fixtures/Regression/CanonicalGeometry/pmi-projected-hole-diameter.firmament b/fixtures/Regression/CanonicalGeometry/pmi-projected-hole-diameter.firmament
index 0f7a127c..45616706 100644
--- a/fixtures/Regression/CanonicalGeometry/pmi-projected-hole-diameter.firmament
+++ b/fixtures/Regression/CanonicalGeometry/pmi-projected-hole-diameter.firmament
@@ -20,7 +20,6 @@ Model ProjectedPmiMount {
HoleDiameter MountDiameterCallout {
From: MountDiameterConstraint
As: HoleDiameter
- DatumRefs: [A]
}
}
}
diff --git a/fixtures/Regression/TypedTolerances/legacy-datum-reference.firmament b/fixtures/Regression/TypedTolerances/legacy-datum-reference.firmament
new file mode 100644
index 00000000..000cfc20
--- /dev/null
+++ b/fixtures/Regression/TypedTolerances/legacy-datum-reference.firmament
@@ -0,0 +1,22 @@
+Model CanonicalPmiMount {
+ Units: mm
+
+ Box Base { Size: [80mm, 50mm, 12mm] }
+ Modify Base {
+ Hole<Shaft> Mount {
+ On: +Z
+ Center: Point2(0mm, 0mm)
+ Diameter: 8mm
+ End: ThroughAll
+ }
+ }
+ Pmi {
+ Datum A { Target: face(+Z) }
+ HoleDiameter MountDiameter {
+ Target: Mount
+ Value: 8mm
+ Tolerance: PlusMinus(0.05mm, 0.02mm)
+ DatumRefs: [A]
+ }
+ }
+}
diff --git a/fixtures/Regression/TypedTolerances/sweep-unconsumed.firmament b/fixtures/Regression/TypedTolerances/sweep-unconsumed.firmament
new file mode 100644
index 00000000..d2e158f0
--- /dev/null
+++ b/fixtures/Regression/TypedTolerances/sweep-unconsumed.firmament
@@ -0,0 +1,10 @@
+Model SweepRequirement {
+ units: mm
+ Static diameterRequirement: Length = 1mm tol 0.1mm
+ Path Centerline {
+ start: Point2(0mm, 0mm)
+ heading: 0deg
+ Line Lead { length: 20mm }
+ }
+ Sweep Wire { path: Centerline diameter: 1mm }
+}
diff --git a/fixtures/Regression/TypedTolerances/unit-mismatch.firmament b/fixtures/Regression/TypedTolerances/unit-mismatch.firmament
new file mode 100644
index 00000000..6c9ad283
--- /dev/null
+++ b/fixtures/Regression/TypedTolerances/unit-mismatch.firmament
@@ -0,0 +1,5 @@
+Model UnitMismatch {
+ units: mm
+ Static drillDiameter: Length = 8mm tol 0.1deg
+ Box Body { size: [40mm, 30mm, 8mm] }
+}
diff --git a/fixtures/Regression/TypedTolerances/wireform-unconsumed.firmament b/fixtures/Regression/TypedTolerances/wireform-unconsumed.firmament
new file mode 100644
index 00000000..a26b476d
--- /dev/null
+++ b/fixtures/Regression/TypedTolerances/wireform-unconsumed.firmament
@@ -0,0 +1,9 @@
+Model WireRequirement {
+ units: mm
+ Static diameterRequirement: Length = 1mm tol 0.1mm
+ WireForm Wire {
+ diameter: 1mm
+ StartFrame { origin: [0mm,0mm,0mm] tangent: [1,0,0] up: [0,0,1] }
+ Straight Lead { length: 20mm }
+ }
+}