Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Improve Firmament authoring feedback and formatting
Yuechen Lif41bb1bb52fa
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentEditorExperienceTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentEditorExperienceTests.csnew file mode 100644index 00000000..ccce4bad--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentEditorExperienceTests.cs@@ -0,0 +1,157 @@+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentEditorExperienceTests+{+ private static string Fixture(string path = "fixtures/Language/Editor/parameterized-plate.firmament") =>+ File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(path)).ReplaceLineEndings("\n");+ private static FirmamentLanguageCompletion Complete(string source, int? offset = null) => FirmamentLanguageService.Complete(source, "editor.firmament", "1", offset ?? source.Length);++ [Fact]+ public void EmptyDocumentOffersAnExecutableModelTemplateWithANameTabStop()+ {+ var entry = Assert.Single(Complete("mo").Entries!);+ Assert.Equal("Model", entry.Name);+ Assert.Contains("${1:part}", entry.Snippet);+ Assert.True(FirmamentBuildAndExport.CompileSource(entry.Source).IsSuccess);+ var garment = Assert.Single(Complete("Gar").Entries!);+ Assert.Contains("${1:Outfit}", garment.Snippet);+ }++ [Theory]+ [InlineData("Cylinder")]+ [InlineData("Cone")]+ [InlineData("Frustum")]+ [InlineData("Sphere")]+ [InlineData("Torus")]+ [InlineData("RoundedBox")]+ public void NewPrimitiveEntriesBuildThroughTheirExistingGeometryOwners(string name)+ {+ var entry = FirmamentSemanticSchemas.Get(name)!.Entry!;+ var build = FirmamentBuildAndExport.CompileSource("Model M { units: mm " + entry + " }");+ Assert.True(build.IsSuccess, string.Join(';', build.Diagnostics.Select(d => d.Message)));+ }++ [Theory]+ [InlineData("01-plate")]+ [InlineData("02-bracket-profile")]+ [InlineData("03-machined-block")]+ [InlineData("04-plate-family")]+ [InlineData("05-checked-plate")]+ public void FormatterKeepsCurrentLessonGeometryAndIsIdempotent(string name)+ {+ var source = Fixture("fixtures/Canonical/Learn/" + name + ".firmament");+ var formatted = FirmamentLanguageAnalysisService.Format(source, "lesson.firmament", "1");+ Assert.Equal(formatted.Text, FirmamentLanguageAnalysisService.Format(formatted.Text, "lesson.firmament", "2").Text);+ var before = FirmamentBuildAndExport.CompileSource(source);+ var after = FirmamentBuildAndExport.CompileSource(formatted.Text);+ Assert.True(before.IsSuccess, string.Join(';', before.Diagnostics.Select(d => d.Message)));+ Assert.True(after.IsSuccess, string.Join(';', after.Diagnostics.Select(d => d.Message)));+ Assert.Equal(before.Value!.StepText, after.Value!.StepText);+ }++ [Theory]+ [InlineData("Cylinder", "radius")]+ [InlineData("Cone", "bottomRadius")]+ [InlineData("Frustum", "topRadius")]+ [InlineData("Sphere", "radius")]+ [InlineData("Torus", "majorRadius")]+ [InlineData("RoundedBox", "cornerRadius")]+ [InlineData("Circle2", "diameter")]+ [InlineData("Rib", "thickness")]+ public void AllRegisteredConstructsUseTheirActualOwnerFields(string name, string field)+ {+ var source = FirmamentSourceSpelling.Prefer(FirmamentSemanticSchemas.Get(name)!.Entry!);+ var offset = source.IndexOf(field + ":", StringComparison.Ordinal) + Math.Min(2, field.Length);+ Assert.True(offset >= 2, source);+ var result = Complete(source, offset);+ var found = Assert.Single(result.Fields);+ Assert.Equal(field, found.Spelling);+ Assert.Equal(field, source.Substring(result.ReplaceStart, result.ReplaceLength));+ Assert.True(found.Required || name == "Circle2");+ }++ [Fact]+ public void ValuesAndFieldsAreSeparateEvenOnOneLineOrAfterAnUnfinishedColon()+ {+ var source = Fixture();+ var units = source.IndexOf("units: ", StringComparison.Ordinal) + "units: ".Length;+ Assert.Equal(["mm"], Complete(source[..units]).Values);+ Assert.Empty(Complete(source[..units]).Fields);+ var end = source.IndexOf("end: ", StringComparison.Ordinal) + "end: ".Length;+ Assert.Contains("ThroughAll", Complete(source, end).Values!);+ Assert.Empty(Complete(source, end).Fields);+ }++ [Fact]+ public void CommentsAndStringsNeverOfferConstructsAndBracesDoNotLeakScope()+ {+ var source = Fixture();+ var comment = source.IndexOf("radius:", StringComparison.Ordinal);+ Assert.Equal("Literal", Complete(source, comment + 3).Context);+ var body = source.IndexOf(" Box", StringComparison.Ordinal);+ var entries = Complete(source, body).Entries!;+ Assert.Contains(entries, e => e.Name == "Cylinder");+ Assert.DoesNotContain(entries, e => e.Name is "Garment" or "Room" or "Fabric" or "Hole" or "Model");+ var literal = "\"brace } radius: ";+ Assert.Equal("Literal", Complete(literal).Context);+ }++ [Fact]+ public void ModifyEntriesInsertTheFeatureInsteadOfAnotherModifyWrapper()+ {+ var source = Fixture();+ var offset = source.IndexOf(" mountHole", StringComparison.Ordinal);+ var entry = Assert.Single(Complete(source, offset).Entries!, e => e.Name == "Hole");+ Assert.StartsWith("Hole<Shaft>", entry.InsertText);+ Assert.DoesNotContain("Modify", entry.InsertText);+ Assert.Contains("${1:H}", entry.Snippet);+ }++ [Fact]+ public void ValueCompletionAndDefinitionsIncludeLocalParametersAndReusableFeatures()+ {+ var source = Fixture();+ var thickness = source.LastIndexOf("thickness", StringComparison.Ordinal);+ Assert.Contains(Complete(source, thickness + 3).Symbols!, s => s.Name == "thickness" && s.Detail == "Static: Length");+ var parameter = source.IndexOf("center: center", StringComparison.Ordinal) + "center: ".Length;+ Assert.Contains(Complete(source, parameter + 3).Symbols!, s => s.Name == "center" && s.Kind == "variable");+ Assert.Equal(source.IndexOf("center:", StringComparison.Ordinal), FirmamentLanguageAnalysisService.Definition(source, "editor.firmament", parameter + 2)!.Start);+ Assert.Contains("Point2", FirmamentLanguageAnalysisService.Hover(source, "editor.firmament", "1", parameter + 2)!.Description);+ var call = source.LastIndexOf("mountHole", StringComparison.Ordinal);+ Assert.Contains(Complete(source, call + 5).Symbols!, s => s.Name == "mountHole" && s.Kind == "function");+ Assert.Equal(source.IndexOf("mountHole", StringComparison.Ordinal), FirmamentLanguageAnalysisService.Definition(source, "editor.firmament", call + 2)!.Start);+ }++ [Fact]+ public void ValidDeclarationModulesAndAssembliesUseTheConservativeFormattingPass()+ {+ var source = Fixture();+ var module = source[..source.IndexOf("Model ", StringComparison.Ordinal)];+ foreach (var text in new[] { module, Fixture("fixtures/Canonical/Learn/06-post-on-plate.firmament") })+ {+ var formatted = FirmamentLanguageAnalysisService.Format(text, "module.firmament", "1");+ Assert.Equal(FirmamentSourceSpelling.Normalize(text), FirmamentSourceSpelling.Normalize(formatted.Text));+ Assert.Equal(formatted.Text, FirmamentLanguageAnalysisService.Format(formatted.Text, "module.firmament", "2").Text);+ }+ }++ [Fact]+ public void CurrentKeywordsHoverAndFormattingPreserveTheParameterizedPart()+ {+ var source = Fixture();+ var analysis = FirmamentLanguageAnalysisService.Analyze(source, "editor.firmament", "1");+ Assert.DoesNotContain(analysis.Diagnostics, d => d.Severity == "error");+ Assert.Contains(analysis.Tokens, t => t.Kind == "keyword" && source.Substring(t.Start, t.Length) == "Feature");+ var on = source.IndexOf("on:", StringComparison.Ordinal);+ Assert.Contains("Entry face", FirmamentLanguageAnalysisService.Hover(source, "editor.firmament", "1", on + 1)!.Description);+ var formatted = FirmamentLanguageAnalysisService.Format(source, "editor.firmament", "1");+ Assert.Equal(formatted.Text, FirmamentLanguageAnalysisService.Format(formatted.Text, "editor.firmament", "2").Text);+ var before = FirmamentBuildAndExport.CompileSource(source);+ var after = FirmamentBuildAndExport.CompileSource(formatted.Text);+ Assert.True(before.IsSuccess, string.Join(';', before.Diagnostics.Select(d => d.Message)));+ Assert.True(after.IsSuccess, string.Join(';', after.Diagnostics.Select(d => d.Message)));+ Assert.Equal(before.Value!.StepText, after.Value!.StepText);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentHeliosAuthoringFeedbackTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentHeliosAuthoringFeedbackTests.csindex 4e84dbaa..cbb6e20c 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentHeliosAuthoringFeedbackTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentHeliosAuthoringFeedbackTests.cs@@ -15,7 +15,9 @@ public sealed class FirmamentHeliosAuthoringFeedbackTests{var source = Source("hole-variant").Replace("<Shaft>", $"<{variant}>").Replace(" end:", relief + " end:");var offset = source.IndexOf(" on:", StringComparison.Ordinal);- var completion = FirmamentLanguageService.Complete(source, "bracket.firmament", "1", offset);+ // Simulate authoring before these fields exist. A complete document must+ // not offer duplicate fields merely because they are below the caret.+ var completion = FirmamentLanguageService.Complete(source[..offset], "bracket.firmament", "1", offset);Assert.Equal("Hole", completion.Context);Assert.Equal(variant == "Counterbore", completion.Fields.Any(f => f.Name == "CounterboreDepth"));Assert.Equal(variant == "Countersink", completion.Fields.Any(f => f.Name == "CountersinkAngle"));diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageServiceTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageServiceTests.csindex cb542b5d..8a0d68a8 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageServiceTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageServiceTests.cs@@ -74,6 +74,10 @@ public sealed class FirmamentLanguageServiceTestsAssert.Contains(analysis.Tokens, token => token.Kind == "construct" && source.Substring(token.Start, token.Length) == "Thread");Assert.Contains(analysis.Tokens, token => token.Kind == "field" && source.Substring(token.Start, token.Length) == "Size");Assert.Contains(analysis.Diagnostics, diagnostic => diagnostic.Code.Contains("thread-field-invalid", StringComparison.Ordinal));+ var invalid = Assert.Single(analysis.Diagnostics, diagnostic => diagnostic.Code.Contains("thread-field-invalid", StringComparison.Ordinal));+ Assert.Contains("Unknown Thread field 'Wrong'", invalid.Message);+ Assert.Equal(source.IndexOf("Wrong", StringComparison.Ordinal), invalid.Start);+ Assert.Equal("Wrong".Length, invalid.Length);var hover = FirmamentLanguageAnalysisService.Hover(source, "test.firmament", "6", source.IndexOf("Thread", StringComparison.Ordinal) + 2);Assert.Contains("thread", hover!.Description, StringComparison.OrdinalIgnoreCase);var definition = FirmamentLanguageAnalysisService.Definition(source + "\nT", "test.firmament", source.Length + 1);diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.csindex e3118a7d..af66c368 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs@@ -11,10 +11,10 @@ public sealed class FirmamentSemanticSchemaTestsstring[] expectedNames =["Appearance", "FrameTransform", "Placement", "Pmi", "Note", "Provenance",- "Box", "Circle2", "Compose", "Base", "Concept", "Points", "Door", "Drape", "EdgeFinish", "Ellipsoid", "Extrude", "Fabric", "FigureFit", "Fitting", "Garment",+ "Box", "Circle2", "Compose", "Base", "Concept", "Points", "Cone", "Cylinder", "Door", "Drape", "EdgeFinish", "Ellipsoid", "Extrude", "Fabric", "FigureFit", "Fitting", "Frustum", "Garment","Groove", "Helix", "Hole", "Interface<Fixed>", "Interface<Prismatic>", "Interface<Revolute>",- "Interface<Stitch>", "Inventory", "Joint", "Loft", "Panel", "Perforation", "Material", "Linear", "Series", "Polyhedron", "Pose", "PoseTransition",- "Profile", "Rect2", "Rib", "Room", "RoundedRect2", "Scene", "Camera", "Section", "Slot2", "Thread", "Window", "Follow", "WireRoute",+ "Interface<Stitch>", "Inventory", "Joint", "Loft", "Model", "Modify", "Panel", "Perforation", "Material", "Linear", "Series", "Polyhedron", "Pose", "PoseTransition",+ "Profile", "Rect2", "Rib", "Room", "RoundedBox", "RoundedRect2", "Scene", "Camera", "Section", "Slot2", "Sphere", "Thread", "Torus", "Window", "Follow", "WireRoute",];Assert.Equal(expectedNames, FirmamentSemanticSchemas.All.Select(schema => schema.Name));var hole = Assert.IsType<FirmamentConstructSchema>(FirmamentSemanticSchemas.Get("Hole"));diff --git a/Aetheris.Kernel.Firmament.Tests/SceneAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/SceneAuthoringTests.csindex 09c6373d..19986dd0 100644--- a/Aetheris.Kernel.Firmament.Tests/SceneAuthoringTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/SceneAuthoringTests.cs@@ -102,7 +102,10 @@ public sealed class SceneAuthoringTestspublic void SceneEditorProjectsSchemaHoverDiagnosticsAndCommentSafePreferredFormatting(){var source=Source("room"); var entries=FirmamentLanguageService.Complete("", "scene","r",0).Entries!;- foreach(var kind in new[] {"Scene","Room","Door","Window","Camera"}) Assert.Contains(entries,e => e.Name == kind);+ Assert.Contains(entries,e => e.Name == "Scene");+ Assert.DoesNotContain(entries,e => e.Name is "Room" or "Door" or "Window" or "Camera");+ var sceneEntries=FirmamentLanguageService.Complete("Scene Factory {\n", "scene", "r", "Scene Factory {\n".Length).Entries!;+ foreach(var kind in new[] {"Room","Door","Window","Camera"}) Assert.Contains(sceneEntries,e => e.Name == kind);var prefix="Scene Factory { units: m; Room hall { "; var completion=FirmamentLanguageService.Complete(prefix,"scene","r",prefix.Length);Assert.Equal("Room",completion.Context); Assert.Contains(completion.Fields,f => f.Name == "Size");var scenePrefix="Scene Factory { units: m;\n Ro";diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentAuthoringField.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentAuthoringField.csindex 4d2a3b42..d7a6e53f 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentAuthoringField.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentAuthoringField.cs@@ -3,7 +3,10 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;/// <summary>Compiler-owned, JSON-safe field help for a bounded authoring construct.</summary>public sealed record FirmamentAuthoringField(string Name, string Type, bool Required, string Meaning,- string? Default = null, IReadOnlyList<string>? Choices = null);+ string? Default = null, IReadOnlyList<string>? Choices = null)+{+ public string Spelling => FirmamentSourceSpelling.PreferredField(Name);+}public static class FirmamentSchemaAuthoringFields{diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.csindex 3a314d69..b74b5814 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs@@ -123,6 +123,16 @@ public static class FirmamentBuildAdmissionValidationreturn diagnostic with { SourceFile = sourceFile, Line = sourceLine, Column = sourceColumn };}if (source is null) return diagnostic with { SourceFile = sourceFile, LocationNote = "Original source is unavailable." };+ if (diagnostic.Code.StartsWith("firmament-v2-thread-field-invalid:", StringComparison.Ordinal))+ {+ var name = diagnostic.Code.Split(':')[^1];+ var fields = Syntax.FirmamentSyntaxTraversal.Declarations(Syntax.FirmamentSyntaxParser.Parse(source).Document)+ .Where(d => d.Type.Name.Text == "Thread")+ .SelectMany(d => d.Body?.Statements.OfType<Syntax.FieldSyntax>() ?? [])+ .Where(f => Syntax.FirmamentSyntaxFields.SameField(f.Name.Text, name)).ToArray();+ if (fields.Length == 1)+ return Locate(diagnostic with { SourceSpan = fields[0].Name.Span, LocationNote = null }, source, sourceFile);+ }var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(token => token.Shape != "comment").ToArray();// Only these parser-owned diagnostics identify a specific original token.// All other legacy producers receive a disclosed enclosing declaration span.diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.csindex bd0d3da7..6ddd17c3 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs@@ -87,6 +87,10 @@ public static class FirmamentV2DiagnosticAdapter=> $"Invalid value for field '{diagnosticCode.Split(':')[^1]}' in {diagnosticCode.Split(':')[1]}. Check the value type, units and admitted vocabulary.",_ when diagnosticCode.StartsWith(FirmamentV2Parser.CanonicalFieldUnknown + ":", StringComparison.Ordinal)=> $"Unknown field '{diagnosticCode.Split(':')[^1]}' in {diagnosticCode.Split(':')[1]}. Check this construct's documented fields.",+ _ when diagnosticCode.StartsWith("firmament-v2-thread-field-invalid:", StringComparison.Ordinal)+ => FirmamentSchemaAuthoringFields.For("Thread").Any(f => f.Name == diagnosticCode.Split(':')[^1])+ ? $"Thread field '{FirmamentSourceSpelling.PreferredField(diagnosticCode.Split(':')[^1])}' is specified more than once. Keep one value."+ : $"Unknown Thread field '{diagnosticCode.Split(':')[^1]}'. Use " + string.Join(", ", FirmamentSchemaAuthoringFields.For("Thread").Select(f => f.Spelling)) + ".",_ when diagnosticCode.StartsWith(FirmamentV2Parser.CanonicalDeclarationUnknown + ":", StringComparison.Ordinal)=> $"Unknown statement '{diagnosticCode.Split(':')[^1]}'{(diagnosticCode.Split(':').Length > 2 ? " in " + diagnosticCode.Split(':')[1] : "")}. Use an admitted construct in this context.",// Producers write "code[:parameters]: explanation"; the explanation is the message.diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.csindex a564639b..d4facd08 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs@@ -1,6 +1,7 @@using System.Text;using Aetheris.Kernel.Firmament.Scene;using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;namespace Aetheris.Kernel.Firmament.FirmamentV2;@@ -20,8 +21,8 @@ public sealed record FirmamentLanguageFormat(string Document, string Revision, spublic static class FirmamentLanguageAnalysisService{internal sealed record Lexeme(int Start, int Length, string Text, string Shape, string? Error = null);- private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "Enum", "Options", "match", "Match", "With", "with", "Expose", "Include", "Subassembly", "Assembly", "Part", "Template", "Function", "Record", "Pattern", "Over", "Using", "As", "as", "Output", "tol", "Concept", "Require", "Motion", "Track", "Keyframes", "Keyframe"];- private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Function", "Pattern", "Section", "SectionChain", "FrameTransform", "Points", "Path", "Semantic", "Enum", "Options", "Concept", "Motion", "Track", "Keyframes", "Keyframe"];+ private static readonly HashSet<string> Keywords = ["Model", "Units", "Modify", "WireForm", "Construction", "Use", "schema", "Let", "Static", "Enum", "Options", "match", "Match", "With", "with", "Expose", "Include", "Subassembly", "Assembly", "Part", "Template", "Feature", "return", "Function", "Record", "Table", "Set", "Assert", "measure", "Pattern", "Over", "Using", "As", "as", "Output", "tol", "Concept", "Require", "Motion", "Track", "Keyframes", "Keyframe"];+ private static readonly HashSet<string> DeclarationKinds = ["Model", "Struct", "Subassembly", "Assembly", "Template", "Profile", "Static", "Record", "Feature", "Function", "Table", "Set", "Pattern", "Section", "SectionChain", "FrameTransform", "Points", "Path", "Semantic", "Enum", "Options", "Concept", "Motion", "Track", "Keyframes", "Keyframe"];private static readonly HashSet<string> Types = ["Length", "Angle", "Time", "Float", "Int", "Bool", "Box3", "Plane", "Point2", "Point3"];private static readonly HashSet<string> Choices = FirmamentSemanticSchemas.All.SelectMany(construct => construct.Fields).SelectMany(field => field.Choices).ToHashSet(StringComparer.Ordinal);@@ -106,10 +107,24 @@ public static class FirmamentLanguageAnalysisServicevar construct = FirmamentSemanticSchemas.All.FirstOrDefault(item => item.Name == token.Text);if (construct is not null)return new(document, revision, token.Start, token.Length, construct.Name, construct.Description ?? construct.Context ?? "Firmament construct");- var field = FirmamentSemanticSchemas.All.SelectMany(item => item.Fields).FirstOrDefault(item => item.Name == token.Text);+ var field = FirmamentLanguageService.FieldAt(FirmamentSourceSpelling.Normalize(source), token.Start, token.Text);if (field is not null && Classify(lexemes, index) == "field")return new(document, revision, token.Start, token.Length, field.Name,- $"{field.Kind}{(field.Unit == FirmamentUnitKind.None ? "" : $" · {field.Unit}")}. {field.Description ?? ""}".Trim());+ $"{field.Type}{(field.Required ? " · required" : "")}. {field.Meaning}".Trim());+ var definition = Definition(source, document, offset);+ if (definition is not null)+ {+ var declaration = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)+ .FirstOrDefault(d => d.Name?.Span.Start == definition.Start);+ if (declaration is not null)+ return new(document, revision, token.Start, token.Length, token.Text,+ "```firmament\n" + source.Substring(declaration.Span.Start, (declaration.Body?.Span.Start ?? declaration.Span.Start + declaration.Span.Length) - declaration.Span.Start).Trim() + "\n```");+ var parameter = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document)+ .SelectMany(d => d.Parameters).FirstOrDefault(p => p.Name?.Span.Start == definition.Start);+ if (parameter is not null)+ return new(document, revision, token.Start, token.Length, token.Text,+ "Parameter: `" + source.Substring(parameter.Span.Start, parameter.Span.Length) + "`");+ }return null;}@@ -118,6 +133,14 @@ public static class FirmamentLanguageAnalysisServicevar tokens = Lex(FirmamentSourceSpelling.Normalize(source));var selected = tokens.FirstOrDefault(item => item.Shape == "identifier" && item.Start <= offset && offset <= item.Start + item.Length);if (selected is null) return null;+ var syntax = FirmamentSyntaxParser.Parse(source).Document;+ if (FirmamentSyntaxTraversal.Expressions(syntax).OfType<ReferenceSyntax>().Any(r => r.Span.Start == selected.Start))+ {+ var parameters = FirmamentSyntaxTraversal.Declarations(syntax).Where(d => d.Body is { } body &&+ body.ContentSpan.Start <= offset && offset <= body.ContentSpan.Start + body.ContentSpan.Length)+ .SelectMany(d => d.Parameters).Where(p => p.Name?.Text == selected.Text).ToArray();+ if (parameters.Length == 1) return new(document, parameters[0].Name!.Span.Start, parameters[0].Name!.Span.Length);+ }var declarations = Declarations(tokens, selected.Text, ReferenceKind(tokens, selected)).ToArray();return declarations.Length == 1 ? new(document, declarations[0].Start, declarations[0].Length) : null;}@@ -245,6 +268,10 @@ public static class FirmamentLanguageAnalysisServicethrow new InvalidOperationException("Scene formatting changed parser admission.");return scene;}+ var sharedSyntax = FirmamentSyntaxParser.Parse(source, document);+ if (sharedSyntax.IsSuccess && (HasAssemblyRoot(source) || !sharedSyntax.Document.Statements.OfType<DeclarationSyntax>().Any(d =>+ d.Type.Name.Text is "Model" or "model" or "Struct" && !d.Modifiers.Any(m => m.Name.Text is "Template" or "Concept"))))+ return FormatConventions(source, document, revision);if (!FirmamentV2Parser.Parse(source).IsSuccess)throw new InvalidOperationException("Format Document requires valid Firmament source. Fix syntax errors first.");var preferred = FirmamentSourceSpelling.Prefer(source);@@ -264,7 +291,8 @@ public static class FirmamentLanguageAnalysisServiceelse if (gap.Contains('\n') && token.Text != ";" && previous?.Text != "{") BreakLine();if (lineStart) { output.Append(' ', indent * 2); lineStart = false; }- else if (NeedsSpace(previous?.Text, token.Text)) output.Append(' ');+ else if (!(gap.Length == 0 && (previous?.Shape == "number" && token.Shape == "identifier"+ || previous?.Shape == "identifier" && token.Text == "<")) && NeedsSpace(previous?.Text, token.Text)) output.Append(' ');output.Append(token.Text);if (token.Shape == "comment" || token.Text is "{" or ";" or "}"){@@ -277,8 +305,10 @@ public static class FirmamentLanguageAnalysisServiceif (!Lex(FirmamentSourceSpelling.Normalize(source)).Select(t => (t.Text, t.Shape)).SequenceEqual(Lex(FirmamentSourceSpelling.Normalize(formatted)).Select(t => (t.Text, t.Shape))))throw new InvalidOperationException("Canonical layout was refused because it changed source tokens.");- if (!FirmamentV2Parser.Parse(formatted).IsSuccess)- throw new InvalidOperationException("Canonical layout was refused because it changed parser admission.");+ var formattedParse = FirmamentV2Parser.Parse(formatted);+ if (!formattedParse.IsSuccess)+ throw new InvalidOperationException("Canonical layout was refused because it changed parser admission: " + string.Join(", ",+ formattedParse.SyntaxDiagnostics.Select(d => d.Code + ": " + d.Message).Concat(formattedParse.Diagnostics).Distinct()));return new(document, revision, formatted, formatted != source);void BreakLine()diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.csindex cbce69dc..65eeeb86 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs@@ -1,6 +1,5 @@using System.Text.RegularExpressions;using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;-using Aetheris.Kernel.Firmament.Materializer;namespace Aetheris.Kernel.Firmament.FirmamentV2;@@ -9,95 +8,71 @@ public sealed record FirmamentLanguageCompletion(IReadOnlyList<FirmamentAuthoringField> Fields,IReadOnlyList<string> MissingRequiredFields,IReadOnlyList<FirmamentLanguageEntry>? Entries = null,- IReadOnlyList<string>? Values = null);-public sealed record FirmamentLanguageEntry(string ConstructId, string Name, string Context, string Source);+ IReadOnlyList<string>? Values = null,+ IReadOnlyList<FirmamentLanguageSymbol>? Symbols = null);+public sealed record FirmamentLanguageEntry(string ConstructId, string Name, string Context, string Source)+{+ public string? InsertText { get; init; }+ public string? Snippet { get; init; }+}+public sealed record FirmamentLanguageSymbol(string Name, string Kind, string Detail, int Start, int Length);-/// <summary>Bounded authoring help from construct owners; no BRep or export work.</summary>+/// <summary>Authoring help from the shared syntax tree and construct owners; no BRep or export work.</summary>public static class FirmamentLanguageService{+ internal sealed record Owner(string Name, string? Variant, BlockSyntax Body, DeclarationSyntax? Declaration)+ {+ public string SchemaName => Name == "Interface" && Variant is not null ? $"Interface<{Variant}>" : Name;+ public string Scope => Name == "Struct" && Declaration?.Modifiers.Any(m => m.Name.Text == "Concept") == true ? "Concept Struct" : Name;+ }+ private sealed record EntryTemplate(FirmamentConstructSchema Schema, string Source, DocumentSyntax Syntax);+ private static readonly EntryTemplate[] Entries = FirmamentSemanticSchemas.All.Where(s => s.Entry is not null)+ .Select(s => { var text = FirmamentSourceSpelling.Prefer(s.Entry!); return new EntryTemplate(s, text, FirmamentSyntaxParser.Parse(text).Document); }).ToArray();+public static FirmamentLanguageCompletion Complete(string source, string document, string revision, int offset){ArgumentNullException.ThrowIfNull(source);if (offset < 0 || offset > source.Length) throw new ArgumentOutOfRangeException(nameof(offset));source = FirmamentSourceSpelling.Normalize(source);- var prefixStart = offset;- while (prefixStart > 0 && (char.IsLetterOrDigit(source[prefixStart - 1]) || source[prefixStart - 1] == '_')) prefixStart--;- var prefix = source[prefixStart..offset];- var lineStart = prefixStart == 0 ? 0 : source.LastIndexOf('\n', prefixStart - 1) + 1;- var beforePrefix = source[lineStart..prefixStart];- IReadOnlyList<FirmamentAuthoringField> fields;- string context;- var interfaceFamily = ActiveFrameInterface(source, offset);- var composition = ActiveCompositionConstruct(source, offset);- if (composition is not null)- {- 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)- {- fields = FirmamentSchemaAuthoringFields.For($"Interface<{interfaceFamily}>");- context = $"Interface<{interfaceFamily}>";- }- else if (IsInsideThread(source, offset))- {- fields = FirmamentSchemaAuthoringFields.For("Thread");- context = "Thread";- }- else if (IsInsidePerforation(source, offset))- {- fields = FirmamentSchemaAuthoringFields.For("Perforation");- context = "Perforation";- }- else if (WireFormAuthoring.IsInsideHelix(source, offset))- {- fields = FirmamentSchemaAuthoringFields.For("Helix");- context = "Helix";- }- else if (LoftAuthoringParser.TryGetAuthoringFields(source, offset, out fields)) context = "Loft";- else if (IsInsideConstruct(source, offset, "Box")) { fields = FirmamentSchemaAuthoringFields.For("Box"); context = "Box"; }- else if (IsInsideConstruct(source, offset, "Ellipsoid")) { fields = FirmamentSchemaAuthoringFields.For("Ellipsoid"); context = "Ellipsoid"; }- else if (IsInsideConstruct(source, offset, "Polyhedron")) { fields = FirmamentSchemaAuthoringFields.For("Polyhedron"); context = "Polyhedron"; }- else if (IsInsideConstruct(source, offset, "Hole")) { fields = FirmamentSchemaAuthoringFields.For("Hole"); context = "Hole"; }- else- {- if (beforePrefix.Contains(':')) return new(document, revision, "Value", prefixStart, prefix.Length, [], []);- var inModify = IsInsideConstruct(source, offset, "Modify");- var entries = FirmamentSemanticSchemas.All- .Where(item => item.Entry is not null &&- (item.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)- || beforePrefix.EndsWith("Interface<", StringComparison.Ordinal)- && item.Name.StartsWith("Interface<" + prefix, StringComparison.OrdinalIgnoreCase)) &&- (!inModify || item.Context?.StartsWith("Modify", StringComparison.Ordinal) == true))- .Select(item => new FirmamentLanguageEntry(item.Id.Value, item.Name, item.Context ?? string.Empty, FirmamentSourceSpelling.Prefer(item.Entry!))).ToArray();- return new(document, revision, entries.Length > 0 ? "ConstructEntry" : "Unsupported",- prefixStart, prefix.Length, [], [], entries);- }+ var start = offset;+ while (start > 0 && IdentifierPart(source[start - 1])) start--;+ var end = offset;+ while (end < source.Length && IdentifierPart(source[end])) end++;+ var prefix = source[start..offset];+ FirmamentLanguageCompletion Empty(string context) => new(document, revision, context, start, end - start, [], []);+ // The compiler lexer owns strings/comments, including unfinished ones while typing.+ if (FirmamentLanguageAnalysisService.Lex(source).Any(t => offset > t.Start &&+ (offset < t.Start + t.Length || offset == t.Start + t.Length &&+ (t.Shape == "comment" && t.Text.StartsWith("//", StringComparison.Ordinal) || t.Error is not null)) &&+ t.Shape is "comment" or "string")) return Empty("Literal");- var activeField = Regex.Match(beforePrefix, @"(?<field>[A-Za-z_]\w*)\s*:\s*$", RegexOptions.CultureInvariant);- if (activeField.Success)+ var syntax = FirmamentSyntaxParser.Parse(source).Document;+ var owner = OwnerAt(syntax, offset);+ var context = owner?.SchemaName ?? "Document";+ if (FirmamentSyntaxTraversal.Declarations(syntax).Any(d => d.Name is { } name &&+ start >= name.Span.Start && offset <= name.Span.Start + name.Span.Length &&+ (owner is null || d.Span.Start > owner.Body.Span.Start))) return Empty("DeclarationName");+ var fields = FieldsFor(owner, source, offset);+ var directFields = owner?.Body.Statements.OfType<FieldSyntax>().ToArray() ?? [];+ var activeField = directFields.LastOrDefault(f => f.Name.Span.Start + f.Name.Span.Length < start &&+ f.Value.Span.Start <= offset && offset <= f.Value.Span.Start + f.Value.Span.Length);+ // A missing expression can be omitted by parser recovery. Its two+ // structural tokens still identify the value slot without inventing an AST.+ var preceding = syntax.Tokens.Where(t => t.Kind is not (SyntaxTokenKind.Comment or SyntaxTokenKind.Whitespace or SyntaxTokenKind.End)+ && t.Span.Start < start && t.Span.Start >= (owner?.Body.ContentSpan.Start ?? 0)).TakeLast(2).ToArray();+ var activeName = activeField?.Name.Text ?? (preceding.Length == 2 && preceding[0].Kind == SyntaxTokenKind.Identifier && preceding[1].Text == ":" ? preceding[0].Text : null);+ if (activeName is not null){- var field = fields.FirstOrDefault(item => item.Name == activeField.Groups["field"].Value);- var values = field?.Choices?.Where(choice => choice.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToArray();- return new(document, revision, "Value", prefixStart, prefix.Length, [], [], Values: values);+ var field = fields.FirstOrDefault(f => FirmamentSyntaxFields.SameField(activeName, f.Name));+ return new(document, revision, "Value", start, end - start, [], [], Values:+ field?.Choices?.Where(c => c.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToArray(),+ Symbols: VisibleSymbols(source, syntax, owner, offset, prefix, values: true));}- if (beforePrefix.Contains(':')) return new(document, revision, "Value", prefixStart, prefix.Length, [], []);-- var open = composition?.Open ?? source.LastIndexOf('{', Math.Max(0, offset - 1));- var body = open >= 0 ? source[(open + 1)..offset] : string.Empty;- var present = fields.Where(field => Regex.IsMatch(body, $@"\b{Regex.Escape(field.Name)}\s*:", RegexOptions.CultureInvariant))- .Select(field => field.Name).ToHashSet(StringComparer.Ordinal);- var candidates = fields.Where(field => !present.Contains(field.Name) && field.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToArray();- var missing = fields.Where(field => field.Required && !present.Contains(field.Name)).Select(field => field.Name).ToList();+ // Fields after the caret still count, except the field currently being edited.+ var present = directFields.Where(f => !(f.Name.Span.Start <= offset && offset <= f.Name.Span.Start + f.Name.Span.Length))+ .Select(f => f.Name.Text).ToHashSet(StringComparer.Ordinal);+ var candidates = fields.Where(f => !present.Contains(f.Name) && f.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToArray();+ var missing = fields.Where(f => f.Required && !present.Contains(f.Name)).Select(f => f.Name).ToList();if (context == "Interface<Fixed>" && present.Contains("Datum")){candidates = candidates.Where(f => f.Name is not ("A" or "B")).ToArray();@@ -105,77 +80,103 @@ public static class FirmamentLanguageServiceif (!present.Contains("Members")) missing.Add("Members");}if (context == "Helix" && !present.Contains("Pitch") && !present.Contains("Height")) missing.Add("Pitch or Height");- if (context is "Scene" or "Garment")- {- var entries = FirmamentSemanticSchemas.All.Where(item => item.Context == context && item.Entry is not null- && item.Name.StartsWith(prefix,StringComparison.OrdinalIgnoreCase))- .Select(item => new FirmamentLanguageEntry(item.Id.Value,item.Name,item.Context!,FirmamentSourceSpelling.Prefer(item.Entry!))).ToArray();- return new(document,revision,context,prefixStart,prefix.Length,candidates,missing,entries);- }- return new(document, revision, context, prefixStart, prefix.Length, candidates, missing);+ var entries = Entries.Where(e => e.Schema.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && LegalScope(e, owner))+ .Select(e => EntryFor(e, owner)).ToArray();+ return new(document, revision, owner?.Name is "Model" or "Struct" && candidates.Length == 0 && entries.Length > 0 ? "ConstructEntry" : context, start, end - start, candidates, missing, entries,+ Symbols: VisibleSymbols(source, syntax, owner, offset, prefix, values: false));}- private static bool IsInsidePerforation(string source, int offset)+ private static bool IdentifierPart(char value) => char.IsLetterOrDigit(value) || value == '_';+ private static bool Contains(BlockSyntax body, int offset) => body.ContentSpan.Start <= offset &&+ offset <= body.ContentSpan.Start + body.ContentSpan.Length;++ internal static Owner? OwnerAt(DocumentSyntax syntax, int offset){- var prefix = source[..offset];- var header = Regex.Matches(prefix, @"\bPerforation\s+[A-Za-z_][A-Za-z0-9_]*\s*\{", RegexOptions.CultureInvariant).Cast<Match>().LastOrDefault();- return header is not null && !prefix[(header.Index + header.Length)..].Contains('}');+ var declarations = FirmamentSyntaxTraversal.Declarations(syntax).Where(d => d.Body is not null && Contains(d.Body, offset))+ .Select(d => new Owner(d.Type.Name.Text, d.Type.Arguments.FirstOrDefault() is { } a ? FirmamentSyntaxValues.Reference(a.Value) : null, d.Body!, d));+ var objects = FirmamentSyntaxTraversal.Expressions(syntax).OfType<ObjectSyntax>().Where(o => o.Type is not null && Contains(o.Body, offset))+ .Select(o => new Owner(FirmamentSyntaxValues.Reference(o.Type is SpecializationSyntax s ? s.Target : o.Type) ?? "",+ o.Type is SpecializationSyntax generic && generic.Arguments.FirstOrDefault() is { } a ? FirmamentSyntaxValues.Reference(a.Value) : null, o.Body, null));+ return declarations.Concat(objects).OrderByDescending(o => o.Body.Span.Start).FirstOrDefault();}- private static string? ActiveFrameInterface(string source, int offset)+ internal static FirmamentAuthoringField? FieldAt(string source, int offset, string name){- var prefix = source[..offset];- var header = Regex.Matches(prefix, @"\bInterface\s*<\s*(Fixed|Revolute|Prismatic)\s*>\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant)- .Cast<Match>().LastOrDefault();- return header is not null && !prefix[(header.Index + header.Length)..].Contains('}')- ? header.Groups[1].Value : null;+ var syntax = FirmamentSyntaxParser.Parse(source).Document;+ return FieldsFor(OwnerAt(syntax, offset), source, offset).FirstOrDefault(f => FirmamentSyntaxFields.SameField(name, f.Name));}- private static bool IsInsideThread(string source, int offset)+ private static IReadOnlyList<FirmamentAuthoringField> FieldsFor(Owner? owner, string source, int offset){- var prefix = source[..offset];- var header = Regex.Matches(prefix, @"\bThread\s+[A-Za-z_][A-Za-z0-9_]*\s*\{", RegexOptions.CultureInvariant).Cast<Match>().LastOrDefault();- return header is not null && !prefix[(header.Index + header.Length)..].Contains('}');+ if (owner is null) return [];+ if (owner.Name == "Loft" && LoftAuthoringParser.TryGetAuthoringFields(source, offset, out var loft)) return loft;+ if (owner.Name == "Points" && owner.Body.Statements.OfType<DeclarationSyntax>().Any(d =>+ d.Type.Name.Text == "Series" || d.Body?.Statements.OfType<DeclarationSyntax>().Any(c => c.Type.Name.Text == "Stations") == true)) return [];+ if (owner.Name == "Struct") return owner.Scope == "Concept Struct" ? [] : FirmamentSchemaAuthoringFields.For("Model").Select(f => f with { Required = false }).ToArray();+ return FirmamentSchemaAuthoringFields.For(owner.SchemaName, owner.Variant);}- private static bool IsInsideConstruct(string source, int offset, string construct)+ private static bool LegalScope(EntryTemplate entry, Owner? owner){- var prefix = source[..offset];- var header = Regex.Matches(prefix, $@"\b{Regex.Escape(construct)}(?:\s*<[^>]+>)?\s+[A-Za-z_]\w*\s*\{{", RegexOptions.CultureInvariant)- .Cast<Match>().LastOrDefault();- return header is not null && !prefix[(header.Index + header.Length)..].Contains('}');+ var context = entry.Schema.Context ?? "";+ var scope = owner?.Scope ?? "Document";+ var modelTemplate = entry.Syntax.Statements.OfType<DeclarationSyntax>().Any(d => d.Type.Name.Text == "Model");+ return scope switch+ {+ "Document" => context is "Document" or "Declaration" || modelTemplate,+ "Model" or "Struct" => context.StartsWith("Model", StringComparison.Ordinal) || modelTemplate && entry.Schema.Name != "Model",+ "Modify" => context.StartsWith("Modify", StringComparison.Ordinal),+ "Assembly" or "Subassembly" => context == "Assembly",+ "Concept Struct" => context == "Concept Struct" || context.Contains("layout", StringComparison.Ordinal),+ _ => Regex.IsMatch(context, $@"\b{Regex.Escape(scope)}\b", RegexOptions.CultureInvariant)+ };+ }++ private static FirmamentLanguageEntry EntryFor(EntryTemplate entry, Owner? owner)+ {+ var text = entry.Source;+ var declarations = FirmamentSyntaxTraversal.Declarations(entry.Syntax).ToArray();+ var declaration = declarations.FirstOrDefault(d => d.Type.Name.Text == entry.Schema.Name.Split('<')[0]);+ if (owner is not null && declaration is not null)+ {+ // An entry may be a complete document (Loft/Helix) or have a Modify+ // wrapper (Hole). Insert the declaration appropriate to the actual owner.+ if (owner.Name is "Model" or "Struct" && entry.Syntax.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d => d.Type.Name.Text == "Model") is { } root)+ declaration = root.Body?.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d =>+ d.Span.Start <= declaration.Span.Start && d.Span.Start + d.Span.Length >= declaration.Span.Start + declaration.Span.Length) ?? declaration;+ text = text.Substring(declaration.Span.Start, declaration.Span.Length);+ var indentStart = entry.Source.LastIndexOf('\n', Math.Max(0, declaration.Span.Start - 1)) + 1;+ var indent = entry.Source[indentStart..declaration.Span.Start];+ if (indent.All(char.IsWhiteSpace) && indent.Length > 0)+ text = string.Join('\n', text.Split('\n').Select((line, i) => i > 0 && line.StartsWith(indent, StringComparison.Ordinal) ? line[indent.Length..] : line));+ }+ var parsed = FirmamentSyntaxParser.Parse(text).Document;+ var roots = parsed.Statements.OfType<DeclarationSyntax>().Where(d => d.Name is not null).ToArray();+ var name = (roots.FirstOrDefault(d => d.Type.Name.Text == entry.Schema.Name)+ ?? roots.FirstOrDefault(d => d.Type.Name.Text is "Model" or "Assembly" or "Scene" or "Garment")+ ?? roots.FirstOrDefault())?.Name;+ static string Escape(string value) => value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("$", "\\$", StringComparison.Ordinal).Replace("}", "\\}", StringComparison.Ordinal);+ var snippet = name is null ? Escape(text) + "$0" : Escape(text[..name.Span.Start]) + "${1:" + Escape(name.Text) + "}" + Escape(text[(name.Span.Start + name.Span.Length)..]) + "$0";+ return new(entry.Schema.Id.Value, entry.Schema.Name, entry.Schema.Context ?? "", entry.Source) { InsertText = text, Snippet = snippet };}- private static (string Name, int Open, string? Variant)? ActiveCompositionConstruct(string source, int offset)+ private static IReadOnlyList<FirmamentLanguageSymbol> VisibleSymbols(string source, DocumentSyntax syntax, Owner? owner, int offset, string prefix, bool values){- // Ignore comments/strings and balance nested blocks in incomplete drafts.- var 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|EdgeFinish";- 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 declarations = FirmamentSyntaxTraversal.Declarations(syntax).ToArray();+ var result = new List<FirmamentLanguageSymbol>();+ foreach (var d in declarations.Where(d => d.Name is not null && d.Name.Text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))){- var depth = 1;- foreach (var c in prefix[(header.Index + header.Length)..])- {- if (c == '{') depth++;- else if (c == '}') depth--;- if (depth == 0) break;- }- if (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());- }+ if (!values && d.Type.Name.Text is not ("Feature" or "Function")) continue;+ var scope = declarations.Where(p => p != d && p.Body is not null && p.Body.Span.Start < d.Span.Start &&+ p.Body.Span.Start + p.Body.Span.Length >= d.Span.Start + d.Span.Length).OrderByDescending(p => p.Body!.Span.Start).FirstOrDefault();+ if (scope?.Body is not null && !Contains(scope.Body, offset) || d == owner?.Declaration) continue;+ var kind = d.Type.Name.Text is "Feature" or "Function" ? "function" : d.Type.Name.Text is "Record" or "Enum" or "Options" ? "type" : "reference";+ result.Add(new(d.Name!.Text, kind, d.Type.Name.Text + (d.Annotation is null ? "" : ": " + source.Substring(d.Annotation.Span.Start, d.Annotation.Span.Length)), d.Name.Span.Start, d.Name.Span.Length));}- return null;+ if (values)+ foreach (var parameter in declarations.Where(d => d.Body is not null && Contains(d.Body, offset)).SelectMany(d => d.Parameters).Where(p => p.Name is not null && p.Name.Text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))+ result.Add(new(parameter.Name!.Text, "variable", "parameter", parameter.Name.Span.Start, parameter.Name.Span.Length));+ // A completion must not choose arbitrarily between same-named declarations.+ return result.GroupBy(s => s.Name, StringComparer.Ordinal).Where(g => g.Count() == 1).Select(g => g.Single()).ToArray();}}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.csindex 4978ad17..013979c4 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs@@ -1,6 +1,45 @@namespace Aetheris.Kernel.Firmament.FirmamentV2;// These are opt-in public Firmament surfaces. The parser remains the execution authority.+[FirmamentConstruct("Model", "Model", Context = "Document", Entry = "Model part {\n units: mm\n Box body { size: [40mm, 30mm, 8mm] }\n}", Description = "One engineered part and its construction. A mechanical Model contains one material body.")]+[FirmamentField("Units", "Units", FirmamentSchemaValueKind.Choice, Required = true, Choices = ["mm"], Description = "Mechanical model length unit; dimensional values still carry explicit units.")]+[FirmamentField("Material", "Material", FirmamentSchemaValueKind.ConstructReference, Description = "Physical material identity; does not change the body's geometry.")]+public static class ModelSemanticDeclaration { }++[FirmamentConstruct("Cylinder", "Cylinder", Context = "Model or Struct", Entry = "Cylinder body { radius: 10mm; height: 20mm }", Description = "Round solid on the Z axis, from Z = 0 to height.")]+[FirmamentField("Radius", "Radius", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true)]+[FirmamentField("Height", "Height", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true)]+public static class CylinderSemanticDeclaration { }++[FirmamentConstruct("Cone", "Cone", Context = "Model or Struct", Entry = "Cone body { bottomRadius: 10mm; topRadius: 0mm; height: 20mm }", Description = "Coaxial cone or truncated cone on the Z axis.")]+[FirmamentField("BottomRadius", "BottomRadius", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true)]+[FirmamentField("TopRadius", "TopRadius", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true, Description = "Zero makes a pointed cone.")]+[FirmamentField("Height", "Height", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true)]+public static class ConeSemanticDeclaration { }++[FirmamentConstruct("Frustum", "Frustum", Context = "Model or Struct", Entry = "Frustum body { bottomRadius: 10mm; topRadius: 6mm; height: 20mm }", Description = "Truncated coaxial cone on the Z axis.")]+[FirmamentField("BottomRadius", "BottomRadius", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true)]+[FirmamentField("TopRadius", "TopRadius", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true)]+[FirmamentField("Height", "Height", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true)]+public static class FrustumSemanticDeclaration { }++[FirmamentConstruct("Sphere", "Sphere", Context = "Model or Struct", Entry = "Sphere body { radius: 10mm }", Description = "Sphere centered on the origin.")]+[FirmamentField("Radius", "Radius", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true)]+public static class SphereSemanticDeclaration { }++[FirmamentConstruct("Torus", "Torus", Context = "Model or Struct", Entry = "Torus body { majorRadius: 15mm; minorRadius: 3mm }", Description = "Ring centered on the origin, with its axis on Y.")]+[FirmamentField("MajorRadius", "MajorRadius", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true)]+[FirmamentField("MinorRadius", "MinorRadius", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true)]+public static class TorusSemanticDeclaration { }++[FirmamentConstruct("RoundedBox", "RoundedBox", Context = "Model or Struct", Entry = "RoundedBox body { size: [40mm, 30mm, 8mm]; cornerRadius: 3mm }", Description = "Box centered on the origin with rounded vertical corners.")]+[FirmamentField("Size", "Size", FirmamentSchemaValueKind.Vector, Unit = FirmamentUnitKind.Length, Required = true)]+[FirmamentField("CornerRadius", "CornerRadius", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true)]+public static class RoundedBoxSemanticDeclaration { }++[FirmamentConstruct("Modify", "Modify", Context = "Model or Struct", Entry = "Modify body {\n Hole<Shaft> hole { on: +Z; center: Point2(0mm, 0mm); diameter: 6mm; end: ThroughAll }\n}", Description = "Features applied to a named material body.")]+public static class ModifySemanticDeclaration { }+[FirmamentConstruct("Box", "Box", Context = "Model or Struct", Entry = "Box Body { Size: [10mm, 10mm, 10mm] }", Description = "Rectangular solid.")][FirmamentField("Size", "Size", FirmamentSchemaValueKind.Vector, Unit = FirmamentUnitKind.Length, Description = "Three lengths for the box dimensions; supply Size or Bounds.")][FirmamentField("Bounds", "Bounds", FirmamentSchemaValueKind.Box3, Description = "A semantic Box3 bound instead of Size.")]diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.csindex af86c3bd..6ae21739 100644--- a/Aetheris.Web.Runtime/Program.cs+++ b/Aetheris.Web.Runtime/Program.cs@@ -206,8 +206,15 @@ public static partial class Program{if (request.Source is null || request.Offset is null)throw new WebRuntimeException("language-input-required", "languageDefinition requires source and offset.");- var location = FirmamentLanguageAnalysisService.Definition(request.Source, request.SourceName ?? "model.firmament", request.Offset.Value);- return location is null ? null : SourceRefAt(location.Document, request.Source, location.Start, location.Length);+ var name = request.SourceName ?? "model.firmament";+ var documents = request.ProjectDocuments is { Count: > 0 }+ ? new Dictionary<string, string>(request.ProjectDocuments, StringComparer.Ordinal) { [name] = request.Source }+ : null;+ var location = documents is null+ ? FirmamentLanguageAnalysisService.Definition(request.Source, name, request.Offset.Value)+ : FirmamentLanguageAnalysisService.Definition(new FirmamentProjectSnapshot(request.ProjectRoot ?? name, documents), name, request.Offset.Value);+ return location is null ? null : SourceRefAt(location.Document,+ documents?.GetValueOrDefault(location.Document) ?? request.Source, location.Start, location.Length);}private static object LanguageFormat(WebRequest request)diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.tsindex 2b48466c..41ea1500 100644--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts@@ -41,9 +41,10 @@ export interface WorkerTiming { readonly operation: string; readonly executionMiexport interface OperationOptions { readonly signal?: AbortSignal; readonly sourceRevision?: string; readonly performance?: boolean }export interface CompileOptions extends OperationOptions { readonly sourceName?: string; readonly projectDocuments?: Readonly<Record<string, string>> }export interface LanguageOptions { readonly sourceName?: string; readonly sourceRevision: string; readonly projectDocuments?: Readonly<Record<string, string>>; readonly projectRoot?: string }-export interface LanguageField { readonly name: string; readonly type: string; readonly required: boolean; readonly meaning: string; readonly default?: string | null; readonly choices?: readonly string[] | null }-export interface LanguageEntry { readonly constructId: string; readonly name: string; readonly context: string; readonly source: string }-export interface LanguageCompletion { readonly document: string; readonly revision: string; readonly context: string; readonly replaceStart: number; readonly replaceLength: number; readonly fields: readonly LanguageField[]; readonly missingRequiredFields: readonly string[]; readonly entries?: readonly LanguageEntry[] | null; readonly values?: readonly string[] | null }+export interface LanguageField { readonly name: string; readonly spelling?: string; readonly type: string; readonly required: boolean; readonly meaning: string; readonly default?: string | null; readonly choices?: readonly string[] | null }+export interface LanguageEntry { readonly constructId: string; readonly name: string; readonly context: string; readonly source: string; readonly insertText?: string | null; readonly snippet?: string | null }+export interface LanguageSymbol { readonly name: string; readonly kind: string; readonly detail: string; readonly start: number; readonly length: number }+export interface LanguageCompletion { readonly document: string; readonly revision: string; readonly context: string; readonly replaceStart: number; readonly replaceLength: number; readonly fields: readonly LanguageField[]; readonly missingRequiredFields: readonly string[]; readonly entries?: readonly LanguageEntry[] | null; readonly values?: readonly string[] | null; readonly symbols?: readonly LanguageSymbol[] | null }export interface LanguageToken { readonly start: number; readonly length: number; readonly kind: 'keyword' | 'construct' | 'type' | 'identifier' | 'field' | 'number' | 'unit' | 'string' | 'comment' | 'punctuation' | 'selector' | 'value' }export interface LanguageAnalysis { readonly document: string; readonly revision: string; readonly tokens: readonly LanguageToken[]; readonly diagnostics: readonly Diagnostic[] }export interface OutlineSpan { readonly start: number; readonly length: number }diff --git a/Aetheris.Web.Runtime/sdk/src/index.js b/Aetheris.Web.Runtime/sdk/src/index.jsindex a40c8347..9cf40cd5 100644--- a/Aetheris.Web.Runtime/sdk/src/index.js+++ b/Aetheris.Web.Runtime/sdk/src/index.js@@ -100,7 +100,7 @@ export class Aetheris {hover: (source, offset, options = {}) => this.transport.request({ operation: 'languageHover', source, offset,sourceName: options.sourceName, sourceRevision: options.sourceRevision }),definition: (source, offset, options = {}) => this.transport.request({ operation: 'languageDefinition', source, offset,- sourceName: options.sourceName, sourceRevision: options.sourceRevision }),+ sourceName: options.sourceName, sourceRevision: options.sourceRevision, projectDocuments: options.projectDocuments, projectRoot: options.projectRoot }),format: (source, options = {}) => this.transport.request({ operation: 'languageFormat', source,sourceName: options.sourceName, sourceRevision: options.sourceRevision })};diff --git a/Aetheris.Web.Runtime/sdk/tests/language.test.mjs b/Aetheris.Web.Runtime/sdk/tests/language.test.mjsindex c6829882..a973a00a 100644--- a/Aetheris.Web.Runtime/sdk/tests/language.test.mjs+++ b/Aetheris.Web.Runtime/sdk/tests/language.test.mjs@@ -2,6 +2,14 @@ import assert from 'node:assert/strict';import test from 'node:test';import { Aetheris } from '../src/index.js';+test('definition lookup retains the in-memory project snapshot', async () => {+ const requests = [];+ const cad = new Aetheris({ request: async request => { requests.push(request); return null; } });+ const options = { sourceName: 'root.firmament', sourceRevision: 'r4', projectRoot: 'root.firmament', projectDocuments: { 'parts/library.firmament': 'Feature member() {}' } };+ await cad.language.definition('member()', 2, options);+ assert.deepEqual(requests, [{ operation: 'languageDefinition', source: 'member()', offset: 2, ...options }]);+});+test('sketch projection and edit retain the authored revision and selected Profile without compiling', async () => {const requests = []; const cad = new Aetheris({ request: async request => { requests.push(request); return { revision: request.sourceRevision }; } });const options = { sourceName: 'part.firmament', sourceRevision: 'r5' };diff --git a/docs/development/architecture/firmament/language-service.md b/docs/development/architecture/firmament/language-service.mdindex 82d75b31..3dda19f2 100644--- a/docs/development/architecture/firmament/language-service.md+++ b/docs/development/architecture/firmament/language-service.md@@ -1,11 +1,58 @@-# Firmament language service X2+# Firmament language service-Firmament language intelligence is owned by `Aetheris.Kernel.Firmament`. `FirmamentLanguageService` supplies schema-backed completion. `FirmamentLanguageAnalysisService` supplies token spans, parser diagnostics, hover, bounded source definition, and formatting. These APIs run without BRep materialization and are exposed by `Aetheris.Web.Runtime` as `languageComplete`, `languageAnalyze`, `languageHover`, `languageDefinition`, and `languageFormat`. The npm SDK forwards those operations. Helios calls the page-thread Web/WASM runtime; geometry builds remain in its Worker. The result records carry document, source revision, and offsets so a later LSP adapter can translate them without owning Firmament semantics.+Firmament language intelligence is owned by `Aetheris.Kernel.Firmament`.+`FirmamentLanguageService` supplies schema-backed completion;+`FirmamentLanguageAnalysisService` supplies token spans, parser diagnostics,+hover, bounded source definitions, and formatting. `Aetheris.Web.Runtime`+exposes these through `languageComplete`, `languageAnalyze`, `languageHover`,+`languageDefinition`, and `languageFormat`; the npm SDK forwards their contracts.+Helios runs language queries in a dedicated WebAssembly Worker separate from+geometry builds. Queries do not materialize BRep. Document identity, revision,+offsets, Monaco model version and cancellation guard asynchronous editor results.-Completion uses generated `FirmamentSemanticSchemas` and existing construct authoring helpers. Model-scope prefixes include legal entry scaffolds for nested constructs such as Helix and Loft. Thread, Perforation, Helix, Loft, Box, and Hole fields are context filtered; bounded choices come from field schema. Selector candidates remain compiled semantic identities in the client, with RuntimeOnly topology excluded.+## Completion and source navigation-Analysis classifies source spans in Aetheris and takes live errors from `FirmamentV2Parser.Parse`; it does not run the geometry pipeline. Current source navigation resolves a uniquely named construct declaration in the same source. Hover covers generated construct and field descriptions. The lexical span mapper and declaration lookup are bounded initial projections; they are not a second parser, and they do not claim full symbol resolution or cross-file navigation.+Completion gets owners and value positions from the shared syntax tree, with+shared tokens recovering incomplete `field:` expressions while typing. Construct+schemas supply field descriptions, required fields, choices, preferred spellings,+and entry examples. Scope projection excludes unrelated construct families.+Fields already authored after the caret are excluded too; the current field is+replaceable across its complete identifier. Strings and comments suppress+completion. Lexical value symbols and scoped parameters supplement schema choices.-`Format` is one opinionated whitespace formatter in Aetheris. It requires parser admission before and after, preserves token text including comments, and is tested for idempotence and a simple Box model's semantic fields. That is not yet a broad semantic-equivalence proof for all Firmament constructs. Helios therefore exposes Format Document but leaves format-on-build disabled. The formatter refuses invalid input; build always receives the authored source.+An entry's `Source` remains the complete reference example. `InsertText` unwraps+the declaration appropriate to the current owner; `Snippet` adds an editable name+tab stop. The client does not infer nesting or author a second catalog. Compiled+selector candidates still come from semantic identities, excluding RuntimeOnly+topology.-Focused language/schema tests: 14 passed. The full Firmament project passed 1,691/1,691 after the completion fix. Aetheris core fast lane: 1,002 passed. The full solution run before that fix exposed the completion regression and an unrelated CLI mesh polygon count failure (905 expected, 908 actual). The full solution gate was not rerun after the fix; the affected Firmament project was.+Hover gets field help from the owning schema and exposes local declaration and+parameter signatures. Definitions resolve unique lexical declaration names and+scoped parameters; the project overload searches the explicit source snapshot.+The SDK transports that snapshot and the Web adapter computes positions using the+target document. Helios opens the file only when Monaco requests navigation,+without changing files during hover or definition-provider lookup. This is bounded+source navigation, not type-aware member binding, rename, or find-all-references.++## Analysis and formatting++Live analysis uses the existing parser and admission owners, without geometry+builds. Thread field errors identify the field when it is unique; ambiguous or+unmapped admission failures retain their disclosed document-level anchor. Assembly+analysis remains project-aware but some diagnostics are still anchored at the+document header. Precise location coverage is not universal.++`Format` arranges part layout and prefers schema-owned vocabulary. It requires+parser admission before and after and preserves tokens, comments, numbers, unit+adjacency, authored names, and specialization syntax such as `Hole<Shaft>`.+Scene and Garment use their existing owners. Valid shared-syntax modules and+assemblies use conservative `FormatConventions` spelling changes with layout+preserved. Formatting does not prove successful project compilation; unsupported+or malformed source is refused. Helios reports the reason, applies accepted edits+as an undoable operation, and leaves format-on-build disabled.++Coverage lives in `FirmamentEditorExperienceTests`, the language-service and+semantic-schema suites, SDK transport tests, and Helios unit/browser tests.+Executable templates compile through the real geometry pipeline; five canonical+Learn parts retain identical STEP output after formatting. The current work report+records full-suite evidence and remaining boundaries.diff --git a/docs/development/reports/2026-11/language-service-polish.md b/docs/development/reports/2026-11/language-service-polish.mdnew file mode 100644index 00000000..b892db18--- /dev/null+++ b/docs/development/reports/2026-11/language-service-polish.md@@ -0,0 +1,59 @@+# Language-service editor polish — 2026-11-02++## Changes++Extended the existing shared-syntax/schema projection rather than adding another+Firmament parser. Completion now distinguishes owners, fields, values, comments+and strings; covers registered owner fields; supplies scoped local symbols;+replaces complete partial identifiers; and prepares context-specific insertions+and name-tab-stop snippets. Existing complete entry examples retain their API+meaning. Added metadata for Model, Modify, Cylinder, Cone, Frustum, Sphere, Torus+and RoundedBox, all backed by existing compiler behavior.++Updated keyword classification, owner-specific hover and bounded parameter and+Feature navigation. Web/SDK definition requests retain explicit project snapshots+and locate targets using their own document text. Thread invalid-field messages+are readable and precisely located when unambiguous. Formatter preserves unit+adjacency and specialization; valid shared-syntax modules and assemblies dispatch+to the conservative spelling pass.++Helios uses an isolated language Worker, guarded Monaco providers and standard+format/find/comment/problem/snippet contributions. Its source bridge handles stale+React updates and document EOL normalization. The sibling HeliosCAD report+`docs/development/reports/2026-11/language-polish.md` covers UI evidence.++## Evidence++- Release full solution build: 0 warnings, 0 errors.+- Core fast lane: 1,168 passed.+- Full solution: 6,371 passed, 0 failed, 2 existing Drawing tests skipped across+ 20 test assemblies. Firmament: 3,393 passed.+- Focused language/schema/scene-authoring feedback: 98 passed.+- SDK transport: 8 passed. Helios units: 238 passed. Language browser cases:+ 6 passed, plus three successful repeated fast-snippet workflows.+- `aetheris validate fixtures/Language/Editor/parameterized-plate.firmament --json`+ reports valid. Six primitive templates compile, and formatting five canonical+ Learn parts plus the Feature fixture preserves exact STEP output.++Logs are ignored `artifacts/local/language-polish-*.log` and+`language-polish-cli-validation.json`. Initial full-suite failures were old Scene+completion and Hole-field expectations; updated them to assert scope-aware+completion and suppression of already-authored fields, then reran the complete+suite successfully. Public style and architecture docs match the current service.++## Remaining boundaries++Definition lookup is lexical and unique-name based, with bounded scoped parameter+support; it is not a general binding/rename service. Some admission diagnostics+still disclose document-level anchors. Conservative formatting does not validate+an imported module's consuming project. Production AOT publish was not rerun.++The UI audit isolated an existing included-Feature compiler failure: splitting+`fixtures/Language/Editor/parameterized-plate.firmament` before `Model editorPart`,+placing the prefix in `parts/library.firmament`, and compiling an include plus the+Model reports Web SDK `internal-error` with details+`ArgumentOutOfRange_IndexLength Arg_ParamName_Name, length`. The same source in one+file validates/builds. Included Learn 06 assembly definitions compile and navigate+correctly. File-local Feature semantics were not broadened in this editor pass;+the sibling Helios ignored `artifacts/local/language-polish/project-audit.*` retain+the exact reproduction. This is a compiler diagnostic/provenance follow-up.diff --git a/docs/public/firmament/language-style.md b/docs/public/firmament/language-style.mdindex 09bf3241..b855a8f5 100644--- a/docs/public/firmament/language-style.md+++ b/docs/public/firmament/language-style.md@@ -58,9 +58,12 @@ It is **not validation**: validate/build the consuming assembly after a sweep.The same pass is available as`FirmamentLanguageAnalysisService.FormatConventions`. The existing standalone-V2 `Format` API also prefers these spellings while arranging layout, and checks-both token equivalence and parser admission. Imported modules use the conservative-pass and their consuming project's compiler; they are not standalone parts.+V2 `Format` API also prefers these spellings while arranging part layout, and checks+both token equivalence and parser admission. For valid shared-syntax modules and+assemblies, `Format` selects the conservative spelling pass and preserves layout.+Validate imported modules with their consuming project's compiler; they are not+standalone parts. Formatting refuses malformed shared syntax and does not claim+that a module will compile in every consuming context.Compatibility is scoped to schema-owned properties, AST-position Profile linksand symmetry fields, plus the bounded frame, assembly, point and wirediff --git a/fixtures/Language/Editor/parameterized-plate.firmament b/fixtures/Language/Editor/parameterized-plate.firmamentnew file mode 100644index 00000000..43ff1921--- /dev/null+++ b/fixtures/Language/Editor/parameterized-plate.firmament@@ -0,0 +1,13 @@+Feature mountHole(center: Point2, diameter: Length = 4mm) -> Hole<Shaft> {+ return Hole<Shaft> { on: +Z; center: center; diameter: diameter; end: ThroughAll }+}++Model editorPart {+ units: mm+ Static thickness: Length = 8mm+ // A commented brace } and a field radius: must not change the editor scope.+ Box stock { size: [40mm, 30mm, thickness] }+ Modify stock {+ mountHole(center: Point2(0mm, 0mm))+ }+}