Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Language outline: declaration graph for visual editors (G0)
Claude1585f637a381
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageOutlineTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageOutlineTests.csnew file mode 100644index 00000000..47dd970f--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageOutlineTests.cs@@ -0,0 +1,164 @@+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentLanguageOutlineTests+{+ private static string Fixture(string relative) =>+ File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(relative));++ private static HashSet<string> EdgeSet(FirmamentLanguageOutline outline) =>+ outline.Edges.Select(e => $"{e.From} -{e.Kind}/{e.Via}-> {e.To}{(e.Member is null ? "" : "." + e.Member)}").ToHashSet();++ [Fact]+ public void ChimeraBaseline_IsTheMotorMountDataflowGraph()+ {+ var outline = FirmamentLanguageOutlineService.Outline(+ Fixture("fixtures/Regression/FrontendX4/chimera.baseline.firmament"), "chimera.baseline.firmament", "7");++ Assert.Equal(FirmamentLanguageOutlineService.Version, outline.Version);+ Assert.Equal("7", outline.Revision);+ Assert.Empty(outline.Diagnostics);+ Assert.Equal(21, outline.Nodes.Count);+ Assert.Equal(+ [+ "MotorMount/Layout/Outline -reference/field:Vertices-> OutlineVertices",+ "MotorMount/Stock -reference/clause:Using-> MotorMount/Layout",+ "MotorMount/Stock/Outer -reference/body-> MotorMount/Layout/Outline",+ "MotorMount/SlotProfile -reference/clause:Using-> MotorMount/Layout",+ "MotorMount/SlotProfile/Outer -reference/body-> MotorMount/Layout/CableSlot",+ "MotorMount/Compose:Body/Plate -reference/field:Profile-> MotorMount/Stock",+ "MotorMount/Compose:Body/Cable -reference/field:Profile-> MotorMount/SlotProfile",+ "MotorMount/Modify:Body -modifies/target-> MotorMount/Compose:Body",+ "MotorMount/Modify:Body/Motor -reference/clause:Over-> MotorBolts",+ "MotorMount/Modify:Body/Motor -call/body-> M3Clearance",+ "MotorMount/Modify:Body/Frame -reference/clause:Over-> FrameHoles",+ "MotorMount/Modify:Body/Frame -call/body-> M5Clearance",+ "MotorMount/Modify:Body/TopBreak -reference/field:Target-> MotorMount/Stock/Outer",+ ], outline.Edges.Select(e => $"{e.From} -{e.Kind}/{e.Via}-> {e.To}{(e.Member is null ? "" : "." + e.Member)}"));++ var pilot = Assert.Single(outline.Nodes, n => n.Id == "MotorMount/Modify:Body/Pilot");+ Assert.Equal(("Hole", "Shaft", "Hole"), (pilot.Kind, pilot.Variant, pilot.SchemaId));+ Assert.Equal(["On", "Center", "Diameter", "End"], pilot.Fields.Select(f => f.Name));+ Assert.Equal("22mm", Assert.Single(pilot.Fields, f => f.Name == "Diameter").Text);+ var feature = Assert.Single(outline.Nodes, n => n.Id == "M3Clearance");+ Assert.Equal(["center"], feature.Parameters);+ Assert.Equal(["MotorMount/Modify:Body/Pilot", "MotorMount/Modify:Body/Motor", "MotorMount/Modify:Body/Frame", "MotorMount/Modify:Body/TopBreak"],+ Assert.Single(outline.Nodes, n => n.Id == "MotorMount/Modify:Body").Children);+ }++ [Fact]+ public void Spans_PointAtTheAuthoredText()+ {+ var source = Fixture("fixtures/Regression/FrontendX4/chimera.baseline.firmament");+ var outline = FirmamentLanguageOutlineService.Outline(source, "c.firmament", "1");+ var pilot = Assert.Single(outline.Nodes, n => n.Id == "MotorMount/Modify:Body/Pilot");+ Assert.StartsWith("Hole<Shaft> Pilot {", source.Substring(pilot.Span.Start, pilot.Span.Length));+ Assert.Equal("Pilot", source.Substring(pilot.NameSpan!.Start, pilot.NameSpan.Length));+ var diameter = Assert.Single(pilot.Fields, f => f.Name == "Diameter");+ Assert.Equal("22mm", source.Substring(diameter.ValueSpan.Start, diameter.ValueSpan.Length));+ var target = Assert.Single(outline.Edges, e => e.Via == "field:Target");+ Assert.Equal("Stock.Outer", source.Substring(target.Span.Start, target.Span.Length));+ }++ [Fact]+ public void Ids_DependOnNamesNotOffsets()+ {+ var source = Fixture("fixtures/Regression/FrontendX4/chimera.baseline.firmament");+ var before = FirmamentLanguageOutlineService.Outline(source, "c.firmament", "1");+ var shifted = FirmamentLanguageOutlineService.Outline("// a comment\n\n" + source.Replace("Diameter: 22mm", "Diameter: 24mm"), "c.firmament", "2");+ Assert.Equal(before.Nodes.Select(n => n.Id), shifted.Nodes.Select(n => n.Id));+ Assert.Equal(EdgeSet(before), EdgeSet(shifted));+ }++ [Fact]+ public void RepeatedNames_AreQualifiedByKindAndOrdinalWithoutRenamingTheFirst()+ {+ const string one = "Model M {\n Box Body { Size: [10mm, 10mm, 2mm] }\n Modify Body { Hole<Shaft> A { On: +Z; Center: Point2(0mm, 0mm); Diameter: 2mm; End: ThroughAll } }\n}\n";+ const string two = "Model M {\n Box Body { Size: [10mm, 10mm, 2mm] }\n Modify Body { Hole<Shaft> A { On: +Z; Center: Point2(0mm, 0mm); Diameter: 2mm; End: ThroughAll } }\n Modify Body { Hole<Shaft> B { On: +Z; Center: Point2(3mm, 0mm); Diameter: 2mm; End: ThroughAll } }\n}\n";+ var a = FirmamentLanguageOutlineService.Outline(one, "a", "1").Nodes.Select(n => n.Id).ToArray();+ var b = FirmamentLanguageOutlineService.Outline(two, "b", "1").Nodes.Select(n => n.Id).ToArray();+ Assert.Contains("M/Box:Body", a);+ Assert.Contains("M/Modify:Body", a);+ Assert.Contains("M/Modify:Body#1/A", b);+ Assert.Contains("M/Modify:Body#2/B", b);+ var edges = FirmamentLanguageOutlineService.Outline(two, "b", "1").Edges.Where(e => e.Kind == "modifies").ToArray();+ Assert.All(edges, e => Assert.Equal("M/Box:Body", e.To));+ Assert.Equal(2, edges.Length);+ }++ [Fact]+ public void VocabularyValues_LoopBindingsAndSelfNames_AreNotDependencies()+ {+ var outline = FirmamentLanguageOutlineService.Outline(+ Fixture("fixtures/Regression/FrontendX4/cases/h00-concept-grid-struct-root.firmament"), "h00", "1");+ var edges = EdgeSet(outline);+ Assert.Contains("GridPlate/Box:Base -reference/field:Bounds-> GridPlate/Design.Bounds", edges);+ Assert.Contains("GridPlate/Modify:Base -modifies/target-> GridPlate/Box:Base", edges);+ Assert.Contains("GridPlate/Modify:Base/Mounts -reference/field:Source-> GridPlate/Design.Points", edges);+ Assert.Contains("GridPlate/Modify:Base/Mounts/Item -reference/field:On-> GridPlate/Box:Base.Top", edges);+ // `Center: Item` names the Pattern's own instance; it is the loop binding, not a wire.+ Assert.DoesNotContain(outline.Edges, e => e.From.EndsWith("/Item", StringComparison.Ordinal) && e.Via == "field:Center");++ var chimera = FirmamentLanguageOutlineService.Outline(+ Fixture("fixtures/Regression/FrontendX4/chimera.baseline.firmament"), "c", "1");+ // `Role: Stock` is vocabulary even though a Profile is named Stock.+ Assert.DoesNotContain(chimera.Edges, e => e.Via == "field:Role");+ // `p => M3Clearance(center: p)`: p is the Pattern's binding.+ Assert.DoesNotContain(chimera.Externals, x => x.Name == "p");+ }++ [Fact]+ public void Templates_LinkSpecializationsArgumentsAndRecordTypes()+ {+ const string source = """+ Record SpacerSpec { OuterDiameter: Length; Height: Length }+ Template<Spec: SpacerSpec> Struct Spacer {+ Box Body { Size: [Spec.OuterDiameter, Spec.OuterDiameter, Spec.Height] }+ }+ Static Short: SpacerSpec = SpacerSpec { OuterDiameter: 10mm; Height: 3mm }+ Model ShortSpacer { Units: mm; Struct Part = Spacer<Spec: Short> }+ """;+ var edges = EdgeSet(FirmamentLanguageOutlineService.Outline(source, "t", "1"));+ Assert.Contains("Spacer -reference/argument:Spec-> SpacerSpec", edges);+ Assert.Contains("Short -reference/annotation-> SpacerSpec", edges);+ Assert.Contains("ShortSpacer/Part -specialization/initializer-> Spacer", edges);+ Assert.Contains("ShortSpacer/Part -reference/initializer-> Short", edges);+ }++ [Fact]+ public void ProjectOutline_ResolvesIncludedDefinitionsAcrossDocuments()+ {+ var root = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/AssemblyInterfaces/IndustrialAtlas");+ var documents = Directory.GetFiles(root, "*.firmament").ToDictionary(Path.GetFileName, File.ReadAllText);+ var outline = FirmamentLanguageOutlineService.Outline(new FirmamentProjectSnapshot("atlas-industrial.firmament", documents!), "atlas-industrial.firmament", "1");++ var cross = outline.Edges.Where(e => e.ToDocument is not null).Select(e => $"{e.From} -> {e.ToDocument}::{e.To}").ToHashSet();+ Assert.Contains("AtlasIndustrial/AtlasIndustrial/Base -> base.firmament::AtlasBase", cross);+ Assert.Contains("AtlasIndustrial/AtlasIndustrial/Gripper -> gripper.firmament::GripperBody", cross);+ Assert.Contains("AtlasIndustrial/AtlasIndustrial/Gripper -> materials.firmament::BlackPaint", cross);+ Assert.Contains(outline.Edges, e => e.From == "AtlasIndustrial/Shoulder" && e.Via == "field:A"+ && e.To == "AtlasIndustrial/AtlasIndustrial/Base" && e.Member == "Hinge");+ Assert.True(Assert.Single(outline.Nodes, n => n.Id == "AtlasIndustrial/AtlasIndustrial/Gripper").Occurrence);+ Assert.Empty(outline.Externals);+ }++ [Fact]+ public void EveryCanonicalFixture_HasUniqueIdsAndOnlyEdgesBetweenItsNodes()+ {+ var root = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical");+ var files = Directory.GetFiles(root, "*.firm*", SearchOption.AllDirectories)+ .Where(f => f.EndsWith(".firmament", StringComparison.Ordinal) || f.EndsWith(".firmasm", StringComparison.Ordinal)).ToArray();+ Assert.NotEmpty(files);+ foreach (var file in files)+ {+ var outline = FirmamentLanguageOutlineService.Outline(File.ReadAllText(file), Path.GetFileName(file), "1");+ var ids = outline.Nodes.Select(n => n.Id).ToArray();+ Assert.True(ids.Length == ids.Distinct(StringComparer.Ordinal).Count(), $"duplicate ids in {file}");+ var known = ids.ToHashSet(StringComparer.Ordinal);+ Assert.All(outline.Edges, e => Assert.True(known.Contains(e.From) && known.Contains(e.To), $"{file}: {e.From} -> {e.To}"));+ Assert.All(outline.Nodes.Where(n => n.ParentId is not null), n => Assert.Contains(n.ParentId!, known));+ }+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageOutline.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageOutline.csnew file mode 100644index 00000000..6d4ea519--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageOutline.cs@@ -0,0 +1,409 @@+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public sealed record FirmamentOutlineSpan(int Start, int Length);++public sealed record FirmamentOutlineField(string Name, string Text, string Shape, FirmamentOutlineSpan Span, FirmamentOutlineSpan ValueSpan);++public sealed record FirmamentOutlineNode(string Id, string Kind, string? Variant, IReadOnlyList<string> Modifiers, string? Name,+ bool Occurrence, string? ParentId, int Order, FirmamentOutlineSpan Span, FirmamentOutlineSpan? NameSpan, string? SchemaId,+ IReadOnlyList<string> Parameters, IReadOnlyList<FirmamentOutlineField> Fields, IReadOnlyList<string> Children);++/// <summary>One resolved name use. <c>Via</c> says where the use sits in the source declaration:+/// <c>field:Profile</c>, <c>clause:Using</c>, <c>clause:Over</c>, <c>target</c>, <c>body</c> (an+/// expression statement or Pattern mapping), <c>argument:Spec</c>, <c>annotation</c>, <c>result</c>.+/// <c>Kind</c> is <c>reference</c>, <c>call</c>, <c>specialization</c>, or, for a declaration whose own+/// name is the use, <c>modifies</c>, <c>asserts</c> or <c>recognizes</c>.</summary>+public sealed record FirmamentOutlineEdge(string From, string To, string Kind, string Via, string? Member,+ FirmamentOutlineSpan Span, bool Ambiguous)+{+ /// <summary>The document that declares <c>To</c> when it is not this one (project outlines only).</summary>+ public string? ToDocument { get; init; }+}++/// <summary>A name use that no declaration in scope answers: a builtin (<c>Point2</c>,+/// <c>TraceLoop</c>), a vocabulary word, or a declaration in another document.</summary>+public sealed record FirmamentOutlineExternal(string From, string Name, string? Member, string Kind, string Via, FirmamentOutlineSpan Span);++public sealed record FirmamentOutlineDiagnostic(string Severity, string Code, string Message, FirmamentOutlineSpan? Span);++public sealed record FirmamentLanguageOutline(string Version, string Document, string Revision,+ IReadOnlyList<FirmamentOutlineNode> Nodes, IReadOnlyList<FirmamentOutlineEdge> Edges,+ IReadOnlyList<FirmamentOutlineExternal> Externals, IReadOnlyList<FirmamentOutlineDiagnostic> Diagnostics);++/// <summary>+/// Declaration graph of one Firmament document for visual editors: every declaration with a+/// stable name-path id, its authored fields, and the resolved name uses between declarations.+/// This is source structure resolved by lexical scope, not compiler admission: an edge says+/// "this declaration names that one", and the build decides whether the use is admitted.+/// </summary>+/// <remarks>+/// Ids are name paths (<c>MotorMount/Body</c>). A name shared by siblings is qualified by kind+/// for every sibling that shares it (<c>MotorMount/Compose:Body</c>, <c>MotorMount/Modify:Body</c>),+/// with a <c>#n</c> ordinal when kind and name both repeat. A nameless declaration is <c>Kind#n</c>.+/// Ids therefore do not depend on source offsets, only on names, kinds and nesting.+/// </remarks>+public static class FirmamentLanguageOutlineService+{+ public const string Version = "firmament-outline/1";++ // Fields whose values are vocabulary, never declaration names, even when a declaration+ // happens to share the word (Role: Stock next to Profile Stock).+ private static readonly HashSet<string> VocabularyFields = new(StringComparer.OrdinalIgnoreCase)+ {+ "Units", "Role", "End", "Kind", "Angle", "Handedness", "Orientation", "Hand", "Rule",+ "Correspondence", "Easing", "Layout", "Direction", "Variant", "Mode", "Policy", "Alignment"+ };++ private static readonly HashSet<string> ChoiceFields = FirmamentSemanticSchemas.All+ .SelectMany(c => c.Fields.Where(f => f.Kind == FirmamentSchemaValueKind.Choice).Select(f => f.Name))+ .ToHashSet(StringComparer.OrdinalIgnoreCase);++ private sealed class Entry+ {+ public required DeclarationSyntax Syntax { get; init; }+ public required string Id { get; init; }+ public Entry? Parent { get; init; }+ public required int Order { get; init; }+ public List<Entry> Children { get; } = [];+ public string Kind => Syntax.Type.Name.Text;+ public string? Name => Syntax.Name?.Text;+ }++ public static FirmamentLanguageOutline Outline(string source, string document, string revision)+ {+ ArgumentNullException.ThrowIfNull(source);+ var parse = FirmamentSyntaxParser.Parse(source, document);+ var roots = new List<Entry>();+ Collect(parse.Document.Statements, null, roots);+ var all = Flatten(roots).ToList();+ var edges = new List<FirmamentOutlineEdge>();+ var externals = new List<FirmamentOutlineExternal>();+ foreach (var entry in all) Resolve(entry, roots, source, edges, externals);+ var nodes = all.Select(entry => Node(entry, source)).ToArray();+ var diagnostics = parse.Diagnostics.Select(d => new FirmamentOutlineDiagnostic(d.Severity, d.Code, d.Message,+ d.SourceSpan is { } s ? new FirmamentOutlineSpan(s.Start, s.Length) : null)).ToArray();+ return new(Version, document, revision, nodes, edges.Distinct().ToArray(), externals.Distinct().ToArray(), diagnostics);+ }++ /// <summary>Outline of one project document. Names its own scopes do not answer are resolved+ /// against the top-level declarations of the other project documents (its includes and+ /// their modules); a resolved use becomes an edge with <c>ToDocument</c> set.</summary>+ public static FirmamentLanguageOutline Outline(Assembly.FirmamentProjectSnapshot project, string document, string revision)+ {+ ArgumentNullException.ThrowIfNull(project);+ if (!project.TryResolve(document, out var source)) throw new ArgumentException("Document is absent from the snapshot.", nameof(document));+ var local = Outline(source, document, revision);+ if (local.Externals.Count == 0) return local;+ var self = Assembly.FirmamentProjectSnapshot.NormalizePath(document);+ var others = project.Documents.Where(d => !string.Equals(d.Key, self, StringComparison.Ordinal))+ .Select(d => Outline(d.Value, d.Key, revision)).ToArray();+ var topLevel = others.SelectMany(o => o.Nodes.Where(n => n.ParentId is null && n.Name is not null && !NameIsUseKind(n))+ .Select(n => (Document: o.Document, Node: n, Outline: o))).ToLookup(x => x.Node.Name!, StringComparer.Ordinal);+ var edges = local.Edges.ToList();+ var remaining = new List<FirmamentOutlineExternal>();+ foreach (var use in local.Externals)+ {+ var candidates = topLevel[use.Name].ToArray();+ if (candidates.Length == 0) { remaining.Add(use); continue; }+ var (doc, node, outline) = candidates[0];+ var target = node;+ var parts = use.Member?.Split('.') ?? [];+ var consumed = 0;+ var byId = outline.Nodes.ToDictionary(n => n.Id, StringComparer.Ordinal);+ while (consumed < parts.Length && target.Children.Select(id => byId[id]).FirstOrDefault(c => c.Name == parts[consumed]) is { } child)+ { target = child; consumed++; }+ var member = consumed < parts.Length ? string.Join(".", parts.Skip(consumed)) : null;+ edges.Add(new(use.From, target.Id, use.Kind, use.Via, member, use.Span, candidates.Length > 1) { ToDocument = doc });+ }+ return local with { Edges = edges, Externals = remaining };+ }++ private static bool NameIsUseKind(FirmamentOutlineNode node) =>+ node.Kind is "Modify" or "modify" or "Recognize" || node.Modifiers.Contains("Assert");++ private static IEnumerable<Entry> Flatten(IEnumerable<Entry> entries) =>+ entries.SelectMany(e => new[] { e }.Concat(Flatten(e.Children)));++ private static void Collect(IEnumerable<StatementSyntax> statements, Entry? parent, List<Entry> into)+ {+ var declarations = statements.SelectMany(DirectDeclarations).ToList();+ var segments = Segments(declarations);+ for (var i = 0; i < declarations.Count; i++)+ {+ var id = parent is null ? segments[i] : parent.Id + "/" + segments[i];+ var entry = new Entry { Syntax = declarations[i], Id = id, Parent = parent, Order = i };+ into.Add(entry);+ Collect(Body(declarations[i]), entry, entry.Children);+ }+ }++ // Declarations reachable from a statement without passing through another declaration:+ // nested blocks and Pattern mappings hold declarations that belong to the enclosing one.+ private static IEnumerable<DeclarationSyntax> DirectDeclarations(StatementSyntax statement) => statement switch+ {+ DeclarationSyntax d => [d],+ StatementBlockSyntax b => b.Body.Statements.SelectMany(DirectDeclarations),+ MappingSyntax m => DirectDeclarations(m.Value),+ ReplacementSyntax r => [r.Replacement],+ _ => []+ };++ private static IEnumerable<StatementSyntax> Body(DeclarationSyntax declaration) =>+ (declaration.Body?.Statements ?? []).Concat(declaration.Initializer is ObjectSyntax o ? o.Body.Statements : []);++ private static string[] Segments(IReadOnlyList<DeclarationSyntax> declarations)+ {+ var nameCounts = declarations.Where(d => d.Name is not null).GroupBy(d => d.Name!.Text, StringComparer.Ordinal)+ .ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal);+ var bases = declarations.Select(d => d.Name is null ? d.Type.Name.Text+ : nameCounts[d.Name.Text] == 1 ? d.Name.Text : d.Type.Name.Text + ":" + d.Name.Text).ToArray();+ var baseCounts = bases.GroupBy(b => b, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.Count(), StringComparer.Ordinal);+ var seen = new Dictionary<string, int>(StringComparer.Ordinal);+ // Every repeat of a basis carries an ordinal, the first included, so adding a second+ // occurrence later in the file never renames the first.+ return bases.Select(b => baseCounts[b] == 1 ? b : b + "#" + (seen[b] = seen.GetValueOrDefault(b) + 1)).ToArray();+ }++ private static FirmamentOutlineNode Node(Entry entry, string source)+ {+ var d = entry.Syntax;+ var variant = d.Type.Arguments.Count == 0 ? null+ : string.Join(", ", d.Type.Arguments.Select(a => Text(source, a.Span)));+ var schema = SchemaFor(entry);+ var fields = Body(d).OfType<FieldSyntax>().Select(f => new FirmamentOutlineField(f.Name.Text,+ Text(source, f.Value.Span), Shape(f.Value), Span(f.Span), Span(f.Value.Span))).ToArray();+ var parameters = d.Parameters.Select(p => p.Name?.Text ?? Text(source, p.Span)).ToArray();+ return new(entry.Id, entry.Kind, variant, d.Modifiers.Select(m => m.Name.Text).ToArray(), entry.Name,+ d.Occurrence, entry.Parent?.Id, entry.Order, Span(d.Span), d.Name is null ? null : Span(d.Name.Span), schema,+ parameters, fields, entry.Children.Select(c => c.Id).ToArray());+ }++ private static string? SchemaFor(Entry entry)+ {+ var name = entry.Kind;+ var variantName = entry.Syntax.Type.Arguments.Count == 1 ? $"{name}<{entry.Syntax.Type.Arguments[0].Value switch { ReferenceSyntax r => r.Name.Text, _ => "" }}>" : null;+ var candidates = FirmamentSemanticSchemas.All.Where(c => c.Name == name || (variantName is not null && c.Name == variantName)).ToArray();+ if (variantName is not null && candidates.Count(c => c.Name == variantName) == 1) return candidates.Single(c => c.Name == variantName).Id.Value;+ return candidates.Length == 1 ? candidates[0].Id.Value : null;+ }++ private static string Shape(ExpressionSyntax expression) => expression switch+ {+ QuantitySyntax => "quantity",+ LiteralSyntax l => l.Kind.ToString().ToLowerInvariant(),+ ReferenceSyntax => "reference",+ MemberSyntax => "member",+ SequenceSyntax => "sequence",+ CallSyntax => "call",+ SpecializationSyntax => "specialization",+ ObjectSyntax => "object",+ BinarySyntax or UnarySyntax => "expression",+ _ => "other"+ };++ private static void Resolve(Entry entry, IReadOnlyList<Entry> roots, string source, List<FirmamentOutlineEdge> edges, List<FirmamentOutlineExternal> externals)+ {+ var d = entry.Syntax;+ var locals = new HashSet<string>(d.Parameters.Select(p => p.Name?.Text).OfType<string>(), StringComparer.Ordinal);+ for (var a = entry.Parent; a is not null; a = a.Parent)+ foreach (var p in a.Syntax.Parameters) if (p.Name is not null) locals.Add(p.Name.Text);++ // `Modify X`, `Assert Volume X` and `Recognize X` name the body they act on: their own name is a use.+ if (NameIsUse(entry) && entry.Name is not null)+ {+ var target = Lookup(entry, roots, [entry.Name], exclude: entry, openUsing: true);+ if (target.Entry is not null)+ edges.Add(new(entry.Id, target.Entry.Id, UseKind(entry), "target", null,+ Span(d.Name!.Span), target.Ambiguous));+ }++ void Uses(ExpressionSyntax? expression, string via, bool vocabulary = false, HashSet<string>? scoped = null, bool quiet = false)+ {+ if (expression is null || vocabulary) return;+ Walk(expression, entry, roots, source, via, locals, scoped, edges, quiet ? null : externals);+ }++ foreach (var c in d.Clauses) Uses(c.Value, "clause:" + c.Kind);+ if (d.Target is not null) Uses(d.Target, "target");+ if (d.Annotation is not null) Uses(d.Annotation, "annotation");+ if (d.ResultType is not null) Uses(d.ResultType, "result");+ // An unnamed type argument is usually a variant word (Hole<Shaft>, Interface<Fixed>): it+ // links when it names a declaration but is never reported as an unresolved use.+ foreach (var a in d.Type.Arguments.Concat(d.Modifiers.SelectMany(m => m.Arguments)))+ Uses(a.Value, "argument:" + (a.Name?.Text ?? "type"), quiet: a.Name is null);+ if (d.Initializer is ObjectSyntax typed) Uses(typed.Type, "initializer");+ else if (d.Initializer is not null) Uses(d.Initializer, "initializer");+ foreach (var s in Body(d)) Statement(s, null);++ void Statement(StatementSyntax s, HashSet<string>? scoped)+ {+ switch (s)+ {+ case FieldSyntax f:+ var vocab = VocabularyFields.Contains(f.Name.Text) || ChoiceFields.Contains(f.Name.Text);+ Uses(f.Value, "field:" + f.Name.Text, vocab && f.Value is ReferenceSyntax, scoped);+ break;+ case ExpressionStatementSyntax e: Uses(e.Value, "body", scoped: scoped); break;+ case ReturnSyntax r: Uses(r.Value, "body", scoped: scoped); break;+ case MappingSyntax m:+ // `key => value`: the key is a loop binding inside a Pattern and a label in a Set.+ var inner = new HashSet<string>(scoped ?? [], StringComparer.Ordinal) { m.Key.Text };+ if (m.Value is not DeclarationSyntax) Statement(m.Value, inner);+ break;+ case StatementBlockSyntax b: foreach (var x in b.Body.Statements) Statement(x, scoped); break;+ }+ }+ }++ private static void Walk(ExpressionSyntax expression, Entry from, IReadOnlyList<Entry> roots, string source, string via,+ HashSet<string> locals, HashSet<string>? scoped, List<FirmamentOutlineEdge> edges, List<FirmamentOutlineExternal>? externals)+ {+ void Recurse(ExpressionSyntax? e) { if (e is not null) Walk(e, from, roots, source, via, locals, scoped, edges, externals); }+ void Nested(string field, ExpressionSyntax e) => Walk(e, from, roots, source, via + "." + field, locals, scoped, edges, externals);+ void Add(IReadOnlyList<string> chain, string kind, FirmamentV2SourceSpan span) =>+ FirmamentLanguageOutlineService.Add(from, roots, chain, kind, via, span, edges, externals);+ bool Local(string name) => locals.Contains(name) || (scoped?.Contains(name) ?? false);++ switch (expression)+ {+ case ReferenceSyntax r:+ if (!Local(r.Name.Text)) Add([r.Name.Text], "reference", r.Span);+ return;+ case MemberSyntax m when Chain(m) is { } chain:+ if (!Local(chain[0])) Add(chain, "reference", m.Span);+ return;+ case CallSyntax c:+ if (c.Target is ReferenceSyntax cr && !Local(cr.Name.Text)) Add([cr.Name.Text], "call", c.Span);+ else if (c.Target is not ReferenceSyntax) Recurse(c.Target);+ foreach (var a in c.Arguments) { Recurse(a.Value); Recurse(a.Default); }+ return;+ case SpecializationSyntax s:+ if (s.Target is ReferenceSyntax sr && !Local(sr.Name.Text)) Add([sr.Name.Text], "specialization", s.Span);+ else Recurse(s.Target);+ foreach (var a in s.Arguments) { Recurse(a.Value); Recurse(a.Default); }+ return;+ case ObjectSyntax o:+ Recurse(o.Type);+ foreach (var f in o.Body.Statements.OfType<FieldSyntax>())+ {+ var vocab = VocabularyFields.Contains(f.Name.Text) || ChoiceFields.Contains(f.Name.Text);+ if (!(vocab && f.Value is ReferenceSyntax)) Nested(f.Name.Text, f.Value);+ }+ foreach (var e in o.Body.Statements.OfType<ExpressionStatementSyntax>()) Recurse(e.Value);+ return;+ case WithSyntax w:+ Recurse(w.Target);+ foreach (var f in w.Body.Statements.OfType<FieldSyntax>()) Nested(f.Name.Text, f.Value);+ return;+ }+ foreach (var child in Children(expression)) Recurse(child);+ }++ private static IEnumerable<ExpressionSyntax> Children(ExpressionSyntax expression) => expression switch+ {+ AliasSyntax a => [a.Value],+ BinarySyntax b => [b.Left, b.Right],+ UnarySyntax u => [u.Operand],+ QuantitySyntax q => [q.Value],+ ToleranceSyntax t => new[] { t.Nominal, t.Plus, t.Minus }.OfType<ExpressionSyntax>(),+ SequenceSyntax s => s.Items.SelectMany(a => new[] { a.Value, a.Default }.OfType<ExpressionSyntax>()),+ MemberSyntax m => [m.Target],+ IndexSyntax i => i.Index is null ? [i.Target] : [i.Target, i.Index],+ TraceSyntax t => new[] { t.Source, t.From, t.To }.OfType<ExpressionSyntax>(),+ TypedValueSyntax t => [t.Type, t.Value],+ ProvenanceSyntax p => [p.Value],+ TypeParameterSyntax p => p.Constraint is null ? [] : [p.Constraint],+ FrameSyntax f => new[] { f.Origin }.Concat(f.Axes.Select(a => a.Value)),+ MemberSetSyntax m => new[] { m.Target }.Concat(m.Members.Select(a => a.Value)),+ MatchSyntax m => new[] { m.Scrutinee }.Concat(m.Arms.SelectMany(a => new[] { a.Pattern, a.Value })),+ _ => []+ };++ // Stock.Outer -> ["Stock", "Outer"]; null when the chain does not start at a plain name.+ private static List<string>? Chain(MemberSyntax member)+ {+ var parts = new List<string>();+ ExpressionSyntax current = member;+ while (current is MemberSyntax m) { parts.Insert(0, m.Member.Text); current = m.Target; }+ if (current is not ReferenceSyntax r) return null;+ parts.Insert(0, r.Name.Text);+ return parts;+ }++ private static void Add(Entry from, IReadOnlyList<Entry> roots, IReadOnlyList<string> chain, string kind, string via,+ FirmamentV2SourceSpan span, List<FirmamentOutlineEdge> edges, List<FirmamentOutlineExternal>? externals)+ {+ var (target, consumed, ambiguous) = Lookup(from, roots, chain, exclude: null, openUsing: true);+ if (target is null)+ {+ externals?.Add(new(from.Id, chain[0], chain.Count > 1 ? string.Join(".", chain.Skip(1)) : null, kind, via, Span(span)));+ return;+ }+ // A name that resolves to the declaration itself or to one of its ancestors is not a+ // dependency (Pattern's `Hole<Shaft> Item { Center: Item }`, a body naming its own host).+ for (var a = from; a is not null; a = a.Parent) if (ReferenceEquals(a, target)) return;+ var member = consumed < chain.Count ? string.Join(".", chain.Skip(consumed)) : null;+ edges.Add(new(from.Id, target.Id, kind, via, member, Span(span), ambiguous));+ }++ private static bool Encloses(Entry candidate, Entry from)+ {+ for (var a = from; a is not null; a = a.Parent) if (ReferenceEquals(a, candidate)) return true;+ return false;+ }++ private readonly record struct Resolution(Entry? Entry, int Consumed, bool Ambiguous);++ private static Resolution Lookup(Entry from, IReadOnlyList<Entry> roots, IReadOnlyList<string> chain, Entry? exclude, bool openUsing)+ {+ var name = chain[0];+ // Scopes from the innermost outward: each enclosing declaration's children, the+ // children of any declaration it opens with `Using`, then the document.+ for (var scope = from; ; scope = scope.Parent)+ {+ IEnumerable<Entry> candidates = scope is null ? roots : scope.Children;+ var visible = candidates.ToList();+ if (scope is not null && openUsing)+ foreach (var clause in scope.Syntax.Clauses.Where(c => c.Kind == ClauseKind.Using && c.Value is ReferenceSyntax))+ {+ // Resolve the opened name from where the clause is written, without opening+ // further Using clauses, so two profiles using each other cannot loop.+ var opened = Lookup(scope, roots, [((ReferenceSyntax)clause.Value).Name.Text], scope, openUsing: false);+ if (opened.Entry is not null) visible.AddRange(opened.Entry.Children);+ }+ // A declaration never resolves its own uses to itself or to an enclosing declaration.+ var matches = visible.Where(e => e.Name == name && !ReferenceEquals(e, exclude) && !Encloses(e, from)).ToList();+ if (matches.Count > 0)+ {+ if (matches.Count > 1)+ {+ var definitions = matches.Where(m => !NameIsUse(m)).ToList();+ if (definitions.Count > 0) matches = definitions;+ }+ var target = matches[0];+ var consumed = 1;+ while (consumed < chain.Count && target.Children.FirstOrDefault(c => c.Name == chain[consumed]) is { } child)+ { target = child; consumed++; }+ return new(target, consumed, matches.Count > 1);+ }+ if (scope is null) return new(null, 0, false);+ }+ }++ private static bool NameIsUse(Entry entry) =>+ entry.Kind is "Modify" or "modify" or "Recognize" || entry.Syntax.Modifiers.Any(m => m.Name.Text == "Assert");++ private static string UseKind(Entry entry) => entry.Kind switch+ {+ "Modify" or "modify" => "modifies",+ "Recognize" => "recognizes",+ _ => "asserts"+ };++ private static string Text(string source, FirmamentV2SourceSpan span) =>+ span.Start >= 0 && span.Start + span.Length <= source.Length ? source.Substring(span.Start, span.Length) : "";++ private static FirmamentOutlineSpan Span(FirmamentV2SourceSpan span) => new(span.Start, span.Length);+}diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.csindex 090bc279..df4d11d0 100644--- a/Aetheris.Web.Runtime/Program.cs+++ b/Aetheris.Web.Runtime/Program.cs@@ -56,6 +56,7 @@ public static partial class Program"compile" => Compile(request),"languageComplete" => LanguageComplete(request),"languageAnalyze" => LanguageAnalyze(request),+ "languageOutline" => LanguageOutline(request),"languageHover" => LanguageHover(request),"languageDefinition" => LanguageDefinition(request),"languageFormat" => LanguageFormat(request),@@ -140,6 +141,17 @@ public static partial class ProgramSourceRefAt(name, request.Source, item.Start, item.Length))).ToArray() };}+ private static object LanguageOutline(WebRequest request)+ {+ if (request.Source is null || string.IsNullOrWhiteSpace(request.SourceRevision))+ throw new WebRuntimeException("language-input-required", "languageOutline requires source and sourceRevision.");+ var name = request.SourceName ?? "model.firmament";+ if (request.ProjectDocuments is not { Count: > 0 })+ return FirmamentLanguageOutlineService.Outline(request.Source, name, request.SourceRevision);+ var documents = new Dictionary<string, string>(request.ProjectDocuments, StringComparer.Ordinal) { [name] = request.Source };+ return FirmamentLanguageOutlineService.Outline(new FirmamentProjectSnapshot(request.ProjectRoot ?? name, documents), name, request.SourceRevision);+ }+private static object? LanguageHover(WebRequest request){if (request.Source is null || request.Offset is null || string.IsNullOrWhiteSpace(request.SourceRevision))diff --git a/Aetheris.Web.Runtime/sdk/README.md b/Aetheris.Web.Runtime/sdk/README.mdindex 702a6921..c9347638 100644--- a/Aetheris.Web.Runtime/sdk/README.md+++ b/Aetheris.Web.Runtime/sdk/README.md@@ -51,6 +51,19 @@ the root is an Assembly. This resolves included ports without touching disk.Single-document analysis remains available; declaration modules without aproject context retain the explicit context-required informational diagnostic.+`cad.language.outline(source, { sourceName, sourceRevision, projectRoot,+projectDocuments })` returns the document's declaration graph for visual editors+(`firmament-outline/1`). Every declaration is a node whose `id` is its name path+(`MotorMount/Modify:Body/Pilot`); a name shared by siblings is qualified by kind,+and a repeat of both carries an ordinal. Ids depend on names, kinds and nesting,+never on offsets. Nodes carry their authored fields with source spans. Edges are+resolved name uses (`field:Profile`, `clause:Using`, `clause:Over`, a Pattern's+Feature call, `Modify X` naming its body) found by lexical scope. With+`projectDocuments`, names the document does not declare are resolved against the+other documents' top-level declarations and carry `toDocument`. Uses nothing+answers are listed as `externals`. The outline is source structure, not+admission: the build still decides whether a use is valid.+Production AOT preserves the semantic provenance record metadata used by thereflection JSON bridge. Package generation clears its owned AOT publish outputbefore publishing, so obsolete fingerprints are not included in the tarball.diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.tsindex 558e5078..e38c1046 100644--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts@@ -31,6 +31,15 @@ export interface LanguageEntry { readonly constructId: string; readonly name: stexport 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 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 }+export interface OutlineField { readonly name: string; readonly text: string; readonly shape: 'quantity' | 'number' | 'string' | 'boolean' | 'version' | 'entityreference' | 'reference' | 'member' | 'sequence' | 'call' | 'specialization' | 'object' | 'expression' | 'other'; readonly span: OutlineSpan; readonly valueSpan: OutlineSpan }+/** One declaration. `id` is its name path (`MotorMount/Modify:Body/Pilot`): stable across edits that keep names, kinds and nesting. */+export interface OutlineNode { readonly id: string; readonly kind: string; readonly variant: string | null; readonly modifiers: readonly string[]; readonly name: string | null; readonly occurrence: boolean; readonly parentId: string | null; readonly order: number; readonly span: OutlineSpan; readonly nameSpan: OutlineSpan | null; readonly schemaId: string | null; readonly parameters: readonly string[]; readonly fields: readonly OutlineField[]; readonly children: readonly string[] }+/** A resolved name use from one declaration to another. `via` is `field:<Name>`, `clause:<Using|Over|On|From|Key>`, `target`, `body`, `argument:<Name|type>`, `annotation`, `result` or `initializer`; nested object fields append `.<Name>`. */+export interface OutlineEdge { readonly from: string; readonly to: string; readonly kind: 'reference' | 'call' | 'specialization' | 'modifies' | 'asserts' | 'recognizes'; readonly via: string; readonly member: string | null; readonly span: OutlineSpan; readonly ambiguous: boolean; readonly toDocument: string | null }+/** A name use no declaration answers: a builtin, a vocabulary word, or a declaration outside the given documents. */+export interface OutlineExternal { readonly from: string; readonly name: string; readonly member: string | null; readonly kind: string; readonly via: string; readonly span: OutlineSpan }+export interface LanguageOutline { readonly version: 'firmament-outline/1'; readonly document: string; readonly revision: string; readonly nodes: readonly OutlineNode[]; readonly edges: readonly OutlineEdge[]; readonly externals: readonly OutlineExternal[]; readonly diagnostics: readonly { readonly severity: string; readonly code: string; readonly message: string; readonly span: OutlineSpan | null }[] }export interface LanguageHover { readonly document: string; readonly revision: string; readonly start: number; readonly length: number; readonly title: string; readonly description: string }export interface LanguageFormat { readonly document: string; readonly revision: string; readonly text: string; readonly changed: boolean }export interface SemanticFieldSchema { readonly id: string; readonly name: string; readonly kind: string; readonly unit: 'None' | 'Length' | 'Angle'; readonly required: boolean; readonly default: string | null; readonly choices: readonly string[]; readonly description: string | null; readonly sourceEditable: boolean }@@ -48,7 +57,7 @@ export class Aetheris {static create(options?: AetherisOptions): Promise<Aetheris>;readonly runtimeInfo: RuntimeInfo;readonly workerTiming: WorkerTiming | null;- readonly language: { complete(source: string, offset: number, options: LanguageOptions): Promise<LanguageCompletion>; analyze(source: string, options: LanguageOptions): Promise<LanguageAnalysis>; 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: { complete(source: string, offset: number, options: LanguageOptions): Promise<LanguageCompletion>; analyze(source: string, options: LanguageOptions): Promise<LanguageAnalysis>; outline(source: string, options: LanguageOptions): Promise<LanguageOutline>; 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 61a27204..23ab8289 100644--- a/Aetheris.Web.Runtime/sdk/src/index.js+++ b/Aetheris.Web.Runtime/sdk/src/index.js@@ -86,6 +86,8 @@ export class Aetheris {sourceName: options.sourceName, sourceRevision: options.sourceRevision }),analyze: (source, options = {}) => this.transport.request({ operation: 'languageAnalyze', source,sourceName: options.sourceName, sourceRevision: options.sourceRevision, projectDocuments: options.projectDocuments, projectRoot: options.projectRoot }),+ outline: (source, options = {}) => this.transport.request({ operation: 'languageOutline', source,+ sourceName: options.sourceName, sourceRevision: options.sourceRevision, projectDocuments: options.projectDocuments, projectRoot: options.projectRoot }),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,diff --git a/Aetheris.Web.Runtime/sdk/tests/language.test.mjs b/Aetheris.Web.Runtime/sdk/tests/language.test.mjsindex 08507f6b..123df138 100644--- a/Aetheris.Web.Runtime/sdk/tests/language.test.mjs+++ b/Aetheris.Web.Runtime/sdk/tests/language.test.mjs@@ -26,3 +26,18 @@ test('public semantic schema uses the versioned runtime contract', async () => {assert.equal(schema.version, 'firmament-semantic-schema/1');assert.deepEqual(requests, [{ operation: 'languageSchema' }]);});++test('public language outline sends source, revision and project context through runtime transport', async () => {+ const requests = [];+ const cad = new Aetheris({ request: async request => {+ requests.push(request);+ return { version: 'firmament-outline/1', document: request.sourceName, revision: request.sourceRevision,+ nodes: [], edges: [], externals: [], diagnostics: [] };+ } });+ const outline = await cad.language.outline('Model M { Units: mm }',+ { sourceName: 'root.firmament', sourceRevision: 'r9', projectRoot: 'root.firmament', projectDocuments: { 'part.firmament': 'Struct P {}' } });+ assert.equal(outline.version, 'firmament-outline/1');+ assert.equal(outline.revision, 'r9');+ assert.deepEqual(requests, [{ operation: 'languageOutline', source: 'Model M { Units: mm }', sourceName: 'root.firmament',+ sourceRevision: 'r9', projectDocuments: { 'part.firmament': 'Struct P {}' }, projectRoot: 'root.firmament' }]);+});