Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Preserve equation curves in canonical authoring output

Yuechen Li8a5eed7b8ed8
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 5e97b833..2601af71 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -1810,6 +1810,7 @@ Model CanonicalPanel {
}).ToArray() ?? [],
linearPatterns = document?.StaticAuthoring?.LinearPatterns ?? [],
planarAxes = document?.StaticAuthoring?.PlanarAxes ?? [],
+ equationCurves = document?.StaticAuthoring?.EquationCurves ?? [],
templateInstances = (document?.TemplateInstantiations ?? document?.ConceptIr?.TemplateInstantiations)?.Select(instance => new
{
instance.Template,
diff --git a/Aetheris.Kernel.Firmament.Tests/EquationCurveTests.cs b/Aetheris.Kernel.Firmament.Tests/EquationCurveTests.cs
new file mode 100644
index 00000000..17656084
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/EquationCurveTests.cs
@@ -0,0 +1,233 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Materializer;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Core.Brep.Verification;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class EquationCurveTests
+{
+ private static string Source(string name) => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/EquationCurves/" + name + ".firmament"));
+
+ [Fact]
+ public void ApproximatePlanarLawExportsItsExplicitRepresentationWithBoundedError()
+ {
+ var parsed = FirmamentV2Parser.Parse(Source("sine-arch"));
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var curve = Assert.Single(parsed.Document!.StaticAuthoring!.EquationCurves!, c => c.Name == "Layout.Crown");
+ Assert.InRange(curve.ErrorBound, double.Epsilon, .05);
+ Assert.True(FirmamentBuildAndExport.CompileSource(Source("sine-arch")).IsSuccess);
+ foreach (var segment in curve.Segments)
+ for (var i = 0; i <= 10; i++)
+ {
+ var u = i / 10d; var t = segment.Start + (segment.End - segment.Start) * u;
+ var y = segment.Controls[0][1] * (1 - u) + segment.Controls[1][1] * u;
+ Assert.InRange(Math.Abs(20 * Math.Sin(t * Math.PI) - y), 0, curve.ErrorBound);
+ }
+ }
+
+ [Fact]
+ public void InvalidTrigCaptureAndToleranceInputsRemainRejected()
+ {
+ var length = Source("arch").Replace("span * t", "span * t * Cos(1mm)");
+ var captured = "Static Captured: Length = 2mm;\n" + Source("arch").Replace("span * t", "Captured * t");
+ var tolerated = Source("record-arch").Replace("span: 80mm; rise: 20mm", "span: 80mm tol 0.1mm; rise: 20mm");
+ Assert.False(FirmamentV2Parser.Parse(length).IsSuccess);
+ Assert.False(FirmamentV2Parser.Parse(captured).IsSuccess);
+ Assert.False(FirmamentV2Parser.Parse(tolerated).IsSuccess);
+ }
+
+ [Theory]
+ [InlineData("Evaluation { point: Point2(span * t, 4 * rise * t * (1 - t)); typo: 1 }.point")]
+ [InlineData("Evaluation { point: Point2(span * t, 4 * rise * t * (1 - t)); point: Point2(0mm,0mm) }.point")]
+ [InlineData("Point2(Point2(span * t, 1mm, 2mm).X, 4 * rise * t * (1 - t))")]
+ [InlineData("Point2(Point2(span * t, 1mm).XY, 4 * rise * t * (1 - t))")]
+ public void MemberProjectionCannotEraseUnknownFieldsOrMalformedPointArguments(string expression)
+ {
+ var source = "Record Evaluation { point: Point2 }\n" + Source("arch").Replace("Point2(span * t, 4 * rise * t * (1 - t))", expression);
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ Assert.Contains(parsed.SyntaxDiagnostics, d => d.Code.Contains("function-body-invalid", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ScalarFunctionNormalizationCannotEraseManufacturingTolerance()
+ {
+ const string source = "Function Identity(x: Length) -> Length = x; Model Test { units: mm; Static D: Length = 10mm tol 0.1mm; Box Base { size: [Identity(D),20mm,5mm] } }";
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ Assert.Contains(parsed.SyntaxDiagnostics, d => d.Message.Contains("tolerance", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void RecordInputsPreserveExactGeometryAndLexicalParameterBinding()
+ {
+ var baseline = FirmamentV2Parser.Parse(Source("arch"));
+ var parsed = FirmamentV2Parser.Parse(Source("record-arch"));
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.True(FirmamentBuildAndExport.CompileSource(Source("record-arch")).IsSuccess);
+ Assert.Equal(baseline.Document!.StaticAuthoring!.EquationCurves![0].Segments[0].Controls.SelectMany(x => x), parsed.Document!.StaticAuthoring!.EquationCurves![0].Segments[0].Controls.SelectMany(x => x));
+ var shadowed = FirmamentV2Parser.Parse("Static t: Float = 999;\n" + Source("record-arch"));
+ Assert.True(shadowed.IsSuccess, string.Join("\n", shadowed.Diagnostics));
+ Assert.Equal(parsed.Document.StaticAuthoring.EquationCurves[0].Segments[0].Controls.SelectMany(x => x), shadowed.Document!.StaticAuthoring!.EquationCurves![0].Segments[0].Controls.SelectMany(x => x));
+ foreach (var unrelated in new[] { "Static t: Length = 999mm tol 0.1mm;", "Static t: ArchSpec { span: 999mm; rise: 999mm }" })
+ {
+ var actual = FirmamentV2Parser.Parse(unrelated + "\n" + Source("record-arch"));
+ Assert.True(actual.IsSuccess, string.Join("\n", actual.Diagnostics));
+ Assert.Equal(parsed.Document.StaticAuthoring.EquationCurves[0].Segments[0].Controls.SelectMany(x => x), actual.Document!.StaticAuthoring!.EquationCurves![0].Segments[0].Controls.SelectMany(x => x));
+ }
+ }
+
+ [Fact]
+ public void CircleRecognitionPreservesAnalyticGeometryAndPeriodicity()
+ {
+ var parsed = FirmamentV2Parser.Parse(Source("circle"));
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var curve = Assert.Single(parsed.Document!.StaticAuthoring!.EquationCurves!);
+ Assert.Equal("Circle", curve.GeometryKind);
+ Assert.True(curve.Periodic);
+ Assert.True(FirmamentBuildAndExport.CompileSource(Source("circle")).IsSuccess);
+ }
+
+ [Fact]
+ public void EllipseRequiresExplicitLoopConsumptionAndNeverCrashesTheFrontend()
+ {
+ var source = Source("circle").Replace("radius * Sin(t * 360deg)", "2 * radius * Sin(t * 360deg)");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.Equal("Ellipse", parsed.Document!.StaticAuthoring!.EquationCurves![0].GeometryKind);
+ Assert.True(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ var invalid = FirmamentV2Parser.Parse(source.Replace("|> TraceLoop", "|> Close"));
+ Assert.False(invalid.IsSuccess);
+ Assert.Contains(invalid.SyntaxDiagnostics, d => d.Code.EndsWith("curve-consumer-invalid", StringComparison.Ordinal) && d.Message.Contains("TraceLoop", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void AlmostFullTurnIsNotSilentlyPromotedToAnExactClosedConic()
+ {
+ var source = Source("circle").Replace("domain: [0, 1]", "domain: [0, 0.99999999999999]").Replace("periodic: true", "periodic: false");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.Contains(parsed.SyntaxDiagnostics, d => d.Message.Contains("Exact lowering", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("Layout.Coil.At(n)", "Layout.Coil.At(n + 5)")]
+ [InlineData("maxDeviation: 0.01mm", "maxDeviation: 0mm")]
+ [InlineData("on: World", "on: XZ")]
+ [InlineData("representation: Approximate", "representation: Approximate; periodic: true")]
+ public void SpatialCurvesRejectOutOfDomainQueriesAndUnprovenContracts(string from, string to)
+ {
+ var source = Source("helix").Replace(from, to);
+ Assert.False(FirmamentV2Parser.Parse(source).IsSuccess);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Fact]
+ public void TypedRecordResultBundlesCanFeedCurvesAndDirectGeometryValues()
+ {
+ var source = Source("arch").Replace("Function Arch", "Record Evaluation { point: Point2; width: Length }\nFunction Bundle(t: Float, span: Length, rise: Length) -> Evaluation = Evaluation { point: Arch(t, span, rise); width: span };\nFunction Arch")
+ .Replace("from: Arch(t, 80mm, 20mm)", "from: Bundle(t, 80mm, 20mm).point");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ Assert.True(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ var direct = Source("helix").Replace("Layout.Stations.Turn1.Z", "Layout.Coil.At(1).Z");
+ Assert.True(FirmamentBuildAndExport.CompileSource(direct).IsSuccess);
+ }
+
+ [Theory]
+ [InlineData("XY")]
+ [InlineData("XZ")]
+ public void ExactArchBuildsThroughNormalProfilePathAndRetainsFrame(string frame)
+ {
+ var source = Source("arch").Replace("on: XY", "on: " + frame);
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var curve = Assert.Single(parsed.Document!.StaticAuthoring!.EquationCurves!, c => c.Name.EndsWith(".Crown", StringComparison.Ordinal));
+ Assert.Equal("CubicBezier", curve.GeometryKind);
+ Assert.Equal(frame, curve.Frame);
+ Assert.Equal(0, curve.ErrorBound);
+ Assert.NotNull(curve.SourceSpan);
+ var compiled = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics));
+ var imported = Step242Importer.ImportBody(compiled.Value!.StepText);
+ Assert.True(imported.IsSuccess, string.Join("\n", imported.Diagnostics));
+ var mass = BrepMassProperties.Evaluate(imported.Value!);
+ Assert.True(mass.IsEnclosed);
+ Assert.True(mass.IsOrientationConsistent);
+ var crowns = imported.Value!.Geometry.Curves.Select(pair => pair.Value.BSpline3).Where(c => c.HasValue).Select(c => c!.Value).ToArray();
+ Assert.Equal(2, crowns.Length);
+ var midpoints = crowns.Select(c => c.Evaluate((c.DomainStart + c.DomainEnd) / 2)).ToArray();
+ Assert.All(midpoints, p => Assert.Equal(40, p.X, 8));
+ if (frame == "XY")
+ {
+ Assert.All(midpoints, p => Assert.Equal(20, p.Y, 8));
+ Assert.Equal(new[] { 0d, 5d }, midpoints.Select(p => p.Z).Order());
+ }
+ else
+ {
+ Assert.All(midpoints, p => Assert.Equal(20, p.Z, 8));
+ Assert.Equal(new[] { -5d, 0d }, midpoints.Select(p => p.Y).Order());
+ }
+ Assert.True(FirmamentV2Parser.TryExpandCanonicalStaticAuthoring(source, out var expanded, out var errors), string.Join("\n", errors));
+ var profile = ProfileAuthoringParser.Parse(expanded);
+ Assert.Empty(profile.Diagnostics);
+ Assert.Equal(80 * 20 * 2d / 3, ResolvedProfile2DValidator.Validate(profile.Profile!).SignedArea, 7);
+ var plane = profile.Profile!.EffectiveConstructionPlane;
+ var world = plane.ToWorld((0, 20));
+ Assert.Equal(frame == "XZ" ? 20 : 0, world.Z, 8);
+ Assert.Equal(frame == "XY" ? 20 : 0, world.Y, 8);
+ }
+
+ [Fact]
+ public void SpatialEquationDrivesKeyedPhysicalDimensionsWithoutPretendingToSweep()
+ {
+ var source = Source("helix");
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var curve = Assert.Single(parsed.Document!.StaticAuthoring!.EquationCurves!);
+ Assert.Equal("Polyline", curve.GeometryKind);
+ Assert.InRange(curve.ErrorBound, double.Epsilon, .01);
+ Assert.InRange(curve.Segments.Count, 2, 4096);
+ var points = Assert.Single(parsed.Document.StaticAuthoring.ConceptPoints!);
+ Assert.Equal(new[] { "Turn0", "Turn1", "Turn2" }, points.Points.Select(p => p.Key));
+ Assert.Equal(12, points.Points[1].Coordinates[0], 8);
+ Assert.Equal(8, points.Points[1].Coordinates[2], 8);
+ Assert.True(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+
+ [Theory]
+ [InlineData("domain: [0, 1]", "domain: [1, 0]")]
+ [InlineData("representation: Exact", "representation: Approximate")]
+ [InlineData("representation: Exact", "representation: Exact; maxDeviation: 0.1mm")]
+ [InlineData("on: XY", "on: Missing")]
+ [InlineData("on: XY", "on: XY; heigth: 1mm")]
+ [InlineData("representation: Exact", "representation: Exact; closed: true")]
+ [InlineData("span * t", "span / (t - 0.5)")]
+ public void InvalidIntentCannotBeAcceptedOrSilentlyReplaced(string from, string to)
+ {
+ var source = Source("arch").Replace(from, to);
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess);
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ Assert.Contains(parsed.SyntaxDiagnostics, d => d.Message.Length > 15 && d.SourceSpan is not null);
+ }
+
+ [Theory]
+ [InlineData("Cos(0)", 1)]
+ [InlineData("Cos(180deg)", -1)]
+ [InlineData("Cos(3.141592653589793)", -1)]
+ [InlineData("Cos(3.141592653589793rad)", -1)]
+ [InlineData("Sin(90deg)", 1)]
+ public void TrigonometryDistinguishesBareRadiansFromDegrees(string expression, double expected)
+ {
+ var source = Source("arch").Replace("span * t", $"span * t * ({expression})");
+ source = source[..source.IndexOf(" Profile Outline", StringComparison.Ordinal)] + "Box Base { size: [10mm,10mm,10mm] } }";
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.True(parsed.IsSuccess, string.Join("\n", parsed.Diagnostics));
+ var curve = Assert.Single(parsed.Document!.StaticAuthoring!.EquationCurves!, c => c.Name.EndsWith(".Crown", StringComparison.Ordinal));
+ Assert.Equal(80 * expected, curve.Segments[0].Controls[^1][0], 8);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
index 4ea39cb8..c04de321 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs
@@ -53,7 +53,7 @@ internal static class CanonicalStaticAuthoring
if (headers.Length == 0)
{
source = points.Math.Normalize(source);
- return diagnostics.Count > 0 ? null : new(source, points.Points.Count == 0 ? null : new([],[],[],[],[], ConceptPoints: points.Points));
+ return diagnostics.Count > 0 ? null : new(source, points.Points.Count == 0 && points.Curves.Count == 0 ? null : new([],[],[],[],[], ConceptPoints: points.Points, EquationCurves: points.Curves));
}
var catalog = source.Select(c => c is '\r' or '\n' ? c : ' ').ToArray();
foreach (var declaration in FirmamentSyntaxTraversal.Declarations(syntax.Document)
@@ -147,7 +147,7 @@ internal static class CanonicalStaticAuthoring
var conceptualSets = points.Points.ToDictionary(p => ConceptPointAuthoring.SetName(p.Name), p => p);
patterns = patterns.Select(pattern => conceptualSets.TryGetValue(pattern.Source, out var collection)
? pattern with { Source = collection.Name, Associations = pattern.Associations?.Select(a => a with { SourceSet = collection.Name }).ToArray() } : pattern).ToList();
- return diagnostics.Count > 0 ? null : new(source,data.Document with { Patterns=patterns, ConceptPoints=points.Points });
+ return diagnostics.Count > 0 ? null : new(source,data.Document with { Patterns=patterns, ConceptPoints=points.Points, EquationCurves=points.Curves });
}
private static IReadOnlyList<string>? OccurrenceOwner(IReadOnlyList<StatementSyntax> statements, DeclarationSyntax target, IReadOnlyList<string> path)
@@ -225,7 +225,7 @@ internal static class CanonicalStaticAuthoring
|| symmetry.Mirrors.Count > 0 || symmetry.RadialPatterns.Count > 0 || linear.Patterns.Count > 0 || linear.Axes.Count > 0;
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);
- return diagnostics.Any(d => d.StartsWith(ConceptPointAuthoring.Prefix, StringComparison.Ordinal)) ? null : new(source, null);
+ return diagnostics.Any(d => d.StartsWith(ConceptPointAuthoring.Prefix, StringComparison.Ordinal)) ? null : new(source, points.Curves.Count == 0 ? null : new([],[],[],[],[], EquationCurves: points.Curves));
}
var changes = new List<(int Start, int Length, string Text)>();
var names = new HashSet<string>(StringComparer.Ordinal);
@@ -486,7 +486,7 @@ internal static class CanonicalStaticAuthoring
if (diagnostics.Any(d => d.StartsWith(ConceptPointAuthoring.Prefix, StringComparison.Ordinal))) return null;
var pointSources = points.Points.ToDictionary(p => ConceptPointAuthoring.SetName(p.Name), p => p.Name, StringComparer.Ordinal);
patterns = patterns.Select(p => pointSources.TryGetValue(p.Source, out var name) ? p with { Source = name, Associations = p.Associations?.Select(a => a with { SourceSet = name }).ToArray() } : p).ToList();
- return new(source, new(recordTypes, arrays, templates.Select(t => new FirmamentV2CanonicalTemplateDecl(t.Name, t.Type, t.Parameter, t.Body, t.Span)).ToArray(), patterns, requires, semanticConstraints, projections, staticRecords, tables, sets, symmetry.Mirrors, symmetry.RadialPatterns, linear.Patterns, linear.Axes, points.Points));
+ return new(source, new(recordTypes, arrays, templates.Select(t => new FirmamentV2CanonicalTemplateDecl(t.Name, t.Type, t.Parameter, t.Body, t.Span)).ToArray(), patterns, requires, semanticConstraints, projections, staticRecords, tables, sets, symmetry.Mirrors, symmetry.RadialPatterns, linear.Patterns, linear.Axes, points.Points, points.Curves));
}
// Domain adapters reuse the existing finite Set binder and Pattern materializer.
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptFunctionBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptFunctionBinding.cs
new file mode 100644
index 00000000..bc186f15
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptFunctionBinding.cs
@@ -0,0 +1,231 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+internal static partial class ConceptPointAuthoring
+{
+ /// <summary>Pure typed Function binding. Inlining is an AST transformation;
+ /// arithmetic and units remain owned by FirmamentNumericEvaluation.</summary>
+ internal sealed class MathCatalog(Action<string, string, FirmamentV2SourceSpan> error, FirmamentCompileTimeValues? scalars)
+ {
+ internal string SourceContext { get; set; } = "";
+ private readonly Dictionary<string, Function> functions = new(StringComparer.Ordinal);
+ private FirmamentCompileTimeValues? Values => scalars;
+ private int work;
+ private bool checking;
+ internal IReadOnlyDictionary<string, EquationCurveAuthoring.BoundCurve> Curves { get; set; } = new Dictionary<string, EquationCurveAuthoring.BoundCurve>();
+
+ internal string Parse(string source)
+ {
+ SourceContext = source;
+ var declarations = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)
+ .Where(d => d.Type.Name.Text == "Function").ToArray();
+ foreach (var d in declarations)
+ {
+ var name = d.Name?.Text ?? "<unnamed>";
+ var type = FirmamentSyntaxValues.Reference(d.ResultType) ?? "";
+ var args = d.Parameters.Select(p => (Name: p.Name?.Text ?? "", Type: FirmamentSyntaxValues.Reference(p.Value) ?? "")).ToArray();
+ if (d.Name is null || d.Type.Arguments.Count != 0 || d.Occurrence || d.Initializer is null || d.Body is not null || d.Modifiers.Count != 0 || d.Clauses.Count != 0 || d.Annotation is not null
+ || name is "Pow" or "Sin" or "Cos" or "Point2" or "Point3" || !Allowed(type) || args.Length > 16 || args.Any(a => a.Name.Length == 0 || !Allowed(a.Type))
+ || args.Select(a => a.Name).Distinct().Count() != args.Length || d.Parameters.Any(p => p.Default is not null)
+ || !functions.TryAdd(name, new(name, args, type, d.Initializer)))
+ error("function-definition-invalid", $"Function '{name}' requires unique typed parameters and one expression result (scalar, Point2, Point3 or a declared Record).", d.Span);
+ }
+ if (functions.Count > 128) error("function-limit", "A Function catalog may contain at most 128 declarations.", declarations[128].Span);
+ var visited = new HashSet<string>();
+ bool Cycle(string name, HashSet<string> active)
+ {
+ if (visited.Contains(name) || !functions.TryGetValue(name, out var function)) return false;
+ if (!active.Add(name)) return true;
+ var cycle = FirmamentSyntaxTraversal.Expressions(new DocumentSyntax("function", [new ExpressionStatementSyntax(function.Body, function.Body.Span)], [], function.Body.Span)).OfType<CallSyntax>()
+ .Select(c => FirmamentSyntaxValues.Reference(c.Target)).OfType<string>().Any(n => Cycle(n, active));
+ active.Remove(name); visited.Add(name); return cycle;
+ }
+ foreach (var f in functions.Values)
+ if (Cycle(f.Name, [])) error("function-cycle", $"Function '{f.Name}' has a recursive dependency; Functions must form a finite acyclic graph.", f.Body.Span);
+ checking = true;
+ foreach (var f in functions.Values)
+ {
+ work = 10000;
+ try
+ {
+ if (f.Body.Span.Length > 8192) throw new FormatException();
+ var bodyTree = new DocumentSyntax("function", [new ExpressionStatementSyntax(f.Body, f.Body.Span)], [], f.Body.Span);
+ if (FirmamentSyntaxTraversal.Expressions(bodyTree).OfType<ReferenceSyntax>().Any(r =>
+ !f.Parameters.Any(p => p.Name == r.Name.Text) && !functions.ContainsKey(r.Name.Text)
+ && r.Name.Text is not ("Point2" or "Point3" or "Sin" or "Cos" or "Pow") && scalars?.IsRecordType(r.Name.Text) != true)) throw new FormatException();
+ var arguments = f.Parameters.ToDictionary(p => p.Name, p => Placeholder(p.Type, 0), StringComparer.Ordinal);
+ var body = new FirmamentSyntaxSubstitution(arguments).Expression(f.Body);
+ var expanded = new Inline(this, new HashSet<string> { f.Name }).Expression(body);
+ if (!Matches(expanded, f.ReturnType)) throw new FormatException();
+ }
+ catch (FormatException) { error("function-body-invalid", $"Function '{f.Name}' must return {f.ReturnType} with matching units and finite, acyclic dependencies; parameters are explicit lexical inputs.", f.Body.Span); }
+ }
+ checking = false;
+ foreach (var d in declarations.OrderByDescending(d => d.Span.Start))
+ source = source.Remove(d.Span.Start, d.Span.Length).Insert(d.Span.Start, Blank(source.Substring(d.Span.Start, d.Span.Length)));
+ return source;
+ }
+
+ private bool Allowed(string type) => type is "Int" or "Float" or "Length" or "Angle" or "Point2" or "Point3" || scalars?.IsRecordType(type) == true;
+ private static string Unit(string type) => type switch { "Length" => "mm", "Angle" => "deg", _ => "" };
+ private static ExpressionSyntax ParseValue(string text) => FirmamentSyntaxParser.ParseExpression(text).Expression ?? throw new FormatException();
+
+ private ExpressionSyntax Placeholder(string type, int depth)
+ {
+ if (depth > 32) throw new FormatException();
+ if (type is "Point2" or "Point3") return ParseValue(type + "(" + string.Join(",", Enumerable.Repeat("1mm", type == "Point2" ? 2 : 3)) + ")");
+ if (scalars?.RecordFields(type) is { } fields)
+ return ParseValue(type + " { " + string.Join(";", fields.Select(f => f.Key + ": " + FirmamentSyntaxWriter.Expression(Placeholder(f.Value, depth + 1)))) + " }");
+ if (type is not ("Int" or "Float" or "Length" or "Angle")) throw new FormatException();
+ return ParseValue("1" + Unit(type));
+ }
+
+ private bool Matches(ExpressionSyntax expression, string type)
+ {
+ if (type is "Point2" or "Point3")
+ return expression is CallSyntax { Target: ReferenceSyntax t } p && t.Name.Text == type
+ && p.Arguments.Count == (type == "Point2" ? 2 : 3) && p.Arguments.All(a => a.Name is null && a.Default is null && Matches(a.Value, "Length"));
+ if (scalars?.RecordFields(type) is { } fields)
+ {
+ if (expression is not ObjectSyntax o || FirmamentSyntaxValues.Reference(o.Type) != type || o.Name is not null
+ || o.Body.Statements.Count != fields.Count || o.Body.Statements.Any(s => s is not FieldSyntax)) return false;
+ var actual = o.Body.Statements.Cast<FieldSyntax>().ToArray();
+ return actual.Select(f => f.Name.Text).Distinct().Count() == fields.Count
+ && actual.All(f => fields.TryGetValue(f.Name.Text, out var fieldType) && Matches(f.Value, fieldType));
+ }
+ if (type is not ("Int" or "Float" or "Length" or "Angle")) return false;
+ if (type == "Int" && curveParameter is not null && FirmamentSyntaxTraversal.Expressions(expression).OfType<ReferenceSyntax>().Any(r => r.Name.Text == curveParameter)) return false;
+ var variables = curveParameter is null ? null : new Dictionary<string, FirmamentNumericEvaluation.Value> { [curveParameter] = new(1, "") };
+ if (!FirmamentNumericEvaluation.TryEvaluate(expression, out var result, variables, typeOnly: checking)) return false;
+ return (type == "Angle" ? result.Unit is "deg" or "rad" : result.Unit == Unit(type))
+ && (checking || type != "Int" || Math.Abs(result.Number) <= 9007199254740991d && result.Number == Math.Truncate(result.Number));
+ }
+
+ private sealed class Inline(MathCatalog owner, HashSet<string> active) : FirmamentSyntaxRewriter
+ {
+ internal override ExpressionSyntax Expression(ExpressionSyntax e)
+ {
+ if (--owner.work < 0 || active.Count > 32) throw new FormatException();
+ if (FirmamentSyntaxValues.Reference(e) is { } input && e is ReferenceSyntax or MemberSyntax
+ && input.Split('.')[0] != owner.curveParameter
+ && owner.Values?.TryValue(input, out var requirement) == true && requirement.Tolerance is not null)
+ throw new FormatException("Function evaluation cannot erase a typed tolerance; use a tolerance-preserving engineering consumer and explicit PMI.");
+ if (e is CallSyntax { Target: MemberSyntax { Member.Text: "At" } member, Arguments.Count: 1 } at
+ && FirmamentSyntaxValues.Reference(member.Target) is { } path && owner.Curves.TryGetValue(path, out var curve))
+ {
+ if (at.Arguments[0].Name is not null || at.Arguments[0].Default is not null
+ || !FirmamentNumericEvaluation.TryEvaluate(Expression(at.Arguments[0].Value), out var parameter) || parameter.Unit != ""
+ || parameter.Number < curve.Value.Start || parameter.Number > curve.Value.End) throw new FormatException();
+ return Expression(new FirmamentSyntaxSubstitution(new Dictionary<string, ExpressionSyntax> { [curve.Value.Parameter] = ParseValue(Literal(parameter.Number, "")) }).Expression(curve.Point));
+ }
+ if (e is CallSyntax { Target: ReferenceSyntax target } call && owner.functions.TryGetValue(target.Name.Text, out var function))
+ {
+ if (call.Arguments.Count != function.Parameters.Count || call.Arguments.Any(a => a.Name is not null || a.Default is not null)
+ || function.Body.Span.Length > 8192) throw new FormatException();
+ var args = new Dictionary<string, ExpressionSyntax>(StringComparer.Ordinal);
+ for (var i = 0; i < function.Parameters.Count; i++)
+ {
+ var arg = Expression(call.Arguments[i].Value);
+ if (!owner.Matches(arg, function.Parameters[i].Type)) throw new FormatException();
+ args.Add(function.Parameters[i].Name, arg);
+ }
+ if (owner.checking && owner.curveParameter is null) return owner.Placeholder(function.ReturnType, 0);
+ if (!active.Add(function.Name)) throw new FormatException();
+ try
+ {
+ var value = Expression(new FirmamentSyntaxSubstitution(args).Expression(function.Body));
+ // Unbound curve parameters are checked by the curve owner after
+ // typed placeholders prove the declaration's result shape.
+ if (!owner.Matches(value, function.ReturnType)) throw new FormatException();
+ return value;
+ }
+ finally { active.Remove(function.Name); }
+ }
+ if (e is ReferenceSyntax r && r.Name.Text != owner.curveParameter && owner.Values?.TryRecord(r.Name.Text, out var record) == true)
+ {
+ if (record.Fields.Keys.Any(field => owner.Values.TryValue(record.Name + "." + field, out var value) && value.Tolerance is not null)) throw new FormatException();
+ return Expression(ParseValue(record.TypeName + " { " + string.Join(";", record.Fields.Select(f => f.Key + ": " + f.Value)) + " }"));
+ }
+ var result = base.Expression(e);
+ // Admit the whole constructor before projecting any member. Otherwise
+ // `.point` could erase unknown/duplicate sibling fields or bad units.
+ if (result is ObjectSyntax obj && (FirmamentSyntaxValues.Reference(obj.Type) is not { } recordType || !owner.Matches(obj, recordType)))
+ throw new FormatException("Record construction requires its declared fields and matching types.");
+ if (result is CallSyntax { Target: ReferenceSyntax pointType } point && pointType.Name.Text is "Point2" or "Point3" && !owner.Matches(point, pointType.Name.Text))
+ throw new FormatException("Point construction requires exactly two/three Length coordinates.");
+ if (result is MemberSyntax m)
+ {
+ if (m.Target is ObjectSyntax o)
+ return o.Body.Statements.OfType<FieldSyntax>().SingleOrDefault(f => f.Name.Text == m.Member.Text)?.Value ?? throw new FormatException();
+ if (m.Target is CallSyntax { Target: ReferenceSyntax t } p && t.Name.Text is "Point2" or "Point3")
+ {
+ var index = "XYZ".IndexOf(m.Member.Text, StringComparison.Ordinal);
+ if (m.Member.Text.Length != 1 || index < 0 || index >= p.Arguments.Count) throw new FormatException();
+ return p.Arguments[index].Value;
+ }
+ }
+ return owner.Values?.NominalExpression(result, owner.curveParameter is null ? null : new HashSet<string> { owner.curveParameter }) ?? result;
+ }
+ }
+
+ internal ExpressionSyntax Bind(ExpressionSyntax expression, IReadOnlyDictionary<string, (double Value, string Unit)>? variables = null, bool symbolic = false)
+ {
+ work = 10000;
+ var saved = checking;
+ checking = symbolic;
+ try
+ {
+ // Symbolic parameters use typed leaves during call admission. Restore
+ // the parameter expression after inlining so curve analysis sees it.
+ var local = variables?.ToDictionary(p => p.Key, p => ParseValue(Literal(p.Value.Value, p.Value.Unit)), StringComparer.Ordinal) ?? [];
+ return new Inline(this, []).Expression(new FirmamentSyntaxSubstitution(local).Expression(expression));
+ }
+ finally { checking = saved; }
+ }
+ internal bool Evaluate(ExpressionSyntax expression, IReadOnlyDictionary<string, (double Value, string Unit)> variables, out double value, out string unit)
+ {
+ value = double.NaN; unit = "";
+ try
+ {
+ if (!FirmamentNumericEvaluation.TryEvaluate(Bind(expression, variables), out var result)) return false;
+ value = result.Number; unit = result.Unit; return true;
+ }
+ catch (FormatException) { return false; }
+ }
+ internal ExpressionSyntax BindCurve(ExpressionSyntax expression, string parameter)
+ {
+ // Curve parameters have Float type but must survive in the resulting AST.
+ // A type-only variable is recognized by Matches, never substituted numerically.
+ curveParameter = parameter;
+ try { return Bind(expression, symbolic: true); }
+ finally { curveParameter = null; }
+ }
+ private string? curveParameter;
+
+ internal string Normalize(string source)
+ {
+ SourceContext = source;
+ var changes = new List<(FirmamentV2SourceSpan Span, string Text)>();
+ bool Known(CallSyntax call) => FirmamentSyntaxValues.Reference(call.Target) is { } name && (functions.ContainsKey(name) || name is "Sin" or "Cos")
+ || call.Target is MemberSyntax { Member.Text: "At" } m && FirmamentSyntaxValues.Reference(m.Target) is { } path && Curves.ContainsKey(path);
+ foreach (var expression in FirmamentSyntaxTraversal.Expressions(FirmamentSyntaxParser.Parse(source).Document)
+ .Where(e => e is CallSyntax c && Known(c) || e is MemberSyntax && FirmamentSyntaxTraversal.Expressions(e).OfType<CallSyntax>().Any(Known))
+ .OrderBy(c => c.Span.Start).ThenByDescending(c => c.Span.Length))
+ {
+ if (changes.Any(c => Contains(c.Span, expression.Span))) continue;
+ try { changes.Add((expression.Span, Render(Bind(expression)))); }
+ catch (FormatException exception) { error("function-call-invalid", "Cannot evaluate Function/curve call: check argument types, units, parameter domain, tolerated inputs and finite evaluation limits. " + exception.Message, expression.Span); }
+ }
+ return Apply(source, changes);
+ }
+ private string Render(ExpressionSyntax value)
+ {
+ if (value is CallSyntax { Target: ReferenceSyntax t } p && t.Name.Text is "Point2" or "Point3")
+ return t.Name.Text + "(" + string.Join(",", p.Arguments.Select(a => Render(a.Value))) + ")";
+ if (value is ObjectSyntax o) return FirmamentSyntaxValues.Reference(o.Type) + " { " + string.Join(";", o.Body.Statements.Cast<FieldSyntax>().Select(f => f.Name.Text + ": " + Render(f.Value))) + " }";
+ if (!FirmamentNumericEvaluation.TryEvaluate(value, out var scalar)) throw new FormatException();
+ return Literal(scalar.Number, scalar.Unit);
+ }
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs
index 0caf3afa..ae6c46ef 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs
@@ -5,99 +5,13 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;
/// <summary>Checked finite point recipes over the unified AST. Existing keyed Set and
/// Pattern owners still perform construction expansion; this owner transports values only.</summary>
-internal static class ConceptPointAuthoring
+internal static partial class ConceptPointAuthoring
{
internal const string Prefix = "firmament-concept-points-";
- internal sealed record Result(string Source, IReadOnlyList<ConceptIrKeyedPointSetValue> Points, MathCatalog Math);
+ internal sealed record Result(string Source, IReadOnlyList<ConceptIrKeyedPointSetValue> Points, MathCatalog Math,
+ IReadOnlyList<FirmamentEquationCurve> Curves);
private sealed record Function(string Name, IReadOnlyList<(string Name, string Type)> Parameters, string ReturnType, ExpressionSyntax Body);
- internal sealed class MathCatalog
- {
- private int remainingCalls;
- internal string SourceContext { get; set; } = "";
- private readonly Dictionary<string, Function> functions = new(StringComparer.Ordinal);
- private readonly Action<string, string, FirmamentV2SourceSpan> error;
- internal MathCatalog(Action<string, string, FirmamentV2SourceSpan> error) => this.error = error;
- internal string Parse(string source)
- {
- SourceContext = source;
- var declarations = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)
- .Where(d => d.Type.Name.Text == "Function").ToArray();
- foreach (var d in declarations)
- {
- var name = d.Name?.Text ?? "<unnamed>";
- var type = FirmamentSyntaxValues.Reference(d.ResultType) ?? "";
- var args = d.Parameters.Select(p => (Name: p.Name?.Text ?? "", Type: FirmamentSyntaxValues.Reference(p.Value) ?? "")).ToArray();
- if (d.Name is null || d.Type.Arguments.Count != 0 || d.Occurrence || d.Initializer is null || d.Body is not null || d.Modifiers.Count != 0 || d.Clauses.Count != 0 || d.Annotation is not null
- || name == "Pow" || !Allowed(type) || args.Length > 16 || args.Any(a => a.Name.Length == 0 || !Allowed(a.Type))
- || args.Select(a => a.Name).Distinct().Count() != args.Length || d.Parameters.Any(p => p.Default is not null)
- || !functions.TryAdd(name, new(name, args, type, d.Initializer)))
- error("function-definition-invalid", $"Function '{name}' requires unique typed scalar parameters and one expression result.", d.Span);
- }
- if (functions.Count > 128) error("function-limit", "A Function catalog may contain at most 128 declarations.", declarations[128].Span);
- var checkedFunctions = new HashSet<string>(StringComparer.Ordinal);
- IEnumerable<string> Dependencies(Function f) => FirmamentSyntaxTraversal.Expressions(f.Body).OfType<CallSyntax>()
- .Select(c => FirmamentSyntaxValues.Reference(c.Target)).OfType<string>();
- bool Cycle(string name, HashSet<string> active)
- {
- if (!functions.TryGetValue(name, out var f) || checkedFunctions.Contains(name)) return false;
- if (!active.Add(name)) return true;
- var cycle = Dependencies(f).Any(n => Cycle(n, active)); active.Remove(name);
- if (!cycle) checkedFunctions.Add(name); return cycle;
- }
- foreach (var f in functions.Values)
- {
- var variables = f.Parameters.ToDictionary(p => p.Name, p => new FirmamentNumericEvaluation.Value(1, Unit(p.Type)), StringComparer.Ordinal);
- if (f.Body.Span.Length > 8192 || !FirmamentNumericEvaluation.TryEvaluate(f.Body, out var result, variables, (n, a) => Call(n, a, true, []), true) || result.Unit != Unit(f.ReturnType))
- error("function-body-invalid", $"Function '{f.Name}' must return {f.ReturnType}; use its parameters and admitted scalar Functions with matching units.", f.Body.Span);
- if (Cycle(f.Name, [])) error("function-cycle", $"Function '{f.Name}' has a recursive dependency; Functions must form a finite acyclic graph.", f.Body.Span);
- }
- // Keep offsets stable for original point diagnostics. Functions have no material output.
- foreach (var d in declarations.OrderByDescending(d => d.Span.Start))
- source = source.Remove(d.Span.Start, d.Span.Length).Insert(d.Span.Start, Blank(source.Substring(d.Span.Start, d.Span.Length)));
- return source;
- }
- private FirmamentNumericEvaluation.Value Call(string name, IReadOnlyList<FirmamentNumericEvaluation.Value> args, bool typeOnly, HashSet<string> active)
- {
- if (!typeOnly && --remainingCalls < 0 || !functions.TryGetValue(name, out var f) || args.Count != f.Parameters.Count || active.Count >= 32 || !active.Add(name)) throw new FormatException();
- try
- {
- for (var i = 0; i < args.Count; i++)
- if (args[i].Unit != Unit(f.Parameters[i].Type) || !typeOnly && f.Parameters[i].Type == "Int" && !ValidInt(args[i].Number)) throw new FormatException();
- if (typeOnly) return new(1, Unit(f.ReturnType));
- var variables = f.Parameters.Select((p, i) => (p.Name, Value: args[i])).ToDictionary(p => p.Name, p => p.Value, StringComparer.Ordinal);
- if (f.Body.Span.Length > 8192 || !FirmamentNumericEvaluation.TryEvaluate(f.Body, out var result, variables, (n, a) => Call(n, a, false, active))
- || result.Unit != Unit(f.ReturnType) || f.ReturnType == "Int" && !ValidInt(result.Number)) throw new FormatException();
- return result;
- }
- finally { active.Remove(name); }
- }
- internal bool Evaluate(ExpressionSyntax expression, IReadOnlyDictionary<string, (double Value, string Unit)> variables, out double value, out string unit)
- {
- remainingCalls = 10000;
- value = double.NaN; unit = "";
- if (expression.Span.Length > 8192 || !FirmamentNumericEvaluation.TryEvaluate(expression, out var result,
- variables.ToDictionary(p => p.Key, p => new FirmamentNumericEvaluation.Value(p.Value.Value, p.Value.Unit)), (n, a) => Call(n, a, false, []))) return false;
- value = result.Number; unit = result.Unit; return true;
- }
- internal string Normalize(string source)
- {
- SourceContext = source;
- var changes = new List<(FirmamentV2SourceSpan Span, string Text)>();
- foreach (var call in FirmamentSyntaxTraversal.Expressions(FirmamentSyntaxParser.Parse(source).Document).OfType<CallSyntax>().OrderBy(c => c.Span.Start).ThenByDescending(c => c.Span.Length))
- {
- if (FirmamentSyntaxValues.Reference(call.Target) is not { } name || !functions.ContainsKey(name)
- || changes.Any(c => Contains(c.Span, call.Span))) continue;
- if (Evaluate(call, new Dictionary<string, (double, string)>(), out var value, out var unit)) changes.Add((call.Span, Literal(value, unit)));
- else { error("function-call-invalid", $"Cannot evaluate Function '{name}': check argument types, units and finite evaluation limits.", call.Span); }
- }
- return Apply(source, changes);
- }
- private static bool ValidInt(double value) => Math.Abs(value) <= 9007199254740991d && value == Math.Truncate(value);
- private static bool Allowed(string type) => type is "Int" or "Float" or "Length" or "Angle";
- private static string Unit(string type) => type switch { "Length" => "mm", "Angle" => "deg", _ => "" };
- }
-
internal static Result? Expand(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null)
{
var input = source;
@@ -108,7 +22,10 @@ internal static class ConceptPointAuthoring
var d = new FirmamentV2ValidationDiagnostic(Prefix + code, "error", message) { SourceSpan = span, IsOriginalSource = true, Stage = "Point/law binding" };
scalars?.AddPointDiagnostic(d, math?.SourceContext ?? input);
}
- math = new MathCatalog(Error); source = math.Parse(source);
+ math = new MathCatalog(Error, scalars); source = math.Parse(source);
+ if (diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal))) return null;
+ var curves = EquationCurveAuthoring.Expand(source, math, scalars, Error);
+ source = curves.Source;
if (diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal))) return null;
var syntax = FirmamentSyntaxParser.Parse(source);
var collections = new List<ConceptIrKeyedPointSetValue>();
@@ -158,6 +75,9 @@ internal static class ConceptPointAuthoring
}
double[]? Point(ExpressionSyntax? expression, IReadOnlyDictionary<string, (double, string)> locals)
{
+ if (expression is not null)
+ try { expression = math.Bind(Bound(expression, locals), locals); }
+ catch (FormatException) { Error("point-expression-invalid", $"'{identity}' requires a finite typed point result; check Function inputs and curve parameter bounds.", expression.Span); return null; }
IReadOnlyList<ArgumentSyntax>? items = expression switch
{
CallSyntax { Target: ReferenceSyntax t } c when t.Name.Text == element => c.Arguments,
@@ -273,7 +193,7 @@ internal static class ConceptPointAuthoring
else if (collections.Any(c => name.StartsWith(c.Name + ".", StringComparison.Ordinal)))
Error("point-member-unresolved", $"Unknown point/member '{name}'; Point2 has X/Y and Point3 has X/Y/Z.", e.Span);
}
- return diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal)) ? null : new(Apply(source, replacements), collections, math);
+ return diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal)) ? null : new(Apply(source, replacements), collections, math, curves.Curves.Select(c => c.Value).ToArray());
Dictionary<string, FieldSyntax> Fields(DeclarationSyntax d, bool vocabulary = true)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/EquationCurveAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/EquationCurveAuthoring.cs
new file mode 100644
index 00000000..d9cf32f1
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/EquationCurveAuthoring.cs
@@ -0,0 +1,294 @@
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>Resolved compile-time curve. Coordinates are local millimetres;
+/// representation accuracy is distinct from an engineering tolerance.</summary>
+public sealed record FirmamentEquationCurve(string StableId, string Name, string ElementType,
+ string Parameter, double Start, double End, string Frame, string Representation, string GeometryKind,
+ double? MaxDeviation, double ErrorBound, IReadOnlyList<FirmamentEquationCurveSegment> Segments,
+ bool Closed, bool Periodic, string Equation, FirmamentV2SourceSpan? SourceSpan)
+{
+ public IReadOnlyList<string> GeneratedGuides { get; init; } = [];
+}
+public sealed record FirmamentEquationCurveSegment(double Start, double End, string Kind,
+ IReadOnlyList<IReadOnlyList<double>> Controls);
+
+/// <summary>Local AST admission and lowering to existing construction guides.
+/// This owner does not choose a document parser or execute host-language code.</summary>
+internal static class EquationCurveAuthoring
+{
+ internal sealed record BoundCurve(FirmamentEquationCurve Value, ExpressionSyntax Point, ConstructionPlane? Plane);
+ internal sealed record Result(string Source, IReadOnlyList<BoundCurve> Curves);
+
+ internal static Result Expand(string source, ConceptPointAuthoring.MathCatalog math, FirmamentCompileTimeValues? scalars,
+ Action<string, string, FirmamentV2SourceSpan> error)
+ {
+ var document = FirmamentSyntaxParser.Parse(source).Document;
+ var declarations = FirmamentSyntaxTraversal.Declarations(document).ToArray();
+ var curves = new List<BoundCurve>();
+ var changes = new List<(FirmamentV2SourceSpan Span, string Text)>();
+ var lowered = new Dictionary<string, string>(StringComparer.Ordinal);
+ var frames = new Dictionary<string, string>(StringComparer.Ordinal);
+ var generated = new List<string>();
+ var occupied = document.Tokens.Where(t => t.Kind == SyntaxTokenKind.Identifier).Select(t => t.Text).ToHashSet(StringComparer.Ordinal);
+ string Fresh(string id)
+ {
+ var stem = "__Equation_" + Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(id)))[..20];
+ var name = stem; var n = 0; while (!occupied.Add(name)) name = stem + "_" + ++n; return name;
+ }
+ foreach (var d in declarations.Where(d => d.Type.Name.Text is "Curve2" or "Curve3" && d.Body is not null))
+ {
+ // Existing profile-copy Curve2 remains owned by ConceptProfileDerivation.
+ if (!d.Body!.Statements.OfType<FieldSyntax>().Any(f => f.Name.Text.Equals("parameter", StringComparison.OrdinalIgnoreCase)) && d.Type.Name.Text == "Curve2") continue;
+ if (curves.Count >= 128) { error("curve-limit", "Use at most 128 equation curves per compilation.", d.Span); break; }
+ var owner = declarations.SingleOrDefault(o => o.Type.Name.Text == "Struct" && o.Modifiers.Any(m => m.Name.Text == "Concept") && o.Body?.Statements.Contains(d) == true);
+ if (owner?.Name is null || d.Name is null || d.Occurrence || d.Type.Arguments.Count != 0 || d.Modifiers.Count != 0 || d.HasParameterList
+ || d.Annotation is not null || d.ResultType is not null || d.Initializer is not null || d.Clauses.Count != 0
+ || owner.Annotation is not null || owner.HasParameterList || owner.Modifiers.Count != 1 || owner.Type.Arguments.Count != 0
+ || owner.Occurrence || owner.Initializer is not null || owner.ResultType is not null
+ || owner.Clauses.Count > 1 || owner.Clauses.Any(c => c.Kind != ClauseKind.On || c.Value is not ReferenceSyntax))
+ { error("curve-header-invalid", "Equation Curve2/Curve3 requires a named declaration directly inside a plain Concept Struct (optionally on XY/XZ/YZ).", d.Span); continue; }
+ var identity = owner.Name.Text + "." + d.Name.Text;
+ if (curves.Any(c => c.Value.Name == identity)) { error("curve-duplicate", $"Duplicate curve '{identity}'.", d.Span); continue; }
+ var fields = new Dictionary<string, FieldSyntax>(StringComparer.OrdinalIgnoreCase); var valid = true;
+ foreach (var s in d.Body.Statements)
+ if (s is not FieldSyntax f || !fields.TryAdd(f.Name.Text, f)) { error("curve-field-invalid", $"Curve '{identity}' requires unique named fields.", s.Span); valid = false; }
+ ExpressionSyntax? Take(string name) => fields.Remove(name, out var f) ? f.Value : null;
+ var parameterExpression = Take("parameter"); var parameter = parameterExpression is ReferenceSyntax p ? p.Name.Text : null;
+ var domain = Take("domain") as SequenceSyntax;
+ var from = Take("from"); var on = Take("on"); var representation = FirmamentSyntaxValues.Reference(Take("representation")) ?? "Exact";
+ var deviation = Take("maxDeviation"); var closedExpression = Take("closed"); var periodicExpression = Take("periodic");
+ foreach (var f in fields.Values) { error("curve-field-unknown", $"Unknown field '{f.Name.Text}' in {d.Type.Name.Text} '{identity}'.", f.Span); valid = false; }
+ if (parameter is null || from is null || domain is not { Kind: SequenceKind.List, Items.Count: 2 } || domain.Items.Any(a => a.Name is not null || a.Default is not null))
+ { error("curve-domain-invalid", $"Curve '{identity}' requires parameter: identifier, domain: [start,end] and a typed Point expression.", d.Span); continue; }
+ bool Scalar(ExpressionSyntax e, string unit, out double value)
+ {
+ if (scalars is not null && FirmamentSyntaxTraversal.Expressions(e).Any(x => FirmamentSyntaxValues.Reference(x) is { } reference && scalars.TryValue(reference, out var v) && v.Tolerance is not null))
+ { error("curve-tolerance-unsupported", "A curve cannot discard a manufacturing tolerance. maxDeviation is a separate representation error budget.", e.Span); value = double.NaN; return false; }
+ return math.Evaluate(e, new Dictionary<string, (double, string)>(), out value, out var actual) && actual == unit;
+ }
+ if (!Scalar(domain.Items[0].Value, "", out var start) || !Scalar(domain.Items[1].Value, "", out var end) || end <= start || !double.IsFinite(end - start))
+ { error("curve-domain-invalid", $"Curve '{identity}' needs a finite, increasing dimensionless domain.", domain.Span); continue; }
+ bool Flag(ExpressionSyntax? e, out bool value)
+ { value = e is LiteralSyntax { Raw: "true" }; return e is null or LiteralSyntax { Raw: "true" or "false" }; }
+ if (!Flag(closedExpression, out var closed) || !Flag(periodicExpression, out var periodic)) { error("curve-closure-invalid", "closed and periodic must be Boolean literals.", d.Span); continue; }
+ closed |= periodic;
+ var type = d.Type.Name.Text == "Curve2" ? "Point2" : "Point3";
+ var dimension = type == "Point2" ? 2 : 3;
+ var frame = FirmamentSyntaxValues.Reference(on) ?? (type == "Point3" ? "World" : owner.Clauses.FirstOrDefault(c => c.Kind == ClauseKind.On) is { } clause ? FirmamentSyntaxValues.Reference(clause.Value) : null);
+ ConstructionPlane? plane = null;
+ if (frame is null || on is not null && FirmamentSyntaxValues.Reference(on) is null || type == "Point3" && (frame != "World" || owner.Clauses.Count != 0))
+ { error("curve-frame-unsupported", $"Curve '{identity}' requires an explicit Curve2 plane, or Curve3 on World in its definition's coordinates.", on?.Span ?? d.Span); continue; }
+ if (type == "Point2")
+ {
+ var errors = new List<string>();
+ var frameSource = source;
+ var lookup = frame;
+ if (frame is "XY" or "XZ" or "YZ") { lookup = Fresh(identity + ":lookup"); frameSource += $"\nConcept Struct {lookup} on {frame} {{ }}"; }
+ else
+ {
+ lookup = Fresh(identity + ":lookup");
+ frameSource += $"\nConstruction Plane {lookup} {{ Trace: {(frame.Contains('.') ? frame : owner.Name.Text + "." + frame)} }}";
+ }
+ plane = ProfileAuthoringParser.ResolveNamedConstructionPlane(frameSource, lookup, errors);
+ if (plane is null) { error("curve-frame-unresolved", $"Curve '{identity}' cannot resolve plane '{frame}': {string.Join("; ", errors)}", on?.Span ?? d.Span); continue; }
+ }
+ double? maximum = null;
+ if (representation is not ("Exact" or "Approximate") || representation == "Exact" && deviation is not null
+ || representation == "Approximate" && (deviation is null || !Scalar(deviation, "mm", out var limit) || limit <= 0))
+ { error("curve-representation-invalid", "Use Exact without maxDeviation, or Approximate with a positive maxDeviation Length.", deviation?.Span ?? d.Span); continue; }
+ if (deviation is not null && Scalar(deviation, "mm", out var budget)) maximum = budget;
+ if (!valid) continue;
+ try
+ {
+ // Manufacturing tolerance must not disappear through Function inputs.
+ if (scalars is not null && FirmamentSyntaxTraversal.Expressions(from).Any(x => FirmamentSyntaxValues.Reference(x) is { } reference && reference != parameter
+ && scalars.TryValue(reference, out var v) && v.Tolerance is not null)) throw new FormatException("A manufacturing tolerance cannot be erased into curve coordinates.");
+ var point = math.BindCurve(from, parameter);
+ if (point is not CallSyntax { Target: ReferenceSyntax target } c || target.Name.Text != type || c.Arguments.Count != dimension || c.Arguments.Any(a => a.Name is not null || a.Default is not null)) throw new FormatException($"from must return {type}.");
+ var coordinates = c.Arguments.Select(a => a.Value).ToArray();
+ var variables = new Dictionary<string, FirmamentNumericEvaluation.Value> { [parameter] = new(1, "") };
+ if (coordinates.Any(e => !FirmamentNumericEvaluation.TryEvaluate(e, out var v, variables, typeOnly: true) || v.Unit != "mm")) throw new FormatException("Every coordinate must have Length type.");
+ double[] At(double t) => coordinates.Select(e => FirmamentNumericEvaluation.TryEvaluate(e, out var v,
+ new Dictionary<string, FirmamentNumericEvaluation.Value> { [parameter] = new(t, "") }) ? v.Number : throw new FormatException("Undefined/non-finite equation value.")).ToArray();
+ var segments = new List<FirmamentEquationCurveSegment>();
+ var kind = "CubicBezier"; var errorBound = 0d;
+ var polynomials = coordinates.Select(e => FirmamentNumericEvaluation.TryPolynomial(e, parameter, out var coefficients) ? coefficients : null).ToArray();
+ if (representation == "Exact" && polynomials.All(p => p is not null))
+ {
+ var a = At(start); var b = At(end); var h = end - start;
+ double[] Derivative(double t) => polynomials.Select(p => p![1] + 2 * p[2] * t + 3 * p[3] * t * t).ToArray();
+ var da = Derivative(start); var db = Derivative(end);
+ kind = polynomials.All(p => p![2] == 0 && p[3] == 0) ? "Line" : "CubicBezier";
+ segments.Add(new(start, end, kind, kind == "Line" ? [a, b] : [a, a.Zip(da, (x, v) => x + v * h / 3).ToArray(), b.Zip(db, (x, v) => x - v * h / 3).ToArray(), b]));
+ }
+ else if (representation == "Exact" && dimension == 2 && TryEllipse(coordinates, parameter, start, end, out var ellipse))
+ { kind = ellipse.Kind; segments.Add(ellipse); }
+ else if (representation == "Exact") throw new FormatException("Exact lowering currently admits degree <= 3 polynomials and axis-aligned full circles/ellipses. Request Approximate with maxDeviation for other bounded laws.");
+ else
+ {
+ kind = "Polyline";
+ void Divide(double a, double b, double[] pa, double[] pb, int depth)
+ {
+ if (segments.Count + curves.Sum(c => c.Value.Segments.Count) >= 4096 || depth >= 24) throw new FormatException("Approximation exhausted 4096 total segments or 24 subdivisions before proving maxDeviation.");
+ var bounds = coordinates.Select(e => FirmamentNumericEvaluation.TrySecondDerivativeBound(e, parameter, a, b, out var m) ? m : double.NaN).ToArray();
+ double EndpointError(double t, double[] point) => Math.Sqrt(coordinates.Select((e, i) =>
+ FirmamentNumericEvaluation.TryCurveEvaluationError(e, parameter, t, point[i], out var uncertainty) ? uncertainty * uncertainty : double.NaN).Sum());
+ var norm = Math.Sqrt(bounds.Sum(m => m * m));
+ var bound = Math.BitIncrement(norm * (b - a) * (b - a) / 8 + Math.Max(EndpointError(a, pa), EndpointError(b, pb)));
+ if (double.IsFinite(bound) && bound <= maximum)
+ { segments.Add(new(a, b, "Line", [pa, pb])); errorBound = Math.Max(errorBound, bound); return; }
+ var mid = a + (b - a) / 2;
+ if (mid == a || mid == b) throw new FormatException("Parameter refinement reached floating-point resolution without establishing maxDeviation.");
+ var pm = At(mid); Divide(a, mid, pa, pm, depth + 1); Divide(mid, b, pm, pb, depth + 1);
+ }
+ Divide(start, end, At(start), At(end), 0);
+ }
+ if (segments.SelectMany(s => s.Controls).SelectMany(p => p).Any(v => !double.IsFinite(v))) throw new FormatException("Curve representation exceeds finite coordinates.");
+ var first = At(start); var last = At(end);
+ if (closed && Distance(first, last) > 1e-8) throw new FormatException("closed/periodic endpoints do not coincide; no closing segment is inserted.");
+ if (periodic)
+ {
+ // Polynomial periodicity can be proved directly. Full conics
+ // have matching derivatives by their recognized construction.
+ if (polynomials.All(p => p is not null))
+ {
+ var da = polynomials.Select(p => p![1] + 2 * p[2] * start + 3 * p[3] * start * start).ToArray();
+ var db = polynomials.Select(p => p![1] + 2 * p[2] * end + 3 * p[3] * end * end).ToArray();
+ if (Distance(da, db) > 1e-8) throw new FormatException("periodic requires matching endpoint first derivatives.");
+ }
+ else if (kind is not ("Circle" or "Ellipse")) throw new FormatException("Periodicity proof for this law is not yet admitted; use closed for positional closure only.");
+ }
+ if (segments.All(s => s.Controls.All(p => Distance(p, first) <= 1e-12))) throw new FormatException("Curve is degenerate.");
+ var value = new FirmamentEquationCurve("concept-curve:" + identity, identity, type, parameter, start, end, frame,
+ representation, kind, maximum, errorBound, segments, closed, periodic, FirmamentSyntaxWriter.Expression(from), scalars?.OriginalPointSpan(d.Span, source) ?? d.Span);
+ curves.Add(new(value, point, plane));
+ if (type == "Point3") { changes.Add((d.Span, Blank(source.Substring(d.Span.Start, d.Span.Length)))); continue; }
+ var names = new List<string>(); var text = new List<string>();
+ string Point(IReadOnlyList<double> xy) { var name = Fresh(identity + ":point:" + text.Count); text.Add($"Point2 {name} {{ Position: [{string.Join(",", xy.Select(x => ConceptPointAuthoring.Literal(x, "mm")))}] }}"); return name; }
+ foreach (var s in segments)
+ {
+ var name = Fresh(identity + ":segment:" + names.Count); names.Add(name);
+ if (s.Kind is "Circle" or "Ellipse")
+ {
+ var center = Point(s.Controls[0]); var radii = s.Controls[1];
+ text.Add(s.Kind == "Circle" ? $"Circle2 {name} {{ Center: {center}; Radius: {ConceptPointAuthoring.Literal(radii[0], "mm")} }}"
+ : $"Ellipse2Guide {name} {{ Center: {center}; SemiAxes: [{ConceptPointAuthoring.Literal(Math.Max(radii[0], radii[1]), "mm")},{ConceptPointAuthoring.Literal(Math.Min(radii[0], radii[1]), "mm")}]; Rotation: {(radii[1] > radii[0] ? "90deg" : "0deg")} }}");
+ }
+ else
+ {
+ var points = s.Controls.Select(Point).ToArray();
+ text.Add(s.Kind == "Line" ? $"Line2 {name} {{ From: {points[0]}; To: {points[1]} }}"
+ : $"CubicBezier2 {name} {{ From: {points[0]}; Control1: {points[1]}; Control2: {points[2]}; To: {points[3]} }}");
+ }
+ }
+ changes.Add((d.Span, string.Join("\n", text)));
+ curves[^1] = curves[^1] with { Value = value with { GeneratedGuides = names } };
+ lowered[identity] = string.Join(" |> ", names);
+ var frameName = Fresh(identity + ":frame"); frames[identity] = frameName;
+ generated.Add(frame is "XY" or "XZ" or "YZ" ? $"Concept Struct {frameName} on {frame} {{ }}" : $"Construction Plane {frameName} {{ Trace: {(frame.Contains('.') ? frame : owner.Name.Text + "." + frame)} }}");
+ }
+ catch (FormatException e) { error("curve-admission-failed", $"Curve '{identity}': {e.Message}", from.Span); }
+ }
+ math.Curves = curves.ToDictionary(c => c.Value.Name, StringComparer.Ordinal);
+ foreach (var profile in declarations.Where(d => d.Type.Name.Text == "Profile" && d.Body is not null))
+ {
+ var refs = FirmamentSyntaxTraversal.Expressions(new DocumentSyntax("profile", [profile], [], profile.Span))
+ .Select(FirmamentSyntaxValues.Reference).OfType<string>().Where(lowered.ContainsKey).Distinct().ToArray();
+ if (refs.Length == 0) continue;
+ var used = refs.Select(r => curves.Single(c => c.Value.Name == r)).ToArray();
+ if (used.Any(c => !SamePlane(c.Plane!, used[0].Plane!))) { error("curve-frame-mismatch", "A Profile cannot mix equation curves from different planes.", profile.Span); continue; }
+ var existing = profile.Clauses.FirstOrDefault(c => c.Kind == ClauseKind.Using || c.Kind == ClauseKind.On);
+ if (existing is not null)
+ {
+ var diagnostics = new List<string>();
+ var plane = ProfileAuthoringParser.ResolveNamedConstructionPlane(source, FirmamentSyntaxValues.Reference(existing.Value) ?? "", diagnostics);
+ if (plane is null || !SamePlane(plane, used[0].Plane!)) { error("curve-frame-mismatch", "Profile placement disagrees with its equation curve's plane.", existing.Span); continue; }
+ }
+ try
+ {
+ var rewriter = new CurveReferences(lowered, curves);
+ var rewritten = (DeclarationSyntax)rewriter.Statement(profile);
+ if (existing is null) rewritten = rewritten with { Clauses = [new(ClauseKind.Using, FirmamentSyntaxParser.ParseExpression(frames[refs[0]]).Expression!, profile.Span)] };
+ changes.Add((profile.Span, FirmamentSyntaxWriter.Statement(rewritten)));
+ }
+ catch (FormatException e) { error("curve-consumer-invalid", e.Message, profile.Span); }
+ }
+ foreach (var change in changes.OrderByDescending(c => c.Span.Start)) source = source.Remove(change.Span.Start, change.Span.Length).Insert(change.Span.Start, change.Text);
+ return new(source + (generated.Count == 0 ? "" : "\n" + string.Join("\n", generated)), curves);
+ }
+
+ private sealed class CurveReferences(IReadOnlyDictionary<string, string> lowered, IReadOnlyList<BoundCurve> curves) : FirmamentSyntaxRewriter
+ {
+ internal override ExpressionSyntax Expression(ExpressionSyntax e)
+ {
+ if (e is UnarySyntax { Operator: UnaryOperator.Reverse } reverse
+ && FirmamentSyntaxValues.Reference(reverse.Operand) is { } reversed && lowered.TryGetValue(reversed, out var ordered))
+ {
+ if (curves.Single(c => c.Value.Name == reversed).Value.GeometryKind is "Circle" or "Ellipse")
+ throw new FormatException($"Use {reversed} |> TraceLoop for a complete circle/ellipse; an open traversal requires explicit endpoints.");
+ return FirmamentSyntaxParser.ParseExpression(string.Join(" |> ", ordered.Split(" |> ").Reverse().Select(n => "Reverse " + n))).Expression!;
+ }
+ if (e is BinarySyntax { Operator: BinaryOperator.Pipeline, Right: ReferenceSyntax { Name.Text: "TraceLoop" } } pipeline
+ && FirmamentSyntaxValues.Reference(pipeline.Left) is { } reference && lowered.TryGetValue(reference, out var chain))
+ {
+ var curve = curves.Single(c => c.Value.Name == reference).Value;
+ if (!curve.Closed && curve.GeometryKind is not ("Circle" or "Ellipse")) throw new FormatException($"TraceLoop requires closed: true on '{reference}'.");
+ return FirmamentSyntaxParser.ParseExpression(chain + (curve.GeometryKind is "Circle" or "Ellipse" ? " |> TraceLoop" : "")).Expression!;
+ }
+ if (FirmamentSyntaxValues.Reference(e) is { } name && lowered.TryGetValue(name, out var text))
+ {
+ if (curves.Single(c => c.Value.Name == name).Value.GeometryKind is "Circle" or "Ellipse")
+ throw new FormatException($"Use {name} |> TraceLoop for a complete circle/ellipse; an open traversal requires explicit endpoints.");
+ return FirmamentSyntaxParser.ParseExpression(text).Expression!;
+ }
+ return base.Expression(e);
+ }
+ }
+ private static bool SamePlane(ConstructionPlane a, ConstructionPlane b) => a.Origin == b.Origin && a.AxisX == b.AxisX && a.AxisY == b.AxisY && a.AxisZ == b.AxisZ;
+ internal static ResolvedProfile2D RestoreProvenance(ResolvedProfile2D profile, IReadOnlyList<FirmamentEquationCurve> curves)
+ {
+ var guides = curves.SelectMany(c => c.GeneratedGuides.Select(g => (Guide: g, Curve: c))).ToDictionary(p => p.Guide, p => p.Curve);
+ return profile with { Loops = profile.Loops.Select(loop => loop with { Segments = loop.Segments.Select(segment =>
+ {
+ if (!guides.TryGetValue(segment.Provenance.TracedFrom ?? "", out var curve)) return segment;
+ return segment with { Provenance = segment.Provenance with { ConceptStableId = curve.StableId, TracedFrom = curve.Name,
+ SourceSpan = curve.SourceSpan is { } span ? $"offset:{span.Start}:length:{span.Length}" : segment.Provenance.SourceSpan,
+ Derivation = $"Equation:{curve.Name};representation:{curve.Representation};errorBound:{curve.ErrorBound:R}mm", SourceFrame = curve.Frame } };
+ }).ToArray() }).ToArray() };
+ }
+ private static double Distance(IReadOnlyList<double> a, IReadOnlyList<double> b) => Math.Sqrt(a.Zip(b, (x, y) => (x - y) * (x - y)).Sum());
+ private static string Blank(string text) => new(text.Select(c => c is '\r' or '\n' ? c : ' ').ToArray());
+
+ private static bool TryEllipse(ExpressionSyntax[] coordinates, string parameter, double start, double end, out FirmamentEquationCurveSegment ellipse)
+ {
+ ellipse = null!;
+ // Recognize offset + radius * Cos/Sin(affine angle); no sample-based guessing.
+ bool Axis(ExpressionSyntax e, string intrinsic, out double center, out double radius, out double phase, out double rate)
+ {
+ center = 0; radius = 1; phase = rate = 0;
+ if (e is BinarySyntax { Operator: BinaryOperator.Add } add)
+ {
+ if (FirmamentNumericEvaluation.TryEvaluate(add.Left, out var a) && a.Unit == "mm") { center = a.Number; e = add.Right; }
+ else if (FirmamentNumericEvaluation.TryEvaluate(add.Right, out a) && a.Unit == "mm") { center = a.Number; e = add.Left; }
+ else return false;
+ }
+ if (e is not BinarySyntax { Operator: BinaryOperator.Multiply } product) return false;
+ ExpressionSyntax trig;
+ if (FirmamentNumericEvaluation.TryEvaluate(product.Left, out var r) && r.Unit == "mm") trig = product.Right;
+ else if (FirmamentNumericEvaluation.TryEvaluate(product.Right, out r) && r.Unit == "mm") trig = product.Left;
+ else return false;
+ radius = r.Number;
+ if (radius <= 0 || trig is not CallSyntax { Target: ReferenceSyntax t, Arguments.Count: 1 } call || t.Name.Text != intrinsic) return false;
+ var arg = call.Arguments[0].Value;
+ if (!FirmamentNumericEvaluation.TryPolynomial(arg, parameter, out var p) || p[2] != 0 || p[3] != 0
+ || !FirmamentNumericEvaluation.TryEvaluate(arg, out var type, new Dictionary<string, FirmamentNumericEvaluation.Value> { [parameter] = new(1, "") }, typeOnly: true)) return false;
+ var factor = type.Unit == "deg" ? Math.PI / 180 : 1; phase = p[0] * factor; rate = p[1] * factor; return true;
+ }
+ if (!Axis(coordinates[0], "Cos", out var x, out var rx, out var px, out var wx) || !Axis(coordinates[1], "Sin", out var y, out var ry, out var py, out var wy)
+ || px != py || wx != wy || Math.Abs(wx * (end - start)) != 2 * Math.PI) return false;
+ ellipse = new(start, end, rx == ry ? "Circle" : "Ellipse", [new[] { x, y }, new[] { rx, ry }]); return true;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs
index 854aa31d..9d8fa5c1 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs
@@ -366,6 +366,7 @@ internal sealed partial class FirmamentCompileTimeValues(string source)
}
internal bool IsRecordType(string type) => recordTypes.ContainsKey(type);
+ internal IReadOnlyDictionary<string, string>? RecordFields(string type) => recordTypes.TryGetValue(type, out var record) ? record.Fields : null;
internal bool TryRecord(string reference, out TemplateStaticRecordIr record) => recordValues.TryGetValue(reference, out record!);
internal string RecordReference(TemplateStaticRecordIr record, ImmutableDictionary<string, string> fields)
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs
index 8e32cdf0..66958d01 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs
@@ -254,7 +254,8 @@ public static class FirmamentSourceSpelling
Add("Circle2", "Center Radius");
Add("Rect2 RoundedRect2 Oval2", "Center Size Radius");
Add("Polygon2", "Vertices");
- Add("Curve2", "From On Scale Pivot Translate Rotate");
+ Add("Curve2", "From On Scale Pivot Translate Rotate Parameter Domain Representation MaxDeviation Closed Periodic");
+ Add("Curve3", "From On Parameter Domain Representation MaxDeviation Closed Periodic");
Add("CubicBezier2", "From Control1 Control2 To");
Add("Line2", "From To");
Add("Profile", "From");
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 3b50f7ed..b63af9c7 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -304,7 +304,7 @@ public sealed record FirmamentV2BossDecl(string Name, string Host, string On, st
public sealed record FirmamentV2PocketDecl(string Name, string Host, string On, string Profile, double Depth, double HostThickness, double RemainingFloor, double MinimumFloorThickness, string MinimumFloorPolicySource, string StableId, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2SelectionDecl(string Name, string Target, string Source, string Requirement, FirmamentV2SourceSpan SourceSpan) { public IReadOnlyList<string>? Sources { get; init; } }
/// <summary>Normalized, erased-before-materialization evidence for canonical static authoring.</summary>
-public sealed record FirmamentV2StaticAuthoringDocument(IReadOnlyList<FirmamentV2RecordTypeDecl> RecordTypes, IReadOnlyList<FirmamentV2StaticArrayDecl> Arrays, IReadOnlyList<FirmamentV2CanonicalTemplateDecl> Templates, IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, IReadOnlyList<FirmamentV2RequireDecl> Requires, IReadOnlyList<FirmamentV2SemanticConstraint>? SemanticConstraints = null, IReadOnlyDictionary<string, FirmamentV2PmiProjection>? PmiProjections = null, IReadOnlyList<FirmamentV2StaticRecordDecl>? StaticRecords = null, IReadOnlyList<FirmamentV2StaticTableDecl>? Tables = null, IReadOnlyList<FirmamentV2StaticSetDecl>? Sets = null, IReadOnlyList<FirmamentV2MirrorDerivation>? Mirrors = null, IReadOnlyList<FirmamentV2RadialPatternDecl>? RadialPatterns = null, IReadOnlyList<FirmamentV2LinearPatternDecl>? LinearPatterns = null, IReadOnlyList<FirmamentV2Axis2Decl>? PlanarAxes = null, IReadOnlyList<ConceptIrKeyedPointSetValue>? ConceptPoints = null);
+public sealed record FirmamentV2StaticAuthoringDocument(IReadOnlyList<FirmamentV2RecordTypeDecl> RecordTypes, IReadOnlyList<FirmamentV2StaticArrayDecl> Arrays, IReadOnlyList<FirmamentV2CanonicalTemplateDecl> Templates, IReadOnlyList<FirmamentV2CanonicalPatternDecl> Patterns, IReadOnlyList<FirmamentV2RequireDecl> Requires, IReadOnlyList<FirmamentV2SemanticConstraint>? SemanticConstraints = null, IReadOnlyDictionary<string, FirmamentV2PmiProjection>? PmiProjections = null, IReadOnlyList<FirmamentV2StaticRecordDecl>? StaticRecords = null, IReadOnlyList<FirmamentV2StaticTableDecl>? Tables = null, IReadOnlyList<FirmamentV2StaticSetDecl>? Sets = null, IReadOnlyList<FirmamentV2MirrorDerivation>? Mirrors = null, IReadOnlyList<FirmamentV2RadialPatternDecl>? RadialPatterns = null, IReadOnlyList<FirmamentV2LinearPatternDecl>? LinearPatterns = null, IReadOnlyList<FirmamentV2Axis2Decl>? PlanarAxes = null, IReadOnlyList<ConceptIrKeyedPointSetValue>? ConceptPoints = null, IReadOnlyList<FirmamentEquationCurve>? EquationCurves = null);
public sealed record FirmamentV2RecordTypeDecl(string Name, IReadOnlyDictionary<string, string> Fields, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2StaticArrayDecl(string Name, string ElementType, IReadOnlyList<IReadOnlyDictionary<string, string>> Elements, FirmamentV2SourceSpan SourceSpan);
/// <summary>A finite immutable source-ordered collection whose entry names are semantic identity.</summary>
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index b7a33110..09ec6437 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -1399,6 +1399,8 @@ public static partial class FirmamentV2Parser
private static FirmamentV2ParseResult AttachVolumeAssertionsAndSymbols(FirmamentV2ParseResult parsed, string source, FirmamentV2StaticAuthoringDocument? staticAuthoring, List<string> diagnostics)
{
+ if (parsed.BoundProfile is { } profile && staticAuthoring?.EquationCurves is { Count: > 0 } curves)
+ parsed = parsed with { BoundProfile = EquationCurveAuthoring.RestoreProvenance(profile, curves) };
if (parsed.Document is null) return parsed;
var threads = ParseCanonicalThreads(source, diagnostics);
if (threads is null)
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs
index 29a12ef0..d754cab2 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs
@@ -122,6 +122,11 @@ internal sealed class FirmamentDataBinding
headers[d] = header;
if (d.Body is null) continue;
var body = new Scope(header, scope.Identity + "/" + label + "#" + ordinal);
+ // The curve parameter is a lexical Float local, like a Function
+ // parameter. An unrelated Static cannot capture its declaration or uses.
+ if (d.Type.Name.Text is "Curve2" or "Curve3"
+ && d.Body.Statements.OfType<FieldSyntax>().FirstOrDefault(f => f.Name.Text.Equals("parameter", StringComparison.OrdinalIgnoreCase))?.Value is ReferenceSyntax parameter)
+ body.Values.Add(parameter.Name.Text);
scopeSpans.Add((d.Body.ContentSpan, body));
Collect(d.Body.Statements, body);
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericCurveAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericCurveAnalysis.cs
new file mode 100644
index 00000000..81ba5f45
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericCurveAnalysis.cs
@@ -0,0 +1,151 @@
+namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+internal static partial class FirmamentNumericEvaluation
+{
+ /// <summary>Coefficient proof, not interpolation. Only degree <= 3 polynomials
+ /// are admitted here; numeric constants use the ordinary scalar evaluator.</summary>
+ internal static bool TryPolynomial(ExpressionSyntax expression, string parameter, out double[] coefficients)
+ {
+ double[]? Visit(ExpressionSyntax e, int depth)
+ {
+ if (depth > 128) return null;
+ if (e is ReferenceSyntax r && r.Name.Text == parameter) return [0, 1, 0, 0];
+ if (!FirmamentSyntaxTraversal.Expressions(e).OfType<ReferenceSyntax>().Any(r => r.Name.Text == parameter)
+ && TryEvaluate(e, out var constant)) return [constant.Number, 0, 0, 0];
+ if (e is QuantitySyntax q) return Visit(q.Value, depth + 1);
+ if (e is SequenceSyntax { Kind: SequenceKind.Tuple, Items.Count: 1 } g) return Visit(g.Items[0].Value, depth + 1);
+ if (e is UnarySyntax { Operator: UnaryOperator.Positive or UnaryOperator.Negative } u && Visit(u.Operand, depth + 1) is { } v)
+ return u.Operator == UnaryOperator.Positive ? v : v.Select(x => -x).ToArray();
+ if (e is CallSyntax { Target: ReferenceSyntax { Name.Text: "Pow" }, Arguments.Count: 2 } power
+ && TryEvaluate(power.Arguments[1].Value, out var exponent) && exponent.Unit == "" && exponent.Number is >= 0 and <= 3 && exponent.Number == Math.Truncate(exponent.Number))
+ {
+ var basis = Visit(power.Arguments[0].Value, depth + 1); if (basis is null) return null;
+ double[]? result = [1, 0, 0, 0];
+ for (var i = 0; i < exponent.Number && result is not null; i++) result = Product(result, basis);
+ return result;
+ }
+ if (e is not BinarySyntax b || Visit(b.Left, depth + 1) is not { } left || Visit(b.Right, depth + 1) is not { } right) return null;
+ return b.Operator switch
+ {
+ BinaryOperator.Add => left.Zip(right, (x, y) => x + y).ToArray(),
+ BinaryOperator.Subtract => left.Zip(right, (x, y) => x - y).ToArray(),
+ BinaryOperator.Multiply => Product(left, right),
+ BinaryOperator.Divide when right[0] != 0 && right.Skip(1).All(x => x == 0) => left.Select(x => x / right[0]).ToArray(),
+ _ => null
+ };
+ }
+ static double[]? Product(double[] a, double[] b)
+ {
+ var c = new double[7]; for (var i = 0; i < 4; i++) for (var j = 0; j < 4; j++) c[i + j] += a[i] * b[j];
+ return c.Skip(4).Any(x => x != 0) ? null : c.Take(4).ToArray();
+ }
+ coefficients = Visit(expression, 0) ?? [];
+ return coefficients.Length == 4 && coefficients.All(double.IsFinite);
+ }
+
+ // Outward-rounded interval jets enclose the whole parameter interval, including
+ // derivatives. No sampled residual is promoted to a geometric error bound.
+ private readonly record struct Interval(double Lo, double Hi)
+ {
+ internal static Interval Point(double x) => new(x, x);
+ internal double Magnitude => Math.Max(Math.Abs(Lo), Math.Abs(Hi));
+ public static Interval operator +(Interval a, Interval b) => new(Math.BitDecrement(a.Lo + b.Lo), Math.BitIncrement(a.Hi + b.Hi));
+ public static Interval operator -(Interval a) => new(-a.Hi, -a.Lo);
+ public static Interval operator -(Interval a, Interval b) => a + -b;
+ public static Interval operator *(Interval a, Interval b)
+ {
+ double[] p = [a.Lo * b.Lo, a.Lo * b.Hi, a.Hi * b.Lo, a.Hi * b.Hi];
+ return new(Math.BitDecrement(p.Min()), Math.BitIncrement(p.Max()));
+ }
+ internal Interval Inverse() => Lo <= 0 && Hi >= 0 ? throw new FormatException() : new(Math.BitDecrement(1 / Hi), Math.BitIncrement(1 / Lo));
+ internal Interval Trig(bool cosine)
+ {
+ // Enclose range reduction and the Taylor polynomial with directed
+ // arithmetic, rather than assuming Math.Sin is correctly rounded.
+ if (!double.IsFinite(Lo) || !double.IsFinite(Hi) || Hi - Lo >= 2 * Math.PI || Magnitude > 1e6) return new(-1, 1);
+ var turns = Math.Round((Lo / 2 + Hi / 2) / (2 * Math.PI));
+ var pi = new Interval(Math.BitDecrement(Math.PI), Math.BitIncrement(Math.PI));
+ var x = this - pi * Point(2 * turns);
+ if (x.Magnitude > 4) return new(-1, 1);
+ var square = x * x;
+ var term = cosine ? Point(1) : x;
+ var sum = term;
+ for (var k = 1; k <= 24; k++)
+ {
+ var denominator = cosine ? (2 * k - 1) * (2 * k) : (2 * k) * (2 * k + 1);
+ term = -term * square * Point(denominator).Inverse(); sum += term;
+ }
+ // |x| <= 4; the first omitted Taylor term is below 1e-34.
+ return new(Math.Max(-1, Math.BitDecrement(sum.Lo - 1e-34)), Math.Min(1, Math.BitIncrement(sum.Hi + 1e-34)));
+ }
+ }
+ private readonly record struct Jet(Interval Value, Interval First, Interval Second)
+ {
+ internal static Jet Constant(double x) => new(Interval.Point(x), Interval.Point(0), Interval.Point(0));
+ public static Jet operator +(Jet a, Jet b) => new(a.Value + b.Value, a.First + b.First, a.Second + b.Second);
+ public static Jet operator -(Jet a) => new(-a.Value, -a.First, -a.Second);
+ public static Jet operator *(Jet a, Jet b) => new(a.Value * b.Value, a.First * b.Value + a.Value * b.First,
+ a.Second * b.Value + Interval.Point(2) * a.First * b.First + a.Value * b.Second);
+ internal Jet Inverse()
+ {
+ var inv = Value.Inverse();
+ return new(inv, -First * inv * inv, Interval.Point(2) * First * First * inv * inv * inv - Second * inv * inv);
+ }
+ }
+ internal static bool TrySecondDerivativeBound(ExpressionSyntax expression, string parameter, double start, double end, out double bound)
+ {
+ var success = TryCurveJet(expression, parameter, start, end, out var jet);
+ bound = jet.Second.Magnitude;
+ return success && double.IsFinite(bound);
+ }
+ internal static bool TryCurveEvaluationError(ExpressionSyntax expression, string parameter, double t, double evaluated, out double error)
+ {
+ var success = TryCurveJet(expression, parameter, t, t, out var jet);
+ error = Math.Max(Math.Abs(evaluated - jet.Value.Lo), Math.Abs(evaluated - jet.Value.Hi));
+ return success && double.IsFinite(error);
+ }
+ private static bool TryCurveJet(ExpressionSyntax expression, string parameter, double start, double end, out Jet jet)
+ {
+ Jet Visit(ExpressionSyntax e, int depth)
+ {
+ if (depth > 128) throw new FormatException();
+ if (e is ReferenceSyntax r && r.Name.Text == parameter) return new(new(start, end), Interval.Point(1), Interval.Point(0));
+ if (!FirmamentSyntaxTraversal.Expressions(e).OfType<ReferenceSyntax>().Any(r => r.Name.Text == parameter)
+ && TryEvaluate(e, out var constant)) return Jet.Constant(constant.Number);
+ if (e is QuantitySyntax q) return Visit(q.Value, depth + 1);
+ if (e is SequenceSyntax { Kind: SequenceKind.Tuple, Items.Count: 1 } g) return Visit(g.Items[0].Value, depth + 1);
+ if (e is UnarySyntax { Operator: UnaryOperator.Positive or UnaryOperator.Negative } u) return u.Operator == UnaryOperator.Positive ? Visit(u.Operand, depth + 1) : -Visit(u.Operand, depth + 1);
+ if (e is BinarySyntax b)
+ {
+ var a = Visit(b.Left, depth + 1); var v = Visit(b.Right, depth + 1);
+ return b.Operator switch { BinaryOperator.Add => a + v, BinaryOperator.Subtract => a + -v,
+ BinaryOperator.Multiply => a * v, BinaryOperator.Divide => a * v.Inverse(), _ => throw new FormatException() };
+ }
+ if (e is CallSyntax { Target: ReferenceSyntax t } call)
+ {
+ if (t.Name.Text is "Sin" or "Cos" && call.Arguments.Count == 1)
+ {
+ var arg = call.Arguments[0].Value;
+ if (!TryEvaluate(arg, out var type, new Dictionary<string, Value> { [parameter] = new(1, "") }, typeOnly: true)) throw new FormatException();
+ var a = Visit(arg, depth + 1);
+ if (type.Unit == "deg") a *= Jet.Constant(Math.PI / 180);
+ // Global [-1,1] enclosures avoid missed extrema and huge-angle
+ // argument reduction assumptions. Refinement still shrinks h².
+ var sin = a.Value.Trig(false); var cos = a.Value.Trig(true);
+ return t.Name.Text == "Sin" ? new(sin, cos * a.First, -sin * a.First * a.First + cos * a.Second)
+ : new(cos, -sin * a.First, -cos * a.First * a.First - sin * a.Second);
+ }
+ if (t.Name.Text == "Pow" && call.Arguments.Count == 2 && TryEvaluate(call.Arguments[1].Value, out var exponent)
+ && exponent.Unit == "" && exponent.Number == Math.Truncate(exponent.Number) && Math.Abs(exponent.Number) <= 8)
+ {
+ var a = Visit(call.Arguments[0].Value, depth + 1); var result = Jet.Constant(1);
+ for (var i = 0; i < Math.Abs(exponent.Number); i++) result *= a;
+ return exponent.Number < 0 ? result.Inverse() : result;
+ }
+ }
+ throw new FormatException();
+ }
+ try { jet = Visit(expression, 0); return true; }
+ catch (FormatException) { jet = default; return false; }
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericEvaluation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericEvaluation.cs
index 37e395bb..6d4fe258 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericEvaluation.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentNumericEvaluation.cs
@@ -4,7 +4,7 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
/// <summary>Finite numeric evaluation over the shared expression grammar. Domain callers
/// supply their expected unit and, where admitted, bounded intrinsic functions.</summary>
-internal static class FirmamentNumericEvaluation
+internal static partial class FirmamentNumericEvaluation
{
internal readonly record struct Value(double Number, string Unit);
@@ -60,6 +60,13 @@ internal static class FirmamentNumericEvaluation
}
if (target.Name.Text == "Pow" && args.Count == 2 && args.All(a => a.Unit.Length == 0))
result = new(typeOnly ? 1 : Math.Pow(args[0].Number, args[1].Number), "");
+ else if (target.Name.Text is "Sin" or "Cos" && args.Count == 1 && args[0].Unit is "" or "rad" or "deg")
+ {
+ // Bare numbers and explicit rad quantities are radians. An Angle
+ // retains its authored unit until this intrinsic consumes it.
+ var radians = args[0].Unit == "deg" ? args[0].Number * Math.PI / 180 : args[0].Number;
+ result = new(typeOnly ? 1 : target.Name.Text == "Sin" ? Math.Sin(radians) : Math.Cos(radians), "");
+ }
else if (functions is not null) result = functions(target.Name.Text, args);
else return false;
return (result.Unit is "" or "mm" or "deg" or "rad" or "s" or "ms") && (typeOnly || double.IsFinite(result.Number));
diff --git a/docs/public/firmament/authoring-composition-proposal.md b/docs/public/firmament/authoring-composition-proposal.md
index 034cb0d2..7980ae3a 100644
--- a/docs/public/firmament/authoring-composition-proposal.md
+++ b/docs/public/firmament/authoring-composition-proposal.md
@@ -30,7 +30,7 @@ source-level capability has not shipped.
| 5. Profile/section families | **Addressed for the guitar** | Generic Profile outputs with local-guide hygiene, keyed Section Patterns, inline Concept frames, periodic boundary derivatives. Body and flat neck recipes are now source-owned. | Higher-order Profile arguments and general InterpolatingLoop2 remain outside this slice. |
| 6. Straight/fair surfacing intent | **Partial: witness fixed, language contract open** | Approved flat-ish neck, isolated heel stations, existing G1 SectionChain path and side-profile regression checks. | No explicit per-transition Law/endpoint tangent authoring or declarative StraightBack envelope contract. The present fix is an authored station recipe, not a new global straightness proof. |
| 7. Non-planar attachment | **Partial; datum-first model clarified** | Concept planes derive from published physical construction frames with offset/clocking; consumers seat on that scaffold. The guitar deck no longer needs an independent bridge-height guess. | Tangent-frame evaluation on analytic/SectionChain surfaces, explicit location/trim/seam rules and curved-base footprint support are not implemented by frame derivation alone. |
-| 8. Engineering expressions and finite sites | **Addressed, bounded** | Pure scalar Function arithmetic and Pow, equation-driven 22-fret series, keyed nut crossings, explicit linear inlay stations, ordinary Linear/Mirrored component sites. | Angle trigonometry, typed vector/frame operations, geometry-valued arguments/results and equation-defined curves remain bounded follow-ons. Functions already run during compilation; no Comptime keyword is needed. |
+| 8. Engineering expressions and finite sites | **Addressed, bounded** | Pure scalar Function arithmetic and Pow, equation-driven 22-fret series, keyed nut crossings, explicit linear inlay stations, ordinary Linear/Mirrored component sites. | Typed Sin/Cos, point/Record Function results and bounded equation-defined Curve2/Curve3 are now admitted; see equation-curves.md. Typed vector/frame operations and general curve sweeps remain follow-ons. Functions already run during compilation; no Comptime keyword is needed. |
| 9. Point-driven WireForm | **Addressed, bounded** | Six strings bind final public tailpiece/nut/tuner frames; typed Point3 specialization and placement-aware cache inputs. First finite Concept Line3 Follow guide lowers to exact WireForm. | Fixed assemblies only; tangent exits. Exact Via, multiple corners, circular/spline guides, route outputs and obstacle search remain deferred. |
| 10. Semantic appearance binding | **Addressed, bounded** | Physical Material owns its default Appearance; occurrence with overrides the finish. USD and Cycles consume authored identities. Look-only edits reuse exact geometry. | Physical aliases do not certify engineering properties; procedural sunburst/pearl and pickup shading remain downstream. |
| 11. Unified compilation and diagnostics | **Addressed front door; deeper tooling partial** | Root-aware build/inspect delegates to existing owners; repeat inspection exposes cache reasons/timings. Section keys, bound endpoint provenance, new schema fields and snapshot cross-file navigation are covered. | Aggregate project diagnostic locations, full generated-span mapping, every draft grammar and client integration remain follow-ons. |
diff --git a/docs/public/firmament/concept-points-and-functions.md b/docs/public/firmament/concept-points-and-functions.md
index 52bc584c..792de785 100644
--- a/docs/public/firmament/concept-points-and-functions.md
+++ b/docs/public/firmament/concept-points-and-functions.md
@@ -1,7 +1,7 @@
# Concept points and Functions
Implemented: keyed local `Points<Point2>` / `Points<Point3>` collections and pure,
-expression-bodied scalar `Function` declarations. Functions always evaluate
+expression-bodied typed `Function` declarations. Functions always evaluate
during compilation. There is no `Comptime` keyword or runtime execution.
## Nut crossings
@@ -172,11 +172,11 @@ Patterns preserve the logical collection name in expanded associations.
## Compilation contract
- Functions have unique names in the compiled source catalog, at most 16
- parameters each, and `Int`, `Float`, `Length` or `Angle` arguments/results.
+ parameters each, and `Int`, `Float`, `Length`, `Angle`, `Point2`, `Point3` or declared Record arguments/results.
Calls use positional arguments. Forward calls are permitted; recursive
dependency cycles are rejected.
- Expressions admit literals, parameters, parentheses, unary signs, arithmetic,
- other declared Functions, and dimensionless `Pow(base,exponent)`.
+ other declared Functions, dimensionless `Pow(base,exponent)`, and `Sin`/`Cos` with bare radians or explicit deg/rad angles.
Division is real division, including when both operands are integral.
- Lengths use `mm`, angles use `deg`. Addition/subtraction require matching
dimensions. Multiplication admits at most one dimensional operand. Dividing
@@ -187,7 +187,7 @@ Patterns preserve the logical collection name in expanded associations.
Linear keys are unique identifiers, and the step must be nonzero. Series
indices are nonnegative with checked integer bounds.
- Function catalogs have at most 128 declarations. Evaluation limits are
- 32 active Function calls, 10000 calls per scalar evaluation, 8192 characters
+ 32 active Function calls, 10000 AST binding work items per evaluation, 8192 characters
per scalar expression and 128 nested scalar atoms. Non-finite results fail.
- There are no loops, mutation, recursion, I/O, reflection, host C# callbacks
or arbitrary source evaluation. New errors use `firmament-concept-points-*`;
@@ -223,8 +223,10 @@ Generated evidence lives under ignored `artifacts/local/concept-points/`:
focused test TRX/logs and full-suite logs. The reusable qualification fixture is
`fixtures/Canonical/AssemblyInterfaces/AuthoringFoundation/concept-points.firmament`.
-Equation-driven profile curves, point-driven WireForm routing, scalar record
-parameters, closures and a general collection programming language are deferred.
+Equation-driven curves and typed point/Record Function results are described in
+[equation-driven curves](equation-curves.md). Point-driven WireForm routing is
+covered by [point wire routes](wire-point-routes.md). Closures and a general
+collection programming language remain deferred.
Final qualification: Release solution build passed; 32 focused authoring/guitar
tests passed; the fast kernel lane passed 1004 tests; the serial full solution
diff --git a/docs/public/firmament/equation-curves.md b/docs/public/firmament/equation-curves.md
new file mode 100644
index 00000000..b4258a2d
--- /dev/null
+++ b/docs/public/firmament/equation-curves.md
@@ -0,0 +1,135 @@
+# Equation-driven curves
+
+A Function defines a pure mathematical relationship. Curve2 or Curve3 binds that
+relationship to a finite parameter interval and a geometric representation.
+Neither declaration creates material. Profiles and other admitted consumers own
+material construction. There is no separate Equation keyword or implicit solver.
+
+## Reusable typed Functions
+
+Functions can return scalars, Point2, Point3 or a declared Record. Parameters can
+use the same types. Records must be composed from these supported scalar/point/Record types. Record fields come from the ordinary Record schema; a result
+must supply every field once, with no unknown fields. Functions use explicit
+arguments, not implicit capture of surrounding Statics. Dependencies must be
+acyclic. Record and point member access works on Function results.
+
+```firmament
+Record ArchSpec { span: Length; rise: Length }
+Function Arch(t: Float, p: ArchSpec) -> Point2 =
+ Point2(p.span * t, 4 * p.rise * t * (1 - t));
+```
+
+A Record result can bundle a point and related dimensions. This is explicit
+computation, not a simultaneous system of constraints. Scalar, point and Record
+results use the existing Function binder and shared numeric expression evaluator.
+Manufacturing tolerances cannot be silently erased into equation coordinates.
+
+## Trigonometric units
+
+`Sin` and `Cos` return dimensionless Float values. A bare number means radians;
+`rad` explicitly means radians; `deg` explicitly means degrees:
+
+```firmament
+Function RadianCos(x: Float) -> Float = Cos(x);
+Function AngleCos(a: Angle) -> Float = Cos(a);
+// Cos(3.141592653589793), Cos(3.141592653589793rad),
+// and Cos(180deg) evaluate to -1 within floating-point precision.
+```
+
+Lengths are invalid trigonometric arguments. No conversion is guessed from the
+magnitude of the number. Sin/Cos are shared scalar intrinsics, not curve-only math.
+
+## An exact planar arch
+
+The complete [arch fixture](../../../fixtures/Canonical/EquationCurves/arch.firmament)
+contains a curved crown, an explicit straight baseline, a Profile and an Extrude.
+Its defining declarations are:
+
+```firmament
+Function Arch(t: Float, span: Length, rise: Length) -> Point2 =
+ Point2(span * t, 4 * rise * t * (1 - t));
+
+// Inside Concept Struct Layout:
+Curve2 Crown {
+ parameter: t;
+ domain: [0, 1];
+ from: Arch(t, 80mm, 20mm);
+ on: XZ;
+ representation: Exact;
+}
+```
+
+Use qualified references such as `Layout.Crown` in Profile pipelines. An equation
+curve carries local Length coordinates and its explicit plane. A consuming
+Profile without a placement inherits the common curve plane. An explicitly
+placed Profile must agree with it. Mixing planes fails. XY, XZ, YZ and named
+Concept planes are supported. Curve2 results remain Point2; querying one never
+silently lifts it into Point3.
+
+A pipeline can trace open equation curves alongside other named guides.
+`Close` checks that the declared segments close; it does not add a missing edge.
+`TraceLoop` requires an explicitly closed equation chain or a recognized full
+circle/ellipse. `Reverse` reverses an open chain. Complete circles/ellipses use `TraceLoop`;
+open conic trimming is a separate consumer capability.
+
+## Spatial laws and parameter queries
+
+```firmament
+Function Helix(t: Float, radius: Length, pitch: Length) -> Point3 =
+ Point3(radius * Cos(t * 360deg), radius * Sin(t * 360deg), pitch * t);
+
+// Inside a plain Concept Struct Layout:
+Curve3 Coil {
+ parameter: t;
+ domain: [0, 2];
+ from: Helix(t, 12mm, 8mm);
+ on: World;
+ representation: Approximate;
+ maxDeviation: 0.01mm;
+}
+```
+
+`Layout.Coil.At(1)` returns the equation's Point3 at parameter 1, not a point
+interpolated from its approximating polyline. `.X`, `.Y` and `.Z` can project
+coordinates. Calls outside the declared domain fail; no clamping or wrapping
+occurs. Calls work in keyed Points/Series recipes and ordinary geometry inputs.
+The [helix fixture](../../../fixtures/Canonical/EquationCurves/helix.firmament)
+uses its keyed turn heights to drive a real Box dimension.
+
+The parameter is dimensionless and is not arc length. Equal parameter increments
+do not promise equal physical spacing. Curve3 currently uses World in the owning
+definition's coordinates; assembly occurrence placement remains separate. Other
+Curve3 frames reject explicitly. General spatial curve sweeps are not admitted by
+this change: existing WireRoute/SectionChain capabilities remain their owners.
+
+## Exactness and approximation
+
+`Exact` is the default and rejects `maxDeviation`. Admitted exact laws are
+polynomials of degree at most three, lowered by coefficient proof to lines/cubic
+Bezier geometry, and recognized axis-aligned full circles/ellipses in Curve2.
+Conic recognition requires matching affine Sin/Cos arguments over exactly one
+turn and positive radii. Other exact requests fail with an explanation.
+
+`Approximate` requires a positive Length `maxDeviation`. The first representation
+is a polyline. Whole-interval derivative bounds establish its geometric deviation;
+endpoint evaluation uncertainty is included. Sampling alone does not establish
+that bound. Unsupported analysis, singularities, non-finite results or exhausted
+budgets reject the declaration. This is a representation error budget, not a
+manufacturing tolerance, and is not projected as PMI.
+
+`closed: true` requires coincident endpoints and inserts no segment. `periodic:
+true` additionally requires matching first derivatives; the initial periodicity
+proof admits polynomial laws and recognized exact full conics. More general
+periodicity requests reject. No higher-order smoothness is implied.
+
+Compilation is bounded to 128 equation curves and 24 approximation subdivision
+levels. Approximation uses a 4,096-segment admission budget, including segments
+already admitted from preceding curves. Existing Function expression/work/dependency
+limits also apply. Approximation supports arithmetic, Sin/Cos and bounded integer
+Pow exponents; other evaluable scalar laws can still be rejected when a geometric
+error bound cannot be established.
+
+`aetheris inspect file.firmament --json` reports `equationCurves`, including stable
+names, original declaration spans, authored equations, parameter domains, frames,
+representation, local segment data and error bounds. Exact BRep export of a
+polyline approximant does not make that polyline an exact equation curve.
diff --git a/docs/public/firmament/profile-boundary-edits.md b/docs/public/firmament/profile-boundary-edits.md
index 1edc0a0a..f0ebce2f 100644
--- a/docs/public/firmament/profile-boundary-edits.md
+++ b/docs/public/firmament/profile-boundary-edits.md
@@ -210,29 +210,15 @@ final-full.log, final-carve-inspection.json, carve-parity.json, timings.json,
mesh-check.json, step-reimport.json, guitar.step, guitar.usda, beauty/hero.png,
isometric/shaded-isometric.png and their saved Blender scenes/render reports.
-## Future equation-driven curves
-
-Curve construction has a typed internal payload seam. A future bounded Equation
-payload can produce the same resolved curves as Through/Hermite without adding
-an executable callback to Profile or a runtime dependency to exported geometry.
-No Equation syntax or C# evaluation is implemented here; such requests fail.
-
-The intended extension is compile-time only: a declared parameter interval,
-Length-valued 2D result, pure arithmetic and approved math intrinsics, bounded
-evaluation/approximation work, and explicit dependencies for cache identity.
-If lowering to C#, validate the restricted program before compilation. No I/O,
-reflection, arbitrary CLR calls, dynamic code loading, mutable static state,
-async work, recursion or unbounded loops. Do not treat running arbitrary C# as
-a purity check.
-
-Recognized polynomial/analytic laws should preserve exact representations.
-Other equations need an explicit approximation tolerance, admitted representation
-and reported error bound before they can be materialized. Exact BRep geometry of
-an approximant must not be reported as an exact representation of the equation.
-After equation binding, the ordinary boundary-edit validity checks still apply.
-See the [larger design proposal](programmable-profile-loops-proposal.md) for
-deferred periodic intervals, Curve2 payloads and inner loops. Profile-valued
-Features are supported by the current [garment authoring workflow](garments.md).
+## Equation-driven construction curves
+
+[Equation-driven Curve2/Curve3](equation-curves.md) now use typed pure Functions,
+explicit parameter intervals and exact or bounded approximate representations.
+Curve2 can feed ordinary Profile pipelines. These declarations do not introduce
+host C# callbacks or runtime dependencies in exported geometry. Profile closure,
+winding and material validity checks remain with the existing geometry owners.
+Direct equation payloads inside boundary Replace operations remain a separate
+consumer extension; use the admitted Profile pipeline path today.
## Owl authoring update
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index b4048e34..569fe676 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -751,6 +751,27 @@ definition does not grant those results new support in an unsupported consumer.
Feature-local Profile construction is also used by Garment; WireForm, Sweep and
SectionChain reject Feature declarations.
+### Functions and equation-driven curves
+
+A pure `Function` can return a scalar, `Point2`, `Point3` or a declared Record.
+Typed Record parameters/results bundle reusable inputs and related outputs.
+`Curve2`/`Curve3` bind a point-valued expression to a finite parameter domain;
+Profiles and other admitted consumers turn those construction values into material.
+See [equation-driven curves](equation-curves.md) for complete fixture links,
+representation limits, frames and parameter queries.
+
+`Sin(number)` and `Cos(number)` take radians. `Sin(angle)` and `Cos(angle)`
+respect explicit `deg`/`rad` units; their results are dimensionless. For example,
+`Cos(180deg)` and `Cos(3.141592653589793)` both evaluate to -1 within numeric
+precision. Length arguments fail.
+
+`representation: Exact` requires a supported exact lowering. `Approximate`
+requires a positive `maxDeviation` Length and reports a geometric error bound.
+This budget is separate from `tol` and PMI. `Layout.Curve.At(t)` evaluates the
+original equation within its declared domain; parameter distance is not arc length.
+Curve2 carries an explicit plane; Curve3 currently uses definition-local World.
+General spatial curve sweeping remains a separate capability.
+
### Pattern: finite repetition
A Pattern maps a finite **layout** to a construction **recipe**. Layouts can be
@@ -864,7 +885,7 @@ contents or a similarly spelled identifier. Generated instance identities still
come from the Pattern and its keys or ordered elements.
Part and assembly point recipes share checked Static/Record/Template inputs.
-Scalar Function parameters and Series indices are lexical locals; same-named
+Function parameters, curve parameters and Series indices are lexical locals; same-named
Statics do not replace them. Functions use explicit arguments rather than
implicit global capture. Layout evaluation rejects unsupported tolerance
consumption instead of erasing tolerance metadata. Local Points recipe owners
diff --git a/docs/release/EQUATION-CURVES-2026-10-20.md b/docs/release/EQUATION-CURVES-2026-10-20.md
new file mode 100644
index 00000000..6fe28f30
--- /dev/null
+++ b/docs/release/EQUATION-CURVES-2026-10-20.md
@@ -0,0 +1,134 @@
+# Equation-driven curves — typed Function foundation
+
+## Outcome and language decisions
+
+The implementation extends the existing pure Function binder. No Equation alias,
+second expression interpreter, whole-document parser route, host-code evaluator
+or geometry solver was introduced. Functions admit Point2/Point3 and typed Record
+inputs/results alongside their existing scalar types. Record schemas remain owned
+by the existing compile-time value catalog. Curve2/Curve3 bind typed point laws to
+finite dimensionless parameter domains.
+
+Bare Sin/Cos arguments are radians. Explicit rad arguments are radians and explicit
+deg arguments are degrees. Lengths reject. The shared numeric evaluator owns these
+intrinsics; curve and Pattern mathematics use the same semantics.
+
+Curve2 owns its construction plane. A Profile with no explicit placement inherits
+the shared plane of its equation curves; conflicting explicit/mixed planes reject.
+Curve3 currently uses definition-local World. At(t) evaluates the original point
+law, checks the declared interval and retains Point2/Point3 dimensionality. It does
+not query the tessellation or silently reinterpret t as arc length.
+
+## Geometry admission
+
+Exact polynomial lowering uses coefficients, not a fitted sample cloud, for degree
+at most three. Supported full circles/ellipses are recognized structurally from
+matching affine Sin/Cos phases and rates. A nearly complete turn is not silently
+closed under an epsilon comparison. Other Exact requests reject explicitly.
+
+Approximate requires maxDeviation in Length units. Its first native representation
+is a polyline. Outward-rounded interval jets enclose derivatives over each complete
+subinterval; the chord-error bound includes endpoint evaluation uncertainty.
+Trigonometric endpoint enclosures include range-reduction and Taylor remainders.
+Independent interior samples test the established bound, but do not establish it.
+Failure to bound a law, singularity, non-finite geometry or budget exhaustion is an
+error, never a partially emitted curve.
+
+Bounds: 128 curves, a shared 4096-segment approximation budget, 24 subdivision levels,
+existing expression/dependency limits and 10000 AST binding work items per
+Function/point evaluation. Manufacturing tolerance is not a representation budget;
+unsupported tolerance consumption fails instead of erasing the requirement.
+
+closed requires endpoint agreement and inserts no segment. periodic additionally
+requires first-derivative agreement, initially proved for polynomials and recognized
+exact full conics. Open curves and explicit baseline geometry remain distinct.
+The ordinary Close pipeline checks closure; it does not draw a missing chord.
+
+## Ownership, identity and provenance
+
+ConceptFunctionBinding performs typed AST argument substitution and record/point
+projection. FirmamentNumericEvaluation remains scalar arithmetic/unit authority;
+its curve analysis adds coefficient and interval derivative proofs. The curve owner
+locally lowers checked Curve2 nodes to existing construction guides and Profile
+pipelines. Existing profile validity, extrusion, topology and STEP owners remain
+responsible for engineering construction.
+
+Stable curve identities derive from named Concept members. Generated guide names
+are deterministic and collision-checked. Inspection retains domains, frames,
+equations, representation, source declaration spans, local segments, error bounds
+and the generated-guide correspondence. The ordinary bound Profile path restores
+curve source provenance on its resolved segments. Keyed At(t) samples retain the
+existing Points/Pattern identity model.
+
+CLI inspect --json exposes equationCurves. New binding errors use the existing
+structured compile-time diagnostic chain, including original span mapping.
+An invalid ellipse open-chain consumer initially exposed an exception in the older
+profile owner; local curve admission now rejects it with a TraceLoop suggestion.
+That failure remains covered by a regression test. The quality pass also reproduced
+and closed Record/Point constructor projection bypasses: all fields/coordinates
+must be admitted before member projection. Scalar Function normalization rejects
+typed tolerance inputs instead of stripping their requirements. Curve parameters
+shadow unrelated ordinary, tolerated and Record Statics.
+
+## Qualification
+
+Final evidence is under ignored artifacts/local/equation-*.log and
+artifacts/local/equation-curves/. The final qualification uses the completed logs from the frozen implementation.
+Earlier runs were interrupted while additional invalid-input defects were repaired;
+those partial runs are not counted as full-suite evidence.
+
+- Release solution build: passed.
+- Focused Function/curve/point/Pattern checks: 86 passed.
+- Fast kernel lane: 1087 passed.
+- Full serial solution gate: 5808 passed across 20 projects, zero failures/skips.
+- CLI: 5 complete equation fixtures pass validate/build/inspect and export STEP; additional XZ and spaced-degree controls pass. All 38 preexisting Pattern specimens retain admission (28 admitted, 10 rejected), with validate/build/export agreement. All 56 frozen guitar leaf STEP hashes and 99 material occurrence identities/transforms are unchanged.
+
+The exact arch is built in XY and XZ, exported and reimported through STEP. Tests
+sample actual imported B-spline edges at their midpoints: X=40 mm, crown height
+20 mm, with extrusion bounds Z=0..5 mm in XY or Y=-5..0 mm in XZ. They also check
+closed/oriented topology and exact nominal profile area. The typed Record arch
+retains the same curve controls. The sine arch exercises a materialized bounded
+approximation; the spatial helix exercises keyed original-equation queries driving
+an 8 mm physical Box dimension. Circle/ellipse tests retain analytic geometry.
+
+The existing generic STEP analyze boundingBox summary is based on topological
+vertices and does not establish a curved crown's tight extrema. The existing
+measure volume recognizer also does not admit this cubic-profile extrusion.
+Neither output is used as false evidence of the arch's dimensions or volume;
+qualification uses imported curve evaluation and resolved profile area instead.
+Those measurement/reporting gaps are outside this curve-language pass.
+
+## Explicit limits and follow-ons
+
+- No general Curve3 sweep, arbitrary frame consumer, arc-length inversion or
+ automatic material creation is implied by declaring a spatial curve.
+- Exact lowering is bounded; general analytic recognition, partial conic trimming,
+ arbitrary polynomial degree and a universal transcendental exporter are absent.
+- Approximation admits arithmetic, Sin/Cos and bounded integer Pow exponents.
+ Other scalar expressions may evaluate at a point yet lack an admitted curve bound.
+- General periodicity, higher-order continuity contracts, derivative query APIs,
+ implicit equation solving and general-purpose collection execution remain absent.
+- New Function result shapes do not grant every legacy Static/Template initializer
+ a new consumer. The qualified path is typed Function composition into curves,
+ Points/Series and supported direct geometry expressions.
+- UI curve authoring and visualization controls were not expanded in this pass.
+
+Public authoring documentation: [equation curves](../public/firmament/equation-curves.md)
+and [syntax](../public/firmament/syntax.md). Complete authored sources are in
+fixtures/Canonical/EquationCurves; negative and cross-route checks are in
+EquationCurveTests. No user decision is required for the bounded implementation.
+
+## Code-quality closeout and verdict
+
+The modified owners were checked for duplicate evaluators/schemas, hidden parser
+fallback, global mutable compilation state, unconsumed constructor fields and
+unit/tolerance erasure. No new regex, document-dispatch route, host-code execution
+or fatality allowlist was added. Record schemas and numeric units remain with their
+existing owners. Documentation links and git diff --check pass. Final test hosts,
+MSBuild hosts and compiler servers have exited; no task-owned runtime host remains.
+
+**Success.** Typed reusable laws drive real planar material and spatial keyed
+geometry inputs through the normal compiler. Exact and approximate representations
+are explicit, malformed intent fails, existing corpus admission remains consistent,
+and the frozen engineering geometry control is unchanged. The spatial sweep and
+other bounded consumer limits above remain explicit rather than implied support.
diff --git a/fixtures/Canonical/EquationCurves/README.md b/fixtures/Canonical/EquationCurves/README.md
new file mode 100644
index 00000000..e390b45b
--- /dev/null
+++ b/fixtures/Canonical/EquationCurves/README.md
@@ -0,0 +1,21 @@
+# Equation curve qualification sources
+
+These are complete buildable Firmament files. Public authoring documentation is
+in docs/public/firmament/equation-curves.md.
+
+- arch: degree-two point law, exact cubic representation, explicit baseline and
+ 5 mm extrusion. Nominal profile area is 1066.6666666666667 mm². The test also
+ builds its XZ variant and samples the reimported STEP crown at world height 20 mm.
+- record-arch: the same geometry with ordinary typed Record inputs.
+- circle: recognized exact full circle, periodic contract, radius 10 mm.
+- sine-arch: explicitly approximated sine crown, 0.05 mm maximum deviation,
+ exact straight baseline and ordinary profile extrusion.
+- helix: spatial construction curve with a 0.01 mm approximation budget. Keyed
+ turn samples evaluate the original equation and drive an 8 mm Box height.
+ This is a guide/layout witness, not a swept helical solid.
+
+EquationCurveTests also cover radians/degrees, typed Record results, domain and
+frame rejection, singularities, tolerance retention, unknown fields, and explicit
+conic loop consumption. Approximation evidence checks the whole-interval bound
+and independent intermediate samples. Geometry acceptance includes STEP reimport
+and enclosed/oriented topology for the arch in XY and XZ.
diff --git a/fixtures/Canonical/EquationCurves/arch.firmament b/fixtures/Canonical/EquationCurves/arch.firmament
new file mode 100644
index 00000000..9fd3dd65
--- /dev/null
+++ b/fixtures/Canonical/EquationCurves/arch.firmament
@@ -0,0 +1,23 @@
+Function Arch(t: Float, span: Length, rise: Length) -> Point2 =
+ Point2(span * t, 4 * rise * t * (1 - t));
+Model ArchPlate {
+ Units: mm
+ Concept Struct Layout {
+ Curve2 Crown {
+ parameter: t;
+ domain: [0, 1];
+ from: Arch(t, 80mm, 20mm);
+ on: XY;
+ representation: Exact;
+ }
+ Curve2 Baseline {
+ parameter: t;
+ domain: [0, 1];
+ from: Arch(1 - t, 80mm, 0mm);
+ on: XY;
+ representation: Exact;
+ }
+ }
+ Profile Outline { Loop Outer { Reverse Layout.Crown |> Layout.Baseline |> Close } }
+ Extrude Body { profile: Outline; from: 0mm; to: 5mm }
+}
diff --git a/fixtures/Canonical/EquationCurves/circle.firmament b/fixtures/Canonical/EquationCurves/circle.firmament
new file mode 100644
index 00000000..c043e3f2
--- /dev/null
+++ b/fixtures/Canonical/EquationCurves/circle.firmament
@@ -0,0 +1,9 @@
+Function Round(t: Float, radius: Length) -> Point2 = Point2(radius * Cos(t * 360deg), radius * Sin(t * 360deg));
+Model RoundPlate {
+ Units: mm
+ Concept Struct Layout {
+ Curve2 Rim { parameter: t; domain: [0, 1]; from: Round(t, 10mm); on: XY; representation: Exact; periodic: true; }
+ }
+ Profile Outline { Loop Outer { Layout.Rim |> TraceLoop } }
+ Extrude Body { profile: Outline; from: 0mm; to: 5mm }
+}
diff --git a/fixtures/Canonical/EquationCurves/helix.firmament b/fixtures/Canonical/EquationCurves/helix.firmament
new file mode 100644
index 00000000..0bd996f1
--- /dev/null
+++ b/fixtures/Canonical/EquationCurves/helix.firmament
@@ -0,0 +1,19 @@
+Function Helix(t: Float, radius: Length, pitch: Length) -> Point3 =
+ Point3(radius * Cos(t * 360deg), radius * Sin(t * 360deg), pitch * t);
+Model HelixStations {
+ Units: mm
+ Concept Struct Layout {
+ Curve3 Coil {
+ parameter: t;
+ domain: [0, 2];
+ from: Helix(t, 12mm, 8mm);
+ on: World;
+ representation: Approximate;
+ maxDeviation: 0.01mm;
+ }
+ Points<Point3> Stations {
+ Series { index: n; first: 0; count: 3; keyPrefix: Turn; position: Layout.Coil.At(n); }
+ }
+ }
+ Box Base { size: [20mm, 20mm, Layout.Stations.Turn1.Z] }
+}
diff --git a/fixtures/Canonical/EquationCurves/record-arch.firmament b/fixtures/Canonical/EquationCurves/record-arch.firmament
new file mode 100644
index 00000000..34e14572
--- /dev/null
+++ b/fixtures/Canonical/EquationCurves/record-arch.firmament
@@ -0,0 +1,26 @@
+Record ArchSpec { span: Length; rise: Length }
+Static Design: ArchSpec { span: 80mm; rise: 20mm }
+Static Flat: ArchSpec { span: 80mm; rise: 0mm }
+Function Arch(t: Float, p: ArchSpec) -> Point2 =
+ Point2(p.span * t, 4 * p.rise * t * (1 - t));
+Model ArchPlate {
+ Units: mm
+ Concept Struct Layout {
+ Curve2 Crown {
+ parameter: t;
+ domain: [0, 1];
+ from: Arch(t, Design);
+ on: XY;
+ representation: Exact;
+ }
+ Curve2 Baseline {
+ parameter: t;
+ domain: [0, 1];
+ from: Arch(1 - t, Flat);
+ on: XY;
+ representation: Exact;
+ }
+ }
+ Profile Outline { Loop Outer { Reverse Layout.Crown |> Layout.Baseline |> Close } }
+ Extrude Body { profile: Outline; from: 0mm; to: 5mm }
+}
diff --git a/fixtures/Canonical/EquationCurves/sine-arch.firmament b/fixtures/Canonical/EquationCurves/sine-arch.firmament
new file mode 100644
index 00000000..cf8b54b5
--- /dev/null
+++ b/fixtures/Canonical/EquationCurves/sine-arch.firmament
@@ -0,0 +1,23 @@
+Function Arch(t: Float, span: Length, rise: Length) -> Point2 =
+ Point2(span * t, rise * Sin(t * 180deg));
+Model ArchPlate {
+ Units: mm
+ Concept Struct Layout {
+ Curve2 Crown {
+ parameter: t;
+ domain: [0, 1];
+ from: Arch(t, 80mm, 20mm);
+ on: XY;
+ representation: Approximate; maxDeviation: 0.05mm;
+ }
+ Curve2 Baseline {
+ parameter: t;
+ domain: [0, 1];
+ from: Point2(80mm * (1 - t), 0mm);
+ on: XY;
+ representation: Exact;
+ }
+ }
+ Profile Outline { Loop Outer { Reverse Layout.Crown |> Layout.Baseline |> Close } }
+ Extrude Body { profile: Outline; from: 0mm; to: 5mm }
+}