From 73f49eaf32d4bf7b88627493de8178edeed87649 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 16:47:14 -0500 Subject: [PATCH] =?UTF-8?q?fix(scripting):=20#1063=20one=20compile-refusal?= =?UTF-8?q?=20authority=20for=20editor=20and=20deploy=20gate=20(ScriptComp?= =?UTF-8?q?ileRules=20+=20the=20runtime's=20own=20wrapper=20text)=20?= =?UTF-8?q?=E2=80=94=20CS0161=20and=20wrapper=20injection=20are=20now=20fl?= =?UTF-8?q?agged=20in=20the=20editor;=20#1065=20{{equip}}=20in=20a=20Calcu?= =?UTF-8?q?lation=20script=20is=20refused=20by=20the=20gate=20and=20by=20a?= =?UTF-8?q?=20new=20Calculation=20editor=20mode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #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). --- docs/ScriptEditor.md | 69 ++++++---- docs/VirtualTags.md | 3 +- docs/drivers/Calculation.md | 5 + .../EquipTokenLiteralScanner.cs | 47 +++++++ .../RoslynDeployScriptChecker.cs | 26 ++-- .../ScriptCompileRules.cs | 105 +++++++++++++++ .../ScriptEvaluator.cs | 124 +++++------------- .../Components/Pages/ScriptEdit.razor | 8 +- .../CalculationTagConfigEditor.razor | 5 +- .../ScriptAnalysis/ScriptAnalysisContracts.cs | 31 ++++- .../ScriptAnalysis/ScriptAnalysisService.cs | 115 ++++++++++------ .../Uns/ScriptUsage.cs | 32 ++--- .../AdminOperations/DeployScriptGate.cs | 3 +- .../RoslynDeployScriptCheckerTests.cs | 53 ++++++++ .../ScriptAnalysis/DiagnoseTests.cs | 39 +++++- .../ScriptAnalysis/EditorGateParityTests.cs | 116 ++++++++++++++++ .../ScriptUsageClassifyTests.cs | 29 ++++ ...inOperationsActorScriptCompileGateTests.cs | 20 +++ 18 files changed, 644 insertions(+), 186 deletions(-) create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptCompileRules.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EditorGateParityTests.cs diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index 0b700d0a4..727c62250 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -100,11 +100,14 @@ debounced (~500 ms) to avoid firing on every keystroke. The analysis seam is the private `Analyze(userSource)` method, which: 1. Builds the wrapped document — the user's source is appended after the - OtOpcUa evaluator preamble (usings from `ScriptSandbox.Build`, the + runtime's own wrapper text, `ScriptEvaluator.WrapperPreamble` + (usings from `ScriptSandbox.Build`, the `CompiledScript.Run(ScriptGlobals)` wrapper, `var ctx = globals.ctx;`, then `#line 1` so Roslyn reports user-source coordinates for - diagnostics). Return type is `object` so one shared script is valid regardless - of any virtual tag's `DataType`. + diagnostics), and closed with `WrapperSuffix`. Since #1063 the editor holds no + copy of the wrapper: it is the exact text the runtime compile and the deploy + gate parse. Return type is `object` so one shared script is valid regardless + of any virtual tag's `DataType` (`bool` in predicate mode). 2. Parses the wrapped document as a `CSharpSyntaxTree` and creates a `CSharpCompilation` against the `ScriptSandbox` reference set. 3. Returns the `SemanticModel`, `SyntaxTree`, and the preamble byte offset (used @@ -145,19 +148,27 @@ The diagnostics endpoint combines three sources and returns **errors only**: ### 1. Roslyn compile diagnostics -`compilation.GetDiagnostics()` filtered to `DiagnosticSeverity.Error`. Warnings -are intentionally excluded: the canonical passthrough pattern +What refuses a script is decided in ONE place, `ScriptCompileRules` +(`Core.Scripting`), which the runtime compile (`ScriptEvaluator`, and so the +deploy gate's `RoslynDeployScriptChecker`) and the editor both call (#1063): +`CompileErrors` — every `DiagnosticSeverity.Error` diagnostic, wherever Roslyn +locates it — and `WrapperInjection` (`LMX001`/`LMX002`, Core.Scripting-013). +`SkipsCompile` is the shared shortcut: a blank or passthrough value script never +reaches the compiler at runtime, so the editor does not compile it either. +Warnings are intentionally excluded: the canonical passthrough pattern `return ctx.GetTag("X").Value;` triggers nullable warning CS8605 under `NullableContextOptions.Enable` but compiles and publishes fine — flagging it in the editor would be misleading noise that does not reflect publish reality. Line numbers are read from `GetMappedLineSpan()` (not `GetLineSpan()`). `GetMappedLineSpan` honours the `#line 1` directive in the preamble, so it -returns user-source coordinates directly. Diagnostics whose -`SourceSpan.Start < preambleLength` are dropped — they are phantom wrapper -diagnostics (e.g. `CS0161` "not all code paths return a value" on the synthesized -`Run` method body when the user has not yet typed `return`) and are not the -user's fault. +returns user-source coordinates directly. A refusal located in the wrapper +rather than the user's text — notably `CS0161` "not all code paths return a +value", which Roslyn pins on the synthesized `Run` — is drawn on the script's +**last line** with a plain-language message. Until #1063 such diagnostics were +dropped as "phantom", so a script with a path that falls off the end was clean in +the editor and refused at deploy. `EditorGateParityTests` now runs one corpus +through the editor and the gate in all three modes and requires the same verdict. ### 2. ForbiddenTypeAnalyzer @@ -192,15 +203,19 @@ editor showed can no longer be deployed silently. Two differences from the edito to know: the gate compiles each script **as the seam that uses it** (a predicate must return `bool`), and it only checks scripts something enabled uses. The editor matches the gate's seam since #1025: the analysis endpoints take an optional `mode` -(`value` default | `alarmPredicate`), the editor wraps the source as +(`value` default | `calculation` | `alarmPredicate`), the editor wraps the source as `bool Run(ScriptGlobals)` in predicate mode, and the ScriptEdit -page has an **Analyse as** selector that defaults to *predicate* when scripted alarms -are the script's only users (a script also used as a VirtualTag/Calculation defaults to -value; pick whichever seam you are authoring for). The per-equipment VirtualTag and -Calculation editors are always value mode. Known remaining gap: a body that lacks a -`return` on some path (CS0161) is not flagged while you type (a deliberate -no-phantom-marker rule) but is refused at deploy. See `docs/VirtualTags.md` -§"Deploy-time script compile gate" for modes, caching and the upgrade note. +page has an **Analyse as** selector. It defaults to *Calculation* when any Calculation +tag runs the script (#1065 — Calculation mode is the value shape plus the refusal of +`{{equip}}`, so it shows every refusal a value use can meet), to *predicate* when +scripted alarms are the script's only users, and to *value* otherwise; pick whichever +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 +modes, caching and the upgrade note. ### Runtime safety (what happens after publish) @@ -300,8 +315,10 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: `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 -same check publish enforces — the editor shows the squiggle where the literal -must appear. +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`. --- @@ -547,8 +564,16 @@ interpolated (`$"…"`) or raw (`"""…"""`) literal is **not substituted**, so 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.) +`ctx.SetVirtualTag` path argument is scanned.) + +**Calculation scripts may not use `{{equip}}` at all (#1065).** A Calculation tag is a raw, +device-level tag in `/raw` — it belongs to no equipment, and the Calculation seam does no +substitution — so the token in any path literal (regular, verbatim, raw or interpolated, anywhere in +the path) is refused: the deploy gate fails the Calculation use (`equip token in a Calculation script +— …`, the passthrough shape included) and the editor flags it in Calculation mode +(`OTSCRIPT_EQUIPCALC`), both through `EquipTokenLiteralScanner.FindInCalculation`. Use the literal +RawPath, or move an equipment-relative computation to a VirtualTag. A script shared by a VirtualTag +and a Calculation tag is held to the rule for its Calculation use only. --- diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index a084b1df9..4f363c940 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -58,7 +58,8 @@ The deploy gate compiles every script the deployment will run before the deploym - **What is checked** is what runs: **enabled** VirtualTags (as `VirtualTagContext → object?`), **enabled** scripted-alarm predicates (`DependencyExtractor` first, as the alarm load does, then `AlarmPredicateContext → bool`), and Calculation tags of **enabled** Calculation drivers (`VirtualTagContext → object?`). Disabled ones are skipped (they never compile at runtime); a passthrough mirror VirtualTag/Calculation body is skipped (the runtime never compiles it); orphan scripts are not checked. The same source can fail as one seam and pass as another — `return 1.5;` is a fine VirtualTag and a refused predicate. - **`{{equip}}` is resolved first**, through the same `EquipmentReferenceMap` + RawPath resolver both compose seams use. When `EquipmentScriptPaths.SubstitutionPreservesCompilation` proves the substitution cannot change a compile, the template is compiled once for every equipment instead of once per equipment; otherwise the resolved source is compiled. Substitution escapes what it pastes (`EscapeForRegularLiteral`: a RawPath segment may contain `\` or `"`), so a device named `de\qv` compiles and `GetTag` receives the exact RawPath; the check is a verified round trip, and the resolved-source fallback remains for any case it cannot prove. -- **Same compile as the runtime.** `ScriptEvaluator.Verify` and `CompileToImage` share one private factory (wrap, injection guard, sandbox compile, `ForbiddenTypeAnalyzer`); `Verify` stops before the stack-guard rewrite and the emit. Problems carry the runtime's own text (`compile error: …`, `sandbox violation: …`, `dependency extraction rejected — …`). +- **Same compile as the runtime.** `ScriptEvaluator.Verify` and `CompileToImage` share one private factory (wrap, injection guard, sandbox compile, `ForbiddenTypeAnalyzer`); `Verify` stops before the stack-guard rewrite and the emit. Problems carry the runtime's own text (`compile error: …`, `sandbox violation: …`, `dependency extraction rejected — …`). **The editor applies the same rule (lmxopcua#1063):** which diagnostics refuse a script (every Error-severity one, wherever Roslyn pins it, plus the wrapper-injection guard) and which sources skip the compile (blank / passthrough value scripts) live in `ScriptCompileRules`, and the wrapper text is `ScriptEvaluator.WrapperPreamble`/`WrapperSuffix` — both read by the runtime compile and by the Monaco diagnostics. The editor used to drop wrapper-located errors, so a script missing a `return` on some path (CS0161) passed the editor and failed this gate. +- **No `{{equip}}` in a Calculation script (lmxopcua#1065).** A Calculation tag is raw/device-level — no equipment — and its seam never substitutes the token, so a Calculation use whose script carries `{{equip}}` in any `ctx.GetTag`/`ctx.SetVirtualTag` path literal is refused (`equip token in a Calculation script — …`), passthrough shape included; it used to deploy and read `{{equip}}/…` literally, Bad for as long as it ran. A source scan (`EquipTokenLiteralScanner.FindInCalculation`), so it is kind-specific and kept out of the shared VirtualTag/Calculation compile cache; the editor runs the same scan in Calculation mode. **Upgrade note:** a deployment that carries such a Calculation script is now rejected under `Error` mode — those tags were already Bad, so no working behaviour is lost; replace the token with the literal RawPath. - **Shape.** ControlPlane (which owns the gate) is Roslyn-free: it depends on `IDeployScriptChecker` (`Core.Scripting.Abstractions`); the Host binds `RoslynDeployScriptChecker` on admin nodes. No checker registered ⇒ the gate is skipped. Verdicts are cached by (compile identity, source SHA-256) for the life of the process (VirtualTag and Calculation share an identity), and distinct uncached sources compile in parallel (half the cores, 1–8). The compose warms that cache from the `Script`/`VirtualTag`/`ScriptedAlarm` tables **before** opening its snapshot transaction and compose lock, then runs the authoritative check on the same snapshot it validates and composes (R03:3.2) — normally all cache hits. An internal checker failure skips the gate for that deploy (logged, noted in the accepted message), never blocks it. | `Deployment:ScriptCompileGateMode` | Behaviour | diff --git a/docs/drivers/Calculation.md b/docs/drivers/Calculation.md index 0cc9c16e3..e751433b4 100644 --- a/docs/drivers/Calculation.md +++ b/docs/drivers/Calculation.md @@ -31,6 +31,11 @@ They are close cousins and easy to confuse: If the same script should apply to many machines, you want a virtual tag with `{{equip}}`. If a single derived signal belongs next to the device tags it is derived from, you want a calc tag. +A Calculation script may **not** use `{{equip}}` (#1065): a Calculation tag has no equipment, so the +token has nothing to resolve to and the Calculation seam never substitutes it. The deploy gate refuses +it (`ScriptCompileFailed` … `equip token in a Calculation script`) and the Calculation tag editor flags +it as you type (`OTSCRIPT_EQUIPCALC`). Read sources by their literal RawPath. + ## Authoring a calc tag Calc tags are authored in `/raw` like any other tag: create a `Calculation` driver, add a device under diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/EquipTokenLiteralScanner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/EquipTokenLiteralScanner.cs index 208eb3703..8b21660e6 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/EquipTokenLiteralScanner.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/EquipTokenLiteralScanner.cs @@ -62,6 +62,53 @@ public static class EquipTokenLiteralScanner return findings; } + /// + /// lmxopcua#1065: the {{equip}} token in ANY path literal of a Calculation script. A Calculation tag is + /// a raw, device-level tag — it belongs to no equipment, so there is nothing for the token to resolve to, and the + /// Calculation seam (unlike the VirtualTag / scripted-alarm compose seams) never substitutes it. Such a script used + /// to deploy clean and read {{equip}}/… literally — Bad for as long as it ran. Both the deploy gate + /// (, for every Calculation use) and the editor (OTSCRIPT_EQUIPCALC, in + /// Calculation mode) run this one scan and refuse it. Same ctx receiver guard as ; every + /// literal form (regular, verbatim, raw, interpolated) counts, and the token anywhere in the path, not only as its + /// prefix. + /// + /// The Calculation script source. + /// The offending path literals, in source order; empty when none. + public static IReadOnlyList FindInCalculation(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(); + foreach (var inv in tree.GetRoot().DescendantNodes().OfType()) + { + 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 carriesToken = path switch + { + LiteralExpressionSyntax lit when lit.IsKind(SyntaxKind.StringLiteralExpression) + => ((string?)lit.Token.Value ?? "").Contains(EquipToken, StringComparison.Ordinal), + InterpolatedStringExpressionSyntax interpolated + => interpolated.ToString().Contains(EquipToken, StringComparison.Ordinal), + _ => false, + }; + if (!carriesToken) continue; + findings.Add(new Finding( + path.Span, + $"The {EquipToken} token cannot be used in a Calculation script (ctx.{member.Name.Identifier.ValueText}(...)): " + + "a Calculation tag is a raw, device-level tag with no equipment, so the token is never substituted and the " + + "path would read Bad. Use the literal RawPath (ctx.GetTag(\"\")), or move an equipment-relative " + + "computation to a VirtualTag on the equipment.")); + } + return findings; + } + private static string? OffendingForm(ExpressionSyntax path) { switch (path) diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs index 0a7fa361f..c0c4c1a56 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs @@ -18,7 +18,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// AlarmPredicateContext → bool. No passthrough shortcut: the alarm engine always compiles. /// /// builds its compilation through the same private factory -/// uses, so the gate and the runtime cannot drift. +/// uses, so the gate and the runtime cannot drift; +/// which diagnostics refuse and which sources skip the compile are , which the Monaco +/// editor reads too (lmxopcua#1063). One rule is kind-specific and runs before everything else: a +/// Calculation script may not carry {{equip}} in a path literal +/// (, lmxopcua#1065) — the passthrough shortcut included, and +/// outside the cache, because VirtualTag and Calculation otherwise share one cached verdict. /// /// /// @@ -55,11 +60,21 @@ public sealed class RoslynDeployScriptChecker : IDeployScriptChecker { ArgumentNullException.ThrowIfNull(requests); var keys = new string?[requests.Count]; + var direct = new IReadOnlyList?[requests.Count]; var pending = new Dictionary(StringComparer.Ordinal); for (var i = 0; i < requests.Count; i++) { var request = requests[i] ?? throw new ArgumentException("A request is null.", nameof(requests)); - if (SkipsCompile(request)) continue; + // lmxopcua#1065: a Calculation script may not carry {{equip}} at all. A source scan, kind-specific, so it runs + // before the passthrough shortcut (`return ctx.GetTag("{{equip}}/X").Value;` never reaches Roslyn) and outside + // the compile cache (VirtualTag and Calculation share one cached compile verdict; this rule is not shared). + if (request.Kind == ScriptContextKind.Calculation + && EquipTokenLiteralScanner.FindInCalculation(request.Source) is { Count: > 0 } calcFindings) + { + direct[i] = ["equip token in a Calculation script — " + string.Join("; ", calcFindings.Select(f => f.Message))]; + continue; + } + if (ScriptCompileRules.SkipsCompile(request.Kind, request.Source)) continue; var key = CacheKey(request); keys[i] = key; if (!_cache.ContainsKey(key)) pending.TryAdd(key, request); @@ -79,7 +94,7 @@ public sealed class RoslynDeployScriptChecker : IDeployScriptChecker { cancellationToken.ThrowIfCancellationRequested(); results[i] = new DeployScriptCheckResult( - requests[i], keys[i] is { } key ? Resolve(key, requests[i]).Problems : []); + requests[i], direct[i] ?? (keys[i] is { } key ? Resolve(key, requests[i]).Problems : [])); } return results; } @@ -94,11 +109,6 @@ public sealed class RoslynDeployScriptChecker : IDeployScriptChecker return verdict; } - /// True when the runtime seam answers the source without compiling it. - private static bool SkipsCompile(DeployScriptCheckRequest request) => - request.Kind is ScriptContextKind.VirtualTag or ScriptContextKind.Calculation - && (string.IsNullOrWhiteSpace(request.Source) || PassthroughScript.TryMatch(request.Source, out _)); - private static string CacheKey(DeployScriptCheckRequest request) { var identity = request.Kind == ScriptContextKind.AlarmPredicate ? "alarm" : "value"; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptCompileRules.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptCompileRules.cs new file mode 100644 index 000000000..5060d56b9 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptCompileRules.cs @@ -0,0 +1,105 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using ZB.MOM.WW.OtOpcUa.Core.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; + +/// +/// The one statement of "does the runtime compile refuse this script" (lmxopcua#1063), shared by the runtime +/// compile (, which the deploy gate's +/// runs through Verify) and the Monaco editor's diagnostics. +/// +/// +/// +/// The editor used to decide for itself which Roslyn diagnostics block a publish, and it dropped every one located +/// in the synthesized wrapper — calling them "phantom". They are not: CS0161 "not all code paths return a value" +/// is pinned by Roslyn on the wrapper's Run identifier, and the runtime compile refuses it. A script with a +/// path that falls off the end passed the editor clean and failed the deploy gate. Both sides now ask this class, +/// over the same wrapper text (), and the editor +/// only decides WHERE to draw a wrapper-located refusal, never WHETHER to. +/// +/// +/// The third refusal leg, , is already one shared analyzer and is called +/// directly by both sides. +/// +/// +public static class ScriptCompileRules +{ + /// + /// True when the runtime seam answers WITHOUT compiling it, so nothing the compiler would + /// say about it can refuse it: a blank value script, or a value script of the passthrough mirror shape + /// (). A scripted-alarm predicate always compiles. + /// + /// The seam the script runs as. + /// The source. + /// Whether the runtime skips the compile. + public static bool SkipsCompile(ScriptContextKind kind, string? source) => + kind is ScriptContextKind.VirtualTag or ScriptContextKind.Calculation + && (string.IsNullOrWhiteSpace(source) || PassthroughScript.TryMatch(source, out _)); + + /// + /// The compiler diagnostics that make the runtime refuse a wrapped script: every + /// diagnostic, wherever it is located (user source, wrapper, or none). + /// Warnings never refuse. + /// + /// The compilation of the wrapped source. + /// Cancellation. + /// The refusing diagnostics; empty when the compile accepts the source. + public static IReadOnlyList CompileErrors(Compilation compilation, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(compilation); + return compilation.GetDiagnostics(cancellationToken).Where(d => d.Severity == DiagnosticSeverity.Error).ToArray(); + } + + /// + /// Core.Scripting-013: the wrapper-injection refusal. The parsed wrapper must hold exactly one type — the + /// synthesized CompiledScript — and that class exactly one member, the Run method. A script body + /// like return 0; } public static int Evil() { return 0; closes Run early and declares a sibling; + /// the analyzer would still walk it, but it breaks the "method body" authoring contract. + /// + /// The parsed wrapper (preamble + user source + suffix). + /// The LMX001 / LMX002 diagnostic, or null when the shape is intact. + public static Diagnostic? WrapperInjection(SyntaxTree wrapperTree) + { + ArgumentNullException.ThrowIfNull(wrapperTree); + var root = wrapperTree.GetCompilationUnitRoot(); + + // The compilation unit must hold exactly one type declaration — our CompiledScript. Anything else means the user + // closed the synthesized namespace or class early and injected another type declaration. + var typeMembers = root.DescendantNodes().OfType().ToArray(); + if (typeMembers.Length != 1 || typeMembers[0].Identifier.ValueText != "CompiledScript") + return Diagnostic.Create( + new DiagnosticDescriptor( + id: "LMX001", + title: "Script wrapper injection", + messageFormat: "Script source must be a statement body. Declarations of " + + "additional types alongside the wrapper's CompiledScript class " + + "are not allowed; check for unbalanced braces or stray " + + "`class` / `namespace` keywords in the source. (Core.Scripting-013)", + category: "Sandbox", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true), + typeMembers.Length > 1 ? typeMembers[1].Identifier.GetLocation() : Location.None); + + // The CompiledScript class itself must contain exactly one member — the Run method. A second member means the + // user closed Run early and started a sibling. + var classMembers = ((ClassDeclarationSyntax)typeMembers[0]).Members; + if (classMembers.Count != 1 || classMembers[0] is not MethodDeclarationSyntax { Identifier.ValueText: "Run" }) + return Diagnostic.Create( + new DiagnosticDescriptor( + id: "LMX002", + title: "Script wrapper injection", + messageFormat: "Script source must be a statement body. Declarations of " + + "sibling members (methods, properties, nested types) alongside " + + "the wrapper's Run method are not allowed; check for unbalanced " + + "braces or a stray `}` followed by a `public`/`private`/`static` " + + "declaration in the source. (Core.Scripting-013)", + category: "Sandbox", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true), + classMembers.Count > 1 ? classMembers[1].GetLocation() : Location.None); + + return null; + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs index ab0639ed3..8012db087 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs @@ -133,7 +133,7 @@ public sealed class ScriptEvaluator : IDisposable // Step 1 — synthesize a wrapper class around the script body and parse it. The // wrapper's `Run` method is what we invoke at runtime; the user's source is // pasted in as its body so explicit `return` semantics apply. - var wrapperSource = BuildWrapperSource(scriptSource, sandbox.Imports); + var wrapperSource = WrapperPreamble + scriptSource + WrapperSuffix; syntaxTree = CSharpSyntaxTree.ParseText(wrapperSource); // Step 1a — defend against wrapper-source injection. @@ -145,7 +145,9 @@ public sealed class ScriptEvaluator : IDisposable // documented "method body" authoring contract and widens the analyzer's // surface. Reject by requiring that the parsed `CompiledScript` class // contains exactly one member declaration (the `Run` method). - EnforceSingleRunMember(syntaxTree); + // The rule lives in ScriptCompileRules so the Monaco editor applies the identical check (lmxopcua#1063). + if (ScriptCompileRules.WrapperInjection(syntaxTree) is { } injection) + throw new CompilationErrorException(new[] { injection }); // Step 2 — Roslyn compile against the sandbox allow-list. Anything not in the // references set is unresolved and produces a compiler error. @@ -164,11 +166,11 @@ public sealed class ScriptEvaluator : IDisposable references: sandbox.References, options: compileOptions); - var compileDiagnostics = compilation.GetDiagnostics(); - var compileErrors = compileDiagnostics - .Where(d => d.Severity == DiagnosticSeverity.Error) - .ToArray(); - if (compileErrors.Length > 0) + // Every Error-severity diagnostic, wherever Roslyn pins it — including the ones it reports on the wrapper + // (CS0161 "not all code paths return a value" sits on Run). ScriptCompileRules is the one statement of this + // rule; the editor's diagnostics use it too (lmxopcua#1063). + var compileErrors = ScriptCompileRules.CompileErrors(compilation); + if (compileErrors.Count > 0) throw new CompilationErrorException(compileErrors); // Step 3 — the sandbox gate: the allow-list analyzer (lmxopcua#971). The narrowed @@ -207,7 +209,7 @@ public sealed class ScriptEvaluator : IDisposable // Step 5 — resolve the wrapper's Run method and bind a typed delegate. The // wrapper source above puts the type in this exact namespace + class — keep the - // names in sync with BuildWrapperSource. + // names in sync with BuildWrapperPreamble. Func, TResult> func; try { @@ -304,97 +306,43 @@ public sealed class ScriptEvaluator : IDisposable } /// - /// Reject scripts whose source contains brace-balanced injections that would - /// declare sibling members alongside the synthesized CompiledScript.Run - /// method. The expected shape is a single CompiledScript class with - /// exactly one member — the Run method. Anything else (a sibling - /// method, nested class, additional class in the namespace, free-floating - /// top-level statement) means the user source closed the synthesized braces - /// early and injected its own declarations. + /// The text the runtime pastes BEFORE the user's script body: the sandbox's using directives (so scripts can + /// write Math.Abs), the CompiledScript class and the Run(ScriptGlobals<TContext>) + /// signature, var ctx = globals.ctx;, then #line 1 so Roslyn's mapped positions are user-source + /// coordinates. Public so the Monaco editor analyses the exact same wrapper (lmxopcua#1063) — never rebuild it + /// elsewhere. Built with \n line ends on every platform, so the text (and every offset into it) is stable. /// - private static void EnforceSingleRunMember(SyntaxTree syntaxTree) - { - var root = syntaxTree.GetCompilationUnitRoot(); + public static string WrapperPreamble => PreambleHolder.Value; - // The compilation unit must hold exactly one type declaration — our - // CompiledScript. Anything else means the user closed the synthesized - // namespace or class early and injected another type declaration. - var typeMembers = root.DescendantNodes() - .OfType() - .ToArray(); - if (typeMembers.Length != 1 || typeMembers[0].Identifier.ValueText != "CompiledScript") - { - throw new CompilationErrorException(new[] - { - Diagnostic.Create( - new DiagnosticDescriptor( - id: "LMX001", - title: "Script wrapper injection", - messageFormat: "Script source must be a statement body. Declarations of " + - "additional types alongside the wrapper's CompiledScript class " + - "are not allowed; check for unbalanced braces or stray " + - "`class` / `namespace` keywords in the source. (Core.Scripting-013)", - category: "Sandbox", - defaultSeverity: DiagnosticSeverity.Error, - isEnabledByDefault: true), - typeMembers.Length > 1 ? typeMembers[1].Identifier.GetLocation() : Location.None), - }); - } + /// The text the runtime appends AFTER the user's script body: closes Run and the class. + public const string WrapperSuffix = "\n }\n}\n"; - // The CompiledScript class itself must contain exactly one member — the Run - // method. A second member means the user closed Run early and started a sibling. - var classMembers = ((Microsoft.CodeAnalysis.CSharp.Syntax.ClassDeclarationSyntax)typeMembers[0]).Members; - if (classMembers.Count != 1 || - classMembers[0] is not Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax m || - m.Identifier.ValueText != "Run") - { - throw new CompilationErrorException(new[] - { - Diagnostic.Create( - new DiagnosticDescriptor( - id: "LMX002", - title: "Script wrapper injection", - messageFormat: "Script source must be a statement body. Declarations of " + - "sibling members (methods, properties, nested types) alongside " + - "the wrapper's Run method are not allowed; check for unbalanced " + - "braces or a stray `}` followed by a `public`/`private`/`static` " + - "declaration in the source. (Core.Scripting-013)", - category: "Sandbox", - defaultSeverity: DiagnosticSeverity.Error, - isEnabledByDefault: true), - classMembers.Count > 1 ? classMembers[1].GetLocation() : Location.None), - }); - } - } + private static readonly Lazy PreambleHolder = + new(() => BuildWrapperPreamble(ScriptSandbox.Build(typeof(TContext)).Imports), LazyThreadSafetyMode.ExecutionAndPublication); /// - /// Synthesize the source we hand to Roslyn. The user's script body is pasted - /// verbatim inside CompiledScript.Run; the using directives mirror - /// 's imports so scripts can write Math.Abs - /// instead of System.Math.Abs. + /// Synthesize the wrapper preamble. The user's script body is pasted verbatim after it, inside + /// CompiledScript.Run, so explicit return semantics apply. /// - private static string BuildWrapperSource(string userSource, IReadOnlyList imports) + private static string BuildWrapperPreamble(IReadOnlyList imports) { var sb = new StringBuilder(); foreach (var import in imports) - sb.Append("using ").Append(import).AppendLine(";"); - sb.AppendLine(); - sb.AppendLine("namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;"); - sb.AppendLine(); - sb.AppendLine("public static class CompiledScript"); - sb.AppendLine("{"); + sb.Append("using ").Append(import).Append(";\n"); + sb.Append('\n'); + sb.Append("namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;\n"); + sb.Append('\n'); + sb.Append("public static class CompiledScript\n"); + sb.Append("{\n"); sb.Append(" public static ").Append(ToCSharpTypeName(typeof(TResult))) .Append(" Run(").Append(ToCSharpTypeName(typeof(ScriptGlobals))) - .AppendLine(" globals)"); - sb.AppendLine(" {"); - sb.AppendLine(" var ctx = globals.ctx;"); - // User source ends with `return X;` per the authoring convention; we paste it - // verbatim. The leading newline keeps Roslyn diagnostics' line numbers usable - // by operators (errors point at the user's source line, not the wrapper). - sb.AppendLine("#line 1"); - sb.AppendLine(userSource); - sb.AppendLine(" }"); - sb.AppendLine("}"); + .Append(" globals)\n"); + sb.Append(" {\n"); + sb.Append(" var ctx = globals.ctx;\n"); + // The user source ends with `return X;` per the authoring convention and is pasted verbatim after this line. + // #line 1 keeps Roslyn diagnostics' mapped line numbers usable by operators (errors point at the user's source + // line, not the wrapper). + sb.Append("#line 1\n"); return sb.ToString(); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor index e1a19f1a0..a0cc48191 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor @@ -76,13 +76,15 @@ else

Source

@* #1025: the editor analyses the script as the seam that runs it — the deploy gate compiles a scripted-alarm - predicate as `bool Run(AlarmPredicateContext)`, a VirtualTag/Calculation script as a value script. + predicate as `bool Run(AlarmPredicateContext)`, a VirtualTag/Calculation script as a value script, and + refuses {{equip}} in a Calculation script (#1065), which is what Calculation mode adds. Defaults from the script's current users; the author can switch for a not-yet-used script. *@
@@ -140,7 +142,7 @@ else } private void ChangeMode(string? value, long generation) { - if (Current(generation)) _mode = ScriptAnalysisModes.IsPredicate(value) ? ScriptAnalysisModes.AlarmPredicate : ScriptAnalysisModes.Value; + if (Current(generation)) _mode = ScriptAnalysisModes.Normalize(value); } private void OnMarkersChanged(ScriptProblemReport report, long generation) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Uns/TagEditors/CalculationTagConfigEditor.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Uns/TagEditors/CalculationTagConfigEditor.razor index d287893ff..9fa43e842 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Uns/TagEditors/CalculationTagConfigEditor.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Uns/TagEditors/CalculationTagConfigEditor.razor @@ -75,7 +75,10 @@ Editing shared script "@_scriptName" — used by @_scriptUsageCount virtual tag(s). Changes affect every tag using it.
- + @* #1065: Calculation mode — a Calculation tag has no equipment, so {{equip}} is refused here exactly as the deploy + gate refuses it. *@ + @if (!string.IsNullOrWhiteSpace(_scriptError)) {
@_scriptError
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisContracts.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisContracts.cs index ccfc3d445..4548fdbdf 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisContracts.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisContracts.cs @@ -1,24 +1,49 @@ +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + namespace ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis; /// /// Which seam the editor analyses a script as (lmxopcua#1025). The deploy gate compiles each script as the seam that /// uses it, so the editor has to wrap the source the same way: a value script is /// object Run(ScriptGlobals<VirtualTagContext>) (VirtualTag and Calculation share it); a scripted-alarm -/// predicate is bool Run(ScriptGlobals<AlarmPredicateContext>). Carried as a string on the wire; null, -/// blank or anything unrecognised means . +/// predicate is bool Run(ScriptGlobals<AlarmPredicateContext>). A Calculation script compiles as a value +/// script but is held to one more gate rule — no {{equip}} token (lmxopcua#1065) — so it has its own mode. +/// Carried as a string on the wire; null, blank or anything unrecognised means . /// public static class ScriptAnalysisModes { - /// A VirtualTag / Calculation value script (the default). + /// A VirtualTag value script (the default). public const string Value = "value"; /// A scripted-alarm predicate: must return bool. public const string AlarmPredicate = "alarmPredicate"; + /// A Calculation-tag script: the value shape, plus the Calculation-only refusal of {{equip}}. + public const string Calculation = "calculation"; + /// True when selects the predicate shape. /// The wire value. /// Whether it names . public static bool IsPredicate(string? mode) => string.Equals(mode, AlarmPredicate, StringComparison.OrdinalIgnoreCase); + + /// True when selects the Calculation rules. + /// The wire value. + /// Whether it names . + public static bool IsCalculation(string? mode) => string.Equals(mode, Calculation, StringComparison.OrdinalIgnoreCase); + + /// The deploy-gate seam a mode analyses as — what the gate's checker is asked for the same script. + /// The wire value. + /// The seam. + public static ScriptContextKind KindOf(string? mode) => + IsPredicate(mode) ? ScriptContextKind.AlarmPredicate + : IsCalculation(mode) ? ScriptContextKind.Calculation + : ScriptContextKind.VirtualTag; + + /// The canonical wire value for (unrecognised means ). + /// The wire value. + /// One of the three constants. + public static string Normalize(string? mode) => + IsPredicate(mode) ? AlarmPredicate : IsCalculation(mode) ? Calculation : Value; } // EquipmentId (optional) carries the owning-equipment context the {{equip}}/ completion + diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs index 48e8e9b45..ff414262e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs @@ -51,19 +51,14 @@ public sealed class ScriptAnalysisService /// 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) - // 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"; - 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.WrapperPreamble / WrapperSuffix) — the + // usings, the Run(ScriptGlobals) 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.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.WrapperPreamble); + private static readonly Shape PredicateShape = + new(typeof(AlarmPredicateContext), ScriptEvaluator.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"); - /// Compiles the script and returns compile-error diagnostics plus sandbox-policy violations - /// (forbidden types, disallowed dynamic tag paths). - /// The diagnose request carrying the script source. + /// Returns the markers for what the deploy gate would refuse — the runtime compile's own refusals (one + /// shared authority, ), sandbox-policy violations, disallowed dynamic tag paths and + /// the {{equip}} literal rules — plus advisory warnings. + /// The diagnose request carrying the script source and the analysis mode. /// The request's cancellation token; a cancelled request throws . /// The list of diagnostic markers, empty when the script is clean or analysis fails. public DiagnoseResponse Diagnose(DiagnoseRequest req, CancellationToken ct = default) { - if (string.IsNullOrEmpty(req.Code)) return new DiagnoseResponse(Array.Empty()); + 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()); try { ct.ThrowIfCancellationRequested(); - var code = Normalize(req.Code); var (tree, compilation, _, preambleLength) = Analyze(code, req.Mode, ct); var markers = new List(); - // (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 } } + /// The message shown for CS0161, which Roslyn words in terms of the synthesized wrapper method. + 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); + } + /// Diagnostics plus the v3 equipment-relative {{equip}}/<RefName> resolution check. /// Runs the synchronous Roslyn/policy then, when an equipment context + catalog /// are present, appends a marker for each {{equip}}/<RefName> whose <RefName> is diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs index 423e7c2bb..12b6d9e16 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs @@ -24,15 +24,20 @@ public static class ScriptUsage /// Which seams use a script. /// An (any) VirtualTag or Calculation tag runs it as a value script. /// An (any) scripted alarm runs it as its predicate. - public readonly record struct SeamUsage(bool UsedAsValue, bool UsedAsPredicate) + /// An (any) Calculation tag runs it (implies ). + public readonly record struct SeamUsage(bool UsedAsValue, bool UsedAsPredicate, bool UsedAsCalculation = false) { /// - /// The editor analysis mode (ScriptAnalysisModes) a script should open in (lmxopcua#1025): the predicate - /// shape only when scripted alarms are its sole users — a script also run as a value script stays a value - /// script (the author can switch), and an unused script is a value script. + /// The editor analysis mode (ScriptAnalysisModes) a script should open in (lmxopcua#1025): Calculation mode + /// whenever a Calculation tag runs it (lmxopcua#1065 — the deploy gate refuses {{equip}} for that use, and + /// Calculation mode is the value shape plus exactly that rule, so it is the mode that shows every refusal a value + /// use can meet); the predicate shape only when scripted alarms are its sole users; otherwise — also run as a + /// virtual tag, or unused — a value script. The author can switch. /// public string DefaultMode => - UsedAsPredicate && !UsedAsValue ? ScriptAnalysis.ScriptAnalysisModes.AlarmPredicate : ScriptAnalysis.ScriptAnalysisModes.Value; + UsedAsCalculation ? ScriptAnalysis.ScriptAnalysisModes.Calculation + : UsedAsPredicate && !UsedAsValue ? ScriptAnalysis.ScriptAnalysisModes.AlarmPredicate + : ScriptAnalysis.ScriptAnalysisModes.Value; } /// Classifies which seams use (same rows, same Calculation parser as the delete check). @@ -45,16 +50,13 @@ public static class ScriptUsage ArgumentNullException.ThrowIfNull(db); ArgumentException.ThrowIfNullOrEmpty(scriptId); var predicate = await db.ScriptedAlarms.AsNoTracking().AnyAsync(a => a.PredicateScriptId == scriptId, ct); - var value = await db.VirtualTags.AsNoTracking().AnyAsync(v => v.ScriptId == scriptId, ct); - if (!value) - { - var calcCandidates = await db.Tags.AsNoTracking() - .Where(t => t.TagConfig.Contains(scriptId)) - .Select(t => t.TagConfig) - .ToListAsync(ct); - value = calcCandidates.Any(c => string.Equals(DraftValidator.ParseScriptId(c), scriptId, StringComparison.Ordinal)); - } - return new SeamUsage(value, predicate); + var virtualTag = await db.VirtualTags.AsNoTracking().AnyAsync(v => v.ScriptId == scriptId, ct); + var calcCandidates = await db.Tags.AsNoTracking() + .Where(t => t.TagConfig.Contains(scriptId)) + .Select(t => t.TagConfig) + .ToListAsync(ct); + var calculation = calcCandidates.Any(c => string.Equals(DraftValidator.ParseScriptId(c), scriptId, StringComparison.Ordinal)); + return new SeamUsage(virtualTag || calculation, predicate, calculation); } /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/DeployScriptGate.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/DeployScriptGate.cs index 543642694..b811ef264 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/DeployScriptGate.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/DeployScriptGate.cs @@ -21,7 +21,8 @@ namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; /// Enabled scripted alarms (a disabled plan is skipped by the alarm host) — predicate source, /// substituted the same way. /// Calculation tags of enabled Calculation drivers — the source verbatim (the artifact injects it -/// into the tag's TagConfig with no substitution). +/// into the tag's TagConfig with no substitution). A Calculation tag has no equipment, so the checker refuses a +/// {{equip}} token in it outright (lmxopcua#1065). /// /// /// When proves the substitution cannot diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/RoslynDeployScriptCheckerTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/RoslynDeployScriptCheckerTests.cs index 653f9a066..f761623f7 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/RoslynDeployScriptCheckerTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/RoslynDeployScriptCheckerTests.cs @@ -144,6 +144,8 @@ public sealed class RoslynDeployScriptCheckerTests [InlineData("return 0; } public static int Evil() { return 0;")] [InlineData("var t = typeof(string).Assembly; return t.FullName;")] [InlineData("return Environment.GetEnvironmentVariable(\"PATH\");")] + [InlineData("if (ctx.GetTag(\"A\").Value is null) return 1;")] // CS0161 on the wrapper (lmxopcua#1063) + [InlineData("var x = 1;")] public void The_gate_accepts_exactly_what_the_runtime_compile_accepts(string source) { var checker = new RoslynDeployScriptChecker(); @@ -160,4 +162,55 @@ public sealed class RoslynDeployScriptCheckerTests var predicateRuntime = DependencyExtractor.Extract(source).IsValid && RuntimeCompiles(source); CheckOne(checker, ScriptContextKind.AlarmPredicate, source).Passed.ShouldBe(predicateRuntime); } + + /// + /// lmxopcua#1065: a Calculation tag is raw/device-level — no equipment — and its seam never substitutes + /// {{equip}}, so a Calculation script carrying it in a path literal is refused (it used to deploy and read + /// Bad forever). Every literal form, the passthrough mirror shape included (which never reaches Roslyn). + /// + [Theory] + [InlineData("return ctx.GetTag(\"{{equip}}/Speed\").Value;")] // passthrough shape + [InlineData("return (double)ctx.GetTag(\"{{equip}}/Speed\").Value * 2;")] + [InlineData("return ctx.GetTag(@\"{{equip}}/Speed\").Value;")] + [InlineData("return ctx.GetTag($\"{{equip}}/Speed\").Value;")] + [InlineData("return ctx.GetTag(\"Plant/{{equip}}/Speed\").Value;")] + [InlineData("ctx.SetVirtualTag(\"{{equip}}/Out\", 1); return 1;")] + public void An_equip_token_in_a_calculation_script_is_refused(string source) + { + var verdict = CheckOne(new RoslynDeployScriptChecker(), ScriptContextKind.Calculation, source); + verdict.Passed.ShouldBeFalse(); + verdict.Problems.Single().ShouldStartWith("equip token in a Calculation script — "); + verdict.Problems.Single().ShouldContain("no equipment"); + } + + [Fact] + public void The_calculation_equip_rule_is_kind_specific_and_not_shared_through_the_cache() + { + // VirtualTag and Calculation share one cached compile verdict; the #1065 rule must not leak through it in + // either order. Positive control: the regular-literal template is the normal VirtualTag form. + const string source = "return (double)ctx.GetTag(\"{{equip}}/Speed\").Value * 2;"; + var vtFirst = new RoslynDeployScriptChecker(); + CheckOne(vtFirst, ScriptContextKind.VirtualTag, source).Passed.ShouldBeTrue(); + CheckOne(vtFirst, ScriptContextKind.Calculation, source).Passed.ShouldBeFalse(); + + var calcFirst = new RoslynDeployScriptChecker(); + CheckOne(calcFirst, ScriptContextKind.Calculation, source).Passed.ShouldBeFalse(); + CheckOne(calcFirst, ScriptContextKind.VirtualTag, source).Passed.ShouldBeTrue(); + + // One batch with both kinds answers each in request order. + var both = vtFirst.Check( + [new DeployScriptCheckRequest(ScriptContextKind.Calculation, source), new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, source)], + TestContext.Current.CancellationToken); + both[0].Passed.ShouldBeFalse(); + both[1].Passed.ShouldBeTrue(); + } + + [Fact] + public void A_calculation_script_without_the_token_is_unaffected_positive_control() + { + var checker = new RoslynDeployScriptChecker(); + CheckOne(checker, ScriptContextKind.Calculation, "return ctx.GetTag(\"Plant/Dev/Speed\").Value;").Passed.ShouldBeTrue(); + // The token in a non-path string (a log message) is not a path and is not refused. + CheckOne(checker, ScriptContextKind.Calculation, "ctx.Logger.Information(\"{{equip}} n/a\"); return 1;").Passed.ShouldBeTrue(); + } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/DiagnoseTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/DiagnoseTests.cs index 5255dcd70..cfa43f049 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/DiagnoseTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/DiagnoseTests.cs @@ -105,8 +105,43 @@ public sealed class DiagnoseTests => Diag("""var p = "A"; return ctx.GetTag(p).Value;""") .ShouldContain(x => x.Message.Contains("literal")); - [Fact] public void Missing_return_does_not_produce_a_phantom_preamble_marker() - => Diag("var x = 1;").ShouldNotContain(m => m.Code == "CS0161"); + // 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 + // reported, on the script's last line (the wrapper location means "the script as a whole"). + [Fact] public void Missing_return_is_an_error_on_the_scripts_last_line() + { + var m = Diag("var x = 1;\nvar y = x + 1;").Single(x => x.Code == "CS0161"); + m.Severity.ShouldBe(8); + m.StartLineNumber.ShouldBe(2); + m.EndLineNumber.ShouldBe(2); + m.StartColumn.ShouldBe(1); + m.EndColumn.ShouldBe("var y = x + 1;".Length + 1); + m.Message.ShouldBe(ScriptAnalysisService.NotAllPathsReturnMessage); + } + + [Fact] public void Trailing_blank_lines_do_not_move_the_whole_script_marker_onto_nothing() + { + var m = Diag("var x = 1;\nvar y = x + 1;\n\n \n").Single(x => x.Code == "CS0161"); + m.StartLineNumber.ShouldBe(2); + m.EndColumn.ShouldBe("var y = x + 1;".Length + 1); + } + + [Fact] public void A_blank_predicate_is_refused_like_the_gate_refuses_it() + { + // A blank VALUE script never compiles at runtime (passes); a blank PREDICATE compiles and fails CS0161. + Diag("").ShouldBeEmpty(); + Svc.Diagnose(new DiagnoseRequest("", Mode: ScriptAnalysisModes.AlarmPredicate), TestContext.Current.CancellationToken) + .Markers.ShouldContain(m => m.Code == "CS0161" && m.StartLineNumber == 1 && m.EndColumn >= 1); + } + + [Fact] public void A_path_that_falls_off_the_end_is_an_error() + => Diag("""if (ctx.GetTag("A").Value is null) return 1;""").ShouldContain(m => m.Code == "CS0161" && m.Severity == 8); + + [Fact] public void Every_path_returning_is_clean_positive_control() + => Diag("""if (ctx.GetTag("A").Value is null) return 1; return 2;""").ShouldBeEmpty(); + + [Fact] public void A_wrapper_injection_is_an_error_like_the_runtime_compile() + => Diag("return 0; } public static int Evil() { return 0;").ShouldContain(m => m.Code == "LMX002" && m.Severity == 8); [Fact] public void Empty_code_has_no_markers() => Diag("").ShouldBeEmpty(); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EditorGateParityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EditorGateParityTests.cs new file mode 100644 index 000000000..f8c9340ad --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EditorGateParityTests.cs @@ -0,0 +1,116 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis; + +/// +/// lmxopcua#1063 / #1065 — "the editor accepts ⇔ publish accepts", checked over one corpus in all three editor modes +/// against the deploy gate's own checker (, the seam the mode names). The +/// editor used to drop wrapper-located errors, so a script with a path that does not return (CS0161) was clean in the +/// editor and refused at deploy; and a Calculation script carrying {{equip}} was accepted by both and read Bad +/// forever. Both sides now share and . +/// +/// +/// Excluded on purpose: a DYNAMIC tag path (ctx.GetTag(variable)) 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). +/// +public sealed class EditorGateParityTests +{ + private static readonly ScriptAnalysisService Svc = new(); + private static readonly RoslynDeployScriptChecker Gate = new(); + + public static TheoryData Corpus() + { + string[] sources = + [ + // CS0161 family (#1063): a path that falls off the end, no return at all, blank, whitespace-only. + "var x = 1;", + """if (ctx.GetTag("A").Value is null) return 1;""", + """if (ctx.GetTag("A").Value is null) return true;""", + "", + " \n ", + "while (true) { }", + "throw new System.InvalidOperationException(\"x\");", + // Well-formed returns: value and bool. + """if (ctx.GetTag("A").Value is null) return 1; return 2;""", + """return ctx.GetTag("A").Value;""", + """return Convert.ToDouble(ctx.GetTag("A").Value ?? 0.0) > 5;""", + "return true;", + "return null;", + "return;", + // Ordinary compile errors, sandbox, injection (LMX001/002). + "var x = ; return 1;", + "return ctx.Nope();", + """var f = new System.IO.FileInfo("/x"); return 1;""", + "return 0; } public static int Evil() { return 0;", + "return 0; } } class Evil { ", + "return 1; }", + "{ return 1;", + // {{equip}} (#1056 / #1065): substituted regular literal, passthrough shape, verbatim, interpolated, mid-path. + """return ctx.GetTag("{{equip}}/Speed").Value;""", + """return (double)ctx.GetTag("{{equip}}/Speed").Value * 2;""", + """return ctx.GetTag(@"{{equip}}/Speed").Value;""", + """return ctx.GetTag($"{{equip}}/Speed").Value;""", + """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;""", + ]; + string[] modes = [ScriptAnalysisModes.Value, ScriptAnalysisModes.Calculation, ScriptAnalysisModes.AlarmPredicate]; + var data = new TheoryData(); + foreach (var mode in modes) + foreach (var source in sources) + data.Add(mode, source); + return data; + } + + [Theory] + [MemberData(nameof(Corpus))] + public void Editor_and_gate_agree(string mode, string source) + { + var markers = Svc.Diagnose(new DiagnoseRequest(source, Mode: mode), TestContext.Current.CancellationToken).Markers; + var editorRejects = markers.Any(m => m.Severity == 8); + var verdict = Gate.Check( + [new DeployScriptCheckRequest(ScriptAnalysisModes.KindOf(mode), source)], TestContext.Current.CancellationToken)[0]; + editorRejects.ShouldBe(!verdict.Passed, + $"mode {mode}, source <{source}>: editor [{string.Join(" | ", markers.Select(m => m.Code + " " + m.Message))}] " + + $"vs gate [{string.Join(" | ", verdict.Problems)}]"); + } + + [Fact] + public void A_missing_return_is_refused_by_both_positive_control_for_the_parity_theory() + { + // Pins that the corpus really exercises #1063 — both sides REFUSE it (a parity theory where both accepted + // everything would pass vacuously). + const string source = """if (ctx.GetTag("A").Value is null) return 1;"""; + Svc.Diagnose(new DiagnoseRequest(source), TestContext.Current.CancellationToken).Markers.ShouldContain(m => m.Code == "CS0161" && m.Severity == 8); + Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, source)], TestContext.Current.CancellationToken)[0] + .Problems.ShouldContain(p => p.Contains("CS0161")); + } + + [Fact] + public void Equip_in_a_calculation_is_refused_by_both_but_accepted_by_both_for_a_virtual_tag() + { + const string source = """return ctx.GetTag("{{equip}}/Speed").Value;"""; + var ct = TestContext.Current.CancellationToken; + Svc.Diagnose(new DiagnoseRequest(source, Mode: ScriptAnalysisModes.Calculation), TestContext.Current.CancellationToken).Markers + .ShouldContain(m => m.Code == "OTSCRIPT_EQUIPCALC" && m.Severity == 8); + Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.Calculation, source)], ct)[0].Passed.ShouldBeFalse(); + // Positive control: the same text is the normal VirtualTag template form. + Svc.Diagnose(new DiagnoseRequest(source, Mode: ScriptAnalysisModes.Value), TestContext.Current.CancellationToken).Markers.ShouldBeEmpty(); + Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, source)], ct)[0].Passed.ShouldBeTrue(); + } + + [Fact] + public void The_editor_wraps_scripts_in_the_runtimes_own_wrapper_text() + { + var tree = Svc.CompilationFor("return 1;").SyntaxTrees.Single().ToString(); + tree.ShouldBe(ScriptEvaluator.WrapperPreamble + + "return 1;" + ScriptEvaluator.WrapperSuffix); + var predicate = Svc.CompilationFor("return true;", ScriptAnalysisModes.AlarmPredicate).SyntaxTrees.Single().ToString(); + predicate.ShouldBe(ScriptEvaluator.WrapperPreamble + + "return true;" + ScriptEvaluator.WrapperSuffix); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/ScriptUsageClassifyTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/ScriptUsageClassifyTests.cs index 9747fddce..d251f54dc 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/ScriptUsageClassifyTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/ScriptUsageClassifyTests.cs @@ -63,5 +63,34 @@ public sealed class ScriptUsageClassifyTests })); u.UsedAsValue.ShouldBeTrue(); u.UsedAsPredicate.ShouldBeFalse(); + // #1065: a Calculation use opens the editor in Calculation mode ({{equip}} refused, as the deploy gate does). + u.UsedAsCalculation.ShouldBeTrue(); + u.DefaultMode.ShouldBe(ScriptAnalysisModes.Calculation); + } + + [Fact] + public async Task A_script_shared_by_a_virtual_tag_and_a_calculation_tag_opens_in_calculation_mode() + { + // Calculation mode is the value shape plus the one Calculation-only refusal, so it shows every refusal either + // value use can meet; value mode would hide the {{equip}} refusal of the Calculation use. + var u = await Classify(db => + { + db.VirtualTags.Add(new VirtualTag { VirtualTagId = "vt-1", EquipmentId = "eq", Name = "v", DataType = "Double", ScriptId = "s-1" }); + db.Tags.Add(new Tag + { + TagId = "t-1", DeviceId = "d", Name = "calc", DataType = "Double", AccessLevel = ZB.MOM.WW.OtOpcUa.Configuration.Enums.TagAccessLevel.Read, TagConfig = "{\"scriptId\":\"s-1\"}", + }); + }); + u.UsedAsCalculation.ShouldBeTrue(); + u.DefaultMode.ShouldBe(ScriptAnalysisModes.Calculation); + } + + [Fact] + public async Task A_virtual_tag_only_script_is_not_a_calculation_script() + { + var u = await Classify(db => + db.VirtualTags.Add(new VirtualTag { VirtualTagId = "vt-1", EquipmentId = "eq", Name = "v", DataType = "Double", ScriptId = "s-1" })); + u.UsedAsCalculation.ShouldBeFalse(); + u.DefaultMode.ShouldBe(ScriptAnalysisModes.Value); } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs index 2688a0599..505fb2a83 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs @@ -211,6 +211,26 @@ public sealed class AdminOperationsActorScriptCompileGateTests : ControlPlaneAct reply.Message.ShouldContain("Calculation tag 'tag-calc' (plant/calc/cdev/sum)"); } + /// + /// lmxopcua#1065: a Calculation tag has no equipment, and the Calculation seam never substitutes {{equip}}, + /// so a Calculation script carrying it used to deploy clean and read {{equip}}/speed literally — Bad forever. + /// The gate now refuses it (the passthrough shape too, which never reaches Roslyn), naming the Calculation tag; + /// the VirtualTag in the same draft uses the token legitimately (positive control: it is not named). + /// + [Theory] + [InlineData("return ctx.GetTag(\"{{equip}}/speed\").Value;")] + [InlineData("return Convert.ToDouble(ctx.GetTag(\"{{equip}}/speed\").Value ?? 0.0) + 1;")] + public void An_equip_token_in_a_calculation_script_is_refused_naming_the_calculation_tag(string calcSource) + { + var reply = Deploy(SeedDraft(new Seed(CalcSource: calcSource)), new RoslynDeployScriptChecker(), expectDispatch: false); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected); + reply.Message.ShouldNotBeNull(); + reply.Message.ShouldContain("script 's-calc' does not compile as a Calculation script"); + reply.Message.ShouldContain("Calculation tag 'tag-calc' (plant/calc/cdev/sum)"); + reply.Message.ShouldContain("equip token in a Calculation script"); + reply.Message.ShouldNotContain("script 's-vt'"); + } + [Fact] public void Disabled_users_are_not_checked_they_never_compile_at_runtime() {