fix(scripting): #1056 refuse a {{equip}} token in a verbatim/raw/interpolated path literal — editor diagnostic + deploy-gate refusal

This commit is contained in:
Joseph Doherty
2026-12-03 15:05:40 -05:00
parent 16c8b7ffad
commit e840ec1fbc
6 changed files with 211 additions and 2 deletions
+6 -2
View File
@@ -527,8 +527,12 @@ hold `\`, `"`, braces, line breaks or non-ASCII text (`RawPaths.ValidateSegment`
A `<RefName>` with a malformed escape (`\e`) is left as written for the compiler to report. Only
regular `"…"` literals are path literals: a `{{equip}}/…` token inside a verbatim (`@"…"`),
interpolated (`$"…"`) or raw (`"""…"""`) literal is **not substituted** (and not checked) — keep the
token in a regular literal.
interpolated (`$"…"`) or raw (`"""…"""`) literal is **not substituted**, so since #1056 it is refused
instead of silently reading Bad at runtime: the editor flags it (`OTSCRIPT_EQUIPLITERAL`, an error) and
the deploy gate fails the script (`equip token not substituted — …`), both through
`EquipTokenLiteralScanner`. Keep the token in a regular literal. (Only a `ctx.GetTag` /
`ctx.SetVirtualTag` path argument is scanned; a `{{equip}}` token in a Calculation script is not
substituted in any literal form — the seam does no substitution.)
---
@@ -0,0 +1,85 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// <summary>
/// Finds <c>ctx.GetTag(…)</c> / <c>ctx.SetVirtualTag(…)</c> calls whose path argument carries the
/// <c>{{equip}}</c> token in a literal form the substitution does NOT rewrite (lmxopcua#1056).
/// </summary>
/// <remarks>
/// <para>
/// <c>EquipmentScriptPaths.SubstituteEquipmentToken</c> rewrites the token only inside a REGULAR <c>"…"</c>
/// path literal. A verbatim (<c>@"…"</c>), raw (<c>"""…"""</c>) or interpolated (<c>$"…"</c>) literal used to pass
/// the editor and the deploy gate and then reach the runtime with the token still in the path — the tag read
/// Bad for as long as it was deployed, with no error anywhere. Both the editor
/// (<c>OTSCRIPT_EQUIPLITERAL</c>) and the deploy gate (<see cref="RoslynDeployScriptChecker"/>) now run this
/// one scan and refuse such a script, so "the editor accepts ⇔ publish accepts" holds.
/// </para>
/// <para>
/// Same receiver guard as <see cref="DependencyExtractor"/> (a member access on the identifier <c>ctx</c>), so
/// comments, other receivers and a token in a string that is not a path argument are never flagged.
/// </para>
/// </remarks>
public static class EquipTokenLiteralScanner
{
private const string EquipToken = "{{equip}}";
/// <summary>One offending path literal.</summary>
/// <param name="Span">The offending literal's span in the scanned source.</param>
/// <param name="Message">The operator-facing explanation.</param>
public sealed record Finding(TextSpan Span, string Message);
/// <summary>The offending path literals of <paramref name="source"/>, in source order.</summary>
/// <param name="source">The script source (any <c>{{equip}}</c> token still unresolved is fine).</param>
/// <returns>The findings; empty when none.</returns>
public static IReadOnlyList<Finding> Find(string? source)
{
if (string.IsNullOrEmpty(source) || !source.Contains(EquipToken, StringComparison.Ordinal))
return [];
var tree = CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(kind: SourceCodeKind.Script));
var findings = new List<Finding>();
foreach (var inv in tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>())
{
if (inv.Expression is not MemberAccessExpressionSyntax
{
Expression: IdentifierNameSyntax { Identifier.ValueText: "ctx" },
Name.Identifier.ValueText: "GetTag" or "SetVirtualTag",
} member)
continue;
if (inv.ArgumentList.Arguments.Count == 0) continue;
var path = inv.ArgumentList.Arguments[0].Expression;
var form = OffendingForm(path);
if (form is null) continue;
findings.Add(new Finding(
path.Span,
$"The {EquipToken} token is inside a {form} string literal in ctx.{member.Name.Identifier.ValueText}(...), " +
"where it is NOT substituted — the path would reach the runtime unresolved and read Bad. " +
$"Use a regular \"…\" literal: ctx.{member.Name.Identifier.ValueText}(\"{EquipToken}/<RefName>\")."));
}
return findings;
}
private static string? OffendingForm(ExpressionSyntax path)
{
switch (path)
{
case LiteralExpressionSyntax lit when lit.IsKind(SyntaxKind.StringLiteralExpression):
{
var text = lit.Token.Text;
var form = text.StartsWith("@\"", StringComparison.Ordinal) ? "verbatim"
: text.StartsWith("\"\"\"", StringComparison.Ordinal) ? "raw"
: null;
return form is not null && ((string?)lit.Token.Value ?? "").StartsWith(EquipToken, StringComparison.Ordinal)
? form : null;
}
case InterpolatedStringExpressionSyntax interpolated
when interpolated.ToString().Contains(EquipToken, StringComparison.Ordinal):
return "interpolated";
default:
return null;
}
}
}
@@ -112,6 +112,13 @@ public sealed class RoslynDeployScriptChecker : IDeployScriptChecker
var source = request.Source ?? string.Empty;
try
{
// lmxopcua#1056: a {{equip}} token in a verbatim/raw/interpolated path literal is never substituted, so the
// script would compile and then read a tag path that cannot resolve. The editor runs the same scan.
var unsubstituted = EquipTokenLiteralScanner.Find(source);
if (unsubstituted.Count > 0)
return new CachedVerdict(
["equip token not substituted — " + string.Join("; ", unsubstituted.Select(f => f.Message))],
Cacheable: true);
if (request.Kind == ScriptContextKind.AlarmPredicate)
{
var extraction = DependencyExtractor.Extract(source);
@@ -162,6 +162,10 @@ public sealed class ScriptAnalysisService
// (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"));
// (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))
@@ -0,0 +1,80 @@
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;
/// <summary>
/// lmxopcua#1056 — <c>{{equip}}/&lt;RefName&gt;</c> is only substituted inside a REGULAR <c>"…"</c> path literal. In a
/// verbatim (<c>@"…"</c>), raw (<c>"""…"""</c>) or interpolated (<c>$"…"</c>) literal the token used to be
/// silently left in the path, so the tag read Bad at runtime while the editor and the deploy gate were green. The
/// scanner finds those forms; the editor (<c>OTSCRIPT_EQUIPLITERAL</c>) and the deploy gate both refuse them.
/// </summary>
[Trait("Category", "Unit")]
public sealed class EquipTokenLiteralScannerTests
{
[Theory]
[InlineData("return ctx.GetTag(@\"{{equip}}/speed\").Value;")]
[InlineData("return ctx.GetTag(\"\"\"{{equip}}/speed\"\"\").Value;")]
[InlineData("return ctx.GetTag($\"{{equip}}/speed\").Value;")]
[InlineData("return ctx.GetTag($@\"{{equip}}/speed\").Value;")]
[InlineData("ctx.SetVirtualTag(@\"{{equip}}/speed\", 1); return 0;")]
public void A_token_inside_a_non_regular_path_literal_is_found(string source)
{
var findings = EquipTokenLiteralScanner.Find(source);
findings.ShouldHaveSingleItem();
findings[0].Message.ShouldContain("regular");
source.Substring(findings[0].Span.Start, findings[0].Span.Length).ShouldContain("{{equip}}");
}
[Theory]
[InlineData("return ctx.GetTag(\"{{equip}}/speed\").Value;")] // the supported form
[InlineData("return ctx.GetTag(@\"Plant/Drv/speed\").Value;")] // verbatim without the token
[InlineData("return ctx.GetTag(\"A\").Value; // @\"{{equip}}/speed\"")] // a comment
[InlineData("var s = @\"{{equip}}/speed\"; return ctx.GetTag(\"A\").Value;")] // not a path argument
[InlineData("return other.GetTag(@\"{{equip}}/speed\");")] // not ctx
[InlineData("return ctx.GetTag($\"Plant/{1}\").Value;")] // interpolated, no token
[InlineData("return 1;")]
public void Everything_else_is_not_flagged_positive_controls(string source)
=> EquipTokenLiteralScanner.Find(source).ShouldBeEmpty();
[Fact]
public void Every_offending_call_is_reported_in_source_order()
{
var findings = EquipTokenLiteralScanner.Find(
"var a = ctx.GetTag(@\"{{equip}}/a\"); var b = ctx.GetTag(\"{{equip}}/ok\"); var c = ctx.GetTag($\"{{equip}}/c\"); return 0;");
findings.Count.ShouldBe(2);
findings[0].Span.Start.ShouldBeLessThan(findings[1].Span.Start);
}
[Fact]
public void The_regular_literal_form_really_is_the_one_substitution_handles()
{
// Pins the premise: the same source with a regular literal substitutes, the verbatim one does not.
var map = new Dictionary<string, string> { ["speed"] = "Plant/Drv/dev/speed" };
ZB.MOM.WW.OtOpcUa.Commons.Types.EquipmentScriptPaths
.SubstituteEquipmentToken("return ctx.GetTag(\"{{equip}}/speed\").Value;", map)
.ShouldContain("Plant/Drv/dev/speed");
ZB.MOM.WW.OtOpcUa.Commons.Types.EquipmentScriptPaths
.SubstituteEquipmentToken("return ctx.GetTag(@\"{{equip}}/speed\").Value;", map)
.ShouldContain("{{equip}}/speed");
}
[Theory]
[InlineData(ScriptContextKind.VirtualTag)]
[InlineData(ScriptContextKind.AlarmPredicate)]
public void The_deploy_gate_refuses_such_a_script(ScriptContextKind kind)
{
var source = kind == ScriptContextKind.AlarmPredicate
? "return ctx.GetTag(@\"{{equip}}/speed\").Value is not null;"
: "return ctx.GetTag(@\"{{equip}}/speed\").Value;";
var result = new RoslynDeployScriptChecker().Check(
[new DeployScriptCheckRequest(kind, source)], TestContext.Current.CancellationToken).Single();
result.Passed.ShouldBeFalse();
result.Problems.ShouldContain(p => p.Contains("{{equip}}") && p.Contains("regular"));
// positive control: the supported spelling of the same script passes
var ok = new RoslynDeployScriptChecker().Check(
[new DeployScriptCheckRequest(kind, source.Replace("@\"", "\""))], TestContext.Current.CancellationToken).Single();
ok.Passed.ShouldBeTrue(string.Join("; ", ok.Problems));
}
}
@@ -0,0 +1,29 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis;
/// <summary>lmxopcua#1056 — the editor refuses a <c>{{equip}}</c> token in a verbatim/raw/interpolated path literal, as the deploy gate does.</summary>
public sealed class EquipLiteralDiagnosticTests
{
private static readonly ScriptAnalysisService Svc = new();
[Theory]
[InlineData("return ctx.GetTag(@\"{{equip}}/speed\").Value;", null)]
[InlineData("return ctx.GetTag(\"\"\"{{equip}}/speed\"\"\").Value;", null)]
[InlineData("return ctx.GetTag(@\"{{equip}}/speed\").Value is not null;", ScriptAnalysisModes.AlarmPredicate)]
public void A_token_in_a_non_regular_literal_is_an_error_marker_on_its_line(string code, string? mode)
{
var m = Svc.Diagnose(new DiagnoseRequest("var a = 1;\n" + code, Mode: mode), TestContext.Current.CancellationToken).Markers
.Single(x => x.Code == "OTSCRIPT_EQUIPLITERAL");
m.Severity.ShouldBe(8);
m.StartLineNumber.ShouldBe(2);
m.Message.ShouldContain("regular");
}
[Fact]
public void The_regular_literal_form_is_not_flagged_positive_control()
=> Svc.Diagnose(new DiagnoseRequest("return ctx.GetTag(\"{{equip}}/speed\").Value;"), TestContext.Current.CancellationToken).Markers
.ShouldNotContain(x => x.Code == "OTSCRIPT_EQUIPLITERAL");
}