Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Support project snapshot assembly compilation

Yuechen Lif7c3658c123c
diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/FirmamentProjectSnapshotTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/FirmamentProjectSnapshotTests.cs
new file mode 100644
index 00000000..641cb42b
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/FirmamentProjectSnapshotTests.cs
@@ -0,0 +1,65 @@
+using Aetheris.Kernel.Firmament.Assembly;
+
+namespace Aetheris.Kernel.Firmament.Tests.Assembly;
+
+public sealed class FirmamentProjectSnapshotTests
+{
+ [Fact]
+ public void PathsAreNormalizedAndCannotEscapeTheProject()
+ {
+ var project = new FirmamentProjectSnapshot("./main.firmasm",
+ [KeyValuePair.Create("parts/./shade.firmament", "source")]);
+ Assert.Equal("main.firmasm", project.RootDocument);
+ Assert.True(project.TryResolve("parts/shade.firmament", out var source));
+ Assert.Equal("source", source);
+ Assert.Throws<ArgumentException>(() => new FirmamentProjectSnapshot("main.firmasm",
+ [KeyValuePair.Create("parts/shade.firmament", "a"), KeyValuePair.Create("parts/./shade.firmament", "b")]));
+ Assert.Throws<ArgumentException>(() => FirmamentProjectSnapshot.NormalizePath("../secret.firmament"));
+ Assert.Throws<ArgumentException>(() => FirmamentProjectSnapshot.NormalizePath("C:/secret.firmament"));
+ }
+
+ [Fact]
+ public void IncludeCycleIsDiagnosedWithoutFilesystemAccess()
+ {
+ var project = new FirmamentProjectSnapshot("main.firmasm", [
+ KeyValuePair.Create("main.firmasm", "Include \"parts/a.firmament\";\nAssembly Root { <Assembly Root></Assembly> Anchor: Root; }"),
+ KeyValuePair.Create("parts/a.firmament", "Include \"parts/b.firmament\";"),
+ KeyValuePair.Create("parts/b.firmament", "Include \"parts/a.firmament\";")]);
+ var result = new AssemblyM1Pipeline().CompileProject(project);
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "assembly-include-cycle" &&
+ diagnostic.Message.Contains("parts/a.firmament -> parts/b.firmament -> parts/a.firmament", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void MissingIncludeNamesTheRequestedProjectPath()
+ {
+ var project = new FirmamentProjectSnapshot("main.firmasm", [
+ KeyValuePair.Create("main.firmasm", "Include \"parts/missing.firmament\";\nAssembly Root { <Assembly Root></Assembly> Anchor: Root; }")]);
+ var result = new AssemblyM1Pipeline().CompileProject(project);
+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "assembly-include-file-not-found" &&
+ diagnostic.Message.Contains("parts/missing.firmament", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ProjectSnapshotRejectsExternalStepBeforeItCanReadDisk()
+ {
+ var project = new FirmamentProjectSnapshot("main.firmasm", [
+ KeyValuePair.Create("main.firmasm", "Assembly Root { <Assembly Root><Part External = ExternalStep<\"C:/secret.step\">></Part></Assembly> Anchor: Root; }")]);
+ var result = new AssemblyM1Pipeline().CompileProject(project);
+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "assembly-profile-external-resource-unsupported");
+ }
+
+ [Fact]
+ public void LampShadeBuildsFromSnapshotWithoutDiskRelativeToTheAssembly()
+ {
+ var lamp = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/ThreeDm/lamp-visible-intent.firmament"));
+ var shade = File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/ThreeDm/lamp-shade-loft.firmament"));
+ var project = new FirmamentProjectSnapshot("main.firmasm", [
+ KeyValuePair.Create("main.firmasm", lamp),
+ KeyValuePair.Create("lamp-shade-loft.firmament", shade)]);
+ var result = new AssemblyM1Pipeline().CompileProject(project);
+ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics.Select(item => $"{item.Code}: {item.Message}")));
+ Assert.Equal(7, result.Geometry!.InstanceBodies.Count);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs
index 9e3d0a8d..ffd9b671 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs
@@ -26,6 +26,61 @@ public sealed class AssemblyM0Parser
return new(parsed.Source is null ? null : parsed.Source with { SourceDependencies = dependencies }, diagnostics, parsed.ElapsedMilliseconds);
}
+ public ParseResult ParseProject(FirmamentProjectSnapshot project)
+ {
+ ArgumentNullException.ThrowIfNull(project);
+ var diagnostics = new List<AssemblyDiagnostic>();
+ var dependencies = new List<AssemblySourceDependencyIr>();
+ var source = LoadProjectSource(project.RootDocument, project, [], dependencies, diagnostics);
+ if (source is null) return new(null, diagnostics, 0);
+ var parsed = Parse(source, project.RootDocument);
+ return new(parsed.Source is null ? null : parsed.Source with { SourceDependencies = dependencies },
+ [.. diagnostics, .. parsed.Diagnostics], parsed.ElapsedMilliseconds);
+ }
+
+ private static string? LoadProjectSource(string path, FirmamentProjectSnapshot project,
+ IReadOnlyList<string> stack, List<AssemblySourceDependencyIr> dependencies, List<AssemblyDiagnostic> diagnostics)
+ {
+ var cycleAt = stack.ToList().FindIndex(item => string.Equals(item, path, StringComparison.Ordinal));
+ if (cycleAt >= 0)
+ {
+ diagnostics.Add(new("assembly-include-cycle", $"Compile-time Include cycle: {string.Join(" -> ", stack.Skip(cycleAt).Append(path))}."));
+ return null;
+ }
+ if (!project.TryResolve(path, out var text))
+ {
+ diagnostics.Add(new("assembly-include-file-not-found", $"Project document '{path}' was not found."));
+ return null;
+ }
+ if (stack.Count > 0 && !path.EndsWith(".firmament", StringComparison.OrdinalIgnoreCase))
+ {
+ diagnostics.Add(new("assembly-include-extension-invalid", $"Compile-time Include '{path}' must reference a .firmament semantic source file."));
+ return null;
+ }
+ if (dependencies.Any(item => string.Equals(item.Path, path, StringComparison.Ordinal))) return string.Empty;
+ var hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(text)));
+ dependencies.Add(new(path, hash, stack.Count == 0));
+ var declarations = new List<string>();
+ foreach (Match include in Regex.Matches(text, @"^[ \t]*Include\s+""(?<path>[^""]+)""\s*;", RegexOptions.CultureInvariant | RegexOptions.Multiline))
+ {
+ string childPath;
+ try
+ {
+ childPath = FirmamentProjectSnapshot.NormalizePath(include.Groups["path"].Value);
+ }
+ catch (ArgumentException)
+ {
+ diagnostics.Add(new("assembly-include-outside-root", $"Include '{include.Groups["path"].Value}' in '{path}' escapes the project root or uses an invalid path."));
+ return null;
+ }
+ var child = LoadProjectSource(childPath, project, [.. stack, path], dependencies, diagnostics);
+ if (child is null) return null;
+ declarations.Add(child);
+ }
+ declarations.Add(Regex.Replace(text, @"^[ \t]*Include\s+""[^""]+""\s*;[ \t]*(?:\r?\n)?", string.Empty, RegexOptions.CultureInvariant | RegexOptions.Multiline));
+ return string.Join(Environment.NewLine, declarations);
+ }
+
private static string FindAllowedSourceRoot(string path)
{
var directory = new DirectoryInfo(Path.GetDirectoryName(path)!);
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
index e793998b..3ddbe33b 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs
@@ -58,7 +58,7 @@ internal sealed record MaterializedAssemblyDefinition(
/// </summary>
internal static class AssemblyDefinitionMaterializer
{
- public static MaterializedAssemblyDefinition? TryMaterialize(string definitionIdentity, string? definitionSource, string sourceIdentity, List<AssemblyDiagnostic> diagnostics)
+ public static MaterializedAssemblyDefinition? TryMaterialize(string definitionIdentity, string? definitionSource, string sourceIdentity, List<AssemblyDiagnostic> diagnostics, FirmamentProjectSnapshot? project = null)
{
if (!string.IsNullOrWhiteSpace(definitionSource))
{
@@ -68,14 +68,43 @@ internal static class AssemblyDefinitionMaterializer
"^(?:SectionChainFile|LoftFile)<\\\"(?<path>[^\\\"]+)\\\">$", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
if (sectionFile.Success)
{
- var baseDirectory = Path.GetDirectoryName(Path.GetFullPath(sourceIdentity)) ?? Directory.GetCurrentDirectory();
- var sectionPath = Path.GetFullPath(Path.Combine(baseDirectory, sectionFile.Groups["path"].Value.Replace('/', Path.DirectorySeparatorChar)));
- if (!File.Exists(sectionPath))
+ var requestedPath = sectionFile.Groups["path"].Value;
+ string sectionPath;
+ string sectionSource;
+ if (project is not null)
{
- diagnostics.Add(new("assembly-profile-unresolved-resource", $"SectionChain source '{sectionFile.Groups["path"].Value}' was not found at '{sectionPath}'."));
- return null;
+ try
+ {
+ sectionPath = FirmamentProjectSnapshot.NormalizePath(requestedPath);
+ }
+ catch (ArgumentException)
+ {
+ diagnostics.Add(new("assembly-profile-invalid-resource-path", $"SectionChain source '{requestedPath}' escapes the project root or uses an invalid path."));
+ return null;
+ }
+ if (!sectionPath.EndsWith(".firmament", StringComparison.OrdinalIgnoreCase))
+ {
+ diagnostics.Add(new("assembly-profile-resource-kind-invalid", $"SectionChain source '{sectionPath}' must be a .firmament document."));
+ return null;
+ }
+ if (!project.TryResolve(sectionPath, out sectionSource!))
+ {
+ diagnostics.Add(new("assembly-profile-unresolved-resource", $"SectionChain source '{sectionPath}' was not found in the project snapshot."));
+ return null;
+ }
+ }
+ else
+ {
+ var baseDirectory = Path.GetDirectoryName(Path.GetFullPath(sourceIdentity)) ?? Directory.GetCurrentDirectory();
+ sectionPath = Path.GetFullPath(Path.Combine(baseDirectory, requestedPath.Replace('/', Path.DirectorySeparatorChar)));
+ if (!File.Exists(sectionPath))
+ {
+ diagnostics.Add(new("assembly-profile-unresolved-resource", $"SectionChain source '{requestedPath}' was not found at '{sectionPath}'."));
+ return null;
+ }
+ sectionSource = File.ReadAllText(sectionPath);
}
- var section = SectionChainAuthoringParser.Compile(File.ReadAllText(sectionPath));
+ var section = SectionChainAuthoringParser.Compile(sectionSource);
if (!section.IsSuccess || section.Materialization?.Body is not { } sectionBody ||
section.Materialization.StructureKind != SectionChainStructureKind.ClosedSolid)
{
@@ -141,6 +170,11 @@ internal static class AssemblyDefinitionMaterializer
var externalStep = System.Text.RegularExpressions.Regex.Match(definitionIdentity, "^ExternalStep<\\\"(?<path>[^\\\"]+)\\\">$", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
if (externalStep.Success)
{
+ if (project is not null)
+ {
+ diagnostics.Add(new("assembly-profile-external-resource-unsupported", "ExternalStep is not a project source document and cannot be resolved from a Firmament project snapshot."));
+ return null;
+ }
var baseDirectory = Path.GetDirectoryName(Path.GetFullPath(sourceIdentity)) ?? Directory.GetCurrentDirectory();
var resolvedPath = Path.GetFullPath(Path.Combine(baseDirectory, externalStep.Groups["path"].Value.Replace('/', Path.DirectorySeparatorChar)));
if (!File.Exists(resolvedPath))
@@ -295,14 +329,30 @@ public sealed class AssemblyM1Pipeline
return CompileParsed(parsed, domainMaterializer);
}
- private static AssemblyM1CompilationResult CompileParsed(AssemblyM0Parser.ParseResult parsed, AssemblyPartMaterializer? domainMaterializer)
+ public AssemblyM1CompilationResult CompileProject(FirmamentProjectSnapshot project)
+ {
+ ArgumentNullException.ThrowIfNull(project);
+ var profile = project.TryResolve(project.RootDocument, out var root)
+ ? FirmamentAssemblyDocumentCompiler.ValidateProfile(root, FirmamentDocumentProfile.Assembly)
+ : [];
+ if (profile.Any(diagnostic => diagnostic.Severity == AssemblyDiagnosticSeverity.Error))
+ return new(null, null, profile);
+ var parsed = new AssemblyM0Parser().ParseProject(project);
+ if (parsed.Source?.DefinitionSource is { } declarations &&
+ System.Text.RegularExpressions.Regex.IsMatch(declarations, @"\bInlineStep\b", System.Text.RegularExpressions.RegexOptions.CultureInvariant))
+ return new(null, null, [new AssemblyDiagnostic("assembly-profile-external-resource-unsupported",
+ "InlineStep requires an external STEP asset and is unsupported in a Firmament project snapshot.")]);
+ return CompileParsed(parsed, null, project);
+ }
+
+ private static AssemblyM1CompilationResult CompileParsed(AssemblyM0Parser.ParseResult parsed, AssemblyPartMaterializer? domainMaterializer, FirmamentProjectSnapshot? project = null)
{
if (!parsed.IsSuccess || parsed.Source is null) return new(null, null, parsed.Diagnostics);
var diagnostics = parsed.Diagnostics.ToList();
var materializationWatch = Stopwatch.StartNew();
var definitions = parsed.Source.Root.Flatten().Where(member => member.Kind == AssemblyInstanceKind.Part)
.Select(member => member.DefinitionIdentity).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)
- .Select(identity => Materialize(identity, parsed.Source.DefinitionSource, parsed.Source.SourceIdentity, diagnostics, domainMaterializer))
+ .Select(identity => Materialize(identity, parsed.Source.DefinitionSource, parsed.Source.SourceIdentity, diagnostics, domainMaterializer, project))
.Where(definition => definition is not null).Cast<MaterializedAssemblyDefinition>().ToDictionary(definition => definition.DefinitionIdentity, StringComparer.Ordinal);
materializationWatch.Stop();
var enriched = parsed.Source with { Root = Enrich(parsed.Source.Root, definitions) };
@@ -321,7 +371,7 @@ public sealed class AssemblyM1Pipeline
}
private static MaterializedAssemblyDefinition? Materialize(string identity, string? declarations, string sourceIdentity,
- List<AssemblyDiagnostic> diagnostics, AssemblyPartMaterializer? domainMaterializer)
+ List<AssemblyDiagnostic> diagnostics, AssemblyPartMaterializer? domainMaterializer, FirmamentProjectSnapshot? project)
{
if (domainMaterializer?.Invoke(identity, declarations, sourceIdentity, diagnostics) is { } supplied)
{
@@ -334,7 +384,7 @@ public sealed class AssemblyM1Pipeline
AssemblyDefinitionMaterializer.Metrics(supplied.Body), supplied.Provenance);
return new(identity, supplied.SpecializationIdentity, supplied.Body, supplied.Semantics ?? [], artifact);
}
- return AssemblyDefinitionMaterializer.TryMaterialize(identity, declarations, sourceIdentity, diagnostics);
+ return AssemblyDefinitionMaterializer.TryMaterialize(identity, declarations, sourceIdentity, diagnostics, project);
}
private static AssemblyMemberSource Enrich(AssemblyMemberSource member, IReadOnlyDictionary<string, MaterializedAssemblyDefinition> definitions)
diff --git a/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs b/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs
new file mode 100644
index 00000000..6c4b15c5
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Assembly/FirmamentProjectSnapshot.cs
@@ -0,0 +1,53 @@
+using System.Collections.Frozen;
+
+namespace Aetheris.Kernel.Firmament.Assembly;
+
+/// <summary>An immutable, project-relative source set for an assembly build.</summary>
+public sealed class FirmamentProjectSnapshot
+{
+ private readonly IReadOnlyDictionary<string, string> documents;
+
+ public string RootDocument { get; }
+ public IReadOnlyDictionary<string, string> Documents => documents;
+
+ public FirmamentProjectSnapshot(string rootDocument, IEnumerable<KeyValuePair<string, string>> documents)
+ {
+ ArgumentNullException.ThrowIfNull(documents);
+ RootDocument = NormalizePath(rootDocument);
+ if (!RootDocument.EndsWith(".firmasm", StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException("The project root must be a .firmasm document.", nameof(rootDocument));
+ var normalized = new Dictionary<string, string>(StringComparer.Ordinal);
+ foreach (var (path, source) in documents)
+ {
+ var key = NormalizePath(path);
+ if (!key.EndsWith(".firmasm", StringComparison.OrdinalIgnoreCase) &&
+ !key.EndsWith(".firmament", StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException($"Unsupported project document kind: '{key}'.", nameof(documents));
+ if (!normalized.TryAdd(key, source ?? throw new ArgumentException($"Null source for '{key}'.", nameof(documents))))
+ throw new ArgumentException($"Duplicate normalized project path: '{key}'.", nameof(documents));
+ }
+ this.documents = normalized.ToFrozenDictionary(StringComparer.Ordinal);
+ }
+
+ public static string NormalizePath(string path)
+ {
+ if (string.IsNullOrWhiteSpace(path) || path.StartsWith('/') || path.StartsWith('\\') ||
+ path.Contains(':') || path.Contains('?') || path.Contains('#'))
+ throw new ArgumentException($"Invalid project-relative path: '{path}'.", nameof(path));
+ var parts = new List<string>();
+ foreach (var part in path.Replace('\\', '/').Split('/'))
+ {
+ if (part is "" or ".") continue;
+ if (part == "..")
+ {
+ if (parts.Count == 0) throw new ArgumentException($"Path escapes project root: '{path}'.", nameof(path));
+ parts.RemoveAt(parts.Count - 1);
+ }
+ else parts.Add(part);
+ }
+ if (parts.Count == 0) throw new ArgumentException($"Empty project path: '{path}'.", nameof(path));
+ return string.Join('/', parts);
+ }
+
+ public bool TryResolve(string path, out string source) => documents.TryGetValue(NormalizePath(path), out source!);
+}
diff --git a/docs/public/firmament/project-snapshots.md b/docs/public/firmament/project-snapshots.md
new file mode 100644
index 00000000..931c456f
--- /dev/null
+++ b/docs/public/firmament/project-snapshots.md
@@ -0,0 +1,7 @@
+# In-memory assembly project snapshots
+
+`FirmamentProjectSnapshot` accepts one explicit `.firmasm` root and a finite map of project-relative `.firmasm` and `.firmament` source documents. `AssemblyM1Pipeline.CompileProject(snapshot)` resolves `Include` declarations and `LoftFile`/`SectionChainFile` sources from that map. Paths use `/`, normalize `.` and `..`, and reject paths outside the project root. The local `CompileFile` path remains available for CLI use.
+
+This compiler entry point can materialize the canonical Cartesian lamp assembly and its shade from two in-memory source strings. It does not yet expose a browser SDK project API. Its `Include` syntax currently accepts `.firmament` documents only, so nested `.firmasm` project documents are not supported. `ExternalStep` and `InlineStep` are rejected for snapshot compilation because the snapshot contains source documents, not binary STEP assets.
+
+The assembly parser currently combines included declarations into the root source before binding. Dependency hashes identify included documents, but construct source ranges within those declarations do not yet retain their original document path. Multi-document source navigation requires that provenance work before an IDE can claim accurate cross-file selection.