Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

12.5 KB
Raw Blame
using Aetheris.Kernel.Core.Diagnostics;

namespace Aetheris.Kernel.Firmament.FirmamentV2;

/// <summary>Validation uses the existing engineering compiler, including selection
/// binding, capability checks, materialization and export. No output file is written.</summary>
public static class FirmamentBuildAdmissionValidation
{
    public static FirmamentV2ValidationReport Admit(
        FirmamentV2ValidationReport report, string source, string? sourceDirectory = null)
    {
        // A junction fillet is validated the way build answers it: the body built without it, then filleted.
        if (JunctionFilletRoute.Find(source) is { } junction && FirmamentV2Parser.Parse(junction.Stripped, sourceDirectory).IsSuccess)
            return Rounded(report, source, sourceDirectory, JunctionFilletRoute.Code);
        if (report.Status == "invalid" && UniformRoundingRoute.Find(source) is { } rounding
            && FirmamentV2Parser.Parse(rounding.Stripped, sourceDirectory).IsSuccess)
            return Rounded(report, source, sourceDirectory);
        if (report.Status == "invalid") return report;
        var compilation = FirmamentBuildAndExport.CompileSource(source, sourceDirectory);
        var diagnostics = report.Diagnostics.Concat(compilation.Diagnostics.Select(diagnostic =>
            Present(diagnostic, report.Source, source))).Distinct().ToArray();
        var fatal = diagnostics.Count(diagnostic => diagnostic.Severity is "fatal" or "error");
        return report with
        {
            Status = !compilation.IsSuccess || fatal > 0 ? "invalid" : report.Status,
            ValidationLevel = compilation.IsSuccess ? "Built" : "BuildRejected",
            Diagnostics = diagnostics,
            Summary = report.Summary with
            {
                FatalDiagnosticCount = fatal,
                WarningDiagnosticCount = diagnostics.Count(diagnostic => diagnostic.Severity == "warning")
            }
        };
    }

    /// <summary>An AllEdges fillet that is all that stops the source parsing (the stock route refuses it, or the
    /// body's construction takes no Modify) is validated the way build answers it: by building the body and
    /// rounding it.</summary>
    private static FirmamentV2ValidationReport Rounded(FirmamentV2ValidationReport report, string source, string? sourceDirectory, string route = UniformRoundingRoute.Code)
    {
        var built = FirmamentBuildAndExport.CompileSource(source, sourceDirectory);
        // Only the finish failed the parse, so the parse's diagnostics give way to the build's answer.
        var diagnostics = report.Diagnostics.Where(d => d.Severity is not ("fatal" or "error"))
            .Concat(built.Diagnostics.Select(d => Present(d, report.Source, source))).Distinct().ToArray();
        var fatal = diagnostics.Count(d => d.Severity is "fatal" or "error");
        return report with
        {
            Status = built.IsSuccess && fatal == 0 ? "valid" : "invalid",
            ValidationLevel = built.IsSuccess ? "Built" : "BuildRejected",
            ParserRoute = route,
            Diagnostics = diagnostics,
            Summary = report.Summary with { FatalDiagnosticCount = fatal, WarningDiagnosticCount = diagnostics.Count(d => d.Severity == "warning") },
        };
    }

    public static FirmamentV2ValidationDiagnostic Present(KernelDiagnostic diagnostic, string sourceFile, string? source = null)
    {
        if (diagnostic.Message.StartsWith("compose-face-hole:", StringComparison.Ordinal)
            && diagnostic.Message.IndexOf(": ", StringComparison.Ordinal) is var explanation && explanation > 0)
        {
            var located = Present(diagnostic with { Message = diagnostic.Message[..explanation] }, sourceFile, source);
            return located with { Message = diagnostic.Message[(explanation + 2)..] };
        }
        var separator = diagnostic.Message.IndexOf(':');
        var code = separator > 0 && !diagnostic.Message[..separator].Any(char.IsWhiteSpace)
            ? diagnostic.Message[..separator]
            : diagnostic.Message.All(character => char.IsLetterOrDigit(character) || character is '-' or '_' or '.')
                ? diagnostic.Message : diagnostic.Code.ToString();
        if (diagnostic.OriginalSourceSpan is { } authored)
            return Locate(new(code, diagnostic.Severity switch
                { KernelDiagnosticSeverity.Error => "error", KernelDiagnosticSeverity.Warning => "warning", _ => "info" }, diagnostic.Message)
                { SourceSpan = new(authored.Start, authored.Length), LocationNote = authored.LocationNote, Source = diagnostic.Source, Stage = diagnostic.Source }, source, sourceFile);
        if (source is not null)
        {
            var parsed = FirmamentV2Parser.Parse(source);
            var original = parsed.SyntaxDiagnostics.FirstOrDefault(d => d.Code == code || d.Code.StartsWith(code + ":", StringComparison.Ordinal));
            if (original is not null) return Locate(original, source, sourceFile);
            if (diagnostic.SourceSpan is { } produced && parsed.DiagnosticSource is { } input)
            {
                var origins = new Syntax.FirmamentSyntaxOrigins(Syntax.FirmamentSyntaxParser.Parse(FirmamentSourceSpelling.Normalize(source)).Document,
                    Syntax.FirmamentSyntaxParser.Parse(input).Document);
                var anchor = origins.Find(new(produced.Start, produced.Length));
                if (anchor is not null) return Locate(new(code, diagnostic.Severity == KernelDiagnosticSeverity.Error ? "fatal" : "warning", diagnostic.Message)
                    { SourceSpan = anchor, Source = diagnostic.Source, Stage = diagnostic.Source }, source, sourceFile);
            }
            if (ProfileAuthoringParser.LocateDiagnostic(source, diagnostic.Message) is { } profileDiagnostic)
                return Locate(profileDiagnostic, source, sourceFile);
        }
        if (source is not null && code.StartsWith("firmament-syntax-", StringComparison.Ordinal))
        {
            var candidates = Syntax.FirmamentSyntaxParser.Parse(source, sourceFile).Diagnostics.Where(d => d.Code == code).ToArray();
            if (candidates.Length == 1) return candidates[0] with { Source = diagnostic.Source, Stage = "Syntax" };
        }
        return Locate(new(diagnostic.Message, diagnostic.Severity switch
        {
            KernelDiagnosticSeverity.Error => "fatal",
            KernelDiagnosticSeverity.Warning => "warning",
            _ => "info"
        }, diagnostic.Message)
        {
            SourceFile = sourceFile,
            Stage = diagnostic.Source,
            Source = diagnostic.Source,
            LocationNote = "The owning build stage did not provide an original-source span."
        }, source, sourceFile) with { Code = code, Message = FirmamentInterop.FirmamentV2DiagnosticAdapter.MessageFor(diagnostic.Message) };
    }

    /// <summary>
    /// Producer codes name what they reject as <c>code:Kind:Name</c> or <c>key=Name</c> parameters. When those
    /// parameters name exactly one declaration in the source, that declaration is the diagnostic's location.
    /// </summary>
    internal static FirmamentV2SourceSpan? NamedDeclaration(string code, string source)
    {
        var parameters = code.Split(": ", 2)[0].Split(':').Skip(1)
            .Select(part => part.Contains('=') ? part[(part.IndexOf('=') + 1)..] : part).ToArray();
        if (parameters.Length == 0) return null;
        if (code.StartsWith("firmament-v2-field-unit-mismatch:", StringComparison.Ordinal) && parameters.Length >= 3)
        {
            var fields = Syntax.FirmamentSyntaxTraversal.Declarations(Syntax.FirmamentSyntaxParser.Parse(source).Document)
                .Where(d => d.Type.Name.Text == parameters[0] && d.Name?.Text == parameters[1])
                .SelectMany(d => d.Body?.Statements.OfType<Syntax.FieldSyntax>() ?? [])
                .Where(f => Syntax.FirmamentSyntaxFields.SameField(f.Name.Text, parameters[2])).ToArray();
            if (fields.Length > 1 && parameters.Length >= 5)
                fields = fields.Where(f => Syntax.FirmamentSyntaxTraversal.Expressions(f.Value)
                    .OfType<Syntax.QuantitySyntax>().Any(q => q.Unit.Text == parameters[4])).ToArray();
            if (fields.Length == 1) return fields[0].Span;
        }
        var declarations = Syntax.FirmamentSyntaxTraversal.Declarations(Syntax.FirmamentSyntaxParser.Parse(source).Document)
            .Where(d => d.Name is not null).ToArray();
        // A Kind:Name pair is the most specific; otherwise the first parameter that names one declaration.
        for (var i = 0; i + 1 < parameters.Length; i++)
        {
            var pair = declarations.Where(d => d.Type.Name.Text == parameters[i] && d.Name!.Text == parameters[i + 1]).ToArray();
            if (pair.Length == 1) return pair[0].Name!.Span;
        }
        foreach (var parameter in parameters)
        {
            // "Modify Plate" repeats its target's name; the target is the declaration meant.
            var named = declarations.Where(d => d.Name!.Text == parameter).ToArray();
            if (named.Length > 1) named = named.Where(d => d.Type.Name.Text != "Modify").ToArray();
            if (named.Length == 1) return named[0].Name!.Span;
        }
        return null;
    }

    public static FirmamentV2ValidationDiagnostic Locate(
        FirmamentV2ValidationDiagnostic diagnostic, string? source, string sourceFile)
    {
        if (diagnostic.SourceSpan is { } span)
        {
            if (source is null) return diagnostic with { SourceFile = sourceFile };
            var sourceLine = 1; var sourceColumn = 1;
            for (var index = 0; index < Math.Min(span.Start, source.Length); index++)
                if (source[index] == '\n') { sourceLine++; sourceColumn = 1; } else sourceColumn++;
            return diagnostic with { SourceFile = sourceFile, Line = sourceLine, Column = sourceColumn };
        }
        if (source is null) return diagnostic with { SourceFile = sourceFile, LocationNote = "Original source is unavailable." };
        if (diagnostic.Code.StartsWith("firmament-v2-thread-field-invalid:", StringComparison.Ordinal))
        {
            var name = diagnostic.Code.Split(':')[^1];
            var fields = Syntax.FirmamentSyntaxTraversal.Declarations(Syntax.FirmamentSyntaxParser.Parse(source).Document)
                .Where(d => d.Type.Name.Text == "Thread")
                .SelectMany(d => d.Body?.Statements.OfType<Syntax.FieldSyntax>() ?? [])
                .Where(f => Syntax.FirmamentSyntaxFields.SameField(f.Name.Text, name)).ToArray();
            if (fields.Length == 1)
                return Locate(diagnostic with { SourceSpan = fields[0].Name.Span, LocationNote = null }, source, sourceFile);
        }
        var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(token => token.Shape != "comment").ToArray();
        // Only these parser-owned diagnostics identify a specific original token.
        // All other legacy producers receive a disclosed enclosing declaration span.
        var parts = diagnostic.Code.Split(':');
        string? subject = parts[0] is FirmamentV2Parser.CanonicalFieldUnknown or FirmamentV2Parser.CanonicalDeclarationUnknown
            && parts.Length > 1 ? parts[^1] : null;
        var matches = subject is null ? [] : tokens.Where((token, index) => token.Shape == "identifier" &&
            (parts[0] == FirmamentV2Parser.CanonicalFieldUnknown
                ? Syntax.FirmamentSyntaxFields.SameField(token.Text, subject) && index + 1 < tokens.Length && tokens[index + 1].Text == ":"
                : token.Text == subject)).ToArray();
        var exact = matches.Length == 1;
        if (!exact && NamedDeclaration(diagnostic.Code, source) is { } named)
            return Locate(diagnostic with { SourceSpan = named, LocationNote = null }, source, sourceFile);
        var token = exact ? matches[0] : tokens.FirstOrDefault(token => token.Shape == "identifier"
            && token.Text is "Model" or "model" or "Struct" or "Concept" or "Profile" or "Template" or "Assembly" or "Scene");
        if (token is null) return diagnostic with { SourceFile = sourceFile, LocationNote = "The producer supplied no original-source location." };
        var line = 1; var column = 1;
        for (var index = 0; index < token.Start; index++)
            if (source[index] == '\n') { line++; column = 1; } else column++;
        return diagnostic with
        {
            SourceFile = sourceFile, SourceSpan = new(token.Start, token.Length), Line = line, Column = column,
            LocationNote = exact ? null : "Document declaration anchor; the producer supplied no precise original-source span."
        };
    }
}