fix(editor): #1025 analyse scripted-alarm predicates as bool Run(AlarmPredicateContext) — predicate mode on the analysis endpoints, Monaco and the ScriptEdit page

This commit is contained in:
Joseph Doherty
2026-12-03 15:03:17 -05:00
parent 29c44d1f04
commit 16c8b7ffad
9 changed files with 371 additions and 55 deletions
@@ -3,6 +3,7 @@ using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
using ZB.MOM.WW.OtOpcUa.Core.VirtualTags;
@@ -27,8 +28,6 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;
/// </remarks>
public sealed class ScriptAnalysisService
{
private static readonly SandboxConfig Sandbox = ScriptSandbox.Build(typeof(VirtualTagContext));
private static readonly string Preamble = BuildPreamble();
private static readonly CSharpCompilationOptions CompileOptions = new(
OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release,
allowUnsafe: false, warningLevel: 4, nullableContextOptions: NullableContextOptions.Enable);
@@ -44,52 +43,66 @@ public sealed class ScriptAnalysisService
_logger = logger;
}
// Mirrors ScriptEvaluator's wrapper EXACTLY (usings from the sandbox + the
// Run(ScriptGlobals<VirtualTagContext>) shape), except the analysis return type is
// `object` so a shared script stays valid regardless of any virtual tag's DataType.
private static string BuildPreamble()
{
var usings = string.Join("\n", Sandbox.Imports.Select(i => $"using {i};"));
var globalsType = $"global::{typeof(ScriptGlobals<>).Namespace}.ScriptGlobals<global::{typeof(VirtualTagContext).FullName}>";
return usings + "\n\n"
+ "namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;\n"
+ "public static class CompiledScript\n{\n"
+ $" public static object Run({globalsType} globals)\n {{\n"
+ " var ctx = globals.ctx;\n#line 1\n";
}
private static SyntaxTree WrapAndParse(string userSource, CancellationToken ct)
=> CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + "\n }\n}\n", cancellationToken: ct);
/// <summary>
/// The process-wide compilation every analysis derives from. Its sandbox reference set is bound ONCE
/// (forced here by resolving <c>System.Object</c>); <see cref="CSharpCompilation.ReplaceSyntaxTree"/> keeps
/// that binding, so a request only re-binds the user's tree instead of the whole reference set. It is
/// immutable, so sharing it across circuits and requests is thread-safe.
/// One analysis shape (lmxopcua#1025): the sandbox + wrapper the deploy gate compiles a seam's script with, and
/// the process-wide <see cref="BaseCompilation"/> every analysis of that seam derives from. Its sandbox reference
/// set is bound ONCE (forced by resolving <c>System.Object</c>); <see cref="CSharpCompilation.ReplaceSyntaxTree"/>
/// keeps that binding, so a request only re-binds the user's tree. Immutable, so shared across circuits/requests.
/// </summary>
internal static readonly CSharpCompilation BaseCompilation = CreateBaseCompilation();
private static CSharpCompilation CreateBaseCompilation()
private sealed class Shape
{
var compilation = CSharpCompilation.Create(
"ScriptAnalysis", new[] { WrapAndParse("", CancellationToken.None) }, Sandbox.References, CompileOptions);
_ = compilation.GetSpecialType(SpecialType.System_Object);
return compilation;
public Shape(Type contextType, string returnType)
{
Sandbox = ScriptSandbox.Build(contextType);
// Mirrors ScriptEvaluator's wrapper EXACTLY (usings from the sandbox + the Run(ScriptGlobals<TContext>)
// shape). The value shape's return type is `object` so a shared script stays valid regardless of any
// virtual tag's DataType; the predicate shape is `bool`, exactly as the alarm engine compiles it.
var usings = string.Join("\n", Sandbox.Imports.Select(i => $"using {i};"));
var globalsType = $"global::{typeof(ScriptGlobals<>).Namespace}.ScriptGlobals<global::{contextType.FullName}>";
Preamble = usings + "\n\n"
+ "namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;\n"
+ "public static class CompiledScript\n{\n"
+ $" public static {returnType} Run({globalsType} globals)\n {{\n"
+ " var ctx = globals.ctx;\n#line 1\n";
var compilation = CSharpCompilation.Create(
"ScriptAnalysis", new[] { Parse("", CancellationToken.None) }, Sandbox.References, CompileOptions);
_ = compilation.GetSpecialType(SpecialType.System_Object);
BaseCompilation = compilation;
}
public SandboxConfig Sandbox { get; }
public string Preamble { get; }
public CSharpCompilation BaseCompilation { get; }
public SyntaxTree Parse(string userSource, CancellationToken ct)
=> CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + "\n }\n}\n", cancellationToken: ct);
}
private static readonly Shape ValueShape = new(typeof(VirtualTagContext), "object");
private static readonly Shape PredicateShape = new(typeof(AlarmPredicateContext), "bool");
private static Shape ShapeFor(string? mode) => ScriptAnalysisModes.IsPredicate(mode) ? PredicateShape : ValueShape;
/// <summary>The process-wide value-shape compilation (test seam; the predicate shape has its own).</summary>
internal static CSharpCompilation BaseCompilation => ValueShape.BaseCompilation;
// userSource is appended after Preamble, then the method/class are closed. Every analysis derives straight
// from the shared BaseCompilation: the analysis endpoints are minimal-API handlers, so a scoped service lives
// for one HTTP request and a per-instance lineage would never be more than one step long.
private static (SyntaxTree Tree, CSharpCompilation Compilation, SemanticModel Model, int PreambleLength) Analyze(
string userSource, CancellationToken ct)
string userSource, string? mode, CancellationToken ct)
{
var tree = WrapAndParse(userSource, ct);
var compilation = BaseCompilation.ReplaceSyntaxTree(BaseCompilation.SyntaxTrees[0], tree);
return (tree, compilation, compilation.GetSemanticModel(tree), Preamble.Length);
var shape = ShapeFor(mode);
var tree = shape.Parse(userSource, ct);
var compilation = shape.BaseCompilation.ReplaceSyntaxTree(shape.BaseCompilation.SyntaxTrees[0], tree);
return (tree, compilation, compilation.GetSemanticModel(tree), shape.Preamble.Length);
}
/// <summary>Test seam: the compilation one analysis of <paramref name="userSource"/> runs against.</summary>
internal CSharpCompilation CompilationFor(string userSource) => Analyze(Normalize(userSource), CancellationToken.None).Compilation;
/// <param name="userSource">The script source.</param>
/// <param name="mode">The analysis mode (<see cref="ScriptAnalysisModes"/>); null = value.</param>
internal CSharpCompilation CompilationFor(string userSource, string? mode = null)
=> Analyze(Normalize(userSource), mode, CancellationToken.None).Compilation;
// editor (line,col) in USER-source coords -> physical offset in the wrapped document
private static int OffsetInWrapped(string userSource, int line, int column, int preambleLength)
@@ -121,7 +134,7 @@ public sealed class ScriptAnalysisService
{
ct.ThrowIfCancellationRequested();
var code = Normalize(req.Code);
var (tree, compilation, _, preambleLength) = Analyze(code, ct);
var (tree, compilation, _, preambleLength) = Analyze(code, req.Mode, ct);
var markers = new List<DiagnosticMarker>();
// (1) Roslyn — surface ONLY compile errors, the same severity that actually blocks a
@@ -152,7 +165,9 @@ public sealed class ScriptAnalysisService
// (4) ctx.SetVirtualTag(...) is inert at runtime — a WARNING (severity 4), never an error: publish
// accepts the script, so the editor must too; the marker just puts the hover's caveat in the Problems list.
foreach (var inv in SetVirtualTagCalls(tree.GetRoot(ct), preambleLength))
markers.Add(ToMarker(tree.GetMappedLineSpan(inv.Span), 4, SetVirtualTagInertMessage, "OTSCRIPT_SETVTAG_INERT"));
markers.Add(ToMarker(tree.GetMappedLineSpan(inv.Span), 4,
ScriptAnalysisModes.IsPredicate(req.Mode) ? SetVirtualTagPredicateMessage : SetVirtualTagInertMessage,
"OTSCRIPT_SETVTAG_INERT"));
return new DiagnoseResponse(Bound(markers));
}
@@ -228,6 +243,10 @@ public sealed class ScriptAnalysisService
: m with { Message = ScriptProblems.Truncate(m.Message, ScriptEditorLimits.MaxDiagnosticMessageChars) })
.ToList();
private const string SetVirtualTagPredicateMessage =
"ctx.SetVirtualTag(...) throws in a scripted-alarm predicate: predicates must be side-effect free. The script " +
"compiles and publishes, but every evaluation fails — move the write into a virtual tag the predicate reads.";
private const string SetVirtualTagInertMessage =
"ctx.SetVirtualTag(...) has no effect at runtime: cross-tag writes are dropped in single-tag mode (the " +
"cascade engine is not wired into the host). The script compiles and publishes, but this write will not " +
@@ -282,7 +301,7 @@ public sealed class ScriptAnalysisService
{
ct.ThrowIfCancellationRequested();
var code = Normalize(req.CodeText);
var (tree, _, model, preambleLength) = Analyze(code, ct);
var (tree, _, model, preambleLength) = Analyze(code, req.Mode, ct);
var position = OffsetInWrapped(code, req.Line, req.Column, preambleLength);
var root = await tree.GetRootAsync(ct);
// position is the offset just AFTER the caret; -1 finds the token the caret sits at/just-after (e.g. the dot in "ctx.").
@@ -402,7 +421,7 @@ public sealed class ScriptAnalysisService
{
ct.ThrowIfCancellationRequested();
var code = Normalize(req.CodeText);
var (tree, _, model, preambleLength) = Analyze(code, ct);
var (tree, _, model, preambleLength) = Analyze(code, req.Mode, ct);
var position = OffsetInWrapped(code, req.Line, req.Column, preambleLength);
var token = tree.GetRoot(ct).FindToken(Math.Max(0, position - 1));
@@ -504,7 +523,7 @@ public sealed class ScriptAnalysisService
{
ct.ThrowIfCancellationRequested();
var code = Normalize(req.CodeText);
var (tree, _, model, preambleLength) = Analyze(code, ct);
var (tree, _, model, preambleLength) = Analyze(code, req.Mode, ct);
var position = OffsetInWrapped(code, req.Line, req.Column, preambleLength);
var token = tree.GetRoot(ct).FindToken(Math.Max(0, position - 1));