Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add compile-time value transfer and provenance

Yuechen Lie933c1920f5b
diff --git a/Aetheris.CLI.Tests/FirmamentCompileTimeValuesCliTests.cs b/Aetheris.CLI.Tests/FirmamentCompileTimeValuesCliTests.cs
new file mode 100644
index 00000000..e2b8ac8e
--- /dev/null
+++ b/Aetheris.CLI.Tests/FirmamentCompileTimeValuesCliTests.cs
@@ -0,0 +1,46 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class FirmamentCompileTimeValuesCliTests
+{
+ private static string Root => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../.."));
+
+ [Fact]
+ public void NormalValidationBuildsTheRecordTemplateFeatureWitnessAndReportsAuthoredOrigins()
+ {
+ var path = Path.Combine(Root, "fixtures/Canonical/PMI/record-template-feature-tolerance.firmament");
+ var output = new StringWriter();
+ Assert.Equal(0, CliRunner.Run(["validate", path, "--json", "--explain"], output, new StringWriter()));
+ using var json = JsonDocument.Parse(output.ToString());
+ var report = json.RootElement.GetProperty("firmamentV2Validation");
+ Assert.Equal("Built", report.GetProperty("validationLevel").GetString());
+ Assert.Equal("UnifiedMechanical", report.GetProperty("parserRoute").GetString());
+ var pmi = Assert.Single(report.GetProperty("pmi").EnumerateArray());
+ Assert.Equal("standardBore.diameter", pmi.GetProperty("projectionSource").GetString());
+ Assert.Contains(pmi.GetProperty("dimensionOrigins").EnumerateArray(), o => o.GetProperty("sourceFile").GetString() == path
+ && o.GetProperty("binding").GetString() == "standardBore.diameter");
+ }
+
+ [Theory]
+ [InlineData("validate")]
+ [InlineData("build")]
+ [InlineData("parse-only")]
+ public void InvalidRecordRequirementRejectsEveryAdmissionCommandAtItsOriginalLine(string command)
+ {
+ var path = Path.Combine(Root, "fixtures/Regression/CompileTimeValues/record-unit-mismatch.firmament");
+ var destination = Path.Combine(Root, "artifacts/local/firmament-value-binding", Guid.NewGuid() + ".step");
+ var output = new StringWriter();
+ string[] args = command == "build" ? ["build", path, "--output", destination, "--json"]
+ : ["validate", path, "--json", .. (command == "parse-only" ? new[] { "--parse-only" } : [])];
+ Assert.Equal(1, CliRunner.Run(args, output, new StringWriter()));
+ using var json = JsonDocument.Parse(output.ToString());
+ var report = command == "build" ? json.RootElement : json.RootElement.GetProperty("firmamentV2Validation");
+ var diagnostic = Assert.Single(report.GetProperty("diagnostics").EnumerateArray(),
+ d => d.GetProperty("code").GetString() == "firmament-v2-tolerance-unit-mismatch");
+ Assert.Equal(path, diagnostic.GetProperty("sourceFile").GetString());
+ Assert.Equal(2, diagnostic.GetProperty("line").GetInt32());
+ Assert.Contains("mm", diagnostic.GetProperty("message").GetString());
+ Assert.False(File.Exists(destination));
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentCompileTimeValueBindingTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentCompileTimeValueBindingTests.cs
new file mode 100644
index 00000000..c0ce66f3
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentCompileTimeValueBindingTests.cs
@@ -0,0 +1,313 @@
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentCompileTimeValueBindingTests
+{
+ private static string Source => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(
+ "fixtures/Canonical/PMI/record-template-feature-tolerance.firmament"));
+
+ [Fact]
+ public void RecordRequirementSurvivesTemplateFeatureAndLocalAliasIntoGeometryAndAp242()
+ {
+ var source = Source;
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.Equal("TolerancedProduct", parsed.Document!.ModelName);
+ Assert.Equal(40, parsed.Document.Solid.Box!.Size[0]);
+ Assert.Equal(8, Assert.Single(Assert.Single(parsed.Document.ModifyBlocks!).SemanticHoles).ShaftDiameter);
+ var pmi = Assert.Single(parsed.Document.BoundPmi!.Dimensions);
+ Assert.Equal("standardBore.diameter", pmi.ProjectionSource);
+ var origin = Assert.Single(pmi.DimensionOrigins, o => o.Binding == "standardBore.diameter"
+ && source.Substring(o.SourceSpan.Start, o.SourceSpan.Length).Contains("tol", StringComparison.Ordinal));
+ Assert.Contains(pmi.DimensionOrigins, o => o.Binding == "Template PlateFamily.spec.diameter");
+ var geometryValue = Assert.Single(parsed.Document.BoundLets!, v => v.Origins.Any(o => o.Binding == "Feature Drill.inspection"));
+ Assert.Contains(origin, geometryValue.Origins);
+ Assert.Equal(0.10, geometryValue.Tolerance!.Plus);
+ Assert.Equal(0.05, geometryValue.Tolerance.Minus);
+ var compiled = FirmamentBuildAndExport.CompileSource(source, null);
+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics.Select(d => d.Message)));
+ var callout = Assert.Single(Step242SemanticPmiInspector.Inspect(compiled.Value.StepText).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 TypedTransportPreservesLiteralGeometryPmiAndStableFeatureIdentities()
+ {
+ var source = Source;
+ var literal = source.Replace("8mm tol +0.10mm -0.05mm", "8mm", StringComparison.Ordinal)
+ .Replace("dimension: spec.diameter", "value: 8mm tolerance: PlusMinus(0.10mm, 0.05mm)", StringComparison.Ordinal);
+ var before = FirmamentBuildAndExport.CompileSource(literal, null);
+ var after = FirmamentBuildAndExport.CompileSource(source, 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(FirmamentV2Parser.Parse(literal).Document!.TemplateInstantiations![0].SpecializationIdentity,
+ FirmamentV2Parser.Parse(source).Document!.TemplateInstantiations![0].SpecializationIdentity);
+ Assert.Equal(FirmamentV2Parser.Parse(literal).Document!.ModifyBlocks![0].SemanticHoles[0].Name,
+ FirmamentV2Parser.Parse(source).Document!.ModifyBlocks![0].SemanticHoles[0].Name);
+ }
+
+ [Fact]
+ public void NoPmiMeansNoAutomaticAnnotationAndToleranceChangesDoNotAffectGeometry()
+ {
+ var source = Source;
+ var start = source.IndexOf(" Pmi {", StringComparison.Ordinal);
+ var end = source.IndexOf("\n }", start, StringComparison.Ordinal) + "\n }".Length;
+ source = source.Remove(start, end - start);
+ var before = FirmamentBuildAndExport.CompileSource(source, null);
+ var after = FirmamentBuildAndExport.CompileSource(source.Replace("+0.10mm -0.05mm", "+0.20mm -0.15mm"), null);
+ Assert.True(before.IsSuccess);
+ Assert.True(after.IsSuccess);
+ Assert.Equal(before.Value.StepText, after.Value.StepText);
+ Assert.Equal(0, Step242SemanticPmiInspector.Inspect(after.Value.StepText).DimensionCount);
+ }
+
+ [Theory]
+ [InlineData("8mm tol 0.1deg", FirmamentV2Parser.ToleranceUnitMismatch)]
+ [InlineData("8mm tol -0.1mm", FirmamentV2Parser.ToleranceNegativeBilateral)]
+ [InlineData("8mm tol +0.1mm", FirmamentV2Parser.ToleranceMissingMinus)]
+ [InlineData("8deg tol 0.1mm", FirmamentV2Parser.ExpressionTypeMismatch)]
+ [InlineData("missing tol 0.1mm", FirmamentV2Parser.ExpressionUnknownSymbol)]
+ [InlineData("8mm / 0 tol 0.1mm", FirmamentV2Parser.ExpressionDivisionByZero)]
+ public void InvalidRecordRequirementRejectsParseAndBuildAtOriginalSource(string initializer, string code)
+ {
+ var source = Source.Replace("8mm tol +0.10mm -0.05mm", initializer);
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.Contains(code, parsed.Diagnostics);
+ Assert.Contains(parsed.SyntaxDiagnostics, d => d.Code == code && d.SourceSpan is not null);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void DerivedRecordReplacesAllowanceAndPreservesTheOverrideOrigin()
+ {
+ var source = Source.Replace("Template<spec:", "Static intermediate = standardBore with { width: 40mm }\nStatic revised = intermediate with { diameter: 8mm tol 0.2mm }\nTemplate<spec:")
+ .Replace("spec: standardBore>", "spec: revised>");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var pmi = Assert.Single(parsed.Document!.BoundPmi!.Dimensions);
+ Assert.Equal(0.2, pmi.DimensionTolerance!.Plus);
+ Assert.Equal(0.2, pmi.DimensionTolerance.Minus);
+ Assert.Contains(pmi.DimensionOrigins, o => source.Substring(o.SourceSpan.Start, o.SourceSpan.Length).Contains("tol 0.2mm", StringComparison.Ordinal));
+ Assert.True(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void NestedRecordFieldsAndTemplateLocalScalarAliasRetainRequirement()
+ {
+ var source = Source.Replace("Template<spec: BoreSpec>", "Record ProductSpec { bore: BoreSpec }\nStatic packaged: ProductSpec { bore: standardBore }\nTemplate<spec: ProductSpec>")
+ .Replace("spec.width", "spec.bore.width").Replace("spec.diameter", "spec.bore.diameter")
+ .Replace("spec: standardBore>", "spec: packaged>")
+ .Replace(" Box Body", " Static drilling: Length = spec.bore.diameter\n Box Body")
+ .Replace("Drill(diameter: spec.bore.diameter)", "Drill(diameter: drilling)");
+ var compiled = FirmamentBuildAndExport.CompileSource(source, null);
+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics.Select(d => d.Message)));
+ var pmi = Assert.Single(FirmamentV2Parser.Parse(source).Document!.BoundPmi!.Dimensions);
+ Assert.Equal(0.10, pmi.DimensionTolerance!.Plus);
+ Assert.Equal(0.05, pmi.DimensionTolerance.Minus);
+ }
+
+ [Fact]
+ public void ScalarTemplateDefaultsUseTheSameCheckedValueEnvironment()
+ {
+ var source = Source.Replace("Template<spec: BoreSpec>", "Static nominal: Length = 8mm tol +0.10mm -0.05mm\nTemplate<diameter: Length = nominal, width: Length = 40mm>")
+ .Replace("spec.diameter", "diameter").Replace("spec.width", "width")
+ .Replace("PlateFamily<spec: standardBore>", "PlateFamily<>");
+ var compiled = FirmamentBuildAndExport.CompileSource(source, null);
+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(0.10, Assert.Single(FirmamentV2Parser.Parse(source).Document!.BoundPmi!.Dimensions).DimensionTolerance!.Plus);
+ }
+
+ [Fact]
+ public void NominalRequireAndArithmeticDoNotPretendToComputeToleranceStacks()
+ {
+ var source = Source.Replace(" units: mm", " units: mm\n Require admitted => spec.diameter >= 8mm")
+ .Replace("let inspection: Length = diameter", "let inspection: Length = diameter + 0mm");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.Contains(parsed.SyntaxDiagnostics, d => d.Code == FirmamentV2Parser.ToleranceDroppedThroughArithmetic && d.Severity == "warning");
+ Assert.True(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void GeometryOutsideProjectedRequirementRejectsWithOriginalRequirementProvenance()
+ {
+ var source = Source.Replace("diameter: inspection", "diameter: 9mm");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ var diagnostic = Assert.Single(parsed.SyntaxDiagnostics, d => d.Code == "firmament-v2-pmi-typed-dimension-unsatisfied");
+ Assert.Contains("standardBore.diameter", diagnostic.Message);
+ Assert.NotNull(diagnostic.SourceSpan);
+ Assert.Contains("tol +0.10mm -0.05mm", source.Substring(diagnostic.SourceSpan.Start, diagnostic.SourceSpan.Length));
+ Assert.False(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void WholeTypedRecordCanCrossTemplateAndFeatureParameterBoundaries()
+ {
+ var source = Source.Replace("Feature Drill(diameter: Length)", "Feature Drill(spec: BoreSpec)")
+ .Replace("let inspection: Length = diameter", "let inspection: Length = spec.diameter")
+ .Replace("Drill(diameter: spec.diameter)", "Drill(spec: spec)");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.Contains(parsed.Document!.BoundLets!, v => v.Origins.Any(o => o.Binding == "Template PlateFamily.spec.diameter")
+ && v.Origins.Any(o => o.Binding == "Feature Drill.spec.diameter") && v.Tolerance?.Plus == 0.1);
+ Assert.True(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ var wrongType = source.Replace("Feature Drill(spec: BoreSpec)", "Record OtherSpec { diameter: Length }\nFeature Drill(spec: OtherSpec)");
+ Assert.False(FirmamentBuildAndExport.CompileSource(wrongType, null).IsSuccess);
+ }
+
+ [Fact]
+ public void NestedTemplateForwardingPreservesRecordRequirementIdentity()
+ {
+ var source = Source.Replace("Model TolerancedProduct = PlateFamily<spec: standardBore>", """
+ Template<outer: BoreSpec> Model Forward {
+ Model Core = PlateFamily<spec: outer>
+ }
+ Model TolerancedProduct = Forward<outer: standardBore>
+ """);
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var dimension = Assert.Single(parsed.Document!.BoundPmi!.Dimensions);
+ Assert.Equal("standardBore.diameter", dimension.ProjectionSource);
+ Assert.Contains(dimension.DimensionOrigins, o => o.Binding == "Template Forward.outer.diameter");
+ Assert.Contains(dimension.DimensionOrigins, o => o.Binding == "Template PlateFamily.spec.diameter");
+ Assert.True(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void RecordMembersAlsoBindDirectGeometryAndExplicitPmiWithoutTemplates()
+ {
+ var source = Source[..Source.IndexOf("Template<", StringComparison.Ordinal)] + """
+ Model DirectRecord {
+ units: mm
+ Box Body { size: [standardBore.width, 30mm, 8mm] }
+ Modify Body {
+ Hole<Shaft> Mount { on: +Z center: Point2(0mm,0mm) diameter: standardBore.diameter end: ThroughAll }
+ }
+ Pmi { HoleDiameter MountSize { target: Mount dimension: standardBore.diameter } }
+ }
+ """;
+ var compiled = FirmamentBuildAndExport.CompileSource(source, null);
+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(0.05, Assert.Single(FirmamentV2Parser.Parse(source).Document!.BoundPmi!.Dimensions).DimensionTolerance!.Minus);
+ }
+
+ [Fact]
+ public void ValueSubstitutionPreservesLabelsLocalBindersAndQuotedStrings()
+ {
+ var source = Source.Replace("Template<spec: BoreSpec>", "Template<spec: BoreSpec, diameter: Length = 8mm, label: String = \"diameter\">")
+ .Replace(" units: mm", " units: mm\n Static message: String = label");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.Equal("diameter", parsed.Document!.BoundLets!.Single(v => v.Name == "message").Value.Value);
+ Assert.True(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void StructSpecializationRetainsTheSameRequirementAndNominalGeometry()
+ {
+ var source = Source.Replace("Model PlateFamily", "Struct PlateFamily")
+ .Replace("Model TolerancedProduct =", "Struct TolerancedProduct =");
+ var compiled = FirmamentBuildAndExport.CompileSource(source, null);
+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(0.1, Assert.Single(FirmamentV2Parser.Parse(source).Document!.BoundPmi!.Dimensions).DimensionTolerance!.Plus);
+ }
+
+ [Fact]
+ public void AnExplicitNewAllowanceOwnsItsRequirementWhileKeepingItsInputProvenance()
+ {
+ var source = Source.Replace("Static standardBore:", "Static nominal: Length = 8mm tol 0.01mm\nStatic standardBore:")
+ .Replace("diameter: 8mm tol +0.10mm -0.05mm", "diameter: nominal tol +0.10mm -0.05mm");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var requirement = Assert.Single(parsed.Document!.BoundPmi!.Dimensions);
+ Assert.Equal("standardBore.diameter", requirement.ProjectionSource);
+ Assert.Contains(requirement.DimensionOrigins, o => o.Binding == "nominal");
+ Assert.Equal(0.10, requirement.DimensionTolerance!.Plus);
+ Assert.True(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void LegacyVersionMetadataDoesNotReplaceARealArithmeticWarningWithUnboundSyntaxErrors()
+ {
+ var source = Source.Replace(" width: Length", " width: Length\n revision: Version")
+ .Replace(" width: 40mm", " width: 40mm\n revision: 1.0.0")
+ .Replace("let inspection: Length = diameter", "let inspection: Length = diameter + 0mm");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.Contains(parsed.SyntaxDiagnostics, d => d.Code == FirmamentV2Parser.ToleranceDroppedThroughArithmetic && d.Severity == "warning");
+ Assert.DoesNotContain(parsed.SyntaxDiagnostics, d => d.Severity is "error" or "fatal");
+ Assert.True(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void UnrelatedLegacyRecordIntegerDataKeepsItsExistingLiteralRange()
+ {
+ var source = Source.Replace(" width: Length", " width: Length\n serial: Int")
+ .Replace(" width: 40mm", " width: 40mm\n serial: 3000000000");
+ var compiled = FirmamentBuildAndExport.CompileSource(source, null);
+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(FirmamentBuildAndExport.CompileSource(Source, null).Value.StepText, compiled.Value.StepText);
+ }
+
+ [Fact]
+ public void DuplicateRecordRequirementsDoNotSilentlySelectTheLastValue()
+ {
+ var source = Source.Replace(" width: 40mm", " diameter: 9mm tol 0.2mm\n width: 40mm");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.Contains(parsed.SyntaxDiagnostics, d => d.Code == "firmament-template-record-duplicate-field:diameter" && d.SourceSpan is not null);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void LegacyRecordCollectionsCannotEraseAnUnsupportedTolerance()
+ {
+ var source = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(
+ "fixtures/Regression/CompileTimeValues/collection-tolerance.firmament"));
+ var before = FirmamentBuildAndExport.CompileSource(source.Replace(" tol 0.1mm", ""), null);
+ Assert.True(before.IsSuccess, string.Join("\n", before.Diagnostics.Select(d => d.Message)));
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ var diagnostic = Assert.Single(parsed.SyntaxDiagnostics, d => d.Code == FirmamentV2Parser.ToleranceUnsupported);
+ Assert.NotNull(diagnostic.SourceSpan);
+ Assert.Equal("tol 0.1mm", source.Substring(diagnostic.SourceSpan.Start, diagnostic.SourceSpan.Length));
+ Assert.False(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void CyclicRecordDataRejectsInsteadOfRecursingDuringArgumentFlattening()
+ {
+ var source = Source.Replace(" width: Length", " width: Length\n next: BoreSpec")
+ .Replace(" width: 40mm", " width: 40mm\n next: standardBore");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.Contains(parsed.SyntaxDiagnostics, d => d.Code == "firmament-template-record-cycle:standardBore" && d.SourceSpan is not null);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+
+ [Fact]
+ public void WholeNestedRecordViewsRetainEveryTemplateAndFeatureReceipt()
+ {
+ var source = Source.Replace("Template<spec: BoreSpec>", "Record ProductSpec { bore: BoreSpec }\nStatic packaged: ProductSpec { bore: standardBore }\nTemplate<spec: ProductSpec>")
+ .Replace("Feature Drill(diameter: Length)", "Feature Drill(spec: ProductSpec)")
+ .Replace("let inspection: Length = diameter", "let inspection: Length = spec.bore.diameter")
+ .Replace("spec.width", "spec.bore.width").Replace("dimension: spec.diameter", "dimension: spec.bore.diameter")
+ .Replace("Drill(diameter: spec.diameter)", "Drill(spec: spec)").Replace("spec: standardBore>", "spec: packaged>");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.Contains(parsed.Document!.BoundLets!, v => v.Origins.Any(o => o.Binding == "Template PlateFamily.spec.bore.diameter")
+ && v.Origins.Any(o => o.Binding == "Feature Drill.spec.bore.diameter") && v.Tolerance?.Plus == 0.10);
+ Assert.True(FirmamentBuildAndExport.CompileSource(source, null).IsSuccess);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs
new file mode 100644
index 00000000..89152500
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs
@@ -0,0 +1,354 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using System.Collections.Immutable;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>
+/// Per-compilation scalar environment shared by Static, Record, Template and Feature binding.
+/// Checked values travel through existing expansion as opaque identifiers, never as stripped
+/// nominal strings. The mechanical binder consumes their nominal AST and PMI consumes their IR.
+/// This is not an evaluator: all scalar semantics belong to the existing typed dependency binder.
+/// </summary>
+internal sealed class FirmamentCompileTimeValues(string source)
+{
+ private readonly Dictionary<string, FirmamentV2BoundLet> values = new(StringComparer.Ordinal);
+ private readonly HashSet<string> identifiers = FirmamentLanguageAnalysisService.Lex(source)
+ .Where(t => t.Shape == "identifier").Select(t => t.Text).ToHashSet(StringComparer.Ordinal);
+ private readonly List<FirmamentV2ValidationDiagnostic> diagnostics = [];
+ private readonly Dictionary<string, DeclarationSyntax> definitions = new(StringComparer.Ordinal);
+ private int nextIdentity;
+ private IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes = new Dictionary<string, TemplateRecordTypeIr>();
+ private readonly Dictionary<string, TemplateStaticRecordIr> recordValues = new(StringComparer.Ordinal);
+ private readonly IReadOnlyDictionary<string, FirmamentV2SourceSpan> originalScopes = OriginalScopes(source);
+
+ internal IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics => diagnostics;
+
+ internal void BindExpandedScalars(string expanded, List<string> codes)
+ {
+ var declarations = Scope(FirmamentSyntaxParser.Parse(expanded).Document.Statements)
+ .Where(d => d.Type.Name.Text == "Static" && d.Name is not null && d.Initializer is not null
+ && !definitions.ContainsKey(d.Name.Text)
+ && d.Body is null && d.Initializer is not (ObjectSyntax or WithSyntax or IndexSyntax)
+ && (d.Annotation is null || IsScalar(FirmamentSyntaxValues.Reference(d.Annotation) ?? ""))).ToArray();
+ if (declarations.Length == 0) return;
+ var bound = FirmamentV2Parser.BindCompileTimeScalars(declarations, expanded, "inline", codes, values.Values.ToArray());
+ foreach (var diagnostic in bound.Diagnostics)
+ {
+ var original = originalScopes.GetValueOrDefault("Static " + diagnostic.Target);
+ diagnostics.Add(diagnostic with { SourceSpan = original, IsOriginalSource = original is not null,
+ LocationNote = original is null ? "Expanded scalar binding; original expression location is unavailable." : "Location identifies the original Static declaration." });
+ }
+ foreach (var value in bound.Values.Where(v => declarations.Any(d => d.Name!.Text == v.Name)))
+ {
+ var original = originalScopes.GetValueOrDefault("Static " + value.Name);
+ values[value.Name] = value with { Origins = original is null ? value.Origins
+ : value.Origins.Append(new("inline", original, "Static " + value.Name)).ToArray() };
+ }
+ }
+
+ internal void Initialize(IReadOnlyDictionary<string, TemplateRecordTypeIr> records, List<string> codes)
+ {
+ var syntax = FirmamentSyntaxParser.Parse(source);
+ var declarations = Scope(syntax.Document.Statements).ToArray();
+ foreach (var d in declarations.Where(d => d.Type.Name.Text == "Static" && d.Name is not null))
+ {
+ var type = FirmamentSyntaxValues.Reference(d.Annotation);
+ if (d.Initializer is not null && d.Body is null && d.Initializer is not (ObjectSyntax or WithSyntax or IndexSyntax)
+ && (d.Annotation is null || type is not null && FirmamentV2Parser.TryParseLetType(type, out _)))
+ Add(d.Name!.Text, d);
+ }
+ var statics = declarations.Where(d => d.Type.Name.Text == "Static" && d.Name is not null).ToArray();
+ var visiting = new HashSet<string>(StringComparer.Ordinal);
+ var recordTypeNames = new Dictionary<string, string>(StringComparer.Ordinal);
+ void Record(DeclarationSyntax d, int depth = 0)
+ {
+ if (depth > 128)
+ {
+ var code = FirmamentV2TemplateExpansion.Prefix + "record-depth-limit:" + d.Name!.Text;
+ codes.Add(code);
+ diagnostics.Add(new(code, "error", "Compile-time Record nesting exceeds the supported depth of 128.", Target: d.Name.Text)
+ { SourceSpan = d.Span, IsOriginalSource = true, Stage = "Binding" });
+ return;
+ }
+ if (!visiting.Add(d.Name!.Text)) return; // The Record owner diagnoses derived-record cycles.
+ var type = FirmamentSyntaxValues.Reference(d.Annotation);
+ BlockSyntax? body = d.Body ?? (d.Initializer as ObjectSyntax)?.Body;
+ if (d.Initializer is WithSyntax w && FirmamentSyntaxValues.Reference(w.Target) is { } parent)
+ {
+ var original = statics.FirstOrDefault(s => s.Name!.Text == parent);
+ if (original is not null)
+ {
+ Record(original, depth + 1);
+ type ??= recordTypeNames.GetValueOrDefault(parent) ?? FirmamentSyntaxValues.Reference(original.Annotation);
+ foreach (var field in definitions.Where(p => p.Key.StartsWith(parent + ".", StringComparison.Ordinal)).ToArray())
+ Add(d.Name.Text + field.Key[parent.Length..], field.Value);
+ }
+ body = w.Body;
+ }
+ if (type is null || !records.TryGetValue(type, out var schema) || body is null) return;
+ recordTypeNames[d.Name.Text] = type;
+ foreach (var field in body.Statements.OfType<FieldSyntax>())
+ if (schema.Fields.TryGetValue(field.Name.Text, out var fieldType)
+ && FirmamentV2Parser.TryParseLetType(fieldType, out _))
+ {
+ var name = d.Name.Text + "." + field.Name.Text;
+ if (LegacyWideInteger(fieldType, Slice(field.Value))) definitions.Remove(name);
+ else Add(name, Scalar(name, fieldType, field.Value, field.Span));
+ }
+ else if (schema.Fields.TryGetValue(field.Name.Text, out fieldType) && records.ContainsKey(fieldType)
+ && FirmamentSyntaxValues.Reference(field.Value) is { } nested)
+ {
+ var original = statics.FirstOrDefault(s => s.Name!.Text == nested);
+ if (original is null) continue;
+ Record(original, depth + 1);
+ foreach (var child in definitions.Where(p => p.Key.StartsWith(nested + ".", StringComparison.Ordinal)).ToArray())
+ Add(d.Name.Text + "." + field.Name.Text + child.Key[nested.Length..], child.Value);
+ }
+ }
+ foreach (var d in statics) Record(d);
+ // A legacy collection reader may retain only a literal prefix. Every tol
+ // in a Static value must belong to a checked scalar initializer before
+ // that reader can erase the containing declaration.
+ var admittedTolerances = definitions.Values.Where(d => d.Initializer is not null)
+ .SelectMany(d => FirmamentSyntaxTraversal.Expressions(d.Initializer!)).OfType<ToleranceSyntax>()
+ .Select(t => t.ToleranceSpan).ToHashSet();
+ foreach (var declaration in statics)
+ foreach (var tolerance in FirmamentSyntaxTraversal.Expressions(new DocumentSyntax("inline", [declaration], [], declaration.Span))
+ .OfType<ToleranceSyntax>().Where(t => !admittedTolerances.Contains(t.ToleranceSpan)))
+ {
+ codes.Add(FirmamentV2Parser.ToleranceUnsupported);
+ diagnostics.Add(new(FirmamentV2Parser.ToleranceUnsupported, "error",
+ $"Tolerance in Static '{declaration.Name!.Text}' is not admitted by its collection or value owner. Declare a scalar Static or typed Record requirement; collection/Table tolerance propagation is not yet supported.", Target: declaration.Name.Text)
+ { SourceSpan = tolerance.ToleranceSpan, IsOriginalSource = true, Stage = "Binding" });
+ }
+ if (definitions.Count == 0) return;
+ var bound = FirmamentV2Parser.BindCompileTimeScalars(definitions.Select(p => p.Value with { Name = new(p.Key, p.Value.Name!.Span) }).ToArray(), source, "inline", codes);
+ diagnostics.AddRange(bound.Diagnostics.Select(d => d with { IsOriginalSource = true }));
+ foreach (var value in bound.Values)
+ {
+ var definition = definitions[value.Name];
+ var origins = new List<FirmamentV2ValueOrigin>();
+ foreach (var dependency in value.Dependencies ?? new HashSet<string>())
+ if (definitions.TryGetValue(dependency, out var origin)) origins.Add(new("inline", origin.Initializer?.Span ?? origin.Span, dependency));
+ origins.Add(new("inline", definition.Initializer?.Span ?? definition.Span, definition.Name!.Text));
+ if (definition.Name.Text != value.Name) origins.Add(new("inline", definition.Span, value.Name));
+ if (definition.Initializer is ToleranceSyntax)
+ origins = origins.OrderByDescending(o => o.Binding == definition.Name.Text).ToList();
+ values[value.Name] = value with { Origins = origins.Distinct().ToArray() };
+ }
+ void Add(string name, DeclarationSyntax declaration) => definitions[name] = declaration;
+ }
+
+ internal bool IsScalar(string type) => FirmamentV2Parser.TryParseLetType(type, out _);
+
+ internal bool TryTransfer(string expression, string type, string binding, FirmamentV2SourceSpan span,
+ List<string> codes, out string transported)
+ {
+ var scopeName = binding.Split('.')[0];
+ var originalConsumer = originalScopes.TryGetValue(scopeName, out var originalSpan);
+ if (originalConsumer) span = originalSpan!;
+ transported = expression;
+ if (!FirmamentV2Parser.TryParseLetType(type, out _)) return false;
+ // Existing Template/Record Int literals admit Int64, whereas Model Static's
+ // graph currently uses Int32. Do not narrow unrelated admitted literal data.
+ if (LegacyWideInteger(type, expression)) return false;
+ FirmamentV2BoundLet? value;
+ if (!values.TryGetValue(expression.Trim(), out value))
+ {
+ var parsed = FirmamentSyntaxParser.ParseExpression(expression);
+ if (parsed.Expression is null || parsed.Diagnostics.Any(d => d.Severity is "error" or "fatal")) return false;
+ var name = FreshName();
+ var localCodes = new List<string>();
+ var bound = FirmamentV2Parser.BindCompileTimeScalars([Scalar(name, type, parsed.Expression, parsed.Expression.Span)],
+ expression, "inline", localCodes, values.Values.ToArray());
+ codes.AddRange(localCodes);
+ diagnostics.AddRange(bound.Diagnostics.Select(d => d with { SourceSpan = originalConsumer ? span : null, IsOriginalSource = originalConsumer,
+ Target = binding, LocationNote = originalConsumer ? "Compile-time argument binding; location identifies the original enclosing declaration."
+ : "Expanded compile-time argument; original consumer location is unavailable." }));
+ value = bound.Values.FirstOrDefault(v => v.Name == name);
+ if (value is not null && parsed.Expression is ToleranceSyntax && value.Tolerance is { } freshTolerance)
+ {
+ var originSpan = originalConsumer ? span : new FirmamentV2SourceSpan(0, source.Length);
+ value = value with { Tolerance = freshTolerance with { SourceSpan = originSpan },
+ Origins = new[] { new FirmamentV2ValueOrigin("inline", originSpan, binding,
+ originalConsumer ? "Location identifies the enclosing declaration of the new requirement." : "Original consumer location is unavailable; location identifies the source module.") }.Concat(value.Origins).ToArray() };
+ }
+ if (value is not null && value.Origins.Count == 0)
+ value = value with { SourceSpan = originalConsumer ? span : new(0, source.Length),
+ Origins = [new("inline", originalConsumer ? span : new(0, source.Length), binding,
+ originalConsumer ? "Location identifies the enclosing declaration." : "Original consumer location is unavailable; location identifies the source module.")],
+ Tolerance = value.Tolerance is { } tolerance ? tolerance with { SourceSpan = originalConsumer ? span : new(0, source.Length) } : null };
+ }
+ if (value is null || !FirmamentV2Parser.TryParseLetType(type, out var expected)) return false;
+ if (value.Type != expected)
+ {
+ TypeError(binding, type, value.Type.ToString(), codes);
+ return false;
+ }
+ // Ordinary literal specialization keeps its established spelling and geometry identities.
+ if (value.Tolerance is null)
+ {
+ transported = IsLiteral(expression) ? expression : Nominal(value);
+ return true;
+ }
+ var identity = FreshName();
+ values[identity] = value with { Name = identity,
+ Origins = value.Origins.LastOrDefault()?.Binding == binding ? value.Origins
+ : value.Origins.Append(new("inline", originalConsumer ? span : value.Origins.FirstOrDefault()?.SourceSpan ?? new(0, source.Length), binding,
+ originalConsumer ? "Location identifies the enclosing declaration." : "Original consumer location is unavailable; location identifies the requirement or source module.")).ToArray() };
+ transported = identity;
+ return true;
+ }
+
+ internal string Field(string record, string field, string expression, string type, FirmamentV2SourceSpan span, List<string> codes)
+ {
+ if (!IsScalar(type)) return expression;
+ if (values.TryGetValue(record + "." + field, out var value) && value.Tolerance is null && IsLiteral(expression)) return expression;
+ return TryTransfer(values.ContainsKey(record + "." + field) ? record + "." + field : expression,
+ type, record + "." + field, span, codes, out var result) ? result : expression;
+ }
+
+ internal IReadOnlyList<FirmamentV2BoundLet> MaterialInputs(string expanded)
+ {
+ var names = FirmamentLanguageAnalysisService.Lex(expanded).Select(t => t.Text).ToHashSet(StringComparer.Ordinal);
+ foreach (var member in FirmamentSyntaxTraversal.Expressions(FirmamentSyntaxParser.Parse(expanded).Document).OfType<MemberSyntax>())
+ if (FirmamentSyntaxValues.Reference(member) is { } name) names.Add(name);
+ return values.Values.Where(v => names.Contains(v.Name)).ToArray();
+ }
+
+ internal void SetRecords(IReadOnlyDictionary<string, TemplateRecordTypeIr> types, IReadOnlyDictionary<string, TemplateStaticRecordIr> records)
+ {
+ recordTypes = types;
+ foreach (var record in records) recordValues[record.Key] = record.Value;
+ }
+
+ internal bool IsRecordType(string type) => recordTypes.ContainsKey(type);
+ internal bool TryRecord(string reference, out TemplateStaticRecordIr record) => recordValues.TryGetValue(reference, out record!);
+
+ internal string RecordReference(TemplateStaticRecordIr record, ImmutableDictionary<string, string> fields)
+ {
+ if (!fields.Values.Any(field => values.TryGetValue(field, out var value) && value.Tolerance is not null)) return record.Name;
+ var name = FreshName();
+ recordValues[name] = record with { Name = name, Fields = fields, AuthoredName = record.AuthoredName ?? record.Name };
+ return name;
+ }
+
+ internal bool TryRecordTransfer(string expression, string type, string binding, FirmamentV2SourceSpan span,
+ List<string> codes, out IReadOnlyDictionary<string, string> fields)
+ {
+ fields = new Dictionary<string, string>();
+ if (!recordValues.TryGetValue(expression, out var record) || record.TypeName != type)
+ {
+ TypeError(binding, type, record?.TypeName ?? expression, codes);
+ return false;
+ }
+ var before = codes.Count;
+ var result = FirmamentV2TemplateExpansion.FlattenRecordFields(record, recordTypes, recordValues, codes).ToBuilder();
+ if (codes.Count > before)
+ {
+ foreach (var code in codes.Skip(before).Distinct()) RecordError(record.AuthoredName ?? record.Name, "", code,
+ $"Record '{record.AuthoredName ?? record.Name}' contains a cyclic reference or exceeds the supported nesting depth of 128. Use finite, acyclic Record data.");
+ return false;
+ }
+ foreach (var field in result.ToArray())
+ {
+ var schema = recordTypes[type];
+ string? fieldType = null;
+ foreach (var part in field.Key.Split('.'))
+ {
+ if (!schema.Fields.TryGetValue(part, out fieldType)) break;
+ if (recordTypes.TryGetValue(fieldType, out var nested)) schema = nested;
+ }
+ if (fieldType is not null && IsScalar(fieldType)
+ && TryTransfer(field.Value, fieldType, binding + "." + field.Key, span, codes, out var transported))
+ result[field.Key] = transported;
+ }
+ fields = result.ToImmutable();
+ return true;
+ }
+
+ internal bool Contains(string expression) => values.ContainsKey(expression.Trim());
+
+ internal void RecordError(string record, string field, string code, string message)
+ {
+ var span = definitions.GetValueOrDefault(record + "." + field)?.Span
+ ?? originalScopes.GetValueOrDefault("Static " + record);
+ diagnostics.Add(new(code, "error", message, field, record) { SourceSpan = span,
+ IsOriginalSource = span is not null, Stage = "Binding" });
+ }
+
+ private void TypeError(string binding, string expected, string actual, List<string> codes)
+ {
+ var original = originalScopes.GetValueOrDefault(binding.Split('.')[0]);
+ codes.Add(FirmamentV2Parser.ExpressionTypeMismatch);
+ diagnostics.Add(new(FirmamentV2Parser.ExpressionTypeMismatch, "error",
+ $"Compile-time input '{binding}' requires {expected}; supplied value has type {actual}.", Target: binding)
+ { SourceSpan = original, IsOriginalSource = original is not null, Stage = "Binding",
+ LocationNote = original is null ? "Expanded input binding; original consumer location is unavailable."
+ : "Location identifies the original parameter's enclosing declaration." });
+ }
+ internal bool HasType(string expression, string type) => values.TryGetValue(expression.Trim(), out var value)
+ && FirmamentV2Parser.TryParseLetType(type, out var expected) && value.Type == expected;
+ internal string NominalExpression(string expression) => values.TryGetValue(expression.Trim(), out var value) ? Nominal(value)
+ : recordValues.TryGetValue(expression.Trim(), out var record) ? record.AuthoredName ?? record.Name : expression;
+
+ private static bool IsLiteral(string expression) => FirmamentSyntaxParser.ParseExpression(expression).Expression is
+ LiteralSyntax or QuantitySyntax or UnarySyntax { Operand: LiteralSyntax or QuantitySyntax };
+
+ private string Slice(ExpressionSyntax expression) => source.Substring(expression.Span.Start, expression.Span.Length);
+ private static bool LegacyWideInteger(string type, string expression) => type is "Int" or "int"
+ && long.TryParse(expression, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var value)
+ && (value < int.MinValue || value > int.MaxValue);
+
+ private string FreshName()
+ {
+ string name;
+ do name = "__firmamentValue" + nextIdentity++; while (!identifiers.Add(name));
+ return name;
+ }
+
+ private static string Nominal(FirmamentV2BoundLet value) => 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", System.Globalization.CultureInfo.InvariantCulture) + value.Value.Unit
+ };
+
+ private static DeclarationSyntax Scalar(string name, string type, ExpressionSyntax expression, FirmamentV2SourceSpan span) =>
+ new(new(new("Static", span), [], span), new(name, span), [], [], new ReferenceSyntax(new(type, span), span),
+ null, [], expression, null, false, span);
+
+ private static IEnumerable<DeclarationSyntax> Scope(IEnumerable<StatementSyntax> statements)
+ {
+ foreach (var d in statements.OfType<DeclarationSyntax>())
+ {
+ if (d.Modifiers.Any(m => m.Name.Text is "Template" or "Concept") || d.Type.Name.Text is "Feature" or "Template") continue;
+ yield return d;
+ if (d.Type.Name.Text == "Model" && d.Body is not null)
+ foreach (var child in Scope(d.Body.Statements)) yield return child;
+ }
+ }
+
+ private static IReadOnlyDictionary<string, FirmamentV2SourceSpan> OriginalScopes(string authored)
+ {
+ var result = new Dictionary<string, FirmamentV2SourceSpan>(StringComparer.Ordinal);
+ var ambiguous = new HashSet<string>(StringComparer.Ordinal);
+ void Add(string name, FirmamentV2SourceSpan span)
+ {
+ if (ambiguous.Contains(name)) return;
+ if (!result.TryAdd(name, span)) { result.Remove(name); ambiguous.Add(name); }
+ }
+ void Visit(IEnumerable<StatementSyntax> statements)
+ {
+ foreach (var d in statements.OfType<DeclarationSyntax>())
+ {
+ if (d.Type.Name.Text == "Feature" && d.Name is not null) Add("Feature " + d.Name.Text, d.Span);
+ if (d.Modifiers.Any(m => m.Name.Text == "Template") && d.Name is not null) Add("Template " + d.Name.Text, d.Span);
+ if (d.Type.Name.Text == "Static" && d.Name is not null) Add("Static " + d.Name.Text, d.Span);
+ if (d.Body is not null) Visit(d.Body.Statements);
+ }
+ }
+ Visit(FirmamentSyntaxParser.Parse(authored).Document.Statements);
+ return result;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 491fed24..31a62422 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -38,7 +38,11 @@ public sealed record FirmamentV2LetRecordField(string Name, FirmamentV2Primitive
public FirmamentV2LiteralValue LiteralValue => ValueExpression is FirmamentV2LiteralExpression literal ? literal.Value : throw new InvalidOperationException("Record field value is not a literal.");
}
public sealed record FirmamentV2BoundExpression(FirmamentV2PrimitiveType InferredType, FirmamentV2LiteralValue Value, IReadOnlySet<string> Dependencies, FirmamentV2SourceSpan SourceSpan, FirmamentV2Tolerance? AliasTolerance = null, bool UsesTolerancedValueInArithmetic = false);
-public sealed record FirmamentV2BoundLet(string Name, FirmamentV2PrimitiveType Type, FirmamentV2LiteralValue Value, FirmamentV2SourceSpan SourceSpan, FirmamentV2BoundExpression? Expression = null, IReadOnlySet<string>? Dependencies = null, FirmamentV2Tolerance? Tolerance = null);
+public sealed record FirmamentV2ValueOrigin(string SourceFile, FirmamentV2SourceSpan SourceSpan, string Binding, string? LocationNote = null);
+public sealed record FirmamentV2BoundLet(string Name, FirmamentV2PrimitiveType Type, FirmamentV2LiteralValue Value, FirmamentV2SourceSpan SourceSpan, FirmamentV2BoundExpression? Expression = null, IReadOnlySet<string>? Dependencies = null, FirmamentV2Tolerance? Tolerance = null)
+{
+ public IReadOnlyList<FirmamentV2ValueOrigin> Origins { get; init; } = [];
+}
public sealed record FirmamentV2BoundLetRecord(string Name, IReadOnlyDictionary<string, FirmamentV2BoundLet> Fields, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2ConceptApplication(string FamilyName, string ConceptName, FirmamentV2SourceSpan SourceSpan);
@@ -260,7 +264,10 @@ public sealed record FirmamentV2PmiBlock(IReadOnlyList<FirmamentV2PmiRecord> Rec
public sealed record FirmamentV2PmiRecord(FirmamentV2PmiKind Kind, string Name, IReadOnlyDictionary<string, FirmamentV2PmiField> Fields, FirmamentV2SourceSpan SourceSpan, FirmamentV2BoundPmiRecord? Bound = null, FirmamentV2PmiProjection? Projection = null);
public sealed record FirmamentV2PmiField(string Name, string Source, FirmamentV2SourceSpan SourceSpan, FirmamentV2ValueExpression? ValueExpression = null);
public sealed record FirmamentV2BoundPmiBlock(IReadOnlyList<FirmamentV2BoundPmiRecord> Datums, IReadOnlyList<FirmamentV2BoundPmiRecord> Dimensions, IReadOnlyList<FirmamentV2BoundPmiRecord> Controls, IReadOnlyList<string> Diagnostics);
-public sealed record FirmamentV2BoundPmiRecord(FirmamentV2PmiKind Kind, string Name, IReadOnlyList<string> Targets, FirmamentV2LiteralValue? DimensionValue, FirmamentV2Tolerance? DimensionTolerance, FirmamentV2LiteralValue? ControlTolerance, IReadOnlyList<string> DatumRefs, FirmamentV2SourceSpan SourceSpan, string? ProjectionSource = null, FirmamentV2HoleWallSelector? HoleWallTarget = null);
+public sealed record FirmamentV2BoundPmiRecord(FirmamentV2PmiKind Kind, string Name, IReadOnlyList<string> Targets, FirmamentV2LiteralValue? DimensionValue, FirmamentV2Tolerance? DimensionTolerance, FirmamentV2LiteralValue? ControlTolerance, IReadOnlyList<string> DatumRefs, FirmamentV2SourceSpan SourceSpan, string? ProjectionSource = null, FirmamentV2HoleWallSelector? HoleWallTarget = null)
+{
+ public IReadOnlyList<FirmamentV2ValueOrigin> DimensionOrigins { get; init; } = [];
+}
/// <summary>Reusable, validated dimensional intent. Only equality of a semantic feature property
/// to a length expectation is admitted in Preview 1.</summary>
public sealed record FirmamentV2SemanticConstraint(string Id, string Subject, string Property, FirmamentV2LiteralValue NominalValue, FirmamentV2Tolerance? Tolerance, bool ValidationSucceeded, FirmamentV2SourceSpan SourceSpan, string ExpectedProvenance);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs
index e9a01609..3d8bef95 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2FeatureExpansion.cs
@@ -40,7 +40,7 @@ internal static class FirmamentV2FeatureExpansion
IReadOnlyList<FirmamentV2FeatureInvocation> Invocations,
FirmamentV2FeatureExpansionMetrics Metrics);
- public static Result? Expand(string source, List<string> diagnostics)
+ public static Result? Expand(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null)
{
var declarations = ParseDeclarations(source, diagnostics);
var byName = declarations.ToDictionary(item => item.Name, StringComparer.Ordinal);
@@ -61,7 +61,7 @@ internal static class FirmamentV2FeatureExpansion
string ExpandCall(Declaration declaration, string argumentText, FirmamentV2SourceSpan span,
IReadOnlyList<string> stack, bool patternContext, string? resultName = null)
{
- var bound = Bind(declaration, argumentText, span.Start, diagnostics, source);
+ var bound = Bind(declaration, argumentText, span.Start, diagnostics, source, scalars);
if (bound is null) return string.Empty;
var invocationOrdinal = ordinal++;
var environment = new Dictionary<string, string>(bound, StringComparer.Ordinal);
@@ -73,12 +73,15 @@ internal static class FirmamentV2FeatureExpansion
return string.Empty;
}
var expression = Substitute(local.Expression, environment);
- if (!TypeMatches(expression, local.Type))
+ if (scalars?.IsScalar(local.Type) == true && scalars.TryTransfer(expression, local.Type,
+ $"Feature {declaration.Name}.{local.Name}", span, diagnostics, out var checkedValue))
+ environment[local.Name] = NormalizeExpression(checkedValue, local.Type);
+ else if (!TypeMatches(expression, local.Type))
{
diagnostics.Add(LocalType + $":{declaration.Name}:{local.Name}:expected-{local.Type}:actual-{DescribeType(expression)}");
return string.Empty;
}
- environment[local.Name] = NormalizeExpression(expression, local.Type);
+ else environment[local.Name] = NormalizeExpression(expression, local.Type);
}
var construction = Substitute(declaration.Construction, environment);
@@ -252,7 +255,8 @@ internal static class FirmamentV2FeatureExpansion
return result.ToImmutable();
}
- private static ImmutableDictionary<string, string>? Bind(Declaration declaration, string argumentText, int offset, List<string> diagnostics, string source)
+ private static ImmutableDictionary<string, string>? Bind(Declaration declaration, string argumentText, int offset, List<string> diagnostics, string source,
+ FirmamentCompileTimeValues? scalars = null)
{
var supplied = new Dictionary<string, string>(StringComparer.Ordinal); var position = 0;
foreach (var (raw, _) in SplitTopLevel(argumentText))
@@ -276,8 +280,19 @@ internal static class FirmamentV2FeatureExpansion
foreach (var parameter in declaration.Parameters)
if (supplied.TryGetValue(parameter.Name, out var expression))
{
+ if (scalars?.IsRecordType(parameter.Type) == true)
+ {
+ if (!scalars.TryRecordTransfer(expression, parameter.Type, $"Feature {declaration.Name}.{parameter.Name}",
+ declaration.Span, diagnostics, out var fields))
+ diagnostics.Add(ArgumentType + $":{declaration.Name}:{parameter.Name}:expected-{parameter.Type}:actual-{expression}:at-{offset}");
+ else foreach (var field in fields) supplied[parameter.Name + "." + field.Key] = field.Value;
+ continue;
+ }
if (parameter.Type == "Point2") expression = ResolvePointArgument(source, expression);
- if (!TypeMatches(expression, parameter.Type))
+ if (scalars?.IsScalar(parameter.Type) == true && scalars.TryTransfer(expression, parameter.Type,
+ $"Feature {declaration.Name}.{parameter.Name}", declaration.Span, diagnostics, out var checkedValue))
+ supplied[parameter.Name] = NormalizeExpression(checkedValue, parameter.Type);
+ else if (!TypeMatches(expression, parameter.Type))
diagnostics.Add(ArgumentType + $":{declaration.Name}:{parameter.Name}:expected-{parameter.Type}:actual-{DescribeType(expression)}:at-{offset}");
else supplied[parameter.Name] = NormalizeExpression(expression, parameter.Type);
}
@@ -324,11 +339,7 @@ internal static class FirmamentV2FeatureExpansion
}
private static string Substitute(string expression, IReadOnlyDictionary<string, string> values)
- {
- foreach (var pair in values.OrderByDescending(item => item.Key.Length))
- expression = Regex.Replace(expression, $@"\b{Regex.Escape(pair.Key)}\b(?!\s*:)", _ => pair.Value, RegexOptions.CultureInvariant);
- return expression;
- }
+ => FirmamentValueSubstitution.Apply(expression, values);
private static bool TypeMatches(string expression, string type)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
index 61628077..9228e894 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
@@ -23,7 +23,7 @@ public static partial class FirmamentV2Parser
/// follows declared material bodies; unused construction data cannot select a grammar.</summary>
private static FirmamentV2ParseResult BindMechanicalModel(DocumentSyntax syntax, DeclarationSyntax model,
string source, List<string> diagnostics, string? sourceDirectory,
- IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations)
+ IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations, FirmamentCompileTimeValues? compileTime = null)
{
if (model.Body is null || model.Name is null) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
if (model.Clauses.Count > 0 || model.Type.Arguments.Count > 0)
@@ -35,7 +35,7 @@ public static partial class FirmamentV2Parser
return ParseConceptModelingDocument(source, diagnostics, templateInstantiations);
}
var outerStatements = syntax.Statements.Where(s => !ReferenceEquals(s, model)).ToArray();
- var staticValues = BindStaticValues(syntax, model, source, diagnostics);
+ var staticValues = BindStaticValues(syntax, model, source, diagnostics, compileTime?.MaterialInputs(source));
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);
@@ -134,12 +134,13 @@ public static partial class FirmamentV2Parser
ValidateCanonicalSelectionSources(bodyText, selections, [], diagnostics);
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();
+ var locatedDiagnostics = (compileTime?.Diagnostics ?? []).Concat(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),
+ Lets: staticValues.Declarations, BoundLets: staticValues.Values,
+ TemplateInstantiations: templateInstantiations is { Count: > 0 } ? templateInstantiations : null),
diagnostics.Append("firmament-v2-unified-canonical-parsed").Append("firmament-v2-parse-succeeded").Distinct(StringComparer.Ordinal).Order().ToArray())
with { SyntaxDiagnostics = locatedDiagnostics };
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index e3a42caa..51736f53 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -364,10 +364,12 @@ public static partial class FirmamentV2Parser
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() };
+ var located = result.SyntaxDiagnostics.Where(d => d.IsOriginalSource).ToArray();
+ var expanded = result.SyntaxDiagnostics.Where(d => !d.IsOriginalSource).ToArray();
+ result = result with { SyntaxDiagnostics = unchanged ? result.SyntaxDiagnostics
+ : located.Concat(expanded.Length > 0 && original.Diagnostics.Count > 0 ? original.Diagnostics
+ : expanded.Select(d => d with { SourceSpan = null, Line = null, Column = null,
+ LocationNote = "The error occurs after expansion; original-source provenance is unavailable." })).ToArray() };
}
var hasErrors = result.Diagnostics.Any(IsFatalDiagnosticCode);
return result with
@@ -392,6 +394,7 @@ public static partial class FirmamentV2Parser
|| leading[0].Text == "{" && leading[1].Shape == "string"))
return FirmamentV2ParseResult.Failure([], FirmamentV2ParseDisposition.NotRecognized) with { ParserRoute = "LegacySerialization" };
sourceText = FirmamentSourceSpelling.Normalize(sourceText);
+ var valueSource = MaskCommentTrivia(sourceText);
sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);
var diagnostics = new List<string> { "firmament-v2-parser-invoked" };
var source = MaskCommentTrivia(sourceText);
@@ -434,26 +437,31 @@ public static partial class FirmamentV2Parser
// Modern Template specialization owns typed Record binding. Run it while
// Record and scalar Static declarations still exist, then let canonical
// static authoring erase those compile-time declarations before AIR.
- var templateExpansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics);
- if (templateExpansion is null)
+ var compileTime = new FirmamentCompileTimeValues(valueSource);
+ var templateExpansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics, compileTime);
+ if (templateExpansion is null || compileTime.Diagnostics.Any(d => d.Severity is "error" or "fatal"))
{
diagnostics.Add("firmament-v2-parse-failed");
return FirmamentV2ParseResult.Failure(
diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray(),
- v2AdmissionCandidate ? FirmamentV2ParseDisposition.RecognizedInvalid : FirmamentV2ParseDisposition.NotRecognized);
+ v2AdmissionCandidate ? FirmamentV2ParseDisposition.RecognizedInvalid : FirmamentV2ParseDisposition.NotRecognized)
+ with { SyntaxDiagnostics = compileTime.Diagnostics,
+ OwnsUnifiedAdmission = compileTime.Diagnostics.Any(d => d.Severity is "error" or "fatal") };
}
source = templateExpansion.Source;
+ compileTime.BindExpandedScalars(source, diagnostics);
// Feature is Firmament's bounded function-like abstraction. It is expanded once,
// after typed Template specialization and before static pattern lowering, so every command consumes the
// same concrete semantic declarations and no geometry callback can bypass AIR.
- var featureExpansion = FirmamentV2FeatureExpansion.Expand(source, diagnostics);
- if (featureExpansion is null)
+ var featureExpansion = FirmamentV2FeatureExpansion.Expand(source, diagnostics, compileTime);
+ if (featureExpansion is null || compileTime.Diagnostics.Any(d => d.Severity is "error" or "fatal"))
{
diagnostics.Add("firmament-v2-parse-failed");
return FirmamentV2ParseResult.Failure(
diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray(),
- FirmamentV2ParseDisposition.RecognizedInvalid);
+ FirmamentV2ParseDisposition.RecognizedInvalid) with { SyntaxDiagnostics = compileTime.Diagnostics,
+ OwnsUnifiedAdmission = compileTime.Diagnostics.Any(d => d.Severity is "error" or "fatal") };
}
source = featureExpansion.Source;
@@ -547,7 +555,7 @@ 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, compileTime))
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,7 +724,7 @@ public static partial class FirmamentV2Parser
return lets;
}
- private static bool TryParseLetType(string text, out FirmamentV2PrimitiveType type)
+ internal static bool TryParseLetType(string text, out FirmamentV2PrimitiveType type)
{
type = text switch
{
@@ -824,9 +832,10 @@ public static partial class FirmamentV2Parser
private static IReadOnlyList<FirmamentV2BoundLetRecord> BindLetRecords(IReadOnlyList<FirmamentV2LetRecordDeclaration> records) =>
records.Select(r => new FirmamentV2BoundLetRecord(r.Name, r.Fields.Where(f => f.ValueExpression is FirmamentV2LiteralExpression).Select(f => new FirmamentV2BoundLet(f.Name, f.DeclaredType, f.LiteralValue, f.SourceSpan, new FirmamentV2BoundExpression(f.DeclaredType, f.LiteralValue, new HashSet<string>(StringComparer.Ordinal), f.SourceSpan, f.Tolerance), new HashSet<string>(StringComparer.Ordinal), f.Tolerance)).ToDictionary(f => f.Name, StringComparer.Ordinal), r.SourceSpan)).ToArray();
- private static IReadOnlyList<FirmamentV2BoundLet> BindLets(IReadOnlyList<FirmamentV2LetDeclaration> lets, IReadOnlyList<FirmamentV2BoundLetRecord> records, IEnumerable<string> solidNames, List<string> diagnostics)
+ private static IReadOnlyList<FirmamentV2BoundLet> BindLets(IReadOnlyList<FirmamentV2LetDeclaration> lets, IReadOnlyList<FirmamentV2BoundLetRecord> records, IEnumerable<string> solidNames, List<string> diagnostics,
+ List<FirmamentV2ValidationDiagnostic>? located = null)
{
- var binder = new ExpressionBinder(lets, records, solidNames, diagnostics);
+ var binder = new ExpressionBinder(lets, records, solidNames, diagnostics, located);
return binder.BindLets();
}
@@ -900,8 +909,10 @@ public static partial class FirmamentV2Parser
private readonly Dictionary<string, FirmamentV2LetDeclaration> _letMap;
private readonly Dictionary<string, FirmamentV2BoundLet> _bound = new(StringComparer.Ordinal);
private readonly HashSet<string> _visiting = new(StringComparer.Ordinal);
- public ExpressionBinder(IReadOnlyList<FirmamentV2LetDeclaration> lets, IReadOnlyList<FirmamentV2BoundLetRecord> records, IEnumerable<string> solidNames, List<string> diagnostics)
- { _lets = lets; _records = records.ToDictionary(r => r.Name, StringComparer.Ordinal); _solidNames = new(solidNames, StringComparer.Ordinal); _diagnostics = diagnostics; _letMap = lets.ToDictionary(l => l.Name, StringComparer.Ordinal); }
+ private readonly List<FirmamentV2ValidationDiagnostic>? _located;
+ public ExpressionBinder(IReadOnlyList<FirmamentV2LetDeclaration> lets, IReadOnlyList<FirmamentV2BoundLetRecord> records, IEnumerable<string> solidNames, List<string> diagnostics,
+ List<FirmamentV2ValidationDiagnostic>? located = null)
+ { _lets = lets; _records = records.ToDictionary(r => r.Name, StringComparer.Ordinal); _solidNames = new(solidNames, StringComparer.Ordinal); _diagnostics = diagnostics; _letMap = lets.ToDictionary(l => l.Name, StringComparer.Ordinal); _located = located; }
public IReadOnlyList<FirmamentV2BoundLet> BindLets() { foreach (var l in _lets) Bind(l.Name); return _lets.Where(l => _bound.ContainsKey(l.Name)).Select(l => _bound[l.Name]).ToArray(); }
private FirmamentV2BoundLet? Bind(string name)
{
@@ -911,7 +922,13 @@ public static partial class FirmamentV2Parser
var expr = Eval(let.ValueExpression);
_visiting.Remove(name);
if (expr is null) return null;
- if (expr.InferredType != let.DeclaredType) { _diagnostics.Add(ExpressionTypeMismatch); _diagnostics.Add(LetTypeMismatch); return null; }
+ if (expr.InferredType != let.DeclaredType)
+ {
+ _diagnostics.Add(ExpressionTypeMismatch); _diagnostics.Add(LetTypeMismatch);
+ _located?.Add(new(ExpressionTypeMismatch, "error", $"Compile-time value '{let.Name}' requires {let.DeclaredType}, but its expression has type {expr.InferredType}.", Target: let.Name)
+ { SourceSpan = let.SourceSpan, Stage = "Binding" });
+ return null;
+ }
var tolerance = let.Tolerance ?? expr.AliasTolerance;
if (tolerance is null && expr.UsesTolerancedValueInArithmetic) _diagnostics.Add(ToleranceDroppedThroughArithmetic);
return _bound[name] = new FirmamentV2BoundLet(let.Name, let.DeclaredType, expr.Value, let.SourceSpan, expr, expr.Dependencies, tolerance);
@@ -2504,7 +2521,12 @@ 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, ProjectionSource: Field(r,"dimension"), HoleWallTarget: wallTarget);
+ var dimensionSource = Field(r, "dimension");
+ var dimensionBinding = dimensionSource is null ? null : ResolveBoundLet(dimensionSource, lets, records);
+ bound=new(r.Kind,r.Name,targets,dim,dimTol,ctlTol,datumRefs,r.SourceSpan,
+ ProjectionSource: dimensionBinding?.Origins.Any(o => o.Binding == dimensionSource) == true ? dimensionSource
+ : dimensionBinding?.Origins.FirstOrDefault()?.Binding ?? dimensionSource, HoleWallTarget: wallTarget)
+ { DimensionOrigins = dimensionBinding?.Origins ?? [] };
return !diagnostics.Any(x => (x.StartsWith("firmament-v2-pmi-", StringComparison.Ordinal) && x is not PmiUnsupported)
|| x.StartsWith("firmament-v2-hole-wall-", StringComparison.Ordinal));
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs
index 062f9f9f..ad64d991 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs
@@ -12,7 +12,7 @@ public static partial class FirmamentV2Parser
// 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)
+ List<string> diagnostics, IReadOnlyList<FirmamentV2BoundLet>? inputs = null)
{
var declarations = new List<FirmamentV2LetDeclaration>();
var located = new List<FirmamentV2ValidationDiagnostic>();
@@ -38,6 +38,7 @@ public static partial class FirmamentV2Parser
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),
+ MemberSyntax m when FirmamentSyntaxValues.Reference(m) is { } member && visiting.Count < 128 && visiting.Add(member) => InferReference(member, 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),
@@ -46,7 +47,7 @@ public static partial class FirmamentV2Parser
FirmamentV2PrimitiveType? InferReference(string name, HashSet<string> visiting)
{
var matches = statics.Where(d => d.Name?.Text == name).ToArray();
- if (matches.Length != 1) return null;
+ if (matches.Length != 1) return inputs?.FirstOrDefault(v => v.Name == name)?.Type;
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;
@@ -97,7 +98,16 @@ public static partial class FirmamentV2Parser
}
var before = diagnostics.Count;
- var values = BindLets(declarations, [], [], diagnostics);
+ var imported = (inputs ?? []).Where(v => declarations.All(d => d.Name != v.Name)).ToArray();
+ // A value already checked by this compilation's specialization environment is
+ // an input, not a second evaluation (and must not emit duplicate drop warnings).
+ var checkedDeclarations = declarations.Select(d => inputs?.FirstOrDefault(v => v.Name == d.Name && v.Type == d.DeclaredType) is { } value
+ ? d with { ValueExpression = new FirmamentV2LiteralExpression(value.Value), Tolerance = value.Tolerance } : d);
+ var values = BindLets(checkedDeclarations.Concat(imported.Select(v => new FirmamentV2LetDeclaration(v.Name, v.Type,
+ new FirmamentV2LiteralExpression(v.Value), v.SourceSpan, v.Tolerance))).ToArray(), [], [], diagnostics, located)
+ .Select(v => inputs?.FirstOrDefault(i => i.Name == v.Name) is { } input
+ ? v with { Origins = input.Origins, Expression = input.Expression, Dependencies = input.Dependencies }
+ : v with { Origins = v.Dependencies?.SelectMany(n => inputs?.FirstOrDefault(i => i.Name == n)?.Origins ?? []).Distinct().ToArray() ?? [] }).ToArray();
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)))
@@ -119,11 +129,12 @@ public static partial class FirmamentV2Parser
_ => "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." });
+ LocationNote = code == ExpressionUnknownSymbol && unresolved.Length == 1 ? null : "Dependency binding reports the enclosing compile-time scope." });
}
var map = values.ToDictionary(v => v.Name, StringComparer.Ordinal);
ExpressionSyntax Nominal(ExpressionSyntax e) => e switch
{
+ MemberSyntax m when FirmamentSyntaxValues.Reference(m) is { } name && map.TryGetValue(name, out var value) => Literal(value, e.Span),
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) },
@@ -152,6 +163,7 @@ public static partial class FirmamentV2Parser
FirmamentV2ValueExpression? ValueExpression(ExpressionSyntax e, FirmamentV2PrimitiveType expected)
{
var text = source.Substring(e.Span.Start, e.Span.Length);
+ if (e is MemberSyntax m && FirmamentSyntaxValues.Reference(m) is { } member) return new FirmamentV2IdentifierReferenceExpression(member, text);
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)
@@ -184,6 +196,19 @@ public static partial class FirmamentV2Parser
}
}
+ // Template/Feature scalar arguments use precisely the same dimensional graph binder as Static.
+ // The caller owns scope and supplies AST declarations and already checked input values.
+ internal static (IReadOnlyList<FirmamentV2BoundLet> Values, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics)
+ BindCompileTimeScalars(IReadOnlyList<DeclarationSyntax> declarations, string source, string sourceFile,
+ List<string> diagnostics, IReadOnlyList<FirmamentV2BoundLet>? inputs = null)
+ {
+ var span = new FirmamentV2SourceSpan(0, source.Length);
+ var model = new DeclarationSyntax(new(new("Model", span), [], span), new("CompileTime", span), [], [],
+ null, null, [], null, new(declarations, span) { Delimited = false }, false, span);
+ var binding = BindStaticValues(new(sourceFile, [model], [], span), model, source, diagnostics, inputs);
+ return (binding.Values, binding.Diagnostics);
+ }
+
private static ExpressionSyntax Literal(FirmamentV2BoundLet value, FirmamentV2SourceSpan span)
{
ExpressionSyntax literal = new LiteralSyntax(value.Type switch
@@ -210,20 +235,24 @@ public static partial class FirmamentV2Parser
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.
+ var requirement = value.Origins.FirstOrDefault();
+ var displayName = requirement?.Binding ?? value.Name;
void Error(string code, string message)
{
diagnostics.Add(code);
- result.Add(new(code, "error", message, "dimension", record.Name) { SourceSpan = record.SourceSpan, Stage = "Binding" });
+ result.Add(new(code, "error", message, "dimension", record.Name) { SourceSpan = requirement?.SourceSpan ?? record.SourceSpan,
+ IsOriginalSource = requirement is not null, Stage = "Binding",
+ LocationNote = requirement is null ? null : "Location identifies the original projected requirement." });
}
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.");
+ Error("firmament-v2-pmi-typed-dimension-override", $"PMI '{record.Name}' projects '{displayName}'; 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).");
+ Error("firmament-v2-pmi-typed-dimension-unsatisfied", $"Hole '{hole.Name}' has diameter {hole.ShaftDiameter:R}mm, outside '{displayName}' ({nominal:R}mm +{value.Tolerance.Plus:R}mm -{value.Tolerance.Minus:R}mm).");
}
return result;
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
index 55b9efbc..501e98d6 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
@@ -3,6 +3,7 @@ using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
@@ -15,7 +16,10 @@ internal sealed record TemplateValueParameterIr(string Name, string TypeName, st
internal sealed record TemplateApplicationIr(string TargetKind, string InstanceName, string TemplateName, ImmutableArray<TemplateArgumentIr> Arguments, FirmamentV2SourceSpan SourceSpan);
internal sealed record TemplateArgumentIr(string Name, string Expression, FirmamentV2SourceSpan SourceSpan);
internal sealed record TemplateRecordTypeIr(string Name, ImmutableDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);
-internal sealed record TemplateStaticRecordIr(string Name, string TypeName, ImmutableDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan, string Provenance = "StaticRecord");
+internal sealed record TemplateStaticRecordIr(string Name, string TypeName, ImmutableDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan, string Provenance = "StaticRecord")
+{
+ internal string? AuthoredName { get; init; }
+}
internal sealed record TemplateStaticTableIr(string Name, string RowType, string? KeyField, ImmutableDictionary<string, ImmutableArray<string>> Columns, FirmamentV2SourceSpan SourceSpan);
internal sealed record BoundTemplateRecordIr(string Parameter, string TypeName, string StaticName, ImmutableDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan, string Provenance);
internal sealed record BoundTemplateArguments(ImmutableDictionary<string, string> TypeArguments, ImmutableDictionary<string, string> ValueArguments, ImmutableDictionary<string, BoundTemplateRecordIr> RecordArguments, ImmutableArray<string> DefaultedArguments);
@@ -142,7 +146,7 @@ internal static class FirmamentV2TemplateExpansion
.Select(record => new HostStaticRecord(
record.Name,
record.TypeName,
- FlattenRecordFields(record, recordTypes, staticRecords),
+ FlattenRecordFields(record, recordTypes, staticRecords, diagnostics),
record.Provenance))
.ToArray();
}
@@ -300,7 +304,7 @@ internal static class FirmamentV2TemplateExpansion
}
}
- public static Result? Expand(string source, List<string> diagnostics)
+ public static Result? Expand(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null)
{
var declarations = ParseDeclarations(source, diagnostics);
var byName = declarations.ToDictionary(d => d.Name, StringComparer.Ordinal);
@@ -314,19 +318,21 @@ internal static class FirmamentV2TemplateExpansion
var enums = ParseEnums(source);
var recordTypes = ParseRecordTypes(source, diagnostics);
+ scalars?.Initialize(recordTypes, diagnostics);
var tables = ParseStaticTables(source, recordTypes, enums, diagnostics);
- var staticRecords = ParseStaticRecords(source, recordTypes, enums, tables, diagnostics);
+ var staticRecords = ParseStaticRecords(source, recordTypes, enums, tables, diagnostics, scalars);
+ scalars?.SetRecords(recordTypes, staticRecords);
var changes = declarations.Select(d => (d.SourceSpan.Start, d.SourceSpan.Length, Text: string.Empty)).ToList();
var instantiations = new List<ConceptIrTemplateInstantiation>();
foreach (var application in applications)
{
var template = byName[application.TemplateName];
if (!string.Equals(application.TargetKind, template.TargetKind, StringComparison.Ordinal)) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); continue; }
- var bound = Bind(template, application, source, enums, recordTypes, staticRecords, diagnostics);
+ var bound = Bind(template, application, source, enums, recordTypes, staticRecords, diagnostics, scalars);
if (bound is null) continue;
- var specialization = new TemplateSpecializationIr(template, application, bound, Identity(template, application, bound), GeneratedPaths(template.Body, application.InstanceName));
+ var specialization = new TemplateSpecializationIr(template, application, bound, Identity(template, application, bound, scalars), GeneratedPaths(template.Body, application.InstanceName));
if (!ValidateRecordMembers(template.Body, bound, diagnostics)) continue;
- if (!EvaluateRequires(Substitute(template.Body, bound), application.InstanceName,
+ if (!EvaluateRequires(Substitute(template.Body, bound, scalars), application.InstanceName,
DisplaySignature(template), diagnostics, out var requireResults)) continue;
var body = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);
if (body is null) continue;
@@ -338,7 +344,7 @@ internal static class FirmamentV2TemplateExpansion
specialization.SpecializationIdentity, specialization.GeneratedDeclarationPaths, template.SourceSpan, application.SourceSpan,
SelectedMatchArms: selectedMatches, RecordArguments: recordArguments, RequireResults: requireResults));
body = ExpandNestedApplications(body, byName, source, enums, recordTypes, staticRecords,
- diagnostics, instantiations, [template.Name]);
+ diagnostics, instantiations, [template.Name], scalars);
var liftedPmi = LiftPmi(body, out body);
changes.Add((application.SourceSpan.Start, application.SourceSpan.Length, RenderOutput(template.TargetKind, application.InstanceName, template.HeaderTail, body) + liftedPmi));
}
@@ -437,7 +443,8 @@ internal static class FirmamentV2TemplateExpansion
}
private static BoundTemplateArguments? Bind(TemplateDeclarationIr template, TemplateApplicationIr application, string source, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums,
- IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes, IReadOnlyDictionary<string, TemplateStaticRecordIr> staticRecords, List<string> diagnostics)
+ IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes, IReadOnlyDictionary<string, TemplateStaticRecordIr> staticRecords, List<string> diagnostics,
+ FirmamentCompileTimeValues? scalars = null)
{
var supplied = application.Arguments.ToDictionary(a => a.Name, a => a.Expression, StringComparer.Ordinal);
var expectedSignature = DisplaySignature(template);
@@ -456,7 +463,9 @@ internal static class FirmamentV2TemplateExpansion
var value = referenced is null ? expression : Resolve(referenced);
resolving.RemoveAt(resolving.Count - 1);
if (value is null) return null;
- if (!TypeMatches(value, p.TypeName, enums)) { diagnostics.Add((supplied.ContainsKey(p.Name) ? TypeMismatch : BadDefault) + $":{p.Name}:expected-{p.TypeName}:actual-{value}:expected-signature:{expectedSignature}"); return null; }
+ if (scalars?.IsScalar(p.TypeName) == true && scalars.TryTransfer(value, p.TypeName,
+ $"Template {template.Name}.{p.Name}", application.SourceSpan, diagnostics, out var checkedValue)) value = checkedValue;
+ if (!TypeMatches(value, p.TypeName, enums, scalars: scalars)) { diagnostics.Add((supplied.ContainsKey(p.Name) ? TypeMismatch : BadDefault) + $":{p.Name}:expected-{p.TypeName}:actual-{value}:expected-signature:{expectedSignature}"); return null; }
values[p.Name] = value;
if (!supplied.ContainsKey(p.Name)) defaults.Add(p.Name);
return value;
@@ -487,12 +496,20 @@ internal static class FirmamentV2TemplateExpansion
if (!supplied.ContainsKey(parameter.Name)) defaults.Add(parameter.Name);
if (Regex.IsMatch(source, $@"\bStatic\s+{Regex.Escape(expression)}\s*:\s*{Regex.Escape(recordType.Name)}\s*\[", RegexOptions.CultureInvariant))
{ diagnostics.Add(RecordCollectionMismatch + $":{parameter.Name}:expected-{recordType.Name}:actual-collection"); return; }
- if (staticRecords.TryGetValue(expression, out var staticRecord))
+ if (staticRecords.TryGetValue(expression, out var staticRecord) || scalars?.TryRecord(expression, out staticRecord) == true)
{
if (!string.Equals(staticRecord.TypeName, recordType.Name, StringComparison.Ordinal))
{ diagnostics.Add(WrongRecordType + $":{parameter.Name}:expected-{recordType.Name}:actual-{staticRecord.TypeName}"); return; }
- records[parameter.Name] = new(parameter.Name, recordType.Name, staticRecord.Name, FlattenRecordFields(staticRecord, recordTypes, staticRecords), staticRecord.SourceSpan, staticRecord.Provenance);
- values[parameter.Name] = staticRecord.Name;
+ ImmutableDictionary<string, string> fields;
+ if (scalars is not null)
+ {
+ if (!scalars.TryRecordTransfer(expression, recordType.Name,
+ $"Template {template.Name}.{parameter.Name}", application.SourceSpan, diagnostics, out var checkedFields)) return;
+ fields = checkedFields.ToImmutableDictionary(StringComparer.Ordinal);
+ }
+ else fields = FlattenRecordFields(staticRecord, recordTypes, staticRecords, diagnostics);
+ records[parameter.Name] = new(parameter.Name, recordType.Name, staticRecord.AuthoredName ?? staticRecord.Name, fields, staticRecord.SourceSpan, staticRecord.Provenance);
+ values[parameter.Name] = scalars?.RecordReference(staticRecord, fields) ?? staticRecord.Name;
return;
}
if (Regex.IsMatch(source, $@"\b(?:Struct|Model)\s+{Regex.Escape(expression)}\b", RegexOptions.CultureInvariant))
@@ -502,12 +519,19 @@ internal static class FirmamentV2TemplateExpansion
}
}
- private static ImmutableDictionary<string, string> FlattenRecordFields(TemplateStaticRecordIr record,
- IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes, IReadOnlyDictionary<string, TemplateStaticRecordIr> staticRecords)
+ internal static ImmutableDictionary<string, string> FlattenRecordFields(TemplateStaticRecordIr record,
+ IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes, IReadOnlyDictionary<string, TemplateStaticRecordIr> staticRecords,
+ List<string> diagnostics)
{
+ // A checked transport view is already flat. Re-expanding its source Record
+ // would overwrite the parameter receipts on its nested leaf values.
+ if (record.AuthoredName is not null) return record.Fields;
var result = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
+ var visiting = new HashSet<string>(StringComparer.Ordinal);
void Add(TemplateStaticRecordIr value, string prefix)
{
+ if (!visiting.Add(value.Name)) { diagnostics.Add(Prefix + "record-cycle:" + value.Name); return; }
+ if (visiting.Count > 128) { diagnostics.Add(Prefix + "record-depth-limit:" + value.Name); visiting.Remove(value.Name); return; }
foreach (var field in value.Fields)
{
var path = prefix + field.Key;
@@ -515,6 +539,7 @@ internal static class FirmamentV2TemplateExpansion
if (recordTypes[value.TypeName].Fields.TryGetValue(field.Key, out var type)
&& recordTypes.ContainsKey(type) && staticRecords.TryGetValue(field.Value, out var nested)) Add(nested, path + ".");
}
+ visiting.Remove(value.Name);
}
Add(record, string.Empty);
return result.ToImmutable();
@@ -524,7 +549,8 @@ internal static class FirmamentV2TemplateExpansion
m => m.Groups["name"].Value,
m => Regex.Matches(m.Groups["body"].Value, @"[A-Za-z_][A-Za-z0-9_]*", RegexOptions.CultureInvariant).Select(v => v.Value).ToImmutableHashSet(StringComparer.Ordinal), StringComparer.Ordinal);
private static bool TypeMatches(string value, string type, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums,
- IReadOnlyDictionary<string, TemplateRecordTypeIr>? recordTypes = null, IReadOnlyDictionary<string, TemplateStaticRecordIr>? staticRecords = null) => type switch
+ IReadOnlyDictionary<string, TemplateRecordTypeIr>? recordTypes = null, IReadOnlyDictionary<string, TemplateStaticRecordIr>? staticRecords = null,
+ FirmamentCompileTimeValues? scalars = null) => scalars?.Contains(value) == true ? scalars.HasType(value, type) : type switch
{
"Point3" => Regex.IsMatch(value, @"^Point3\(\s*[-+]?\d+(?:\.\d+)?mm\s*,\s*[-+]?\d+(?:\.\d+)?mm\s*,\s*[-+]?\d+(?:\.\d+)?mm\s*\)$"),
"Length" => Regex.IsMatch(value, @"^[-+]?[0-9]+(?:\.[0-9]+)?mm$", RegexOptions.CultureInvariant),
@@ -597,7 +623,8 @@ internal static class FirmamentV2TemplateExpansion
}
private static IReadOnlyDictionary<string, TemplateStaticRecordIr> ParseStaticRecords(string source, IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes,
- IReadOnlyDictionary<string, ImmutableHashSet<string>> enums, IReadOnlyDictionary<string, TemplateStaticTableIr> tables, List<string> diagnostics)
+ IReadOnlyDictionary<string, ImmutableHashSet<string>> enums, IReadOnlyDictionary<string, TemplateStaticTableIr> tables, List<string> diagnostics,
+ FirmamentCompileTimeValues? scalars = null)
{
var result = new Dictionary<string, TemplateStaticRecordIr>(StringComparer.Ordinal);
foreach (Match header in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)(?:\s*=\s*(?<literal>[A-Za-z_]\w*))?\s*\{", RegexOptions.CultureInvariant))
@@ -606,10 +633,13 @@ internal static class FirmamentV2TemplateExpansion
var open = source.IndexOf('{', header.Index); var close = Matching(source, open, '{', '}');
if (close < 0 || !recordTypes.TryGetValue(typeName, out var recordType)) continue;
if (!string.Equals(typeName, literalType, StringComparison.Ordinal)) { diagnostics.Add(WrongRecordType + $":{name}:expected-{typeName}:actual-{literalType}"); continue; }
- var fields = ParseRecordFields(source[(open + 1)..close]);
+ var fields = ParseRecordFields(source[(open + 1)..close], recordType.Fields, diagnostics, scalars, name);
+ foreach (var field in fields.ToArray())
+ if (recordType.Fields.TryGetValue(field.Key, out var fieldType) && scalars is not null)
+ fields[field.Key] = scalars.Field(name, field.Key, field.Value, fieldType, new(header.Index, close - header.Index + 1), diagnostics);
foreach (var missing in recordType.Fields.Keys.Where(field => !fields.ContainsKey(field))) diagnostics.Add(RecordMissingField + ":" + name + ":" + missing);
foreach (var extra in fields.Keys.Where(field => !recordType.Fields.ContainsKey(field))) diagnostics.Add(RecordExtraField + ":" + name + ":" + extra);
- foreach (var field in fields.Where(field => recordType.Fields.TryGetValue(field.Key, out var expected) && !recordTypes.ContainsKey(expected) && !TypeMatches(field.Value, expected, enums, recordTypes, result)))
+ foreach (var field in fields.Where(field => recordType.Fields.TryGetValue(field.Key, out var expected) && !recordTypes.ContainsKey(expected) && !TypeMatches(field.Value, expected, enums, recordTypes, result, scalars)))
diagnostics.Add(RecordFieldTypeMismatch + ":" + name + "." + field.Key + ":expected-" + recordType.Fields[field.Key] + ":actual-" + field.Value);
result[name] = new(name, typeName, fields.ToImmutableDictionary(StringComparer.Ordinal), new(header.Index, close - header.Index + 1));
}
@@ -649,12 +679,15 @@ internal static class FirmamentV2TemplateExpansion
if (!result.TryGetValue(baseName, out var baseRecord)) { remaining.Add(declaration); continue; }
var type = declaration.Groups["type"].Success ? declaration.Groups["type"].Value : baseRecord.TypeName;
if (!string.Equals(type, baseRecord.TypeName, StringComparison.Ordinal)) { diagnostics.Add(WrongRecordType + ":" + name + ":expected-" + type + ":actual-" + baseRecord.TypeName); continue; }
- var overrides = ParseRecordFields(source[(open + 1)..close]);
+ var overrides = ParseRecordFields(source[(open + 1)..close], recordTypes[baseRecord.TypeName].Fields, diagnostics, scalars, name);
+ foreach (var field in overrides.ToArray())
+ if (recordTypes[baseRecord.TypeName].Fields.TryGetValue(field.Key, out var fieldType) && scalars is not null)
+ overrides[field.Key] = scalars.Field(name, field.Key, field.Value, fieldType, new(declaration.Index, close - declaration.Index + 1), diagnostics);
var overrideNames = Regex.Matches(source[(open + 1)..close], @"\b(?<name>[A-Za-z_]\w*)\s*:", RegexOptions.CultureInvariant).Cast<Match>().Select(match => match.Groups["name"].Value).ToArray();
foreach (var duplicate in overrideNames.GroupBy(value => value, StringComparer.Ordinal).Where(group => group.Count() > 1)) diagnostics.Add(WithDuplicateField + ":" + name + ":" + duplicate.Key);
foreach (var field in overrides.Keys.Where(field => !recordTypes[baseRecord.TypeName].Fields.ContainsKey(field))) diagnostics.Add(WithUnknownField + ":" + name + ":" + field);
foreach (var field in overrideNames.Where(field => recordTypes[baseRecord.TypeName].Fields.ContainsKey(field) && !overrides.ContainsKey(field))) diagnostics.Add(WithTypeMismatch + ":" + name + "." + field + ":collection-or-unsupported-value");
- foreach (var field in overrides.Where(field => recordTypes[baseRecord.TypeName].Fields.TryGetValue(field.Key, out var expected) && !TypeMatches(field.Value, expected, enums, recordTypes, result))) diagnostics.Add(WithTypeMismatch + ":" + name + "." + field.Key + ":expected-" + recordTypes[baseRecord.TypeName].Fields[field.Key] + ":actual-" + field.Value);
+ foreach (var field in overrides.Where(field => recordTypes[baseRecord.TypeName].Fields.TryGetValue(field.Key, out var expected) && !TypeMatches(field.Value, expected, enums, recordTypes, result, scalars))) diagnostics.Add(WithTypeMismatch + ":" + name + "." + field.Key + ":expected-" + recordTypes[baseRecord.TypeName].Fields[field.Key] + ":actual-" + field.Value);
var fields = baseRecord.Fields.SetItems(overrides);
var inherited = baseRecord.Fields.Values.Concat(overrides.Values).Where(result.ContainsKey).Select(value => result[value].Provenance).Distinct(StringComparer.Ordinal).ToArray();
result[name] = new(name, type, fields, new(declaration.Index, close - declaration.Index + 1), baseRecord.Provenance + "; derivedFrom:" + baseName + (inherited.Length == 0 ? string.Empty : "; origin:" + string.Join("|", inherited)) + "; overrides:" + string.Join(",", overrides.Keys.OrderBy(value => value, StringComparer.Ordinal)));
@@ -694,16 +727,45 @@ internal static class FirmamentV2TemplateExpansion
if (origins.Length > 0 && !record.Provenance.Contains("origin:", StringComparison.Ordinal)) result[record.Name] = record with { Provenance = record.Provenance + "; origin:" + string.Join("|", origins) };
}
foreach (var record in result.Values)
- foreach (var field in record.Fields.Where(field => recordTypes[record.TypeName].Fields.TryGetValue(field.Key, out var expected) && !TypeMatches(field.Value, expected, enums, recordTypes, result)))
+ foreach (var field in record.Fields.Where(field => recordTypes[record.TypeName].Fields.TryGetValue(field.Key, out var expected) && !TypeMatches(field.Value, expected, enums, recordTypes, result, scalars)))
diagnostics.Add(Prefix + "record-field-type-mismatch:" + record.Name + "." + field.Key + ":expected-" + recordTypes[record.TypeName].Fields[field.Key] + ":actual-" + field.Value);
return result;
}
private static IReadOnlyList<string> SplitValues(string text) => Regex.Matches(text, "\"[^\"]*\"|\\d+\\.\\d+\\.\\d+|\\d{4}-\\d{2}-\\d{2}|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?|[A-Za-z_]\\w*", RegexOptions.CultureInvariant).Cast<Match>().Select(match => match.Value).ToArray();
- private static Dictionary<string, string> ParseRecordFields(string body) => Regex.Matches(body,
- "\\b(?<name>[A-Za-z_]\\w*)\\s*:\\s*(?<value>\"[^\"]*\"|(?:Point2|Point3|Vector2|Vector3|Axis)\\s*\\([^)]*\\)|\\d+\\.\\d+\\.\\d+|\\d{4}-\\d{2}-\\d{2}|[A-Za-z_]\\w*|[-+]?\\d+(?:\\.\\d+)?(?:mm|deg)?)",
- RegexOptions.CultureInvariant).Cast<Match>().GroupBy(m => m.Groups["name"].Value, StringComparer.Ordinal).ToDictionary(group => group.Key, group => group.Last().Groups["value"].Value, StringComparer.Ordinal);
+ private static Dictionary<string, string> ParseRecordFields(string body, IReadOnlyDictionary<string, string> schema, List<string> diagnostics,
+ FirmamentCompileTimeValues? scalars, string recordName)
+ {
+ const string prefix = "Struct Fields {\n";
+ var text = prefix + body + "\n}";
+ var syntax = FirmamentSyntaxParser.Parse(text);
+ var fields = syntax.Document.Statements.OfType<DeclarationSyntax>().SelectMany(d => d.Body?.Statements ?? []).OfType<FieldSyntax>().ToArray();
+ foreach (var duplicate in fields.GroupBy(f => f.Name.Text, StringComparer.Ordinal).Where(g => g.Count() > 1))
+ {
+ var code = Prefix + "record-duplicate-field:" + duplicate.Key;
+ diagnostics.Add(code);
+ scalars?.RecordError(recordName, duplicate.Key, code,
+ $"Record '{recordName}' supplies field '{duplicate.Key}' more than once. Supply it once, or derive a new Record with a checked with override.");
+ }
+ var result = fields.GroupBy(f => f.Name.Text, StringComparer.Ordinal)
+ .ToDictionary(g => g.Key, g => text.Substring(g.Last().Value.Span.Start, g.Last().Value.Span.Length), StringComparer.Ordinal);
+ // Version/Date are established domain symbols, not decimal arithmetic. Keep their
+ // complete token spelling using the Record owner's existing field type metadata.
+ var tokens = FirmamentLanguageAnalysisService.Lex(body).Where(t => t.Shape != "comment").ToArray();
+ var depth = 0;
+ for (var i = 0; i + 2 < tokens.Length; i++)
+ {
+ if (tokens[i].Text is "(" or "[" or "{") depth++;
+ if (tokens[i].Text is ")" or "]" or "}") depth--;
+ if (depth != 0 || tokens[i + 1].Text != ":" || !schema.TryGetValue(tokens[i].Text, out var type) || type is not ("Version" or "Date")) continue;
+ var end = i + 2;
+ while (end < tokens.Length && tokens[end].Text != ";" && !(end + 1 < tokens.Length && tokens[end + 1].Text == ":")) end++;
+ var finish = end == tokens.Length ? body.Length : tokens[end].Start;
+ result[tokens[i].Text] = body[tokens[i + 2].Start..finish].Trim();
+ }
+ return result;
+ }
private static bool ConceptExists(string concept, string source) => Regex.IsMatch(source, $@"\bConcept\s+{Regex.Escape(concept)}\s*\{{", RegexOptions.CultureInvariant);
private static bool Satisfies(string type, string concept, string source)
{
@@ -712,15 +774,13 @@ internal static class FirmamentV2TemplateExpansion
var capabilities = new Dictionary<string, string>(StringComparer.Ordinal) { ["Bounds"] = "Box3", ["TopPlane"] = "Plane", ["CenterAxis"] = "Axis" };
return definition.Success && Regex.Matches(definition.Groups["body"].Value, @"(?m)^\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<kind>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant).Cast<Match>().All(m => capabilities.TryGetValue(m.Groups["name"].Value, out var actual) && actual == m.Groups["kind"].Value);
}
- private static string Substitute(string body, BoundTemplateArguments bound)
+ private static string Substitute(string body, BoundTemplateArguments bound, FirmamentCompileTimeValues? nominalScalars = null)
{
+ var values = bound.TypeArguments.Concat(bound.ValueArguments)
+ .ToDictionary(p => p.Key, p => nominalScalars?.NominalExpression(p.Value) ?? p.Value, StringComparer.Ordinal);
foreach (var record in bound.RecordArguments.Values)
- {
- foreach (var field in record.Fields.OrderByDescending(field => field.Key.Length))
- body = Regex.Replace(body, $@"\b{Regex.Escape(record.Parameter)}\s*\.\s*{Regex.Escape(field.Key).Replace("\\.", @"\s*\.\s*", StringComparison.Ordinal)}\b", _ => field.Value, RegexOptions.CultureInvariant);
- }
- return bound.TypeArguments.Concat(bound.ValueArguments.Where(pair => !bound.RecordArguments.ContainsKey(pair.Key)))
- .Aggregate(body, (result, pair) => Regex.Replace(result, $@"\b{Regex.Escape(pair.Key)}\b", pair.Value));
+ foreach (var field in record.Fields) values[record.Parameter + "." + field.Key] = nominalScalars?.NominalExpression(field.Value) ?? field.Value;
+ return FirmamentValueSubstitution.Apply(body, values);
}
private static bool ValidateRecordMembers(string body, BoundTemplateArguments bound, List<string> diagnostics)
{
@@ -816,10 +876,11 @@ internal static class FirmamentV2TemplateExpansion
_ = Visit(template.Name);
}
}
- private static string Identity(TemplateDeclarationIr template, TemplateApplicationIr application, BoundTemplateArguments args)
+ private static string Identity(TemplateDeclarationIr template, TemplateApplicationIr application, BoundTemplateArguments args, FirmamentCompileTimeValues? scalars = null)
{
- var recordInput = args.RecordArguments.OrderBy(x => x.Key).SelectMany(x => x.Value.Fields.OrderBy(f => f.Key).Select(f => x.Key + "." + f.Key + "=" + f.Value));
- var input = template.Name + "|" + application.InstanceName + "|" + string.Join("|", args.TypeArguments.Concat(args.ValueArguments).OrderBy(x => x.Key).Select(x => x.Key + "=" + x.Value).Concat(recordInput));
+ string Value(string value) => scalars?.NominalExpression(value) ?? value;
+ var recordInput = args.RecordArguments.OrderBy(x => x.Key).SelectMany(x => x.Value.Fields.OrderBy(f => f.Key).Select(f => x.Key + "." + f.Key + "=" + Value(f.Value)));
+ var input = template.Name + "|" + application.InstanceName + "|" + string.Join("|", args.TypeArguments.Concat(args.ValueArguments).OrderBy(x => x.Key).Select(x => x.Key + "=" + Value(x.Value)).Concat(recordInput));
return "template:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(input))).ToLowerInvariant()[..16];
}
private static string DisplaySignature(TemplateDeclarationIr template) => template.Name + "<" + string.Join(", ", template.Parameters.Select(parameter => parameter switch
@@ -855,7 +916,7 @@ internal static class FirmamentV2TemplateExpansion
IReadOnlyDictionary<string, TemplateStaticRecordIr> staticRecords,
List<string> diagnostics,
ICollection<ConceptIrTemplateInstantiation> instantiations,
- IReadOnlyList<string> stack)
+ IReadOnlyList<string> stack, FirmamentCompileTimeValues? scalars = null)
{
var applications = ParseApplications(body, templates, diagnostics);
var changes = new List<(int Start, int Length, string Text)>();
@@ -867,17 +928,17 @@ internal static class FirmamentV2TemplateExpansion
diagnostics.Add(Recursive + ":" + string.Join(" -> ", stack.Append(template.Name)));
continue;
}
- var bound = Bind(template, application, moduleSource, enums, recordTypes, staticRecords, diagnostics);
+ var bound = Bind(template, application, moduleSource, enums, recordTypes, staticRecords, diagnostics, scalars);
if (bound is null) continue;
if (!ValidateRecordMembers(template.Body, bound, diagnostics)) continue;
- if (!EvaluateRequires(Substitute(template.Body, bound), application.InstanceName,
+ if (!EvaluateRequires(Substitute(template.Body, bound, scalars), application.InstanceName,
DisplaySignature(template), diagnostics, out var requireResults)) continue;
var specializedBody = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);
if (specializedBody is null) continue;
specializedBody = Substitute(specializedBody, bound);
specializedBody = RemoveRequires(specializedBody);
var specialization = new TemplateSpecializationIr(template, application, bound,
- Identity(template, application, bound), GeneratedPaths(template.Body, application.InstanceName));
+ Identity(template, application, bound, scalars), GeneratedPaths(template.Body, application.InstanceName));
var recordArguments = bound.RecordArguments.ToDictionary(pair => pair.Key, pair => new ConceptIrTemplateRecordArgument(
pair.Value.TypeName, pair.Value.StaticName, pair.Value.Fields, pair.Value.SourceSpan, pair.Value.Provenance), StringComparer.Ordinal);
instantiations.Add(new(template.Name, application.InstanceName, bound.TypeArguments, bound.ValueArguments,
@@ -885,7 +946,7 @@ internal static class FirmamentV2TemplateExpansion
template.SourceSpan, application.SourceSpan, SelectedMatchArms: selectedMatches,
RecordArguments: recordArguments, RequireResults: requireResults));
specializedBody = ExpandNestedApplications(specializedBody, templates, moduleSource, enums, recordTypes,
- staticRecords, diagnostics, instantiations, stack.Append(template.Name).ToArray());
+ staticRecords, diagnostics, instantiations, stack.Append(template.Name).ToArray(), scalars);
var liftedPmi = LiftPmi(specializedBody, out specializedBody);
// Nested finite specializations flatten into the containing declaration before
// Feature AIR. The instantiation record above preserves the semantic boundary;
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
index fbc358a1..3a2f12a6 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
@@ -23,6 +23,7 @@ public sealed record FirmamentV2ValidationReport(
public sealed record FirmamentV2ValidationSummary(int LetCount, int TolerancedLetCount, int ConceptCount, int ValidConceptCount, int PmiRecordCount, int ExportSupportedPmiCount, int ExportDeferredPmiCount, int PmiObligationCount, int SatisfiedPmiObligationCount, int MissingPmiObligationCount, int FatalDiagnosticCount, int WarningDiagnosticCount);
public sealed record FirmamentV2ValidationDiagnostic(string Code, string Severity, string Message, string? FieldName = null, string? Target = null)
{
+ [System.Text.Json.Serialization.JsonIgnore] public bool IsOriginalSource { get; init; }
public string? SourceFile { get; init; }
public FirmamentV2SourceSpan? SourceSpan { get; init; }
public string? LocationNote { get; init; }
@@ -32,12 +33,18 @@ public sealed record FirmamentV2ValidationDiagnostic(string Code, string Severit
public int? Column { get; init; }
}
public sealed record FirmamentV2ValidationExportSupport(int SupportedPmiCount, int DeferredPmiCount, IReadOnlyDictionary<string, string> Matrix);
-public sealed record FirmamentV2ValidationLet(string Name, string Type, string Nominal, FirmamentV2ValidationTolerance? Tolerance, string Source, IReadOnlyList<string> Dependencies, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics);
+public sealed record FirmamentV2ValidationLet(string Name, string Type, string Nominal, FirmamentV2ValidationTolerance? Tolerance, string Source, IReadOnlyList<string> Dependencies, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics)
+{
+ public IReadOnlyList<FirmamentV2ValueOrigin> Origins { get; init; } = [];
+}
public sealed record FirmamentV2ValidationTolerance(string Kind, string Plus, string Minus);
public sealed record FirmamentV2ValidationConceptRuntimeValidation(string Provider, string Status, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics);
public sealed record FirmamentV2ValidationConcept(string Kind, string? Name, string Family, string Concept, string Status, string DfmStatus, IReadOnlyList<FirmamentV2ValidationConceptField> Fields, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics, FirmamentV2ValidationConceptRuntimeValidation? RuntimeValidation = null);
public sealed record FirmamentV2ValidationConceptField(string Name, string Type, bool HasTolerance, string Source);
-public sealed record FirmamentV2ValidationPmiRecord(string Kind, string Name, string Status, string ExportSupport, string? Target, IReadOnlyList<string> Targets, IReadOnlyList<string> DatumRefs, FirmamentV2ValidationDimension? Dimension, string? Reason, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics, string? ProjectionSource = null, string? SourceConstraintKind = null, string? SourceSubject = null, string? ValidationStatus = null, string? Provenance = null);
+public sealed record FirmamentV2ValidationPmiRecord(string Kind, string Name, string Status, string ExportSupport, string? Target, IReadOnlyList<string> Targets, IReadOnlyList<string> DatumRefs, FirmamentV2ValidationDimension? Dimension, string? Reason, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics, string? ProjectionSource = null, string? SourceConstraintKind = null, string? SourceSubject = null, string? ValidationStatus = null, string? Provenance = null)
+{
+ public IReadOnlyList<FirmamentV2ValueOrigin> DimensionOrigins { get; init; } = [];
+}
public sealed record FirmamentV2ValidationDimension(string Nominal, FirmamentV2ValidationTolerance? Tolerance);
public sealed record FirmamentV2ValidationConceptPmiObligation(string Kind, string SourceConcept, string? SourceName, string? Target, string? ExpectedDimensionField, string Status, string Severity, string? MatchedPmi = null, string? DiagnosticCode = null);
@@ -68,9 +75,9 @@ public static class FirmamentV2ValidationReportBuilder
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);
+ IReadOnlyList<FirmamentV2ValidationLet> lets = document is null ? [] : BuildLets(document).Select(l => l with { Origins = l.Origins.Select(o => o.SourceFile == "inline" ? o with { SourceFile = source } : o).ToArray() }).ToArray();
var concepts = document is null ? [] : BuildConcepts(document, runtimeValidation, conceptCatalog);
- var pmi = document is null ? [] : BuildPmi(document, diagnostics);
+ IReadOnlyList<FirmamentV2ValidationPmiRecord> pmi = document is null ? [] : BuildPmi(document, diagnostics).Select(p => p with { DimensionOrigins = p.DimensionOrigins.Select(o => o.SourceFile == "inline" ? o with { SourceFile = source } : o).ToArray() }).ToArray();
var conceptPmiEvaluation = document is null
? new FirmamentV2ConceptPmiObligationEvaluation([], [])
: BuildConceptPmiObligations(document, runtimeValidation);
@@ -138,7 +145,7 @@ public static class FirmamentV2ValidationReportBuilder
boundLet.Dependencies is null ? [] : boundLet.Dependencies.Order(StringComparer.Ordinal).ToArray();
private static FirmamentV2ValidationLet Let(string name, FirmamentV2BoundLet boundLet, string source) =>
- new(name, TypeName(boundLet.Type), FormatValue(boundLet.Value), ToTolerance(boundLet.Tolerance), source, Dependencies(boundLet), []);
+ new(name, TypeName(boundLet.Type), FormatValue(boundLet.Value), ToTolerance(boundLet.Tolerance), source, Dependencies(boundLet), []) { Origins = boundLet.Origins };
private static IReadOnlyList<FirmamentV2ValidationConcept> BuildConcepts(
FirmamentV2Document document,
@@ -243,11 +250,11 @@ public static class FirmamentV2ValidationReportBuilder
Dimension(boundRecord),
exportSupport == "deferred" ? FirmamentBuildAndExport.V2PmiExportRejection(record.Kind, record.Name, boundRecord)?.Message : null,
itemDiagnostics,
- record.Projection?.SourceRequireId,
+ record.Projection?.SourceRequireId ?? boundRecord?.ProjectionSource,
constraint is null ? null : "dimensional-equality",
constraint is null ? null : constraint.Subject + "." + constraint.Property,
constraint is null ? null : constraint.ValidationSucceeded ? "succeeded" : "failed",
- constraint?.ExpectedProvenance);
+ constraint?.ExpectedProvenance) { DimensionOrigins = boundRecord?.DimensionOrigins ?? [] };
}).ToArray();
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentValueSubstitution.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentValueSubstitution.cs
new file mode 100644
index 00000000..23586f1e
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentValueSubstitution.cs
@@ -0,0 +1,48 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>Value substitution inside the existing expansion owners. Shared AST declaration
+/// spans protect local binders; lexer spans protect labels, members, strings and comments.</summary>
+internal static class FirmamentValueSubstitution
+{
+ internal static string Apply(string source, IReadOnlyDictionary<string, string> values)
+ {
+ if (values.Count == 0) return source;
+ const string prefix = "Struct Binding {\n";
+ var syntax = FirmamentSyntaxParser.Parse(prefix + source + "\n}");
+ var declarations = FirmamentSyntaxTraversal.Declarations(syntax.Document).ToArray();
+ var names = declarations.Where(d => d.Name is not null).Select(d => d.Name!.Span.Start - prefix.Length).ToHashSet();
+ var scopes = declarations.Where(d => d.Body is not null).Select(d => (Span: d.Body!.Span,
+ Names: d.Parameters.Select(p => p.Name?.Text).OfType<string>()
+ .Concat(d.Modifiers.Where(m => m.Name.Text == "Template").SelectMany(m => m.Arguments).Select(a => a.Name?.Text).OfType<string>())
+ .Concat(d.Type.Name.Text == "Feature" ? d.Body.Statements.OfType<DeclarationSyntax>()
+ .Where(l => l.Type.Name.Text == "let").Select(l => l.Name?.Text).OfType<string>() : [])
+ .ToHashSet(StringComparer.Ordinal))).Where(s => s.Names.Count > 0).ToArray();
+ var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(t => t.Shape != "comment").ToArray();
+ var changes = new List<(int Start, int Length, string Value)>();
+ for (var i = 0; i < tokens.Length; i++)
+ {
+ if (tokens[i].Shape == "string" || names.Contains(tokens[i].Start) || i > 0 && tokens[i - 1].Text == "."
+ || i + 1 < tokens.Length && tokens[i + 1].Text == ":") continue;
+ if (scopes.Any(s => tokens[i].Start + prefix.Length >= s.Span.Start
+ && tokens[i].Start + prefix.Length < s.Span.Start + s.Span.Length && s.Names.Contains(tokens[i].Text))) continue;
+ var key = tokens[i].Text;
+ var last = i;
+ var matched = values.TryGetValue(key, out var replacement);
+ var matchedLast = i;
+ while (last + 2 < tokens.Length && tokens[last + 1].Text == ".")
+ {
+ key += "." + tokens[last + 2].Text;
+ last += 2;
+ if (values.TryGetValue(key, out var member)) { matched = true; matchedLast = last; replacement = member; }
+ }
+ if (!matched) continue;
+ changes.Add((tokens[i].Start, tokens[matchedLast].Start + tokens[matchedLast].Length - tokens[i].Start, replacement!));
+ i = matchedLast;
+ }
+ foreach (var change in changes.OrderByDescending(c => c.Start))
+ source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Value);
+ return source;
+ }
+}
diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
index 8133275c..0c4d457c 100644
--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
@@ -1,12 +1,23 @@
# October 2026 Firmament language decision register
+Compile-time value-binding amendment:
+[qualification report](../release/FIRMAMENT-COMPILE-TIME-VALUES.md) carries
+typed Record requirements through scalar/whole-Record Template and Feature
+parameters, defaults, nested specialization and local aliases into admitted
+geometry and explicit PMI. It adds original requirement/binding receipts and
+repairs value substitution of labels/shadowed locals under #1–#4, #8, #9 and
+#19. The shared scalar graph remains authoritative; full scoped AST expansion,
+all-domain expression consolidation, enum Static and total Match checking are
+not declared complete. This supersedes the earlier Record/Template propagation
+deferral only for the report's qualified lane.
+
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,
+At that pass, Template/Record/domain-wide tolerance propagation remained 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)
diff --git a/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md b/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md
index 9645bbc7..07ea2268 100644
--- a/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md
+++ b/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md
@@ -1,5 +1,13 @@
# Firmament syntax review — 2026-10-14
+Compile-time binding follow-up:
+[implementation and qualification](../release/FIRMAMENT-COMPILE-TIME-VALUES.md)
+extends S17 with typed Record members, Template/Feature inputs, defaults and
+aliases sharing the scalar binder and retaining requirements/provenance. It
+also repairs Template value substitution of labels and shadowed Feature
+parameters. This does not close every expression position, numeric-policy
+seam, Pattern binder or domain grammar listed below.
+
Implementation follow-up: the [directive/casing pass](../release/FIRMAMENT-DIRECTIVES-AND-CASING.md)
repairs S01 (symmetry fields), S02 (Profile/mirror links), S14 and S15.
It also repairs S13's dense mirror/override witness; specialized semicolon rules
diff --git a/docs/public/firmament/pmi.md b/docs/public/firmament/pmi.md
index be82bcb8..4f27e866 100644
--- a/docs/public/firmament/pmi.md
+++ b/docs/public/firmament/pmi.md
@@ -31,11 +31,18 @@ Model TypedHole {
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
+typed value and allowance survive Static aliases, Record members, Template
+specialization and Feature parameter/local bindings; 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).
+The complete [Record/Template/Feature witness](../../../fixtures/Canonical/PMI/record-template-feature-tolerance.firmament)
+projects the original Record requirement after using it in a named Hole recipe.
+Validation JSON includes the authored projection source and structured
+`dimensionOrigins`; those receipts describe binding provenance, not additional
+PMI annotations. AP242 continues to carry the admitted nominal, allowances and
+geometric association through the existing semantic exporter.
HoleDiameter projection exports a size requirement attached to the hole wall.
A Datum may be exported separately. A `datum:`/`DatumRefs:` relationship on a
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index 33fa24c8..baf91433 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -188,16 +188,57 @@ 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.
+Typed requirements also travel through Record data, Template parameters and
+Feature parameters or local aliases. This complete example uses the same
+requirement for construction and explicit inspection:
+
+```firmament
+Record BoreSpec { diameter: Length }
+Static production: BoreSpec { diameter: 8mm tol +0.10mm -0.05mm }
+
+Template<spec: BoreSpec> Model PlateFamily {
+ units: mm
+ Feature Drill(spec: BoreSpec) -> Hole<Shaft> {
+ let inspection: Length = spec.diameter
+ return Hole<Shaft> {
+ on: +Z
+ center: Point2(0mm, 0mm)
+ diameter: inspection
+ end: ThroughAll
+ }
+ }
+ Box Body { size: [40mm, 30mm, 8mm] }
+ Modify Body { Feature Mount = Drill(spec: spec) }
+ Pmi { HoleDiameter MountSize { target: Mount dimension: spec.diameter } }
+}
+Model ProductionPlate = PlateFamily<spec: production>
+```
+
+Record field initializers may declare `tol`; Record field types remain `Length`
+or `Angle`. Passing either a scalar field or the whole typed Record preserves
+its requirement. Nested Records, checked `with` overrides, scalar Template
+defaults, nested specialization and Feature-local aliases follow the same
+rule. Feature locals stay local; the enclosing model selects its visible
+Static or Record requirement for PMI. Record data must be finite and acyclic;
+the current nesting limit is 128. A replacement field without `tol` replaces
+the requirement with an
+untoleranced value. Template `Require` conditions check nominal values; they
+do not certify a tolerance stack. Validation reports expose requirement origins
+and binding steps; internal transport identifiers are compiler details.
+
Scalar Static values belong directly to the Model or its source module and
-currently feed direct primitive and Modify fields. The existing shorthand
+feed direct primitive and Modify fields. Direct Record member references are
+also admitted in these fields and `Pmi dimension:`. 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
+qualify arbitrary scalar environments in other domains. Inline geometry-field
annotations such as `diameter: 8mm tol 0.1mm` reject; give
-the requirement a name. Angle allowances can be bound and inspected, but native
+the requirement a named Static or Record field. Toleranced Table cells and
+collection elements are not qualified by the Record/Template/Feature lane.
+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.
diff --git a/docs/public/firmament/templates.md b/docs/public/firmament/templates.md
index 6fd263fa..d8d6846c 100644
--- a/docs/public/firmament/templates.md
+++ b/docs/public/firmament/templates.md
@@ -59,10 +59,17 @@ 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.
+Scalar `Static` bindings and typed Record fields can carry
+[typed tolerances](pmi.md#project-a-compile-time-tolerance). Scalar or whole-Record
+Template arguments preserve nominal value, dimensional type, allowance and
+original-source provenance through nested specialization. Checked `with`
+overrides replace individual requirements. Scalar defaults use the same typed
+value binder. Features can accept either the scalar field or the whole typed
+Record; direct local aliases retain the allowance. Arithmetic retains the
+documented nominal-only policy and warns when it drops an allowance.
+This does not grant arbitrary scalar environments to every material domain or
+implement tolerance-stack arithmetic. See the complete
+[Record/Template/Feature example](syntax.md#typed-tolerances-and-pmi).
Value parameters use `Name: Type`. Defaults use `Name: Type = Value`. A real semantic/type parameter is explicit:
diff --git a/docs/release/FIRMAMENT-COMPILE-TIME-VALUES.md b/docs/release/FIRMAMENT-COMPILE-TIME-VALUES.md
new file mode 100644
index 00000000..7e49ba17
--- /dev/null
+++ b/docs/release/FIRMAMENT-COMPILE-TIME-VALUES.md
@@ -0,0 +1,183 @@
+# Firmament compile-time values: Record → Template → Feature → PMI
+
+## Contract and motivating case
+
+A dimensional requirement retains its nominal, type, tolerance and authored
+provenance when passed as a Record member, scalar Template argument, whole
+Record argument or Feature-local alias. Geometry consumes the nominal. Only
+an explicit `Pmi dimension:` projects the selected requirement to AP242.
+
+The complete production witness is
+[`record-template-feature-tolerance.firmament`](../../fixtures/Canonical/PMI/record-template-feature-tolerance.firmament).
+Its diameter is 8 mm with upper allowance +0.10 mm and lower allowance −0.05 mm.
+Before this pass the equivalent literal construction/PMI built, while the
+Record projection failed with PMI dimension-type/diameter errors. Original
+evidence and a pre-pass literal STEP baseline are preserved under ignored
+`artifacts/local/firmament-value-binding/`.
+
+## Repairs and ownership
+
+The per-compilation value environment reuses the existing typed scalar graph
+binder and tolerance IR. Record types remain owned by the existing Record
+schema; this pass does not introduce another field schema or expression
+evaluator. Scalar/Record inputs bind before specialization, newly specialized
+Model scalars bind before Feature expansion, and mechanical admission consumes
+those checked values without evaluating them a second time.
+
+Existing Template/Feature expansion carries opaque references to immutable
+checked values. The mechanical AST projects nominal literals into its existing
+primitive/Modify owners; the PMI binder receives the original typed value.
+Record views retain their authored identities when forwarded through nested
+specialization. Internal transport allocation does not determine Template
+specialization identity.
+Already flattened Record views are not expanded again, preserving nested
+parameter receipts. Cyclic Record references reject before argument flattening
+can recurse indefinitely; supported Record nesting is bounded to 128.
+
+Template and Feature value substitution now uses shared AST declaration/scope
+spans and lexer token spans. Field labels, named argument labels, declaration
+names, local Feature binders, strings and comments are protected. This repairs
+a reproduced collision where a lowercase Template parameter could replace a
+Hole field label or a shadowing Feature parameter. It replaces the existing
+value-substitution implementation; it adds no whole-document parser dispatch
+or global source rewrite pass. Full Template/Pattern/Feature AST expansion is
+still separate work.
+
+Record initializers retain the full AST expression rather than a regex-matched
+literal prefix. Duplicate fields reject. Existing Version/Date field symbols
+retain their complete spelling using the Record owner's type metadata and
+bounded token boundaries. Existing wide Int literals in Record/Template data
+are preserved; Model Static's existing narrower integer policy is unchanged.
+
+## Qualified language behavior
+
+The compatibility review also reproduced an ignored `tol` in a legacy Record
+array: normal build succeeded with no diagnostic after the array reader kept
+only `8mm`. The source is preserved as
+[`collection-tolerance.firmament`](../../fixtures/Regression/CompileTimeValues/collection-tolerance.firmament),
+with its pre-repair CLI result under `collection-before.json`. A bounded AST
+consumption check now rejects tolerance nodes in Static values that have no
+checked scalar owner before collection erasure. Collection/Table support is
+explicitly deferred; its unsupported annotations cannot silently disappear.
+
+* Record Length/Angle field initializers may declare `tol`.
+* Direct Record members feed admitted primitive/Modify fields and explicit PMI.
+* Scalar and whole-Record Template/Feature parameters preserve requirements.
+* Nested Records, checked `with` overrides and nested Templates retain metadata.
+* Scalar Template defaults and specialized Model Static aliases use the same
+ checked environment; Feature-local direct aliases retain allowances.
+* Nominal `Require` comparisons do not certify tolerance intervals.
+* Arithmetic retains nominal-only semantics and warns when an allowance is
+ dropped. An explicit new `tol` introduces a new requirement and retains its
+ input provenance.
+* Replacing a Record field with an untoleranced value removes its allowance.
+ PMI cannot invent the missing requirement or override a selected one.
+
+The authoring contract and complete example are maintained in
+[`syntax.md`](../public/firmament/syntax.md#typed-tolerances-and-pmi), with
+corresponding [Template](../public/firmament/templates.md) and
+[PMI](../public/firmament/pmi.md) updates.
+
+## Diagnostic and provenance contract
+
+Bound values carry structured origin receipts: source file, source span,
+binding name and an optional location limitation. PMI retains the authored
+projection identity and its requirement's binding chain. CLI validation adds
+`origins` to value rows and `dimensionOrigins` to PMI rows; existing fields
+remain available. These are compiler receipts, not extra AP242 annotations.
+
+The original Record initializer is precisely located. Parameter/local binding
+steps identify their original enclosing declaration. Unavailable expanded or
+imported consumer locations disclose the limitation and anchor to the original
+requirement or source module. This is not a claim of complete expansion maps.
+Located compile-time diagnostics survive later expansion and normal build
+failure; compilation does not retry them through the legacy expansion path.
+Original-source diagnostics are not overwritten by unrelated unbound syntax
+errors from an otherwise admitted domain symbol.
+
+## Qualification
+
+Focused tests exercise acceptance/rejection, nominal dimensions, hole identity,
+real AP242 reinspection and geometric face association, topology, exact STEP
+parity, provenance, nested forwarding, overrides, defaults, local shadowing,
+and validate/build/parse-only agreement. The invalid source witness is
+[`record-unit-mismatch.firmament`](../../fixtures/Regression/CompileTimeValues/record-unit-mismatch.firmament).
+
+The Release solution builds with zero errors (19 existing nullable, analyzer,
+platform/WASM warnings). Focused compiler tests pass 106 cases and focused CLI
+tests pass 10. The Core fast lane passes 1,068 cases. Final full-suite totals
+are **4,840 passed across 20 test assemblies, zero failed and zero skipped**.
+This includes 2,381 Firmament, 507 CLI and 1,201 full Core cases; fast-lane
+results are not used as a substitute for that complete run.
+
+The CLI witness reimports as one body with seven faces and bounds
+`[-20, -15, 0]..[20, 15, 8]` mm. Semantic AP242 inspection recovers one diameter
+with nominal 8 mm, allowances +0.10/−0.05 mm and a nonempty cylindrical face
+association. The typed export is byte-identical to the pre-pass literal STEP.
+Twelve earlier STEP specimens also retain their exact bytes. These cover
+symmetry, profile links, primitive holes, Template/Pattern construction and
+existing literal/typed PMI.
+
+Eight complete documentation examples compile. Fifteen real CLI checks pass,
+including all three admission commands for an invalid Record requirement,
+rejection of unsupported collection annotations, threaded bolt, GuitarX0,
+Industrial ATLAS, WarmModernHouse, FactoryX0, sheet metal and existing PMI.
+Assembly/Scene checks use their existing inspection commands; they are not a
+new assembly STEP byte-parity claim or a live Helios UI qualification.
+
+Reproduction commands:
+
+```powershell
+dotnet build Aetheris.slnx -c Release --no-restore -m:1 -nr:false -p:UseSharedCompilation=false
+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
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll validate fixtures/Canonical/PMI/record-template-feature-tolerance.firmament --json --explain
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build fixtures/Canonical/PMI/record-template-feature-tolerance.firmament --output artifacts/local/firmament-value-binding/typed.step --json
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll analyze artifacts/local/firmament-value-binding/typed.step --json
+```
+
+Detailed machine-local evidence remains in ignored
+`artifacts/local/firmament-value-binding/`, including `qualify.ps1`, build/test
+logs, the before/after specimens' CLI output, topology/PMI inspection,
+documentation receipts and STEP comparisons.
+
+## Code-quality review
+
+The new lane reuses the existing scalar evaluator, Record field metadata,
+diagnostic objects, mechanical lowerers and PMI exporter. Both admission
+commands consume the checked mechanical document. No diagnostic-code fatality
+allowlist, new parser route, global rewrite pass, product-side validator or
+geometry operation is added. The only value-substitution changes replace the
+two existing owners' regex substitutions with shared token/AST span handling;
+Record Version/Date recognition is local and schema-directed. The environment
+is per compilation, with no global mutable value registry or background host.
+Source-located receipts survive specialization, and missing consumer maps are
+disclosed. `git diff --check` passes; no repository formatting pass is included.
+Builds/tests ran serially with MSBuild node reuse and shared compiler hosts
+disabled. Final process inspection found zero dotnet, MSBuild or testhost
+processes remaining. This is runtime hygiene evidence, not a general memory
+profiler certification.
+
+## Remaining boundaries
+
+This pass does not implement interval/tolerance-stack arithmetic, angular or
+general distance/GD&T PMI export, toleranced Table/collection elements, arbitrary
+nested scalar environments or every material domain's expression positions.
+Existing Profile/Compose and other domain owners retain their established
+typed inputs and explicit admission limits. Enum-valued scalar Static and
+universal Match exhaustiveness are not added. Existing numeric-policy seams
+are not declared globally reconciled.
+
+Complete AST expansion/source maps and the remaining domain owner migrations
+remain tracked in the [decision register](../development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md).
+No user syntax or engineering-policy decision blocks the qualified value lane.
+
+## Verdict
+
+**Success for the compile-time value-binding pass.** The motivating source now
+builds through normal unified mechanical admission and exports its requirement
+correctly. Scalar/Record transport preserves nominal geometry, allowances and
+authored receipts; unsupported collection annotations and cyclic Record data
+reject rather than disappearing or recursing indefinitely. Existing qualified
+geometry retains its bytes. This is not a claim that all remaining frontend
+owners, expressions or expansion maps have migrated.
diff --git a/docs/release/FIRMAMENT-TYPED-TOLERANCES.md b/docs/release/FIRMAMENT-TYPED-TOLERANCES.md
index 40d97eb4..fbb13408 100644
--- a/docs/release/FIRMAMENT-TYPED-TOLERANCES.md
+++ b/docs/release/FIRMAMENT-TYPED-TOLERANCES.md
@@ -1,5 +1,9 @@
# Firmament typed tolerances and language roles
+Follow-up: [compile-time value binding](FIRMAMENT-COMPILE-TIME-VALUES.md)
+extends the qualified lane through Record, Template and Feature inputs.
+The original pass boundaries below remain its historical qualification record.
+
## Contract
`Static drillDiameter: Length = 8mm tol +0.10mm -0.05mm` is an immutable
diff --git a/fixtures/Canonical/PMI/record-template-feature-tolerance.firmament b/fixtures/Canonical/PMI/record-template-feature-tolerance.firmament
new file mode 100644
index 00000000..46be63e8
--- /dev/null
+++ b/fixtures/Canonical/PMI/record-template-feature-tolerance.firmament
@@ -0,0 +1,29 @@
+// One engineering requirement crosses data, specialization and recipe boundaries.
+Record BoreSpec {
+ diameter: Length
+ width: Length
+}
+Static standardBore: BoreSpec = BoreSpec {
+ diameter: 8mm tol +0.10mm -0.05mm
+ width: 40mm
+}
+
+Template<spec: BoreSpec>
+Model PlateFamily {
+ units: mm
+ Feature Drill(diameter: Length) -> Hole<Shaft> {
+ let inspection: Length = diameter
+ return Hole<Shaft> {
+ on: +Z
+ center: Point2(0mm, 0mm)
+ diameter: inspection
+ end: ThroughAll
+ }
+ }
+ Box Body { size: [spec.width, 30mm, 8mm] }
+ Modify Body { Feature Mount = Drill(diameter: spec.diameter) }
+ Pmi {
+ HoleDiameter MountSize { target: Mount dimension: spec.diameter }
+ }
+}
+Model TolerancedProduct = PlateFamily<spec: standardBore>
diff --git a/fixtures/Regression/CompileTimeValues/collection-tolerance.firmament b/fixtures/Regression/CompileTimeValues/collection-tolerance.firmament
new file mode 100644
index 00000000..c488c12d
--- /dev/null
+++ b/fixtures/Regression/CompileTimeValues/collection-tolerance.firmament
@@ -0,0 +1,12 @@
+Model CollectionRequirement {
+ units: mm
+ Record MountSpec { center: Point2 diameter: Length }
+ Static mounts: MountSpec[] = [
+ MountSpec { center: Point2(0mm, 0mm) diameter: 8mm tol 0.1mm }
+ ]
+ Template<spec: MountSpec> Drill {
+ Hole<Shaft> Mount { on: +Z center: spec.center diameter: spec.diameter end: ThroughAll }
+ }
+ Box Body { size: [40mm, 30mm, 8mm] }
+ Modify Body { Pattern Mounts Over mounts { Drill<Current> } }
+}
diff --git a/fixtures/Regression/CompileTimeValues/record-unit-mismatch.firmament b/fixtures/Regression/CompileTimeValues/record-unit-mismatch.firmament
new file mode 100644
index 00000000..05c2b5df
--- /dev/null
+++ b/fixtures/Regression/CompileTimeValues/record-unit-mismatch.firmament
@@ -0,0 +1,11 @@
+Record BoreSpec { diameter: Length }
+Static production: BoreSpec { diameter: 8mm tol 0.1deg }
+Template<spec: BoreSpec> Model PlateFamily {
+ units: mm
+ Box Body { size: [40mm, 30mm, 8mm] }
+ Modify Body {
+ Hole<Shaft> Mount { on: +Z center: Point2(0mm, 0mm) diameter: spec.diameter end: ThroughAll }
+ }
+ Pmi { HoleDiameter MountSize { target: Mount dimension: spec.diameter } }
+}
+Model InvalidProduct = PlateFamily<spec: production>