using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace ZB.MOM.WW.ScadaBridge.ScriptAnalysis; /// /// The single authoritative Roslyn compile gate. Ported from the /// SiteRuntime ScriptCompilationService.CompileCore, but returns /// diagnostic messages rather than a compiled Script delegate — this is /// the design-time gate (the deploy-time validation that previously relied on /// the FAKE substring + brace-balance check in /// TemplateEngine/Validation/ScriptCompiler.cs), which needs to know /// whether the script compiles, not to execute it. /// public static class RoslynScriptCompiler { /// /// One loader for every design-time compile. CSharpScript.Create otherwise /// constructs a fresh per call, and on .NET /// each loader registers its own non-collectible AssemblyLoadContext — even /// when nothing is ever emitted or loaded through it. The gate never executes a /// script, so this loader never loads anything; sharing it keeps the per-compile /// ALC count at zero (review 2026-10-21 04/M1). /// private static readonly InteractiveAssemblyLoader SharedNonLoadingLoader = new(); /// /// Parses the script as C# script source and returns syntax-error diagnostic /// messages (severity Error only). Empty list means the script parses. /// /// The C# script source to parse. /// Error-severity parse diagnostic messages; empty if the script parses. public static IReadOnlyList ParseDiagnostics(string code) { var tree = CSharpSyntaxTree.ParseText( code, new CSharpParseOptions(kind: SourceCodeKind.Script)); return tree.GetDiagnostics() .Where(d => d.Severity == DiagnosticSeverity.Error) .Select(d => d.GetMessage()) .ToList(); } /// /// Compiles the script against the trust-model references and imports and /// returns error-severity compilation diagnostic messages. Empty list means /// the script compiles cleanly against . /// /// The C# script source to compile. /// /// Optional globals type the script binds against — e.g. /// ScriptCompileSurface for instance/shared scripts or /// TriggerCompileSurface for trigger expressions. /// /// Optional additional metadata references. /// Optional additional namespace imports. /// Error-severity compile diagnostic messages; empty if the script compiles. /// /// Any non-diagnostic failure (metadata I/O, out-of-memory, an invalid import) is /// thrown, never folded into the returned list — a returned message is always a /// genuine compile error and therefore safe to memoise. /// public static IReadOnlyList Compile( string code, Type? globalsType = null, IEnumerable? extraReferences = null, IEnumerable? extraImports = null) { var script = CreateScript(code, globalsType, extraReferences, extraImports); // Diagnostics only — NO emit, NO load. `Script.Compile()` builds the // executor, which emits the PE image and loads it through // InteractiveAssemblyLoader into a fresh, non-collectible // AssemblyLoadContext: one permanent assembly per DISTINCT script for a gate // that never executes anything (review 2026-10-21 04/M1). The compilation's // own diagnostics are the declaration + method-body errors that decide // whether the script compiles. // // No catch-all here (review 2026-10-21 04/C1): an unexpected exception // (I/O reading metadata, OOM, ...) used to come back as a // "Compilation exception: ..." diagnostic, which the design-time verdict // cache then memoised as a sticky, process-wide "failed to compile". It now // propagates, so the caller can report it without caching it. var diagnostics = script.GetCompilation().GetDiagnostics(); return diagnostics .Where(d => d.Severity == DiagnosticSeverity.Error) .Select(d => d.GetMessage()) .ToList(); } /// /// Builds the design-time with the trust-model references, /// imports, the shared metadata resolver and the shared non-loading assembly /// loader. Callers must only read its compilation — never run it. /// /// The C# script source. /// Optional globals type the script binds against. /// Optional additional metadata references. /// Optional additional namespace imports. /// The unexecuted script. internal static Script CreateScript( string code, Type? globalsType, IEnumerable? extraReferences = null, IEnumerable? extraImports = null) { var references = ScriptTrustPolicy.DefaultReferences.ToList(); if (extraReferences != null) references.AddRange(extraReferences); var imports = ScriptTrustPolicy.DefaultImports.AsEnumerable(); if (extraImports != null) imports = imports.Concat(extraImports); var options = ScriptOptions.Default .WithReferences(references) .WithMetadataResolver(CachingScriptMetadataResolver.Instance) .WithImports(imports); return CSharpScript.Create(code, options, globalsType, SharedNonLoadingLoader); } }