Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Implement Firmament M8a schema parse and validation
Yuechen Li5649e3106218
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentScaffoldTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentScaffoldTests.csindex 03135bce..5be22aae 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentScaffoldTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentScaffoldTests.cs@@ -761,7 +761,7 @@ public sealed class FirmamentScaffoldTestsAssert.StartsWith("FIRM-REF", FirmamentDiagnosticCodes.ReferenceDuplicateFeatureId.Value);Assert.StartsWith("FIRM-REF", FirmamentDiagnosticCodes.ReferenceUnknownFeatureId.Value);Assert.StartsWith("FIRM-SEL", FirmamentDiagnosticCodes.SelectorPlaceholder.Value);- Assert.StartsWith("FIRM-SCHEMA", FirmamentDiagnosticCodes.SchemaPlaceholder.Value);+ Assert.StartsWith("FIRM-SCHEMA", FirmamentDiagnosticCodes.SchemaUnknownProcess.Value);Assert.StartsWith("FIRM-LOWER", FirmamentDiagnosticCodes.LoweringPlaceholder.Value);}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentSchemaValidationTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentSchemaValidationTests.csnew file mode 100644index 00000000..36478b26--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentSchemaValidationTests.cs@@ -0,0 +1,296 @@+using Aetheris.Kernel.Firmament.Diagnostics;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentSchemaValidationTests+{+ [Fact]+ public void Compile_WithoutSchema_StillSucceeds()+ {+ var result = Compile(BasicOpsSource);++ Assert.True(result.Compilation.IsSuccess);+ Assert.Null(result.Compilation.Value.ParsedDocument!.Schema);+ }++ [Fact]+ public void Compile_WithValidCncSchema_Succeeds_AndPreservesSchemaMetadata()+ {+ var result = Compile($"""+{Header}++schema:+ process: cnc+ minimum_tool_radius: 1.5++{OpsSingleBox}+""");++ Assert.True(result.Compilation.IsSuccess);+ var schema = result.Compilation.Value.ParsedDocument!.Schema;+ Assert.NotNull(schema);+ Assert.Equal("cnc", schema!.ProcessRaw);+ Assert.Equal(1.5d, schema.MinimumToolRadius);+ }++ [Fact]+ public void Compile_WithValidInjectionMoldedSchema_Succeeds()+ {+ var result = Compile($"""+{Header}++schema:+ process: injection_molded+ parting_plane: xy+ gate_location:+ x: 0+ y: 0+ z: 0+ draft_angle: 2++{OpsSingleBox}+""");++ Assert.True(result.Compilation.IsSuccess);+ Assert.Equal("xy", result.Compilation.Value.ParsedDocument!.Schema!.PartingPlane);+ }++ [Fact]+ public void Compile_WithValidAdditiveSchema_Succeeds()+ {+ var result = Compile($"""+{Header}++schema:+ process: additive+ printer_resolution: 0.1++{OpsSingleBox}+""");++ Assert.True(result.Compilation.IsSuccess);+ Assert.Equal(0.1d, result.Compilation.Value.ParsedDocument!.Schema!.PrinterResolution);+ }++ [Fact]+ public void Compile_Rejects_UnknownSchemaProcess()+ => AssertSchemaError("""+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: laser++ops[0]:+""", FirmamentDiagnosticCodes.SchemaUnknownProcess);++ [Fact]+ public void Compile_Rejects_MissingRequiredCncField()+ => AssertSchemaError("""+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: cnc++ops[0]:+""", FirmamentDiagnosticCodes.SchemaMissingRequiredField);++ [Fact]+ public void Compile_Rejects_MissingRequiredInjectionField()+ => AssertSchemaError("""+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: injection_molded+ parting_plane: xy+ draft_angle: 2++ops[0]:+""", FirmamentDiagnosticCodes.SchemaMissingRequiredField);++ [Fact]+ public void Compile_Rejects_MissingRequiredAdditiveField()+ => AssertSchemaError("""+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: additive++ops[0]:+""", FirmamentDiagnosticCodes.SchemaMissingRequiredField);++ [Fact]+ public void Compile_Rejects_InvalidPartingPlane()+ => AssertSchemaError("""+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: injection_molded+ parting_plane: zx+ gate_location:+ x: 0+ y: 0+ z: 0+ draft_angle: 2++ops[0]:+""", FirmamentDiagnosticCodes.SchemaInvalidFieldValue);++ [Fact]+ public void Compile_Rejects_InvalidGateLocationCoordinateType()+ => AssertSchemaError("""+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: injection_molded+ parting_plane: xy+ gate_location:+ x: left+ y: 0+ z: 0+ draft_angle: 2++ops[0]:+""", FirmamentDiagnosticCodes.SchemaInvalidFieldTypeOrShape);++ [Fact]+ public void Compile_Rejects_NonPositiveSchemaNumericValues()+ => AssertSchemaError("""+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: additive+ printer_resolution: 0++ops[0]:+""", FirmamentDiagnosticCodes.SchemaInvalidFieldValue);++ [Fact]+ public void Compile_WithSchema_DoesNotChangeGeometryOrValidationExecution()+ {+ const string baseline = """+firmament:+ version: 1++model:+ name: demo+ units: mm++ops[2]:+ -+ op: box+ id: base+ size[3]:+ 4+ 2+ 1+ -+ op: expect_exists+ target: base+""";++ const string withSchema = """+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: cnc+ minimum_tool_radius: 1++ops[2]:+ -+ op: box+ id: base+ size[3]:+ 4+ 2+ 1+ -+ op: expect_exists+ target: base+""";++ var first = Compile(baseline);+ var second = Compile(withSchema);++ Assert.True(first.Compilation.IsSuccess);+ Assert.True(second.Compilation.IsSuccess);+ Assert.Equal(first.Compilation.Value.PrimitiveLoweringPlan!.Primitives.Count, second.Compilation.Value.PrimitiveLoweringPlan!.Primitives.Count);+ Assert.Equal(first.Compilation.Value.PrimitiveExecutionResult!.ExecutedPrimitives.Count, second.Compilation.Value.PrimitiveExecutionResult!.ExecutedPrimitives.Count);+ Assert.Equal(first.Compilation.Value.ValidationExecutionResult!.Validations.Count, second.Compilation.Value.ValidationExecutionResult!.Validations.Count);+ }++ private static void AssertSchemaError(string source, FirmamentDiagnosticCode expectedCode)+ {+ var result = Compile(source);+ Assert.False(result.Compilation.IsSuccess);+ var diagnostic = Assert.Single(result.Compilation.Diagnostics);+ Assert.Contains(expectedCode.Value, diagnostic.Message, StringComparison.Ordinal);+ }++ private static FirmamentCompileResult Compile(string source)+ {+ var compiler = new FirmamentCompiler();+ return compiler.Compile(new FirmamentCompileRequest(new FirmamentSourceDocument(source)));+ }++ private const string Header = """+firmament:+ version: 1++model:+ name: demo+ units: mm+""";++ private const string OpsSingleBox = """+ops[1]:+ -+ op: box+ id: base+ size[3]:+ 1+ 2+ 3+""";++ private const string BasicOpsSource = Header + "\n" + OpsSingleBox;+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentValidationExecutionTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentValidationExecutionTests.csindex 04299aa5..fa981eae 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentValidationExecutionTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentValidationExecutionTests.cs@@ -150,7 +150,7 @@ public sealed class FirmamentValidationExecutionTestsRawFields: new Dictionary<string, string>(StringComparer.Ordinal) { ["target"] = "base" },ClassifiedFields: new Dictionary<string, string>(StringComparer.Ordinal) { ["targetShape"] = "FeatureId" })]),- HasSchema: false,+ Schema: null,HasPmi: false);var executionResult = new FirmamentPrimitiveExecutionResult(diff --git a/Aetheris.Kernel.Firmament/Diagnostics/FirmamentDiagnosticCodes.cs b/Aetheris.Kernel.Firmament/Diagnostics/FirmamentDiagnosticCodes.csindex 2a5b0641..7f2aa765 100644--- a/Aetheris.Kernel.Firmament/Diagnostics/FirmamentDiagnosticCodes.cs+++ b/Aetheris.Kernel.Firmament/Diagnostics/FirmamentDiagnosticCodes.cs@@ -39,6 +39,11 @@ public static class FirmamentDiagnosticCodespublic static readonly FirmamentDiagnosticCode ValidationTargetSelectableCountMismatch = new($"{FirmamentDiagnosticConventions.ReferencePrefix}-0008");public static readonly FirmamentDiagnosticCode ValidationTargetNonManifoldBody = new($"{FirmamentDiagnosticConventions.ReferencePrefix}-0009");public static readonly FirmamentDiagnosticCode SelectorPlaceholder = new($"{FirmamentDiagnosticConventions.SelectorPrefix}-0001");- public static readonly FirmamentDiagnosticCode SchemaPlaceholder = new($"{FirmamentDiagnosticConventions.SchemaPrefix}-0001");++ public static readonly FirmamentDiagnosticCode SchemaUnknownProcess = new($"{FirmamentDiagnosticConventions.SchemaPrefix}-0001");+ public static readonly FirmamentDiagnosticCode SchemaMissingRequiredField = new($"{FirmamentDiagnosticConventions.SchemaPrefix}-0002");+ public static readonly FirmamentDiagnosticCode SchemaInvalidFieldTypeOrShape = new($"{FirmamentDiagnosticConventions.SchemaPrefix}-0003");+ public static readonly FirmamentDiagnosticCode SchemaInvalidFieldValue = new($"{FirmamentDiagnosticConventions.SchemaPrefix}-0004");+public static readonly FirmamentDiagnosticCode LoweringPlaceholder = new($"{FirmamentDiagnosticConventions.LoweringPrefix}-0001");}diff --git a/Aetheris.Kernel.Firmament/FirmamentCompiler.cs b/Aetheris.Kernel.Firmament/FirmamentCompiler.csindex 53de2dca..bd2214e1 100644--- a/Aetheris.Kernel.Firmament/FirmamentCompiler.cs+++ b/Aetheris.Kernel.Firmament/FirmamentCompiler.cs@@ -19,6 +19,13 @@ public sealed class FirmamentCompilerKernelResult<FirmamentCompilationArtifact>.Failure(parseResult.Diagnostics));}+ var schemaValidationResult = FirmamentSchemaValidator.Validate(parseResult.Value);+ if (!schemaValidationResult.IsSuccess)+ {+ return new FirmamentCompileResult(+ KernelResult<FirmamentCompilationArtifact>.Failure(schemaValidationResult.Diagnostics));+ }+var primitiveValidationResult = FirmamentPrimitiveRequiredFieldValidator.Validate(parseResult.Value);if (!primitiveValidationResult.IsSuccess){diff --git a/Aetheris.Kernel.Firmament/ParsedModel/FirmamentParsedDocument.cs b/Aetheris.Kernel.Firmament/ParsedModel/FirmamentParsedDocument.csindex a7ef8f5d..00518fae 100644--- a/Aetheris.Kernel.Firmament/ParsedModel/FirmamentParsedDocument.cs+++ b/Aetheris.Kernel.Firmament/ParsedModel/FirmamentParsedDocument.cs@@ -4,7 +4,7 @@ public sealed record FirmamentParsedDocument(FirmamentParsedHeader Firmament,FirmamentParsedModelHeader Model,FirmamentParsedOpsSection Ops,- bool HasSchema,+ FirmamentParsedSchema? Schema,bool HasPmi);public sealed record FirmamentParsedHeader(string Version);diff --git a/Aetheris.Kernel.Firmament/ParsedModel/FirmamentParsedSchema.cs b/Aetheris.Kernel.Firmament/ParsedModel/FirmamentParsedSchema.csnew file mode 100644index 00000000..3ee34047--- /dev/null+++ b/Aetheris.Kernel.Firmament/ParsedModel/FirmamentParsedSchema.cs@@ -0,0 +1,26 @@+namespace Aetheris.Kernel.Firmament.ParsedModel;++public sealed record FirmamentParsedSchema(+ bool IsObjectLike,+ string? ProcessRaw,+ FirmamentParsedSchemaProcess Process,+ string? MinimumToolRadiusRaw = null,+ double? MinimumToolRadius = null,+ string? PartingPlane = null,+ bool HasGateLocation = false,+ bool GateLocationIsObjectLike = false,+ FirmamentParsedSchemaGateLocation? GateLocation = null,+ string? DraftAngleRaw = null,+ double? DraftAngle = null,+ string? PrinterResolutionRaw = null,+ double? PrinterResolution = null);++public enum FirmamentParsedSchemaProcess+{+ Cnc,+ InjectionMolded,+ Additive,+ Unknown+}++public sealed record FirmamentParsedSchemaGateLocation(string? XRaw, string? YRaw, string? ZRaw);diff --git a/Aetheris.Kernel.Firmament/Parsing/FirmamentTopLevelParser.cs b/Aetheris.Kernel.Firmament/Parsing/FirmamentTopLevelParser.csindex 2d58d9bb..738284c5 100644--- a/Aetheris.Kernel.Firmament/Parsing/FirmamentTopLevelParser.cs+++ b/Aetheris.Kernel.Firmament/Parsing/FirmamentTopLevelParser.cs@@ -125,12 +125,14 @@ internal static class FirmamentTopLevelParserreturn KernelResult<FirmamentParsedDocument>.Failure(parsedOpsResult.Diagnostics);}+ var parsedSchema = ParseSchemaFromJsonRoot(root);+return KernelResult<FirmamentParsedDocument>.Success(new FirmamentParsedDocument(new FirmamentParsedHeader(versionElement.ToString()),new FirmamentParsedModelHeader(nameElement.ToString(), unitsElement.ToString()),new FirmamentParsedOpsSection(parsedOpsResult.Value),- HasSchema: root.TryGetProperty("schema", out _),+ Schema: parsedSchema,HasPmi: root.TryGetProperty("pmi", out _)));}@@ -203,12 +205,14 @@ internal static class FirmamentTopLevelParserreturn KernelResult<FirmamentParsedDocument>.Failure(parsedOpsResult.Diagnostics);}+ var parsedSchema = ParseSchemaFromToonSections(toon.Sections);+return KernelResult<FirmamentParsedDocument>.Success(new FirmamentParsedDocument(new FirmamentParsedHeader(version),new FirmamentParsedModelHeader(name, units),new FirmamentParsedOpsSection(parsedOpsResult.Value),- HasSchema: toon.Sections.ContainsKey("schema"),+ Schema: parsedSchema,HasPmi: toon.Sections.ContainsKey("pmi")));}@@ -298,6 +302,7 @@ internal static class FirmamentTopLevelParserstring? currentNestedFieldName = null;int currentNestedFieldIndent = -1;var currentNestedLines = new List<string>();+ Action<string, string>? currentNestedFieldWriter = null;static string CollapseNestedFieldValue(IReadOnlyList<string> nestedLines){@@ -358,18 +363,20 @@ internal static class FirmamentTopLevelParservoid FlushNestedFieldIfNeeded(){- if (currentArrayObjectEntry is null || string.IsNullOrWhiteSpace(currentNestedFieldName))+ if (currentNestedFieldWriter is null || string.IsNullOrWhiteSpace(currentNestedFieldName)){currentNestedFieldName = null;currentNestedFieldIndent = -1;currentNestedLines.Clear();+ currentNestedFieldWriter = null;return;}- currentArrayObjectEntry.Fields[currentNestedFieldName] = CollapseNestedFieldValue(currentNestedLines);+ currentNestedFieldWriter(currentNestedFieldName, CollapseNestedFieldValue(currentNestedLines));currentNestedFieldName = null;currentNestedFieldIndent = -1;currentNestedLines.Clear();+ currentNestedFieldWriter = null;}var lines = sourceText.Replace("\r\n", "\n", StringComparison.Ordinal).Replace("\r", "\n", StringComparison.Ordinal).Split('\n');@@ -389,18 +396,19 @@ internal static class FirmamentTopLevelParser{var field = line.Trim();- if (currentArraySection is not null)+ if (!string.IsNullOrWhiteSpace(currentNestedFieldName) && indentation <= currentNestedFieldIndent){- if (!string.IsNullOrWhiteSpace(currentNestedFieldName) && indentation <= currentNestedFieldIndent)- {- FlushNestedFieldIfNeeded();- }+ FlushNestedFieldIfNeeded();+ }- if (!string.IsNullOrWhiteSpace(currentNestedFieldName) && indentation > currentNestedFieldIndent)- {- currentNestedLines.Add(field);- continue;- }+ if (!string.IsNullOrWhiteSpace(currentNestedFieldName) && indentation > currentNestedFieldIndent)+ {+ currentNestedLines.Add(field);+ continue;+ }++ if (currentArraySection is not null)+ {if (field == "-"){@@ -446,6 +454,7 @@ internal static class FirmamentTopLevelParsercurrentNestedFieldName = normalizedArrayFieldName;currentNestedFieldIndent = indentation;currentNestedLines.Clear();+ currentNestedFieldWriter = (key, value) => currentArrayObjectEntry.Fields[key] = value;continue;}@@ -466,11 +475,21 @@ internal static class FirmamentTopLevelParservar fieldName = field[..separator].Trim();var fieldValue = field[(separator + 1)..].Trim();- if (fieldName.Length == 0 || fieldValue.Length == 0)+ if (fieldName.Length == 0){return InvalidToonSyntax();}+ if (fieldValue.Length == 0)+ {+ var objectSectionName = currentObjectSection;+ currentNestedFieldName = fieldName;+ currentNestedFieldIndent = indentation;+ currentNestedLines.Clear();+ currentNestedFieldWriter = (key, value) => sections[objectSectionName].Fields[key] = value;+ continue;+ }+sections[currentObjectSection].Fields[fieldName] = fieldValue;continue;}@@ -530,6 +549,177 @@ internal static class FirmamentTopLevelParser&& int.TryParse(countText, out _);}+ private static FirmamentParsedSchema? ParseSchemaFromJsonRoot(JsonElement root)+ {+ if (!root.TryGetProperty("schema", out var schemaElement))+ {+ return null;+ }++ if (schemaElement.ValueKind != JsonValueKind.Object)+ {+ return new FirmamentParsedSchema(false, null, FirmamentParsedSchemaProcess.Unknown);+ }++ schemaElement.TryGetProperty("process", out var processElement);+ var processRaw = processElement.ToString();+ var process = ParseSchemaProcess(processRaw);++ schemaElement.TryGetProperty("minimum_tool_radius", out var minimumToolRadiusElement);+ var minimumToolRadiusRaw = minimumToolRadiusElement.ToString();+ double? minimumToolRadius = null;+ if (minimumToolRadiusElement.ValueKind == JsonValueKind.Number)+ {+ minimumToolRadius = minimumToolRadiusElement.GetDouble();+ }++ string? partingPlane = null;+ if (schemaElement.TryGetProperty("parting_plane", out var partingPlaneElement))+ {+ partingPlane = partingPlaneElement.ToString();+ }++ var hasGateLocation = schemaElement.TryGetProperty("gate_location", out var gateLocationElement);+ var gateLocationIsObjectLike = hasGateLocation && gateLocationElement.ValueKind == JsonValueKind.Object;+ FirmamentParsedSchemaGateLocation? gateLocation = null;+ if (gateLocationIsObjectLike)+ {+ gateLocationElement.TryGetProperty("x", out var xElement);+ gateLocationElement.TryGetProperty("y", out var yElement);+ gateLocationElement.TryGetProperty("z", out var zElement);+ gateLocation = new FirmamentParsedSchemaGateLocation(xElement.ToString(), yElement.ToString(), zElement.ToString());+ }++ schemaElement.TryGetProperty("draft_angle", out var draftAngleElement);+ var draftAngleRaw = draftAngleElement.ToString();+ double? draftAngle = null;+ if (draftAngleElement.ValueKind == JsonValueKind.Number)+ {+ draftAngle = draftAngleElement.GetDouble();+ }++ schemaElement.TryGetProperty("printer_resolution", out var printerResolutionElement);+ var printerResolutionRaw = printerResolutionElement.ToString();+ double? printerResolution = null;+ if (printerResolutionElement.ValueKind == JsonValueKind.Number)+ {+ printerResolution = printerResolutionElement.GetDouble();+ }++ return new FirmamentParsedSchema(true, processRaw, process, minimumToolRadiusRaw, minimumToolRadius, partingPlane, hasGateLocation, gateLocationIsObjectLike, gateLocation, draftAngleRaw, draftAngle, printerResolutionRaw, printerResolution);+ }++ private static FirmamentParsedSchema? ParseSchemaFromToonSections(IReadOnlyDictionary<string, FirmamentToonSection> sections)+ {+ if (!sections.TryGetValue("schema", out var schemaSection))+ {+ return null;+ }++ if (!schemaSection.IsObjectLike)+ {+ return new FirmamentParsedSchema(false, null, FirmamentParsedSchemaProcess.Unknown);+ }++ schemaSection.Fields.TryGetValue("process", out var processRaw);+ var process = ParseSchemaProcess(processRaw);++ schemaSection.Fields.TryGetValue("minimum_tool_radius", out var minimumToolRadiusRaw);+ double? minimumToolRadius = null;+ if (!string.IsNullOrWhiteSpace(minimumToolRadiusRaw)+ && TryParseNumeric(minimumToolRadiusRaw, out var minimumToolRadiusValue))+ {+ minimumToolRadius = minimumToolRadiusValue;+ }++ schemaSection.Fields.TryGetValue("parting_plane", out var partingPlane);++ var hasGateLocation = schemaSection.Fields.TryGetValue("gate_location", out var gateLocationRaw);+ var gateLocationIsObjectLike = false;+ var gateLocationFields = new Dictionary<string, string>(StringComparer.Ordinal);+ if (hasGateLocation && TryParseStructuredFields(gateLocationRaw!, out var parsedGateLocationFields))+ {+ gateLocationIsObjectLike = true;+ gateLocationFields = new Dictionary<string, string>(parsedGateLocationFields, StringComparer.Ordinal);+ }++ FirmamentParsedSchemaGateLocation? gateLocation = null;+ if (gateLocationIsObjectLike)+ {+ gateLocationFields.TryGetValue("x", out var xRaw);+ gateLocationFields.TryGetValue("y", out var yRaw);+ gateLocationFields.TryGetValue("z", out var zRaw);+ gateLocation = new FirmamentParsedSchemaGateLocation(xRaw, yRaw, zRaw);+ }++ schemaSection.Fields.TryGetValue("draft_angle", out var draftAngleRaw);+ double? draftAngle = null;+ if (!string.IsNullOrWhiteSpace(draftAngleRaw)+ && TryParseNumeric(draftAngleRaw, out var draftAngleValue))+ {+ draftAngle = draftAngleValue;+ }++ schemaSection.Fields.TryGetValue("printer_resolution", out var printerResolutionRaw);+ double? printerResolution = null;+ if (!string.IsNullOrWhiteSpace(printerResolutionRaw)+ && TryParseNumeric(printerResolutionRaw, out var printerResolutionValue))+ {+ printerResolution = printerResolutionValue;+ }++ return new FirmamentParsedSchema(true, processRaw, process, minimumToolRadiusRaw, minimumToolRadius, partingPlane, hasGateLocation, gateLocationIsObjectLike, gateLocation, draftAngleRaw, draftAngle, printerResolutionRaw, printerResolution);+ }++ private static FirmamentParsedSchemaProcess ParseSchemaProcess(string? raw)+ {+ return raw?.Trim() switch+ {+ "cnc" => FirmamentParsedSchemaProcess.Cnc,+ "injection_molded" => FirmamentParsedSchemaProcess.InjectionMolded,+ "additive" => FirmamentParsedSchemaProcess.Additive,+ _ => FirmamentParsedSchemaProcess.Unknown+ };+ }++ private static bool TryParseStructuredFields(string raw, out IReadOnlyDictionary<string, string> fields)+ {+ fields = new Dictionary<string, string>(StringComparer.Ordinal);+ var trimmed = raw.Trim();+ if (!trimmed.StartsWith("{", StringComparison.Ordinal) || !trimmed.EndsWith("}", StringComparison.Ordinal))+ {+ return false;+ }++ var body = trimmed[1..^1].Trim();+ var parsedFields = new Dictionary<string, string>(StringComparer.Ordinal);+ foreach (var pair in SplitTopLevelCommaSeparated(body))+ {+ var separator = pair.IndexOf(':');+ if (separator <= 0)+ {+ continue;+ }++ var name = pair[..separator].Trim();+ var value = pair[(separator + 1)..].Trim();+ if (name.Length == 0 || value.Length == 0)+ {+ continue;+ }++ parsedFields[name] = value;+ }++ fields = parsedFields;+ return true;+ }++ private static bool TryParseNumeric(string raw, out double value)+ {+ return double.TryParse(raw.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out value);+ }+private static FirmamentParsedPlacement? ParsePlacementFromJson(JsonElement opElement){if (!opElement.TryGetProperty("place", out var placeElement))diff --git a/Aetheris.Kernel.Firmament/Validation/FirmamentSchemaValidator.cs b/Aetheris.Kernel.Firmament/Validation/FirmamentSchemaValidator.csnew file mode 100644index 00000000..3d8ef7b5--- /dev/null+++ b/Aetheris.Kernel.Firmament/Validation/FirmamentSchemaValidator.cs@@ -0,0 +1,177 @@+using System.Globalization;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Firmament.Diagnostics;+using Aetheris.Kernel.Firmament.ParsedModel;++namespace Aetheris.Kernel.Firmament.Validation;++internal static class FirmamentSchemaValidator+{+ public static KernelResult<bool> Validate(FirmamentParsedDocument parsedDocument)+ {+ ArgumentNullException.ThrowIfNull(parsedDocument);++ var schema = parsedDocument.Schema;+ if (schema is null)+ {+ return KernelResult<bool>.Success(true);+ }++ if (!schema.IsObjectLike)+ {+ return InvalidFieldTypeOrShape("schema", "expected an object-like mapping block");+ }++ if (string.IsNullOrWhiteSpace(schema.ProcessRaw))+ {+ return MissingField("process");+ }++ if (schema.Process == FirmamentParsedSchemaProcess.Unknown)+ {+ return UnknownProcess(schema.ProcessRaw!);+ }++ return schema.Process switch+ {+ FirmamentParsedSchemaProcess.Cnc => ValidateCnc(schema),+ FirmamentParsedSchemaProcess.InjectionMolded => ValidateInjectionMolded(schema),+ FirmamentParsedSchemaProcess.Additive => ValidateAdditive(schema),+ _ => UnknownProcess(schema.ProcessRaw!)+ };+ }++ private static KernelResult<bool> ValidateCnc(FirmamentParsedSchema schema)+ {+ if (string.IsNullOrWhiteSpace(schema.MinimumToolRadiusRaw))+ {+ return MissingField("minimum_tool_radius");+ }++ if (schema.MinimumToolRadius is null)+ {+ return InvalidFieldTypeOrShape("minimum_tool_radius", "expected a numeric scalar");+ }++ if (schema.MinimumToolRadius <= 0)+ {+ return InvalidFieldValue("minimum_tool_radius", "expected a numeric value greater than 0");+ }++ return KernelResult<bool>.Success(true);+ }++ private static KernelResult<bool> ValidateInjectionMolded(FirmamentParsedSchema schema)+ {+ if (string.IsNullOrWhiteSpace(schema.PartingPlane))+ {+ return MissingField("parting_plane");+ }++ if (schema.PartingPlane is not ("xy" or "yz" or "xz"))+ {+ return InvalidFieldValue("parting_plane", "expected one of 'xy', 'yz', or 'xz'");+ }++ if (!schema.HasGateLocation)+ {+ return MissingField("gate_location");+ }++ if (!schema.GateLocationIsObjectLike || schema.GateLocation is null)+ {+ return InvalidFieldTypeOrShape("gate_location", "expected an object-like mapping with numeric fields 'x', 'y', and 'z'");+ }++ if (!TryParseRequiredNumeric(schema.GateLocation.XRaw, out _))+ {+ return InvalidFieldTypeOrShape("gate_location.x", "expected a numeric scalar");+ }++ if (!TryParseRequiredNumeric(schema.GateLocation.YRaw, out _))+ {+ return InvalidFieldTypeOrShape("gate_location.y", "expected a numeric scalar");+ }++ if (!TryParseRequiredNumeric(schema.GateLocation.ZRaw, out _))+ {+ return InvalidFieldTypeOrShape("gate_location.z", "expected a numeric scalar");+ }++ if (string.IsNullOrWhiteSpace(schema.DraftAngleRaw))+ {+ return MissingField("draft_angle");+ }++ if (schema.DraftAngle is null)+ {+ return InvalidFieldTypeOrShape("draft_angle", "expected a numeric scalar");+ }++ if (schema.DraftAngle <= 0)+ {+ return InvalidFieldValue("draft_angle", "expected a numeric value greater than 0");+ }++ return KernelResult<bool>.Success(true);+ }++ private static KernelResult<bool> ValidateAdditive(FirmamentParsedSchema schema)+ {+ if (string.IsNullOrWhiteSpace(schema.PrinterResolutionRaw))+ {+ return MissingField("printer_resolution");+ }++ if (schema.PrinterResolution is null)+ {+ return InvalidFieldTypeOrShape("printer_resolution", "expected a numeric scalar");+ }++ if (schema.PrinterResolution <= 0)+ {+ return InvalidFieldValue("printer_resolution", "expected a numeric value greater than 0");+ }++ return KernelResult<bool>.Success(true);+ }++ private static bool TryParseRequiredNumeric(string? raw, out double value)+ {+ value = default;+ return !string.IsNullOrWhiteSpace(raw)+ && double.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out value);+ }++ private static KernelResult<bool> UnknownProcess(string process) =>+ KernelResult<bool>.Failure([+ CreateDiagnostic(+ FirmamentDiagnosticCodes.SchemaUnknownProcess,+ $"Schema has unknown process '{process}'.")]);++ private static KernelResult<bool> MissingField(string fieldName) =>+ KernelResult<bool>.Failure([+ CreateDiagnostic(+ FirmamentDiagnosticCodes.SchemaMissingRequiredField,+ $"Schema is missing required field '{fieldName}'.")]);++ private static KernelResult<bool> InvalidFieldTypeOrShape(string fieldName, string expectation) =>+ KernelResult<bool>.Failure([+ CreateDiagnostic(+ FirmamentDiagnosticCodes.SchemaInvalidFieldTypeOrShape,+ $"Schema field '{fieldName}' has invalid type/shape; {expectation}.")]);++ private static KernelResult<bool> InvalidFieldValue(string fieldName, string expectation) =>+ KernelResult<bool>.Failure([+ CreateDiagnostic(+ FirmamentDiagnosticCodes.SchemaInvalidFieldValue,+ $"Schema field '{fieldName}' has invalid value; {expectation}.")]);++ private static KernelDiagnostic CreateDiagnostic(FirmamentDiagnosticCode code, string message) =>+ new(+ KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error,+ $"[{code.Value}] {message}",+ Source: FirmamentDiagnosticConventions.Source);+}diff --git a/testdata/firmament/fixtures/m8a-invalid-schema-gate-location-nonnumeric.firmament b/testdata/firmament/fixtures/m8a-invalid-schema-gate-location-nonnumeric.firmamentnew file mode 100644index 00000000..a382ad97--- /dev/null+++ b/testdata/firmament/fixtures/m8a-invalid-schema-gate-location-nonnumeric.firmament@@ -0,0 +1,17 @@+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: injection_molded+ parting_plane: xy+ gate_location:+ x: left+ y: 0+ z: 0+ draft_angle: 2++ops[0]:diff --git a/testdata/firmament/fixtures/m8a-invalid-schema-unknown-process.firmament b/testdata/firmament/fixtures/m8a-invalid-schema-unknown-process.firmamentnew file mode 100644index 00000000..b16894dd--- /dev/null+++ b/testdata/firmament/fixtures/m8a-invalid-schema-unknown-process.firmament@@ -0,0 +1,11 @@+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: laser++ops[0]:diff --git a/testdata/firmament/fixtures/m8a-valid-schema-additive.firmament b/testdata/firmament/fixtures/m8a-valid-schema-additive.firmamentnew file mode 100644index 00000000..8ae90f36--- /dev/null+++ b/testdata/firmament/fixtures/m8a-valid-schema-additive.firmament@@ -0,0 +1,12 @@+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: additive+ printer_resolution: 0.1++ops[0]:diff --git a/testdata/firmament/fixtures/m8a-valid-schema-cnc.firmament b/testdata/firmament/fixtures/m8a-valid-schema-cnc.firmamentnew file mode 100644index 00000000..d96d9930--- /dev/null+++ b/testdata/firmament/fixtures/m8a-valid-schema-cnc.firmament@@ -0,0 +1,12 @@+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: cnc+ minimum_tool_radius: 1.5++ops[0]:diff --git a/testdata/firmament/fixtures/m8a-valid-schema-injection-molded.firmament b/testdata/firmament/fixtures/m8a-valid-schema-injection-molded.firmamentnew file mode 100644index 00000000..d8998537--- /dev/null+++ b/testdata/firmament/fixtures/m8a-valid-schema-injection-molded.firmament@@ -0,0 +1,17 @@+firmament:+ version: 1++model:+ name: demo+ units: mm++schema:+ process: injection_molded+ parting_plane: xy+ gate_location:+ x: 0+ y: 0+ z: 0+ draft_angle: 2++ops[0]: