fix(scripting): #1063 one compile-refusal authority for editor and deploy gate (ScriptCompileRules + the runtime's own wrapper text) — CS0161 and wrapper injection are now flagged in the editor; #1065 {{equip}} in a Calculation script is refused by the gate and by a new Calculation editor mode

#1063: the Monaco diagnostics dropped every Roslyn error located in the synthesized
wrapper as 'phantom', so CS0161 (not all code paths return a value, pinned on Run)
passed the editor and failed the deploy gate. ScriptCompileRules (Core.Scripting) now
states which diagnostics refuse (every Error, wherever located; LMX001/002 injection)
and which sources skip the compile (blank/passthrough value scripts); ScriptEvaluator
and the editor both use it, and the editor wraps with ScriptEvaluator.WrapperPreamble/
WrapperSuffix instead of its own copy. Wrapper-located refusals are drawn on the
script's last line. EditorGateParityTests runs one corpus through editor and gate in
all three modes.

#1065: a Calculation tag is raw/device-level with no equipment and its seam never
substitutes {{equip}}, so such a script deployed clean and read Bad forever. Refused
rather than substituted: EquipTokenLiteralScanner.FindInCalculation is run by
RoslynDeployScriptChecker for every Calculation use (before the passthrough shortcut,
outside the shared VT/Calc cache) and by the editor in the new 'calculation' mode
(Calculation tag editor; ScriptEdit defaults to it when a Calculation tag uses the
script).
This commit is contained in:
Joseph Doherty
2026-12-03 16:47:14 -05:00
parent a06dc8dd9f
commit 73f49eaf32
18 changed files with 644 additions and 186 deletions
@@ -51,19 +51,14 @@ public sealed class ScriptAnalysisService
/// </summary>
private sealed class Shape
{
public Shape(Type contextType, string returnType)
public Shape(Type contextType, string preamble)
{
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";
// The runtime's OWN wrapper text (ScriptEvaluator<TContext, TResult>.WrapperPreamble / WrapperSuffix) — the
// usings, the Run(ScriptGlobals<TContext>) signature and #line 1 — never a local copy (lmxopcua#1063). The
// value shape compiles to `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.
Preamble = preamble;
var compilation = CSharpCompilation.Create(
"ScriptAnalysis", new[] { Parse("", CancellationToken.None) }, Sandbox.References, CompileOptions);
_ = compilation.GetSpecialType(SpecialType.System_Object);
@@ -75,11 +70,14 @@ public sealed class ScriptAnalysisService
public CSharpCompilation BaseCompilation { get; }
public SyntaxTree Parse(string userSource, CancellationToken ct)
=> CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + "\n }\n}\n", cancellationToken: ct);
=> CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + ScriptEvaluator<VirtualTagContext, object?>.WrapperSuffix,
cancellationToken: ct);
}
private static readonly Shape ValueShape = new(typeof(VirtualTagContext), "object");
private static readonly Shape PredicateShape = new(typeof(AlarmPredicateContext), "bool");
private static readonly Shape ValueShape =
new(typeof(VirtualTagContext), ScriptEvaluator<VirtualTagContext, object?>.WrapperPreamble);
private static readonly Shape PredicateShape =
new(typeof(AlarmPredicateContext), ScriptEvaluator<AlarmPredicateContext, bool>.WrapperPreamble);
private static Shape ShapeFor(string? mode) => ScriptAnalysisModes.IsPredicate(mode) ? PredicateShape : ValueShape;
@@ -122,50 +120,62 @@ public sealed class ScriptAnalysisService
private static string Normalize(string? s) => (s ?? "").Replace("\r\n", "\n").Replace("\r", "\n");
/// <summary>Compiles the script and returns compile-error diagnostics plus sandbox-policy violations
/// (forbidden types, disallowed dynamic tag paths).</summary>
/// <param name="req">The diagnose request carrying the script source.</param>
/// <summary>Returns the markers for what the deploy gate would refuse — the runtime compile's own refusals (one
/// shared authority, <see cref="ScriptCompileRules"/>), sandbox-policy violations, disallowed dynamic tag paths and
/// the <c>{{equip}}</c> literal rules — plus advisory warnings.</summary>
/// <param name="req">The diagnose request carrying the script source and the analysis mode.</param>
/// <param name="ct">The request's cancellation token; a cancelled request throws <see cref="OperationCanceledException"/>.</param>
/// <returns>The list of diagnostic markers, empty when the script is clean or analysis fails.</returns>
public DiagnoseResponse Diagnose(DiagnoseRequest req, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(req.Code)) return new DiagnoseResponse(Array.Empty<DiagnosticMarker>());
var code = Normalize(req.Code);
var kind = ScriptAnalysisModes.KindOf(req.Mode);
// A blank / passthrough value script never reaches the compiler at runtime, so nothing the compiler says can
// refuse it (ScriptCompileRules.SkipsCompile — the deploy gate's own shortcut). A blank PREDICATE does compile,
// and is refused (CS0161), so it is analysed.
var compiles = !ScriptCompileRules.SkipsCompile(kind, code);
if (code.Length == 0 && !compiles) return new DiagnoseResponse(Array.Empty<DiagnosticMarker>());
try
{
ct.ThrowIfCancellationRequested();
var code = Normalize(req.Code);
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
// publish in ScriptEvaluator.Compile (it filters GetDiagnostics() to
// DiagnosticSeverity.Error). Mirroring that here keeps editor markers in lockstep with
// what fails publish: a nullable warning like CS8605 on the canonical passthrough shape
// `return ctx.GetTag("X").Value;` compiles + publishes fine under the evaluator's
// nullable-enabled options, so flagging it in the editor would be misleading noise.
// Restricted to diagnostics physically inside the user source — #line 1 in the preamble
// makes GetMappedLineSpan report user-source coords (GetLineSpan would return the
// physical wrapper line and be wrong); the preambleLength guard also drops phantom
// wrapper diagnostics like CS0161 on Run() when the user hasn't typed `return` yet.
foreach (var d in compilation.GetDiagnostics(ct))
// (1) The runtime compile's own refusals (lmxopcua#1063), from the one authority — ScriptCompileRules — over
// the runtime's own wrapper text: wrapper injection (LMX001/002) and EVERY Error-severity diagnostic. Warnings
// never refuse (a nullable warning like CS8605 on `return ctx.GetTag("X").Value;` publishes fine), so they are
// not shown. This used to drop every diagnostic located in the wrapper as "phantom" — including CS0161 "not
// all code paths return a value", which Roslyn pins on the wrapper's Run and the deploy gate refuses. Such a
// diagnostic is now drawn on the script's last line instead (ToRefusalMarker).
if (compiles)
{
if (d.Severity != DiagnosticSeverity.Error || !d.Location.IsInSource) continue;
if (d.Location.SourceSpan.Start < preambleLength) continue;
var span = d.Location.GetMappedLineSpan(); // honors #line 1 → user coords
markers.Add(ToMarker(span, Sev(d.Severity), d.GetMessage(), d.Id));
if (ScriptCompileRules.WrapperInjection(tree) is { } injection)
markers.Add(ToRefusalMarker(injection, code, preambleLength));
foreach (var d in ScriptCompileRules.CompileErrors(compilation, ct))
markers.Add(ToRefusalMarker(d, code, preambleLength));
// (2) ForbiddenTypeAnalyzer — spans are in the wrapped tree; map via #line.
ct.ThrowIfCancellationRequested();
foreach (var r in ForbiddenTypeAnalyzer.Analyze(compilation))
markers.Add(ToMarker(tree.GetMappedLineSpan(r.Span), 8, r.Message, "OTSCRIPT_FORBIDDEN"));
}
// (2) ForbiddenTypeAnalyzer — spans are in the wrapped tree; map via #line.
ct.ThrowIfCancellationRequested();
foreach (var r in ForbiddenTypeAnalyzer.Analyze(compilation))
markers.Add(ToMarker(tree.GetMappedLineSpan(r.Span), 8, r.Message, "OTSCRIPT_FORBIDDEN"));
ct.ThrowIfCancellationRequested();
// (3) DependencyExtractor — spans are offsets in the normalized user source; map directly.
foreach (var r in DependencyExtractor.Extract(code).Rejections)
markers.Add(ToUserMarker(code, r.Span, r.Message, "OTSCRIPT_DYNPATH"));
// (3b) lmxopcua#1056: a {{equip}} token in a verbatim/raw/interpolated path literal is never substituted —
// the deploy gate refuses it (RoslynDeployScriptChecker runs this same scan), so the editor does too.
foreach (var f in EquipTokenLiteralScanner.Find(code))
markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_EQUIPLITERAL"));
if (kind == ScriptContextKind.Calculation)
{
// (3a) lmxopcua#1065: a Calculation tag has no equipment — {{equip}} in any path literal is refused by the
// deploy gate (RoslynDeployScriptChecker runs this same scan). Covers every literal form, so it subsumes 3b.
foreach (var f in EquipTokenLiteralScanner.FindInCalculation(code))
markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_EQUIPCALC"));
}
else
{
// (3b) lmxopcua#1056: a {{equip}} token in a verbatim/raw/interpolated path literal is never substituted —
// the deploy gate refuses it (RoslynDeployScriptChecker runs this same scan), so the editor does too.
foreach (var f in EquipTokenLiteralScanner.Find(code))
markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_EQUIPLITERAL"));
}
// (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))
@@ -186,6 +196,27 @@ public sealed class ScriptAnalysisService
}
}
/// <summary>The message shown for CS0161, which Roslyn words in terms of the synthesized wrapper method.</summary>
internal const string NotAllPathsReturnMessage =
"Not all code paths return a value: every path through the script must end in a `return …;` statement " +
"(the deploy gate refuses the script otherwise).";
// A refusal of the runtime compile, as a marker. Physically inside the user source => its #line-mapped user-source
// position (GetMappedLineSpan honours #line 1; GetLineSpan would give the wrapper line). Anywhere else — on the
// wrapper (CS0161 sits on Run's identifier), or with no location — it is about the script as a whole, so it is drawn
// on the script's last line: never dropped, because the runtime compile refuses it all the same.
private static DiagnosticMarker ToRefusalMarker(Diagnostic d, string code, int preambleLength)
{
var message = d.Id == "CS0161" ? NotAllPathsReturnMessage : d.GetMessage();
if (d.Location.IsInSource && d.Location.SourceSpan.Start >= preambleLength)
return ToMarker(d.Location.GetMappedLineSpan(), 8, message, d.Id);
// The last line with text on it (trailing blank lines would put the squiggle on nothing).
var end = code.TrimEnd().Length;
var lastLineStart = end == 0 ? 0 : code.LastIndexOf('\n', end - 1) + 1;
var (line, _) = LineCol(code, lastLineStart);
return new DiagnosticMarker(8, line, 1, line, Math.Max(1, end - lastLineStart + 1), message, d.Id);
}
/// <summary>Diagnostics plus the v3 equipment-relative <c>{{equip}}/&lt;RefName&gt;</c> resolution check.
/// Runs the synchronous Roslyn/policy <see cref="Diagnose"/> then, when an equipment context + catalog
/// are present, appends a marker for each <c>{{equip}}/&lt;RefName&gt;</c> whose <c>&lt;RefName&gt;</c> is