Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Improve point recipe validation and diagnostics
Yuechen Li2e55e0415af2
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentPatternBindingTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentPatternBindingTests.csnew file mode 100644index 00000000..83835dba--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentPatternBindingTests.cs@@ -0,0 +1,214 @@+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentPatternBindingTests+{+ private static string Source(string name) => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(+ "fixtures/Regression/PatternAuthoringAudit/" + name + ".firmament"));++ [Fact]+ public void UnrelatedStaticCannotCaptureExpressionFunctionParameterOrMoveFrets()+ {+ var before = new AssemblyM1Pipeline().Compile(Source("function-parameter-shadow-assembly-control"));+ var after = new AssemblyM1Pipeline().Compile(Source("function-parameter-shadow-assembly"));+ Assert.True(before.IsSuccess, string.Join("\n", before.Diagnostics));+ Assert.True(after.IsSuccess, string.Join("\n", after.Diagnostics));+ var point = after.Ir!.ConceptPoints!.Single(c => c.Name == "Board.Frets").Points.Single(p => p.Key == "Fret12");+ Assert.Equal(-314, point.Coordinates[1], 10);+ foreach (var instance in before.Ir!.Instances)+ {+ var actual = after.Ir.Instances.Single(i => i.StableId == instance.StableId);+ Assert.Equal(instance.ResolvedTransform?.Matrix, actual.ResolvedTransform?.Matrix);+ }+ Assert.Equal(344, after.Ir.Instances.Single(i => i.Path.ToString() == "PointWitness.Frets.Fret12.Fret").ResolvedTransform!.Matrix[13], 10);+ Assert.Equal(before.Geometry!.DefinitionBodies.Keys, after.Geometry!.DefinitionBodies.Keys);+ }++ [Theory]+ [InlineData("series-record-inputs")]+ [InlineData("series-template-inputs")]+ [InlineData("series-count-static")]+ [InlineData("series-pitch-static")]+ [InlineData("series-pitch-static-unshadowed")]+ [InlineData("series-module-static")]+ [InlineData("series-part-count-static-module")]+ public void PartSeriesConsumesCheckedLexicalValuesAndPreservesPatternKeys(string name)+ {+ var control = FirmamentV2Parser.Parse(Source("equation-plate"));+ var actual = FirmamentV2Parser.Parse(Source(name));+ Assert.True(actual.IsSuccess, string.Join("\n", actual.Diagnostics));+ var points = Assert.Single(actual.Document!.StaticAuthoring!.ConceptPoints!);+ Assert.Equal(new[] { -30d, -25d, -10d, 15d }, points.Points.Select(p => p.Coordinates[0]));+ Assert.Equal(control.Document!.StaticAuthoring!.ConceptPoints![0].Points.Select(p => p.StableId), points.Points.Select(p => p.StableId));+ var pattern = Assert.Single(actual.Document.StaticAuthoring.Patterns);+ Assert.Equal("Layout.Sites", pattern.Source);+ Assert.All(pattern.Associations!, a => Assert.Equal("Layout.Sites", a.SourceSet));+ Assert.Equal(4, Assert.Single(actual.Document.ModifyBlocks!).SemanticHoles.Count);+ }++ [Fact]+ public void PointErrorsKeepOffendingExpressionSpanAndHumanMessage()+ {+ var source = Source("series-unknown-field");+ var view = FirmamentPatternService.Project(source, "part.firmament", "1");+ var error = Assert.Single(view.Diagnostics, d => d.Code == "firmament-concept-points-field-unknown");+ Assert.Contains("heigth", error.Message);+ Assert.NotNull(error.Span);+ Assert.StartsWith("heigth:", source.Substring(error.Span.Start, error.Span.Length));+ Assert.Equal("Unresolved", view.ValidationLevel);+ }++ [Fact]+ public void PatternProjectionResolvesIncludedFunctionsThroughProductionModuleGraph()+ {+ var complete = Source("equation-plate");+ var at = complete.IndexOf("Model EquationPlate", StringComparison.Ordinal);+ var root = "include \"laws.firmament\"\n" + complete[at..];+ var project = new FirmamentProjectSnapshot("plate.firmament", new Dictionary<string, string>+ { ["plate.firmament"] = root, ["laws.firmament"] = complete[..at] });+ var view = FirmamentPatternService.Project(root, "plate.firmament", "r1", project);+ Assert.Empty(view.Diagnostics);+ Assert.Equal(new[] { -30d, -25d, -10d, 15d }, Assert.Single(view.Layouts).Rows.Select(r => r.Coordinates![0]));+ Assert.Equal("point => Drill(center: point)", Assert.Single(view.Patterns).Body);+ }++ [Fact]+ public void SeriesCompletionDoesNotSuggestIncompatibleKeys()+ {+ var source = Source("equation-plate");+ var offset = source.IndexOf("Points<Point2> Sites {", StringComparison.Ordinal) + "Points<Point2> Sites {".Length;+ var completion = FirmamentLanguageService.Complete(source, "part.firmament", "1", offset);+ Assert.Equal("Points", completion.Context);+ Assert.Empty(completion.Fields);+ }++ [Theory]+ [InlineData("Points<Point2> Sites {", "Points<Point2> Sites on XZ {")]+ [InlineData("Series {", "Series Named {")]+ [InlineData("Series {", "Series<Length> {")]+ public void PointAstMigrationDoesNotIgnoreNewlyRecognizedHeaders(string from, string to)+ {+ var result = FirmamentV2Parser.Parse(Source("equation-plate").Replace(from, to, StringComparison.Ordinal));+ Assert.False(result.IsSuccess);+ }++ [Fact]+ public void PointCollectionOwnerFrameCannotBeErasedIntoAValidXyPattern()+ {+ var result = FirmamentV2Parser.Parse(Source("series-owner-frame-rejected"));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.SyntaxDiagnostics, d => d.Code == "firmament-concept-points-collection-owner-header-unsupported"+ && d.Message.Contains("frame", StringComparison.Ordinal));+ }++ [Fact]+ public void PointRecipesCannotEraseTypedTolerance()+ {+ var result = FirmamentV2Parser.Parse(Source("series-tolerance-input-rejected"));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.SyntaxDiagnostics, d => d.Code == "firmament-concept-points-tolerance-consumer-unsupported");+ }++ [Theory]+ [InlineData("ui-created-series", 5)]+ [InlineData("ui-created-stations", 7)]+ public void SavedBrowserPatternsRetainExistingHolesAndProduceEveryNewKey(string fixture, int count)+ {+ var baseline = FirmamentV2Parser.Parse(Source("ui-edited-law"));+ var actual = FirmamentV2Parser.Parse(Source(fixture));+ Assert.True(actual.IsSuccess, string.Join("\n", actual.Diagnostics));+ var holes = Assert.Single(actual.Document!.ModifyBlocks!).SemanticHoles;+ Assert.Equal(count, holes.Count);+ foreach (var original in Assert.Single(baseline.Document!.ModifyBlocks!).SemanticHoles)+ {+ var hole = holes.Single(h => h.Name == original.Name);+ Assert.Equal(original.Center, hole.Center);+ Assert.Equal(original.ShaftDiameter, hole.ShaftDiameter);+ }+ Assert.Equal(count, actual.Document.StaticAuthoring!.Patterns.Sum(p => p.GeneratedCount));+ Assert.All(actual.Document.StaticAuthoring.Patterns.SelectMany(p => p.Associations!), a => Assert.DoesNotContain("__ConceptPoints_", a.SourceSet));+ }++ [Fact]+ public void CollectionNameInPatternClauseCannotImpersonateAPointsDeclarationForCompletion()+ {+ var source = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Set/pattern-feature-map.firmament"));+ var offset = source.IndexOf("over Points {", StringComparison.Ordinal) + "over Points {".Length;+ var completion = FirmamentLanguageService.Complete(source, "part.firmament", "1", offset);+ Assert.DoesNotContain(completion.Fields, f => f.Name.Equals("Keys", StringComparison.OrdinalIgnoreCase));+ }++ [Fact]+ public void PatternSourceRetargetUsesOneCheckedExpression()+ {+ var source = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Set/pattern-feature-map.firmament"));+ var view = FirmamentPatternService.Project(source, "part.firmament", "r1");+ var pattern = Assert.Single(view.Patterns);+ var edit = FirmamentLanguageEditService.Apply(source, "part.firmament", "r1", [+ new("insertDeclaration") { Parent = "SetFeaturePattern", Source = "Static Other: Set<Point2> { Center => Point2(0mm, 0mm) }" },+ new("setPatternSource") { Node = pattern.Node, Value = "Other" }]);+ var after = FirmamentV2Parser.Parse(edit.Text);+ Assert.True(after.IsSuccess, string.Join("\n", after.Diagnostics));+ Assert.Equal(0, Assert.Single(Assert.Single(after.Document!.ModifyBlocks!).SemanticHoles).Center.U);+ }++ [Fact]+ public void AssemblyMappingEditsKeepKeysFramesAndGeometryArguments()+ {+ var source = Source("series-assembly");+ var pattern = Assert.Single(FirmamentPatternService.Project(source, "assembly.firmament", "r1").Patterns);+ var edit = FirmamentLanguageEditService.Apply(source, "assembly.firmament", "r1", [new("setPatternBody")+ { Node = pattern.Node, Value = "point => <Part Fret = Pad<H:PadHeight(1mm)>> Placement { from: Bottom.Frame; to: BoardSeat.Frame; translateLocal: [point.X,point.Y,0mm]; } </Part>" }]);+ var before = new AssemblyM1Pipeline().Compile(source);+ var after = new AssemblyM1Pipeline().Compile(edit.Text);+ Assert.True(after.IsSuccess, string.Join("\n", after.Diagnostics));+ Assert.Equal(before.Ir!.Instances.Select(i => i.StableId), after.Ir!.Instances.Select(i => i.StableId));+ foreach (var instance in before.Ir.Instances)+ Assert.Equal(instance.ResolvedTransform?.Matrix, after.Ir.Instances.Single(i => i.StableId == instance.StableId).ResolvedTransform?.Matrix);+ Assert.Equal(before.Geometry!.DefinitionBodies.Keys, after.Geometry!.DefinitionBodies.Keys);+ }++ [Fact]+ public void KeyedSetEditingChangesAuthoredValueAndKeepsTheEntryIdentity()+ {+ var source = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Set/pattern-feature-map.firmament"));+ var view = FirmamentPatternService.Project(source, "part.firmament", "r1");+ Assert.Empty(view.Diagnostics);+ var layout = Assert.Single(view.Layouts);+ Assert.Equal("Point2(-12mm, 0mm)", layout.Rows[0].Authored);+ var edit = FirmamentLanguageEditService.Apply(source, "part.firmament", "r1", [+ new("setSetEntry") { Node = layout.Node, Field = "First", Value = "Point2(-10mm, 0mm)" }]);+ var after = FirmamentV2Parser.Parse(edit.Text);+ Assert.True(after.IsSuccess, string.Join("\n", after.Diagnostics));+ var holes = Assert.Single(after.Document!.ModifyBlocks!).SemanticHoles;+ Assert.Equal(new[] { -10d, 12d }, holes.Select(h => h.Center.U));+ var projected = FirmamentPatternService.Project(edit.Text, "part.firmament", "r2");+ Assert.Equal(layout.Rows.Select(r => r.Key), projected.Layouts.Single().Rows.Select(r => r.Key));+ Assert.Equal(layout.Rows.SelectMany(r => r.GeneratedIds), projected.Layouts.Single().Rows.SelectMany(r => r.GeneratedIds));+ }++ [Fact]+ public void PatternProjectionAndEditsKeepLawSourceKeysAndReadOnlyResults()+ {+ var source = Source("equation-plate");+ var view = FirmamentPatternService.Project(source, "part.firmament", "r1");+ Assert.Empty(view.Diagnostics);+ var layout = Assert.Single(view.Layouts);+ var pattern = Assert.Single(view.Patterns);+ Assert.Equal("Series", layout.Kind);+ Assert.Equal(4, layout.Rows.Count);+ Assert.All(layout.Rows, r => Assert.NotEmpty(r.GeneratedIds));+ Assert.Contains("siteX", pattern.Controls);+ var edit = FirmamentLanguageEditService.Apply(source, "part.firmament", "r1", [+ new("setField") { Node = FirmamentLanguageOutlineService.Outline(source, "part.firmament", "r1").Nodes.Single(n => n.Kind == "Series").Id, Field = "count", Value = "3" },+ new("setValue") { Node = "siteX", Value = "-25mm + pitch * n * n" }]);+ var projected = FirmamentPatternService.Project(edit.Text, "part.firmament", "r2");+ Assert.Empty(projected.Diagnostics);+ Assert.Equal(new[] { -25d, -20d, -5d }, projected.Layouts.Single().Rows.Select(r => r.Coordinates![0]));+ Assert.Equal(layout.Rows.Take(3).Select(r => r.StableId), projected.Layouts.Single().Rows.Select(r => r.StableId));+ Assert.Contains("position: Point2(siteX(n,5mm),0mm)", edit.Text);+ Assert.Contains("point => Drill(center: point)", edit.Text);+ }+}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.csindex 84e0f8c0..2d701f92 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs@@ -99,15 +99,24 @@ public sealed class AssemblyM0Parserif (diagnostics.Count > 0) return new(null, diagnostics, watch.Elapsed.TotalMilliseconds);var patternDiagnostics = new List<string>();var patternsPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("m0.patterns");- var expandedPatterns = CanonicalStaticAuthoring.ExpandAssemblyPatterns(source,patternDiagnostics);+ var pointDiagnostics = new List<FirmamentV2ValidationDiagnostic>();+ var patternOrigins = new FirmamentSyntaxOrigins(syntax.Document, FirmamentSyntaxParser.Parse(source).Document);+ var expandedPatterns = CanonicalStaticAuthoring.ExpandAssemblyPatterns(source,patternDiagnostics, report: pointDiagnostics.Add);patternsPhase.Dispose();var patternOwner = syntax.Document.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d => d.Type.Name.Text == "Assembly" && d.Modifiers.Count == 0)?.Name?.Span;- foreach (var error in patternDiagnostics) diagnostics.Add(new("assembly-pattern-invalid",error)+ foreach (var error in patternDiagnostics){- SourceSpan = patternOwner is { } patternAnchor ? new(sourceIdentity,patternAnchor.Start,patternAnchor.Length) : null,- LocationNote = "Enclosing Assembly declaration; the compile-time value expander did not return an original expression span."- });+ var located = pointDiagnostics.FirstOrDefault(d => error.StartsWith(d.Code, StringComparison.Ordinal));+ var precise = located?.SourceSpan is { } pointSpan ? patternOrigins.Find(pointSpan) : null;+ diagnostics.Add(new("assembly-pattern-invalid", located is null ? error : located.Code + ": " + located.Message)+ {+ SourceSpan = precise is { } p ? new(sourceIdentity,p.Start,p.Length)+ : patternOwner is { } pointAnchor ? new(sourceIdentity,pointAnchor.Start,pointAnchor.Length) : null,+ LocationNote = precise is not null ? located?.LocationNote+ : "Enclosing Assembly declaration; an exact original expression span is unavailable after expansion."+ });+ }if (expandedPatterns is null || patternDiagnostics.Count>0) return Done(null);source = expandedPatterns.Source;var concreteSyntax = FirmamentSyntaxParser.Parse(source).Document;diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.csindex 791abdcc..4ea39cb8 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs@@ -23,7 +23,7 @@ internal static class CanonicalStaticAuthoring.Any(d => d.Type.Name.Text == "Pattern" && d.Clauses.Any(c => c.Kind == ClauseKind.Over && c.Value.Span == match.Span));/// <summary>Assembly consumes the same checked Record/Set values, but yields product-tree declarations.</summary>- internal static Result? ExpandAssemblyPatterns(string source, List<string> diagnostics, bool spatial = false)+ internal static Result? ExpandAssemblyPatterns(string source, List<string> diagnostics, bool spatial = false, Action<FirmamentV2ValidationDiagnostic>? report = null){var binding = new FirmamentDataBinding(source);diagnostics.AddRange(binding.Diagnostics.Select(d => d.Code + ": " + d.Message));@@ -40,10 +40,10 @@ internal static class CanonicalStaticAuthoringvar inputs = scalars.MaterialInputs(source);if (inputs.Any(v => v.Tolerance is not null)){ diagnostics.Add(Prefix + "assembly-tolerance-consumer-unsupported: Assembly frame values cannot project a manufacturing tolerance; use the owning Part and explicit PMI."); return null; }- source = FirmamentValueSubstitution.Apply(source, inputs.ToDictionary(v => v.Name, v => scalars.NominalExpression(v.Name), StringComparer.Ordinal));- var points = ConceptPointAuthoring.Expand(source, diagnostics);+ var points = ConceptPointAuthoring.Expand(source, diagnostics, scalars);+ foreach (var diagnostic in scalars.Diagnostics) report?.Invoke(diagnostic);if (points is null) return null;- source = points.Source;+ source = FirmamentValueSubstitution.Apply(points.Source, inputs.ToDictionary(v => v.Name, v => scalars.NominalExpression(v.Name), StringComparer.Ordinal));var sites = AssemblySiteAuthoring.Expand(source, diagnostics);if (sites is null) return null;source = sites.Source;@@ -52,7 +52,7 @@ internal static class CanonicalStaticAuthoring.Where(d => d.Type.Name.Text == "Pattern" && d.Clauses.Any(c => c.Kind == ClauseKind.Over)).ToArray();if (headers.Length == 0){- source = points.Math.Normalize(source, diagnostics);+ source = points.Math.Normalize(source);return diagnostics.Count > 0 ? null : new(source, points.Points.Count == 0 ? null : new([],[],[],[],[], ConceptPoints: points.Points));}var catalog = source.Select(c => c is '\r' or '\n' ? c : ' ').ToArray();@@ -143,7 +143,7 @@ internal static class CanonicalStaticAuthoring}foreach (var change in changes.OrderByDescending(c=>c.Start)) source=source.Remove(change.Start,change.Length).Insert(change.Start,change.Text);source += "\n" + string.Join("\n", hoisted);- source = points.Math.Normalize(source, diagnostics);+ source = points.Math.Normalize(source);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();@@ -207,7 +207,10 @@ internal static class CanonicalStaticAuthoringdiagnostics.AddRange(choices.Diagnostics.Select(d => d.Code + ": " + d.Message));if (choices.Diagnostics.Any(d => d.Severity is "error" or "fatal")) return null;}- var points = ConceptPointAuthoring.Expand(source, diagnostics);+ scalars ??= new FirmamentCompileTimeValues(source);+ scalars.UseDataBinding(binding);+ _ = FirmamentV2TemplateExpansion.ReadDataCatalog(source, diagnostics, scalars, initialize: true);+ var points = ConceptPointAuthoring.Expand(source, diagnostics, scalars);if (points is null) return null;source = points.Source;var linear = LinearFeatureAuthoring.Expand(source, diagnostics);@@ -221,7 +224,7 @@ internal static class CanonicalStaticAuthoringvar staticDeclaration = Regex.IsMatch(source, @"\b(?:Record|Static|Template\s*(?:<|[A-Za-z_]\w*\s*\()|Pattern\s+\w+\s+Over)\b", RegexOptions.CultureInvariant)|| symmetry.Mirrors.Count > 0 || symmetry.RadialPatterns.Count > 0 || linear.Patterns.Count > 0 || linear.Axes.Count > 0;if (!staticDeclaration && booleanRequires.Length == 0 && !(canonicalRoot && Regex.IsMatch(source, @"\b(?:Require\s+[A-Za-z_]\w*\s*(?:=>|\{)|Pmi\s*\{[\s\S]*?\bFrom\s*:)", RegexOptions.CultureInvariant))) {- source = points.Math.Normalize(source, diagnostics);+ source = points.Math.Normalize(source);return diagnostics.Any(d => d.StartsWith(ConceptPointAuthoring.Prefix, StringComparison.Ordinal)) ? null : new(source, null);}var changes = new List<(int Start, int Length, string Text)>();@@ -479,8 +482,10 @@ internal static class CanonicalStaticAuthoring.Where(change => !erasures.Any(erase => erase.Start < change.Start && change.Start < erase.Start + erase.Length)).OrderByDescending(change => change.Start))source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);- source = points.Math.Normalize(source, diagnostics);+ source = points.Math.Normalize(source);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));}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.csindex 615a1c57..b66a98b3 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs@@ -69,10 +69,15 @@ public sealed record ConceptIrPointSetValue(string StableId, IReadOnlyList<Conce/// <summary>Finite local points; ElementType preserves dimensionality without an implicit 2D-to-3D lift.</summary>public sealed record ConceptIrKeyedPointValue(string StableId, string Key, int Ordinal, string ElementType,- IReadOnlyList<double> Coordinates, string Provenance);+ IReadOnlyList<double> Coordinates, string Provenance)+{ public FirmamentV2SourceSpan? SourceSpan { get; init; } }public sealed record ConceptIrKeyedPointSetValue(string StableId, string Name, string ElementType,IReadOnlyList<ConceptIrKeyedPointValue> Points, string Recipe, string Provenance)- : ConceptIrValue(StableId, ConceptIrValueKind.PointSet, Provenance);+ : ConceptIrValue(StableId, ConceptIrValueKind.PointSet, Provenance)+{+ public FirmamentV2SourceSpan? SourceSpan { get; init; }+ public string? RecipeKind { get; init; }+}public enum ConceptIrSemanticPhase { ConceptIr, FeatureAir }public enum ConceptIrMaterializationCategory { CompileTimeValue, MaterializedSemanticReference }diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.csindex df22b5ad..0caf3afa 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptPointAuthoring.cs@@ -1,284 +1,301 @@using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using System.Globalization;-using System.Text.RegularExpressions;namespace Aetheris.Kernel.Firmament.FirmamentV2;-/// <summary>Finite Concept point recipes. Checked geometry projects to existing keyed Sets;-/// the ordinary Pattern expander remains the only occurrence expansion authority.</summary>+/// <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 const string Prefix = "firmament-concept-points-";internal sealed record Result(string Source, IReadOnlyList<ConceptIrKeyedPointSetValue> Points, MathCatalog Math);- private sealed record Function(string Name, IReadOnlyList<(string Name, string Type)> Parameters, string ReturnType, string Body);+ private sealed record Function(string Name, IReadOnlyList<(string Name, string Type)> Parameters, string ReturnType, ExpressionSyntax Body);internal sealed class MathCatalog{- private int _remainingCalls;- private readonly Dictionary<string, Function> _functions = new(StringComparer.Ordinal);- internal string Parse(string source, List<string> diagnostics)+ 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){- var changes = new List<(int Start, int Length)>();- if (Regex.IsMatch(source, @"\bComptime\s+Function\b")) diagnostics.Add(Prefix+"function-syntax-invalid");- foreach (Match header in Regex.Matches(source, @"\bFunction\s+(?<name>\w+)\s*\((?<args>[^()]*)\)\s*->\s*(?<type>\w+)\s*=\s*(?<body>[^;{}]+);"))+ SourceContext = source;+ var declarations = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)+ .Where(d => d.Type.Name.Text == "Function").ToArray();+ foreach (var d in declarations){- var args = header.Groups["args"].Value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);- var parameters = new List<(string Name,string Type)>();- foreach (var argument in args)- {- var match = Regex.Match(argument,@"^(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>Int|Float|Length|Angle)$");- if (!match.Success) diagnostics.Add(Prefix+"function-parameter-invalid");- else parameters.Add((match.Groups["name"].Value,match.Groups["type"].Value));- }- var name = header.Groups["name"].Value;- var type = header.Groups["type"].Value;- if (!Regex.IsMatch(name, @"^[A-Za-z_]\w*$") || name == "Pow" || !Allowed(type) || parameters.Count > 16 || parameters.Select(p=>p.Name).Distinct().Count()!=parameters.Count- || !_functions.TryAdd(name,new(name,parameters,type,header.Groups["body"].Value)))- diagnostics.Add(Prefix+"function-definition-invalid:"+name);- changes.Add((header.Index,header.Length));+ 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) { diagnostics.Add(Prefix+"function-limit"); return source; }+ 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);- foreach (var function in _functions.Values)+ 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){- var variables=function.Parameters.ToDictionary(p=>p.Name,p=>(1d,Unit(p.Type)),StringComparer.Ordinal);- var dependencies = Regex.Matches(function.Body,@"\b(?<name>[A-Za-z_]\w*)\s*\(").Select(m=>m.Groups["name"].Value).ToArray();- if (!FirmamentNumericEvaluation.TryEvaluateScalar(function.Body,variables,(name,args)=>Call(name,args,true,[]),true,out _,out var unit)- || unit!=Unit(function.ReturnType)) diagnostics.Add(Prefix+"function-body-invalid:"+function.Name);- bool Cycle(string name,HashSet<string> visiting)- {- if (!_functions.TryGetValue(name,out var f) || checkedFunctions.Contains(name)) return false;- if (!visiting.Add(name)) return true;- var cycle=Regex.Matches(f.Body,@"\b(?<name>[A-Za-z_]\w*)\s*\(").Any(m=>Cycle(m.Groups["name"].Value,visiting));- visiting.Remove(name);- if (!cycle) checkedFunctions.Add(name);- return cycle;- }- if (dependencies.Any(d=>Cycle(d,new HashSet<string>(StringComparer.Ordinal)))) diagnostics.Add(Prefix+"function-cycle:"+function.Name);+ 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 change in changes.OrderByDescending(c=>c.Start)) source=source.Remove(change.Start,change.Length);- if (Regex.IsMatch(source,@"\b(?:Comptime\s+)?Function\b")) diagnostics.Add(Prefix+"function-syntax-invalid");+ 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 (double Value,string Unit) Call(string name,IReadOnlyList<(double Value,string Unit)> args,bool typeOnly,HashSet<string> active)+ private FirmamentNumericEvaluation.Value Call(string name, IReadOnlyList<FirmamentNumericEvaluation.Value> args, bool typeOnly, HashSet<string> active){- if (!typeOnly && --_remainingCalls < 0) throw new FormatException();- if (!_functions.TryGetValue(name,out var function) || args.Count!=function.Parameters.Count || active.Count>=32 || !active.Add(name)) throw new FormatException();+ 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(function.Parameters[i].Type) || (!typeOnly && function.Parameters[i].Type=="Int" && !ValidInt(args[i].Value))) throw new FormatException();- if(typeOnly) return (1,Unit(function.ReturnType));- var variables=function.Parameters.Select((p,i)=>(p.Name,args[i])).ToDictionary(p=>p.Name,p=>p.Item2,StringComparer.Ordinal);- if(!FirmamentNumericEvaluation.TryEvaluateScalar(function.Body,variables,(n,a)=>Call(n,a,false,active),false,out var value,out var unit)- || unit!=Unit(function.ReturnType) || (function.ReturnType=="Int" && !ValidInt(value))) throw new FormatException();- return (value,unit);+ 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(string expression,IReadOnlyDictionary<string,(double Value,string Unit)> variables,out double value,out string unit)+ internal bool Evaluate(ExpressionSyntax expression, IReadOnlyDictionary<string, (double Value, string Unit)> variables, out double value, out string unit){- _remainingCalls = 10000;- return FirmamentNumericEvaluation.TryEvaluateScalar(expression,variables,(n,a)=>Call(n,a,false,[]),false,out value,out 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;}-- // Only scalar consumer fields are normalized. No source code is executed.- internal string Normalize(string source,List<string> diagnostics)+ internal string Normalize(string source){- foreach(var name in _functions.Keys)+ 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)){- var offset=0;- while(offset<source.Length)- {- var match=Regex.Match(source[offset..],$@"\b{Regex.Escape(name)}\s*\(");- if(!match.Success) break;- var start=offset+match.Index; var open=source.IndexOf('(',start); var close=Matching(source,open,'(',')');- if(close<0) { diagnostics.Add(Prefix+"function-call-invalid:"+name); break; }- var expression=source[start..(close+1)];- if(!Evaluate(expression,new Dictionary<string,(double,string)>(),out var value,out var unit))- { diagnostics.Add(Prefix+"function-call-invalid:"+expression); offset=close+1; continue; }- var literal=Literal(value,unit);- source=source.Remove(start,close-start+1).Insert(start,literal); offset=start+literal.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 source;+ 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",_=>"" };+ 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)+ internal static Result? Expand(string source, List<string> diagnostics, FirmamentCompileTimeValues? scalars = null){- var math=new MathCatalog(); source=math.Parse(source,diagnostics);- var collections=new List<ConceptIrKeyedPointSetValue>();- var changes=new List<(int Start,int Length,string Text)>();- var sets=new Dictionary<string,string>(StringComparer.Ordinal);- var totalPoints = 0;- foreach(Match owner in Regex.Matches(source,@"\bConcept\s+Struct\s+(?<name>[A-Za-z_]\w*)\s*\{"))+ var input = source;+ MathCatalog? math = null;+ void Error(string code, string message, FirmamentV2SourceSpan span)+ {+ diagnostics.Add(Prefix + code);+ 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);+ if (diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal))) return null;+ var syntax = FirmamentSyntaxParser.Parse(source);+ var collections = new List<ConceptIrKeyedPointSetValue>();+ var changes = new List<(FirmamentV2SourceSpan Span, string Text)>();+ var total = 0;+ foreach (var owner in FirmamentSyntaxTraversal.Declarations(syntax.Document).Where(d => d.Type.Name.Text == "Struct" && d.Modifiers.Any(m => m.Name.Text == "Concept") && d.Body is not null)){- var open=source.IndexOf('{',owner.Index); var close=Matching(source,open,'{','}');- if(close<0) { diagnostics.Add(Prefix+"unclosed"); continue; }- var body=source[(open+1)..close];- if(!Regex.IsMatch(body,@"\bPoints\s*<")) continue;- var generated=new List<string>(); var remaining=body;- foreach(Match header in Regex.Matches(body,@"\bPoints\s*<\s*(?<type>Point2|Point3)\s*>\s+(?<name>[A-Za-z_]\w*)\s*\{"))+ var pointDeclarations = owner.Body!.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Points").ToArray();+ if (pointDeclarations.Length == 0) continue;+ if (owner.Type.Arguments.Count > 0 || owner.Clauses.Count > 0 || owner.Annotation is not null || owner.HasParameterList || owner.ResultType is not null+ || owner.Modifiers.Any(m => m.Name.Text != "Concept"))+ {+ Error("collection-owner-header-unsupported",+ "Local Points recipes do not consume a Concept Struct placement, parameter or contract header. Keep the layout unplaced and bind its physical support/frame explicitly in the Pattern recipe.",+ owner.Clauses.FirstOrDefault()?.Value.Span ?? owner.Annotation?.Span ?? owner.Span);+ continue;+ }+ var generated = new List<string>();+ foreach (var collection in pointDeclarations){- var end=Matching(body,body.IndexOf('{',header.Index),'{','}');- if(end<0) { diagnostics.Add(Prefix+"unclosed"); continue; }- if (totalPoints > 4096) return null;- var fields=body[(header.Index+header.Length)..end];- var identity=owner.Groups["name"].Value+"."+header.Groups["name"].Value;- var setName=SetName(identity);- if(!sets.TryAdd(identity,setName)) { diagnostics.Add(Prefix+"duplicate:"+identity); continue; }- var type=header.Groups["type"].Value; var count=type=="Point2"?2:3;- var points=new List<ConceptIrKeyedPointValue>();- void Error(string reason)=>diagnostics.Add(Prefix+reason+":"+identity);- var recipe=Regex.Match(fields,@"\b(?<kind>Linear|Series)\s*\{");- if(recipe.Success)+ var identity = owner.Name!.Text + "." + collection.Name?.Text;+ if (collections.Any(c => c.Name == identity)) { Error("collection-duplicate", $"Duplicate point collection '{identity}'.", collection.Span); continue; }+ var element = collection.Type.Arguments.Count == 1 ? FirmamentSyntaxValues.Reference(collection.Type.Arguments[0].Value) : null;+ if (element is not ("Point2" or "Point3") || collection.Body is null || collection.Name is null)+ { Error("collection-syntax-invalid", $"'{identity}' requires Points<Point2> or Points<Point3> with a body.", collection.Span); continue; }+ if (!PlainHeader(collection, named: true) || collection.Type.Arguments.Any(a => a.Name is not null))+ { Error("collection-header-unsupported", "Points requires its named Point2/Point3 collection and body, without placement or other header clauses.", collection.Span); continue; }+ var dimension = element == "Point2" ? 2 : 3;+ var fields = Fields(collection, false);+ var points = new List<ConceptIrKeyedPointValue>();+ var recipes = collection.Body.Statements.OfType<DeclarationSyntax>().ToArray();+ var recipe = recipes.Length == 1 ? recipes[0] : null;+ ExpressionSyntax Bound(ExpressionSyntax expression, IReadOnlyDictionary<string, (double, string)> locals)+ {+ if (scalars is null) return expression;+ foreach (var e in FirmamentSyntaxTraversal.Expressions(expression))+ if (FirmamentSyntaxValues.Reference(e) is { } reference && !locals.ContainsKey(reference.Split('.')[0])+ && scalars.TryValue(reference, out var value) && value.Tolerance is not null)+ Error("tolerance-consumer-unsupported", $"Point layout '{identity}' cannot discard the tolerance on '{reference}'; retain it on the owning material feature and explicit PMI.", e.Span);+ return scalars.NominalExpression(expression, locals.Keys.ToHashSet(StringComparer.Ordinal));+ }+ bool Number(ExpressionSyntax? expression, string expected, IReadOnlyDictionary<string, (double, string)> locals, out double number)+ {+ number = double.NaN;+ if (expression is not null && math.Evaluate(Bound(expression, locals), locals, out number, out var unit) && unit == expected) return true;+ Error("point-expression-invalid", $"Layout '{identity}' requires a finite {(expected == "mm" ? "Length" : "dimensionless number")}; check names, units and Function arguments.", expression?.Span ?? collection.Span); return false;+ }+ double[]? Point(ExpressionSyntax? expression, IReadOnlyDictionary<string, (double, string)> locals)+ {+ IReadOnlyList<ArgumentSyntax>? items = expression switch+ {+ CallSyntax { Target: ReferenceSyntax t } c when t.Name.Text == element => c.Arguments,+ SequenceSyntax { Kind: SequenceKind.List } s => s.Items,+ _ => null+ };+ if (items is null || items.Count != dimension || items.Any(i => i.Name is not null))+ { Error("point-arity-invalid", $"'{identity}' requires {element} with exactly {dimension} Length coordinates.", expression?.Span ?? collection.Span); return null; }+ var values = new double[dimension];+ for (var i = 0; i < dimension; i++) if (!Number(items[i].Value, "mm", locals, out values[i])) return null;+ return values;+ }+ void Add(string key, double[]? value, FirmamentV2SourceSpan span)+ {+ if (value is null) return;+ if (value.Any(v => !double.IsFinite(v))) { Error("point-expression-invalid", $"Point '{identity}.{key}' exceeds finite coordinate bounds.", span); return; }+ if (++total > 4096 || points.Count >= 1024) { if (total == 4097 || points.Count == 1024) Error("point-limit", "Use at most 1024 points per collection and 4096 in total.", span); return; }+ if (points.Any(p => p.Key == key)) { Error("keys-invalid", $"Duplicate point key '{key}' in '{identity}'.", span); return; }+ points.Add(new("concept:" + identity + "." + key, key, points.Count, element, value, identity + "." + key) { SourceSpan = scalars?.OriginalPointSpan(span, input) });+ }+ var empty = new Dictionary<string, (double, string)>();+ if (recipes.Length == 0)+ {+ foreach (var f in fields.Values) Add(f.Name.Text, Point(f.Value, empty), f.Span);+ if (fields.Count == 0) Error("point-limit", "A Points collection requires at least one member; an empty typed Set can represent no instances.", collection.Span);+ }+ else if (recipes.Length != 1 || recipe?.Type.Name.Text is not ("Series" or "Linear") || recipe.Body is null)+ Error("recipe-invalid", $"'{identity}' admits one Linear or Series recipe, or explicit keyed points.", collection.Span);+ else{- var finish=Matching(fields,fields.IndexOf('{',recipe.Index),'{','}');- if(finish<0) { Error("recipe-unclosed"); continue; }- var recipeBody=fields[(recipe.Index+recipe.Length)..finish];- string? stationsBody = null;- var stationHeaders = Regex.Matches(recipeBody, @"\bStations\s*\{");- if (stationHeaders.Count > 0)+ if (!PlainHeader(recipe, named: false) || recipe.Type.Arguments.Count != 0)+ { Error("recipe-header-unsupported", $"{recipe.Type.Name.Text} requires an anonymous recipe body, without extra header clauses.", recipe.Span); continue; }+ foreach (var child in recipe.Body.Statements.OfType<DeclarationSyntax>().Where(d => recipe.Type.Name.Text == "Series" || d.Type.Name.Text != "Stations"))+ Error("recipe-invalid", $"Unexpected child '{child.Type.Name.Text}' in {recipe.Type.Name.Text}.", child.Span);+ var entries = Fields(recipe); ExpressionSyntax? Take(string n) => entries.Remove(n, out var f) ? f.Value : null;+ if (recipe.Type.Name.Text == "Series"){- if (stationHeaders.Count != 1 || recipe.Groups["kind"].Value != "Linear") { Error("stations-fields-invalid"); continue; }- var stationHeader = stationHeaders[0];- var stationEnd = Matching(recipeBody, stationHeader.Index + stationHeader.Length - 1, '{', '}');- if (stationEnd < 0) { Error("stations-unclosed"); continue; }- stationsBody = recipeBody[(stationHeader.Index + stationHeader.Length)..stationEnd];- recipeBody = recipeBody.Remove(stationHeader.Index, stationEnd - stationHeader.Index + 1);+ var indexExpression = Take("index"); var index = FirmamentSyntaxValues.Reference(indexExpression);+ var firstExpression = Take("first"); var countExpression = Take("count"); var prefixExpression = Take("keyPrefix"); var prefix = FirmamentSyntaxValues.Reference(prefixExpression); var position = Take("position");+ if (fields.Count > 0) foreach (var f in fields.Values) Error("series-fields-invalid", "Series cannot be combined with Keys or explicit point members.", f.Span);+ if (indexExpression is not ReferenceSyntax || prefixExpression is not ReferenceSyntax || index is null || prefix is null)+ Error("series-fields-invalid", "Series index and keyPrefix must be identifiers.", recipe.Span);+ else if (Number(firstExpression, "", empty, out var first) && Number(countExpression, "", empty, out var amount))+ {+ if (first != Math.Truncate(first) || first < 0 || amount != Math.Truncate(amount) || amount is < 1 or > 1024 || first + amount > int.MaxValue)+ Error("series-bounds-invalid", "Series first must be a nonnegative Int, count must be 1–1024, and the index range must fit Int32.", countExpression?.Span ?? recipe.Span);+ else for (var i = 0; i < (int)amount; i++) { var n = (int)first + i; var local = new Dictionary<string, (double, string)> { { index, (n, "") } }; Add(prefix + n.ToString(CultureInfo.InvariantCulture), Point(position, local), position?.Span ?? recipe.Span); }+ }}- var entries=Fields(recipeBody,Error);- var outer=fields.Remove(recipe.Index,finish-recipe.Index+1);- if(recipe.Groups["kind"].Value=="Linear")+ else{- var outerFields=Fields(outer,Error);- if (stationsBody is not null)+ var start = Point(Take("start"), empty); var stations = recipe.Body.Statements.OfType<DeclarationSyntax>().ToArray();+ if (stations.Length == 1 && stations[0].Type.Name.Text == "Stations"){- if (outerFields.Count != 0 || entries.Count != 2 || !entries.ContainsKey("Start") || !entries.ContainsKey("Direction"))- { Error("stations-fields-invalid"); continue; }- var start = Point(entries["Start"], type, math, new Dictionary<string,(double,string)>(), Error);- var directionText = entries["Direction"].Trim();- if (start is null || !Regex.IsMatch(directionText, @"^\[[^\[\]]*\]$")) { Error("stations-direction-invalid"); continue; }- var components = Components(directionText[1..^1]);- var direction = new double[count];- if (components.Count != count) { Error("stations-direction-invalid"); continue; }- var validDirection = true;- for (var i = 0; i < count; i++)- if (!math.Evaluate(components[i], new Dictionary<string,(double,string)>(), out direction[i], out var unit)- || unit != "" || !double.IsFinite(direction[i])) validDirection = false;+ if (!PlainHeader(stations[0], named: false) || stations[0].Type.Arguments.Count != 0)+ Error("recipe-header-unsupported", "Stations requires an anonymous body of named Length fields.", stations[0].Span);+ var directionExpression = Take("direction"); var items = directionExpression is SequenceSyntax { Kind: SequenceKind.List } vector ? vector.Items : null;+ var direction = new double[dimension]; var valid = items is not null && items.Count == dimension && items.All(i => i.Name is null);+ if (valid) for (var i = 0; i < dimension; i++) valid &= Number(items![i].Value, "", empty, out direction[i]);var scale = direction.Max(v => Math.Abs(v));- if (!validDirection || scale == 0) { Error("stations-direction-invalid"); continue; }- // Scale first so even finite very large/small vectors normalize safely.- var norm = Math.Sqrt(direction.Sum(v => (v / scale) * (v / scale)));- direction = direction.Select(v => (v / scale) / norm).ToArray();- var stations = Fields(stationsBody, Error);- if (stations.Count is < 1 or > 1024) { Error("point-limit"); continue; }- foreach (var station in stations)+ if (!valid || scale == 0) Error("stations-direction-invalid", "Stations requires a nonzero dimensionless direction matching Point2/Point3.", directionExpression?.Span ?? recipe.Span);+ else if (start is not null){- if (!math.Evaluate(station.Value, new Dictionary<string,(double,string)>(), out var distance, out var unit)- || unit != "mm" || !double.IsFinite(distance)) { Error("station-distance-invalid"); continue; }- Add(station.Key, points.Count, start.Zip(direction, (s, d) => s + d * distance).ToArray());+ var norm = Math.Sqrt(direction.Sum(v => (v / scale) * (v / scale))); direction = direction.Select(v => (v / scale) / norm).ToArray();+ foreach (var child in stations[0].Body?.Statements.OfType<DeclarationSyntax>() ?? [])+ Error("recipe-invalid", "Stations contains named Length fields only.", child.Span);+ foreach (var f in Fields(stations[0], false).Values) if (Number(f.Value, "mm", empty, out var distance)) Add(f.Name.Text, start.Zip(direction, (s, d) => s + d * distance).ToArray(), f.Span);}- // Explicit station form is mutually exclusive with Keys/Step.- // The same keyed point IR and Pattern executor own both forms.+ if (fields.Count > 0) foreach (var f in fields.Values) Error("stations-fields-invalid", "Stations cannot be combined with Keys or point members.", f.Span);}else{- if(outerFields.Count!=1 || !outerFields.TryGetValue("Keys",out var keysText) || entries.Count!=2 || !entries.ContainsKey("Start") || !entries.ContainsKey("Step"))- { Error("linear-fields-invalid"); continue; }- if (!Regex.IsMatch(keysText, @"^\s*\[[^\[\]]*\]\s*$")) { Error("keys-invalid"); continue; }- var keys=keysText.Trim().Trim('[',']').Split(',',StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries);- var start=Point(entries["Start"],type,math,new Dictionary<string,(double,string)>(),Error); var step=Point(entries["Step"],type,math,new Dictionary<string,(double,string)>(),Error);- if(start is null || step is null || keys.Length is <1 or >1024 || keys.Distinct().Count()!=keys.Length || keys.Any(k=>!Regex.IsMatch(k,@"^[A-Za-z_]\w*$")) || step.All(v=>v==0))- { Error("linear-invalid"); continue; }- for(var i=0;i<keys.Length;i++) Add(keys[i],i,start.Zip(step,(s,d)=>s+i*d).ToArray());+ var step = Point(Take("step"), empty); var keys = fields.Remove(fields.Keys.FirstOrDefault(k => k.Equals("keys", StringComparison.OrdinalIgnoreCase)) ?? "keys", out var keyField) ? keyField.Value as SequenceSyntax : null;+ if (stations.Length > 0 || keys is not { Kind: SequenceKind.List } || keys.Items.Count is < 1 or > 1024 || keys.Items.Any(k => k.Name is not null || k.Value is not ReferenceSyntax) || step is null || step.All(v => v == 0))+ Error("linear-invalid", "Linear requires unique identifier Keys, Start and a nonzero Step, or Direction with named Stations.", recipe.Span);+ else if (start is not null) for (var i = 0; i < keys.Items.Count; i++) Add(FirmamentSyntaxValues.Reference(keys.Items[i].Value)!, start.Zip(step, (s, d) => s + i * d).ToArray(), keys.Items[i].Value.Span);}}- else- {- if(!string.IsNullOrWhiteSpace(outer.Replace(";","")) || entries.Count!=5 || new[]{"Index","First","Count","KeyPrefix","Position"}.Any(k=>!entries.ContainsKey(k)))- { Error("series-fields-invalid"); continue; }- if(!Regex.IsMatch(entries["Index"],@"^[A-Za-z_]\w*$") || !Regex.IsMatch(entries["KeyPrefix"],@"^[A-Za-z_]\w*$")- || !int.TryParse(entries["First"],out var first) || !int.TryParse(entries["Count"],out var amount) || first<0 || amount is <1 or >1024 || (long)first+amount>int.MaxValue)- { Error("series-bounds-invalid"); continue; }- for(var i=0;i<amount;i++)- {- var n=first+i;- var point=Point(entries["Position"],type,math,new Dictionary<string,(double,string)>{{entries["Index"],(n,"")}},Error);- if(point is not null) Add(entries["KeyPrefix"]+n.ToString(CultureInfo.InvariantCulture),i,point);- }- }- }- else- {- var manual=Fields(fields,Error);- if(manual.Count is <1 or >1024) Error("point-limit");- foreach(var entry in manual)- { var point=Point(entry.Value,type,math,new Dictionary<string,(double,string)>(),Error); if(point is not null) Add(entry.Key,points.Count,point); }+ foreach (var f in entries.Values) Error("field-unknown", $"Unknown field '{f.Name.Text}' in {recipe.Type.Name.Text} for '{identity}'.", f.Span);+ foreach (var f in fields.Values) Error("field-unknown", $"Unknown field '{f.Name.Text}' in Points for '{identity}'.", f.Span);}- void Add(string key,int ordinal,double[] point)- {- if (++totalPoints > 4096) { if (totalPoints == 4097) Error("total-limit"); return; }- if(point.Length!=count || point.Any(v=>!double.IsFinite(v))) { Error("nonfinite"); return; }- points.Add(new("concept:"+identity+"."+key,key,ordinal,type,point,identity+"."+key));- }- collections.Add(new("concept:"+identity,identity,type,points,body[header.Index..(end+1)],identity));- generated.Add($"Static {setName}: Set<{type}> {{\n"+string.Join("\n",points.Select(p=>$"{p.Key} => {type}({string.Join(",",p.Coordinates.Select(v=>Literal(v,"mm")))})"))+"\n}");- remaining=remaining.Replace(body[header.Index..(end+1)],"",StringComparison.Ordinal);+ if (points.Count == 0 && !diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal)))+ Error("point-limit", "A point recipe requires at least one keyed member; use an empty typed Set for no instances.", collection.Span);+ collections.Add(new("concept:" + identity, identity, element, points, source.Substring(collection.Span.Start, collection.Span.Length), identity)+ { SourceSpan = scalars?.OriginalPointSpan(collection.Span, input), RecipeKind = recipe?.Type.Name.Text ?? "Explicit" });+ generated.Add($"Static {SetName(identity)}: Set<{element}> {{\n" + string.Join("\n", points.Select(p => $"{p.Key} => {element}({string.Join(",", p.Coordinates.Select(v => Literal(v, "mm")))})")) + "\n}");+ changes.Add((collection.Span, ""));}- if (Regex.IsMatch(remaining, @"\bPoints\s*<")) diagnostics.Add(Prefix+"collection-syntax-invalid");- // Preserve other Concept members for their existing owner; erase an empty container.- var retained=string.IsNullOrWhiteSpace(remaining.Replace(";",""))?"":$"Concept Struct {owner.Groups["name"].Value} {{ {remaining} }}";- changes.Add((owner.Index,close-owner.Index+1,retained+"\n"+string.Join("\n",generated)));+ var retained = owner.Body.Statements.Where(s => !pointDeclarations.Any(d => ReferenceEquals(d, s))).ToArray();+ if (retained.Length == 0) { changes.RemoveAll(c => Contains(owner.Span, c.Span)); changes.Add((owner.Span, string.Join("\n", generated))); }+ else changes.Add((new(owner.Span.Start + owner.Span.Length, 0), "\n" + string.Join("\n", generated)));}- if(collections.Sum(c=>c.Points.Count)>4096) diagnostics.Add(Prefix+"total-limit");- foreach(var change in changes.OrderByDescending(c=>c.Start)) source=source.Remove(change.Start,change.Length).Insert(change.Start,change.Text);- foreach(var collection in collections)+ if (diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal))) return null;+ source = Apply(source, changes);+ math.SourceContext = source;+ // Resolve only actual expression spans; labels, strings and comments are not substitutions.+ var values = new Dictionary<string, string>(StringComparer.Ordinal);+ foreach (var c in collections){- foreach(var point in collection.Points)+ values[c.Name] = SetName(c.Name);+ foreach (var p in c.Points){- var path=collection.Name+"."+point.Key;- if (point.ElementType == "Point2" && Regex.IsMatch(source,$@"\b{Regex.Escape(path)}(?:\.Position)?\.Z\b")) diagnostics.Add(Prefix+"point-dimension-invalid:"+path);- for(var i=0;i<point.Coordinates.Count;i++) source=Regex.Replace(source,$@"\b{Regex.Escape(path)}(?:\.Position)?\.{"XYZ"[i]}\b",Literal(point.Coordinates[i],"mm"));- source=Regex.Replace(source,$@"\b{Regex.Escape(path)}(?:\.Position)?\b",$"{point.ElementType}({string.Join(",",point.Coordinates.Select(v=>Literal(v,"mm")))})");+ var path = c.Name + "." + p.Key; var point = $"{p.ElementType}({string.Join(",", p.Coordinates.Select(v => Literal(v, "mm")))})";+ values[path] = point; values[path + ".Position"] = point;+ for (var i = 0; i < p.Coordinates.Count; i++) { values[path + "." + "XYZ"[i]] = Literal(p.Coordinates[i], "mm"); values[path + ".Position." + "XYZ"[i]] = Literal(p.Coordinates[i], "mm"); }}- source=Regex.Replace(source,$@"\bOver\s+{Regex.Escape(collection.Name)}\b","Over "+sets[collection.Name]);- if (Regex.IsMatch(source,$@"\b{Regex.Escape(collection.Name)}\.")) diagnostics.Add(Prefix+"point-member-unresolved:"+collection.Name);}- return diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal)) ? null : new(source,collections,math);- }+ var replacements = new List<(FirmamentV2SourceSpan Span, string Text)>();+ foreach (var e in FirmamentSyntaxTraversal.Expressions(FirmamentSyntaxParser.Parse(source).Document).OrderBy(e => e.Span.Start).ThenByDescending(e => e.Span.Length))+ {+ if (replacements.Any(r => Contains(r.Span, e.Span)) || FirmamentSyntaxValues.Reference(e) is not { } name) continue;+ if (values.TryGetValue(name, out var v)) replacements.Add((e.Span, v));+ 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);- private static Dictionary<string,string> Fields(string body,Action<string> error)- {- var result=new Dictionary<string,string>(StringComparer.Ordinal);- foreach(var field in body.Split(';',StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries))- { var split=field.Split(':',2,StringSplitOptions.TrimEntries); if(split.Length!=2 || !Regex.IsMatch(split[0],@"^[A-Za-z_]\w*$") || !result.TryAdd(split[0],split[1])) error("field-invalid"); }- return result;- }- private static double[]? Point(string text,string type,MathCatalog math,IReadOnlyDictionary<string,(double Value,string Unit)> variables,Action<string> error)- {- text=text.Trim();- if(text.StartsWith(type+"(",StringComparison.Ordinal) && text.EndsWith(')')) text=text[(type.Length+1)..^1];- else if(text.StartsWith('[') && text.EndsWith(']')) text=text[1..^1];- else { error("point-type-invalid"); return null; }- var parts=Components(text); var expected=type=="Point2"?2:3;- if(parts.Count!=expected) { error("point-arity-invalid"); return null; }- var result=new double[expected];- for(var i=0;i<expected;i++) if(!math.Evaluate(parts[i],variables,out result[i],out var unit) || unit!="mm") { error("point-expression-invalid");return null; }- return result;- }- internal static IReadOnlyList<string> Components(string text)- {- var parts=new List<string>(); var start=0; var depth=0;- for(var i=0;i<text.Length;i++) { if(text[i]=='(') depth++; if(text[i]==')') depth--; if(text[i]==',' && depth==0) { parts.Add(text[start..i]);start=i+1; } }- parts.Add(text[start..]); return parts;+ Dictionary<string, FieldSyntax> Fields(DeclarationSyntax d, bool vocabulary = true)+ {+ var result = new Dictionary<string, FieldSyntax>(vocabulary ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);+ foreach (var f in d.Body?.Statements.OfType<FieldSyntax>() ?? [])+ if (!result.TryAdd(f.Name.Text, f)) Error("field-invalid", $"Duplicate field/key '{f.Name.Text}' in '{d.Name?.Text ?? d.Type.Name.Text}'.", f.Span);+ foreach (var s in d.Body?.Statements.Where(s => s is not FieldSyntax and not DeclarationSyntax) ?? [])+ Error("recipe-invalid", "Point recipes require named fields or their documented child recipe.", s.Span);+ return result;+ }}+ private static bool PlainHeader(DeclarationSyntax declaration, bool named) =>+ (named ? declaration.Name is not null : declaration.Name is null) && !declaration.Occurrence+ && declaration.Modifiers.Count == 0 && declaration.Parameters.Count == 0 && !declaration.HasParameterList+ && declaration.Annotation is null && declaration.ResultType is null && declaration.Initializer is null+ && declaration.Clauses.Count == 0;++ private static bool Contains(FirmamentV2SourceSpan outer, FirmamentV2SourceSpan inner) => outer.Start <= inner.Start && outer.Start + outer.Length >= inner.Start + inner.Length;+ private static string Apply(string source, IEnumerable<(FirmamentV2SourceSpan Span, string Text)> changes)+ { foreach (var c in changes.OrderByDescending(c => c.Span.Start)) source = source.Remove(c.Span.Start, c.Span.Length).Insert(c.Span.Start, c.Text); return source; }+ private static string Blank(string source) => new(source.Select(c => c is '\r' or '\n' ? c : ' ').ToArray());+ internal static IReadOnlyList<string> Components(string text) => FirmamentSyntaxValues.Components(text).Select(c => c.Text).ToArray();internal static string SetName(string identity) => "__ConceptPoints_" + identity.Split('.').Aggregate("", (name, part) => name + part.Length.ToString(CultureInfo.InvariantCulture) + "_" + part);internal static string Literal(double value, string unit){@@ -299,6 +316,4 @@ internal static class ConceptPointAuthoring: digits.Insert(decimalAt, ".");return sign + plain + unit;}- private static int Matching(string text,int open,char first,char last)- { var depth=0; for(var i=open;i<text.Length;i++) { if(text[i]==first) depth++;else if(text[i]==last && --depth==0) return i; }return -1; }}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.csindex 4068e968..854aa31d 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentCompileTimeValues.cs@@ -29,6 +29,8 @@ internal sealed partial class FirmamentCompileTimeValues(string source)dataBinding = binding;source = binding.Source;originalSyntax = null;+ pointProducer = null;+ pointOrigins = null;originalScopes = OriginalScopes(source).ToDictionary(p => p.Key, p => binding.OriginalSpan(p.Value), StringComparer.Ordinal);identifiers.UnionWith(FirmamentLanguageAnalysisService.Lex(source).Where(t => t.Shape == "identifier").Select(t => t.Text));}@@ -39,6 +41,37 @@ internal sealed partial class FirmamentCompileTimeValues(string source)internal void AddExpansionDiagnostics(IEnumerable<FirmamentV2ValidationDiagnostic> reported) => diagnostics.AddRange(reported);+ private string? pointProducer;+ private FirmamentSyntaxOrigins? pointOrigins;+ internal FirmamentV2SourceSpan? OriginalPointSpan(FirmamentV2SourceSpan span, string producerSource)+ {+ if (producerSource == source) return dataBinding?.OriginalSpan(span) ?? span;+ if (pointProducer != producerSource)+ {+ pointProducer = producerSource;+ originalSyntax ??= FirmamentSyntaxParser.Parse(source).Document;+ pointOrigins = new(originalSyntax, FirmamentSyntaxParser.Parse(producerSource).Document);+ }+ return pointOrigins?.Find(span) is { } matched ? dataBinding?.OriginalSpan(matched) ?? matched : null;+ }++ internal void AddPointDiagnostic(FirmamentV2ValidationDiagnostic diagnostic, string producerSource)+ {+ if (diagnostic.SourceSpan is { } exact && OriginalPointSpan(exact, producerSource) is { } precise)+ {+ diagnostics.Add(diagnostic with { SourceSpan = precise });+ return;+ }+ var owner = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(producerSource).Document)+ .Where(d => d.Name is not null && diagnostic.SourceSpan is { } span+ && d.Span.Start <= span.Start && d.Span.Start + d.Span.Length >= span.Start + span.Length)+ .OrderBy(d => d.Span.Length).FirstOrDefault();+ var anchor = owner is null ? null : OriginalDeclaration(owner.Type.Name.Text, owner.Name!.Text);+ diagnostics.Add(diagnostic with { SourceSpan = anchor, IsOriginalSource = anchor is not null,+ LocationNote = anchor is null ? "Point binding evaluated expanded source; exact original provenance is unavailable."+ : "Location identifies the original enclosing declaration; point binding evaluated expanded source." });+ }+internal void AddConceptDiagnostics(IEnumerable<FirmamentV2ValidationDiagnostic> reported, bool original = true, string? producerSource = null){var producer = producerSource is not null && producerSource != source ? FirmamentSyntaxParser.Parse(producerSource).Document : null;@@ -397,14 +430,16 @@ internal sealed partial class FirmamentCompileTimeValues(string source)internal string NominalExpression(string expression) => values.TryGetValue(expression.Trim(), out var value) ? Nominal(value): recordValues.TryGetValue(expression.Trim(), out var record) ? record.AuthoredName ?? record.Name : expression;- internal ExpressionSyntax NominalExpression(ExpressionSyntax expression)+ internal ExpressionSyntax NominalExpression(ExpressionSyntax expression) => NominalExpression(expression, null);++ internal ExpressionSyntax NominalExpression(ExpressionSyntax expression, IReadOnlySet<string>? shadowed){// Object/with bodies contain statements, so expression-only traversal// misses their scalar fields. Use the existing complete tree traversal.var tree = new DocumentSyntax("inline", [new ExpressionStatementSyntax(expression, expression.Span)], [], expression.Span);var replacements = FirmamentSyntaxTraversal.Expressions(tree).Select(FirmamentSyntaxValues.Reference).OfType<string>().Distinct(StringComparer.Ordinal)- .Where(values.ContainsKey).ToDictionary(name => name,+ .Where(name => values.ContainsKey(name) && shadowed?.Contains(name.Split('.')[0]) != true).ToDictionary(name => name,name => FirmamentSyntaxParser.ParseExpression(NominalExpression(name)).Expression!, StringComparer.Ordinal);return new FirmamentSyntaxSubstitution(replacements).Expression(expression);}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.csindex 6447fedd..cd8c14b4 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs@@ -83,6 +83,8 @@ public static partial class FirmamentLanguageEditService{"setField" => SetField(text, before, operation),"setValue" => SetValue(text, before, operation),+ "setPatternSource" or "setPatternBody" => SetPattern(text, before, operation),+ "setSetEntry" => SetSetEntry(text, before, operation),"removeField" => RemoveField(text, before, operation),"insertDeclaration" => InsertDeclaration(text, before, operation),"removeDeclaration" => RemoveDeclaration(text, before, operation, document, warnings),@@ -114,8 +116,8 @@ public static partial class FirmamentLanguageEditServiceprivate static (string, string?) SetValue(string text, SyntaxParseResult parse, FirmamentLanguageEditOperation op){var (id, declaration) = Find(parse, op.Node);- if (declaration.Type.Name.Text != "Static" || declaration.Initializer is null || declaration.Body is not null)- throw new FirmamentLanguageEditException("edit-value-readonly", "Only an authored Static initializer can be edited as a value.");+ if (declaration.Type.Name.Text is not ("Static" or "Function") || declaration.Initializer is null || declaration.Body is not null)+ throw new FirmamentLanguageEditException("edit-value-readonly", "Only an authored Static initializer or Function expression can be edited as a value.");var value = RequireValue(op.Value, "Value");return (Replace(text, declaration.Initializer.Span.Start, declaration.Initializer.Span.Length, value), id);}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguagePatterns.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguagePatterns.csnew file mode 100644index 00000000..0c53b50b--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguagePatterns.cs@@ -0,0 +1,157 @@+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.Modules;+using Aetheris.Kernel.Firmament.Scene;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public sealed record FirmamentPatternRow(string Key, int Ordinal, string Value, double[]? Coordinates,+ string? StableId, IReadOnlyList<string> GeneratedIds, FirmamentOutlineSpan? Span)+{+ /// <summary>Exact authored keyed Set value; null for generated or derived entries.</summary>+ public string? Authored { get; init; }+}+public sealed record FirmamentPatternLayout(string Node, string Name, string ElementType, string Kind,+ IReadOnlyList<FirmamentPatternRow> Rows);+public sealed record FirmamentPatternApplication(string Node, string Name, string? Source, string Body,+ IReadOnlyList<string> Controls, IReadOnlyList<string> Consumers, string? ReadOnlyReason);+public sealed record FirmamentPatternProjection(string Version, string Document, string Revision,+ IReadOnlyList<FirmamentPatternLayout> Layouts, IReadOnlyList<FirmamentPatternApplication> Patterns,+ IReadOnlyList<FirmamentOutlineDiagnostic> Diagnostics, string ValidationLevel);++/// <summary>Authoring projection of the production finite-layout binder. Coordinates are local+/// values, never guessed world placements. Full project Preview remains the geometry admission gate.</summary>+public static class FirmamentPatternService+{+ public static FirmamentPatternProjection Project(string source, string document, string revision, FirmamentProjectSnapshot? project = null)+ {+ var parsed = FirmamentSyntaxParser.Parse(source, document);+ var declarations = FirmamentLanguageOutlineService.Declarations(parsed);+ var outline = FirmamentLanguageOutlineService.Outline(source, document, revision);+ var errors = parsed.Diagnostics.Select(Diagnostic).ToList();+ var codes = new List<string>();+ var input = source;+ FirmamentModuleGraph.Projection? projection = null;+ if (project is not null && FirmamentModuleGraph.HasImports(source))+ {+ var graph = FirmamentModuleGraph.Load(source, document, project);+ errors.AddRange(graph.Diagnostics.Select(d => new FirmamentOutlineDiagnostic("error", d.Code, d.Message,+ d.SourceSpan?.Source == document ? new(d.SourceSpan.Start, d.SourceSpan.Length) : null)));+ if (graph.Diagnostics.Count == 0) { projection = graph.ProjectSource(graph.Root); input = projection.Text; }+ }+ FirmamentV2StaticAuthoringDocument? bound = null;+ if (errors.Count == 0)+ {+ // Use the existing expansion owner: this is not an editor evaluator or validator.+ var assembly = FirmamentLanguageAnalysisService.HasAssemblyRoot(input);+ var scene = SceneAuthoring.HasRoot(input);+ if (assembly || scene)+ bound = CanonicalStaticAuthoring.ExpandAssemblyPatterns(input, codes, spatial: scene, report: d => errors.Add(MappedDiagnostic(d)))?.Document;+ else+ {+ var result = FirmamentV2Parser.Parse(input);+ bound = result.Document?.StaticAuthoring;+ errors.AddRange(result.SyntaxDiagnostics.Select(MappedDiagnostic));+ if (!result.IsSuccess) codes.AddRange(result.Diagnostics);+ }+ foreach (var code in codes.Where(c => !errors.Any(e => c.StartsWith(e.Code, StringComparison.Ordinal))))+ {+ var diagnostic = FirmamentInterop.FirmamentV2DiagnosticAdapter.FromParserDiagnosticCode(code);+ errors.Add(new(diagnostic.Severity.ToString().ToLowerInvariant(), code.Split(':')[0], diagnostic.Message, null));+ }+ }+ var layouts = new List<FirmamentPatternLayout>();+ foreach (var point in bound?.ConceptPoints ?? [])+ {+ var node = declarations.FirstOrDefault(d => d.Syntax.Type.Name.Text == "Points"+ && d.Syntax.Name?.Text == point.Name.Split('.').Last()+ && declarations.Any(p => p.Id == d.ParentId && p.Syntax.Name?.Text == point.Name.Split('.')[0]));+ if (node.Syntax is null) continue;+ layouts.Add(new(node.Id, point.Name, point.ElementType, point.RecipeKind ?? "Points",+ point.Points.Select(p => new FirmamentPatternRow(p.Key, p.Ordinal,+ $"{p.ElementType}({string.Join(", ", p.Coordinates.Select(v => ConceptPointAuthoring.Literal(v, "mm")))})",+ p.Coordinates.ToArray(), p.StableId, Generated(point.Name, p.Key), MappedSpan(p.SourceSpan))).ToArray()));+ }+ foreach (var set in bound?.Sets ?? [])+ {+ if (set.Name.StartsWith("__ConceptPoints_", StringComparison.Ordinal)) continue;+ var node = declarations.FirstOrDefault(d => d.Syntax.Type.Name.Text == "Static" && d.Syntax.Name?.Text == set.Name);+ if (node.Syntax is null) continue;+ layouts.Add(new(node.Id, set.Name, set.ElementType, "Keyed Set", set.Entries.Select(e =>+ new FirmamentPatternRow(e.Name, e.SourceOrder, e.Value, null, null, Generated(set.Name, e.Name),+ node.Syntax.Body?.Statements.OfType<MappingSyntax>().FirstOrDefault(m => m.Key.Text == e.Name) is { } entry ? Span(entry.Value.Span) : null)+ { Authored = node.Syntax.Body?.Statements.OfType<MappingSyntax>().FirstOrDefault(m => m.Key.Text == e.Name) is { } mapping ? Slice(mapping.Value.Span) : null }).ToArray()));+ }+ var patterns = declarations.Where(d => d.Syntax.Type.Name.Text == "Pattern").Select(d =>+ {+ var over = d.Syntax.Clauses.FirstOrDefault(c => c.Kind == ClauseKind.Over);+ var reachable = new HashSet<string>(StringComparer.Ordinal) { d.Id };+ if (FirmamentSyntaxValues.Reference(over?.Value) is { } layoutName+ && layouts.FirstOrDefault(l => l.Name == layoutName) is { } layout) reachable.Add(layout.Node);+ bool changed;+ do+ {+ changed = false;+ foreach (var edge in outline.Edges.Where(e => reachable.Contains(e.From) && e.ToDocument is null)) changed |= reachable.Add(edge.To);+ foreach (var child in outline.Nodes.Where(n => n.ParentId is not null && reachable.Contains(n.ParentId))) changed |= reachable.Add(child.Id);+ } while (changed);+ var controls = outline.Nodes.Where(n => reachable.Contains(n.Id)+ && (n.Fields.Count > 0 || n.Value is not null)).Select(n => n.Id).ToArray();+ var consumers = outline.Edges.Where(e => reachable.Contains(e.To) && !reachable.Contains(e.From)).Select(e => e.From).Distinct().ToArray();+ return new FirmamentPatternApplication(d.Id, d.Syntax.Name?.Text ?? "Pattern", over is null ? null : Slice(over.Value.Span),+ d.Syntax.Body is { } body ? source.Substring(body.Span.Start + 1, Math.Max(0, body.Span.Length - 2)).Trim() : "",+ controls, consumers, over is null ? "This legacy Pattern has a dedicated domain owner. Its source and geometry remain supported; this editor changes finite 'over' applications." : null);+ }).ToArray();+ return new("firmament-patterns/1", document, revision, layouts, patterns, errors,+ errors.Any(d => d.Severity is "error" or "fatal") ? "Unresolved" : "LayoutResolvedNotBuilt");++ FirmamentOutlineSpan? MappedSpan(FirmamentV2SourceSpan? span)+ {+ if (projection is null) return Span(span);+ return span is { } s && projection.Original(s) is { } original && original.Source == document+ ? new(original.Start, original.Length) : null;+ }+ FirmamentOutlineDiagnostic MappedDiagnostic(FirmamentV2ValidationDiagnostic d) => new(d.Severity, d.Code, d.Message, MappedSpan(d.SourceSpan));+ string Slice(FirmamentV2SourceSpan span) => source.Substring(span.Start, span.Length);+ IReadOnlyList<string> Generated(string name, string key) => (bound?.Patterns ?? [])+ .Where(p => p.Source == name).SelectMany(p => p.Associations ?? []).Where(a => a.SourceEntry == key).Select(a => a.GeneratedId).ToArray();+ }++ private static FirmamentOutlineSpan? Span(FirmamentV2SourceSpan? span) => span is { } s ? new(s.Start, s.Length) : null;+ private static FirmamentOutlineDiagnostic Diagnostic(FirmamentV2ValidationDiagnostic d) => new(d.Severity, d.Code, d.Message, Span(d.SourceSpan));+}++public static partial class FirmamentLanguageEditService+{+ private static (string, string?) SetSetEntry(string text, SyntaxParseResult parse, FirmamentLanguageEditOperation op)+ {+ var (id, declaration) = Find(parse, op.Node);+ var key = RequireIdentifier(op.Field, "Set entry key");+ if (declaration.Type.Name.Text != "Static"+ || declaration.Annotation is not SpecializationSyntax { Target: ReferenceSyntax { Name.Text: "Set" } })+ throw new FirmamentLanguageEditException("edit-set-required", "Choose an authored Static Set.");+ var entries = declaration.Body?.Statements.OfType<MappingSyntax>().Where(m => m.Key.Text == key).ToArray() ?? [];+ if (entries.Length != 1)+ throw new FirmamentLanguageEditException("edit-set-entry-readonly", "Choose one uniquely authored Set entry. Derived values remain owned by their source.");+ var value = RequireValue(op.Value, key);+ return (Replace(text, entries[0].Value.Span.Start, entries[0].Value.Span.Length, value), id);+ }++ private static (string, string?) SetPattern(string text, SyntaxParseResult parse, FirmamentLanguageEditOperation op)+ {+ var (id, declaration) = Find(parse, op.Node);+ if (declaration.Type.Name.Text != "Pattern" || declaration.Body is null+ || !declaration.Clauses.Any(c => c.Kind == ClauseKind.Over))+ throw new FirmamentLanguageEditException("edit-pattern-required", "Choose a finite Pattern over a collection.");+ if (op.Kind == "setPatternSource")+ {+ var clause = declaration.Clauses.Single(c => c.Kind == ClauseKind.Over);+ var value = RequireValue(op.Value, "source");+ return (Replace(text, clause.Value.Span.Start, clause.Value.Span.Length, value), id);+ }+ if (string.IsNullOrWhiteSpace(op.Value))+ throw new FirmamentLanguageEditException("edit-pattern-body-required", "A Pattern needs its keyed mapping and recipe.");+ var body = declaration.Body.Span;+ return (Replace(text, body.Start + 1, body.Length - 2, "\n" + op.Value.Trim() + "\n"), id);+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.csindex c4ec4a49..cf95ea62 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs@@ -1,4 +1,5 @@using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.Firmament.Materializer;namespace Aetheris.Kernel.Firmament.FirmamentV2;@@ -32,6 +33,14 @@ public static class FirmamentLanguageService{beforePrefix = source[Math.Max(lineStart,composition.Value.Open+1)..prefixStart];fields = FirmamentSchemaAuthoringFields.For(composition.Value.Name, composition.Value.Variant);+ if (composition.Value.Name == "Points")+ {+ var owner = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)+ .FirstOrDefault(d => d.Type.Name.Text == "Points" && d.Body?.Span.Start == composition.Value.Open);+ var recipe = owner?.Body?.Statements.OfType<DeclarationSyntax>().FirstOrDefault();+ if (recipe?.Type.Name.Text == "Series" || recipe?.Body?.Statements.OfType<DeclarationSyntax>().Any(d => d.Type.Name.Text == "Stations") == true)+ fields = [];+ }context = composition.Value.Name;}else if (interfaceFamily is not null)@@ -143,6 +152,8 @@ public static class FirmamentLanguageServicevar prefix = Regex.Replace(source[..offset], @"//[^\r\n]*|/\*[\s\S]*?\*/|""(?:\\.|[^""\\])*""", m => new string(' ', m.Length));var names = "Scene|Room|Door|Window|Camera|WireRoute|Follow|Section|Points|Linear|Series|Appearance|Material|Placement|FrameTransform|Garment|Panel|Fabric|Drape|FigureFit|Fitting|PoseTransition|Pose|Joint|Interface|Hole";var matches = Regex.Matches(prefix, $@"\b(?<kind>{names})(?:\s*<(?<family>[^>]+)>)?(?:\s+[A-Za-z_]\w*)?\s*\{{");+ var syntax = FirmamentSyntaxParser.Parse(source);+ var declarations = FirmamentSyntaxTraversal.Declarations(syntax.Document).ToArray();foreach (Match header in matches.Cast<Match>().Reverse()){var depth = 1;@@ -155,6 +166,12 @@ public static class FirmamentLanguageServiceif (depth > 0){string name = header.Groups["kind"].Value;+ var open = header.Index + header.Length - 1;+ var owner = declarations.FirstOrDefault(d => d.Body?.Span.Start == open);+ // A collection named Points in `Pattern ... over Points {` is a reference,+ // not a Points declaration. Use actual AST ownership when available;+ // retain lexical help for object initializers and incomplete drafts.+ if (owner is not null && owner.Type.Name.Text != name) continue;if (name == "Interface") name += "<" + header.Groups["family"].Value.Trim() + ">";return (name, header.Index + header.Length - 1, header.Groups["family"].Value.Trim());}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentValueSubstitution.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentValueSubstitution.csindex 23586f1e..03dd6e83 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentValueSubstitution.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentValueSubstitution.cs@@ -13,10 +13,10 @@ internal static class FirmamentValueSubstitutionvar syntax = FirmamentSyntaxParser.Parse(prefix + source + "\n}");var declarations = FirmamentSyntaxTraversal.Declarations(syntax.Document).ToArray();var names = declarations.Where(d => d.Name is not null).Select(d => d.Name!.Span.Start - prefix.Length).ToHashSet();- var scopes = declarations.Where(d => d.Body is not null).Select(d => (Span: d.Body!.Span,+ var scopes = declarations.Where(d => d.Body is not null || d.Initializer is not null && d.HasParameterList).Select(d => (Span: d.Body?.Span ?? d.Initializer!.Span,Names: d.Parameters.Select(p => p.Name?.Text).OfType<string>().Concat(d.Modifiers.Where(m => m.Name.Text == "Template").SelectMany(m => m.Arguments).Select(a => a.Name?.Text).OfType<string>())- .Concat(d.Type.Name.Text == "Feature" ? d.Body.Statements.OfType<DeclarationSyntax>()+ .Concat(d.Type.Name.Text == "Feature" && d.Body is not null ? d.Body.Statements.OfType<DeclarationSyntax>().Where(l => l.Type.Name.Text == "let").Select(l => l.Name?.Text).OfType<string>() : []).ToHashSet(StringComparer.Ordinal))).Where(s => s.Names.Count > 0).ToArray();var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(t => t.Shape != "comment").ToArray();diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.csindex ffea7856..29a12ef0 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentDataBinding.cs@@ -109,7 +109,7 @@ internal sealed class FirmamentDataBindingvar child = new Scope(scope, scope.Identity + "/mapping " + m.Key.Text); child.Values.Add(m.Key.Text);Collect([m.Value], child); continue;}- if (statement is not DeclarationSyntax d || d.Body is null) continue;+ if (statement is not DeclarationSyntax d || d.Body is null && !d.HasParameterList) continue;var label = d.Type.Name.Text + " " + d.Name?.Text;var ordinal = ordinals.GetValueOrDefault(label); ordinals[label] = ordinal + 1;var header = new Scope(scope, scope.Identity + "/parameters " + label + "#" + ordinal);@@ -120,6 +120,7 @@ internal sealed class FirmamentDataBindingelse header.Values.Add(p.Name.Text);}headers[d] = header;+ if (d.Body is null) continue;var body = new Scope(header, scope.Identity + "/" + label + "#" + ordinal);scopeSpans.Add((d.Body.ContentSpan, body));Collect(d.Body.Statements, body);@@ -145,7 +146,7 @@ internal sealed class FirmamentDataBinding}if (d.Annotation is not null) Expression(d.Annotation, scope, true);if (d.ResultType is not null) Expression(d.ResultType, headers.GetValueOrDefault(d) ?? scope, true);- if (d.Initializer is not null) Expression(d.Initializer, scope, false);+ if (d.Initializer is not null) Expression(d.Initializer, headers.GetValueOrDefault(d) ?? scope, false);foreach (var clause in d.Clauses.Where(c => c.Kind != ClauseKind.Key)) Expression(clause.Value, scope, false);if (d.Body is not null){diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.csindex 7c1958b4..b4b29369 100644--- a/Aetheris.Web.Runtime/Program.cs+++ b/Aetheris.Web.Runtime/Program.cs@@ -59,6 +59,7 @@ public static partial class Program"languageAnalyze" => LanguageAnalyze(request),"languageOutline" => LanguageOutline(request),"languageSketch" => LanguageSketch(request),+ "languagePatterns" => LanguagePatterns(request),"languageSketchEdit" => LanguageSketchEdit(request),"languageEdit" => LanguageEdit(request),"languagePalette" => FirmamentLanguagePaletteService.Palette(),@@ -160,6 +161,16 @@ public static partial class Programreturn FirmamentLanguageOutlineService.Outline(new FirmamentProjectSnapshot(request.ProjectRoot ?? name, documents), name, request.SourceRevision);}+ private static object LanguagePatterns(WebRequest request)+ {+ if (request.Source is null || request.SourceRevision is null)+ throw new WebRuntimeException("source-required", "A Pattern query requires source and its revision.");+ var name = request.SourceName ?? "model.firmament";+ var documents = new Dictionary<string, string>(request.ProjectDocuments ?? new Dictionary<string, string>(), StringComparer.Ordinal) { [name] = request.Source };+ return FirmamentPatternService.Project(request.Source, name, request.SourceRevision,+ new FirmamentProjectSnapshot(request.ProjectRoot ?? name, documents));+ }+private static object LanguageSketch(WebRequest request){if (request.Source is null || request.SourceRevision is null)diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.tsindex 31f4fbdd..6e7b4298 100644--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts@@ -60,6 +60,8 @@ export interface LanguageOutline { readonly version: 'firmament-outline/1'; readexport interface DeclarationSpec { readonly kind: string; readonly variant?: string | null; readonly modifiers?: readonly string[] | null; readonly name?: string | null; readonly fields?: readonly { readonly name: string; readonly value: string }[] | null }/** One structural edit, addressed by outline node ids. Operations apply in order; each later one sees the ids the earlier ones produced. */export type LanguageEditOperation =+ | { readonly kind: 'setPatternSource' | 'setPatternBody'; readonly node: string; readonly value: string }+ | { readonly kind: 'setSetEntry'; readonly node: string; readonly field: string; readonly value: string }| { readonly kind: 'setValue'; readonly node: string; readonly value: string }| { readonly kind: 'setField'; readonly node: string; readonly field: string; readonly value: string }| { readonly kind: 'removeField'; readonly node: string; readonly field: string }@@ -80,6 +82,10 @@ export interface LanguageEdit { readonly document: string; readonly revision: st/** Something a visual editor can add. `placement` `model` inserts with `insertDeclaration`; `feature` with `insertFeature` on a body. `source` declares `nameStem`; pass a unique `name` with the insert. Every item is proven to build. */export interface PaletteItem { readonly id: string; readonly label: string; readonly category: string; readonly description: string; readonly placement: 'model' | 'feature'; readonly nameStem: string; readonly source: string; readonly requiresEmptyModel?: boolean }export interface LanguagePalette { readonly version: 'firmament-palette/1'; readonly items: readonly PaletteItem[] }+export interface PatternRow { readonly authored?: string | null; readonly key: string; readonly ordinal: number; readonly value: string; readonly coordinates: readonly number[] | null; readonly stableId: string | null; readonly generatedIds: readonly string[]; readonly span: OutlineSpan | null }+export interface PatternLayout { readonly node: string; readonly name: string; readonly elementType: string; readonly kind: string; readonly rows: readonly PatternRow[] }+export interface PatternApplication { readonly node: string; readonly name: string; readonly source: string | null; readonly body: string; readonly controls: readonly string[]; readonly consumers: readonly string[]; readonly readOnlyReason: string | null }+export interface PatternProjection { readonly version: 'firmament-patterns/1'; readonly document: string; readonly revision: string; readonly layouts: readonly PatternLayout[]; readonly patterns: readonly PatternApplication[]; readonly diagnostics: readonly { severity: string; code: string; message: string; span: OutlineSpan | null }[]; readonly validationLevel: 'LayoutResolvedNotBuilt' | 'Unresolved' }export interface SketchControl { id: string; label: string; authored: string; value: number; unit: string; editable: boolean; parameter: string | null; readOnlyReason: string | null; span: { start: number; length: number } }export interface SketchShape { id: string; name: string; kind: string; center: readonly number[]; controls: readonly SketchControl[] }export interface SketchCurve {@@ -116,7 +122,7 @@ export class Aetheris {static create(options?: AetherisOptions): Promise<Aetheris>;readonly runtimeInfo: RuntimeInfo;readonly workerTiming: WorkerTiming | null;- readonly language: { sketch(source: string, node: string | null, options: LanguageOptions): Promise<SketchProjection>; sketchEdit(source: string, edit: SketchEditRequest, options: LanguageOptions): Promise<LanguageEdit>; complete(source: string, offset: number, options: LanguageOptions): Promise<LanguageCompletion>; analyze(source: string, options: LanguageOptions): Promise<LanguageAnalysis>; outline(source: string, options: LanguageOptions): Promise<LanguageOutline>; edit(source: string, operations: readonly LanguageEditOperation[], options: LanguageOptions): Promise<LanguageEdit>; palette(): Promise<LanguagePalette>; hover(source: string, offset: number, options: LanguageOptions): Promise<LanguageHover | null>; definition(source: string, offset: number, options: LanguageOptions): Promise<SourceReference | null>; format(source: string, options: LanguageOptions): Promise<LanguageFormat>; schema(): Promise<SemanticSchema> };+ readonly language: { patterns(source: string, options: LanguageOptions): Promise<PatternProjection>; sketch(source: string, node: string | null, options: LanguageOptions): Promise<SketchProjection>; sketchEdit(source: string, edit: SketchEditRequest, options: LanguageOptions): Promise<LanguageEdit>; complete(source: string, offset: number, options: LanguageOptions): Promise<LanguageCompletion>; analyze(source: string, options: LanguageOptions): Promise<LanguageAnalysis>; outline(source: string, options: LanguageOptions): Promise<LanguageOutline>; edit(source: string, operations: readonly LanguageEditOperation[], options: LanguageOptions): Promise<LanguageEdit>; palette(): Promise<LanguagePalette>; hover(source: string, offset: number, options: LanguageOptions): Promise<LanguageHover | null>; definition(source: string, offset: number, options: LanguageOptions): Promise<SourceReference | null>; format(source: string, options: LanguageOptions): Promise<LanguageFormat>; schema(): Promise<SemanticSchema> };info(): Promise<RuntimeInfo>;capabilities(): Promise<RuntimeCapabilities>;compile(source: string, options?: CompileOptions): Promise<{ model: ModelSession | null; diagnostics: readonly Diagnostic[] }>;diff --git a/Aetheris.Web.Runtime/sdk/src/index.js b/Aetheris.Web.Runtime/sdk/src/index.jsindex e93da3c5..a40c8347 100644--- a/Aetheris.Web.Runtime/sdk/src/index.js+++ b/Aetheris.Web.Runtime/sdk/src/index.js@@ -89,6 +89,8 @@ export class Aetheris {outline: (source, options = {}) => this.transport.request({ operation: 'languageOutline', source,sourceName: options.sourceName, sourceRevision: options.sourceRevision, projectDocuments: options.projectDocuments, projectRoot: options.projectRoot }),palette: () => this.transport.request({ operation: 'languagePalette' }),+ patterns: (source, options = {}) => this.transport.request({ operation: 'languagePatterns', source,+ sourceName: options.sourceName, sourceRevision: options.sourceRevision, projectDocuments: options.projectDocuments, projectRoot: options.projectRoot }),sketch: (source, node, options = {}) => this.transport.request({ operation: 'languageSketch', source, node,sourceName: options.sourceName, sourceRevision: options.sourceRevision }),sketchEdit: (source, sketchEdit, options = {}) => this.transport.request({ operation: 'languageSketchEdit', source, sketchEdit,diff --git a/Aetheris.Web.Runtime/sdk/tests/language.test.mjs b/Aetheris.Web.Runtime/sdk/tests/language.test.mjsindex 9a6747ed..c6829882 100644--- a/Aetheris.Web.Runtime/sdk/tests/language.test.mjs+++ b/Aetheris.Web.Runtime/sdk/tests/language.test.mjs@@ -74,3 +74,12 @@ test('public language palette asks the runtime for the catalog', async () => {assert.equal((await cad.language.palette()).version, 'firmament-palette/1');assert.deepEqual(requests, [{ operation: 'languagePalette' }]);});++test('Pattern projection uses compiler source and revision; edits retain expressions', async () => {+ const requests = [];+ const cad = new Aetheris({ request: async request => { requests.push(request); return {}; } });+ await cad.language.patterns('law source', { sourceName: 'plate.firmament', sourceRevision: 'r7' });+ await cad.language.edit('law source', [{ kind: 'setPatternSource', node: 'Plate/Drills', value: 'Layout.Sites' }], { sourceName: 'plate.firmament', sourceRevision: 'r7' });+ assert.deepEqual(requests[0], { operation: 'languagePatterns', source: 'law source', sourceName: 'plate.firmament', sourceRevision: 'r7', projectDocuments: undefined, projectRoot: undefined });+ assert.equal(requests[1].operations[0].value, 'Layout.Sites');+});diff --git a/docs/public/firmament/concept-points-and-functions.md b/docs/public/firmament/concept-points-and-functions.mdindex 999db339..52bc584c 100644--- a/docs/public/firmament/concept-points-and-functions.md+++ b/docs/public/firmament/concept-points-and-functions.md@@ -132,8 +132,15 @@ Concept Struct FretboardLayout {}```-`First` and `Count` are literal integer bounds. This produces Fret1 through-Fret22, in ascending index order; Fret12 is exactly `[0mm,-314mm]`.+`first` and `count` define checked integer bounds. Part and assembly recipes+resolve checked Static/Record inputs and specialized Template inputs through the+shared lexical binder. Function parameters and the Series index shadow unrelated+Statics with the same name. Pass design values explicitly to pure Functions.+See [Patterns](patterns.md#helios-layout-recipe-instances) for source-preserving+visual editing, evaluated keyed rows and full-project Preview/Apply.++The example produces Fret1 through Fret22, in ascending index order; Fret12 is+exactly `[0mm,-314mm]`.The authored recipe and each point's key, ordinal, dimensionality, coordinatesand stable identity remain in inspection evidence.@@ -166,7 +173,8 @@ Patterns preserve the logical collection name in expanded associations.- Functions have unique names in the compiled source catalog, at most 16parameters each, and `Int`, `Float`, `Length` or `Angle` arguments/results.- Forward calls are permitted; recursive dependency cycles are rejected.+ 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)`.Division is real division, including when both operands are integral.diff --git a/docs/public/firmament/patterns.md b/docs/public/firmament/patterns.mdnew file mode 100644index 00000000..70fcac3c--- /dev/null+++ b/docs/public/firmament/patterns.md@@ -0,0 +1,142 @@+# Patterns: a layout mapped to construction++A Firmament Pattern is finite compile-time construction. Linear and circular+repetition are useful layouts, but they are not the limits of the language.+Keep three responsibilities separate:++1. **Layout:** a keyed `Set<T>` or Concept `Points<Point2>` / `Points<Point3>`.+ Points may be explicit, equally spaced, placed at named stations, or generated+ by a checked `Series` expression.+2. **Recipe:** a `Feature` for repeated construction, or a shared Part/Subassembly+ definition for repeated components. A scalar `Function` computes dimensions+ and coordinates; it does not construct a body itself.+3. **Application:** `Pattern ... over ...` maps that finite collection to the+ recipe in the owning Model, Modify, assembly, or admitted domain scope.++## A complete nonlinear hole pattern++This file builds four diameter-3mm holes at X = -30, -25, -10 and 15mm.+The square-spacing law lives in a Function; the Pattern does not contain copied+coordinates or a second implementation of the equation.++```firmament+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}+```++Arithmetic can also appear directly in `position`. Functions compose scalar+arithmetic and the admitted dimensionless `Pow` builtin. Their supported+argument/result types are Int, Float, Length and Angle. Function calls currently+use positional arguments; Feature calls may use named arguments. There is no+host-code execution, recursion, mutation, I/O or arbitrary function library.+`Sin`/`Cos` are not currently admitted by this scalar Function evaluator.+See [Concept points and Functions](concept-points-and-functions.md) for its+checked units and evaluation budgets.++## Choose a layout for its intent++| Intent | Existing source form |+| --- | --- |+| Named irregular positions or per-site Record data | `Static sites: Set<T> { key => value }` |+| Equal pitch with named members | Concept Points with `keys` and `Linear { start; step; }` |+| Unequal distances along one direction | `Linear { start; direction; Stations { key: distance; } }` |+| Coordinates governed by a scalar design law | `Series { index; first; count; keyPrefix; position; }` |+| Existing planar circular feature symmetry | `Radial Pattern ...` in its admitted owner |+| Repeated complete equipment / components | Keyed assembly Pattern producing Part or Assembly occurrences |+| Cross-sections driven by station Records | Keyed Pattern producing Section values in SectionChain |++The guitar uses the equation route for 22 frets, named stations for nine inlays,+and ordinary finite Patterns for other components. A law may affect both+placement and recipe dimensions, as fret distance also determines fret width.+Changing the law can therefore reshape a part intentionally; preserved instance+identity does not imply preserved geometry.++Point2 stays local 2D data. An assembly placement explicitly supplies the frame+and lifts the coordinates into 3D. Point3 stays 3D. The local Points binder rejects a placement/contract header on+its containing Concept Struct rather than erasing it. Geometric Concept Struct+frames remain a separate supported scaffold owner. Neither the graph nor an+exporter should guess a missing frame or silently promote dimensionality.++## Keys, count and order++Set/Concept member keys identify repeated instances. Reordering explicit keyed+stations retains each key's distance. Changing a Series law or growing its count+retains identities for existing keys. Changing `first` changes the key domain;+changing `keyPrefix` renames the generated members. Those are identity edits,+not merely display labels. Ordered arrays and older Grid expansions retain their+existing positional identity rules.++A Series contains 1–1024 points; the current point expansion total is 4096.+An empty typed Set is admitted and produces no mapped instances. A zero-count+Series is currently rejected. A Pattern does not bypass the target feature's+geometry, overlap, containment or frame capability checks.++## Checked inputs and scope++Part and assembly Series consume the same checked Static and Record values.+Template specialization may supply those inputs too. For example, add+`Static count: Int = 4;` to the model and use `count: count` in Series. Changing+the Static changes the finite layout without turning its law into coordinates.++Function parameters are lexical locals. A Static named `pitch` does not replace+the `pitch` parameter in `siteX`; the call's actual argument controls the value.+Functions remain pure: pass design values as arguments rather than capturing+Statics implicitly. This distinction also applies to the Series index.++Typed tolerances cannot be silently discarded by layout evaluation. A tolerated+value that has no admitted point-layout tolerance projection is rejected; keep+manufacturing tolerance on the owning material feature and explicit PMI.++## Helios: Layout, Recipe, Instances++Open **Patterns…** from the graph construction menu, or select a Pattern, Points,+Series, Stations or Function and open its Pattern action.++- **Layout** reopens the authored collection and exposes its expressions,+ count/spacing inputs, station distances and scalar Function laws. An authored+ keyed Set entry has a separate value control; editing it keeps its key and+ original expression ownership. Derived entries stay read-only. References+ remain references until explicitly edited. Shared consumers are listed.+- **Recipe** exposes the keyed mapping and fields of the shared construction+ recipe. A Feature can be selected when creating an application; its typed+ parameter names seed the mapping. A component selector reuses an existing+ definition/specialization; explicit source/target frames and a coordinate law+ generate ordinary Part/Assembly Placement source. The mapping remains editable.+- **Instances** shows compiler-evaluated keys, values and expansion associations.+ Rows are read-only. The gold 2D plot is a **local layout**, not a world-space+ placement. The recipe's explicit support/frame still controls construction.++**New Pattern…** can use an existing keyed collection, create an equation Series,+or create named Stations. The initial create controls make Point2 layouts;+existing Point3 layouts retain their dimensionality and can be used/edited.+Review `first`, `keyPrefix` and station/Set keys carefully: changing them changes+identities. Changing an equation or distance keeps keys stable.++**Preview** compiles the complete candidate project with its includes. It does+not change the working source. **Apply** commits that exact admitted candidate+as one undoable source transaction. Changing any control invalidates the preview;+Cancel or a refused build leaves the working source and model intact. Layout+resolution alone reports `LayoutResolvedNotBuilt`, never a successful solid.++Imported definitions remain owned by their document; open that document to edit+its law or recipe. The current panel edits one source document per transaction.+Legacy radial/linear Pattern forms keep their production owners and show an+explicit read-only explanation when this finite-collection editor has no adapter.++**Grid seed hole…** remains a separate convenience action for a field-based Hole.+Its counts include the original seed, while its keyed Pattern maps the additional+holes. It is not an equation-layout editor and does not infer a grid from existing+coordinates.diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 7c37dcb8..b4048e34 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -753,6 +753,11 @@ SectionChain reject Feature declarations.### Pattern: finite repetition+A Pattern maps a finite **layout** to a construction **recipe**. Layouts can be+named data, equal pitch, irregular stations, or a Function-driven Series; they+are not limited to linear/circular repetition. See [Patterns](patterns.md) for a+complete nonlinear hole example, stable-key behavior and current editor limits.+**Complete file — two named points mapped to two holes:**```firmament@@ -799,6 +804,8 @@ have different Pattern forms:| Pattern source | Binding form || --- | --- |+| Concept Points generated by Linear / Stations / Series | `Pattern name over Layout.Points { point => Recipe(point) }` |+| Keyed assembly sites | `Pattern name over sites { site => <Part Member = Definition> ... </Part> }` || Named Set mapped to a Feature | `Pattern name over values { value => Recipe(value) }` || Semantic PointSet / Grid | `Pattern name { Source: layout.Points ... Item ... }` || Record array with finite feature Template | `Pattern name over records { Recipe<Current> }` |@@ -856,6 +863,21 @@ value references. It does not rename field labels, declaration names, stringcontents or a similarly spelled identifier. Generated instance identities stillcome 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+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+use a plain Concept Struct header; unconsumed placement/contract headers reject+rather than silently changing the frame. Geometric Concept Struct frames remain+owned by their geometric scaffold binder.++Helios **Patterns…** edits the owning layout, law and keyed recipe, previews the+complete candidate project, then applies one undoable source transaction.+Evaluated instance rows are read-only. Its golden Point2 plot shows local layout+coordinates; the recipe resolves the physical support frame. **Grid seed hole…**+is the separate rectangular seed convenience tool. See [Patterns](patterns.md).+### Template: specialize a product**Complete file — one sized member of a product family:**diff --git a/docs/public/web-sdk/api-reference.md b/docs/public/web-sdk/api-reference.mdindex 5523677b..3b39392c 100644--- a/docs/public/web-sdk/api-reference.md+++ b/docs/public/web-sdk/api-reference.md@@ -19,3 +19,32 @@ The stable preview contract is `aetheris/web-editor-contract/1`.- `model.dispose()` and `cad.dispose()` release managed sessions.Unexpected failures throw `AetherisError` with stable `code`, safe `message`, and optional developer `details`. See the shipped `index.d.ts` for exact readonly record types.+++## Pattern source projection++`cad.language.patterns(source, { sourceName, sourceRevision, projectRoot,+projectDocuments })` returns `firmament-patterns/1`: finite layouts, authored+Pattern mappings, reachable control node ids, shared consumers, diagnostics and+compiler-evaluated keyed rows. Included declarations resolve through the existing+module graph. `validationLevel: "LayoutResolvedNotBuilt"` describes layout+resolution, not geometry admission; compile the complete candidate project before+committing an edit.++Rows expose their value and expansion associations. `authored` is present only+for directly authored keyed Set entries; generated/derived rows are read-only.+Point coordinates are local values and preserve Point2/Point3 dimensionality.+The response retains its document and revision for stale-response checks.++Use ordinary `language.edit` operations to change the source:++- `setValue` edits a Static initializer or scalar Function expression.+- `setField` edits a Series/Linear/Stations input or other authored field.+- `setSetEntry` edits one authored Static Set value by node and `field` key,+ retaining the key itself.+- `setPatternSource` and `setPatternBody` edit the collection expression and+ keyed mapping; `insertDeclaration` creates ordinary layout/Pattern declarations.++These edits parse their result. Complete compiler Preview remains responsible+for binding, feature/capability admission and geometry construction. See+[Patterns](../firmament/patterns.md) for the language and Helios workflow.diff --git a/docs/release/PATTERN-AUTHORING-AUDIT-2026-10-20.md b/docs/release/PATTERN-AUTHORING-AUDIT-2026-10-20.mdnew file mode 100644index 00000000..2788d123--- /dev/null+++ b/docs/release/PATTERN-AUTHORING-AUDIT-2026-10-20.md@@ -0,0 +1,330 @@+# Pattern authoring — compiler and visual editing audit++> Historical audit snapshot. Repairs and current qualification are tracked in+> [the implementation report](PATTERN-AUTHORING-IMPLEMENTATION-2026-10-20.md).++Date: 2026-10-20. Source baseline: Aetheris `ad6dc5ce`, HeliosCAD `f038b19`.++**Outcome: audit complete; broader Pattern exposure is blocked by a confirmed+silent geometry defect.** The equation engine is real, but Function parameter+shadowing can change admitted engineering geometry. A full visual Pattern editor+is not implemented in this pass. Thirty-two source specimens, seven canonical+controls and real browser interactions identify the required repairs.+No compiler, SDK or product implementation code changed during this audit.++## The language model to expose++```text+Function law + checked inputs+ ↓+Concept Points (Linear / Stations / Series), or keyed Set<Record>+ ↓+Pattern application → Feature construction OR Part/Subassembly occurrences+```++`Function` computes scalar values. `Series` generates a bounded collection of+Point2/Point3 values. `Feature` constructs feature intent. `Pattern` applies a+recipe to a finite source. These responsibilities already exist; no new generic+loop runtime, constraint solver or host-code evaluator is needed.++Linear and circular patterns are convenient layouts. They must not become the+editor's definition of Pattern. The guitar's fret law controls placement and+width; its inlays use independent named distances along a direction. Preserve+those laws and datums instead of turning them into editable coordinate dumps.++## Reproduced capabilities++| Lane | Witness and result |+| --- | --- |+| Nonlinear part pattern | `equation-plate`: Function x = -30mm + 5mm*n*n; four real through holes at X=-30,-25,-10,15mm. Normal validate and build accept. |+| Direct expression / Pow | Direct arithmetic in Series position and dimensionless Pow(n,2) both build. |+| Keyed part mapping | Changing pitch to 6mm changes coordinates, retaining the four Pattern keys/generated identities. |+| Irregular stations | Named distances 0,17,45mm build; reordering declarations retains each key's coordinates. |+| Function/Series assembly | Existing 12-fret witness builds and exports through the ordinary assembly pipeline. Resizing scale retains occurrence identities and changes transforms. |+| Growing Series | Count 12→13 retains the existing occurrence identities as a subset. Fixed Pad geometry hashes remain unchanged. |+| Point3 Series | Explicit Point3 values and frame-relative XYZ placement work; the twelfth member resolves to world Z=64mm. No implicit Point2 promotion. |+| Empty source | An empty typed Set yields zero mapped holes and builds stock. Zero-count Series is rejected under its existing 1–1024 contract. |+| Guitar | Actual root inspection accepts: 22 fret Parts; Concept collections contain six crossings, 22 fret sites and nine inlay stations. Current artifact has 99 material instances and 56 geometry definitions. |+| Other canonical owners | Record-array Hole and Slot, keyed Set→Feature, semantic Grid, partial radial feature symmetry and Scene Pattern all build/inspect successfully. Guitar also exercises SectionChain Patterns and repeated subassemblies. |++The nonlinear plate has exact compiler volume **39773.80532894153mm³** =+40000−72π and stock bounds [-50,-25,0] to [50,25,8]mm. This checks actual four-hole+geometry, not merely parser output. The assembly identity/hash comparison is+for the fixed Pad witness; changing fret-width arguments can intentionally+change the guitar's leaf geometry.++## Findings and ownership++### P01 — Part/assembly parameter admission differs (high priority)++**Observed:** part Series count/spacing literals build. A checked Static count+or spacing, at Model or module scope, is rejected. Equivalent assembly Static+count/scale references build. `ui-promoted-count` is the actual source downloaded+from Helios after its offered Make count a parameter action; it fails normally.+The working model is correctly retained, but the operation itself is not useful.++**Root cause:** Assembly's `CanonicalStaticAuthoring.ExpandAssemblyPatterns`+reads and substitutes checked scalar inputs before Concept points expansion.+Part `Expand` runs `ConceptPointAuthoring.Expand` without that same bound value+environment. The point owner expects literal integer bounds and scalar+expressions whose variables are only the Series index / Function parameters.++**Repair:** pass the existing checked lexical value environment to a shared+AST-based point/law binder. Resolve integer bounds as checked Int values before+limits are enforced. Resolve Length/Angle inputs through the existing scalar+owner. Do not add another UI evaluator or another global substitution pass.+Literal-only Series is not a sensible permanent engineering language rule.++### P02 — Unrelated Static captures a Function parameter (P0: wrong geometry)++**Observed:** `Distance(n: Int, scale: Length)` computes the fret law and is+called with `Distance(n,628mm)`. The baseline twelfth fret is [0,-314]mm local,+[0,344,62]mm world. Prepending `Static scale: Length = 100mm;` still validates,+builds and exports successfully, but changes that fret to [0,-50]mm local and+[0,608,62]mm world. Renaming only that unrelated Static to `catalogScale`+restores the correct result. This is accepted **wrong geometry**, not merely a+poor diagnostic or an invalid fixture.++`function-parameter-shadow-assembly` and its `-control` preserve the pair.+The Function argument remains 628mm in both. The module Static's 100mm has been+substituted into the Function body in place of its own bound parameter.++A related part symptom appears when a Model Static is named `pitch`: a module+Function's own `pitch` parameter use fails with+`firmament-binding-name-not-visible:pitch`. A differently named Static avoids+that visibility diagnostic, but still hits P01 when passed into a part Series.++**Root cause:** `Syntax/FirmamentDataBinding.Collect` creates parameter scopes+only for declarations with block bodies. An expression-bodied Function has no+block body. `Rewrite` visits its initializer in the outer scope rather than a+Function parameter scope. This can misclassify an ordinary bound parameter as+an inaccessible or captured compile-time value. In assembly, subsequent scalar+substitution replaces the misbound reference with the unrelated Static value;+Function type checking cannot recover the lost parameter binding.++**Repair:** establish parameter scope for expression-bodied declarations and+bind their initializer in that scope. This is lexical binding repair, not a+proposal to add closures or implicit global captures.++### P03 — Part inspection loses the author's collection name/provenance++**Observed:** the equation plate inspection names its Pattern source+`__ConceptPoints_6_Layout5_Sites`. Assembly expansion already maps generated Set+names back to the logical collection name. Concept point IR carries Recipe and+string provenance, but no original per-field source spans. Some displayed+association spans refer to rewritten/generated source.++**Repair:** retain original AST collection/law/application identities, original+source file/revision/spans and index/key provenance through the existing+expansion owner. Apply the logical-source projection consistently in part and+assembly inspection. Keep existing exported instance IDs; add explicit mappings+rather than renaming identities to make the UI look uniform.++### P04 — Rejections are honest but explanations are weak++**Observed:** invalid units, unknown `heigth`, zero/excessive count, unsupported+calls and recursive Function dependencies all reject. Part failures often lead+with `collection-syntax-invalid`, followed by `series-fields-invalid:Layout.Sites`+at the Model's document anchor. That does not say which bound/expression/field+failed. A known Function cycle code survives, but precise law/field location is+still lost. No validate/build admission disagreement appeared in the 32 probes. P02 shows+why agreement alone is insufficient: both paths admit the same wrong geometry.++**Repair:** produce structured diagnostics at the Function/Points/Series AST+owner, with the offending expression/field and enclosing collection. Preserve+existing stable codes where useful; transport a readable reason, expected type,+actual type and checked limit. Avoid cascading collection syntax errors after a+specific failed point recipe. Disclose generated-source provenance limits.++### P05 — Graph navigation exists; Pattern editing is incomplete++Real browser sequence:++1. Open equation plate: Ready, four holes, Function→Layout→Modify dependencies.+2. Select Pattern Drills: its inspector offers Source/Delete/+Field, but no+ layout selector, mapped recipe, instance count or key table. Right Inspector+ lands on the first generated Hole; all generated fields are read-only.+3. Navigate Layout→Points Sites→Series: literal count 4→3 builds three holes.+4. Make count a parameter: rejected source, last valid model retained. Revert+ restores the accepted source.+5. Select Function siteX: its generic Value expression is editable. Changing+ -30mm to -25mm builds; saved source retains the Series and Pattern.++Thus the graph is not wholly incapable of editing laws. It requires knowing+source structure, hides the Pattern's real dependencies, and has no joined+source-to-instance explanation. Function parameter names/types and calls are+not presented together with the editable law inputs.++**Repair:** a compiler-owned Pattern description projected into one inspector,+with Layout, Recipe and Instances sections and direct Edit source-owner links.+Opening an existing Pattern is as important as creating one.++### P06 — Generic field metadata offers invalid recipe combinations++Points with a Series child currently offers `Keys` as `Vector3`, even though+Keys belongs to the alternate equal-pitch recipe. Count offers parameter+promotion despite P01. Series index/keyPrefix are identifiers, count/first are+checked integers, and position is a typed point expression; generic text/scalar+controls cannot fully express those rules.++**Repair:** conditional metadata comes from the owning parsed/bound recipe.+Reuse existing schema metadata; add missing value distinctions at that owner.+Do not maintain a separate Helios list of valid recipe combinations.++### P07 — Layout preview is missing for this working Concept point source++The equation plate has a valid Layout point collection, but its Concepts toggle+is disabled. The current retained geometric Concept visualization does not+expose these evaluated point recipes as an editable layout preview.++**Repair:** project compiler-resolved keyed points in their explicit frame using+the existing gold Concept overlay. Hover/select shows key and source owner.+For Point2, use the selected application's resolved support/target frame; if+none is available, show a local 2D layout instead of inventing world XY. A+collection can have consumers in different frames. Avoid 1024 permanent labels;+use selection/hover. A connecting guide, if shown,+is a construction aid, not an inferred manufacturing curve. No JavaScript law+evaluation or viewport-derived coordinate authoring.++### P08 — The current grid helper is a creation adapter++It preserves a field-based Hole seed, emits a Feature and explicit keyed Set,+and maps the remaining copies. Its grid controls count the seed; the Pattern+it emits has one fewer mapped entry. It does not retain an authored grid recipe+that can simply be reopened with row/pitch controls.++**Repair boundary:** preserve that accepted source and identities. Open it as+an explicit keyed layout unless real recipe provenance exists. Never infer a+grid from approximate floating-point coordinates or turn an arbitrary Series+into a grid. A reusable parametric 2D grid recipe with durable row/column keys+is a separate bounded language decision; not a prerequisite for exposing the+already implemented equation/station capabilities.++## Proposed implementation++### Compiler / SDK++Extend the existing language-service/compiler projection with a Pattern+description joined from the original AST and admitted IR:++- Application ID, source file/revision, owner/target, producer kind and spans.+- Logical collection identity, source kind and recipe kind; checked field/input+ controls with reference-versus-literal state and explicit read-only reasons.+- Function references/signatures, positional call inputs and expression span.+- Typed Feature or Part/Subassembly recipe reference and authored argument spans.+- Generated keys/IDs, ordinals, values and frame, plus key→instance provenance.+- Count/identity policy, source consumers, diagnostics and admission level.++This is a projection over current owners, not another validator or expansion+engine. AST source structure alone must say ParsedNotBuilt; a built preview may+report admitted expansion/geometry facts. Compilation still checks geometry+capabilities and engineering conflicts. Keep existing tolerance/provenance+admission; do not erase typed tolerances or imply nonlinear uncertainty+propagation has been implemented.++Consume existing Function/Points/Series AST nodes in their binder and reuse+`FirmamentNumericEvaluation`'s AST evaluator. The current structural admission+and Pattern header parsing already use AST; ConceptPointAuthoring still+extracts Functions/point recipes with regex and rewrites source strings. Migrate+that bounded owner rather than installing another parser or rewrite layer.+Existing Feature, assembly, Scene and SectionChain lowerers stay authoritative.++### Helios workflow++**Pattern…** opens a pending transaction with three sections:++- **Layout:** use existing collection, explicit keyed values, equal spacing,+ named stations or equation Series where the source owner admits it. Show+ dimensionality, support frame, bound inputs and evaluated gold point preview.+ Preserve expressions/reference bindings. An advanced expression editor is+ appropriate; do not create a graph node for every multiplication.+- **Recipe:** choose an existing Feature for a part or a shared component+ definition for an assembly. Bind element fields to typed arguments and+ placement references. Changing a shared layout/Function shows its consumers.+- **Instances:** a read-only key/value/instance table. Selecting a generated+ feature leads back to Edit layout / Edit recipe / Edit law input. Changing+ first/keyPrefix warns of changed identities. Distinguish mapped count from a+ helper's external seed and from produced physical bodies.++Preview compiles the entire candidate project; Apply commits one source edit+transaction. Cancel/refused preview retain working source and geometry. Use the+existing ModelSession lifecycle, project context, compiler edits and Monaco+Undo/Redo. No hidden per-instance position overrides or baked coordinate caches.++For existing source, keep its actual layout form. Named stations stay stations;+Series stays a law; explicit Set stays explicit data. Legacy radial/linear+feature forms remain supported via their production owners and receive honest+read-only explanations where a visual adapter is not yet qualified.++### Recommended sequence / acceptance gate++1. Close P02 first: its paired witnesses must both yield -314mm local / 344mm+ world for the twelfth fret. Then close P01 with shared lexical value binding+ and original AST provenance.+ Test literal, Static, scoped Record/Template inputs and shadowing. Add P04+ precise diagnostics at that same owner.+2. Expose the Pattern description; close part/assembly inspection mismatch P03.+3. Implement reopen/edit of existing Set, Series and station applications and+ compiler-evaluated layout preview. Repair conditional controls P06.+4. Add create-from-existing-collection and new Series/station workflows, using+ pending Preview/Apply; preserve the current grid helper's seed semantics.+5. Qualify the nonlinear plate, Point3 assembly, existing grid, record Hole/Slot,+ radial/linear controls and full guitar through code and browser editing.+ Compare keys, source bindings, world transforms, topology and STEP leaf+ geometry where edits are placement-only. Run the full regression gate.++No user decision blocks that sequence. Optional later decisions are a durable+2D grid recipe, broader math builtins (including angle-safe trig), named/default+Function arguments, and explicit sparse exclusions. They are not prerequisites+and are not silently included in this proposal. General Function-returned+collections, recursion and a higher-order collection language are unnecessary.++## Evidence and qualification++- 32 source probes: 18 admitted, 14 rejected; validate/build agreement in all 32.+ One admitted source produces confirmed wrong geometry (P02); it is **not** a+ passing geometry witness. The paired control produces the correct geometry.+ Cases are classified as correct controls, admitted geometry defects, rejected+ binding defects, expected invalid inputs, or outside the Function contract.+- Seven existing canonical controls accepted, including full guitar and Scene.+- 62 focused existing tests passed.+- Release solution build passed with zero errors (existing warnings remain).+- Fast kernel lane: 1087 passed. Full serial solution gate: 5754 passed, zero+ failed/skipped, across 20 projects with discovered tests. FrictionLab.Tests+ reports no discovered tests and is not counted as a passing project.+- The independent shadowing regression assertion **fails as expected**:+ expected local [0,-314]mm, observed [0,-50]mm while admitted=true. Its expected+ coordinates are recorded durably in the fixture `expectations.json`.+ The existing full suite passes because it does not cover this counterexample.+- This is an audit/docs/specimen change; no new implementation unit tests or+ production AOT publish are claimed. Source probes exercise the real CLI and+ browser path in addition to the existing regression suites.+- Temporary browser tab and task-owned Vite host were closed after the run;+ .NET execution used disabled node reuse and shared compilation.+- Geometry/identity checks ran against actual CLI JSON; the browser count/law+ edits and failed promotion were saved as source evidence.++Sources: `fixtures/Regression/PatternAuthoringAudit/`. Raw JSON, STEP, source+hashes, screenshots and read-only reproduction/qualification scripts remain+ignored under `artifacts/local/pattern-authoring-audit/`. The public Patterns+walkthrough, syntax entry and point/Function guide now describe current behavior.+This audit does not claim its identified implementation defects are repaired.++Reproduction commands (PowerShell, repository root):++```powershell+dotnet build Aetheris.slnx -c Release -m:1 -nr:false -p:UseSharedCompilation=false+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter "Category!=SlowCorpus" -m:1 -nr:false -- RunConfiguration.MaxCpuCount=1+dotnet test Aetheris.slnx -c Release --no-build -m:1 -nr:false -- RunConfiguration.MaxCpuCount=1+aetheris validate fixtures/Regression/PatternAuthoringAudit/equation-plate.firmament --json+aetheris build fixtures/Regression/PatternAuthoringAudit/equation-plate.firmament --output artifacts/local/pattern-authoring-audit/equation-plate.step --json+aetheris inspect fixtures/Regression/PatternAuthoringAudit/equation-plate.firmament --json+aetheris asm inspect fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm --json+```++If aetheris is not on PATH, substitute+`dotnet ./Aetheris.CLI/bin/Release/net10.0/aetheris.dll` for that executable.+`run.py` retains input hashes and validate/build results; `canonical.py` collects+canonical domain witnesses; `qualify.py` checks the recorded geometry/identity facts; shadowing is recorded+as a known defect, not passed as correct geometry. These read-only harnesses and raw output are local run evidence, not new+language processors.diff --git a/docs/release/PATTERN-AUTHORING-IMPLEMENTATION-2026-10-20.md b/docs/release/PATTERN-AUTHORING-IMPLEMENTATION-2026-10-20.mdnew file mode 100644index 00000000..5dbeb033--- /dev/null+++ b/docs/release/PATTERN-AUTHORING-IMPLEMENTATION-2026-10-20.md@@ -0,0 +1,143 @@+# Pattern authoring — binding repair and visual editor++Date: 2026-10-20. Baselines: Aetheris `ad6dc5ce`, HeliosCAD `f038b19`.++This report supersedes the current-status statements in the preserved+[original audit](PATTERN-AUTHORING-AUDIT-2026-10-20.md).++## Repairs++| Finding | Repair and ownership |+| --- | --- |+| P01: part/assembly Static admission mismatch | Point recipes consume the existing checked compile-time environment, including Record leaves and Template specializations. Both owners use the AST numeric evaluator. |+| P02: same-named Static captures Function parameter | Expression-bodied declarations receive a parameter scope; initializers bind in it. The existing value-substitution owner respects expression-body parameter spans. Assembly resolves point/law expressions before transporting remaining frame values. |+| P03: generated source names/provenance | Part Pattern sources and association sources expose `Layout.Sites`, matching assembly. Keyed point IR retains optional original collection/member spans and recipe kind. Existing generated identities are unchanged. Unmapped expanded locations remain unavailable rather than invented. |+| P04: generic point/law errors | The AST owner emits readable, source-located diagnostics for invalid expressions, units, bounds, unknown fields, duplicate keys, cycles and budgets. Assembly preserves the existing outer diagnostic code and now transports the inner explanation and original location when available. |+| P05: disconnected Pattern UI | Compiler-owned `language.patterns` projection and a Layout / Recipe / Instances editor reopen existing applications and create new ones. Preview/Apply uses the existing transaction and ModelSession lifecycle. |+| P06: incompatible Keys suggestion | Completion and inspector omit Keys for Series/Stations, while retaining Keys for equal-step Linear layouts. Completion checks actual AST ownership so an `over Points` reference cannot masquerade as a Points declaration. |++The point/law owner now reads unified AST declarations, fields, calls and spans.+It does not add a parser route, regex dispatcher, field schema or JavaScript+expression evaluator. Existing Set/Pattern construction expansion and domain+geometry owners remain authoritative. AST spans delimit the remaining transport+to those owners. Functions remain pure scalar expressions, with existing typed+units, acyclic dependencies and finite evaluation budgets.++## Editor behavior++- Existing Series, named Stations, explicit points and keyed Sets remain their+ authored forms. Keyed Set entries have distinct authored-value controls; their+ evaluated rows remain read-only. Expression/reference edits do not flatten+ values into lists.+- New applications can use an existing collection, a Point2 equation Series or+ named Point2 Stations. A Feature selector seeds named, typed argument bindings;+ the keyed mapping is editable Firmament source. A component selector reuses+ existing definition expressions; explicit published source/target frames and+ a coordinate law generate ordinary component/Placement source.+- Read-only rows show keys, compiler values and expansion associations. The gold+ point plot is local 2D data. It does not guess a world plane or implicit Point3+ lift. Point3 values retain their type and coordinates in the table.+- Shared consumers are listed. Changing first, keyPrefix or explicit keys warns+ about identity changes. Imported law/recipe definitions stay in their owning+ document; the panel edits one document per transaction.+- Includes resolve through the existing module graph. Preview compiles the+ complete project snapshot; it is the admission gate. The layout projection+ reports `LayoutResolvedNotBuilt`, not a built solid.+- The existing grid helper is separately named **Grid seed hole…**, preserving+ its original external seed and count semantics.+- Legacy domain Pattern forms remain supported. Forms without a qualified finite+ editor adapter have an explicit read-only explanation.++Typed tolerance evidence is not silently reduced to a nominal point input.+Unsupported tolerance-bearing layout consumers reject. Material-feature and+explicit PMI tolerance handling remains in its existing owner.++## Qualification++- 38 source specimens: 28 admitted and ten rejected, with validate/build/export+ agreement. Invalid cases retain explicit failures; none were made green by+ changing their requested geometry.+- Both shadowing witnesses produce Fret12 local `[0,-314]`mm and world+ `[0,344,62]`mm, identical occurrence transforms and leaf STEP hashes.+- Nonlinear plate: four holes at X = -30,-25,-10,15mm; exact volume+ 39773.80532894153mm³ = 40000−72π; unchanged stock bounds. Pitch edits retain keys.+- Named station reorder retains each keyed coordinate. Growing assembly count+ retains prior identities; changing scale moves occurrences with unchanged+ fixed Pad leaf geometry. Point3 witness retains world Z = 64mm.+- Seven canonical controls passed: Record-array Hole/Slot, keyed Feature mapping,+ semantic Grid, radial symmetry, Scene and full guitar. Guitar's 56 leaf STEP+ hashes and occurrence transforms match the pre-repair audit baseline; 22 fret+ Parts, six crossings and nine inlay stations remain present.+- Browser dogfood: reopen/edit law and count, refuse excessive count, Cancel,+ Apply and single-step Undo/Redo; create/reopen a second Series Pattern and a+ named-Stations Pattern. Actual saved browser sources produce five and seven+ holes while preserving their earlier named holes.+- Helios: 145 tests passed in 34 files; TypeScript check and development-mode bundle+ passed. SDK transport/selection/measurement tests passed (19). Production AOT+ publishing and a packaged Cadmata desktop run are not claimed.++- Final Release solution build: zero errors (existing build warnings remain).+- Focused binding/point/Stations/language-service checks: 82 passed.+- Fast kernel lane: 1087 passed. Full serial solution gate: **5777 passed,+ zero failed/skipped across 20 projects with discovered tests**. FrictionLab.Tests+ reports no discovered tests and is not counted as a passing project.+- The completed documentation link check passed separately after the SDK API+ reference update.+- Actual browser Set edit retained First/Second keys. The browser-created assembly+ Pattern exported through normal AP242 build: 32 tree occurrences, including two+ added material components. All previous 27 occurrences retain their transforms,+ both leaf STEP hashes remain unchanged, and the new world origins are+ `[0,20,0]` and `[10,20,0]`mm. Component definitions are shared.+- Browser-created five/seven-hole parts have authoritative exact volumes+ 39717.25666117692mm³ and 39604.159325647684mm³ respectively, matching stock minus+ five/seven diameter-3mm through holes.++The final 38-source CLI rerun and all seven canonical controls passed their+classified outcomes against the final build. The guitar still matches the frozen+audit baseline. No production AOT publish or packaged native desktop execution+is implied by the web/native compiler checks. An intermediate run found+an empty-Stations rejection missing during migration; that check was restored.+Another run read a report link before its new target had been written; the final+qualification runs against the completed documentation tree.++Evidence remains ignored under `artifacts/local/`: `pattern-*-*.log`, the+`pattern-authoring-audit/` CLI JSON/STEP results, saved `pattern-editor-*.firmament`+and screenshots. Durable source specimens live in+`fixtures/Regression/PatternAuthoringAudit/`; regression tests are in+`FirmamentPatternBindingTests`, `ConceptPointAuthoringTests` and+`LinearStationAuthoringTests`.++[Pattern instance view](../../artifacts/local/pattern-editor-stations.png),+[assembly recipe view](../../artifacts/local/pattern-editor-assembly.png).+Temporary browser tabs, preview ModelSessions and task-owned Vite hosts were+closed. No .NET/testhost/MSBuild/compiler-server processes remained at the end.+A [review-only cleanup script](../../artifacts/local/pattern-cleanup-downloads.ps1)+can remove unchanged test downloads. No test downloads were deleted by this task.++The code-quality pass also restored rejection of empty Stations and rejects+unconsumed placement/contract headers on point-collection owners. The AST reader+must not broaden recognition and then erase a requested frame. This restriction+is local to Points recipes; geometric Concept Struct frames retain their owner.++## Deliberate limits++No new trigonometric library, implicit global Function capture, named/default+Function arguments, sparse-exclusion language, general loop runtime or constraint+solver is introduced. The initial new-layout controls author Point2; existing+Point3 layouts can be edited and mapped. Component frames and coordinate laws remain explicit source expressions; the+editor does not add another mate/placement solver. A layout's+local plot is deliberately separate from physical world placement.+++## Verdict++**Success.** The reproduced parameter capture and part/assembly binding mismatch+are repaired through the existing AST/value owners. Patterns can be authored and+edited without baking their laws or keyed layouts, and actual compiler Preview+admits their geometry before one source transaction is applied. Geometry,+identity and provenance controls pass, including the original wrong-geometry+witness and frozen guitar comparison.++No user decision is required for this pass. The bounded limits above remain+explicit; this does not claim a broader math library, implicit frame inference,+Template-specialization debugger or a new geometry capability.diff --git a/fixtures/Regression/PatternAuthoringAudit/README.md b/fixtures/Regression/PatternAuthoringAudit/README.mdnew file mode 100644index 00000000..257fa766--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/README.md@@ -0,0 +1,83 @@+# Pattern authoring audit specimens++These preserve the original audit and repair witnesses. The table below records+**audit-time** behavior, not the repaired compiler. Rejected bug reproducers were+not invalid engineering intent. The original admitted geometry defect is now+covered by a required geometry regression.++The report is `docs/release/PATTERN-AUTHORING-AUDIT-2026-10-20.md`.+`expectations.json` records the independent expected fret coordinates for the+critical Function-parameter shadowing pair. Both must produce local [0,-314]mm+and world [0,344,62]mm. Before repair, the same-named Static specimen produced+[0,-50]mm and [0,608,62]mm even though its Function call still supplies 628mm.++| Specimen | Audit admission | Original disposition |+| --- | --- | --- |+| `equation-plate-modern-math` | Admitted | Correct accepted control |+| `equation-plate-resized` | Admitted | Correct accepted control |+| `equation-plate` | Admitted | Correct accepted control |+| `function-captures-static` | Rejected | Outside current Function contract |+| `function-comment` | Admitted | Correct accepted control |+| `function-cycle` | Rejected | Expected invalid-input rejection |+| `function-named-arguments` | Rejected | Outside current Function contract |+| `function-parameter-shadow-assembly-control` | Admitted | Correct accepted control |+| `function-parameter-shadow-assembly` | Admitted | Admitted wrong geometry: P0 Function parameter capture |+| `keyed-stations-plate` | Admitted | Correct accepted control |+| `keyed-stations-reordered` | Admitted | Correct accepted control |+| `series-assembly-count-static` | Admitted | Correct accepted control |+| `series-assembly-count` | Admitted | Correct accepted control |+| `series-assembly-pitch-static` | Admitted | Correct accepted control |+| `series-assembly-resized` | Admitted | Correct accepted control |+| `series-assembly` | Admitted | Correct accepted control |+| `series-count-static` | Rejected | Rejected binding defect reproducer |+| `series-count-too-large` | Rejected | Expected invalid-input rejection |+| `series-count-zero` | Rejected | Expected invalid-input rejection |+| `series-empty-set` | Admitted | Correct accepted control |+| `series-module-static` | Rejected | Rejected binding defect reproducer |+| `series-part-count-static-module` | Rejected | Rejected binding defect reproducer |+| `series-pitch-static-unshadowed` | Rejected | Rejected binding defect reproducer |+| `series-pitch-static` | Rejected | Rejected binding defect reproducer |+| `series-point3-assembly` | Admitted | Correct accepted control |+| `series-position-arithmetic` | Admitted | Correct accepted control |+| `series-string-reference` | Admitted | Correct accepted control |+| `series-trigonometry` | Rejected | Outside current Function contract |+| `series-unknown-field` | Rejected | Expected invalid-input rejection |+| `series-wrong-unit` | Rejected | Expected invalid-input rejection |+| `ui-edited-law` | Admitted | Correct accepted control |+| `ui-promoted-count` | Rejected | Rejected binding defect reproducer |++`ui-promoted-count` is actual source saved after Helios Make count a parameter.+`ui-edited-law` is recovered browser source after literal count 3 and a Function+expression edit. Other sources are minimized CLI probes. All 32 agree between+normal validate and build admission in the original audit; admission alone did+not close the admitted geometry defect. Raw JSON, source hashes, STEP and screenshots remain under ignored+`artifacts/local/pattern-authoring-audit/`.+++## Repair qualification++Both Function-shadowing specimens must now produce the expected coordinates,+with identical occurrence transforms and leaf geometry. The six rejected binding+witnesses (`series-count-static`, `series-pitch-static`,+`series-pitch-static-unshadowed`, `series-module-static`,+`series-part-count-static-module`, `ui-promoted-count`) must now build correctly.++Additional specimens qualify scoped values and tolerance honesty:++| Specimen | Required result |+| --- | --- |+| `series-record-inputs` | Four original keyed holes using checked Record fields |+| `series-template-inputs` | Same layout after typed Template specialization |+| `ui-created-series` | Actual browser-created second Pattern: five holes total, original law/keys retained |+| `ui-created-stations` | Actual browser-created named Stations Pattern: seven holes total, earlier keys retained |+| `series-owner-frame-rejected` | Reject an unconsumed `on XZ` owner header; never erase it into XY geometry |+| `series-tolerance-input-rejected` | Reject unsupported tolerated point input; never discard its tolerance |++The repaired 38-source corpus expects 28 admitted and ten accurately rejected.+Pure Functions still require positional explicit arguments; implicit Static+capture, named Function arguments and unimplemented trigonometry remain outside+the contract. Sources were not rewritten to hide the original failures.++Durable tests live in `FirmamentPatternBindingTests`, `ConceptPointAuthoringTests`+and `LinearStationAuthoringTests`. The implementation report is+`docs/release/PATTERN-AUTHORING-IMPLEMENTATION-2026-10-20.md`.diff --git a/fixtures/Regression/PatternAuthoringAudit/equation-plate-modern-math.firmament b/fixtures/Regression/PatternAuthoringAudit/equation-plate-modern-math.firmamentnew file mode 100644index 00000000..9792201f--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/equation-plate-modern-math.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * Pow(n,2);+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/equation-plate-resized.firmament b/fixtures/Regression/PatternAuthoringAudit/equation-plate-resized.firmamentnew file mode 100644index 00000000..4c88cae0--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/equation-plate-resized.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,6mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/equation-plate.firmament b/fixtures/Regression/PatternAuthoringAudit/equation-plate.firmamentnew file mode 100644index 00000000..4ffd904d--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/equation-plate.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/expectations.json b/fixtures/Regression/PatternAuthoringAudit/expectations.jsonnew file mode 100644index 00000000..ee8e0d6a--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/expectations.json@@ -0,0 +1,21 @@+{+ "schema": "pattern-authoring-audit/1",+ "criticalRegression": {+ "source": "function-parameter-shadow-assembly.firmament",+ "control": "function-parameter-shadow-assembly-control.firmament",+ "expectedAdmission": true,+ "logicalPoint": "Board.Frets.Fret12",+ "expectedLocalMm": [+ 0,+ -314+ ],+ "instance": "PointWitness.Frets.Fret12.Fret",+ "expectedWorldTranslationMm": [+ 0,+ 344,+ 62+ ],+ "currentDisposition": "AdmittedWrongGeometry",+ "reason": "A same-named module Static must not replace the Function parameter supplied as 628mm."+ }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/function-captures-static.firmament b/fixtures/Regression/PatternAuthoringAudit/function-captures-static.firmamentnew file mode 100644index 00000000..1c854b4e--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/function-captures-static.firmament@@ -0,0 +1,16 @@+Static pitch: Length = 5mm;+Function siteX(n: Int, spacing: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/function-comment.firmament b/fixtures/Regression/PatternAuthoringAudit/function-comment.firmamentnew file mode 100644index 00000000..6a34b21e--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/function-comment.firmament@@ -0,0 +1,16 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+// Function expressions are pure.+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/function-cycle.firmament b/fixtures/Regression/PatternAuthoringAudit/function-cycle.firmamentnew file mode 100644index 00000000..cbcd8e86--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/function-cycle.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = siteX(n,pitch);+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/function-named-arguments.firmament b/fixtures/Regression/PatternAuthoringAudit/function-named-arguments.firmamentnew file mode 100644index 00000000..999d7577--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/function-named-arguments.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n: n, pitch: 5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/function-parameter-shadow-assembly-control.firmament b/fixtures/Regression/PatternAuthoringAudit/function-parameter-shadow-assembly-control.firmamentnew file mode 100644index 00000000..3b3b6122--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/function-parameter-shadow-assembly-control.firmament@@ -0,0 +1,41 @@+Static catalogScale: Length = 100mm;+Function Distance(n: Int, scale: Length) -> Length = scale * (1.0 - Pow(2.0, -n / 12.0));+Function PadHeight(h: Length) -> Length = h + 1mm;+Concept Struct Nut {+ Points<Point2> Crossings {+ keys: [Bass, Middle, Treble];+ Linear { start: Point2(-18mm,0mm); step: [18mm,0mm]; }+ }+ Points<Point3> Supports {+ Left: Point3(-18mm,0mm,2mm);+ Right: Point3(18mm,0mm,2mm);+ }+}+Concept Struct Board {+ Points<Point2> Frets {+ Series { index: n; first: 1; count: 12; keyPrefix: Fret;+ position: Point2(0mm, -Distance(n,628mm)); }+ }+}+Template<H: Length> Struct Pad {+ Rect2 Outline { center: [0mm,0mm]; size: [4mm,2mm] }+ Profile P { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { profile: P; from: 0mm; to: H }+ expose { Semantic Bottom { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }+}+Assembly PointWitness {+ <Assembly PointWitness>+ Pattern Frets over Board.Frets {+ point => <Part Fret = Pad<H:PadHeight(1mm)>>+ Placement { from: Bottom.Frame; to: BoardSeat.Frame;+ translateLocal: [point.Position.X,point.Position.Y,0mm]; }+ </Part>+ }+ <Part Bass = Pad<H:1mm>>+ Placement { from: Bottom.Frame; to: World;+ translateLocal: [Nut.Crossings.Bass.X,Nut.Crossings.Bass.Y,Nut.Supports.Left.Z]; }+ </Part>+ </Assembly>+ FrameTransform BoardSeat { from: World; translateLocal: [0mm,658mm,62mm]; }+ anchor: PointWitness;+}diff --git a/fixtures/Regression/PatternAuthoringAudit/function-parameter-shadow-assembly.firmament b/fixtures/Regression/PatternAuthoringAudit/function-parameter-shadow-assembly.firmamentnew file mode 100644index 00000000..6614814b--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/function-parameter-shadow-assembly.firmament@@ -0,0 +1,41 @@+Static scale: Length = 100mm;+Function Distance(n: Int, scale: Length) -> Length = scale * (1.0 - Pow(2.0, -n / 12.0));+Function PadHeight(h: Length) -> Length = h + 1mm;+Concept Struct Nut {+ Points<Point2> Crossings {+ keys: [Bass, Middle, Treble];+ Linear { start: Point2(-18mm,0mm); step: [18mm,0mm]; }+ }+ Points<Point3> Supports {+ Left: Point3(-18mm,0mm,2mm);+ Right: Point3(18mm,0mm,2mm);+ }+}+Concept Struct Board {+ Points<Point2> Frets {+ Series { index: n; first: 1; count: 12; keyPrefix: Fret;+ position: Point2(0mm, -Distance(n,628mm)); }+ }+}+Template<H: Length> Struct Pad {+ Rect2 Outline { center: [0mm,0mm]; size: [4mm,2mm] }+ Profile P { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { profile: P; from: 0mm; to: H }+ expose { Semantic Bottom { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }+}+Assembly PointWitness {+ <Assembly PointWitness>+ Pattern Frets over Board.Frets {+ point => <Part Fret = Pad<H:PadHeight(1mm)>>+ Placement { from: Bottom.Frame; to: BoardSeat.Frame;+ translateLocal: [point.Position.X,point.Position.Y,0mm]; }+ </Part>+ }+ <Part Bass = Pad<H:1mm>>+ Placement { from: Bottom.Frame; to: World;+ translateLocal: [Nut.Crossings.Bass.X,Nut.Crossings.Bass.Y,Nut.Supports.Left.Z]; }+ </Part>+ </Assembly>+ FrameTransform BoardSeat { from: World; translateLocal: [0mm,658mm,62mm]; }+ anchor: PointWitness;+}diff --git a/fixtures/Regression/PatternAuthoringAudit/keyed-stations-plate.firmament b/fixtures/Regression/PatternAuthoringAudit/keyed-stations-plate.firmamentnew file mode 100644index 00000000..7668d074--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/keyed-stations-plate.firmament@@ -0,0 +1,14 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Linear { start: Point2(-30mm,0mm); direction: [1,0]; Stations { First: 0mm; Middle: 17mm; Last: 45mm; } }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/keyed-stations-reordered.firmament b/fixtures/Regression/PatternAuthoringAudit/keyed-stations-reordered.firmamentnew file mode 100644index 00000000..d9f2ff27--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/keyed-stations-reordered.firmament@@ -0,0 +1,14 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Linear { start: Point2(-30mm,0mm); direction: [1,0]; Stations { Last: 45mm; First: 0mm; Middle: 17mm; } }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-assembly-count-static.firmament b/fixtures/Regression/PatternAuthoringAudit/series-assembly-count-static.firmamentnew file mode 100644index 00000000..78bfcb78--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-assembly-count-static.firmament@@ -0,0 +1,41 @@+Static fretCount: Int = 12;+Function Distance(n: Int, scale: Length) -> Length = scale * (1.0 - Pow(2.0, -n / 12.0));+Function PadHeight(h: Length) -> Length = h + 1mm;+Concept Struct Nut {+ Points<Point2> Crossings {+ keys: [Bass, Middle, Treble];+ Linear { start: Point2(-18mm,0mm); step: [18mm,0mm]; }+ }+ Points<Point3> Supports {+ Left: Point3(-18mm,0mm,2mm);+ Right: Point3(18mm,0mm,2mm);+ }+}+Concept Struct Board {+ Points<Point2> Frets {+ Series { index: n; first: 1; count: fretCount; keyPrefix: Fret;+ position: Point2(0mm, -Distance(n,628mm)); }+ }+}+Template<H: Length> Struct Pad {+ Rect2 Outline { center: [0mm,0mm]; size: [4mm,2mm] }+ Profile P { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { profile: P; from: 0mm; to: H }+ expose { Semantic Bottom { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }+}+Assembly PointWitness {+ <Assembly PointWitness>+ Pattern Frets over Board.Frets {+ point => <Part Fret = Pad<H:PadHeight(1mm)>>+ Placement { from: Bottom.Frame; to: BoardSeat.Frame;+ translateLocal: [point.Position.X,point.Position.Y,0mm]; }+ </Part>+ }+ <Part Bass = Pad<H:1mm>>+ Placement { from: Bottom.Frame; to: World;+ translateLocal: [Nut.Crossings.Bass.X,Nut.Crossings.Bass.Y,Nut.Supports.Left.Z]; }+ </Part>+ </Assembly>+ FrameTransform BoardSeat { from: World; translateLocal: [0mm,658mm,62mm]; }+ anchor: PointWitness;+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-assembly-count.firmament b/fixtures/Regression/PatternAuthoringAudit/series-assembly-count.firmamentnew file mode 100644index 00000000..0c14ce30--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-assembly-count.firmament@@ -0,0 +1,40 @@+Function Distance(n: Int, scale: Length) -> Length = scale * (1.0 - Pow(2.0, -n / 12.0));+Function PadHeight(h: Length) -> Length = h + 1mm;+Concept Struct Nut {+ Points<Point2> Crossings {+ keys: [Bass, Middle, Treble];+ Linear { start: Point2(-18mm,0mm); step: [18mm,0mm]; }+ }+ Points<Point3> Supports {+ Left: Point3(-18mm,0mm,2mm);+ Right: Point3(18mm,0mm,2mm);+ }+}+Concept Struct Board {+ Points<Point2> Frets {+ Series { index: n; first: 1; count: 13; keyPrefix: Fret;+ position: Point2(0mm, -Distance(n,628mm)); }+ }+}+Template<H: Length> Struct Pad {+ Rect2 Outline { center: [0mm,0mm]; size: [4mm,2mm] }+ Profile P { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { profile: P; from: 0mm; to: H }+ expose { Semantic Bottom { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }+}+Assembly PointWitness {+ <Assembly PointWitness>+ Pattern Frets over Board.Frets {+ point => <Part Fret = Pad<H:PadHeight(1mm)>>+ Placement { from: Bottom.Frame; to: BoardSeat.Frame;+ translateLocal: [point.Position.X,point.Position.Y,0mm]; }+ </Part>+ }+ <Part Bass = Pad<H:1mm>>+ Placement { from: Bottom.Frame; to: World;+ translateLocal: [Nut.Crossings.Bass.X,Nut.Crossings.Bass.Y,Nut.Supports.Left.Z]; }+ </Part>+ </Assembly>+ FrameTransform BoardSeat { from: World; translateLocal: [0mm,658mm,62mm]; }+ anchor: PointWitness;+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-assembly-pitch-static.firmament b/fixtures/Regression/PatternAuthoringAudit/series-assembly-pitch-static.firmamentnew file mode 100644index 00000000..7007f4be--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-assembly-pitch-static.firmament@@ -0,0 +1,41 @@+Static scale: Length = 628mm;+Function Distance(n: Int, scale: Length) -> Length = scale * (1.0 - Pow(2.0, -n / 12.0));+Function PadHeight(h: Length) -> Length = h + 1mm;+Concept Struct Nut {+ Points<Point2> Crossings {+ keys: [Bass, Middle, Treble];+ Linear { start: Point2(-18mm,0mm); step: [18mm,0mm]; }+ }+ Points<Point3> Supports {+ Left: Point3(-18mm,0mm,2mm);+ Right: Point3(18mm,0mm,2mm);+ }+}+Concept Struct Board {+ Points<Point2> Frets {+ Series { index: n; first: 1; count: 12; keyPrefix: Fret;+ position: Point2(0mm, -Distance(n,scale)); }+ }+}+Template<H: Length> Struct Pad {+ Rect2 Outline { center: [0mm,0mm]; size: [4mm,2mm] }+ Profile P { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { profile: P; from: 0mm; to: H }+ expose { Semantic Bottom { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }+}+Assembly PointWitness {+ <Assembly PointWitness>+ Pattern Frets over Board.Frets {+ point => <Part Fret = Pad<H:PadHeight(1mm)>>+ Placement { from: Bottom.Frame; to: BoardSeat.Frame;+ translateLocal: [point.Position.X,point.Position.Y,0mm]; }+ </Part>+ }+ <Part Bass = Pad<H:1mm>>+ Placement { from: Bottom.Frame; to: World;+ translateLocal: [Nut.Crossings.Bass.X,Nut.Crossings.Bass.Y,Nut.Supports.Left.Z]; }+ </Part>+ </Assembly>+ FrameTransform BoardSeat { from: World; translateLocal: [0mm,658mm,62mm]; }+ anchor: PointWitness;+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-assembly-resized.firmament b/fixtures/Regression/PatternAuthoringAudit/series-assembly-resized.firmamentnew file mode 100644index 00000000..68b18bae--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-assembly-resized.firmament@@ -0,0 +1,40 @@+Function Distance(n: Int, scale: Length) -> Length = scale * (1.0 - Pow(2.0, -n / 12.0));+Function PadHeight(h: Length) -> Length = h + 1mm;+Concept Struct Nut {+ Points<Point2> Crossings {+ keys: [Bass, Middle, Treble];+ Linear { start: Point2(-18mm,0mm); step: [18mm,0mm]; }+ }+ Points<Point3> Supports {+ Left: Point3(-18mm,0mm,2mm);+ Right: Point3(18mm,0mm,2mm);+ }+}+Concept Struct Board {+ Points<Point2> Frets {+ Series { index: n; first: 1; count: 12; keyPrefix: Fret;+ position: Point2(0mm, -Distance(n,630mm)); }+ }+}+Template<H: Length> Struct Pad {+ Rect2 Outline { center: [0mm,0mm]; size: [4mm,2mm] }+ Profile P { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { profile: P; from: 0mm; to: H }+ expose { Semantic Bottom { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }+}+Assembly PointWitness {+ <Assembly PointWitness>+ Pattern Frets over Board.Frets {+ point => <Part Fret = Pad<H:PadHeight(1mm)>>+ Placement { from: Bottom.Frame; to: BoardSeat.Frame;+ translateLocal: [point.Position.X,point.Position.Y,0mm]; }+ </Part>+ }+ <Part Bass = Pad<H:1mm>>+ Placement { from: Bottom.Frame; to: World;+ translateLocal: [Nut.Crossings.Bass.X,Nut.Crossings.Bass.Y,Nut.Supports.Left.Z]; }+ </Part>+ </Assembly>+ FrameTransform BoardSeat { from: World; translateLocal: [0mm,658mm,62mm]; }+ anchor: PointWitness;+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-assembly.firmament b/fixtures/Regression/PatternAuthoringAudit/series-assembly.firmamentnew file mode 100644index 00000000..d24c4225--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-assembly.firmament@@ -0,0 +1,40 @@+Function Distance(n: Int, scale: Length) -> Length = scale * (1.0 - Pow(2.0, -n / 12.0));+Function PadHeight(h: Length) -> Length = h + 1mm;+Concept Struct Nut {+ Points<Point2> Crossings {+ keys: [Bass, Middle, Treble];+ Linear { start: Point2(-18mm,0mm); step: [18mm,0mm]; }+ }+ Points<Point3> Supports {+ Left: Point3(-18mm,0mm,2mm);+ Right: Point3(18mm,0mm,2mm);+ }+}+Concept Struct Board {+ Points<Point2> Frets {+ Series { index: n; first: 1; count: 12; keyPrefix: Fret;+ position: Point2(0mm, -Distance(n,628mm)); }+ }+}+Template<H: Length> Struct Pad {+ Rect2 Outline { center: [0mm,0mm]; size: [4mm,2mm] }+ Profile P { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { profile: P; from: 0mm; to: H }+ expose { Semantic Bottom { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }+}+Assembly PointWitness {+ <Assembly PointWitness>+ Pattern Frets over Board.Frets {+ point => <Part Fret = Pad<H:PadHeight(1mm)>>+ Placement { from: Bottom.Frame; to: BoardSeat.Frame;+ translateLocal: [point.Position.X,point.Position.Y,0mm]; }+ </Part>+ }+ <Part Bass = Pad<H:1mm>>+ Placement { from: Bottom.Frame; to: World;+ translateLocal: [Nut.Crossings.Bass.X,Nut.Crossings.Bass.Y,Nut.Supports.Left.Z]; }+ </Part>+ </Assembly>+ FrameTransform BoardSeat { from: World; translateLocal: [0mm,658mm,62mm]; }+ anchor: PointWitness;+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-count-static.firmament b/fixtures/Regression/PatternAuthoringAudit/series-count-static.firmamentnew file mode 100644index 00000000..bbde8ba7--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-count-static.firmament@@ -0,0 +1,16 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Static siteCount: Int = 4;+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: siteCount; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-count-too-large.firmament b/fixtures/Regression/PatternAuthoringAudit/series-count-too-large.firmamentnew file mode 100644index 00000000..0dd30ca8--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-count-too-large.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 1025; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-count-zero.firmament b/fixtures/Regression/PatternAuthoringAudit/series-count-zero.firmamentnew file mode 100644index 00000000..7de48600--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-count-zero.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 0; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-empty-set.firmament b/fixtures/Regression/PatternAuthoringAudit/series-empty-set.firmamentnew file mode 100644index 00000000..a065f8ce--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-empty-set.firmament@@ -0,0 +1,9 @@+Model EquationPlate {+ units: mm+ Static emptySites: Set<Point2> { }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over emptySites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-module-static.firmament b/fixtures/Regression/PatternAuthoringAudit/series-module-static.firmamentnew file mode 100644index 00000000..be552658--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-module-static.firmament@@ -0,0 +1,16 @@+Static spacing: Length = 5mm;+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,spacing),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-owner-frame-rejected.firmament b/fixtures/Regression/PatternAuthoringAudit/series-owner-frame-rejected.firmamentnew file mode 100644index 00000000..4d7b3c85--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-owner-frame-rejected.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout on XZ {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-part-count-static-module.firmament b/fixtures/Regression/PatternAuthoringAudit/series-part-count-static-module.firmamentnew file mode 100644index 00000000..83e9f144--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-part-count-static-module.firmament@@ -0,0 +1,16 @@+Static siteCount: Int = 4;+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: siteCount; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-pitch-static-unshadowed.firmament b/fixtures/Regression/PatternAuthoringAudit/series-pitch-static-unshadowed.firmamentnew file mode 100644index 00000000..49e1f485--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-pitch-static-unshadowed.firmament@@ -0,0 +1,16 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Static spacing: Length = 5mm;+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,spacing),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-pitch-static.firmament b/fixtures/Regression/PatternAuthoringAudit/series-pitch-static.firmamentnew file mode 100644index 00000000..80ccc249--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-pitch-static.firmament@@ -0,0 +1,16 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Static pitch: Length = 5mm;+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,pitch),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-point3-assembly.firmament b/fixtures/Regression/PatternAuthoringAudit/series-point3-assembly.firmamentnew file mode 100644index 00000000..8e58ae40--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-point3-assembly.firmament@@ -0,0 +1,40 @@+Function Distance(n: Int, scale: Length) -> Length = scale * (1.0 - Pow(2.0, -n / 12.0));+Function PadHeight(h: Length) -> Length = h + 1mm;+Concept Struct Nut {+ Points<Point2> Crossings {+ keys: [Bass, Middle, Treble];+ Linear { start: Point2(-18mm,0mm); step: [18mm,0mm]; }+ }+ Points<Point3> Supports {+ Left: Point3(-18mm,0mm,2mm);+ Right: Point3(18mm,0mm,2mm);+ }+}+Concept Struct Board {+ Points<Point3> Frets {+ Series { index: n; first: 1; count: 12; keyPrefix: Fret;+ position: Point3(0mm, -Distance(n,628mm),2mm); }+ }+}+Template<H: Length> Struct Pad {+ Rect2 Outline { center: [0mm,0mm]; size: [4mm,2mm] }+ Profile P { Loop Outer { Outline |> TraceLoop } }+ Extrude Body { profile: P; from: 0mm; to: H }+ expose { Semantic Bottom { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; } }+}+Assembly PointWitness {+ <Assembly PointWitness>+ Pattern Frets over Board.Frets {+ point => <Part Fret = Pad<H:PadHeight(1mm)>>+ Placement { from: Bottom.Frame; to: BoardSeat.Frame;+ translateLocal: [point.Position.X,point.Position.Y,point.Position.Z]; }+ </Part>+ }+ <Part Bass = Pad<H:1mm>>+ Placement { from: Bottom.Frame; to: World;+ translateLocal: [Nut.Crossings.Bass.X,Nut.Crossings.Bass.Y,Nut.Supports.Left.Z]; }+ </Part>+ </Assembly>+ FrameTransform BoardSeat { from: World; translateLocal: [0mm,658mm,62mm]; }+ anchor: PointWitness;+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-position-arithmetic.firmament b/fixtures/Regression/PatternAuthoringAudit/series-position-arithmetic.firmamentnew file mode 100644index 00000000..45ea4de8--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-position-arithmetic.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(-30mm + 5mm * n * n,0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-record-inputs.firmament b/fixtures/Regression/PatternAuthoringAudit/series-record-inputs.firmamentnew file mode 100644index 00000000..76fefdad--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-record-inputs.firmament@@ -0,0 +1,17 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Record LayoutSpec { pitch: Length; amount: Int; }+ Static spec: LayoutSpec = LayoutSpec { pitch: 5mm; amount: 4; }+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: spec.amount; keyPrefix: Site;+ position: Point2(siteX(n,spec.pitch),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-string-reference.firmament b/fixtures/Regression/PatternAuthoringAudit/series-string-reference.firmamentnew file mode 100644index 00000000..213ba581--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-string-reference.firmament@@ -0,0 +1,16 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Static note: String = "siteX(2,5mm)";+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-template-inputs.firmament b/fixtures/Regression/PatternAuthoringAudit/series-template-inputs.firmamentnew file mode 100644index 00000000..3a8ca986--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-template-inputs.firmament@@ -0,0 +1,19 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Record LayoutSpec { pitch: Length; amount: Int; }+Static chosen: LayoutSpec = LayoutSpec { pitch: 5mm; amount: 4; }+Template<spec: LayoutSpec> Model Plate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: spec.amount; keyPrefix: Site;+ position: Point2(siteX(n,spec.pitch),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}++Model EquationPlate = Plate<spec: chosen>diff --git a/fixtures/Regression/PatternAuthoringAudit/series-tolerance-input-rejected.firmament b/fixtures/Regression/PatternAuthoringAudit/series-tolerance-input-rejected.firmamentnew file mode 100644index 00000000..d5e69d54--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-tolerance-input-rejected.firmament@@ -0,0 +1,17 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Record LayoutSpec { pitch: Length; amount: Int; }+ Static spec: LayoutSpec = LayoutSpec { pitch: 5mm tol 0.1mm; amount: 4; }+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: spec.amount; keyPrefix: Site;+ position: Point2(siteX(n,spec.pitch),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-trigonometry.firmament b/fixtures/Regression/PatternAuthoringAudit/series-trigonometry.firmamentnew file mode 100644index 00000000..2fac177a--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-trigonometry.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(5mm * Sin(n),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-unknown-field.firmament b/fixtures/Regression/PatternAuthoringAudit/series-unknown-field.firmamentnew file mode 100644index 00000000..a185d1d9--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-unknown-field.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; heigth: 3mm; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/series-wrong-unit.firmament b/fixtures/Regression/PatternAuthoringAudit/series-wrong-unit.firmamentnew file mode 100644index 00000000..07ec2829--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/series-wrong-unit.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 4; keyPrefix: Site;+ position: Point2(siteX(n,5deg),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/ui-created-series.firmament b/fixtures/Regression/PatternAuthoringAudit/ui-created-series.firmamentnew file mode 100644index 00000000..a4d1672a--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/ui-created-series.firmament@@ -0,0 +1,16 @@+Function siteX(n: Int, pitch: Length) -> Length = -25mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 3; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } Pattern Copies over Layout2.Sites { point => Drill(center: point) } }+ Concept Struct Layout2 { Points<Point2> Sites { Series { index: n; first: 0; count: 2; keyPrefix: Site; position: Point2(10mm * n, 10mm); } } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/ui-created-stations.firmament b/fixtures/Regression/PatternAuthoringAudit/ui-created-stations.firmamentnew file mode 100644index 00000000..52882ce9--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/ui-created-stations.firmament@@ -0,0 +1,17 @@+Function siteX(n: Int, pitch: Length) -> Length = -25mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 3; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } Pattern Copies over Layout2.Sites { point => Drill(center: point) } Pattern Copies2 over Layout3.Sites { point => Drill(center: point) } }+ Concept Struct Layout2 { Points<Point2> Sites { Series { index: n; first: 0; count: 2; keyPrefix: Site; position: Point2(10mm * n, 10mm); } } }+ Concept Struct Layout3 { Points<Point2> Sites { Linear { start: Point2(-40mm, 15mm); direction: [1, 0]; Stations { First: 0mm; Last: 10mm; } } } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/ui-edited-law.firmament b/fixtures/Regression/PatternAuthoringAudit/ui-edited-law.firmamentnew file mode 100644index 00000000..d731186c--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/ui-edited-law.firmament@@ -0,0 +1,15 @@+Function siteX(n: Int, pitch: Length) -> Length = -25mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: 3; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}diff --git a/fixtures/Regression/PatternAuthoringAudit/ui-promoted-count.firmament b/fixtures/Regression/PatternAuthoringAudit/ui-promoted-count.firmamentnew file mode 100644index 00000000..ee93ce76--- /dev/null+++ b/fixtures/Regression/PatternAuthoringAudit/ui-promoted-count.firmament@@ -0,0 +1,16 @@+Function siteX(n: Int, pitch: Length) -> Length = -30mm + pitch * n * n;+Model EquationPlate {+ units: mm+ Static SeriesCount: Int = 3+ Concept Struct Layout {+ Points<Point2> Sites {+ Series { index: n; first: 0; count: SeriesCount; keyPrefix: Site;+ position: Point2(siteX(n,5mm),0mm); }+ }+ }+ Feature Drill(center: Point2) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: 3mm; end: ThroughAll; }+ }+ Box Stock { size: [100mm,50mm,8mm] }+ Modify Stock { Pattern Drills over Layout.Sites { point => Drill(center: point) } }+}