Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Route Firmament requirements through concept binding

Yuechen Li0bf9f7da0ee4
diff --git a/Aetheris.CLI.Tests/FirmamentConceptRequirementsCliTests.cs b/Aetheris.CLI.Tests/FirmamentConceptRequirementsCliTests.cs
new file mode 100644
index 00000000..2a0878e0
--- /dev/null
+++ b/Aetheris.CLI.Tests/FirmamentConceptRequirementsCliTests.cs
@@ -0,0 +1,44 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class FirmamentConceptRequirementsCliTests
+{
+ private static string Root => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../.."));
+
+ [Theory]
+ [InlineData("requirements")]
+ [InlineData("shape-prefix")]
+ public void NormalValidationActuallyBuildsTheConceptWitness(string name)
+ {
+ var path = Path.Combine(Root, "fixtures/Canonical/Concepts", name + ".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());
+ }
+
+ [Theory]
+ [InlineData("validate")]
+ [InlineData("build")]
+ [InlineData("parse-only")]
+ public void FalseBundleRejectsAllAdmissionCommandsWithItsLabeledFailure(string command)
+ {
+ var path = Path.Combine(Root, "fixtures/Regression/Concepts/failed-requirement.firmament");
+ var destination = Path.Combine(Root, "artifacts/local/firmament-concepts", 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-concept-requirement-failed");
+ Assert.Equal(path, diagnostic.GetProperty("sourceFile").GetString());
+ Assert.Equal(9, diagnostic.GetProperty("line").GetInt32());
+ Assert.Contains("PlateRequirements.aspect", diagnostic.GetProperty("message").GetString());
+ Assert.False(File.Exists(destination));
+ }
+}
diff --git a/Aetheris.CLI.Tests/FirmamentV2DiagnosticRoutingCliTests.cs b/Aetheris.CLI.Tests/FirmamentV2DiagnosticRoutingCliTests.cs
index 14b14318..8a7cb0e7 100644
--- a/Aetheris.CLI.Tests/FirmamentV2DiagnosticRoutingCliTests.cs
+++ b/Aetheris.CLI.Tests/FirmamentV2DiagnosticRoutingCliTests.cs
@@ -21,9 +21,9 @@ public sealed class FirmamentV2DiagnosticRoutingCliTests
var buildMessages = build.RootElement.GetProperty("diagnostics").EnumerateArray().Select(diagnostic => diagnostic.GetProperty("message").GetString()).ToArray();
var validationDiagnostics = validate.RootElement.GetProperty("firmamentV2Validation").GetProperty("diagnostics").EnumerateArray().ToArray();
- Assert.Contains("HoleLocalCenterInvalid", buildMessages);
+ Assert.Contains(buildMessages, message => message!.Contains("does not provide 'BracketFrame'", StringComparison.Ordinal));
Assert.Contains("firmament-concept-missing-member:BracketConcept.RequiredExpose", buildMessages);
- Assert.Contains(validationDiagnostics, diagnostic => diagnostic.GetProperty("code").GetString() == "HoleLocalCenterInvalid" && diagnostic.GetProperty("severity").GetString() == "fatal");
+ Assert.Contains(validationDiagnostics, diagnostic => diagnostic.GetProperty("code").GetString() == "firmament-concept-structural-conformance-failed" && diagnostic.GetProperty("severity").GetString() == "error");
Assert.Contains(validationDiagnostics, diagnostic => diagnostic.GetProperty("code").GetString() == "firmament-concept-missing-member:BracketConcept.RequiredExpose" && diagnostic.GetProperty("severity").GetString() == "fatal");
Assert.DoesNotContain(buildMessages, message => message!.Contains("FIRM-PARSE-0001", StringComparison.Ordinal) || message.Contains("canonical TOON-style text", StringComparison.Ordinal));
}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentConceptRequirementsTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentConceptRequirementsTests.cs
new file mode 100644
index 00000000..1881330b
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentConceptRequirementsTests.cs
@@ -0,0 +1,316 @@
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentConceptRequirementsTests
+{
+ private static string Fixture(string name) => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Concepts/" + name + ".firmament"));
+
+ [Fact]
+ public void PredicateBundleAdmitsTemplateAndPreservesLiteralGeometry()
+ {
+ var source = Fixture("requirements");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.Equal("Product", parsed.Document!.ModelName);
+ var expansion = Assert.Single(parsed.Document.TemplateInstantiations!);
+ Assert.StartsWith("Passed:", expansion.RequireResults!["dimensions"]);
+ var build = FirmamentBuildAndExport.CompileSource(source);
+ var literal = FirmamentBuildAndExport.CompileSource("Model Product { units: mm Box Body { size: [40mm, 20mm, 5mm] } }");
+ Assert.True(build.IsSuccess, string.Join("\n", build.Diagnostics.Select(d => d.Message)));
+ Assert.True(literal.IsSuccess);
+ Assert.Equal(literal.Value.StepText, build.Value.StepText);
+ Assert.Equal(6, Step242Importer.ImportBody(build.Value.StepText).Value.Topology.Faces.Count());
+ }
+
+ [Fact]
+ public void FailedBundleNamesTheMemberAndRetainsTheAuthoredRequireLocation()
+ {
+ var source = Fixture("requirements").Replace("width: 40mm, height: 20mm", "width: 10mm, height: 20mm");
+ Reject(source, "firmament-concept-requirement-failed");
+ var diagnostic = Assert.Single(FirmamentV2Parser.Parse(source).SyntaxDiagnostics, d => d.Code == "firmament-concept-requirement-failed");
+ Assert.Contains("PlateRequirements.aspect", diagnostic.Message);
+ Assert.Contains("Require dimensions", source.Substring(diagnostic.SourceSpan!.Start, diagnostic.SourceSpan.Length));
+ }
+
+ [Fact]
+ public void GeometryExpansionCannotInventAnOriginalRequirementOffset()
+ {
+ var source = "Square2 unused { center: [0mm,0mm]; size: 10mm }\n" + Fixture("requirements")
+ .Replace("width: 40mm, height: 20mm", "width: 10mm, height: 20mm");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ var diagnostic = Assert.Single(parsed.SyntaxDiagnostics, d => d.Code == "firmament-concept-requirement-failed");
+ Assert.Contains("Require dimensions", source.Substring(diagnostic.SourceSpan!.Start, diagnostic.SourceSpan.Length));
+ Assert.Contains("enclosing", diagnostic.LocationNote);
+ }
+
+ [Theory]
+ [InlineData("true")]
+ [InlineData("!(2mm > 3mm) && (1mm + 2mm == 3mm)")]
+ [InlineData("Positive(value: 4mm)")]
+ [InlineData("Positive(4mm) || false")]
+ [InlineData("length > 2mm")]
+ public void NativeRequireActuallyChecksTheSameBooleanLanguage(string expression)
+ {
+ var source = $$"""
+ Concept Positive(value: Length) => value > 0mm
+ Model Part {
+ units: mm
+ Static length: Length = 4mm tol 0.1mm
+ Require check => {{expression}}
+ Box Body { size: [length, 3mm, 2mm] }
+ }
+ """;
+ var build = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(build.IsSuccess, string.Join("\n", build.Diagnostics.Select(d => d.Message)));
+ }
+
+ [Theory]
+ [InlineData("false", "requirement-failed")]
+ [InlineData("Positive(-1mm)", "requirement-failed")]
+ [InlineData("Positive(1deg)", "argument-type-mismatch")]
+ [InlineData("Positive(other: 1mm)", "argument-invalid")]
+ [InlineData("Positive(1mm, 2mm)", "argument-invalid")]
+ [InlineData("Unknown(1mm)", "name-unresolved")]
+ [InlineData("1mm > 1deg", "expression-type-mismatch")]
+ [InlineData("1mm / 0 > 1mm", "expression-type-mismatch")]
+ [InlineData("true || Unknown(1mm)", "name-unresolved")]
+ [InlineData("1mm", "requirement-non-bool")]
+ public void InvalidRequirementCannotBecomeAnAcceptedBox(string expression, string suffix) =>
+ Reject($$"""
+ Concept Positive(value: Length) => value > 0mm
+ Model Part { units: mm Require check => {{expression}}; Box Body { size: [4mm, 3mm, 2mm] } }
+ """, "firmament-concept-" + suffix);
+
+ [Theory]
+ [InlineData("Concept Positive(value: Length) => Positive(value)", "predicate-cycle")]
+ [InlineData("Concept Positive(value: Length) => value", "requirement-non-bool")]
+ [InlineData("Concept Positive(value: Length) { one: true; one: false }", "bundle-member-invalid")]
+ [InlineData("Concept Positive(value: Length) { Box Body { size: [1mm,1mm,1mm] } }", "bundle-member-invalid")]
+ public void MalformedConceptsFailBeforeMaterialization(string declaration, string suffix) =>
+ Reject(declaration + "\nModel Part { units: mm Require check => Positive(1mm); Box Body { size: [4mm,3mm,2mm] } }", "firmament-concept-" + suffix);
+
+ [Fact]
+ public void UnappliedPredicatesAreTypeCheckedButNeedNotBeTrue()
+ {
+ const string model = "\nModel Part { units: mm Box Body { size: [4mm,3mm,2mm] } }";
+ Reject("Concept Broken(value: Length) => value > 0deg" + model, "firmament-concept-expression-type-mismatch");
+ Reject("Concept Broken => Missing" + model, "firmament-concept-name-unresolved");
+ Assert.True(FirmamentBuildAndExport.CompileSource("Concept AlwaysFalse => false" + model).IsSuccess);
+ }
+
+ [Fact]
+ public void ZeroArgumentPredicatesAndBundlesComposeWithoutConjunctions()
+ {
+ const string source = """
+ Concept First => true
+ Concept Pair { first: First; second: true }
+ Concept Bundle { pair: Pair; another: First }
+ Model Part { units: mm Require check => Bundle; Box Body { size: [4mm,3mm,2mm] } }
+ """;
+ Assert.True(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ Reject(source.Replace("Concept First => true", "Concept First => false"), "firmament-concept-requirement-failed");
+ }
+
+ [Theory]
+ [InlineData("1.5 + 0.5")]
+ [InlineData("4 / 2")]
+ public void IntegralFloatResultsDoNotBecomeIntArguments(string expression) =>
+ Reject($"Concept Integer(value: Int) => value > 0\nModel Part {{ units: mm Require check => Integer({expression}); Box Body {{ size: [4mm,3mm,2mm] }} }}", "firmament-concept-argument-type-mismatch");
+
+ [Fact]
+ public void RecordFieldsAndTypedAllowancesAreNominalInputsToTheRequirement()
+ {
+ var source = Fixture("requirements").Replace("Model Product = Plate<width: 40mm, height: 20mm>", """
+ Record SizeSpec { width: Length; height: Length }
+ Static size: SizeSpec = SizeSpec { width: 40mm tol 0.1mm; height: 20mm }
+ Model Product = Plate<width: size.width, height: size.height>
+ """);
+ var build = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(build.IsSuccess, string.Join("\n", build.Diagnostics.Select(d => d.Message)));
+ var baseline = FirmamentBuildAndExport.CompileSource(Fixture("requirements"));
+ Assert.Equal(baseline.Value.StepText, build.Value.StepText);
+ }
+
+ [Theory]
+ [InlineData("Concept Contract { Bounds: Box3 }", true)]
+ [InlineData("Concept Contract { Missing: Length }", false)]
+ [InlineData("Concept Contract { Bounds: Length }", false)]
+ [InlineData("Concept Contract { Bounds: Box3; Missing: Length }", false)]
+ [InlineData("Concept BoundsContract { Bounds: Box3 } Concept PlaneContract { TopPlane: Plane } Concept Contract : BoundsContract && PlaneContract { }", true)]
+ public void InlineStructuralContractsAndCompositionAreNotVacuouslySatisfied(string contract, bool valid)
+ {
+ var source = contract + "\nTemplate<type T satisfies Contract> Model Part { units: mm Box Body { size: [4mm,3mm,2mm] } }\nModel Product = Part<T: Box>";
+ var parsed = FirmamentV2Parser.Parse(source);
+ var build = FirmamentBuildAndExport.CompileSource(source);
+ Assert.Equal(valid, parsed.IsSuccess);
+ Assert.Equal(valid, build.IsSuccess);
+ if (!valid) Assert.Contains(parsed.Diagnostics, d => d.StartsWith("firmament-template-type-argument-does-not-satisfy-", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("Concept A : B {} Concept B : A {}", "contract-cycle")]
+ [InlineData("Concept A { x: Length; x: Angle }", "contract-member-conflict")]
+ [InlineData("Concept A { x: Length } Concept B { x: Angle } Concept C : A && B {}", "contract-member-conflict")]
+ [InlineData("Concept A : Missing {}", "contract-unresolved")]
+ public void StructuralCompositionErrorsHaveNoGeometry(string declarations, string suffix) =>
+ Reject(declarations + "\nModel Part { units: mm Box Body { size: [4mm,3mm,2mm] } }", "firmament-concept-" + suffix);
+
+ [Theory]
+ [InlineData("Bounds: Box3 { Size: [4mm,3mm,2mm] }", true)]
+ [InlineData("Bounds: 4mm", false)]
+ [InlineData("Other: 4mm", false)]
+ public void AClaimedContractMustBeProvidedByTheActualConceptStruct(string members, bool valid)
+ {
+ var source = $$"""
+ Concept Bounded { Bounds: Box3 }
+ Concept Struct Design: Bounded { {{members}} }
+ Template<type T satisfies Bounded> Model Part { units: mm Box Body { size: [4mm,3mm,2mm] } }
+ Model Product = Part<T: Design>
+ """;
+ Assert.Equal(valid, FirmamentV2Parser.Parse(source).IsSuccess);
+ Assert.Equal(valid, FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Fact]
+ public void AnUnusedConformanceClaimStillCannotLie()
+ {
+ const string source = """
+ Concept Bounded { Bounds: Box3 }
+ Concept Struct Design: Bounded { Bounds: 4mm }
+ Model Part { units: mm Box Body { size: [4mm,3mm,2mm] } }
+ """;
+ Reject(source, "firmament-concept-structural-conformance-failed");
+ var diagnostic = Assert.Single(FirmamentV2Parser.Parse(source).SyntaxDiagnostics, d => d.Code == "firmament-concept-structural-conformance-failed");
+ Assert.Contains("Concept Struct Design", source.Substring(diagnostic.SourceSpan!.Start, diagnostic.SourceSpan.Length));
+ }
+
+ [Fact]
+ public void ExplicitCoordinatesCannotSilentlyDiscardRequestedRotation()
+ {
+ var source = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/Concepts/explicit-rotation.firmament"));
+ Reject(source, "firmament-boundary2-rotation-unsupported");
+ var admitted = FirmamentBuildAndExport.CompileSource(source.Replace("rotation: 90deg", "rotation: 0deg"));
+ Assert.True(admitted.IsSuccess);
+ Assert.Equal(5, Step242Importer.ImportBody(admitted.Value.StepText).Value.Topology.Faces.Count());
+ }
+
+ [Fact]
+ public void RequireDoesNotDisappearFromInsideAPrimitiveFieldBlock() =>
+ Reject("Model Part { units: mm Box Body { size: [4mm,3mm,2mm]; Require check => true } }", "firmament-concept-requirement-scope-unsupported");
+
+ [Fact]
+ public void NativeRequirementKeepsItsExistingStaticInspectionReceipt()
+ {
+ var parsed = FirmamentV2Parser.Parse("Model Part { units: mm Require dimensions => 4mm > 1mm; Box Body { size: [4mm,3mm,2mm] } }");
+ Assert.True(parsed.IsSuccess);
+ var requirement = Assert.Single(parsed.Document!.StaticAuthoring!.Requires);
+ Assert.Equal("dimensions", requirement.Name);
+ Assert.True(requirement.Value);
+ }
+
+ [Fact]
+ public void CompilerDiagnosticProjectsToTheLanguageServiceAtTheAuthoredRequirement()
+ {
+ var source = Fixture("requirements").Replace("width: 40mm, height: 20mm", "width: 10mm, height: 20mm");
+ var analysis = FirmamentLanguageAnalysisService.Analyze(source, "plate.firmament", "draft");
+ var diagnostic = Assert.Single(analysis.Diagnostics, d => d.Code == "firmament-concept-requirement-failed");
+ Assert.Equal("error", diagnostic.Severity);
+ Assert.Contains("Require dimensions", source.Substring(diagnostic.Start, diagnostic.Length));
+ }
+
+ public static TheoryData<string> Shapes => new()
+ {
+ "Rect2 boundary { center: [0mm,0mm]; size: [40mm,20mm] }",
+ "Square2 boundary { center: [0mm,0mm]; size: 20mm }",
+ "Circle2 boundary { center: [0mm,0mm]; radius: 12mm }",
+ "Circle2 boundary { center: [0mm,0mm]; diameter: 24mm }",
+ "Ellipse2 boundary { center: [0mm,0mm]; axisLengths: [40mm,20mm] }",
+ "Slot2 boundary { center: [0mm,0mm]; length: 40mm; width: 12mm }",
+ "RoundedRect2 boundary { center: [0mm,0mm]; size: [40mm,20mm]; radius: 4mm }",
+ "SmoothRoundedRect2 boundary { center: [0mm,0mm]; size: [40mm,20mm]; cornerExtent: 4mm }",
+ "Triangle2<Equilateral> boundary { center: [0mm,0mm]; side: 20mm }",
+ "Triangle2<Isosceles> boundary { center: [0mm,0mm]; base: 30mm; height: 20mm }",
+ "Triangle2<Right> boundary { origin: [0mm,0mm]; legs: [30mm,20mm] }",
+ "Triangle2<Explicit> boundary { a: [0mm,0mm]; b: [30mm,0mm]; c: [0mm,20mm] }",
+ "Polygon2<Rhombus> boundary { center: [0mm,0mm]; diagonals: [40mm,20mm] }",
+ "Polygon2<Parallelogram> boundary { center: [0mm,0mm]; base: 30mm; height: 20mm; shear: 8mm }",
+ "Polygon2<Trapezoid> boundary { center: [0mm,0mm]; bottomWidth: 30mm; topWidth: 20mm; height: 15mm }",
+ "RegularPolygon2<6> boundary { center: [0mm,0mm]; circumradius: 20mm }"
+ };
+
+ [Theory]
+ [MemberData(nameof(Shapes))]
+ public void ConceptShapePrefixHasTheSameGeometryAsThePlainShape(string shape)
+ {
+ var plain = Shape(shape);
+ var prefixed = Shape("Concept " + shape);
+ var baseline = FirmamentBuildAndExport.CompileSource(plain);
+ var compatibility = FirmamentBuildAndExport.CompileSource(prefixed);
+ Assert.True(baseline.IsSuccess, string.Join("\n", baseline.Diagnostics.Select(d => d.Message)));
+ Assert.True(compatibility.IsSuccess, string.Join("\n", compatibility.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(baseline.Value.StepText, compatibility.Value.StepText);
+ }
+
+ [Theory]
+ [InlineData("Concept Circle2 boundary { center: [0mm,0mm]; radius: 12mm; raduis: 8mm }", "canonical-field-unknown")]
+ [InlineData("Concept Slot2 boundary on XZ { center: [0mm,0mm]; length: 40mm; width: 12mm }", "placement-unsupported")]
+ [InlineData("Concept Rect2 boundary { center: [0mm,0mm]; size: [40mm,20mm]; heigth: 20mm }", "canonical-field-unknown")]
+ public void ConceptShapeCannotBypassUnknownFieldsOrPlacement(string shape, string suffix)
+ {
+ var source = Shape(shape);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ Assert.Contains(FirmamentV2Parser.Parse(source).Diagnostics, d => d.Contains(suffix, StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("Concept Rect2 unused { center: Missing; size: [40mm,20mm]; heigth: 10mm }", "canonical-field-unknown")]
+ [InlineData("Concept Circle2 unused { center: Missing; radius: 10mm; raduis: 8mm }", "canonical-field-unknown")]
+ [InlineData("Concept Rect2 unused { center: [0mm,0mm]; size: Missing }", "rect2-invalid-size")]
+ [InlineData("Concept Circle2 unused { center: Missing; radius: 10mm }", "profile-layout-unresolved-circle")]
+ [InlineData("Concept Point2 unused { position: [0mm,0mm]; heigth: 10mm }", "canonical-field-unknown")]
+ public void UnconsumedGuideCannotHideInvalidAuthoringIntent(string declaration, string code)
+ {
+ var source = $"Model Part {{ units: mm {declaration} Box Body {{ size: [4mm,3mm,2mm] }} }}";
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ Assert.Contains(FirmamentV2Parser.Parse(source).Diagnostics, d => d.Contains(code, StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ExplicitPolygonUsesTheSameNamedPointSetWithEitherSpelling()
+ {
+ const string source = """
+ Model GuidePlate {
+ units: mm
+ Static vertices: Set<Point2> { A => Point2(0mm,0mm) B => Point2(30mm,0mm) C => Point2(20mm,20mm) D => Point2(0mm,15mm) }
+ Polygon2<Explicit> boundary { vertices: vertices }
+ Profile outline { Loop Outer { boundary |> TraceLoop } }
+ Extrude Body { profile: outline; from: 0mm; to: 5mm }
+ }
+ """;
+ var plain = FirmamentBuildAndExport.CompileSource(source);
+ var prefixed = FirmamentBuildAndExport.CompileSource(source.Replace("Polygon2<Explicit>", "Concept Polygon2<Explicit>"));
+ Assert.True(plain.IsSuccess, string.Join("\n", plain.Diagnostics.Select(d => d.Message)));
+ Assert.True(prefixed.IsSuccess, string.Join("\n", prefixed.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(plain.Value.StepText, prefixed.Value.StepText);
+ }
+
+ private static string Shape(string declaration) => $$"""
+ Model GuidePlate {
+ units: mm
+ Concept Struct layout on XY { {{declaration}} }
+ Profile outline using layout { Loop Outer { boundary |> TraceLoop } }
+ Extrude Body { profile: outline; from: 0mm; to: 5mm }
+ }
+ """;
+
+ private static void Reject(string source, string code)
+ {
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.Contains(parsed.Diagnostics, d => d.StartsWith(code, StringComparison.Ordinal));
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2DiagnosticRoutingBuildTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2DiagnosticRoutingBuildTests.cs
index f562b0a8..4be28b8c 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2DiagnosticRoutingBuildTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2DiagnosticRoutingBuildTests.cs
@@ -10,7 +10,7 @@ public sealed class FirmamentV2DiagnosticRoutingBuildTests
var result = FirmamentBuildAndExport.Run(FixturePath());
Assert.False(result.IsSuccess);
- Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Message == FirmamentV2Parser.HoleConstructionPlaneCenterMissing);
+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Message.StartsWith("firmament-concept-structural-conformance-failed", StringComparison.Ordinal));
Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Message.StartsWith("firmament-concept-missing-member:", StringComparison.Ordinal));
Assert.DoesNotContain(result.Diagnostics, diagnostic => diagnostic.Message.Contains("FIRM-PARSE-0001", StringComparison.Ordinal));
Assert.DoesNotContain(result.Diagnostics, diagnostic => diagnostic.Message.Contains("canonical TOON-style text", StringComparison.Ordinal));
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs
index 3865b373..04ca805c 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs
@@ -927,7 +927,7 @@ model BadPmiDiameter {
Assert.False(result.IsSuccess);
Assert.Equal(FirmamentV2ParseDisposition.RecognizedInvalid, result.Disposition);
- Assert.Contains(FirmamentV2Parser.HoleConstructionPlaneCenterMissing, result.Diagnostics);
+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.StartsWith("firmament-concept-structural-conformance-failed", StringComparison.Ordinal));
Assert.Contains(result.Diagnostics, diagnostic => diagnostic.StartsWith("firmament-concept-missing-member:", StringComparison.Ordinal));
}
diff --git a/Aetheris.Kernel.Firmament.Tests/GeomRevolveX1Tests.cs b/Aetheris.Kernel.Firmament.Tests/GeomRevolveX1Tests.cs
index a96079e7..d4c8551d 100644
--- a/Aetheris.Kernel.Firmament.Tests/GeomRevolveX1Tests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/GeomRevolveX1Tests.cs
@@ -57,7 +57,9 @@ public sealed class GeomRevolveX1Tests
var expanded = ClosedBoundary2Authoring.Expand(Sphere, diagnostics);
Assert.NotNull(expanded);
Assert.Empty(diagnostics);
- Assert.DoesNotContain(expanded.Boundaries, boundary => boundary.Name == "Meridian");
+ // Concept-prefixed guides now share the plain shape's inspection metadata.
+ // This does not create a full-circle Profile or materialize the guide.
+ Assert.Contains(expanded.Boundaries, boundary => boundary.Name == "Meridian" && boundary.ShapeType == "Circle2");
var profile = ProfileAuthoringParser.ResolveNamedProfile(expanded.Source, "SphereSection", out var profileDiagnostics);
Assert.NotNull(profile);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
index 528d5b38..6a7ab662 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
@@ -1,5 +1,6 @@
using System.Globalization;
using System.Text.RegularExpressions;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
@@ -105,7 +106,7 @@ internal static class CanonicalStaticAuthoring
return mapping;
}
- public static Result? Expand(string source, List<string> diagnostics)
+ public static Result? Expand(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null)
{
var points = ConceptPointAuthoring.Expand(source, diagnostics);
if (points is null) return null;
@@ -117,9 +118,10 @@ internal static class CanonicalStaticAuthoring
if (symmetry is null) return null;
source = symmetry.Source;
var canonicalRoot = Regex.IsMatch(source, @"^\s*Model\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant);
+ var booleanRequires = FirmamentConcepts.Requirements(FirmamentSyntaxParser.Parse(source).Document).ToArray();
var staticDeclaration = Regex.IsMatch(source, @"\b(?:Record|Static|Template\s*(?:<|[A-Za-z_]\w*\s*\()|Pattern\s+\w+\s+Over)\b", RegexOptions.CultureInvariant)
|| symmetry.Mirrors.Count > 0 || symmetry.RadialPatterns.Count > 0 || linear.Patterns.Count > 0 || linear.Axes.Count > 0;
- if (!staticDeclaration && !(canonicalRoot && Regex.IsMatch(source, @"\b(?:Require\s+[A-Za-z_]\w*\s*(?:=>|\{)|Pmi\s*\{[\s\S]*?\bFrom\s*:)", RegexOptions.CultureInvariant))) {
+ if (!staticDeclaration && booleanRequires.Length == 0 && !(canonicalRoot && Regex.IsMatch(source, @"\b(?:Require\s+[A-Za-z_]\w*\s*(?:=>|\{)|Pmi\s*\{[\s\S]*?\bFrom\s*:)", RegexOptions.CultureInvariant))) {
source = points.Math.Normalize(source, diagnostics);
return diagnostics.Any(d => d.StartsWith(ConceptPointAuthoring.Prefix, StringComparison.Ordinal)) ? null : new(source, null);
}
@@ -337,13 +339,31 @@ internal static class CanonicalStaticAuthoring
if (declaration is not null) changes.Add((invocation.Index, invocation.Length, declaration));
}
- foreach (Match require in Regex.Matches(source, @"\bRequire\s+(?<name>[A-Za-z_]\w*)\s*=>\s*(?<expr>[^\r\n}]+)", RegexOptions.CultureInvariant))
+ foreach (var (require, admittedScope) in booleanRequires)
{
- var expression = require.Groups["expr"].Value.Trim();
- if (!TryRequire(expression, out var value)) { diagnostics.Add(Prefix + "require-non-bool:" + require.Groups["name"].Value); continue; }
- requires.Add(new(require.Groups["name"].Value, expression, value, new(require.Index, require.Length)));
- if (!value) diagnostics.Add(Prefix + "require-failed:" + require.Groups["name"].Value + ":" + expression);
- changes.Add((require.Index, require.Length, string.Empty));
+ var name = require.Name?.Text ?? "<unnamed>";
+ if (!admittedScope)
+ {
+ const string code = "firmament-concept-requirement-scope-unsupported";
+ const string message = "Place a Boolean Require in the Model/module or a construction Struct, not inside a primitive or feature field block.";
+ diagnostics.Add(Prefix + "require-invalid-scope:" + name);
+ diagnostics.Add(code + ": " + message);
+ var original = scalars?.OriginalRequirement(name);
+ scalars?.AddConceptDiagnostics([new(code, "error", message) { SourceSpan = original, Stage = "Concept binding" }], original: original is not null);
+ continue;
+ }
+ if (require.Initializer is null || require.Name is null || require.Parameters.Count > 0 || require.Annotation is not null
+ || require.Modifiers.Count > 0 || require.Type.Arguments.Count > 0 || require.Clauses.Count > 0 || require.ResultType is not null)
+ { diagnostics.Add(Prefix + "require-non-bool:" + name); continue; }
+ var expression = source.Substring(require.Initializer.Span.Start, require.Initializer.Span.Length);
+ var concepts = new FirmamentConcepts(source, scalars);
+ var location = scalars?.OriginalRequirement(name);
+ var value = concepts.Check(require.Initializer, name, location);
+ diagnostics.AddRange(concepts.Diagnostics.Select(d => d.Code + ": " + d.Message));
+ scalars?.AddConceptDiagnostics(concepts.Diagnostics, original: location is not null);
+ requires.Add(new(name, expression, value, require.Span));
+ if (!value) diagnostics.Add(Prefix + "require-failed:" + name + ":" + expression);
+ changes.Add((require.Span.Start, require.Span.Length, string.Empty));
}
var semanticConstraints = new List<FirmamentV2SemanticConstraint>();
foreach (Match header in Regex.Matches(source, @"\bRequire\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))
@@ -606,12 +626,5 @@ internal static class CanonicalStaticAuthoring
}
return result;
}
- private static bool TryRequire(string expression, out bool value)
- {
- value = false; var m = Regex.Match(expression, @"^(?<a>[-+]?\d+(?:\.\d+)?)(?<u>mm|deg)?\s*(?<op>>=|<=|==|>|<)\s*(?<b>[-+]?\d+(?:\.\d+)?)(?<v>mm|deg)?$", RegexOptions.CultureInvariant);
- if (!m.Success || m.Groups["u"].Value != m.Groups["v"].Value) return false;
- var a = double.Parse(m.Groups["a"].Value, CultureInfo.InvariantCulture); var b = double.Parse(m.Groups["b"].Value, CultureInfo.InvariantCulture);
- value = m.Groups["op"].Value switch { ">" => a > b, ">=" => a >= b, "<" => a < b, "<=" => a <= b, "==" => a == b, _ => false }; return true;
- }
private static int MatchPair(string text, int open, char left, char right) { var depth = 0; for (var i = open; i < text.Length; i++) { if (text[i] == left) depth++; else if (text[i] == right && --depth == 0) return i; } return -1; }
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
index 6a3fccde..b61be78b 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
@@ -16,6 +16,7 @@ internal static class ClosedBoundary2Authoring
private const double Tol = 1e-9;
internal sealed record Result(string Source, IReadOnlyList<FirmamentV2ClosedBoundary2Decl> Boundaries)
{
+ internal IReadOnlyList<string> GeneratedDeclarationNames { get; init; } = [];
public IReadOnlyList<FirmamentV2Polygon2Decl> Polygons => Boundaries.Where(x => x.ShapeType == "Polygon2")
.Select(x => new FirmamentV2Polygon2Decl(x.Name, x.Variant!, x.CenterX, x.CenterY,
x.Dimensions.GetValueOrDefault("DiagonalX"), x.Dimensions.GetValueOrDefault("DiagonalY"),
@@ -53,10 +54,12 @@ internal static class ClosedBoundary2Authoring
// ProfileGuide is an established authoring annotation emitted by the
// static geometry expander; it does not request a material operation.
fields.Word("Role");
+ var beforeBinding = diagnostics.Count;
var shape = Bind(source, declaration, fields, diagnostics);
// Unbound template/record expressions remain with their specialization
// owner. Successful shape binding must consume every authored field.
if (shape is not null) { fields.Complete(); shapes.Add(shape); }
+ else if (diagnostics.Count == beforeBinding) fields.Complete(); // Deferred values cannot hide unknown fields/header intent.
}
if (diagnostics.Any(FirmamentV2Parser.IsFatalDiagnosticCode)) return null;
var changes = new List<(int Start, int Length, string Text)>();
@@ -94,12 +97,16 @@ internal static class ClosedBoundary2Authoring
}
if (diagnostics.Any(x => x.StartsWith(Prefix, StringComparison.Ordinal))) return null;
foreach (var change in changes.OrderByDescending(x => x.Start)) source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
- return new(source, shapes.Select(x => x.Declaration).ToArray());
+ return new(source, shapes.Select(x => x.Declaration).ToArray())
+ {
+ GeneratedDeclarationNames = shapes.Where(s => s.LoweredSource is not null)
+ .SelectMany(s => s.MemberMap.Values).Distinct(StringComparer.Ordinal).ToArray()
+ };
}
private static IEnumerable<DeclarationSyntax> BoundaryDeclarations(DocumentSyntax syntax) =>
FirmamentSyntaxTraversal.Declarations(syntax)
- .Where(d => d.Name is not null && d.Body is not null && !d.Modifiers.Any(m => m.Name.Text == "Concept")
+ .Where(d => d.Name is not null && d.Body is not null && d.Modifiers.All(m => m.Name.Text == "Concept")
&& d.Type.Name.Text is "Rect2" or "Square2" or "Circle2" or "Ellipse2" or "Slot2" or "RoundedRect2" or "SmoothRoundedRect2" or "Triangle2" or "Polygon2" or "RegularPolygon2");
private static Shape? Bind(string source, DeclarationSyntax declaration, FirmamentSyntaxFields body, List<string> diagnostics)
@@ -111,10 +118,14 @@ internal static class ClosedBoundary2Authoring
var variant = declaration.Type.Arguments.FirstOrDefault()?.Value is { } argument
? FirmamentSyntaxValues.Reference(argument) ?? (argument as LiteralSyntax)?.Raw : null;
var rotation = Angle(body, "Rotation", 0d, out var rotationOk); if (!rotationOk) return Invalid(name, "invalid-rotation", diagnostics);
+ if (variant == "Explicit" && type is "Triangle2" or "Polygon2" && Math.Abs(rotation) > Tol)
+ return Invalid(name, "rotation-unsupported: Explicit boundaries use authored coordinates; rotate the points or place a derived Profile with Curve2", diagnostics);
var span = declaration.Span;
if (type == "Rect2")
{
- if (!Point(body, "Center", out var c) || !Vector(body, "Size", out var size)) return null; // legacy/template Rect2 is bound after static specialization
+ var hasCenter = Point(body, "Center", out var c);
+ var hasSize = Vector(body, "Size", out var size);
+ if (!hasCenter || !hasSize) return null; // legacy/static values are resolved by their existing owner
if (!Positive(size.X, size.Y)) return Invalid(name, "invalid-dimensions", diagnostics);
return Math.Abs(rotation) <= Tol ? ExistingRect(name, c, size.X, size.Y, span)
: Linear(name, type, null, c, rotation, Rectangle(c, size.X, size.Y, rotation), ["BottomLeft", "BottomRight", "TopRight", "TopLeft"], ["Bottom", "Right", "Top", "Left"], span, new Dictionary<string, double> { ["Width"] = size.X, ["Height"] = size.Y });
@@ -171,8 +182,8 @@ internal static class ClosedBoundary2Authoring
private static Shape? Circle(string source, string name, FirmamentSyntaxFields body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)
{
var inline = Point(body, "Center", out var c); var centerRef = Identifier(body, "Center");
- if (!inline && (centerRef is null || !ResolvePoint(source, centerRef, out c))) return null; // legacy/template Circle2 remains on its existing binder path
var hasRadius = Length(body, "Radius", out var radius); var hasDiameter = Length(body, "Diameter", out var diameter);
+ if (!inline && (centerRef is null || !ResolvePoint(source, centerRef, out c))) return null; // named/static centers retain their existing binder
if (hasRadius == hasDiameter || (radius = hasRadius ? radius : diameter / 2) <= 0) return Invalid(name, "invalid-dimensions", diagnostics);
var lowered = inline || hasDiameter ? $"Point2 {name}_Center {{ Position: [{N(c.X)}, {N(c.Y)}] }}\nConcept Circle2 {name}_Curve {{ Center: {name}_Center; Radius: {N(radius)} }}" : null;
var guide = lowered is null ? name : name + "_Curve"; var map = new Dictionary<string, string>(StringComparer.Ordinal) { ["Center"] = inline || hasDiameter ? name + "_Center" : centerRef!, ["Boundary"] = guide };
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
index 965f30b8..d6903be3 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
@@ -188,7 +188,6 @@ internal static class ConceptIrResolver
public const string SelectedBranchEvaluationFailure = "firmament-static-match-selected-branch-evaluation-failure";
public const string InvalidEnumName = "firmament-static-enum-invalid-pascal-case";
- private static readonly Regex ConceptHeader = new(@"\bConcept\s+(?!Struct\b)(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex ConceptStructHeader = new(@"\bConcept\s+Struct\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*(?<concept>[A-Za-z_][A-Za-z0-9_]*))?\s*\{", RegexOptions.CultureInvariant);
private static readonly Regex MaterializedHeader = new(@"\b(?<kind>Struct|Model)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*(?<concept>[A-Za-z_][A-Za-z0-9_]*))?\s*(?<units>mm\s*)?\{", RegexOptions.CultureInvariant);
private static readonly Regex EnumHeader = new(@"\bEnum\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
@@ -636,30 +635,19 @@ internal static class ConceptIrResolver
private static IReadOnlyDictionary<string, ParsedConceptMember> ParseConceptMembers(string body, int bodyOffset, List<string> diagnostics)
{
- var starts = new List<(int Index, Match Match)>();
- var depth = 0;
- for (var lineStart = 0; lineStart < body.Length;)
- {
- var lineEnd = body.IndexOf('\n', lineStart); if (lineEnd < 0) lineEnd = body.Length;
- var line = body[lineStart..lineEnd];
- if (depth == 0)
- {
- var match = Regex.Match(line, @"^\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<rest>.*?)\s*$", RegexOptions.CultureInvariant);
- if (match.Success) starts.Add((lineStart, match));
- }
- depth += line.Count(c => c == '{') - line.Count(c => c == '}');
- lineStart = lineEnd == body.Length ? body.Length : lineEnd + 1;
- }
+ var syntax = FirmamentSyntaxParser.Parse(body);
+ diagnostics.AddRange(syntax.Diagnostics.Select(d => d.Code + ": " + d.Message));
var result = new Dictionary<string, ParsedConceptMember>(StringComparer.Ordinal);
- for (var i = 0; i < starts.Count; i++)
+ // This resolver owns semantic value fields. Layout declarations in the same
+ // Concept Struct belong to the profile/point/derived-frame binders.
+ foreach (var field in syntax.Document.Statements.OfType<FieldSyntax>())
{
- var (start, match) = starts[i]; var end = i + 1 < starts.Count ? starts[i + 1].Index : body.Length;
- var colon = body.IndexOf(':', start, end - start); var raw = body[(colon + 1)..end].Trim();
- var assignment = Regex.Match(raw, @"^(?<type>[A-Za-z_][A-Za-z0-9_]*(?:\[\])?)\s*=\s*(?<expression>.*)$", RegexOptions.Singleline | RegexOptions.CultureInvariant);
- var declaredType = assignment.Success ? assignment.Groups["type"].Value : null;
- var expression = assignment.Success ? assignment.Groups["expression"].Value.Trim() : raw;
- var name = match.Groups["name"].Value;
- if (!result.TryAdd(name, new(name, declaredType, expression, new(bodyOffset + start, end - start)))) diagnostics.Add($"{DuplicateDeclaration}:{name}");
+ var value = field.Value;
+ var declaredType = value is TypedValueSyntax typed ? body.Substring(typed.Type.Span.Start, typed.Type.Span.Length) : null;
+ if (value is TypedValueSyntax assignment) value = assignment.Value;
+ var expression = body.Substring(value.Span.Start, value.Span.Length);
+ if (!result.TryAdd(field.Name.Text, new(field.Name.Text, declaredType, expression,
+ new(bodyOffset + field.Span.Start, field.Span.Length)))) diagnostics.Add($"{DuplicateDeclaration}:{field.Name.Text}");
}
return result;
}
@@ -712,24 +700,25 @@ internal static class ConceptIrResolver
private static IReadOnlyList<ConceptIrDefinition> ParseDefinitions(string source, List<string> diagnostics)
{
- var result = new List<ConceptIrDefinition>();
- var names = new HashSet<string>(StringComparer.Ordinal);
- foreach (Match match in ConceptHeader.Matches(source))
- {
- var open = source.IndexOf('{', match.Index); var close = FindMatchingBrace(source, open);
- if (close < 0) { diagnostics.Add(InvalidSpatialDerivation); continue; }
- var name = match.Groups["name"].Value;
- if (!names.Add(name)) { diagnostics.Add(DuplicateDeclaration); continue; }
- var members = new Dictionary<string, ConceptIrMemberRequirement>(StringComparer.Ordinal);
- var body = source[(open + 1)..close];
- foreach (Match field in Regex.Matches(body, @"(?m)^\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<type>[A-Za-z_][A-Za-z0-9_]*)(?<array>\[\])?\s*$", RegexOptions.CultureInvariant))
- {
- var memberName = field.Groups["name"].Value;
- if (!members.TryAdd(memberName, new(memberName, new(field.Groups["type"].Value, field.Groups["array"].Success), new(open + 1 + field.Index, field.Length)))) diagnostics.Add(DuplicateDeclaration);
- }
- result.Add(new(name, members, new(match.Index, close - match.Index + 1)));
- }
- return result;
+ var concepts = new FirmamentConcepts(source);
+ diagnostics.AddRange(concepts.Diagnostics.Select(d => d.Code + ": " + d.Message));
+ return concepts.Contracts;
+ }
+
+ internal static bool ProvidesContract(string source, DeclarationSyntax declaration, ConceptIrDefinition contract,
+ out IReadOnlyList<string> reported)
+ {
+ reported = [];
+ if (declaration.Body is null || declaration.Body.Statements.Any(s => s is not FieldSyntax))
+ { reported = ["firmament-concept-structural-member-form-unsupported"]; return false; }
+ var diagnostics = new List<string>();
+ var selections = new List<ConceptIrStaticSelection>();
+ var span = declaration.Body.ContentSpan;
+ var members = ResolveMembers(declaration.Name!.Text, source.Substring(span.Start, span.Length), span.Start,
+ "", ParseEnums(source, diagnostics), selections, diagnostics);
+ ValidateConformance(declaration.Name.Text, [contract.Name], members, [contract], diagnostics);
+ reported = diagnostics;
+ return diagnostics.Count == 0;
}
private static IReadOnlyDictionary<string, ConceptIrValue> ResolveMembers(
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs
index 89152500..8a4d37b4 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs
@@ -23,6 +23,34 @@ internal sealed class FirmamentCompileTimeValues(string source)
internal IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics => diagnostics;
+ internal void AddConceptDiagnostics(IEnumerable<FirmamentV2ValidationDiagnostic> reported, bool original = true, string? producerSource = null)
+ {
+ var producer = producerSource is not null && producerSource != source ? FirmamentSyntaxParser.Parse(producerSource).Document : null;
+ foreach (var diagnostic in reported)
+ {
+ if (producer is null) { diagnostics.Add(diagnostic with { IsOriginalSource = original }); continue; }
+ var owner = FirmamentSyntaxTraversal.Declarations(producer).Where(d => d.Name is not null
+ && (d.Type.Name.Text is "Concept" or "Require" || d.Modifiers.Any(m => m.Name.Text == "Template"))
+ && diagnostic.SourceSpan is { } span && d.Span.Start <= span.Start && d.Span.Start + d.Span.Length >= span.Start + span.Length)
+ .OrderBy(d => d.Span.Length).FirstOrDefault();
+ var anchor = owner is null ? null : OriginalDeclaration(owner.Type.Name.Text, owner.Name!.Text);
+ diagnostics.Add(diagnostic with { SourceSpan = anchor, IsOriginalSource = anchor is not null,
+ LocationNote = anchor is null ? "Binding failed after expansion; original-source provenance is unavailable."
+ : "Location identifies the original enclosing declaration; the check evaluated expanded values." });
+ }
+ }
+
+ private DocumentSyntax? originalSyntax;
+ internal FirmamentV2SourceSpan? OriginalRequirement(string name) => OriginalDeclaration("Require", name);
+
+ internal FirmamentV2SourceSpan? OriginalDeclaration(string type, string name, string? modifier = null)
+ {
+ originalSyntax ??= FirmamentSyntaxParser.Parse(source).Document;
+ var matches = FirmamentSyntaxTraversal.Declarations(originalSyntax)
+ .Where(d => d.Type.Name.Text == type && d.Name?.Text == name && (modifier is null || d.Modifiers.Any(m => m.Name.Text == modifier))).ToArray();
+ return matches.Length == 1 ? matches[0].Span : null;
+ }
+
internal void BindExpandedScalars(string expanded, List<string> codes)
{
var declarations = Scope(FirmamentSyntaxParser.Parse(expanded).Document.Statements)
@@ -268,6 +296,7 @@ internal sealed class FirmamentCompileTimeValues(string source)
}
internal bool Contains(string expression) => values.ContainsKey(expression.Trim());
+ internal bool TryValue(string expression, out FirmamentV2BoundLet value) => values.TryGetValue(expression.Trim(), out value!);
internal void RecordError(string record, string field, string code, string message)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentConcepts.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentConcepts.cs
new file mode 100644
index 00000000..e65b96cb
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentConcepts.cs
@@ -0,0 +1,357 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using System.Globalization;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>
+/// Source-level Concept contracts and requirements. All recognition uses the shared AST;
+/// numeric operations retain the existing dimensional syntax binder. This owns neither
+/// material geometry nor Template expansion.
+/// </summary>
+internal sealed class FirmamentConcepts
+{
+ private readonly DocumentSyntax syntax;
+ private readonly string source;
+ private readonly FirmamentCompileTimeValues? scalars;
+ private readonly Dictionary<string, DeclarationSyntax> declarations = new(StringComparer.Ordinal);
+ private readonly Dictionary<string, ConceptIrDefinition> contracts = new(StringComparer.Ordinal);
+ private readonly List<FirmamentV2ValidationDiagnostic> diagnostics = [];
+ private readonly List<string> bindingDiagnostics = [];
+ internal IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics => diagnostics;
+ internal IReadOnlyList<string> BindingDiagnostics => bindingDiagnostics;
+
+ internal FirmamentConcepts(string source, FirmamentCompileTimeValues? scalars = null)
+ {
+ syntax = FirmamentSyntaxParser.Parse(source).Document;
+ this.source = source;
+ this.scalars = scalars;
+ foreach (var d in FirmamentSyntaxTraversal.Declarations(syntax).Where(d => d.Type.Name.Text == "Concept"))
+ {
+ if (d.Name is null) { Add("declaration-invalid", "A Concept needs a name.", d.Span); continue; }
+ if (!declarations.TryAdd(d.Name.Text, d)) Add("duplicate-declaration", $"Concept '{d.Name.Text}' is declared twice.", d.Span);
+ }
+ foreach (var d in declarations.Values)
+ {
+ try
+ {
+ if (d.Modifiers.Count > 0 || d.Type.Arguments.Count > 0 || d.ResultType is not null || d.Clauses.Count > 0 || d.Occurrence
+ || (d.Initializer is null) == (d.Body is null))
+ throw Error("declaration-invalid", "Use Concept Name { member: Type }, Concept Name(parameters) => predicate, or a labeled requirement bundle.", d.Span);
+ if (IsPredicate(d))
+ {
+ if (d.Annotation is not null) throw Error("declaration-invalid", "A predicate Concept returns Bool; structural inheritance belongs to a structural Concept.", d.Annotation.Span);
+ var names = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var p in d.Parameters)
+ if (p.Name is null || !names.Add(p.Name.Text) || p.Default is not null
+ || FirmamentSyntaxValues.Reference(p.Value) is not { } type || !FirmamentV2Parser.TryParseLetType(type, out _))
+ throw Error("parameter-invalid", "Concept parameters need unique names and scalar types (Length, Angle, Int, Float, Bool or String), without defaults.", p.Span);
+ if (d.Body is not null)
+ {
+ if (d.Body.Statements.Count == 0) throw Error("bundle-empty", "A requirement bundle needs at least one labeled Boolean requirement.", d.Body.Span);
+ names.Clear();
+ foreach (var s in d.Body.Statements)
+ if (s is not FieldSyntax f || !names.Add(f.Name.Text))
+ throw Error("bundle-member-invalid", "A requirement bundle contains unique labeled Boolean expressions: name: predicate.", s.Span);
+ }
+ }
+ else _ = Contract(d.Name!.Text, []);
+ }
+ catch (BindingError e) { Add(e); }
+ }
+ // Definitions must type-check even if no Require applies them. Placeholder
+ // values check types, never impose the truth of an unapplied requirement.
+ if (scalars is not null && diagnostics.Count == 0)
+ foreach (var d in declarations.Values.Where(IsPredicate))
+ {
+ try
+ {
+ var arguments = d.Parameters.Select(p => new ArgumentSyntax(null,
+ Sample(FirmamentSyntaxValues.Reference(p.Value)!, p.Span), null, p.Span)).ToArray();
+ _ = Evaluate(new CallSyntax(new ReferenceSyntax(d.Name!, d.Name!.Span), arguments, d.Span),
+ new(StringComparer.Ordinal), [], 0, typeOnly: true);
+ }
+ catch (BindingError e) { Add(e); }
+ }
+ }
+
+ private bool IsPredicate(DeclarationSyntax d)
+ {
+ return Visit(d, new(StringComparer.Ordinal));
+ bool Visit(DeclarationSyntax current, HashSet<string> visiting)
+ {
+ if (current.Initializer is not null || current.Parameters.Count > 0) return true;
+ if (visiting.Count >= 128 || !visiting.Add(current.Name!.Text)) return false;
+ return current.Body?.Statements.OfType<FieldSyntax>().Any(f => !IsType(f.Value)
+ || f.Value is ReferenceSyntax r && declarations.TryGetValue(r.Name.Text, out var target)
+ && Visit(target, new(visiting, StringComparer.Ordinal))) == true;
+ }
+ }
+
+ private static bool IsType(ExpressionSyntax e) => e is ReferenceSyntax or IndexSyntax { Target: ReferenceSyntax, Index: null };
+
+ internal IReadOnlyList<ConceptIrDefinition> Contracts => contracts.Values.ToArray();
+ internal bool HasContract(string name) => declarations.TryGetValue(name, out var d) && !IsPredicate(d);
+
+ internal void ValidateClaims()
+ {
+ Visit(syntax.Statements);
+ void Visit(IReadOnlyList<StatementSyntax> statements)
+ {
+ foreach (var d in statements.OfType<DeclarationSyntax>())
+ {
+ if (d.Type.Name.Text is "Template" or "Feature" || d.Modifiers.Any(m => m.Name.Text == "Template")) continue;
+ if (d.Type.Name.Text == "Struct" && d.Modifiers.Any(m => m.Name.Text == "Concept") && d.Annotation is not null)
+ {
+ var name = FirmamentSyntaxValues.Reference(d.Annotation);
+ if (name is null || !contracts.TryGetValue(name, out var contract))
+ Add("contract-unresolved", "A Concept Struct conformance annotation must name a declared structural Concept; compose contracts in a named Concept first.", d.Annotation.Span);
+ else if (!ConceptIrResolver.ProvidesContract(source, d, contract, out var reasons))
+ {
+ bindingDiagnostics.AddRange(reasons);
+ diagnostics.Add(new("firmament-concept-structural-conformance-failed", "error",
+ $"Concept Struct '{d.Name?.Text}' does not provide '{name}'. Required semantic members: {string.Join(", ", contract.Members.Values.Select(m => m.Name + ": " + m.Type))}. Binding reasons: {string.Join("; ", reasons)}.", Target: d.Name?.Text)
+ { SourceSpan = d.Span, Stage = "Concept binding" });
+ }
+ }
+ else if (d.Type.Name.Text is "Model" or "Struct" && d.Body is not null) Visit(d.Body.Statements);
+ }
+ }
+ }
+
+ internal static IEnumerable<(DeclarationSyntax Declaration, bool AdmittedScope)> Requirements(DocumentSyntax document)
+ {
+ return Visit(document.Statements, true);
+ static IEnumerable<(DeclarationSyntax, bool)> Visit(IReadOnlyList<StatementSyntax> statements, bool admitted)
+ {
+ foreach (var d in statements.OfType<DeclarationSyntax>())
+ {
+ if (d.Type.Name.Text is "Concept" or "Template" or "Feature" || d.Modifiers.Any(m => m.Name.Text == "Template")) continue;
+ if (d.Type.Name.Text == "Require" && d.Body is null) yield return (d, admitted);
+ else if (d.Body is not null)
+ foreach (var child in Visit(d.Body.Statements, d.Type.Name.Text is "Model" or "Struct")) yield return child;
+ }
+ }
+ }
+
+ private ConceptIrDefinition Contract(string name, List<string> stack)
+ {
+ if (contracts.TryGetValue(name, out var known)) return known;
+ if (!declarations.TryGetValue(name, out var d) || IsPredicate(d))
+ throw Error("contract-unresolved", $"'{name}' is not a structural Concept.", declarations.GetValueOrDefault(name)?.Span ?? syntax.Span);
+ if (stack.Contains(name, StringComparer.Ordinal) || stack.Count >= 128)
+ throw Error("contract-cycle", $"Cyclic or excessively deep Concept composition: {string.Join(" -> ", stack.Append(name))}.", d.Span);
+ var members = new Dictionary<string, ConceptIrMemberRequirement>(StringComparer.Ordinal);
+ foreach (var parent in Parents(d.Annotation))
+ foreach (var field in Contract(parent, [.. stack, name]).Members.Values) Merge(field);
+ foreach (var statement in d.Body?.Statements ?? [])
+ {
+ if (statement is not FieldSyntax f || !IsType(f.Value))
+ throw Error("contract-member-invalid", "A structural Concept contains typed members (name: Type); Boolean checks belong in a parameterized requirement bundle.", statement.Span);
+ var element = f.Value is IndexSyntax index ? index.Target : f.Value;
+ Merge(new(f.Name.Text, new(FirmamentSyntaxValues.Reference(element)!, f.Value is IndexSyntax), f.Span), own: true);
+ }
+ return contracts[name] = new(name, members, d.Span);
+
+ void Merge(ConceptIrMemberRequirement member, bool own = false)
+ {
+ if (members.TryGetValue(member.Name, out var previous))
+ {
+ if (previous.Type != member.Type || own)
+ throw Error("contract-member-conflict", $"Concept '{name}' has duplicate or conflicting requirement '{member.Name}' ({previous.Type} and {member.Type}).", member.SourceSpan);
+ return; // A diamond can require the same member with the same type.
+ }
+ members.Add(member.Name, member);
+ }
+ IEnumerable<string> Parents(ExpressionSyntax? e) => e switch
+ {
+ null => [],
+ ReferenceSyntax r => [r.Name.Text],
+ BinarySyntax { Operator: BinaryOperator.And } b => Parents(b.Left).Concat(Parents(b.Right)),
+ _ => throw Error("contract-composition-invalid", "Compose structural Concepts with : First && Second; every name must be a structural Concept.", e.Span)
+ };
+ }
+
+ // A supplied type must provide the required structural signature, including inherited
+ // members. The existing semantic resolver still checks concrete values and Expose.
+ internal bool Satisfies(string type, string concept)
+ {
+ if (!contracts.TryGetValue(concept, out var required)) return false;
+ if (type == "Box")
+ {
+ var available = new Dictionary<string, string>(StringComparer.Ordinal) { ["Bounds"] = "Box3", ["TopPlane"] = "Plane", ["CenterAxis"] = "Axis" };
+ return required.Members.Values.All(m => !m.Type.IsCollection && available.GetValueOrDefault(m.Name) == m.Type.Name);
+ }
+ var supplied = FirmamentSyntaxTraversal.Declarations(syntax).Where(d => d.Type.Name.Text == "Struct"
+ && d.Modifiers.Any(m => m.Name.Text == "Concept") && d.Name?.Text == type).ToArray();
+ if (supplied.Length != 1 || supplied[0].Annotation is not ReferenceSyntax claim || !contracts.TryGetValue(claim.Name.Text, out var actual)) return false;
+ if (!required.Members.Values.All(m => actual.Members.TryGetValue(m.Name, out var provided) && provided.Type == m.Type)) return false;
+ var valid = ConceptIrResolver.ProvidesContract(source, supplied[0], actual, out var reasons);
+ bindingDiagnostics.AddRange(reasons);
+ return valid;
+ }
+
+ internal bool Check(ExpressionSyntax expression, string context, FirmamentV2SourceSpan? location = null)
+ {
+ try
+ {
+ var value = Evaluate(expression, new(StringComparer.Ordinal), [], 0);
+ if (value.Type != "Bool") throw Error("requirement-non-bool", $"Requirement '{context}' must be Bool, not {value.Type}.", expression.Span);
+ if (!(bool)value.Data) throw Error("requirement-failed", $"Requirement '{context}' is false{value.FailedMember}; no geometry was admitted.", expression.Span);
+ return true;
+ }
+ catch (BindingError e)
+ {
+ Add(e);
+ if (location is not null) diagnostics[^1] = diagnostics[^1] with { SourceSpan = location,
+ LocationNote = "Location identifies the authored Require declaration; the check evaluated its specialized values." };
+ return false;
+ }
+ }
+
+ private sealed record Value(string Type, object Data, ExpressionSyntax Syntax, string? FailedMember = null);
+
+ private Value Evaluate(ExpressionSyntax e, Dictionary<string, Value> scope, List<string> stack, int depth, bool typeOnly = false)
+ {
+ if (depth > 128) throw Error("expression-depth", "Concept expressions are limited to 128 nesting levels.", e.Span);
+ Value Eval(ExpressionSyntax child) => Evaluate(child, scope, stack, depth + 1, typeOnly);
+ if (e is SequenceSyntax { Kind: SequenceKind.Tuple, Items.Count: 1 } group) return Eval(group.Items[0].Value);
+ if (e is LiteralSyntax { Kind: LiteralKind.Boolean } boolean) return new("Bool", bool.Parse(boolean.Raw), e);
+ if (e is LiteralSyntax { Kind: LiteralKind.String } text) return new("String", System.Text.Json.JsonSerializer.Deserialize<string>(text.Raw)!, e);
+ if (e is ReferenceSyntax or MemberSyntax)
+ {
+ var name = FirmamentSyntaxValues.Reference(e)!;
+ if (scope.TryGetValue(name, out var local)) return local;
+ if (scalars?.TryValue(name, out var checkedValue) == true)
+ {
+ var nominal = FirmamentSyntaxParser.ParseExpression(scalars.NominalExpression(name)).Expression;
+ if (nominal is not null) return Eval(nominal) with { Type = checkedValue.Type.ToString() };
+ }
+ if (declarations.TryGetValue(name, out var predicate)) return Invoke(predicate, [], e.Span);
+ throw Error("name-unresolved", $"Cannot resolve '{name}' in a Concept requirement.", e.Span);
+ }
+ if (e is CallSyntax call && FirmamentSyntaxValues.Reference(call.Target) is { } target)
+ {
+ if (!declarations.TryGetValue(target, out var predicate)) throw Error("name-unresolved", $"Unknown Concept predicate '{target}'.", call.Target.Span);
+ return Invoke(predicate, call.Arguments, call.Span);
+ }
+ if (e is UnarySyntax { Operator: UnaryOperator.Not } not)
+ {
+ var operand = Eval(not.Operand);
+ if (operand.Type != "Bool") throw TypeError(e);
+ return Boolean(!(bool)operand.Data, e);
+ }
+ if (e is BinarySyntax b && b.Operator is BinaryOperator.And or BinaryOperator.Or)
+ {
+ var left = Eval(b.Left); var right = Eval(b.Right); // Check both operands, including unresolved/ill-typed branches.
+ if (left.Type != "Bool" || right.Type != "Bool") throw TypeError(e);
+ return Boolean(b.Operator == BinaryOperator.And ? (bool)left.Data && (bool)right.Data : (bool)left.Data || (bool)right.Data, e);
+ }
+ if (e is BinarySyntax compare && compare.Operator is BinaryOperator.Equal or BinaryOperator.NotEqual or BinaryOperator.Less or BinaryOperator.LessEqual or BinaryOperator.Greater or BinaryOperator.GreaterEqual)
+ {
+ var left = Eval(compare.Left); var right = Eval(compare.Right);
+ if (left.Type != right.Type && !(IsNumber(left) && IsNumber(right))) throw TypeError(e);
+ var numeric = left.Data is double && right.Data is double;
+ if (!numeric && compare.Operator is not (BinaryOperator.Equal or BinaryOperator.NotEqual)) throw TypeError(e);
+ var order = numeric ? ((double)left.Data).CompareTo((double)right.Data) : Equals(left.Data, right.Data) ? 0 : 1;
+ return Boolean(compare.Operator switch { BinaryOperator.Equal => order == 0, BinaryOperator.NotEqual => order != 0,
+ BinaryOperator.Less => order < 0, BinaryOperator.LessEqual => order <= 0, BinaryOperator.Greater => order > 0, _ => order >= 0 }, e);
+ }
+ // Rebind operands to their checked nominal syntax, then delegate all arithmetic
+ // and dimensional rules to the existing shared geometry/scalar syntax owner.
+ string? arithmeticType = null;
+ ExpressionSyntax Arithmetic(BinarySyntax binary)
+ {
+ var left = Eval(binary.Left); var right = Eval(binary.Right);
+ _ = FirmamentV2Parser.TryParseLetType(left.Type, out var lt);
+ _ = FirmamentV2Parser.TryParseLetType(right.Type, out var rt);
+ var op = binary.Operator switch { BinaryOperator.Add => "+", BinaryOperator.Subtract => "-", BinaryOperator.Multiply => "*", _ => "/" };
+ arithmeticType = FirmamentV2Parser.CompileTimeArithmeticType(lt, op, rt)?.ToString();
+ if (arithmeticType is null) throw TypeError(e);
+ return binary with { Left = left.Syntax, Right = right.Syntax };
+ }
+ ExpressionSyntax Unary(UnarySyntax unary)
+ {
+ var operand = Eval(unary.Operand); arithmeticType = operand.Type;
+ return unary with { Operand = operand.Syntax };
+ }
+ var normalized = e switch
+ {
+ BinarySyntax binary when binary.Operator is BinaryOperator.Add or BinaryOperator.Subtract or BinaryOperator.Multiply or BinaryOperator.Divide => Arithmetic(binary),
+ UnarySyntax unary when unary.Operator is UnaryOperator.Positive or UnaryOperator.Negative => Unary(unary),
+ QuantitySyntax quantity => quantity with { Value = Eval(quantity.Value).Syntax },
+ LiteralSyntax { Kind: LiteralKind.Number } => e,
+ _ => throw Error("expression-unsupported", "Expected a Concept call, scalar comparison, Boolean expression or dimensional arithmetic.", e.Span)
+ };
+ foreach (var unit in new[] { "mm", "deg", "" })
+ if (FirmamentSyntaxValues.TryMeasure(normalized, unit, out var number))
+ {
+ var type = arithmeticType ?? (unit == "mm" ? "Length" : unit == "deg" ? "Angle"
+ : e is LiteralSyntax n && !n.Raw.Contains('.') && !n.Raw.Contains('e', StringComparison.OrdinalIgnoreCase) ? "Int" : "Float");
+ if (typeOnly && e is BinarySyntax) number = 1;
+ if (type == "Int" && (number < int.MinValue || number > int.MaxValue)) throw TypeError(e);
+ var literal = new LiteralSyntax(LiteralKind.Number, number.ToString("R", CultureInfo.InvariantCulture), e.Span);
+ return new(type, number, unit.Length == 0 ? literal : new QuantitySyntax(literal, new(unit, e.Span), e.Span));
+ }
+ throw TypeError(e);
+
+ Value Invoke(DeclarationSyntax d, IReadOnlyList<ArgumentSyntax> arguments, FirmamentV2SourceSpan span)
+ {
+ var name = d.Name!.Text;
+ if (!IsPredicate(d)) throw Error("predicate-expected", $"'{name}' is a structural Concept; use it as a conformance constraint, not a Boolean predicate.", span);
+ if (stack.Contains(name, StringComparer.Ordinal) || stack.Count >= 128)
+ throw Error("predicate-cycle", $"Recursive Concept requirement: {string.Join(" -> ", stack.Append(name))}.", span);
+ if (arguments.Count != d.Parameters.Count) throw Error("argument-invalid", $"Concept '{name}' expects {d.Parameters.Count} argument(s), received {arguments.Count}.", span);
+ var inputs = new Dictionary<string, Value>(StringComparer.Ordinal);
+ for (var i = 0; i < arguments.Count; i++)
+ {
+ var a = arguments[i];
+ var p = a.Name is null ? d.Parameters[i] : d.Parameters.FirstOrDefault(p => p.Name?.Text == a.Name.Text);
+ if (p?.Name is null || inputs.ContainsKey(p.Name.Text) || a.Default is not null)
+ throw Error("argument-invalid", $"Unknown or duplicate argument in Concept '{name}'.", a.Span);
+ var value = Eval(a.Value); var type = FirmamentSyntaxValues.Reference(p.Value)!;
+ if (FirmamentV2Parser.TryParseLetType(type, out var primitive)) type = primitive.ToString();
+ if (value.Type != type && !(type == "Float" && value.Type == "Int"))
+ throw Error("argument-type-mismatch", $"Concept '{name}.{p.Name.Text}' expects {type}, received {value.Type}.", a.Span);
+ inputs.Add(p.Name.Text, value with { Type = type });
+ }
+ var next = new List<string>(stack) { name };
+ if (d.Initializer is not null)
+ {
+ var result = Evaluate(d.Initializer, inputs, next, depth + 1, typeOnly);
+ if (result.Type != "Bool") throw Error("requirement-non-bool", $"Concept '{name}' must return Bool, not {result.Type}.", d.Initializer.Span);
+ return result;
+ }
+ Value? failed = null;
+ foreach (var field in d.Body!.Statements.Cast<FieldSyntax>())
+ {
+ var result = Evaluate(field.Value, inputs, next, depth + 1, typeOnly);
+ if (result.Type != "Bool") throw Error("requirement-non-bool", $"Concept '{name}.{field.Name.Text}' must be Bool, not {result.Type}.", field.Value.Span);
+ if (!(bool)result.Data && failed is null) failed = result with { FailedMember = $" at {name}.{field.Name.Text}{result.FailedMember}" };
+ }
+ return failed ?? Boolean(true, span: span);
+ }
+ }
+
+ private static bool IsNumber(Value value) => value.Type is "Int" or "Float";
+ private static ExpressionSyntax Sample(string type, FirmamentV2SourceSpan span)
+ {
+ _ = FirmamentV2Parser.TryParseLetType(type, out var primitive);
+ return primitive switch
+ {
+ FirmamentV2PrimitiveType.Bool => new LiteralSyntax(LiteralKind.Boolean, "true", span),
+ FirmamentV2PrimitiveType.String => new LiteralSyntax(LiteralKind.String, "\"sample\"", span),
+ FirmamentV2PrimitiveType.Length => new QuantitySyntax(new LiteralSyntax(LiteralKind.Number, "1", span), new("mm", span), span),
+ FirmamentV2PrimitiveType.Angle => new QuantitySyntax(new LiteralSyntax(LiteralKind.Number, "1", span), new("deg", span), span),
+ _ => new LiteralSyntax(LiteralKind.Number, primitive == FirmamentV2PrimitiveType.Float ? "1.5" : "1", span)
+ };
+ }
+ private static Value Boolean(bool value, ExpressionSyntax? syntax = null, FirmamentV2SourceSpan? span = null) =>
+ new("Bool", value, syntax ?? new LiteralSyntax(LiteralKind.Boolean, value ? "true" : "false", span!));
+ private static BindingError TypeError(ExpressionSyntax e) => Error("expression-type-mismatch", "Concept operands have incompatible types or units, or the arithmetic is undefined. Lengths compare with lengths, angles with angles, and logical operators require Bool.", e.Span);
+ private sealed class BindingError(string code, string message, FirmamentV2SourceSpan span) : Exception(message)
+ { internal string Code => "firmament-concept-" + code; internal FirmamentV2SourceSpan Span => span; }
+ private static BindingError Error(string code, string message, FirmamentV2SourceSpan span) => new(code, message, span);
+ private void Add(BindingError error) => diagnostics.Add(new(error.Code, "error", error.Message)
+ { SourceFile = syntax.SourceFile, SourceSpan = error.Span, Stage = "Concept binding" });
+ private void Add(string code, string message, FirmamentV2SourceSpan span) => Add(Error(code, message, span));
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
index 506ac454..646927a4 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs
@@ -20,8 +20,8 @@ public sealed record FirmamentLanguageFormat(string Document, string Revision, s
public static class FirmamentLanguageAnalysisService
{
internal sealed record Lexeme(int Start, int Length, string Text, string Shape, string? Error = null);
- private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "With", "with", "Expose", "Include", "Subassembly", "Assembly", "Part", "Template", "Function", "Record", "Pattern", "Over", "Using", "As", "as", "Output", "tol"];
- private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Function", "Pattern", "Section", "SectionChain", "FrameTransform", "Points", "Path", "Semantic", "Enum"];
+ private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "With", "with", "Expose", "Include", "Subassembly", "Assembly", "Part", "Template", "Function", "Record", "Pattern", "Over", "Using", "As", "as", "Output", "tol", "Concept", "Require"];
+ private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Function", "Pattern", "Section", "SectionChain", "FrameTransform", "Points", "Path", "Semantic", "Enum", "Concept"];
private static readonly HashSet<string> Types = ["Length", "Angle", "Float", "Int", "Bool", "Box3", "Plane", "Point2", "Point3"];
private static readonly HashSet<string> Choices = FirmamentSemanticSchemas.All
.SelectMany(construct => construct.Fields).SelectMany(field => field.Choices).ToHashSet(StringComparer.Ordinal);
@@ -30,6 +30,9 @@ public static class FirmamentLanguageAnalysisService
{
ArgumentNullException.ThrowIfNull(source);
var lexemes = Lex(FirmamentSourceSpelling.Normalize(source));
+ var documentSyntax = Syntax.FirmamentSyntaxParser.Parse(source).Document;
+ var hasConcreteRoot = documentSyntax.Statements.OfType<Syntax.DeclarationSyntax>().Any(d =>
+ d.Type.Name.Text is "Model" or "model" or "Struct" && !d.Modifiers.Any(m => m.Name.Text is "Template" or "Concept"));
var tokens = lexemes.Select((lexeme, index) => new FirmamentLanguageToken(
lexeme.Start, lexeme.Length, Classify(lexemes, index))).ToArray();
if (Garment.GarmentAuthoring.HasRoot(source))
@@ -47,7 +50,7 @@ public static class FirmamentLanguageAnalysisService
// Imported authoring modules need project context. Do not feed them into
// the unrelated concrete-part parser and manufacture syntax errors.
if (lexemes.Any(t => t.Text == "Include" && t.Shape == "identifier")
- && !Syntax.FirmamentSyntaxParser.Parse(source).Document.Statements.OfType<Syntax.DeclarationSyntax>().Any(d => d.Type.Name.Text is "Model" or "model"))
+ && !hasConcreteRoot)
return new(document, revision, tokens, [new("information", "firmament-language-project-context-required", "Imported declarations require project-aware analysis.", 0, 0)]);
if (HasAssemblyRoot(source))
{
@@ -64,13 +67,13 @@ public static class FirmamentLanguageAnalysisService
var route = Materializer.WireFormAuthoring.Parse(source);
return new(document, revision, tokens, route.Diagnostics.Select(d => new FirmamentLanguageDiagnostic("error", d.Source, d.Message, 0, 0)).ToArray());
}
- if (lexemes.Any(t => t.Shape == "identifier" && t.Text is "Template" or "Subassembly" or "Appearance" or "Material"))
+ if (!hasConcreteRoot && lexemes.Any(t => t.Shape == "identifier" && t.Text is "Template" or "Subassembly" or "Appearance" or "Material"))
return new(document, revision, tokens, [new("information", "firmament-language-project-context-required", "Declaration modules are validated in their consuming project.", 0, 0)]);
var parse = FirmamentV2Parser.Parse(source);
var failures = parse.Diagnostics.Where(item => FirmamentV2Parser.IsFatalDiagnosticCode(item) || parse.SyntaxDiagnostics.Any(d => d.Code == item && d.Severity == "warning") ||
item == "firmament-v2-parse-failed").Distinct(StringComparer.Ordinal).ToArray();
if (failures.Length > 1) failures = failures.Where(item => item != "firmament-v2-parse-failed").ToArray();
- var diagnostics = failures.Select(item => parse.SyntaxDiagnostics.FirstOrDefault(d => d.Code == item) is { SourceSpan: { } span } located
+ var diagnostics = failures.Select(item => parse.SyntaxDiagnostics.FirstOrDefault(d => d.Code == item || item.StartsWith(d.Code + ":", StringComparison.Ordinal)) is { SourceSpan: { } span } located
? new FirmamentLanguageDiagnostic(located.Severity == "warning" ? "warning" : "error", located.Code, located.Message, span.Start, span.Length)
: LocateDiagnostic(source, lexemes, item)).ToArray();
return new(document, revision, tokens, diagnostics);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
index 9228e894..c26041ae 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
@@ -42,6 +42,10 @@ public static partial class FirmamentV2Parser
if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed)
with { SyntaxDiagnostics = staticValues.Diagnostics };
var declarations = MechanicalDeclarations(model.Body.Statements).ToArray();
+ // Non-materialized guides are still authored intent. Validate them through
+ // their ordinary owner even when no Profile happens to consume them.
+ diagnostics.AddRange(ProfileAuthoringParser.ValidateConstructionGuides(source));
+ if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
var primitives = declarations.Where(IsPrimitiveDeclaration).ToArray();
var constructions = declarations.Where(d => d.Type.Name.Text is "Compose" or "Extrude").ToArray();
var materialConstruction = constructions.Length > 0;
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 51736f53..725cab64 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -450,7 +450,6 @@ public static partial class FirmamentV2Parser
}
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.
@@ -474,17 +473,38 @@ public static partial class FirmamentV2Parser
return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray(), FirmamentV2ParseDisposition.RecognizedInvalid);
}
source = specializedBoundaries.Source;
- polygonExpansion = new(source, polygonExpansion.Boundaries.Concat(specializedBoundaries.Boundaries)
+ polygonExpansion = new(source, polygonExpansion.Boundaries.Concat(specializedBoundaries.Boundaries
+ .Where(boundary => !polygonExpansion.GeneratedDeclarationNames.Contains(boundary.Name, StringComparer.Ordinal)))
.DistinctBy(boundary => boundary.Name, StringComparer.Ordinal).ToArray());
- var canonicalStaticExpansion = CanonicalStaticAuthoring.Expand(source, diagnostics);
+ var canonicalStaticExpansion = CanonicalStaticAuthoring.Expand(source, diagnostics, compileTime);
if (canonicalStaticExpansion is null)
{
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 = canonicalStaticExpansion.Source;
+ var concepts = new FirmamentConcepts(source, compileTime);
+ concepts.ValidateClaims();
+ if (concepts.Diagnostics.Count > 0)
+ {
+ diagnostics.AddRange(concepts.BindingDiagnostics);
+ diagnostics.AddRange(concepts.Diagnostics.Select(d => d.Code + ": " + d.Message));
+ return FirmamentV2ParseResult.Failure(diagnostics.Append("firmament-v2-parse-failed").ToArray()) with
+ {
+ OwnsUnifiedAdmission = true, ParserRoute = "UnifiedConceptBinding",
+ SyntaxDiagnostics = concepts.Diagnostics.Select(d =>
+ {
+ var original = d.Target is { } name ? compileTime.OriginalDeclaration("Struct", name, "Concept") : null;
+ var unchanged = source == valueSource;
+ return d with { SourceSpan = original ?? (unchanged ? d.SourceSpan : null), IsOriginalSource = original is not null || unchanged,
+ LocationNote = original is not null ? "Location identifies the original Concept Struct declaration; conformance uses specialized values."
+ : unchanged ? d.LocationNote : "Conformance failed after expansion; original-source provenance is unavailable." };
+ }).ToArray()
+ };
+ }
v2AdmissionCandidate |= IsV2AdmissionCandidate(source);
var syntax = FirmamentSyntaxParser.Parse(source);
@@ -1231,13 +1251,9 @@ public static partial class FirmamentV2Parser
static string TextValue(string value) => value.Length >= 2 && value[0] == '"' && value[^1] == '"' ? value[1..^1] : value;
var instanceName = materialized.Groups["name"].Value; var conceptName = materialized.Groups["concept"].Value;
var conceptSpan = new FirmamentV2SourceSpan(materialized.Index, 0);
- var conceptHeader = Regex.Match(source, $@"\bConcept\s+{Regex.Escape(conceptName)}\s*\{{", RegexOptions.CultureInvariant);
- var conceptOpen = conceptHeader.Success ? source.IndexOf('{', conceptHeader.Index) : -1;
- var conceptClose = conceptOpen >= 0 ? FindMatchingBrace(source, conceptOpen) : -1;
- if (conceptClose < 0) { diagnostics.Add(ConceptUnknownConcept); return false; }
- var requirements = Regex.Matches(source[(conceptOpen + 1)..conceptClose], @"(?m)^\s*(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\s*$", RegexOptions.CultureInvariant)
- .Cast<Match>().ToDictionary(match => match.Groups["name"].Value,
- match => new ConceptIrMemberRequirement(match.Groups["name"].Value, new(match.Groups["type"].Value), conceptSpan), StringComparer.Ordinal);
+ var definition = new FirmamentConcepts(source).Contracts.SingleOrDefault(d => d.Name == conceptName);
+ if (definition is null) { diagnostics.Add(ConceptUnknownConcept); return false; }
+ var requirements = definition.Members;
var materializedOpen = source.IndexOf('{', materialized.Index); var materializedClose = FindMatchingBrace(source, materializedOpen);
var materializedBody = source[(materializedOpen + 1)..materializedClose];
var expose = Regex.Match(materializedBody, @"\bExpose\s*\{(?<body>.*?)\}", RegexOptions.Singleline | RegexOptions.CultureInvariant);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs
index ad64d991..6c11cbb5 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2StaticValues.cs
@@ -5,6 +5,8 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;
public static partial class FirmamentV2Parser
{
+ internal static FirmamentV2PrimitiveType? CompileTimeArithmeticType(FirmamentV2PrimitiveType left, string op, FirmamentV2PrimitiveType right) =>
+ ExpressionBinder.ResultType(left, op, right);
private sealed record StaticValueBinding(DeclarationSyntax Model,
IReadOnlyList<FirmamentV2LetDeclaration> Declarations, IReadOnlyList<FirmamentV2BoundLet> Values,
IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
index 501e98d6..50b39775 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
@@ -116,9 +116,9 @@ internal static class FirmamentV2TemplateExpansion
.ToArray();
private static IReadOnlyList<HostConstraint> ParseRequires(string body) =>
- Regex.Matches(body, @"\bRequire\s+(?<name>[A-Za-z_]\w*)\s*=>\s*(?<expression>[^\r\n}]+)", RegexOptions.CultureInvariant)
- .Cast<Match>()
- .Select(match => new HostConstraint(match.Groups["name"].Value, match.Groups["expression"].Value.Trim()))
+ FirmamentSyntaxParser.Parse(body).Document.Statements.OfType<DeclarationSyntax>()
+ .Where(d => d.Type.Name.Text == "Require" && d.Name is not null && d.Initializer is not null && d.Body is null)
+ .Select(d => new HostConstraint(d.Name!.Text, body.Substring(d.Initializer!.Span.Start, d.Initializer.Span.Length)))
.ToArray();
internal static IReadOnlyList<HostRecord> InspectRecords(string source, List<string> diagnostics) =>
@@ -223,7 +223,7 @@ internal static class FirmamentV2TemplateExpansion
if (!ValidateRecordMembers(template.Body, bound, diagnostics)) return null;
if (!EvaluateRequires(Substitute(template.Body, bound), application.InstanceName,
- DisplaySignature(template), diagnostics, out var requireResults)) return null;
+ DisplaySignature(template), diagnostics, out var requireResults, source)) return null;
var body = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);
if (body is null) return null;
body = Substitute(body, bound);
@@ -322,6 +322,10 @@ internal static class FirmamentV2TemplateExpansion
var tables = ParseStaticTables(source, recordTypes, enums, diagnostics);
var staticRecords = ParseStaticRecords(source, recordTypes, enums, tables, diagnostics, scalars);
scalars?.SetRecords(recordTypes, staticRecords);
+ var concepts = new FirmamentConcepts(source, scalars);
+ diagnostics.AddRange(concepts.Diagnostics.Select(d => d.Code + ": " + d.Message));
+ scalars?.AddConceptDiagnostics(concepts.Diagnostics, producerSource: source);
+ if (HasErrors(diagnostics)) return null;
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)
@@ -333,7 +337,7 @@ internal static class FirmamentV2TemplateExpansion
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, scalars), application.InstanceName,
- DisplaySignature(template), diagnostics, out var requireResults)) continue;
+ DisplaySignature(template), diagnostics, out var requireResults, source, scalars)) continue;
var body = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);
if (body is null) continue;
body = Substitute(body, bound);
@@ -447,6 +451,9 @@ internal static class FirmamentV2TemplateExpansion
FirmamentCompileTimeValues? scalars = null)
{
var supplied = application.Arguments.ToDictionary(a => a.Name, a => a.Expression, StringComparer.Ordinal);
+ var concepts = new FirmamentConcepts(source, scalars);
+ diagnostics.AddRange(concepts.Diagnostics.Select(d => d.Code + ": " + d.Message));
+ scalars?.AddConceptDiagnostics(concepts.Diagnostics, producerSource: source);
var expectedSignature = DisplaySignature(template);
foreach (var unknown in supplied.Keys.Where(name => template.Parameters.All(p => p.Name != name))) diagnostics.Add(UnknownArgument + ":" + unknown + ":expected-signature:" + expectedSignature);
var types = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal); var values = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
@@ -475,8 +482,18 @@ internal static class FirmamentV2TemplateExpansion
if (parameter is TemplateTypeParameterIr type)
{
if (!supplied.TryGetValue(type.Name, out var value)) { diagnostics.Add(MissingArgument + ":" + type.Name + ":expected-signature:" + expectedSignature); continue; }
- if (!ConceptExists(type.ConstraintConcept, source)) diagnostics.Add(UnknownConstraint + ":" + type.ConstraintConcept);
- else if (!Satisfies(value, type.ConstraintConcept, source)) diagnostics.Add(ConstraintFailure + $":{type.Name}:{value}:{type.ConstraintConcept}:expected-signature:{expectedSignature}");
+ if (!concepts.HasContract(type.ConstraintConcept)) diagnostics.Add(UnknownConstraint + ":" + type.ConstraintConcept);
+ else if (!concepts.Satisfies(value, type.ConstraintConcept))
+ {
+ diagnostics.AddRange(concepts.BindingDiagnostics);
+ diagnostics.Add(ConstraintFailure + $":{type.Name}:{value}:{type.ConstraintConcept}:expected-signature:{expectedSignature}");
+ var members = concepts.Contracts.Single(c => c.Name == type.ConstraintConcept).Members.Values;
+ var diagnostic = new FirmamentV2ValidationDiagnostic("firmament-concept-structural-conformance-failed", "error",
+ $"Type '{value}' does not provide Concept '{type.ConstraintConcept}'. Required semantic members: {string.Join(", ", members.Select(m => m.Name + ": " + m.Type))}. A claimed contract must also match the Concept Struct's actual members.", type.Name, value)
+ { SourceSpan = type.SourceSpan, Stage = "Concept binding", LocationNote = "Location identifies the Template type parameter whose supplied type failed conformance." };
+ diagnostics.Add(diagnostic.Code + ": " + diagnostic.Message);
+ scalars?.AddConceptDiagnostics([diagnostic], producerSource: source);
+ }
types[type.Name] = value;
}
else
@@ -766,14 +783,6 @@ internal static class FirmamentV2TemplateExpansion
}
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)
- {
- if (type != "Box") return Regex.IsMatch(source, $@"\bConcept\s+Struct\s+{Regex.Escape(type)}\s*:\s*{Regex.Escape(concept)}\s*\{{", RegexOptions.CultureInvariant);
- var definition = Regex.Match(source, $@"\bConcept\s+{Regex.Escape(concept)}\s*\{{(?<body>.*?)\}}", RegexOptions.Singleline | RegexOptions.CultureInvariant);
- 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, FirmamentCompileTimeValues? nominalScalars = null)
{
var values = bound.TypeArguments.Concat(bound.ValueArguments)
@@ -836,31 +845,36 @@ internal static class FirmamentV2TemplateExpansion
if (end < 0 || end > enclosingClose) end = enclosingClose;
return body[start..end].Trim();
}
- private static bool EvaluateRequires(string body, string instance, string signature, List<string> diagnostics, out IReadOnlyDictionary<string, string> results)
+ private static bool EvaluateRequires(string body, string instance, string signature, List<string> diagnostics,
+ out IReadOnlyDictionary<string, string> results, string moduleSource, FirmamentCompileTimeValues? scalars = null)
{
var evidence = new Dictionary<string, string>(StringComparer.Ordinal);
- foreach (Match require in Regex.Matches(body, @"\bRequire\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*=>\s*(?<expr>[^\r\n}]+)", RegexOptions.CultureInvariant))
+ var concepts = new FirmamentConcepts(moduleSource, scalars);
+ var templateName = signature.Split('<')[0];
+ var original = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(moduleSource).Document)
+ .FirstOrDefault(d => d.Name?.Text == templateName && d.Modifiers.Any(m => m.Name.Text == "Template"));
+ foreach (var require in FirmamentSyntaxParser.Parse(body).Document.Statements.OfType<DeclarationSyntax>()
+ .Where(d => d.Type.Name.Text == "Require" && d.Body is null))
{
- var name = require.Groups["name"].Value; var expression = require.Groups["expr"].Value.Trim();
- if (!TryBool(expression, out var value)) { diagnostics.Add(RequireNonBool + ":" + name + ":template-signature:" + signature); evidence[name] = "Invalid:" + expression; }
- else if (!value) { diagnostics.Add(RequireFailed + $":{instance}.{name}:{expression}:template-signature:{signature}"); evidence[name] = "Failed:" + expression; }
+ var name = require.Name?.Text ?? "<unnamed>";
+ var expression = require.Initializer is null ? "" : body.Substring(require.Initializer.Span.Start, require.Initializer.Span.Length);
+ var location = original?.Body?.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d => d.Type.Name.Text == "Require" && d.Name?.Text == name)?.Span;
+ if (require.Initializer is null || require.Body is not null || require.Parameters.Count > 0)
+ diagnostics.Add(RequireNonBool + ":" + name + ":template-signature:" + signature);
+ else if (!concepts.Check(require.Initializer, instance + "." + name, location))
+ {
+ var failed = concepts.Diagnostics.LastOrDefault()?.Code == "firmament-concept-requirement-failed";
+ diagnostics.Add(failed ? RequireFailed + $":{instance}.{name}:{expression}:template-signature:{signature}"
+ : RequireNonBool + ":" + name + ":template-signature:" + signature);
+ evidence[name] = (failed ? "Failed:" : "Invalid:") + expression;
+ }
else evidence[name] = "Passed:" + expression;
}
+ diagnostics.AddRange(concepts.Diagnostics.Select(d => d.Code + ": " + d.Message));
+ scalars?.AddConceptDiagnostics(concepts.Diagnostics, producerSource: moduleSource);
results = evidence;
return !HasErrors(diagnostics);
}
- private static bool TryBool(string expression, out bool result)
- {
- result = true;
- foreach (var clause in expression.Split("&&", StringSplitOptions.TrimEntries))
- {
- var m = Regex.Match(clause, @"^(?<a>[-+]?[0-9]+(?:\.[0-9]+)?)(?<u>mm|deg)?\s*(?<op>>=|<=|>|<|==)\s*(?<b>[-+]?[0-9]+(?:\.[0-9]+)?)(?<u2>mm|deg)?$", RegexOptions.CultureInvariant);
- if (!m.Success || m.Groups["u"].Value != m.Groups["u2"].Value) return false;
- var a = double.Parse(m.Groups["a"].Value, CultureInfo.InvariantCulture); var b = double.Parse(m.Groups["b"].Value, CultureInfo.InvariantCulture);
- result &= m.Groups["op"].Value switch { ">" => a > b, "<" => a < b, ">=" => a >= b, "<=" => a <= b, _ => a == b };
- }
- return true;
- }
private static void DetectTemplateCycles(IEnumerable<TemplateDeclarationIr> templates, IReadOnlyDictionary<string, TemplateDeclarationIr> byName, List<string> diagnostics)
{
foreach (var template in templates)
@@ -890,7 +904,13 @@ internal static class FirmamentV2TemplateExpansion
_ => parameter.Name,
})) + ">";
private static ImmutableArray<string> GeneratedPaths(string body, string instance) => Regex.Matches(body, @"\b(?:Concept\s+Struct|Box|Modify|EdgeFinish)\s+(?<n>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant).Select(m => instance + "::" + m.Groups["n"].Value).Distinct().ToImmutableArray();
- private static string RemoveRequires(string body) => Regex.Replace(body, @"(?m)^\s*Require\s+[A-Za-z_][A-Za-z0-9_]*\s*=>\s*[^\r\n}]+\s*$", string.Empty);
+ private static string RemoveRequires(string body)
+ {
+ var spans = FirmamentSyntaxParser.Parse(body).Document.Statements.OfType<DeclarationSyntax>()
+ .Where(d => d.Type.Name.Text == "Require" && d.Body is null).Select(d => d.Span).OrderByDescending(s => s.Start);
+ foreach (var span in spans) body = body.Remove(span.Start, span.Length);
+ return body;
+ }
private static string LiftPmi(string body, out string withoutPmi)
{
var blocks = new List<(int Start, int Length, string Text)>();
@@ -932,7 +952,7 @@ internal static class FirmamentV2TemplateExpansion
if (bound is null) continue;
if (!ValidateRecordMembers(template.Body, bound, diagnostics)) continue;
if (!EvaluateRequires(Substitute(template.Body, bound, scalars), application.InstanceName,
- DisplaySignature(template), diagnostics, out var requireResults)) continue;
+ DisplaySignature(template), diagnostics, out var requireResults, moduleSource, scalars)) continue;
var specializedBody = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);
if (specializedBody is null) continue;
specializedBody = Substitute(specializedBody, bound);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
index ade87ed2..83e0191c 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
@@ -309,6 +309,13 @@ public static class ProfileAuthoringParser
if (applySpans) ApplyGeometricSpans(source, points, guides, diagnostics, addGuides: true);
}
+ internal static IReadOnlyList<string> ValidateConstructionGuides(string source)
+ {
+ var diagnostics = new List<string>();
+ AddOrdinaryGuides(source, new(StringComparer.Ordinal), new(StringComparer.Ordinal), diagnostics, applySpans: false);
+ return diagnostics;
+ }
+
private static IEnumerable<DeclarationSyntax> SourceDeclarations(IEnumerable<StatementSyntax> statements)
{
foreach (var d in statements.OfType<DeclarationSyntax>())
diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
index 0c4d457c..eba00104 100644
--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
@@ -1,5 +1,26 @@
# October 2026 Firmament language decision register
+Concept/2D amendment (2026-10-14):
+[production qualification](../release/FIRMAMENT-CONCEPTS-AND-2D.md) adds named
+scalar predicates and record-shaped labeled requirement bundles. Structural
+Concepts compose named contracts and check actual semantic members. Plain 2D
+shape names are canonical; Concept-prefixed closed families share their existing
+geometry owner. Nonzero rotation of explicit Triangle2/Polygon2 now rejects
+instead of disappearing. These decisions extend #1–#4, #9 and #23 within the
+qualified mechanical lane; the original 24 recommendations and other domain
+dispositions below remain in force.
+
+| Decision | Disposition | Boundary |
+| --- | --- | --- |
+| Named predicates and labeled Boolean bundles | Implemented in production AST admission | Compile-time scalar parameters; Require applies a check. A bundle groups requirements, not data. |
+| Structural contract composition | Implemented in production AST admission | Named `: A && B` composition, inherited type conflicts/cycles rejected; no material class inheritance or new namespaces. |
+| Claimed Concept Struct conformance | Checked through the existing semantic value resolver | Unknown/missing/wrong members reject even without material use; underlying binding diagnostics survive. |
+| 2D spelling consistency | Plain shape declarations preferred; legitimate Concept prefixes preserved | Same existing curve/Profile/AIR/BRep/STEP owners and fields; no new 2D solver or Boolean engine. |
+| Explicit-shape rotation | Reject nonzero rotation, preserve zero rotation | Author rotated points or use Curve2 placement; do not silently change previously emitted coordinates. |
+| Predicate casing | PascalCase names/types; camelCase parameters and labels recommended | User symbols retain case. Published structural member names retain their existing identity. |
+| Whole Record/shape/frame/selector predicate inputs | Deferred to X2 semantic consolidation | Their value owners are not yet one shared expression environment; no string-based substitute is added. |
+| Legacy dimensional Require / projected PMI | Existing owner preserved | Its block form is not reinterpreted as a Boolean bundle. |
+
Compile-time value-binding amendment:
[qualification report](../release/FIRMAMENT-COMPILE-TIME-VALUES.md) carries
typed Record requirements through scalar/whole-Record Template and Feature
diff --git a/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md b/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md
index 07ea2268..5cd854d0 100644
--- a/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md
+++ b/docs/development/FIRMAMENT-SYNTAX-REVIEW-2026-10.md
@@ -1,5 +1,17 @@
# Firmament syntax review — 2026-10-14
+Concept/2D follow-up:
+[implementation and qualification](../release/FIRMAMENT-CONCEPTS-AND-2D.md)
+reconciles S16's vocabulary in production. Concept names a requirement: a
+structural contract, scalar Boolean predicate or labeled requirement bundle.
+Concept Struct supplies non-materialized construction. Plain shape names are
+preferred; the compatibility Concept prefix shares closed-shape binding rather
+than selecting a different interpretation. Definitions, conformance claims and
+applied checks are distinguished in the rewritten syntax reference. Unconsumed
+guides still bind, and explicit boundary rotation can no longer disappear.
+Record/shape predicate parameters, namespaces and complete AST expansion remain
+separate semantic/frontend work. Historical findings below are preserved.
+
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
diff --git a/docs/public/firmament/boundaries.md b/docs/public/firmament/boundaries.md
index 7377d2f8..ebbe7838 100644
--- a/docs/public/firmament/boundaries.md
+++ b/docs/public/firmament/boundaries.md
@@ -6,56 +6,70 @@ Use the most semantic available noun:
| Type | Intended use | Primary dimensions | Stable guides |
| --- | --- | --- | --- |
-| `Rect2` | rectangle | `Center`, `Size: [width, height]` | `Bottom`, `Right`, `Top`, `Left`; four corners |
-| `Square2` | structurally equal sides | `Center`, scalar `Size` | same edge/corner vocabulary as `Rect2` |
-| `Triangle2<Equilateral>` | equal-sided triangle | `Center`, `Side` | `A`, `B`, `C`; `AB`, `BC`, `CA` |
-| `Triangle2<Isosceles>` | centered isosceles triangle | `Center`, `Base`, `Height` | `A`, `B`, `C`; `AB`, `BC`, `CA` |
-| `Triangle2<Right>` | right triangle | right-angle `Origin`, `Legs` | `A`, `B`, `C`; `AB`, `BC`, `CA` |
+| `Rect2` | rectangle | `center`, `size: [width, height]` | `Bottom`, `Right`, `Top`, `Left`; four corners |
+| `Square2` | structurally equal sides | `center`, scalar `size` | same edge/corner vocabulary as `Rect2` |
+| `Triangle2<Equilateral>` | equal-sided triangle | `center`, `side` | `A`, `B`, `C`; `AB`, `BC`, `CA` |
+| `Triangle2<Isosceles>` | centered isosceles triangle | `center`, `base`, `height` | `A`, `B`, `C`; `AB`, `BC`, `CA` |
+| `Triangle2<Right>` | right triangle | right-angle `origin`, `legs` | `A`, `B`, `C`; `AB`, `BC`, `CA` |
| `Triangle2<Explicit>` | directly named triangle | `A`, `B`, `C` | `A`, `B`, `C`; `AB`, `BC`, `CA` |
-| `Circle2` | circular boundary | `Center`, exactly one of `Diameter` or `Radius` | `Center`, one analytic `Boundary` |
-| `Ellipse2` | elliptical boundary | `Center`, full `AxisLengths` | center/extrema and one analytic `Boundary` |
-| `Slot2` | straight engineering slot | `Center`, overall `Length`, `Width` | `Top`, `EndArc`, `Bottom`, `StartArc` |
-| `RoundedRect2` | rounded rectangular region | `Center`, `Size`, `Radius` | four lines and four named corner arcs |
-| `SmoothRoundedRect2` | squircle-style corners with straight sides | `Center`, `Size`, `CornerExtent` | four sides; `BottomRightCornerA/B`, `TopRightCornerA/B`, `TopLeftCornerA/B`, `BottomLeftCornerA/B` |
-| `Polygon2<Rhombus>` | diagonal-defined rhombus | `Center`, full `Diagonals` | four compass vertices and derived edges |
-| `Polygon2<Parallelogram>` | sheared parallel-sided boundary | `Center`, `Base`, `Height`, `Shear` | four corners and derived edges |
-| `Polygon2<Trapezoid>` | centered parallel-sided taper | `Center`, `BottomWidth`, `TopWidth`, `Height` | four corners and derived edges |
+| `Circle2` | circular boundary | `center`, exactly one of `diameter` or `radius` | `center`, one analytic `Boundary` |
+| `Ellipse2` | elliptical boundary | `center`, full `axisLengths` | center/extrema and one analytic `Boundary` |
+| `Slot2` | straight engineering slot | `center`, overall `length`, `width` | `Top`, `EndArc`, `Bottom`, `StartArc` |
+| `RoundedRect2` | rounded rectangular region | `center`, `size`, `radius` | four lines and four named corner arcs |
+| `SmoothRoundedRect2` | squircle-style corners with straight sides | `center`, `size`, `cornerExtent` | four sides; `BottomRightCornerA/B`, `TopRightCornerA/B`, `TopLeftCornerA/B`, `BottomLeftCornerA/B` |
+| `Polygon2<Rhombus>` | diagonal-defined rhombus | `center`, full `diagonals` | four compass vertices and derived edges |
+| `Polygon2<Parallelogram>` | sheared parallel-sided boundary | `center`, `base`, `height`, `shear` | four corners and derived edges |
+| `Polygon2<Trapezoid>` | centered parallel-sided taper | `center`, `bottomWidth`, `topWidth`, `height` | four corners and derived edges |
| `Polygon2<Explicit>` | arbitrary linear boundary | named `Set<Point2>` | authored vertex names and derived `A_B` edges |
-| `RegularPolygon2<N>` | regular polygon | `Center`, `Circumradius` or `AcrossFlats` | `Vertex0...`, `Edge0...` |
+| `RegularPolygon2<N>` | regular polygon | `center`, `circumradius` or `acrossFlats` | `Vertex0...`, `Edge0...` |
+
+New authoring uses the plain shape names. The compatibility prefix `Concept`
+is also admitted for every closed family above, including generic Triangle2,
+Polygon2 and RegularPolygon2 forms. Both spellings use the same AST field binder,
+reject unknown fields and unsupported header placements, and emit the same
+geometry. `Concept Circle2` is a construction guide, not a Boolean requirement
+named Circle2. The [syntax guide](syntax.md#contracts-semantic-interfaces-and-construction-geometry)
+separates requirements, requirement bundles and construction values.
Every form is consumed identically inside a profile:
```firmament
-RoundedRect2 Panel { Center: [0mm, 0mm] Size: [100mm, 60mm] Radius: 8mm }
+RoundedRect2 Panel { center: [0mm, 0mm] size: [100mm, 60mm] radius: 8mm }
Profile PanelProfile { Loop Outer { Panel |> TraceLoop } }
```
Compact declarations for the complete family:
```firmament
-Rect2 Plate { Center: [0mm,0mm] Size: [100mm,60mm] }
-Square2 Pad { Center: [0mm,0mm] Size: 40mm }
-Triangle2<Equilateral> TriEq { Center: [0mm,0mm] Side: 40mm }
-Triangle2<Isosceles> TriIso { Center: [0mm,0mm] Base: 40mm Height: 30mm }
-Triangle2<Right> TriRight { Origin: [0mm,0mm] Legs: [30mm,40mm] }
+Rect2 Plate { center: [0mm,0mm] size: [100mm,60mm] }
+Square2 Pad { center: [0mm,0mm] size: 40mm }
+Triangle2<Equilateral> TriEq { center: [0mm,0mm] side: 40mm }
+Triangle2<Isosceles> TriIso { center: [0mm,0mm] base: 40mm height: 30mm }
+Triangle2<Right> TriRight { origin: [0mm,0mm] legs: [30mm,40mm] }
Triangle2<Explicit> TriAny { A: [0mm,0mm] B: [30mm,0mm] C: [0mm,20mm] }
-Circle2 HoleBoundary { Center: [0mm,0mm] Diameter: 20mm }
-Ellipse2 Opening { Center: [0mm,0mm] AxisLengths: [40mm,20mm] }
-Slot2 CableSlot { Center: [0mm,0mm] Length: 50mm Width: 12mm }
-RoundedRect2 Panel { Center: [0mm,0mm] Size: [100mm,60mm] Radius: 8mm }
-Polygon2<Rhombus> Diamond { Center: [0mm,0mm] Diagonals: [50mm,32mm] }
-Polygon2<Parallelogram> Leaning { Center: [0mm,0mm] Base: 40mm Height: 24mm Shear: 10mm }
-Polygon2<Trapezoid> Tapered { Center: [0mm,0mm] BottomWidth: 44mm TopWidth: 28mm Height: 24mm }
-Static Vertices: Set<Point2> { A => Point2(0mm,0mm) B => Point2(30mm,0mm) C => Point2(20mm,20mm) D => Point2(0mm,15mm) }
-Polygon2<Explicit> Outline { Vertices: Vertices }
-RegularPolygon2<6> Hex { Center: [0mm,0mm] AcrossFlats: 32mm Rotation: 30deg }
+Circle2 HoleBoundary { center: [0mm,0mm] diameter: 20mm }
+Ellipse2 Opening { center: [0mm,0mm] axisLengths: [40mm,20mm] }
+Slot2 CableSlot { center: [0mm,0mm] length: 50mm width: 12mm }
+RoundedRect2 Panel { center: [0mm,0mm] size: [100mm,60mm] radius: 8mm }
+Polygon2<Rhombus> Diamond { center: [0mm,0mm] diagonals: [50mm,32mm] }
+Polygon2<Parallelogram> Leaning { center: [0mm,0mm] base: 40mm height: 24mm shear: 10mm }
+Polygon2<Trapezoid> Tapered { center: [0mm,0mm] bottomWidth: 44mm topWidth: 28mm height: 24mm }
+Static vertices: Set<Point2> { A => Point2(0mm,0mm) B => Point2(30mm,0mm) C => Point2(20mm,20mm) D => Point2(0mm,15mm) }
+Polygon2<Explicit> Outline { vertices: Vertices }
+RegularPolygon2<6> Hex { center: [0mm,0mm] acrossFlats: 32mm rotation: 30deg }
```
-`Rotation: Angle` rotates a shape in its local XY plane. Placement remains owned by the existing `Concept Struct ... On XY` / `Profile ... Using ...` frame architecture; the shape declarations do not introduce a second frame system.
+`rotation: Angle` rotates a shape in its local XY plane. Placement remains owned by the existing `Concept Struct ... on XY` / `Profile ... using ...` frame architecture; the shape declarations do not introduce a second frame system.
+
+Explicit Triangle2 and Polygon2 boundaries use their authored point coordinates.
+A nonzero `rotation` on those variants is rejected; it previously disappeared.
+Rotate the authored points or use the existing Curve2 placement of a Profile.
+A zero rotation remains compatible. Other shape variants retain their admitted
+local rotation.
-After Template specialization, boundary coordinate and length fields accept bounded dimensional arithmetic through the existing Profile evaluator, for example `Center: [Spec.Width / 2, -Spec.Length / 2]` and `Radius: 2mm + 1mm`. Extrusion `From`/`To` intervals use the same evaluator. Expressions must consume the entire field and yield a length; incompatible units, unknown names, and division by zero fail rather than accepting a numeric prefix. This does not add arbitrary functions or a new expression language.
+After Template specialization, boundary coordinate and length fields accept bounded dimensional arithmetic through the existing Profile evaluator, for example `center: [Spec.Width / 2, -Spec.Length / 2]` and `radius: 2mm + 1mm`. Extrusion `from`/`to` intervals use the same evaluator. Expressions must consume the entire field and yield a length; incompatible units, unknown names, and division by zero fail rather than accepting a numeric prefix. This does not add arbitrary functions or a new expression language.
-`Slot2.Length` is the overall end-to-end length and must be at least `Width`; equality lowers deterministically to one circular boundary. `Ellipse2.AxisLengths` are full lengths, not semi-axes. `RoundedRect2` accepts radius zero as rectangle-equivalent geometry. All sizes must be finite and positive, and rounded radius cannot exceed half the smaller size.
+`Slot2.Length` is the overall end-to-end length and must be at least `width`; equality lowers deterministically to one circular boundary. `Ellipse2.AxisLengths` are full lengths, not semi-axes. `RoundedRect2` accepts radius zero as rectangle-equivalent geometry. All sizes must be finite and positive, and rounded radius cannot exceed half the smaller size.
`RegularPolygon2<N>` is a bounded built-in structural parameter (`3 <= N <= 1024`), not general const generics. `Polygon2<T>` admits only the documented constrained variants. Add another named polygon variant only when it supplies meaningful geometric constraints or substantially better engineering dimensions than `Polygon2<Explicit>`.
@@ -65,16 +79,16 @@ After Template specialization, boundary coordinate and length fields accept boun
```firmament
SmoothRoundedRect2 Outline {
- Center: [0mm,0mm]
- Size: [77.98mm,163.43mm]
- CornerExtent: 19.43mm
+ center: [0mm,0mm]
+ size: [77.98mm,163.43mm]
+ cornerExtent: 19.43mm
}
Profile Section { Loop Outer { Outline |> TraceLoop } }
```
-This bounded primitive provides four straight sides and eight cubic B�zier spans. `CornerExtent` is the distance from the sharp envelope corner to each side tangency point, not a circular radius. It must be strictly between zero and half the smaller size. Rotation and dimensional arithmetic work as for the other boundaries. Closure and orientation are constructed internally; users do not author control points.
+This bounded primitive provides four straight sides and eight cubic Bézier spans. `cornerExtent` is the distance from the sharp envelope corner to each side tangency point, not a circular radius. It must be strictly between zero and half the smaller size. Rotation and dimensional arithmetic work as for the other boundaries. Closure and orientation are constructed internally; users do not author control points.
-The fixed corner law is polynomial, inspired by a fourth-power superellipse; it is not an exact Lam� curve or a certified Apple contour. In a unit corner from (0,0) to (1,1), let `b = 2^(-1/4)`, `q = 1-b`, and `a = b-1/2`. The first cubic has controls `(0,0), (a,0), (2a,0), (b,q)`. Reflect it across the corner bisector and reverse traversal for the second half. Endpoint speed is nonzero, collinear endpoint controls give zero side curvature, and reflection gives matching tangent and signed curvature at the midpoint. Monotone convex corner spans remain inside their envelope. Area is integrated exactly; the inspection perimeter is a fixed Simpson quadrature estimate.
+The fixed corner law is polynomial, inspired by a fourth-power superellipse; it is not an exact Lamé curve or a certified Apple contour. In a unit corner from (0,0) to (1,1), let `b = 2^(-1/4)`, `q = 1-b`, and `a = b-1/2`. The first cubic has controls `(0,0), (a,0), (2a,0), (b,q)`. Reflect it across the corner bisector and reverse traversal for the second half. Endpoint speed is nonzero, collinear endpoint controls give zero side curvature, and reflection gives matching tangent and signed curvature at the midpoint. Monotone convex corner spans remain inside their envelope. Area is integrated exactly; the inspection perimeter is a fixed Simpson quadrature estimate.
The existing Profile binder owns the resolved curves, and ordinary extrusion and SectionChain consume them as polynomial B-splines. No guide body is exported. [The SectionChain witness](../../../fixtures/Canonical/SectionChain/smooth-corner-sections.firmament) checks realized surface position, normals, and geometric curvature at every span and section join. Its straight extrusion has G2 side joins; its planar caps meet the sides with sharp edges. General `Continuity: G2` surface construction and plateau-to-body support matching remain separate work.
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index baf91433..f9361248 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -60,7 +60,7 @@ mutation or general-purpose computation.
| `Model` | An enclosing engineering artifact and its construction. |
| `Struct` | Named construction that may be specialized and used by a consuming artifact. |
| `Concept Struct` | Non-materialized construction data: points, guides, frames and semantic members. |
-| `Concept` | A semantic contract, or a domain-qualified construction value such as `Concept Path`. |
+| `Concept` | A compile-time requirement: a structural contract, a Boolean predicate, or a labeled bundle of predicates. |
| `Profile` | Named planar boundaries consumed by an extrusion or another feature. |
| `Feature` | A reusable recipe returning one typed semantic result. |
| `Template` | Typed compile-time specialization of a declared product or bounded feature recipe. |
@@ -244,8 +244,76 @@ targets and export limits.
### Contracts, semantic interfaces and construction geometry
-`Concept` describes what a construction must provide. `Concept Struct` supplies
-non-materialized design geometry or an implementation of that contract.
+`Concept` names a requirement. A structural Concept describes the members a
+construction must provide. A predicate Concept checks compile-time values and
+returns Bool. A record-shaped requirement bundle names several Boolean checks;
+every field must pass. A bundle is not a data Record and does not store geometry.
+
+**Complete file — reusable requirements applied before geometry:**
+
+```firmament
+Concept Positive(value: Length) => value > 0mm
+
+Concept PlateRequirements(width: Length, height: Length) {
+ positiveWidth: Positive(width)
+ positiveHeight: Positive(height)
+ aspect: width >= height
+}
+
+Template<width: Length, height: Length> Model Plate {
+ units: mm
+ Require dimensions => PlateRequirements(width, height)
+ Box Body { size: [width, height, 5mm] }
+}
+Model Product = Plate<width: 40mm, height: 20mm>
+```
+
+`Require` applies a requirement. It also works directly in a mechanical Model
+with literal or checked scalar Static inputs. Defining a Concept alone imposes
+no check: `Concept AlwaysFalse => false` is a legal definition, but a Require
+that applies it fails. Definitions are type-checked even when unapplied.
+Predicate parameters are scalar Length, Angle, Int, Float, Bool or String;
+positional and named calls are admitted. Pass Record scalar members as arguments.
+Concepts do not introduce runtime functions, implicit unit conversion, Record
+parameters, arbitrary geometry queries or a general constraint solver. Toleranced
+inputs are checked at their nominal values; this is not an interval proof.
+
+Bundles can call other bundles. Their labels identify a failed check, avoiding
+long chains of `&&`. `&&`, `||`, `!`, comparisons and dimensional arithmetic
+remain available; all operands must resolve and type-check, including an operand
+whose Boolean result would not affect the answer. Bare zero-argument predicates
+can be referenced by name or called with `()`.
+
+**Fragment — structural contracts, used by an existing conformance consumer:**
+
+```firmament
+Concept Bounded { Bounds: Box3 }
+Concept Planar { TopPlane: Plane }
+Concept PlateContract : Bounded && Planar { }
+```
+
+The composed contract requires both typed members. Use its name in
+`type T satisfies PlateContract` or `Concept Struct Design: PlateContract`.
+Conformance checks typed members; a structural Concept is not a Boolean value.
+Composition permits identical inherited requirements and rejects conflicting
+member types, duplicate own members, missing contracts and cycles. Claims on
+Concept Struct retain the existing closed published-member signature: additional
+members require a larger composed contract. Built-in type constraints check the
+required capabilities of that type. This pass does not introduce private members
+or general trait/type inheritance.
+
+Contract member names are user-owned symbols: `Bounds` is not silently renamed to
+`bounds`. Current part compilation resolves Concept names within the expanded
+part; this does not introduce namespaces or nested class-style type scopes.
+
+`Concept Struct` supplies non-materialized design geometry or an implementation
+of a structural contract. Its historical `Concept` prefix does not apply a
+Boolean predicate. Inside a planar layout, prefer plain `Rect2`, `Circle2` and
+the other geometry declarations. Compatibility forms such as
+`Concept Circle2 circle { ... }` and `Concept Slot2 slot { ... }` bind through
+the same shape owner, with the same fields, placement restrictions and geometry.
+They are construction values, not declarations of new requirement types.
+
`Semantic Name { ... }`, usually published through `Expose` or attached to an
Assembly occurrence, groups engineering references that consumers can name.
For example, a mount interface can publish a `DatumFrame` and a toleranced
@@ -355,6 +423,29 @@ references a named point set; it does not introduce inline arbitrary vertex-arra
syntax. `RegularPolygon2<N>` uses a bounded vertex count. These are built-in
shape parameters, not user-extensible generic types.
+| 2D construction family | Main fields / meaning |
+| --- | --- |
+| `Point2`, `Line2`, `CubicBezier2` | `position`; named `from`/`to`; named endpoints plus `control1`/`control2`. Open guides create no material. |
+| `Rect2`, `Square2` | `center`, `size`; rectangle size is two full lengths, square size is one length. |
+| `Circle2` | `center` and exactly one of `radius` or `diameter`. |
+| `Ellipse2` | `center`, `axisLengths` (two full axis lengths); `axes` is an admitted alias. |
+| `Slot2` | `center`, `length`, `width`; length includes both semicircular ends and must be at least width. |
+| `RoundedRect2` | `center`, `size`, `radius`. |
+| `SmoothRoundedRect2` | `center`, `size`, `cornerExtent`; polynomial corners, not circular fillets. |
+| `Triangle2<...>` | `Equilateral`, `Isosceles`, `Right` or `Explicit`, each with its own dimension fields. |
+| `Polygon2<...>`, `RegularPolygon2<N>` | Named polygon variants or a bounded regular polygon. |
+
+The closed families admit the compatibility `Concept` prefix. Parametric variants
+admit `rotation` in degrees; a rotation is redundant for a circle. Explicit
+Triangle2 and Polygon2 variants use authored points directly and reject nonzero
+rotation. Rotate those points or place a derived Profile with Curve2 instead.
+These remain planar guides: trace a Profile
+and give it a material consumer to obtain a solid. Layout `on XY` is admitted;
+an unsupported `on XZ` does not silently change the plane. These forms do not
+promise arbitrary 2D Boolean operations, implicit sketch solving, or first-class
+shape arguments to predicate Concepts. See [boundary details](boundaries.md)
+for variant fields and exact curve families.
+
**Fragment — layout and Profile declarations inside a Model:**
```firmament
diff --git a/docs/public/firmament/templates.md b/docs/public/firmament/templates.md
index d8d6846c..be1f3aae 100644
--- a/docs/public/firmament/templates.md
+++ b/docs/public/firmament/templates.md
@@ -129,11 +129,29 @@ The coherent flow is: Records, Static values, and Tables define finite data; `wi
## Concepts and Require
-A language `Concept` is a compile-time structural semantic contract. `Concept Struct` is a non-materialized typed semantic value. This differs from Forge C# runtime concept descriptors, even though both carry engineering semantics.
+A language `Concept` names a compile-time requirement. Structural Concepts specify
+typed members and can compose other contracts. Predicate Concepts return Bool;
+record-shaped requirement bundles label several predicates and require every
+field to pass. `Concept Struct` is a non-materialized construction value that can
+provide a structural contract. These differ from Forge C# runtime concept
+descriptors, even though both carry engineering semantics.
Parameter types own structural and dimensional checking. Records own grouped data shape. Concepts own semantic conformance. `Require Name => BooleanExpression` owns specialization-specific admissibility. A failed `Require` stops specialization before geometry materialization and records the named check in specialization provenance.
-`Require` is finite: comparisons and bounded boolean combinations over specialized data are supported. It is not a runtime script or a general constraint solver.
+Use `Require dimensions => PlateRequirements(width, height)` to apply a predicate
+or bundle after argument binding. The same Boolean requirement syntax works in a
+native mechanical Model. Comparisons, bounded Boolean combinations and dimensional
+arithmetic use the shared AST; unapplied definitions are checked for type errors.
+See the complete [requirement and bundle example](syntax.md#contracts-semantic-interfaces-and-construction-geometry).
+This is not a runtime script or a general constraint solver. Scalar inputs retain
+their dimensional type; tolerances contribute nominal values rather than an
+interval proof. Record fields can supply scalar arguments; whole Record and shape
+predicate parameters are not admitted.
+
+The established `Require Name { Actual: ... Expected: ... Tolerance: ... }` is a
+different, domain-owned dimensional constraint used by projected PMI. It retains
+its existing checking and projection path; it is not reinterpreted as a predicate
+bundle. See [PMI](pmi.md).
## DFM policy families
diff --git a/docs/release/FIRMAMENT-CONCEPTS-AND-2D.md b/docs/release/FIRMAMENT-CONCEPTS-AND-2D.md
new file mode 100644
index 00000000..42bfc8ba
--- /dev/null
+++ b/docs/release/FIRMAMENT-CONCEPTS-AND-2D.md
@@ -0,0 +1,184 @@
+# Firmament Concepts and 2D construction
+
+Date: 2026-10-14
+
+## Intent and language decisions
+
+A Concept is a compile-time requirement. This pass admits both named predicates
+and structural contracts, plus labeled bundles that avoid long Boolean
+conjunctions. It qualifies the compatibility Concept prefix across the existing
+closed 2D families through production compilation.
+
+```firmament
+Concept Positive(value: Length) => value > 0mm
+Concept PlateRequirements(width: Length, height: Length) {
+ positiveWidth: Positive(width)
+ positiveHeight: Positive(height)
+ aspect: width >= height
+}
+```
+
+`Require dimensions => PlateRequirements(width, height)` applies the bundle.
+Every field must be Bool and true; a failure identifies its label. Definitions
+are type-checked even if unapplied, but defining a false predicate is legal.
+Calls use positional or named scalar arguments. Record scalar members and checked
+toleranced values can supply arguments. Toleranced inputs contribute their
+nominals; this does not prove interval satisfaction.
+
+Structural Concepts keep `member: Type`. Named composition uses
+`Concept PlateContract : Bounded && Planar { }`. Identical inherited requirements
+merge; conflicts, duplicate own fields, unknown bases and cycles reject.
+Concept Struct conformance claims are checked against actual semantic values,
+including claims unused by material construction. Built-in Box type admission
+retains its established Bounds/TopPlane/CenterAxis contract. Concrete semantic
+values and Expose continue to belong to their existing resolver.
+Claimed Concept Struct contracts retain that resolver's closed published-member
+signature; additional members need a larger composed contract. General open
+traits, private members and structural subtyping are not introduced.
+
+A Record defines data shape. A record-shaped Concept bundle defines labeled
+Boolean requirements; it is not a Record value. `Concept Struct` remains
+non-materialized construction. Plain Circle2, Rect2 and other shape declarations
+are preferred. `Concept Circle2`, `Concept Slot2` and the other closed-family
+forms remain compatibility construction spellings, with the same fields and
+geometry as their plain forms. They do not define new predicate types.
+
+Construct/type names use PascalCase and built-in fields use camelCase. Predicate
+parameter names and bundle labels are user-owned symbols; their spelling is
+preserved. Published structural symbols such as Bounds keep their existing case.
+No global case folding or new capitalization aliases were added.
+
+## Reproduction and repairs
+
+| Case | Observed before | Production repair |
+| --- | --- | --- |
+| Named predicate and bundle | Canonical witness rejected with Template require-non-bool. | Shared AST Concept binding, applied from Template and native mechanical Require. |
+| Concept Slot2 used by TraceLoop | Canonical witness rejected as traceloop-not-loop. | The closed-boundary owner consumes Concept-prefixed shapes instead of skipping them. |
+| Inline structural requirements | Source readers could read only a prefix or miss semicolon-separated members. | Contract definitions and semantic member extraction consume AST fields/spans. |
+| Claimed conformance | Template type admission trusted a matching source annotation. Unused claims could evade semantic checking. | Actual semantic values are checked through ConceptIrResolver. Original missing-member/cycle codes survive. |
+| Unknown fields with unresolved guide inputs | The boundary owner returned before closing field consumption. | Deferred Rect2/Circle2 inputs still consume their known fields and reject unknown intent. |
+| Unconsumed invalid guides | A primitive-only body could bypass the profile guide binder. | Mechanical admission calls that existing binder for non-materialized guides too. |
+| Explicit boundary rotation | CLI validation reported Built while nonzero rotation was discarded. | Explicit Triangle2/Polygon2 reject nonzero rotation and suggest authored-point or Curve2 placement. Zero rotation is retained. |
+| Editor errors with Templates | Presence of any Template caused a project-context-only response, even for a concrete Model. | AST concrete-root identification allows normal compiler diagnostics through. Structured code/message/span projection uses the compiler receipt. |
+
+The original rejected sources and accepted-but-ignored rotation report are
+preserved under ignored `artifacts/local/firmament-concepts/before-*.json`.
+Durable positive sources live under `fixtures/Canonical/Concepts/`; negative
+sources live under `fixtures/Regression/Concepts/`.
+
+## Ownership and compatibility
+
+FirmamentConcepts binds structural signatures and Boolean requirements from the
+shared syntax tree. Arithmetic types reuse the native compile-time binder's
+type rules; numeric evaluation reuses FirmamentSyntaxValues. Template and native
+static Require now call this same owner. Their previous Boolean regex evaluators
+were removed. Template Require extraction, removal and host inspection use AST
+spans rather than line matching.
+
+This does not add a parser route for accepted geometry, a diagnostic fatality
+allowlist, a field-schema copy or a source rewrite system. The existing closed
+boundary, Profile, AIR, BRep and STEP owners still construct geometry. Early
+conformance rejection is visible as UnifiedConceptBinding; accepted mechanical
+sources retain UnifiedMechanical.
+
+The legacy dimensional `Require { Actual: ... Expected: ... Tolerance: ... }`
+keeps its semantic-constraint and projected-PMI owner. Construction declarations
+inside Concept Struct keep their profile/point/derived-frame owners. The new
+semantic member reader does not claim those declarations. Existing native
+Require inspection receipts and Template RequireResults remain available.
+
+Concept Circle2 now carries the same closed-guide inspection metadata as plain
+Circle2. This additive metadata does not materialize a guide or force its
+consumer to use the full circle: the semicircular Revolve witness remains valid.
+Older routing assertions and fixture expectation metadata now expect the earlier structural conformance
+failure instead of requiring a downstream missing-hole-center error. The source
+is still rejected, and its original missing-member diagnostic remains present.
+Generated helper names are retained as expansion receipts and excluded from the
+authored boundary list; the 15-shape family still reports 15 boundaries.
+
+Errors retain stable codes, readable messages and available source spans.
+Specialization checks point to the authored Require. If preceding expansion
+moves offsets, a unique original declaration supplies an enclosing anchor with
+an explicit location note. Unavailable provenance is disclosed rather than
+reported as an exact original expression offset. Underlying semantic binding
+codes and the named failed bundle member are preserved.
+
+## Qualification
+
+The Release solution build succeeded with zero errors and 19 existing
+nullable/analyzer/platform/WASM warnings. Builds used `-m:1 -nr:false` and
+`UseSharedCompilation=false`; test execution was serial.
+
+| Check | Result | Local evidence |
+| --- | --- | --- |
+| Firmament component lane, excluding SlowCorpus | 2,436 passed | `firmament-final.log` |
+| Focused CLI routing, inspection, corpus and new requirements | 35 passed | `cli-final.log` |
+| Required Core fast lane | 1,068 passed | `fast.log` |
+| Full `dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1` | 4,914 passed across 20 executing assemblies; zero failed/skipped | `full.log`, `test-summary.json` |
+| Normal CLI commands | 21 expected outcomes, including validate/build/parse-only rejection agreement | `cli-results.json`, command-specific JSON |
+| Complete public examples | 9 compiled through the real compiler | `documentation.json` |
+| Existing STEP baselines | 13 byte-identical outputs, including typed-tolerance and Record/Template/Feature explicit PMI | `step-parity.json` |
+| Plain versus Concept-prefixed closed shapes | 17 byte-identical STEP comparisons | `FirmamentConceptRequirementsTests` in full regression |
+| Slot acceptance witness | One body, six faces, world bounds (-20,-6,0)..(20,6,5) mm | `shape.step`, `shape-analyze.json`, `qualification.json` |
+| Runtime cleanup | Zero remaining dotnet/test hosts or Visual Studio build nodes; 15.1 GiB memory and 103.8 GiB disk free at final snapshot | `runtime-summary.json` |
+
+The full lane includes 2,450 Firmament and 512 CLI cases. The solution's existing
+FrictionLab test project reports no discoverable tests; it is not counted among
+the 20 executing assemblies. The narrower component lane is not substituted for
+the full gate.
+
+Fresh CLI checks include the threaded bolt, guitar, industrial ATLAS, warm-modern
+house, factory scene, sheet-metal Template, existing PMI and generic mounting
+plate. Their domain-appropriate validate/inspect paths succeeded. This is compiler
+and artifact qualification; no new Helios browser-interaction claim is made.
+The shared language-service test verifies the compiler's failed-requirement
+message and authored Require span project into editor diagnostics.
+
+All generated evidence is under ignored `artifacts/local/firmament-concepts/`.
+Older failed logs are retained as reproduction evidence; the final gate is
+`full.log`. Invalid CLI builds produced no STEP file. Byte identity is claimed
+for the 13 saved baselines and paired shape cases, not every showcase export.
+
+## Code-quality pass
+
+The modified owners were reviewed for duplicate admission, hidden fallback,
+diagnostic loss, spans, mutable parser state and new rewrite/schema debt. Contract
+definitions, semantic member extraction and both Boolean Require consumers now
+use AST spans. The two Boolean regex evaluators and Template conformance regex
+checks were removed. No new regex, error-code fatality list, field lookup schema,
+global mutable environment, whole-document dispatch or geometry operation was
+added. Construction guides are checked through their existing owner. Missing
+member and cycle codes survive earlier conformance rejection; generated boundary
+helpers retain receipts instead of becoming fake authored shapes. The new owner
+introduces no build warning. Markdown links/fences and `git diff --check` pass.
+
+## Deliberate limits
+
+- Predicate arguments are scalar Length, Angle, Int, Float, Bool and String.
+ Whole Record, shape, frame and selector parameters need their semantic value
+ owners consolidated first. No missing geometry capability is implemented.
+- Concept names retain part-wide resolution in the expanded mechanical source.
+ This does not introduce namespaces, nested type scopes, runtime methods or
+ inheritance of material construction.
+- Boolean Require is admitted in a mechanical module, Model or construction
+ Struct. A primitive field block cannot silently consume it. Other domain
+ frontends and the legacy dimensional constraint owner are not universally
+ migrated by this pass.
+- Template/Feature/Pattern source expansion still exists. This is production
+ admission work, not a claim that the complete frontend has one AST lowerer.
+- A 2D guide creates no material. Profile closure, supported consumers and
+ existing placement/capability limits still apply. Arbitrary sketch solving,
+ 2D Boolean algebra and general shape-valued predicates are not added.
+
+No unresolved policy choice requires the user's approval. The remaining limits
+are explicit implementation boundaries.
+
+## Verdict
+
+**Success for this pass.** Named predicates, labeled requirement bundles and
+structural composition work through production validate/build admission. The
+qualified 2D families accept legitimate Concept compatibility spellings with
+identical geometry and reject the reproduced unknown-field and ignored-rotation
+cases. Existing geometry, tolerance/PMI artifacts and canonical projects remain
+qualified by the evidence above. This is not whole-frontend or universal
+cross-domain semantic-consolidation acceptance.
diff --git a/fixtures/Canonical/Concepts/requirements.firmament b/fixtures/Canonical/Concepts/requirements.firmament
new file mode 100644
index 00000000..e893ef30
--- /dev/null
+++ b/fixtures/Canonical/Concepts/requirements.firmament
@@ -0,0 +1,13 @@
+Concept Positive(value: Length) => value > 0mm
+Concept PlateRequirements(width: Length, height: Length) {
+ positiveWidth: Positive(width)
+ positiveHeight: Positive(height)
+ aspect: width >= height
+}
+
+Template<width: Length, height: Length> Model Plate {
+ units: mm
+ Require dimensions => PlateRequirements(width, height)
+ Box Body { size: [width, height, 5mm] }
+}
+Model Product = Plate<width: 40mm, height: 20mm>
diff --git a/fixtures/Canonical/Concepts/shape-prefix.firmament b/fixtures/Canonical/Concepts/shape-prefix.firmament
new file mode 100644
index 00000000..b9fd1da2
--- /dev/null
+++ b/fixtures/Canonical/Concepts/shape-prefix.firmament
@@ -0,0 +1,8 @@
+Model GuidePlate {
+ units: mm
+ Concept Struct layout on XY {
+ Concept Slot2 boundary { center: [0mm, 0mm]; length: 40mm; width: 12mm }
+ }
+ Profile outline using layout { Loop Outer { boundary |> TraceLoop } }
+ Extrude Body { profile: outline; from: 0mm; to: 5mm }
+}
diff --git a/fixtures/Invalid/Language/concept-struct-diagnostic-routing-x1.invalid.firmfixture b/fixtures/Invalid/Language/concept-struct-diagnostic-routing-x1.invalid.firmfixture
index 9e1979f6..46d61810 100644
--- a/fixtures/Invalid/Language/concept-struct-diagnostic-routing-x1.invalid.firmfixture
+++ b/fixtures/Invalid/Language/concept-struct-diagnostic-routing-x1.invalid.firmfixture
@@ -6,7 +6,7 @@
// implementation: parser-backed
// expected: invalid
// expected-stage: parsed
-// expected-diagnostic: HoleLocalCenterInvalid
+// expected-diagnostic: firmament-concept-missing-member:BracketConcept.RequiredExpose
// notes: V2-recognized Concept/Struct source with a malformed construction-plane hole and omitted Concept members.
Concept BracketFrame {
Bounds: Box3
diff --git a/fixtures/Regression/Concepts/explicit-rotation.firmament b/fixtures/Regression/Concepts/explicit-rotation.firmament
new file mode 100644
index 00000000..c54a99fa
--- /dev/null
+++ b/fixtures/Regression/Concepts/explicit-rotation.firmament
@@ -0,0 +1,9 @@
+Model TrianglePlate {
+ units: mm
+ Triangle2<Explicit> boundary {
+ a: [0mm,0mm]; b: [30mm,0mm]; c: [0mm,10mm]
+ rotation: 90deg
+ }
+ Profile outline { Loop Outer { boundary |> TraceLoop } }
+ Extrude Body { profile: outline; from: 0mm; to: 5mm }
+}
diff --git a/fixtures/Regression/Concepts/failed-requirement.firmament b/fixtures/Regression/Concepts/failed-requirement.firmament
new file mode 100644
index 00000000..bd919ba6
--- /dev/null
+++ b/fixtures/Regression/Concepts/failed-requirement.firmament
@@ -0,0 +1,12 @@
+Concept Positive(value: Length) => value > 0mm
+Concept PlateRequirements(width: Length, height: Length) {
+ positiveWidth: Positive(width)
+ positiveHeight: Positive(height)
+ aspect: width >= height
+}
+Template<width: Length, height: Length> Model Plate {
+ units: mm
+ Require dimensions => PlateRequirements(width, height)
+ Box Body { size: [width, height, 5mm] }
+}
+Model Product = Plate<width: 10mm, height: 20mm>
diff --git a/fixtures/Regression/Concepts/unknown-shape-field.firmament b/fixtures/Regression/Concepts/unknown-shape-field.firmament
new file mode 100644
index 00000000..349262eb
--- /dev/null
+++ b/fixtures/Regression/Concepts/unknown-shape-field.firmament
@@ -0,0 +1,8 @@
+Model GuidePlate {
+ units: mm
+ Concept Struct layout on XY {
+ Concept Circle2 boundary { center: [0mm,0mm]; radius: 12mm; raduis: 8mm }
+ }
+ Profile outline using layout { Loop Outer { boundary |> TraceLoop } }
+ Extrude Body { profile: outline; from: 0mm; to: 5mm }
+}