Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add canonical Firmament formatter skeleton
Yuechen Li0fe2a0f1745c
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentFormatterTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentFormatterTests.csnew file mode 100644index 00000000..410f19f0--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentFormatterTests.cs@@ -0,0 +1,104 @@+using Aetheris.Kernel.Firmament.Parsing;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentFormatterTests+{+ [Theory]+ [InlineData("testdata/firmament/fixtures/m3a-valid-primitive-only-lower.firmament")]+ [InlineData("testdata/firmament/fixtures/m3b-mixed-primitive-boolean-validation.firmament")]+ [InlineData("testdata/firmament/fixtures/m7a-valid-box-origin-placement.firmament")]+ [InlineData("testdata/firmament/fixtures/m8a-valid-schema-cnc.firmament")]+ [InlineData("testdata/firmament/fixtures/m8a-valid-schema-additive.firmament")]+ [InlineData("testdata/firmament/fixtures/m8a-valid-schema-injection-molded.firmament")]+ public void Format_CanonicalFixtures_RoundTrip_As_ByteForByte_NoOp(string fixturePath)+ {+ var source = FirmamentCorpusHarness.ReadFixtureText(fixturePath);++ var result = Format(source);++ Assert.True(result.Formatting.IsSuccess);+ Assert.Equal(source, result.Formatting.Value.Text);+ }++ [Theory]+ [InlineData("testdata/firmament/fixtures/m3a-valid-primitive-only-lower.firmament")]+ [InlineData("testdata/firmament/fixtures/m3b-mixed-primitive-boolean-validation.firmament")]+ [InlineData("testdata/firmament/fixtures/m7d-valid-boolean-selector-placement.firmament")]+ [InlineData("testdata/firmament/fixtures/m8c-valid-schema-cnc-minimum-tool-radius.firmament")]+ public void Format_Is_Deterministic_For_Supported_Canonical_Fixtures(string fixturePath)+ {+ var source = FirmamentCorpusHarness.ReadFixtureText(fixturePath);++ var first = Format(source);+ var second = Format(source);+ var third = Format(first.Formatting.Value.Text);++ Assert.True(first.Formatting.IsSuccess);+ Assert.True(second.Formatting.IsSuccess);+ Assert.True(third.Formatting.IsSuccess);+ Assert.Equal(first.Formatting.Value.Text, second.Formatting.Value.Text);+ Assert.Equal(first.Formatting.Value.Text, third.Formatting.Value.Text);+ }++ [Theory]+ [InlineData("testdata/firmament/fixtures/m3b-mixed-primitive-boolean-validation.firmament")]+ [InlineData("testdata/firmament/fixtures/m7d-valid-boolean-selector-placement.firmament")]+ [InlineData("testdata/firmament/fixtures/m8a-valid-schema-injection-molded.firmament")]+ public void Format_Does_Not_Change_Parsed_Meaning_For_Supported_Fixtures(string fixturePath)+ {+ var source = FirmamentCorpusHarness.ReadFixtureText(fixturePath);+ var formatted = Format(source);++ Assert.True(formatted.Formatting.IsSuccess);++ var originalParse = FirmamentTopLevelParser.Parse(source);+ var reparsed = FirmamentTopLevelParser.Parse(formatted.Formatting.Value.Text);++ Assert.True(originalParse.IsSuccess);+ Assert.True(reparsed.IsSuccess);+ Assert.Equivalent(originalParse.Value, reparsed.Value);+ }++ [Fact]+ public void Format_CanonicalPmiSection_Preserves_EmptyExplicitArrayShape()+ {+ const string source = """+ firmament:+ version: 1++ model:+ name: demo+ units: mm++ ops[0]:++ pmi[0]:+ """;++ var result = Format(source);++ Assert.True(result.Formatting.IsSuccess);+ Assert.Equal(FirmamentCorpusHarness.NormalizeLf(source) + "\n", result.Formatting.Value.Text);+ }++ [Fact]+ public void Format_InvalidInput_Reuses_ParseFailureDiagnostics()+ {+ const string source = """+ firmament+ version: 1+ """;++ var result = Format(source);++ Assert.False(result.Formatting.IsSuccess);+ Assert.NotEmpty(result.Formatting.Diagnostics);+ }++ private static FirmamentFormatResult Format(string source)+ {+ var formatter = new FirmamentFormatter();+ return formatter.Format(new FirmamentFormatRequest(new FirmamentSourceDocument(FirmamentCorpusHarness.NormalizeLf(source))));+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentFormatRequest.cs b/Aetheris.Kernel.Firmament/FirmamentFormatRequest.csnew file mode 100644index 00000000..8ebcfbe9--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentFormatRequest.cs@@ -0,0 +1,3 @@+namespace Aetheris.Kernel.Firmament;++public sealed record FirmamentFormatRequest(FirmamentSourceDocument Document);diff --git a/Aetheris.Kernel.Firmament/FirmamentFormatResult.cs b/Aetheris.Kernel.Firmament/FirmamentFormatResult.csnew file mode 100644index 00000000..ff0cb272--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentFormatResult.cs@@ -0,0 +1,7 @@+using Aetheris.Kernel.Core.Results;++namespace Aetheris.Kernel.Firmament;++public sealed record FirmamentFormatResult(KernelResult<FirmamentFormattedDocument> Formatting);++public sealed record FirmamentFormattedDocument(string Text, ParsedModel.FirmamentParsedDocument ParsedDocument);diff --git a/Aetheris.Kernel.Firmament/FirmamentFormatter.cs b/Aetheris.Kernel.Firmament/FirmamentFormatter.csnew file mode 100644index 00000000..6d7696dd--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentFormatter.cs@@ -0,0 +1,25 @@+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Firmament.Formatting;+using Aetheris.Kernel.Firmament.Parsing;++namespace Aetheris.Kernel.Firmament;++public sealed class FirmamentFormatter+{+ public FirmamentFormatResult Format(FirmamentFormatRequest request)+ {+ ArgumentNullException.ThrowIfNull(request);++ var parseResult = FirmamentTopLevelParser.Parse(request.Document.SourceText);+ if (!parseResult.IsSuccess)+ {+ return new FirmamentFormatResult(+ KernelResult<FirmamentFormattedDocument>.Failure(parseResult.Diagnostics));+ }++ var formattedText = FirmamentCanonicalFormatter.Format(parseResult.Value);+ return new FirmamentFormatResult(+ KernelResult<FirmamentFormattedDocument>.Success(+ new FirmamentFormattedDocument(formattedText, parseResult.Value)));+ }+}diff --git a/Aetheris.Kernel.Firmament/Formatting/FirmamentCanonicalFormatter.cs b/Aetheris.Kernel.Firmament/Formatting/FirmamentCanonicalFormatter.csnew file mode 100644index 00000000..de964150--- /dev/null+++ b/Aetheris.Kernel.Firmament/Formatting/FirmamentCanonicalFormatter.cs@@ -0,0 +1,259 @@+using System.Globalization;+using System.Linq;+using System.Text;+using Aetheris.Kernel.Firmament.ParsedModel;++namespace Aetheris.Kernel.Firmament.Formatting;++internal static class FirmamentCanonicalFormatter+{+ private const string IndentUnit = " ";++ public static string Format(FirmamentParsedDocument document)+ {+ ArgumentNullException.ThrowIfNull(document);++ var builder = new StringBuilder();+ AppendHeaderSection(builder, document.Firmament);+ builder.AppendLine();+ AppendModelSection(builder, document.Model);++ if (document.Schema is not null)+ {+ builder.AppendLine();+ AppendSchemaSection(builder, document.Schema);+ }++ builder.AppendLine();+ AppendOpsSection(builder, document.Ops);++ if (document.HasPmi)+ {+ builder.AppendLine();+ builder.Append("pmi[0]:\n");+ }++ return builder.ToString();+ }++ private static void AppendHeaderSection(StringBuilder builder, FirmamentParsedHeader header)+ {+ builder.Append("firmament:\n");+ AppendScalarField(builder, 1, "version", header.Version);+ }++ private static void AppendModelSection(StringBuilder builder, FirmamentParsedModelHeader model)+ {+ builder.Append("model:\n");+ AppendScalarField(builder, 1, "name", model.Name);+ AppendScalarField(builder, 1, "units", model.Units);+ }++ private static void AppendSchemaSection(StringBuilder builder, FirmamentParsedSchema schema)+ {+ builder.Append("schema:\n");++ if (schema.ProcessRaw is not null)+ {+ AppendScalarField(builder, 1, "process", schema.ProcessRaw);+ }++ if (schema.MinimumToolRadiusRaw is not null)+ {+ AppendScalarField(builder, 1, "minimum_tool_radius", schema.MinimumToolRadiusRaw);+ }++ if (schema.PartingPlane is not null)+ {+ AppendScalarField(builder, 1, "parting_plane", schema.PartingPlane);+ }++ if (schema.HasGateLocation)+ {+ builder.Append(Indent(1)).Append("gate_location:\n");+ AppendScalarField(builder, 2, "x", schema.GateLocation?.XRaw ?? string.Empty);+ AppendScalarField(builder, 2, "y", schema.GateLocation?.YRaw ?? string.Empty);+ AppendScalarField(builder, 2, "z", schema.GateLocation?.ZRaw ?? string.Empty);+ }++ if (schema.DraftAngleRaw is not null)+ {+ AppendScalarField(builder, 1, "draft_angle", schema.DraftAngleRaw);+ }++ if (schema.PrinterResolutionRaw is not null)+ {+ AppendScalarField(builder, 1, "printer_resolution", schema.PrinterResolutionRaw);+ }+ }++ private static void AppendOpsSection(StringBuilder builder, FirmamentParsedOpsSection ops)+ {+ builder.Append("ops[").Append(ops.Entries.Count.ToString(CultureInfo.InvariantCulture)).Append("]:\n");++ for (var index = 0; index < ops.Entries.Count; index++)+ {+ if (index > 0)+ {+ builder.AppendLine();+ }++ builder.Append(Indent(1)).Append("-\n");+ AppendOpEntry(builder, ops.Entries[index], 2);+ }+ }++ private static void AppendOpEntry(StringBuilder builder, FirmamentParsedOpEntry entry, int indentLevel)+ {+ var emitted = new HashSet<string>(StringComparer.Ordinal);++ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "op");+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "id");++ switch (entry.KnownKind)+ {+ case FirmamentKnownOpKind.Box:+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "size");+ break;+ case FirmamentKnownOpKind.Cylinder:+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "radius");+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "height");+ break;+ case FirmamentKnownOpKind.Sphere:+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "radius");+ break;+ case FirmamentKnownOpKind.Add:+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "to");+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "with");+ break;+ case FirmamentKnownOpKind.Subtract:+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "from");+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "with");+ break;+ case FirmamentKnownOpKind.Intersect:+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "left");+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "with");+ break;+ case FirmamentKnownOpKind.ExpectExists:+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "target");+ break;+ case FirmamentKnownOpKind.ExpectSelectable:+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "target");+ EmitIfPresent(builder, entry.RawFields, emitted, indentLevel, "count");+ break;+ case FirmamentKnownOpKind.ExpectManifold:+ break;+ }++ foreach (var pair in entry.RawFields)+ {+ if (emitted.Contains(pair.Key) || string.Equals(pair.Key, "place", StringComparison.Ordinal))+ {+ continue;+ }++ AppendField(builder, indentLevel, pair.Key, pair.Value);+ emitted.Add(pair.Key);+ }++ if (entry.Placement is not null)+ {+ AppendPlacement(builder, indentLevel, entry.Placement);+ emitted.Add("place");+ }+ }++ private static void EmitIfPresent(StringBuilder builder, IReadOnlyDictionary<string, string> fields, ISet<string> emitted, int indentLevel, string fieldName)+ {+ if (!fields.TryGetValue(fieldName, out var value))+ {+ return;+ }++ AppendField(builder, indentLevel, fieldName, value);+ emitted.Add(fieldName);+ }++ private static void AppendPlacement(StringBuilder builder, int indentLevel, FirmamentParsedPlacement placement)+ {+ builder.Append(Indent(indentLevel)).Append("place:\n");+ var onValue = placement.On switch+ {+ FirmamentParsedPlacementOriginAnchor => "origin",+ FirmamentParsedPlacementSelectorAnchor selector => selector.Selector,+ _ => throw new InvalidOperationException("Unknown placement anchor.")+ };++ AppendScalarField(builder, indentLevel + 1, "on", onValue);+ builder.Append(Indent(indentLevel + 1))+ .Append("offset[")+ .Append(placement.Offset.Count.ToString(CultureInfo.InvariantCulture))+ .Append("]:\n");+ foreach (var component in placement.Offset)+ {+ builder.Append(Indent(indentLevel + 2)).Append(FormatNumber(component)).Append('\n');+ }+ }++ private static void AppendField(StringBuilder builder, int indentLevel, string fieldName, string rawValue)+ {+ var node = FirmamentFormatValueParser.Parse(rawValue);+ switch (node)+ {+ case FirmamentScalarValue scalar:+ AppendScalarField(builder, indentLevel, fieldName, scalar.Value);+ break;+ case FirmamentArrayValue array:+ builder.Append(Indent(indentLevel))+ .Append(fieldName)+ .Append('[')+ .Append(array.Items.Count.ToString(CultureInfo.InvariantCulture))+ .Append("]:\n");+ foreach (var item in array.Items)+ {+ AppendArrayItem(builder, indentLevel + 1, item);+ }++ break;+ case FirmamentObjectValue obj:+ builder.Append(Indent(indentLevel)).Append(fieldName).Append(":\n");+ foreach (var member in obj.Members)+ {+ AppendField(builder, indentLevel + 1, member.Name, member.Value.RawText);+ }++ break;+ default:+ throw new InvalidOperationException("Unknown formatter value node.");+ }+ }++ private static void AppendArrayItem(StringBuilder builder, int indentLevel, FirmamentFormatValue item)+ {+ switch (item)+ {+ case FirmamentScalarValue scalar:+ builder.Append(Indent(indentLevel)).Append(scalar.Value).Append('\n');+ break;+ case FirmamentObjectValue obj:+ builder.Append(Indent(indentLevel)).Append("-\n");+ foreach (var member in obj.Members)+ {+ AppendField(builder, indentLevel + 1, member.Name, member.Value.RawText);+ }++ break;+ default:+ throw new InvalidOperationException("Canonical formatter arrays only support scalar and object entries.");+ }+ }++ private static void AppendScalarField(StringBuilder builder, int indentLevel, string fieldName, string value)+ {+ builder.Append(Indent(indentLevel)).Append(fieldName).Append(": ").Append(value).Append('\n');+ }++ private static string Indent(int level) => string.Concat(Enumerable.Repeat(IndentUnit, level));++ private static string FormatNumber(double value) => value.ToString("G", CultureInfo.InvariantCulture);+}diff --git a/Aetheris.Kernel.Firmament/Formatting/FirmamentFormatValueParser.cs b/Aetheris.Kernel.Firmament/Formatting/FirmamentFormatValueParser.csnew file mode 100644index 00000000..4e904804--- /dev/null+++ b/Aetheris.Kernel.Firmament/Formatting/FirmamentFormatValueParser.cs@@ -0,0 +1,222 @@+using System.Text;++namespace Aetheris.Kernel.Firmament.Formatting;++internal static class FirmamentFormatValueParser+{+ public static FirmamentFormatValue Parse(string raw)+ {+ ArgumentNullException.ThrowIfNull(raw);++ var parser = new Parser(raw);+ var value = parser.ParseValue();+ parser.SkipWhitespace();+ if (!parser.IsAtEnd)+ {+ throw new FormatException($"Unexpected trailing content in formatter value '{raw}'.");+ }++ return value;+ }++ private sealed class Parser(string text)+ {+ private int _index;++ public bool IsAtEnd => _index >= text.Length;++ public FirmamentFormatValue ParseValue()+ {+ SkipWhitespace();+ if (IsAtEnd)+ {+ return new FirmamentScalarValue(string.Empty);+ }++ return text[_index] switch+ {+ '{' => ParseObject(),+ '[' => ParseArray(),+ _ => ParseScalarUntilDelimiter()+ };+ }++ public void SkipWhitespace()+ {+ while (!IsAtEnd && char.IsWhiteSpace(text[_index]))+ {+ _index++;+ }+ }++ private FirmamentObjectValue ParseObject()+ {+ Expect('{');+ SkipWhitespace();+ var members = new List<FirmamentObjectMember>();+ while (!IsAtEnd && text[_index] != '}')+ {+ var name = NormalizeFieldName(ParseName());+ SkipWhitespace();+ Expect(':');+ var value = ParseValueUntilMemberBoundary();+ members.Add(new FirmamentObjectMember(name, value));+ SkipWhitespace();+ if (!IsAtEnd && text[_index] == ',')+ {+ _index++;+ SkipWhitespace();+ }+ }++ Expect('}');+ return new FirmamentObjectValue(members);+ }++ private FirmamentArrayValue ParseArray()+ {+ Expect('[');+ SkipWhitespace();+ var items = new List<FirmamentFormatValue>();+ while (!IsAtEnd && text[_index] != ']')+ {+ var item = ParseValueUntilArrayBoundary();+ items.Add(item);+ SkipWhitespace();+ if (!IsAtEnd && text[_index] == ',')+ {+ _index++;+ SkipWhitespace();+ }+ }++ Expect(']');+ return new FirmamentArrayValue(items);+ }++ private FirmamentFormatValue ParseValueUntilMemberBoundary()+ {+ SkipWhitespace();+ if (IsAtEnd)+ {+ return new FirmamentScalarValue(string.Empty);+ }++ return text[_index] switch+ {+ '{' => ParseObject(),+ '[' => ParseArray(),+ _ => new FirmamentScalarValue(ParseTokenUntilBoundary(',', '}'))+ };+ }++ private FirmamentFormatValue ParseValueUntilArrayBoundary()+ {+ SkipWhitespace();+ if (IsAtEnd)+ {+ return new FirmamentScalarValue(string.Empty);+ }++ return text[_index] switch+ {+ '{' => ParseObject(),+ '[' => ParseArray(),+ _ => new FirmamentScalarValue(ParseTokenUntilBoundary(',', ']'))+ };+ }++ private FirmamentScalarValue ParseScalarUntilDelimiter()+ => new(ParseTokenUntilBoundary('\0'));+++ private static string NormalizeFieldName(string fieldName)+ {+ var bracketIndex = fieldName.IndexOf('[', StringComparison.Ordinal);+ return bracketIndex > 0 && fieldName.EndsWith("]", StringComparison.Ordinal)+ ? fieldName[..bracketIndex]+ : fieldName;+ }++ private string ParseName()+ {+ SkipWhitespace();+ var start = _index;+ while (!IsAtEnd && text[_index] != ':' && !char.IsWhiteSpace(text[_index]))+ {+ _index++;+ }++ return text[start.._index].Trim();+ }++ private string ParseTokenUntilBoundary(params char[] boundaries)+ {+ var builder = new StringBuilder();+ var squareDepth = 0;+ var curlyDepth = 0;++ while (!IsAtEnd)+ {+ var current = text[_index];+ if (current == '[')+ {+ squareDepth++;+ }+ else if (current == ']')+ {+ if (squareDepth == 0 && boundaries.Contains(']'))+ {+ break;+ }++ squareDepth = Math.Max(0, squareDepth - 1);+ }+ else if (current == '{')+ {+ curlyDepth++;+ }+ else if (current == '}')+ {+ if (curlyDepth == 0 && boundaries.Contains('}'))+ {+ break;+ }++ curlyDepth = Math.Max(0, curlyDepth - 1);+ }+ else if (squareDepth == 0 && curlyDepth == 0 && boundaries.Contains(current))+ {+ break;+ }++ builder.Append(current);+ _index++;+ }++ return builder.ToString().Trim();+ }++ private void Expect(char ch)+ {+ if (IsAtEnd || text[_index] != ch)+ {+ throw new FormatException($"Expected '{ch}' while parsing formatter value '{text}'.");+ }++ _index++;+ }+ }+}++internal abstract record FirmamentFormatValue(string RawText);++internal sealed record FirmamentScalarValue(string Value) : FirmamentFormatValue(Value);++internal sealed record FirmamentArrayValue(IReadOnlyList<FirmamentFormatValue> Items)+ : FirmamentFormatValue("[" + string.Join(", ", Items.Select(item => item.RawText)) + "]");++internal sealed record FirmamentObjectValue(IReadOnlyList<FirmamentObjectMember> Members)+ : FirmamentFormatValue("{ " + string.Join(", ", Members.Select(member => $"{member.Name}: {member.Value.RawText}")) + " }");++internal sealed record FirmamentObjectMember(string Name, FirmamentFormatValue Value);