Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Implement Firmament V2 toleranced lets

Yuechen Li58c7aecbbffa
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs
index 62dbaecd..0e53e097 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs
@@ -892,7 +892,6 @@ model BadPmiDiameter {
[InlineData("let scale: float = 1.25mm", FirmamentV2Parser.LetUnitMismatch)]
[InlineData("let unknownThing: banana = 1", FirmamentV2Parser.LetUnknownType)]
[InlineData("let radius: length = holeDiameter / 2", FirmamentV2Parser.ExpressionUnknownSymbol)]
- [InlineData("let holeDiameter: length = 6.0mm tol 0.05mm", FirmamentV2Parser.LetInvalidLiteral)]
public void FirmamentV2Parser_LetPrimitiveLiterals_InvalidCasesAreDiagnostics(string letSource, string expectedDiagnostic)
{
var result = FirmamentV2Parser.Parse($$"""
@@ -979,6 +978,79 @@ model BadPmiDiameter {
AssertLet(Assert.Single(result.Document!.BoundLets!), "exportedHoleDiameter", FirmamentV2PrimitiveType.Length, 6.0d, "mm");
}
+
+ [Fact]
+ public void FirmamentV2Parser_TolerancedValues_ParseBilateralAsymmetricAndRecordFields()
+ {
+ var result = FirmamentV2Parser.Parse(Source("Language/valid/let-toleranced-values.valid.firmfixture"));
+
+ Assert.True(result.IsSuccess, string.Join(", ", result.Diagnostics));
+ var lets = result.Document!.BoundLets!.ToDictionary(l => l.Name);
+ AssertLet(lets["holeDiameter"], "holeDiameter", FirmamentV2PrimitiveType.Length, 6.0d, "mm");
+ AssertTolerance(lets["holeDiameter"].Tolerance, FirmamentV2ToleranceKind.Bilateral, 0.05d, 0.05d, "mm");
+ AssertTolerance(lets["slotWidth"].Tolerance, FirmamentV2ToleranceKind.Asymmetric, 0.10d, 0.05d, "mm");
+ AssertTolerance(lets["draftAngle"].Tolerance, FirmamentV2ToleranceKind.Bilateral, 0.5d, 0.5d, "deg");
+
+ var fields = Assert.Single(result.Document!.BoundLetRecords!).Fields;
+ AssertTolerance(fields["holeDiameter"].Tolerance, FirmamentV2ToleranceKind.Bilateral, 0.05d, 0.05d, "mm");
+ AssertTolerance(fields["holeSpacingX"].Tolerance, FirmamentV2ToleranceKind.Asymmetric, 0.10d, 0.05d, "mm");
+ }
+
+ [Fact]
+ public void FirmamentV2Parser_TolerancedExpressions_ExplicitToleranceAndAliasesBehaveDeterministically()
+ {
+ var result = FirmamentV2Parser.Parse("""
+ model TolerancedExpressions {
+ units mm
+ solid base: Box { size: [10, 8, 6] }
+ let holeDiameter: length = 6.0mm tol 0.05mm
+ let clearance: length = 0.25mm
+ let drill: length = holeDiameter + clearance tol 0.05mm
+ let radius: length = holeDiameter / 2
+ let exportedHoleDiameter: length = holeDiameter
+ let MountingPattern { fieldDiameter: length = 7.0mm tol 0.1mm }
+ let exportedFieldDiameter: length = MountingPattern.fieldDiameter
+ }
+ """);
+
+ Assert.True(result.IsSuccess, string.Join(", ", result.Diagnostics));
+ Assert.Contains(FirmamentV2Parser.ToleranceDroppedThroughArithmetic, result.Diagnostics);
+ var lets = result.Document!.BoundLets!.ToDictionary(l => l.Name);
+ AssertLet(lets["drill"], "drill", FirmamentV2PrimitiveType.Length, 6.25d, "mm");
+ AssertTolerance(lets["drill"].Tolerance, FirmamentV2ToleranceKind.Bilateral, 0.05d, 0.05d, "mm");
+ AssertLet(lets["radius"], "radius", FirmamentV2PrimitiveType.Length, 3.0d, "mm");
+ Assert.Null(lets["radius"].Tolerance);
+ AssertTolerance(lets["exportedHoleDiameter"].Tolerance, FirmamentV2ToleranceKind.Bilateral, 0.05d, 0.05d, "mm");
+ AssertTolerance(lets["exportedFieldDiameter"].Tolerance, FirmamentV2ToleranceKind.Bilateral, 0.1d, 0.1d, "mm");
+ }
+
+ [Theory]
+ [InlineData("let holeCount: int = 4 tol 1", FirmamentV2Parser.ToleranceInvalidType)]
+ [InlineData("let scale: float = 1.25 tol 0.01", FirmamentV2Parser.ToleranceInvalidType)]
+ [InlineData("let name: string = \"Aluminum\" tol 1", FirmamentV2Parser.ToleranceInvalidType)]
+ [InlineData("let flag: bool = true tol 1", FirmamentV2Parser.ToleranceInvalidType)]
+ [InlineData("let holeDiameter: length = 6.0mm tol 0.5deg", FirmamentV2Parser.ToleranceUnitMismatch)]
+ [InlineData("let draftAngle: angle = 3deg tol 0.1mm", FirmamentV2Parser.ToleranceUnitMismatch)]
+ [InlineData("let x: length = 1.0mm tol +0.1mm", FirmamentV2Parser.ToleranceMissingMinus)]
+ [InlineData("let x: length = 1.0mm tol -0.1mm", FirmamentV2Parser.ToleranceNegativeBilateral)]
+ [InlineData("let x: length = 1.0mm tol +0.1mm +0.2mm", FirmamentV2Parser.ToleranceMissingMinus)]
+ [InlineData("let x: length = 1.0mm tol -0.1mm +0.2mm", FirmamentV2Parser.ToleranceMissingPlus)]
+ [InlineData("let x: length = 1.0mm tol 0.1", FirmamentV2Parser.ToleranceInvalidLiteral)]
+ [InlineData("let bad: length = (6.0mm tol 0.05mm) + 1.0mm", FirmamentV2Parser.ToleranceUnsupported)]
+ public void FirmamentV2Parser_TolerancedValues_InvalidCasesAreDiagnostics(string letSource, string expectedDiagnostic)
+ {
+ var result = FirmamentV2Parser.Parse($$"""
+ model InvalidTolerance {
+ units mm
+ solid base: Box { size: [10, 8, 6] }
+ {{letSource}}
+ }
+ """);
+
+ Assert.False(result.IsSuccess);
+ Assert.Contains(expectedDiagnostic, result.Diagnostics);
+ }
+
[Fact]
public void FirmamentV2Parser_LetArithmeticExpressions_EvaluateStrictTypedGraph()
{
@@ -1022,7 +1094,6 @@ model BadPmiDiameter {
[Theory]
[InlineData("let MountingPattern { holeDiameter: length = 6.0mm holeDiameter: length = 7.0mm }", FirmamentV2Parser.LetInvalidLiteral)]
- [InlineData("let MountingPattern { holeDiameter: length = 6.0mm tol 0.05mm }", FirmamentV2Parser.LetInvalidLiteral)]
[InlineData("let MountingPattern { radius: length = holeDiameter / 2 }", FirmamentV2Parser.LetLiteralOnly)]
[InlineData("let Process { Tooling { minimumRadius: length = 1.5mm } }", FirmamentV2Parser.LetInvalidLiteral)]
public void FirmamentV2Parser_LetRecordGroups_InvalidRecordBodiesAreDiagnostics(string recordSource, string expectedDiagnostic)
@@ -1096,4 +1167,13 @@ model BadPmiDiameter {
Assert.Equal(unit, actual.Value.Unit);
}
+ private static void AssertTolerance(FirmamentV2Tolerance? actual, FirmamentV2ToleranceKind kind, double plus, double minus, string unit)
+ {
+ Assert.NotNull(actual);
+ Assert.Equal(kind, actual.Kind);
+ Assert.Equal(plus, actual.Plus);
+ Assert.Equal(minus, actual.Minus);
+ Assert.Equal(unit, actual.Unit);
+ }
+
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 5a5175fd..e41dd480 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -13,23 +13,25 @@ public sealed record FirmamentV2Document(string ModelName, string Units, IReadOn
public sealed record FirmamentV2SourceSpan(int Start, int Length);
public enum FirmamentV2PrimitiveType { Int, Float, Length, Angle, String, Bool }
+public enum FirmamentV2ToleranceKind { Bilateral, Asymmetric }
+public sealed record FirmamentV2Tolerance(FirmamentV2ToleranceKind Kind, double Plus, double Minus, string Unit, FirmamentV2PrimitiveType Type, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2LiteralValue(FirmamentV2PrimitiveType Type, object Value, double? NumericValue = null, string? Unit = null, string? Raw = null);
public abstract record FirmamentV2ValueExpression;
public sealed record FirmamentV2LiteralExpression(FirmamentV2LiteralValue Value) : FirmamentV2ValueExpression;
public sealed record FirmamentV2DottedReferenceExpression(string RecordName, string FieldName, string Source) : FirmamentV2ValueExpression;
public sealed record FirmamentV2IdentifierReferenceExpression(string Name, string Source) : FirmamentV2ValueExpression;
public sealed record FirmamentV2BinaryExpression(FirmamentV2ValueExpression Left, string Operator, FirmamentV2ValueExpression Right, string Source) : FirmamentV2ValueExpression;
-public sealed record FirmamentV2LetDeclaration(string Name, FirmamentV2PrimitiveType DeclaredType, FirmamentV2ValueExpression ValueExpression, FirmamentV2SourceSpan SourceSpan)
+public sealed record FirmamentV2LetDeclaration(string Name, FirmamentV2PrimitiveType DeclaredType, FirmamentV2ValueExpression ValueExpression, FirmamentV2SourceSpan SourceSpan, FirmamentV2Tolerance? Tolerance = null)
{
public FirmamentV2LiteralValue LiteralValue => ValueExpression is FirmamentV2LiteralExpression literal ? literal.Value : throw new InvalidOperationException("Let value is not a literal.");
}
public sealed record FirmamentV2LetRecordDeclaration(string Name, IReadOnlyList<FirmamentV2LetRecordField> Fields, FirmamentV2SourceSpan SourceSpan);
-public sealed record FirmamentV2LetRecordField(string Name, FirmamentV2PrimitiveType DeclaredType, FirmamentV2ValueExpression ValueExpression, FirmamentV2SourceSpan SourceSpan)
+public sealed record FirmamentV2LetRecordField(string Name, FirmamentV2PrimitiveType DeclaredType, FirmamentV2ValueExpression ValueExpression, FirmamentV2SourceSpan SourceSpan, FirmamentV2Tolerance? Tolerance = null)
{
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);
-public sealed record FirmamentV2BoundLet(string Name, FirmamentV2PrimitiveType Type, FirmamentV2LiteralValue Value, FirmamentV2SourceSpan SourceSpan, FirmamentV2BoundExpression? Expression = null, IReadOnlySet<string>? Dependencies = null);
+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 FirmamentV2BoundLetRecord(string Name, IReadOnlyDictionary<string, FirmamentV2BoundLet> Fields, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2SolidBinding(string Name, string RecordType, FirmamentV2PrimitiveRecord Primitive, string? DerivedFrom = null, IReadOnlyDictionary<string, IReadOnlyList<double>>? Overrides = null)
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 08875f4d..89170989 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -61,6 +61,14 @@ public static class FirmamentV2Parser
public const string ExpressionDivisionByZero = "firmament-v2-expression-division-by-zero";
public const string ExpressionCycle = "firmament-v2-expression-cycle";
public const string ExpressionUnsupported = "firmament-v2-expression-unsupported";
+ public const string ToleranceInvalidType = "firmament-v2-tolerance-invalid-type";
+ public const string ToleranceUnitMismatch = "firmament-v2-tolerance-unit-mismatch";
+ public const string ToleranceInvalidLiteral = "firmament-v2-tolerance-invalid-literal";
+ public const string ToleranceNegativeBilateral = "firmament-v2-tolerance-negative-bilateral";
+ public const string ToleranceMissingMinus = "firmament-v2-tolerance-missing-minus";
+ public const string ToleranceMissingPlus = "firmament-v2-tolerance-missing-plus";
+ public const string ToleranceDroppedThroughArithmetic = "firmament-v2-tolerance-dropped-through-arithmetic";
+ public const string ToleranceUnsupported = "firmament-v2-tolerance-unsupported";
public const string ModifyTargetUnresolved = "firmament-v2-modify-target-unresolved";
public const string ModifyTargetNotSolid = "firmament-v2-modify-target-not-solid";
@@ -133,7 +141,7 @@ public static class FirmamentV2Parser
private static readonly Regex ModelRegex = new(@"\bmodel\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex UnitsRegex = new(@"\bunits\s+(?<units>[A-Za-z_][A-Za-z0-9_]*)\b", RegexOptions.CultureInvariant);
- private static readonly HashSet<string> ReservedWords = new(StringComparer.Ordinal) { "let", "model", "units", "solid", "modify", "region", "cut", "template", "concept", "pmi", "recognize", "replace", "with", "true", "false", "int", "float", "length", "angle", "string", "bool" };
+ private static readonly HashSet<string> ReservedWords = new(StringComparer.Ordinal) { "let", "model", "units", "solid", "modify", "region", "cut", "template", "concept", "pmi", "recognize", "replace", "with", "true", "false", "int", "float", "length", "angle", "string", "bool", "tol" };
private static readonly Regex LetRegex = new(@"\blet\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<type>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?<literal>[^\r\n{}]+)", RegexOptions.CultureInvariant);
private static readonly Regex LetRecordHeaderRegex = new(@"^\s*let\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant | RegexOptions.Multiline);
private static readonly Regex LetRecordFieldRegex = new(@"^\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<type>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?<literal>.+?)\s*$", RegexOptions.CultureInvariant);
@@ -267,8 +275,9 @@ public static class FirmamentV2Parser
var fieldName = fm.Groups["name"].Value;
if (ReservedWords.Contains(fieldName) || !fieldNames.Add(fieldName)) { diagnostics.Add(LetRecordDuplicateField); continue; }
if (!TryParseLetType(fm.Groups["type"].Value, out var type)) { diagnostics.Add(LetUnknownType); continue; }
- var expr = ParseLetValueExpression(type, fm.Groups["literal"].Value.Trim(), diagnostics);
- if (expr is FirmamentV2LiteralExpression) fields.Add(new(fieldName, type, expr, new FirmamentV2SourceSpan(open + 1 + body.IndexOf(rawLine, StringComparison.Ordinal), rawLine.Length)));
+ var (valueText, tolerance) = ParseOptionalTolerance(type, fm.Groups["literal"].Value.Trim(), diagnostics);
+ var expr = ParseLetValueExpression(type, valueText, diagnostics);
+ if (expr is FirmamentV2LiteralExpression) fields.Add(new(fieldName, type, expr, new FirmamentV2SourceSpan(open + 1 + body.IndexOf(rawLine, StringComparison.Ordinal), rawLine.Length), tolerance));
else if (expr is not null) diagnostics.Add(LetLiteralOnly);
}
records.Add(new(name, fields, new FirmamentV2SourceSpan(match.Index, close - match.Index + 1)));
@@ -287,8 +296,9 @@ public static class FirmamentV2Parser
names.Add(name);
if (!TryParseLetType(match.Groups["type"].Value, out var type)) { diagnostics.Add(LetUnknownType); continue; }
var literal = match.Groups["literal"].Value.Trim();
- var value = ParseLetValueExpression(type, literal, diagnostics);
- if (value is not null) lets.Add(new FirmamentV2LetDeclaration(name, type, value, new FirmamentV2SourceSpan(match.Index, match.Length)));
+ var (valueText, tolerance) = ParseOptionalTolerance(type, literal, diagnostics);
+ var value = ParseLetValueExpression(type, valueText, diagnostics);
+ if (value is not null) lets.Add(new FirmamentV2LetDeclaration(name, type, value, new FirmamentV2SourceSpan(match.Index, match.Length), tolerance));
}
return lets;
}
@@ -311,7 +321,7 @@ public static class FirmamentV2Parser
private static FirmamentV2ValueExpression? ParseLetValueExpression(FirmamentV2PrimitiveType type, string literal, List<string> diagnostics)
{
if (literal.Contains(" tol ", StringComparison.Ordinal) || literal.Contains(" if ", StringComparison.Ordinal) || literal.StartsWith("if ", StringComparison.Ordinal) || Regex.IsMatch(literal, @"^[A-Za-z_][A-Za-z0-9_]*\s*\(", RegexOptions.CultureInvariant))
- { diagnostics.Add(literal.Contains("tol", StringComparison.Ordinal) ? LetInvalidLiteral : ExpressionUnsupported); return null; }
+ { diagnostics.Add(literal.Contains("tol", StringComparison.Ordinal) ? ToleranceUnsupported : ExpressionUnsupported); return null; }
if (literal.IndexOfAny(['+', '-', '*', '/', '(', ')']) >= 0)
{
var parser = new LetExpressionParser(literal, diagnostics);
@@ -324,6 +334,45 @@ public static class FirmamentV2Parser
return value is null ? null : new FirmamentV2LiteralExpression(value);
}
+ private static (string ValueText, FirmamentV2Tolerance? Tolerance) ParseOptionalTolerance(FirmamentV2PrimitiveType type, string text, List<string> diagnostics)
+ {
+ if (Regex.IsMatch(text, @"\([^)]*\s+tol\s+", RegexOptions.CultureInvariant))
+ {
+ diagnostics.Add(ToleranceUnsupported);
+ return (text, null);
+ }
+ var match = Regex.Match(text, @"^(?<value>.+?)\s+tol\s+(?<tol>.+)$", RegexOptions.CultureInvariant);
+ if (!match.Success) return (text, null);
+ if (type is not (FirmamentV2PrimitiveType.Length or FirmamentV2PrimitiveType.Angle)) diagnostics.Add(ToleranceInvalidType);
+ var tolerance = ParseTolerance(type, match.Groups["tol"].Value.Trim(), diagnostics);
+ return (match.Groups["value"].Value.Trim(), tolerance);
+ }
+
+ private static FirmamentV2Tolerance? ParseTolerance(FirmamentV2PrimitiveType type, string text, List<string> diagnostics)
+ {
+ var expectedUnit = type == FirmamentV2PrimitiveType.Length ? "mm" : type == FirmamentV2PrimitiveType.Angle ? "deg" : null;
+ var bilateral = Regex.Match(text, @"^(?<num>[-+]?\d+(?:\.\d+)?)(?<unit>[A-Za-z_][A-Za-z0-9_]*)$", RegexOptions.CultureInvariant);
+ if (bilateral.Success && !text.StartsWith('+'))
+ {
+ var unit = bilateral.Groups["unit"].Value;
+ if (expectedUnit is not null && unit != expectedUnit) diagnostics.Add(ToleranceUnitMismatch);
+ var plus = double.Parse(bilateral.Groups["num"].Value, CultureInfo.InvariantCulture);
+ if (plus < 0) diagnostics.Add(ToleranceNegativeBilateral);
+ return plus < 0 ? null : new(FirmamentV2ToleranceKind.Bilateral, plus, plus, unit, type, new(0, text.Length));
+ }
+ var asymmetric = Regex.Match(text, @"^\+(?<plus>\d+(?:\.\d+)?)(?<plusUnit>[A-Za-z_][A-Za-z0-9_]*)\s+-(?<minus>\d+(?:\.\d+)?)(?<minusUnit>[A-Za-z_][A-Za-z0-9_]*)$", RegexOptions.CultureInvariant);
+ if (asymmetric.Success)
+ {
+ var plusUnit = asymmetric.Groups["plusUnit"].Value; var minusUnit = asymmetric.Groups["minusUnit"].Value;
+ if (plusUnit != minusUnit || (expectedUnit is not null && plusUnit != expectedUnit)) diagnostics.Add(ToleranceUnitMismatch);
+ return new(FirmamentV2ToleranceKind.Asymmetric, double.Parse(asymmetric.Groups["plus"].Value, CultureInfo.InvariantCulture), double.Parse(asymmetric.Groups["minus"].Value, CultureInfo.InvariantCulture), plusUnit, type, new(0, text.Length));
+ }
+ if (text.StartsWith('+')) diagnostics.Add(ToleranceMissingMinus);
+ else if (text.StartsWith('-')) diagnostics.Add(ToleranceMissingPlus);
+ else diagnostics.Add(ToleranceInvalidLiteral);
+ return null;
+ }
+
private static FirmamentV2LiteralValue? ParseLetLiteral(FirmamentV2PrimitiveType type, string literal, List<string> diagnostics)
{
if (literal.Contains('/') || Regex.IsMatch(literal, @"^[A-Za-z_][A-Za-z0-9_]*\b", RegexOptions.CultureInvariant) && type is not FirmamentV2PrimitiveType.Bool)
@@ -360,7 +409,7 @@ public static 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), new HashSet<string>(StringComparer.Ordinal))).ToDictionary(f => f.Name, StringComparer.Ordinal), r.SourceSpan)).ToArray();
+ 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)
{
@@ -450,7 +499,9 @@ public static class FirmamentV2Parser
_visiting.Remove(name);
if (expr is null) return null;
if (expr.InferredType != let.DeclaredType) { _diagnostics.Add(ExpressionTypeMismatch); _diagnostics.Add(LetTypeMismatch); return null; }
- return _bound[name] = new FirmamentV2BoundLet(let.Name, let.DeclaredType, expr.Value, let.SourceSpan, expr, expr.Dependencies);
+ 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);
}
private FirmamentV2BoundExpression? Eval(FirmamentV2ValueExpression e) => e switch
{
@@ -465,14 +516,14 @@ public static class FirmamentV2Parser
if (_records.ContainsKey(r.Name)) { _diagnostics.Add(ExpressionRecordUsedAsValue); _diagnostics.Add(LetReferenceRecordUsedAsValue); return null; }
var b = Bind(r.Name);
if (b is null) { _diagnostics.Add(ExpressionUnknownSymbol); return null; }
- return new(b.Type, b.Value, new HashSet<string>((b.Dependencies ?? new HashSet<string>()).Append(r.Name), StringComparer.Ordinal), b.SourceSpan);
+ return new(b.Type, b.Value, new HashSet<string>((b.Dependencies ?? new HashSet<string>()).Append(r.Name), StringComparer.Ordinal), b.SourceSpan, b.Tolerance);
}
private FirmamentV2BoundExpression? EvalDotted(FirmamentV2DottedReferenceExpression r)
{
if (_solidNames.Contains(r.RecordName) || _letMap.ContainsKey(r.RecordName)) { _diagnostics.Add(ExpressionScalarUsedAsRecord); _diagnostics.Add(LetReferenceNonRecord); return null; }
if (!_records.TryGetValue(r.RecordName, out var record)) { _diagnostics.Add(ExpressionUnknownRecord); _diagnostics.Add(LetReferenceUnknownRecord); return null; }
if (!record.Fields.TryGetValue(r.FieldName, out var f)) { _diagnostics.Add(ExpressionUnknownField); _diagnostics.Add(LetReferenceUnknownField); return null; }
- return new(f.Type, f.Value, new HashSet<string> { $"{r.RecordName}.{r.FieldName}" }, f.SourceSpan);
+ return new(f.Type, f.Value, new HashSet<string> { $"{r.RecordName}.{r.FieldName}" }, f.SourceSpan, f.Tolerance);
}
private FirmamentV2BoundExpression? EvalBinary(FirmamentV2BinaryExpression b)
{
@@ -481,7 +532,7 @@ public static class FirmamentV2Parser
if (type is null) { _diagnostics.Add(ExpressionInvalidOperator); return null; }
if (b.Operator == "/" && IsZero(r.Value)) { _diagnostics.Add(ExpressionDivisionByZero); return null; }
var val = Compute(type.Value, l.Value, b.Operator, r.Value, b.Source);
- return new(type.Value, val, new HashSet<string>(l.Dependencies.Concat(r.Dependencies), StringComparer.Ordinal), new(0, b.Source.Length));
+ return new(type.Value, val, new HashSet<string>(l.Dependencies.Concat(r.Dependencies), StringComparer.Ordinal), new(0, b.Source.Length), null, l.AliasTolerance is not null || r.AliasTolerance is not null || l.UsesTolerancedValueInArithmetic || r.UsesTolerancedValueInArithmetic);
}
private static bool IsZero(FirmamentV2LiteralValue v) => v.NumericValue is double d && d == 0d;
private static FirmamentV2PrimitiveType? ResultType(FirmamentV2PrimitiveType a, string op, FirmamentV2PrimitiveType b) => op switch
@@ -614,7 +665,7 @@ public static class FirmamentV2Parser
return new(name, "Box", new FirmamentV2BoxRecord(values, []), baseName, new Dictionary<string, IReadOnlyList<double>>(StringComparer.Ordinal) { ["size"] = values });
}
- private static bool IsFatalDiagnostic(string code) => code is PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetTypeMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported;
+ private static bool IsFatalDiagnostic(string code) => code is PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetTypeMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported;
private static IReadOnlyList<FirmamentV2Exposure> ParseExposures(string body, List<string> diagnostics)
{
diff --git a/docs/implementation/firmament-v2-l4-toleranced-values.md b/docs/implementation/firmament-v2-l4-toleranced-values.md
new file mode 100644
index 00000000..d9bf7299
--- /dev/null
+++ b/docs/implementation/firmament-v2-l4-toleranced-values.md
@@ -0,0 +1,90 @@
+# Firmament V2 L4 toleranced let values
+
+V2-PHASE1-L4 adds narrow tolerance syntax to Firmament V2 `let` declarations while keeping Firmament pure data: immutable, typed, acyclic, and without functions, conditionals, loops, mutation, hidden state machines, PMI wiring, or tolerance arithmetic.
+
+## Supported syntax
+
+A tolerance may appear after the nominal value expression of a dimensional `let`:
+
+```firmament
+let holeDiameter: length = 6.0mm tol 0.05mm
+let slotWidth: length = 12.0mm tol +0.10mm -0.05mm
+let draftAngle: angle = 3deg tol 0.5deg
+```
+
+The same syntax is available on one-level record fields:
+
+```firmament
+let MountingPattern {
+ holeDiameter: length = 6.0mm tol 0.05mm
+ holeSpacingX: length = 80.0mm tol +0.10mm -0.05mm
+ holeCount: int = 4
+}
+```
+
+Tolerance remains declaration-level syntax. It is not valid inside arbitrary subexpressions such as `(6.0mm tol 0.05mm) + 1.0mm`.
+
+## Forms and storage
+
+`tol 0.05mm` is bilateral tolerance. It is stored as `FirmamentV2ToleranceKind.Bilateral` with positive magnitudes: `plus = 0.05`, `minus = 0.05`, `unit = mm`, and the dimensional primitive type.
+
+`tol +0.10mm -0.05mm` is asymmetric tolerance. It is stored as `FirmamentV2ToleranceKind.Asymmetric` with positive magnitudes: `plus = 0.10`, `minus = 0.05`, `unit = mm`, and the dimensional primitive type. The source signs are syntax only.
+
+Bound scalar lets and bound record fields expose the parsed tolerance through `FirmamentV2BoundLet.Tolerance`; expression binding also carries alias tolerance metadata so future consumers can identify toleranced values without PMI coupling.
+
+## Type and unit rules
+
+L4 supports tolerance only for dimensional primitive types:
+
+- `length` with `mm` tolerances;
+- `angle` with `deg` tolerances.
+
+Tolerance on `int`, `float`, `string`, or `bool` is rejected with `firmament-v2-tolerance-invalid-type`. Unit mismatch is rejected with `firmament-v2-tolerance-unit-mismatch`.
+
+## Alias and arithmetic behavior
+
+Exact scalar aliases preserve tolerance:
+
+```firmament
+let holeDiameter: length = 6.0mm tol 0.05mm
+let exportedHoleDiameter: length = holeDiameter
+```
+
+Exact dotted aliases also preserve tolerance:
+
+```firmament
+let MountingPattern { holeDiameter: length = 6.0mm tol 0.05mm }
+let exportedHoleDiameter: length = MountingPattern.holeDiameter
+```
+
+Arithmetic remains nominal-only. If arithmetic uses a toleranced input and the result has no explicit tolerance, the result binds without tolerance and the parser emits the non-fatal diagnostic `firmament-v2-tolerance-dropped-through-arithmetic`:
+
+```firmament
+let holeDiameter: length = 6.0mm tol 0.05mm
+let radius: length = holeDiameter / 2
+```
+
+If the arithmetic result has an explicit tolerance, that explicit tolerance is used and no propagation is inferred:
+
+```firmament
+let radius: length = holeDiameter / 2 tol 0.025mm
+```
+
+## Diagnostics
+
+L4 adds deterministic tolerance diagnostics:
+
+- `firmament-v2-tolerance-invalid-type`
+- `firmament-v2-tolerance-unit-mismatch`
+- `firmament-v2-tolerance-invalid-literal`
+- `firmament-v2-tolerance-negative-bilateral`
+- `firmament-v2-tolerance-missing-minus`
+- `firmament-v2-tolerance-missing-plus`
+- `firmament-v2-tolerance-dropped-through-arithmetic`
+- `firmament-v2-tolerance-unsupported`
+
+All malformed tolerance forms fail binding except `firmament-v2-tolerance-dropped-through-arithmetic`, which is intentionally non-fatal because the result is a valid nominal-only value.
+
+## Explicit non-scope
+
+L4 does not implement PMI wiring, automatic tolerance propagation, tolerance arithmetic, GD&T/full PMI controls, functions, conditionals, loops, mutation, or changes to STEP/AP242/analyze behavior.
diff --git a/docs/v2/aetheris-v2-phase1-scope-contract.md b/docs/v2/aetheris-v2-phase1-scope-contract.md
index 4f672dfa..ba393d25 100644
--- a/docs/v2/aetheris-v2-phase1-scope-contract.md
+++ b/docs/v2/aetheris-v2-phase1-scope-contract.md
@@ -99,7 +99,7 @@ This doctrine exists because Firmament files must be auditable. Humans, LLMs, su
- L1 primitive immutable typed `let` declarations are implemented.
- L2 grouped one-level `let` records and exact dotted record-field references are implemented for parser/model/binder exposure.
- L3 scalar arithmetic expression graph is implemented with strict primitive type rules, evaluated dependencies, and acyclic validation; same-record field expression binding remains deferred.
-- L4 tolerance syntax remains deferred.
+- L4 toleranced dimensional `let` syntax is implemented for `length`/`angle` scalar lets and literal record fields, with exact-alias tolerance preservation and nominal-only arithmetic drop diagnostics; PMI wiring and automatic tolerance propagation remain out of scope.
## 5. `let` declarations and typed values
diff --git a/fixtures/FirmamentV2/Language/valid/let-toleranced-values.valid.firmfixture b/fixtures/FirmamentV2/Language/valid/let-toleranced-values.valid.firmfixture
new file mode 100644
index 00000000..4d8a5c8d
--- /dev/null
+++ b/fixtures/FirmamentV2/Language/valid/let-toleranced-values.valid.firmfixture
@@ -0,0 +1,17 @@
+// fixture: FirmamentV2 toleranced let values
+// syntax-version: FirmamentV2
+model TolerancedValues {
+ units mm
+ solid base: Box { size: [100, 80, 10] }
+
+ let holeDiameter: length = 6.0mm tol 0.05mm
+ let slotWidth: length = 12.0mm tol +0.10mm -0.05mm
+ let draftAngle: angle = 3deg tol 0.5deg
+
+ let MountingPattern {
+ holeDiameter: length = 6.0mm tol 0.05mm
+ holeSpacingX: length = 80.0mm tol +0.10mm -0.05mm
+ holeSpacingY: length = 40.0mm tol 0.10mm
+ holeCount: int = 4
+ }
+}