fix(scripting): #1083 a dynamic tag path is an editor error only where the gate refuses it (predicate), a warning in value/Calculation mode; #1093 Calculation-mode {{equip}} hover says it is refused

#1083: OTSCRIPT_DYNPATH was an error in every editor mode while the deploy gate refuses a
non-literal tag path only for a scripted-alarm predicate (editor stricter than the gate).
Decision: do not make the gate stricter (it would reject configurations that deploy today).
ScriptCompileRules now owns the split — RefusesNonLiteralTagPaths(kind) and
TagPathFindings(kind, source), each finding carrying Refuses — the gate refuses on exactly
those findings and the editor draws them as errors (8) and the rest as warnings (4), whose
text says what the path does at runtime (not a declared input: not subscribed, does not
re-trigger, reads BadNodeIdUnknown unless also read literally). DependencyRejection gains
Kind + MethodName for that wording. EditorGateParityTests carries dynamic / concatenated /
interpolated / empty paths in all three modes (14 rows fail with the old always-error
severity).

#1093: hovering a {{equip}} path literal in Calculation mode showed the VirtualTag
"resolves ... when deployed" text, contradicting the OTSCRIPT_EQUIPCALC marker on the same
span. It now says the token is refused in a Calculation script and why (no owning
equipment, never substituted, the gate refuses it). The {{equip}} hover no longer needs a
tag catalog.
This commit is contained in:
Joseph Doherty
2026-12-04 15:02:41 -05:00
parent ec4eed337c
commit bd4fff6444
8 changed files with 234 additions and 33 deletions
+23 -10
View File
@@ -124,7 +124,7 @@ the `ConfigEditor` authorization policy (`AdminUiPolicies.ConfigEditor`: Adminis
| Route | Request DTO | Response DTO | Purpose |
|-------|-------------|--------------|---------|
| `POST /api/script-analysis/diagnostics` | `DiagnoseRequest(Code)` | `DiagnoseResponse(Markers)` | Roslyn + ForbiddenType + dynamic-path error markers |
| `POST /api/script-analysis/diagnostics` | `DiagnoseRequest(Code)` | `DiagnoseResponse(Markers)` | Roslyn + ForbiddenType + dynamic-path markers (error for a predicate, warning otherwise — #1083) |
| `POST /api/script-analysis/completions` | `CompletionsRequest(CodeText, Line, Column)` | `CompletionsResponse(Items)` | Scope, dot-member, and tag-path completions |
| `POST /api/script-analysis/hover` | `HoverRequest(CodeText, Line, Column)` | `HoverResponse(Markdown?)` | Type + XML doc markdown |
| `POST /api/script-analysis/signature-help` | `SignatureHelpRequest(CodeText, Line, Column)` | `SignatureHelpResponse(Label?, Parameters?, ActiveParameter)` | Parameter help |
@@ -212,9 +212,10 @@ scripted alarms are the script's only users, and to *value* otherwise; pick whic
seam you are authoring for. The per-equipment VirtualTag editor is value mode and the
Calculation tag editor is Calculation mode. A body that lacks a `return` on some path
(CS0161) is flagged while you type since #1063 (it used to be filtered as a "phantom"
wrapper diagnostic while the gate refused it). Known remaining divergence: a dynamic
tag path (`OTSCRIPT_DYNPATH`) is an editor error in every mode but a gate refusal only
for a predicate. See `docs/VirtualTags.md` §"Deploy-time script compile gate" for
wrapper diagnostic while the gate refused it). A dynamic tag path (`OTSCRIPT_DYNPATH`)
is an editor **error** only in predicate mode, where the gate refuses it, and a
**warning** in value and Calculation mode, where it deploys (#1083 — it used to be an
error in every mode). See `docs/VirtualTags.md` §"Deploy-time script compile gate" for
modes, caching and the upgrade note.
### Runtime safety (what happens after publish)
@@ -314,11 +315,20 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`:
`DependencyExtractor.Extract(code).Rejections` enumerates every `ctx.GetTag` /
`ctx.SetVirtualTag` call whose first argument is NOT a string literal (variable,
concatenation, interpolation). Each rejection carries a `TextSpan` in
user-source coordinates, emitted as code `OTSCRIPT_DYNPATH`. This is the exact
check the deploy gate (and the scripted-alarm load) enforces for a scripted-alarm
predicate — the editor shows the squiggle where the literal must appear. In value
and Calculation mode the editor marks it an error too, but the gate does not refuse
it there: a known editor-stricter divergence, excluded from `EditorGateParityTests`.
user-source coordinates, emitted as code `OTSCRIPT_DYNPATH`. Which seams it refuses is
decided in `ScriptCompileRules` (#1083): `RefusesNonLiteralTagPaths(kind)` is true for a
scripted-alarm predicate only (the alarm load runs the extractor and refuses the alarm),
and `TagPathFindings(kind, source)` returns each rejection with a `Refuses` flag. The
deploy gate refuses on exactly those findings, and the editor draws them as an **error**
(severity 8) where `Refuses` and a **warning** (severity 4) otherwise — so the two cannot
drift. In value and Calculation mode the warning says what the path does at runtime:
those seams read only their *declared* inputs (the literal `ctx.GetTag` paths, which
are what gets subscribed and what re-triggers the script), so a dynamic read returns
Bad (`BadNodeIdUnknown`, null value) unless the same path is also read with a literal
elsewhere in the script; an empty literal path always reads Bad (and an empty
`SetVirtualTag` path throws). Making the gate refuse these in value/Calculation scripts
was declined — it would reject configurations that deploy today. `EditorGateParityTests`
carries dynamic, concatenated, interpolated and empty paths in all three modes.
---
@@ -520,7 +530,10 @@ inline script panel):
- **Hover** — hovering a `{{equip}}/<RefName>` path literal shows an
*"Equipment-relative path — resolved through the equipment's tag reference at
deploy"* note.
deploy"* note. In **Calculation** mode it instead says the token is refused there and
why — a Calculation tag is raw/device-level with no owning equipment, so nothing
substitutes it and the deploy gate refuses the script (#1093, matching the
`OTSCRIPT_EQUIPCALC` marker on the same span). This hover needs no tag catalog.
- **Completions** — typing `{{equip}}/` inside a `GetTag`/`SetVirtualTag` literal
offers the owning equipment's **reference effective names** (needs an equipment
context; inert on the shared ScriptEdit page).
@@ -103,7 +103,9 @@ public static class DependencyExtractor
_rejections.Add(new DependencyRejection(
Span: node.Span,
Message: $"Call to ctx.{methodName} has no arguments. " +
"The tag path must be the first argument."));
"The tag path must be the first argument.",
Kind: DependencyRejectionKind.NoArguments,
MethodName: methodName));
return;
}
@@ -122,7 +124,9 @@ public static class DependencyExtractor
Message: $"Tag path passed to ctx.{methodName} must be a string literal. " +
$"Dynamic paths (variables, concatenation, interpolation, method " +
$"calls) are rejected at publish so the dependency graph can be " +
$"built statically. Got: {pathArg.Kind()} ({pathArg})"));
$"built statically. Got: {pathArg.Kind()} ({pathArg})",
Kind: DependencyRejectionKind.NotALiteral,
MethodName: methodName));
return;
}
@@ -131,7 +135,9 @@ public static class DependencyExtractor
{
_rejections.Add(new DependencyRejection(
Span: literal.Span,
Message: $"Tag path passed to ctx.{methodName} is empty or whitespace."));
Message: $"Tag path passed to ctx.{methodName} is empty or whitespace.",
Kind: DependencyRejectionKind.EmptyPath,
MethodName: methodName));
return;
}
@@ -154,4 +160,25 @@ public sealed record DependencyExtractionResult(
}
/// <summary>A single non-literal-path rejection with the exact source span for UI pointing.</summary>
public sealed record DependencyRejection(TextSpan Span, string Message);
/// <param name="Span">The offending source span (the path argument, or the whole call when it has no arguments).</param>
/// <param name="Message">The refusal text (worded for a seam that refuses it — see <see cref="ScriptCompileRules.TagPathFindings"/>).</param>
/// <param name="Kind">What is wrong with the path.</param>
/// <param name="MethodName"><c>GetTag</c> or <c>SetVirtualTag</c>.</param>
public sealed record DependencyRejection(
TextSpan Span,
string Message,
DependencyRejectionKind Kind = DependencyRejectionKind.NotALiteral,
string MethodName = nameof(ScriptContext.GetTag));
/// <summary>What a <see cref="DependencyRejection"/> found wrong with a tag-path argument.</summary>
public enum DependencyRejectionKind
{
/// <summary>The path is not a string literal (a variable, concatenation, interpolation, a method call).</summary>
NotALiteral,
/// <summary>The path is an empty or whitespace string literal.</summary>
EmptyPath,
/// <summary>The call has no arguments at all (also a compile error).</summary>
NoArguments,
}
@@ -14,7 +14,8 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// blank source never reach Roslyn at runtime, so they pass; anything else goes through
/// <see cref="ScriptEvaluator{TContext, TResult}.Verify"/> as <c>VirtualTagContext → object?</c>.</item>
/// <item><b>AlarmPredicate</b> — <see cref="DependencyExtractor"/> first (the scripted-alarm load rejects a
/// non-literal tag path before compiling), then <see cref="ScriptEvaluator{TContext, TResult}.Verify"/> as
/// non-literal tag path before compiling; which seams refuse one is
/// <see cref="ScriptCompileRules.RefusesNonLiteralTagPaths"/>, lmxopcua#1083), then <see cref="ScriptEvaluator{TContext, TResult}.Verify"/> as
/// <c>AlarmPredicateContext → bool</c>. No passthrough shortcut: the alarm engine always compiles.</item>
/// </list>
/// <see cref="ScriptEvaluator{TContext, TResult}.Verify"/> builds its compilation through the same private factory
@@ -129,13 +130,15 @@ public sealed class RoslynDeployScriptChecker : IDeployScriptChecker
return new CachedVerdict(
["equip token not substituted — " + string.Join("; ", unsubstituted.Select(f => f.Message))],
Cacheable: true);
// lmxopcua#1083: which seams a non-literal tag path refuses (only the predicate — the alarm load runs the
// extractor) is ScriptCompileRules' decision, read by the editor too, so its error/warning split matches this.
var pathRefusals = ScriptCompileRules.TagPathFindings(request.Kind, source).Where(f => f.Refuses).ToArray();
if (pathRefusals.Length > 0)
return new CachedVerdict(
["dependency extraction rejected — " + string.Join("; ", pathRefusals.Select(f => f.Message))],
Cacheable: true);
if (request.Kind == ScriptContextKind.AlarmPredicate)
{
var extraction = DependencyExtractor.Extract(source);
if (!extraction.IsValid)
return new CachedVerdict(
["dependency extraction rejected — " + string.Join("; ", extraction.Rejections.Select(r => r.Message))],
Cacheable: true);
ScriptEvaluator<AlarmPredicateContext, bool>.Verify(source);
}
else
@@ -1,6 +1,7 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using ZB.MOM.WW.OtOpcUa.Core.VirtualTags;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
@@ -23,6 +24,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// The third refusal leg, <see cref="ForbiddenTypeAnalyzer"/>, is already one shared analyzer and is called
/// directly by both sides.
/// </para>
/// <para>
/// The fourth is a seam rule rather than a compile rule: a NON-LITERAL tag path (<c>ctx.GetTag(variable)</c>)
/// refuses a scripted-alarm predicate only (<see cref="RefusesNonLiteralTagPaths"/>, lmxopcua#1083). The gate
/// refuses what <see cref="TagPathFindings"/> marks <c>Refuses</c>, and the editor draws exactly those as errors
/// and the rest as warnings — so the editor's severity cannot drift from the gate's verdict.
/// </para>
/// </remarks>
public static class ScriptCompileRules
{
@@ -38,6 +45,69 @@ public static class ScriptCompileRules
kind is ScriptContextKind.VirtualTag or ScriptContextKind.Calculation
&& (string.IsNullOrWhiteSpace(source) || PassthroughScript.TryMatch(source, out _));
/// <summary>
/// Whether a tag path that is not a non-empty string literal refuses a script run as <paramref name="kind"/>
/// (lmxopcua#1083). Only a scripted-alarm predicate: the alarm load runs <see cref="DependencyExtractor"/> and
/// refuses the alarm, so the deploy gate does too. A VirtualTag or Calculation script with such a path deploys and
/// runs — the path is simply not a declared input (see <see cref="TagPathFindings"/>). Making the gate refuse it
/// there too was declined: it would start rejecting configurations that deploy today.
/// </summary>
/// <param name="kind">The seam the script runs as.</param>
/// <returns>True for <see cref="ScriptContextKind.AlarmPredicate"/>.</returns>
public static bool RefusesNonLiteralTagPaths(ScriptContextKind kind) => kind == ScriptContextKind.AlarmPredicate;
/// <summary>
/// Every <c>ctx.GetTag</c> / <c>ctx.SetVirtualTag</c> whose path is not a non-empty string literal
/// (<see cref="DependencyExtractor"/>), with what it means for <paramref name="kind"/>: a refusal (the original
/// extractor text) where <see cref="RefusesNonLiteralTagPaths"/>, otherwise an advisory that says what the path
/// does at runtime. The deploy gate refuses on the <c>Refuses</c> findings; the editor shows them as errors and the
/// others as warnings.
/// </summary>
/// <param name="kind">The seam the script runs as.</param>
/// <param name="source">The script source (user coordinates).</param>
/// <returns>The findings; empty when every tag path is a non-empty literal.</returns>
public static IReadOnlyList<TagPathFinding> TagPathFindings(ScriptContextKind kind, string? source)
{
source ??= string.Empty;
var rejections = DependencyExtractor.Extract(source).Rejections;
if (rejections.Count == 0) return [];
var refuses = RefusesNonLiteralTagPaths(kind);
var findings = new TagPathFinding[rejections.Count];
for (var i = 0; i < rejections.Count; i++)
{
var r = rejections[i];
findings[i] = new TagPathFinding(r.Span, refuses ? r.Message : AdvisoryFor(r, source), refuses);
}
return findings;
}
// The text for a path the seam accepts: what actually happens at runtime. A VirtualTag / Calculation seam reads from
// its DECLARED inputs only (the literal ctx.GetTag paths, EquipmentScriptPaths.ExtractDependencyRefs) — those are
// what the mux subscribes and what re-triggers the script — so any other path reads as unknown.
private static string AdvisoryFor(DependencyRejection r, string source)
{
const string accepted = "The deploy accepts this in a VirtualTag or Calculation script (a scripted-alarm predicate refuses it).";
var call = "ctx." + r.MethodName;
var text = r.Span.End <= source.Length ? source.Substring(r.Span.Start, r.Span.Length) : "";
var isRead = r.MethodName == nameof(ScriptContext.GetTag);
return r.Kind switch
{
DependencyRejectionKind.NotALiteral when isRead =>
$"Dynamic tag path `{text}`: it is not a string literal, so it is not a declared input of this script. " +
"Only literal paths are subscribed, so this read returns Bad (BadNodeIdUnknown, null value) unless the same " +
"path is also read with a literal elsewhere in the script, and a change to that tag does not re-run the script. " +
accepted,
DependencyRejectionKind.NotALiteral =>
$"Dynamic tag path `{text}` passed to {call}: it is not a string literal, so dependency analysis cannot see " +
"the target. " + accepted,
DependencyRejectionKind.EmptyPath when isRead =>
$"Empty tag path passed to {call}: the read always returns Bad (BadNodeIdUnknown, null value). " + accepted,
DependencyRejectionKind.EmptyPath =>
$"Empty tag path passed to {call}: the call throws when it runs, failing the script. " + accepted,
_ => r.Message,
};
}
/// <summary>
/// The compiler diagnostics that make the runtime refuse a wrapped script: every
/// <see cref="DiagnosticSeverity.Error"/> diagnostic, wherever it is located (user source, wrapper, or none).
@@ -103,3 +173,9 @@ public static class ScriptCompileRules
return null;
}
}
/// <summary>One finding of <see cref="ScriptCompileRules.TagPathFindings"/> (lmxopcua#1083).</summary>
/// <param name="Span">The offending span, in user-source coordinates.</param>
/// <param name="Message">What is wrong, worded for the seam (a refusal, or an advisory of what it does at runtime).</param>
/// <param name="Refuses">Whether the seam — and so the deploy gate — refuses the script for it.</param>
public sealed record TagPathFinding(TextSpan Span, string Message, bool Refuses);
@@ -121,8 +121,9 @@ public sealed class ScriptAnalysisService
private static string Normalize(string? s) => (s ?? "").Replace("\r\n", "\n").Replace("\r", "\n");
/// <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>
/// shared authority, <see cref="ScriptCompileRules"/>), sandbox-policy violations, dynamic tag paths where the seam
/// refuses them (a predicate; a warning elsewhere, lmxopcua#1083) 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>
@@ -159,9 +160,12 @@ public sealed class ScriptAnalysisService
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"));
// (3) Non-literal tag paths (DependencyExtractor) — spans are offsets in the normalized user source; map
// directly. lmxopcua#1083: an ERROR only where the deploy gate refuses it (a scripted-alarm predicate), a
// WARNING in value / Calculation mode, where the script deploys and the path is just not a declared input.
// The split is ScriptCompileRules' (Refuses), the same flag the gate refuses on.
foreach (var f in ScriptCompileRules.TagPathFindings(kind, code))
markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_DYNPATH", f.Refuses ? 8 : 4));
if (kind == ScriptContextKind.Calculation)
{
// (3a) lmxopcua#1065: a Calculation tag has no equipment — {{equip}} in any path literal is refused by the
@@ -311,11 +315,11 @@ public sealed class ScriptAnalysisService
sev, span.StartLinePosition.Line + 1, span.StartLinePosition.Character + 1,
span.EndLinePosition.Line + 1, span.EndLinePosition.Character + 1, msg, code);
private static DiagnosticMarker ToUserMarker(string userSource, Microsoft.CodeAnalysis.Text.TextSpan span, string msg, string code)
private static DiagnosticMarker ToUserMarker(string userSource, Microsoft.CodeAnalysis.Text.TextSpan span, string msg, string code, int severity = 8)
{
var (sl, sc) = LineCol(userSource, span.Start);
var (el, ec) = LineCol(userSource, span.End);
return new DiagnosticMarker(8, sl, sc, el, ec, msg, code);
return new DiagnosticMarker(severity, sl, sc, el, ec, msg, code);
}
private static (int Line, int Col) LineCol(string code, int offset)
@@ -445,6 +449,19 @@ public sealed class ScriptAnalysisService
return new CompletionItem(symbol.Name, symbol.Name,
symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), kind);
}
/// <summary>
/// The hover for a <c>{{equip}}</c> path literal in a Calculation script (lmxopcua#1093): it says the token is
/// refused there and why, matching the <c>OTSCRIPT_EQUIPCALC</c> marker on the same span (lmxopcua#1065).
/// </summary>
/// <param name="escapedPath">The literal's path, already backtick-escaped for markdown.</param>
/// <returns>The hover markdown.</returns>
internal static string CalculationEquipHover(string escapedPath) =>
$"**`{{{{equip}}}}` is refused in a Calculation script** `{escapedPath}`\n\n" +
"A Calculation tag is a raw, device-level tag: it has no owning equipment, so `{{equip}}` has nothing to " +
"resolve to, and the Calculation seam never substitutes it. The deploy gate refuses the script " +
"(`equip token in a Calculation script`). Read the source by its literal RawPath instead; " +
"`{{equip}}/<RefName>` is for VirtualTags, which belong to an equipment.";
/// <summary>Computes hover information (tag-path info or C# symbol info) for the position under the caret.</summary>
/// <param name="req">The hover request carrying the script source and caret position.</param>
/// <param name="ct">The request's cancellation token; a cancelled request throws <see cref="OperationCanceledException"/>.</param>
@@ -463,21 +480,27 @@ public sealed class ScriptAnalysisService
// Tag-path hover takes priority over C# symbol resolution: when the caret sits on a
// ctx.GetTag("…")/ctx.SetVirtualTag("…") path literal, show the resolved tag's info
// (or note it's not a known configured tag path) instead of the string-literal symbol.
if (_catalog is not null && TryGetTagPathLiteral(token, out var tagPath, out var isSetVirtualTag) && !string.IsNullOrEmpty(tagPath))
if (TryGetTagPathLiteral(token, out var tagPath, out var isSetVirtualTag) && !string.IsNullOrEmpty(tagPath)
&& (_catalog is not null || tagPath.Contains(EquipmentScriptPaths.EquipToken, StringComparison.Ordinal)))
{
static string Code(string s) => s.Replace("`", "\\`");
// Equipment-relative literal (contains the {{equip}} token): it cannot resolve to a
// configured path as-typed (the token is only substituted at deploy), so short-circuit
// before GetTagInfoAsync and explain the token instead of warning "not a known path".
// Needs no catalog, so it is answered even where none is wired.
if (tagPath.Contains(EquipmentScriptPaths.EquipToken, StringComparison.Ordinal))
{
// lmxopcua#1093: in a Calculation script the token is refused (OTSCRIPT_EQUIPCALC, #1065), so the
// VirtualTag explanation ("resolves … when deployed") would contradict the marker on the same span.
if (ScriptAnalysisModes.KindOf(req.Mode) == ScriptContextKind.Calculation)
return new HoverResponse(CalculationEquipHover(Code(tagPath)));
return new HoverResponse(
$"**Equipment-relative path** `{Code(tagPath)}`\n\n" +
"`{{equip}}/<RefName>` resolves through the owning equipment's tag reference " +
"(by effective name) to the backing raw tag's path when the VirtualTag is deployed.");
}
var info = await _catalog.GetTagInfoAsync(tagPath, ct);
var info = await _catalog!.GetTagInfoAsync(tagPath, ct);
var tagMd = info is null
? $"**Tag path** `{Code(tagPath)}`\n\n⚠ Not a known configured tag path."
: $"**Tag path** `{Code(info.Path)}`\n\n{info.Kind} · Type **{info.DataType}**"
@@ -101,9 +101,11 @@ public sealed class DiagnoseTests
Diag(code).Any(x => x.Severity == 8).ShouldBe(publishRefuses);
}
// lmxopcua#1083: flagged as a WARNING in the (default) value mode — the deploy gate accepts it there; only a
// scripted-alarm predicate refuses it (EditorGateParityTests pins the per-mode split).
[Fact] public void Dynamic_tag_path_is_flagged()
=> Diag("""var p = "A"; return ctx.GetTag(p).Value;""")
.ShouldContain(x => x.Message.Contains("literal"));
.ShouldContain(x => x.Code == "OTSCRIPT_DYNPATH" && x.Severity == 4 && x.Message.Contains("literal"));
// lmxopcua#1063: this used to assert the OPPOSITE ("does not produce a phantom preamble marker"). CS0161 is not a
// phantom: Roslyn pins it on the wrapper's Run, and the runtime compile / deploy gate refuse the script. It is now
@@ -13,9 +13,10 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis;
/// forever. Both sides now share <see cref="ScriptCompileRules"/> and <see cref="EquipTokenLiteralScanner"/>.
/// </summary>
/// <remarks>
/// Excluded on purpose: a DYNAMIC tag path (<c>ctx.GetTag(variable)</c>) in a value or Calculation script. The editor
/// marks it an error in every mode while the gate refuses it only for a scripted-alarm predicate — a known,
/// editor-stricter divergence tracked separately (it is not a compile rule, and either fix changes behaviour).
/// A DYNAMIC tag path (<c>ctx.GetTag(variable)</c>, <c>OTSCRIPT_DYNPATH</c>) is in the corpus since lmxopcua#1083: the
/// editor used to mark it an error in every mode while the gate refuses it only for a scripted-alarm predicate. The
/// split is now <see cref="ScriptCompileRules.TagPathFindings"/>'s — an error where the gate refuses, a warning
/// elsewhere — so it gets the same verdict per mode.
/// </remarks>
public sealed class EditorGateParityTests
{
@@ -57,6 +58,15 @@ public sealed class EditorGateParityTests
"""return ctx.GetTag("Plant/{{equip}}/Speed").Value;""",
"""ctx.SetVirtualTag("{{equip}}/Out", 1); return 1;""",
"""ctx.Logger.Information("{{equip}} is only a log string"); return 1;""",
// Dynamic / empty tag paths (#1083): refused for a predicate only. Bool-returning forms too, so the predicate's
// refusal is the path's, not a non-bool return.
"""var p = "A"; return ctx.GetTag(p).Value;""",
"""var p = "A"; return ctx.GetTag(p).Value is null;""",
"""return ctx.GetTag("A" + "B").Value is null;""",
"""return ctx.GetTag($"A{1}").Value is null;""",
"""return ctx.GetTag("").Value is null;""",
"""var p = "Out"; ctx.SetVirtualTag(p, 1); return true;""",
"""var p = "A"; return ctx.GetTag(p).Value is null && ctx.GetTag("A").Value is null;""",
];
string[] modes = [ScriptAnalysisModes.Value, ScriptAnalysisModes.Calculation, ScriptAnalysisModes.AlarmPredicate];
var data = new TheoryData<string, string>();
@@ -103,6 +113,27 @@ public sealed class EditorGateParityTests
Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, source)], ct)[0].Passed.ShouldBeTrue();
}
/// <summary>
/// lmxopcua#1083: a dynamic tag path is an editor ERROR exactly where the gate refuses it (a predicate) and a
/// WARNING where the gate accepts it (value, Calculation) — and the warning still shows, so the author learns the
/// path is not a declared input. Positive control for the corpus rows: the predicate really is refused by both.
/// </summary>
[Theory]
[InlineData(ScriptAnalysisModes.Value, 4, true)]
[InlineData(ScriptAnalysisModes.Calculation, 4, true)]
[InlineData(ScriptAnalysisModes.AlarmPredicate, 8, false)]
public void A_dynamic_tag_path_is_an_error_only_where_the_gate_refuses_it(string mode, int severity, bool gatePasses)
{
const string source = """var p = "A"; return ctx.GetTag(p).Value is null;""";
var ct = TestContext.Current.CancellationToken;
var dynpath = Svc.Diagnose(new DiagnoseRequest(source, Mode: mode), ct).Markers.Single(m => m.Code == "OTSCRIPT_DYNPATH");
dynpath.Severity.ShouldBe(severity);
(dynpath.StartLineNumber, dynpath.StartColumn).ShouldBe((1, 32)); // on the `p` argument
if (severity == 4) dynpath.Message.ShouldContain("not a declared input");
Gate.Check([new DeployScriptCheckRequest(ScriptAnalysisModes.KindOf(mode), source)], ct)[0].Passed.ShouldBe(gatePasses);
ScriptCompileRules.RefusesNonLiteralTagPaths(ScriptAnalysisModes.KindOf(mode)).ShouldBe(!gatePasses);
}
[Fact]
public void The_editor_wraps_scripts_in_the_runtimes_own_wrapper_text()
{
@@ -73,6 +73,32 @@ public sealed class EquipTokenEditorTests
md.ShouldNotContain("Not a known");
}
/// <summary>
/// lmxopcua#1093: in Calculation mode the token is refused (OTSCRIPT_EQUIPCALC on the same span, #1065), so the
/// hover says so instead of the VirtualTag "resolves … when deployed" text that contradicted the marker. Also
/// answered without a catalog (the hover needs none for this literal). The value-mode hover above is the control.
/// </summary>
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Hover_on_equip_token_literal_in_calculation_mode_says_it_is_refused(bool withCatalog)
{
var svc = withCatalog ? Svc : new ScriptAnalysisService();
const string code = """return ctx.GetTag("{{equip}}/Speed").Value;""";
var md = (await svc.Hover(new HoverRequest(code, 1, 24, Mode: ScriptAnalysisModes.Calculation), TestContext.Current.CancellationToken)).Markdown;
md.ShouldNotBeNull();
md!.ShouldContain("refused in a Calculation script");
md.ShouldContain("no owning equipment");
md.ShouldContain("{{equip}}/Speed");
md.ShouldNotContain("resolves through the owning equipment");
// The marker on the same span agrees.
svc.Diagnose(new DiagnoseRequest(code, Mode: ScriptAnalysisModes.Calculation), TestContext.Current.CancellationToken)
.Markers.ShouldContain(m => m.Code == "OTSCRIPT_EQUIPCALC" && m.Severity == 8);
// Value mode on the same service keeps the VirtualTag explanation.
(await svc.Hover(new HoverRequest(code, 1, 24, Mode: ScriptAnalysisModes.Value), TestContext.Current.CancellationToken))
.Markdown.ShouldNotBeNull().ShouldContain("Equipment-relative");
}
[Fact] public async Task Diagnostic_flags_unresolved_equip_reference()
{
// "Missing" is not one of the equipment's references (Speed/Temp) → a diagnostic, matching the