Files
ScadaBridge/src/ZB.MOM.WW.ScadaBridge.ScriptAnalysis/RoslynScriptCompiler.cs
T
Joseph Doherty 5919a71b8b fix(scriptanalysis): warn on scripts blocking on a Task (.Result/.Wait()/GetAwaiter().GetResult()) (review 2026-10-21 01/SR-U2)
Advisory, not a trust-policy violation: every policy entry blocks deploy, and
an error here would fail the next redeploy of already-deployed scripts.
ValidationService surfaces it as a non-blocking ScriptCompilation warning.
2026-10-22 06:33:44 -04:00

127 lines
6.1 KiB
C#

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;
/// <summary>
/// The single authoritative Roslyn compile gate. Ported from the
/// SiteRuntime <c>ScriptCompilationService.CompileCore</c>, but returns
/// diagnostic messages rather than a compiled <c>Script</c> delegate — this is
/// the design-time gate (the deploy-time validation that previously relied on
/// the FAKE substring + brace-balance check in
/// <c>TemplateEngine/Validation/ScriptCompiler.cs</c>), which needs to know
/// whether the script <em>compiles</em>, not to execute it.
/// </summary>
public static class RoslynScriptCompiler
{
/// <summary>
/// One loader for every design-time compile. <c>CSharpScript.Create</c> otherwise
/// constructs a fresh <see cref="InteractiveAssemblyLoader"/> per call, and on .NET
/// each loader registers its own non-collectible <c>AssemblyLoadContext</c> — 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).
/// </summary>
private static readonly InteractiveAssemblyLoader SharedNonLoadingLoader = new();
/// <summary>
/// Parses the script as C# script source and returns syntax-error diagnostic
/// messages (severity Error only). Empty list means the script parses.
/// </summary>
/// <param name="code">The C# script source to parse.</param>
/// <returns>Error-severity parse diagnostic messages; empty if the script parses.</returns>
public static IReadOnlyList<string> 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();
}
/// <summary>
/// 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 <paramref name="globalsType"/>.
/// </summary>
/// <param name="code">The C# script source to compile.</param>
/// <param name="globalsType">
/// Optional globals type the script binds against — e.g.
/// <c>ScriptCompileSurface</c> for instance/shared scripts or
/// <c>TriggerCompileSurface</c> for trigger expressions.
/// </param>
/// <param name="extraReferences">Optional additional metadata references.</param>
/// <param name="extraImports">Optional additional namespace imports.</param>
/// <returns>Error-severity compile diagnostic messages; empty if the script compiles.</returns>
/// <exception cref="Exception">
/// 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.
/// </exception>
public static IReadOnlyList<string> Compile(
string code,
Type? globalsType = null,
IEnumerable<MetadataReference>? extraReferences = null,
IEnumerable<string>? 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();
}
/// <summary>
/// Builds the design-time <see cref="Script{T}"/> 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.
/// </summary>
/// <param name="code">The C# script source.</param>
/// <param name="globalsType">Optional globals type the script binds against.</param>
/// <param name="extraReferences">Optional additional metadata references.</param>
/// <param name="extraImports">Optional additional namespace imports.</param>
/// <returns>The unexecuted script.</returns>
internal static Script<object?> CreateScript(
string code,
Type? globalsType,
IEnumerable<MetadataReference>? extraReferences = null,
IEnumerable<string>? 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<object?>(code, options, globalsType, SharedNonLoadingLoader);
}
}