fix(scripting): #1063 one compile-refusal authority for editor and deploy gate (ScriptCompileRules + the runtime's own wrapper text) — CS0161 and wrapper injection are now flagged in the editor; #1065 {{equip}} in a Calculation script is refused by the gate and by a new Calculation editor mode
#1063: the Monaco diagnostics dropped every Roslyn error located in the synthesized wrapper as 'phantom', so CS0161 (not all code paths return a value, pinned on Run) passed the editor and failed the deploy gate. ScriptCompileRules (Core.Scripting) now states which diagnostics refuse (every Error, wherever located; LMX001/002 injection) and which sources skip the compile (blank/passthrough value scripts); ScriptEvaluator and the editor both use it, and the editor wraps with ScriptEvaluator.WrapperPreamble/ WrapperSuffix instead of its own copy. Wrapper-located refusals are drawn on the script's last line. EditorGateParityTests runs one corpus through editor and gate in all three modes. #1065: a Calculation tag is raw/device-level with no equipment and its seam never substitutes {{equip}}, so such a script deployed clean and read Bad forever. Refused rather than substituted: EquipTokenLiteralScanner.FindInCalculation is run by RoslynDeployScriptChecker for every Calculation use (before the passthrough shortcut, outside the shared VT/Calc cache) and by the editor in the new 'calculation' mode (Calculation tag editor; ScriptEdit defaults to it when a Calculation tag uses the script).
This commit is contained in:
+47
-22
@@ -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<TContext, TResult>.WrapperPreamble`
|
||||
(usings from `ScriptSandbox.Build`, the
|
||||
`CompiledScript.Run(ScriptGlobals<VirtualTagContext>)` 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<AlarmPredicateContext>)` 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.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+2
-1
@@ -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<TContext, TResult>.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 |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -62,6 +62,53 @@ public static class EquipTokenLiteralScanner
|
||||
return findings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1065: the <c>{{equip}}</c> token in ANY path literal of a <b>Calculation</b> 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 <c>{{equip}}/…</c> literally — Bad for as long as it ran. Both the deploy gate
|
||||
/// (<see cref="RoslynDeployScriptChecker"/>, for every Calculation use) and the editor (<c>OTSCRIPT_EQUIPCALC</c>, in
|
||||
/// Calculation mode) run this one scan and refuse it. Same <c>ctx</c> receiver guard as <see cref="Find"/>; every
|
||||
/// literal form (regular, verbatim, raw, interpolated) counts, and the token anywhere in the path, not only as its
|
||||
/// prefix.
|
||||
/// </summary>
|
||||
/// <param name="source">The Calculation script source.</param>
|
||||
/// <returns>The offending path literals, in source order; empty when none.</returns>
|
||||
public static IReadOnlyList<Finding> 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<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 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(\"<RawPath>\")), or move an equipment-relative " +
|
||||
"computation to a VirtualTag on the equipment."));
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
private static string? OffendingForm(ExpressionSyntax path)
|
||||
{
|
||||
switch (path)
|
||||
|
||||
@@ -18,7 +18,12 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
/// <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
|
||||
/// <see cref="ScriptEvaluator{TContext, TResult}.CompileToImage"/> uses, so the gate and the runtime cannot drift.
|
||||
/// <see cref="ScriptEvaluator{TContext, TResult}.CompileToImage"/> uses, so the gate and the runtime cannot drift;
|
||||
/// which diagnostics refuse and which sources skip the compile are <see cref="ScriptCompileRules"/>, which the Monaco
|
||||
/// editor reads too (lmxopcua#1063). One rule is kind-specific and runs before everything else: a
|
||||
/// <b>Calculation</b> script may not carry <c>{{equip}}</c> in a path literal
|
||||
/// (<see cref="EquipTokenLiteralScanner.FindInCalculation"/>, lmxopcua#1065) — the passthrough shortcut included, and
|
||||
/// outside the cache, because VirtualTag and Calculation otherwise share one cached verdict.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
@@ -55,11 +60,21 @@ public sealed class RoslynDeployScriptChecker : IDeployScriptChecker
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(requests);
|
||||
var keys = new string?[requests.Count];
|
||||
var direct = new IReadOnlyList<string>?[requests.Count];
|
||||
var pending = new Dictionary<string, DeployScriptCheckRequest>(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;
|
||||
}
|
||||
|
||||
/// <summary>True when the runtime seam answers the source without compiling it.</summary>
|
||||
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";
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The one statement of "does the runtime compile refuse this script" (lmxopcua#1063), shared by the runtime
|
||||
/// compile (<see cref="ScriptEvaluator{TContext, TResult}"/>, which the deploy gate's
|
||||
/// <see cref="RoslynDeployScriptChecker"/> runs through <c>Verify</c>) and the Monaco editor's diagnostics.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// 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 <c>Run</c> 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 (<see cref="ScriptEvaluator{TContext, TResult}.WrapperPreamble"/>), and the editor
|
||||
/// only decides WHERE to draw a wrapper-located refusal, never WHETHER to.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The third refusal leg, <see cref="ForbiddenTypeAnalyzer"/>, is already one shared analyzer and is called
|
||||
/// directly by both sides.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class ScriptCompileRules
|
||||
{
|
||||
/// <summary>
|
||||
/// True when the runtime seam answers <paramref name="source"/> 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
|
||||
/// (<see cref="PassthroughScript"/>). A scripted-alarm predicate always compiles.
|
||||
/// </summary>
|
||||
/// <param name="kind">The seam the script runs as.</param>
|
||||
/// <param name="source">The source.</param>
|
||||
/// <returns>Whether the runtime skips the compile.</returns>
|
||||
public static bool SkipsCompile(ScriptContextKind kind, string? source) =>
|
||||
kind is ScriptContextKind.VirtualTag or ScriptContextKind.Calculation
|
||||
&& (string.IsNullOrWhiteSpace(source) || PassthroughScript.TryMatch(source, out _));
|
||||
|
||||
/// <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).
|
||||
/// Warnings never refuse.
|
||||
/// </summary>
|
||||
/// <param name="compilation">The compilation of the wrapped source.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The refusing diagnostics; empty when the compile accepts the source.</returns>
|
||||
public static IReadOnlyList<Diagnostic> CompileErrors(Compilation compilation, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(compilation);
|
||||
return compilation.GetDiagnostics(cancellationToken).Where(d => d.Severity == DiagnosticSeverity.Error).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Core.Scripting-013: the wrapper-injection refusal. The parsed wrapper must hold exactly one type — the
|
||||
/// synthesized <c>CompiledScript</c> — and that class exactly one member, the <c>Run</c> method. A script body
|
||||
/// like <c>return 0; } public static int Evil() { return 0;</c> closes <c>Run</c> early and declares a sibling;
|
||||
/// the analyzer would still walk it, but it breaks the "method body" authoring contract.
|
||||
/// </summary>
|
||||
/// <param name="wrapperTree">The parsed wrapper (preamble + user source + suffix).</param>
|
||||
/// <returns>The <c>LMX001</c> / <c>LMX002</c> diagnostic, or null when the shape is intact.</returns>
|
||||
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<BaseTypeDeclarationSyntax>().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;
|
||||
}
|
||||
}
|
||||
@@ -133,7 +133,7 @@ public sealed class ScriptEvaluator<TContext, TResult> : 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<TContext, TResult> : 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<TContext, TResult> : 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<TContext, TResult> : 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<ScriptGlobals<TContext>, TResult> func;
|
||||
try
|
||||
{
|
||||
@@ -304,97 +306,43 @@ public sealed class ScriptEvaluator<TContext, TResult> : IDisposable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reject scripts whose source contains brace-balanced injections that would
|
||||
/// declare sibling members alongside the synthesized <c>CompiledScript.Run</c>
|
||||
/// method. The expected shape is a single <c>CompiledScript</c> class with
|
||||
/// exactly one member — the <c>Run</c> 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 <c>using</c> directives (so scripts can
|
||||
/// write <c>Math.Abs</c>), the <c>CompiledScript</c> class and the <c>Run(ScriptGlobals<TContext>)</c>
|
||||
/// signature, <c>var ctx = globals.ctx;</c>, then <c>#line 1</c> 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 <c>\n</c> line ends on every platform, so the text (and every offset into it) is stable.
|
||||
/// </summary>
|
||||
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<Microsoft.CodeAnalysis.CSharp.Syntax.BaseTypeDeclarationSyntax>()
|
||||
.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),
|
||||
});
|
||||
}
|
||||
/// <summary>The text the runtime appends AFTER the user's script body: closes <c>Run</c> and the class.</summary>
|
||||
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<string> PreambleHolder =
|
||||
new(() => BuildWrapperPreamble(ScriptSandbox.Build(typeof(TContext)).Imports), LazyThreadSafetyMode.ExecutionAndPublication);
|
||||
|
||||
/// <summary>
|
||||
/// Synthesize the source we hand to Roslyn. The user's script body is pasted
|
||||
/// verbatim inside <c>CompiledScript.Run</c>; the <c>using</c> directives mirror
|
||||
/// <see cref="ScriptSandbox"/>'s imports so scripts can write <c>Math.Abs</c>
|
||||
/// instead of <c>System.Math.Abs</c>.
|
||||
/// Synthesize the wrapper preamble. The user's script body is pasted verbatim after it, inside
|
||||
/// <c>CompiledScript.Run</c>, so explicit <c>return</c> semantics apply.
|
||||
/// </summary>
|
||||
private static string BuildWrapperSource(string userSource, IReadOnlyList<string> imports)
|
||||
private static string BuildWrapperPreamble(IReadOnlyList<string> 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<TContext>)))
|
||||
.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();
|
||||
}
|
||||
|
||||
|
||||
@@ -76,13 +76,15 @@ else
|
||||
<h2 class="panel-head">Source</h2>
|
||||
<div style="padding:1rem">
|
||||
@* #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. *@
|
||||
<div class="mb-2 d-flex align-items-center gap-2">
|
||||
<label class="form-label mb-0" for="@(_fieldId + "-mode")">Analyse as</label>
|
||||
<select id="@(_fieldId + "-mode")" class="form-select form-select-sm w-auto" value="@_mode"
|
||||
@onchange="e => ChangeMode(e.Value?.ToString(), presentation)">
|
||||
<option value="@ScriptAnalysisModes.Value">Virtual tag / Calculation value script</option>
|
||||
<option value="@ScriptAnalysisModes.Value">Virtual tag value script</option>
|
||||
<option value="@ScriptAnalysisModes.Calculation">Calculation tag script (no {{equip}})</option>
|
||||
<option value="@ScriptAnalysisModes.AlarmPredicate">Scripted-alarm predicate (must return bool)</option>
|
||||
</select>
|
||||
</div>
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
+4
-1
@@ -75,7 +75,10 @@
|
||||
Editing shared script "<span class="mono">@_scriptName</span>" — used by
|
||||
@_scriptUsageCount virtual tag(s). Changes affect every tag using it.
|
||||
</div>
|
||||
<MonacoEditor AriaLabel="Calculation script source" @bind-Value="_scriptSource" Height="300px" />
|
||||
@* #1065: Calculation mode — a Calculation tag has no equipment, so {{equip}} is refused here exactly as the deploy
|
||||
gate refuses it. *@
|
||||
<MonacoEditor AriaLabel="Calculation script source" @bind-Value="_scriptSource" Height="300px"
|
||||
Mode="@ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis.ScriptAnalysisModes.Calculation" />
|
||||
@if (!string.IsNullOrWhiteSpace(_scriptError))
|
||||
{
|
||||
<div class="text-danger small mt-2">@_scriptError</div>
|
||||
|
||||
@@ -1,24 +1,49 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <c>object Run(ScriptGlobals<VirtualTagContext>)</c> (VirtualTag and Calculation share it); a scripted-alarm
|
||||
/// predicate is <c>bool Run(ScriptGlobals<AlarmPredicateContext>)</c>. Carried as a string on the wire; null,
|
||||
/// blank or anything unrecognised means <see cref="Value"/>.
|
||||
/// predicate is <c>bool Run(ScriptGlobals<AlarmPredicateContext>)</c>. A Calculation script compiles as a value
|
||||
/// script but is held to one more gate rule — no <c>{{equip}}</c> token (lmxopcua#1065) — so it has its own mode.
|
||||
/// Carried as a string on the wire; null, blank or anything unrecognised means <see cref="Value"/>.
|
||||
/// </summary>
|
||||
public static class ScriptAnalysisModes
|
||||
{
|
||||
/// <summary>A VirtualTag / Calculation value script (the default).</summary>
|
||||
/// <summary>A VirtualTag value script (the default).</summary>
|
||||
public const string Value = "value";
|
||||
|
||||
/// <summary>A scripted-alarm predicate: must return <c>bool</c>.</summary>
|
||||
public const string AlarmPredicate = "alarmPredicate";
|
||||
|
||||
/// <summary>A Calculation-tag script: the value shape, plus the Calculation-only refusal of <c>{{equip}}</c>.</summary>
|
||||
public const string Calculation = "calculation";
|
||||
|
||||
/// <summary>True when <paramref name="mode"/> selects the predicate shape.</summary>
|
||||
/// <param name="mode">The wire value.</param>
|
||||
/// <returns>Whether it names <see cref="AlarmPredicate"/>.</returns>
|
||||
public static bool IsPredicate(string? mode) => string.Equals(mode, AlarmPredicate, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>True when <paramref name="mode"/> selects the Calculation rules.</summary>
|
||||
/// <param name="mode">The wire value.</param>
|
||||
/// <returns>Whether it names <see cref="Calculation"/>.</returns>
|
||||
public static bool IsCalculation(string? mode) => string.Equals(mode, Calculation, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The deploy-gate seam a mode analyses as — what the gate's checker is asked for the same script.</summary>
|
||||
/// <param name="mode">The wire value.</param>
|
||||
/// <returns>The seam.</returns>
|
||||
public static ScriptContextKind KindOf(string? mode) =>
|
||||
IsPredicate(mode) ? ScriptContextKind.AlarmPredicate
|
||||
: IsCalculation(mode) ? ScriptContextKind.Calculation
|
||||
: ScriptContextKind.VirtualTag;
|
||||
|
||||
/// <summary>The canonical wire value for <paramref name="mode"/> (unrecognised means <see cref="Value"/>).</summary>
|
||||
/// <param name="mode">The wire value.</param>
|
||||
/// <returns>One of the three constants.</returns>
|
||||
public static string Normalize(string? mode) =>
|
||||
IsPredicate(mode) ? AlarmPredicate : IsCalculation(mode) ? Calculation : Value;
|
||||
}
|
||||
|
||||
// EquipmentId (optional) carries the owning-equipment context the {{equip}}/<RefName> completion +
|
||||
|
||||
@@ -51,19 +51,14 @@ public sealed class ScriptAnalysisService
|
||||
/// </summary>
|
||||
private sealed class Shape
|
||||
{
|
||||
public Shape(Type contextType, string returnType)
|
||||
public Shape(Type contextType, string preamble)
|
||||
{
|
||||
Sandbox = ScriptSandbox.Build(contextType);
|
||||
// Mirrors ScriptEvaluator's wrapper EXACTLY (usings from the sandbox + the Run(ScriptGlobals<TContext>)
|
||||
// shape). The value shape's return type is `object` so a shared script stays valid regardless of any
|
||||
// virtual tag's DataType; the predicate shape is `bool`, exactly as the alarm engine compiles it.
|
||||
var usings = string.Join("\n", Sandbox.Imports.Select(i => $"using {i};"));
|
||||
var globalsType = $"global::{typeof(ScriptGlobals<>).Namespace}.ScriptGlobals<global::{contextType.FullName}>";
|
||||
Preamble = usings + "\n\n"
|
||||
+ "namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;\n"
|
||||
+ "public static class CompiledScript\n{\n"
|
||||
+ $" public static {returnType} Run({globalsType} globals)\n {{\n"
|
||||
+ " var ctx = globals.ctx;\n#line 1\n";
|
||||
// The runtime's OWN wrapper text (ScriptEvaluator<TContext, TResult>.WrapperPreamble / WrapperSuffix) — the
|
||||
// usings, the Run(ScriptGlobals<TContext>) signature and #line 1 — never a local copy (lmxopcua#1063). The
|
||||
// value shape compiles to `object` so a shared script stays valid regardless of any virtual tag's DataType;
|
||||
// the predicate shape is `bool`, exactly as the alarm engine compiles it.
|
||||
Preamble = preamble;
|
||||
var compilation = CSharpCompilation.Create(
|
||||
"ScriptAnalysis", new[] { Parse("", CancellationToken.None) }, Sandbox.References, CompileOptions);
|
||||
_ = compilation.GetSpecialType(SpecialType.System_Object);
|
||||
@@ -75,11 +70,14 @@ public sealed class ScriptAnalysisService
|
||||
public CSharpCompilation BaseCompilation { get; }
|
||||
|
||||
public SyntaxTree Parse(string userSource, CancellationToken ct)
|
||||
=> CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + "\n }\n}\n", cancellationToken: ct);
|
||||
=> CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + ScriptEvaluator<VirtualTagContext, object?>.WrapperSuffix,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
|
||||
private static readonly Shape ValueShape = new(typeof(VirtualTagContext), "object");
|
||||
private static readonly Shape PredicateShape = new(typeof(AlarmPredicateContext), "bool");
|
||||
private static readonly Shape ValueShape =
|
||||
new(typeof(VirtualTagContext), ScriptEvaluator<VirtualTagContext, object?>.WrapperPreamble);
|
||||
private static readonly Shape PredicateShape =
|
||||
new(typeof(AlarmPredicateContext), ScriptEvaluator<AlarmPredicateContext, bool>.WrapperPreamble);
|
||||
|
||||
private static Shape ShapeFor(string? mode) => ScriptAnalysisModes.IsPredicate(mode) ? PredicateShape : ValueShape;
|
||||
|
||||
@@ -122,50 +120,62 @@ public sealed class ScriptAnalysisService
|
||||
|
||||
private static string Normalize(string? s) => (s ?? "").Replace("\r\n", "\n").Replace("\r", "\n");
|
||||
|
||||
/// <summary>Compiles the script and returns compile-error diagnostics plus sandbox-policy violations
|
||||
/// (forbidden types, disallowed dynamic tag paths).</summary>
|
||||
/// <param name="req">The diagnose request carrying the script source.</param>
|
||||
/// <summary>Returns the markers for what the deploy gate would refuse — the runtime compile's own refusals (one
|
||||
/// shared authority, <see cref="ScriptCompileRules"/>), sandbox-policy violations, disallowed dynamic tag paths and
|
||||
/// the <c>{{equip}}</c> literal rules — plus advisory warnings.</summary>
|
||||
/// <param name="req">The diagnose request carrying the script source and the analysis mode.</param>
|
||||
/// <param name="ct">The request's cancellation token; a cancelled request throws <see cref="OperationCanceledException"/>.</param>
|
||||
/// <returns>The list of diagnostic markers, empty when the script is clean or analysis fails.</returns>
|
||||
public DiagnoseResponse Diagnose(DiagnoseRequest req, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(req.Code)) return new DiagnoseResponse(Array.Empty<DiagnosticMarker>());
|
||||
var code = Normalize(req.Code);
|
||||
var kind = ScriptAnalysisModes.KindOf(req.Mode);
|
||||
// A blank / passthrough value script never reaches the compiler at runtime, so nothing the compiler says can
|
||||
// refuse it (ScriptCompileRules.SkipsCompile — the deploy gate's own shortcut). A blank PREDICATE does compile,
|
||||
// and is refused (CS0161), so it is analysed.
|
||||
var compiles = !ScriptCompileRules.SkipsCompile(kind, code);
|
||||
if (code.Length == 0 && !compiles) return new DiagnoseResponse(Array.Empty<DiagnosticMarker>());
|
||||
try
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var code = Normalize(req.Code);
|
||||
var (tree, compilation, _, preambleLength) = Analyze(code, req.Mode, ct);
|
||||
var markers = new List<DiagnosticMarker>();
|
||||
|
||||
// (1) Roslyn — surface ONLY compile errors, the same severity that actually blocks a
|
||||
// publish in ScriptEvaluator.Compile (it filters GetDiagnostics() to
|
||||
// DiagnosticSeverity.Error). Mirroring that here keeps editor markers in lockstep with
|
||||
// what fails publish: a nullable warning like CS8605 on the canonical passthrough shape
|
||||
// `return ctx.GetTag("X").Value;` compiles + publishes fine under the evaluator's
|
||||
// nullable-enabled options, so flagging it in the editor would be misleading noise.
|
||||
// Restricted to diagnostics physically inside the user source — #line 1 in the preamble
|
||||
// makes GetMappedLineSpan report user-source coords (GetLineSpan would return the
|
||||
// physical wrapper line and be wrong); the preambleLength guard also drops phantom
|
||||
// wrapper diagnostics like CS0161 on Run() when the user hasn't typed `return` yet.
|
||||
foreach (var d in compilation.GetDiagnostics(ct))
|
||||
// (1) The runtime compile's own refusals (lmxopcua#1063), from the one authority — ScriptCompileRules — over
|
||||
// the runtime's own wrapper text: wrapper injection (LMX001/002) and EVERY Error-severity diagnostic. Warnings
|
||||
// never refuse (a nullable warning like CS8605 on `return ctx.GetTag("X").Value;` publishes fine), so they are
|
||||
// not shown. This used to drop every diagnostic located in the wrapper as "phantom" — including CS0161 "not
|
||||
// all code paths return a value", which Roslyn pins on the wrapper's Run and the deploy gate refuses. Such a
|
||||
// diagnostic is now drawn on the script's last line instead (ToRefusalMarker).
|
||||
if (compiles)
|
||||
{
|
||||
if (d.Severity != DiagnosticSeverity.Error || !d.Location.IsInSource) continue;
|
||||
if (d.Location.SourceSpan.Start < preambleLength) continue;
|
||||
var span = d.Location.GetMappedLineSpan(); // honors #line 1 → user coords
|
||||
markers.Add(ToMarker(span, Sev(d.Severity), d.GetMessage(), d.Id));
|
||||
if (ScriptCompileRules.WrapperInjection(tree) is { } injection)
|
||||
markers.Add(ToRefusalMarker(injection, code, preambleLength));
|
||||
foreach (var d in ScriptCompileRules.CompileErrors(compilation, ct))
|
||||
markers.Add(ToRefusalMarker(d, code, preambleLength));
|
||||
// (2) ForbiddenTypeAnalyzer — spans are in the wrapped tree; map via #line.
|
||||
ct.ThrowIfCancellationRequested();
|
||||
foreach (var r in ForbiddenTypeAnalyzer.Analyze(compilation))
|
||||
markers.Add(ToMarker(tree.GetMappedLineSpan(r.Span), 8, r.Message, "OTSCRIPT_FORBIDDEN"));
|
||||
}
|
||||
// (2) ForbiddenTypeAnalyzer — spans are in the wrapped tree; map via #line.
|
||||
ct.ThrowIfCancellationRequested();
|
||||
foreach (var r in ForbiddenTypeAnalyzer.Analyze(compilation))
|
||||
markers.Add(ToMarker(tree.GetMappedLineSpan(r.Span), 8, r.Message, "OTSCRIPT_FORBIDDEN"));
|
||||
ct.ThrowIfCancellationRequested();
|
||||
// (3) DependencyExtractor — spans are offsets in the normalized user source; map directly.
|
||||
foreach (var r in DependencyExtractor.Extract(code).Rejections)
|
||||
markers.Add(ToUserMarker(code, r.Span, r.Message, "OTSCRIPT_DYNPATH"));
|
||||
// (3b) lmxopcua#1056: a {{equip}} token in a verbatim/raw/interpolated path literal is never substituted —
|
||||
// the deploy gate refuses it (RoslynDeployScriptChecker runs this same scan), so the editor does too.
|
||||
foreach (var f in EquipTokenLiteralScanner.Find(code))
|
||||
markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_EQUIPLITERAL"));
|
||||
if (kind == ScriptContextKind.Calculation)
|
||||
{
|
||||
// (3a) lmxopcua#1065: a Calculation tag has no equipment — {{equip}} in any path literal is refused by the
|
||||
// deploy gate (RoslynDeployScriptChecker runs this same scan). Covers every literal form, so it subsumes 3b.
|
||||
foreach (var f in EquipTokenLiteralScanner.FindInCalculation(code))
|
||||
markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_EQUIPCALC"));
|
||||
}
|
||||
else
|
||||
{
|
||||
// (3b) lmxopcua#1056: a {{equip}} token in a verbatim/raw/interpolated path literal is never substituted —
|
||||
// the deploy gate refuses it (RoslynDeployScriptChecker runs this same scan), so the editor does too.
|
||||
foreach (var f in EquipTokenLiteralScanner.Find(code))
|
||||
markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_EQUIPLITERAL"));
|
||||
}
|
||||
// (4) ctx.SetVirtualTag(...) is inert at runtime — a WARNING (severity 4), never an error: publish
|
||||
// accepts the script, so the editor must too; the marker just puts the hover's caveat in the Problems list.
|
||||
foreach (var inv in SetVirtualTagCalls(tree.GetRoot(ct), preambleLength))
|
||||
@@ -186,6 +196,27 @@ public sealed class ScriptAnalysisService
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The message shown for CS0161, which Roslyn words in terms of the synthesized wrapper method.</summary>
|
||||
internal const string NotAllPathsReturnMessage =
|
||||
"Not all code paths return a value: every path through the script must end in a `return …;` statement " +
|
||||
"(the deploy gate refuses the script otherwise).";
|
||||
|
||||
// A refusal of the runtime compile, as a marker. Physically inside the user source => its #line-mapped user-source
|
||||
// position (GetMappedLineSpan honours #line 1; GetLineSpan would give the wrapper line). Anywhere else — on the
|
||||
// wrapper (CS0161 sits on Run's identifier), or with no location — it is about the script as a whole, so it is drawn
|
||||
// on the script's last line: never dropped, because the runtime compile refuses it all the same.
|
||||
private static DiagnosticMarker ToRefusalMarker(Diagnostic d, string code, int preambleLength)
|
||||
{
|
||||
var message = d.Id == "CS0161" ? NotAllPathsReturnMessage : d.GetMessage();
|
||||
if (d.Location.IsInSource && d.Location.SourceSpan.Start >= preambleLength)
|
||||
return ToMarker(d.Location.GetMappedLineSpan(), 8, message, d.Id);
|
||||
// The last line with text on it (trailing blank lines would put the squiggle on nothing).
|
||||
var end = code.TrimEnd().Length;
|
||||
var lastLineStart = end == 0 ? 0 : code.LastIndexOf('\n', end - 1) + 1;
|
||||
var (line, _) = LineCol(code, lastLineStart);
|
||||
return new DiagnosticMarker(8, line, 1, line, Math.Max(1, end - lastLineStart + 1), message, d.Id);
|
||||
}
|
||||
|
||||
/// <summary>Diagnostics plus the v3 equipment-relative <c>{{equip}}/<RefName></c> resolution check.
|
||||
/// Runs the synchronous Roslyn/policy <see cref="Diagnose"/> then, when an equipment context + catalog
|
||||
/// are present, appends a marker for each <c>{{equip}}/<RefName></c> whose <c><RefName></c> is
|
||||
|
||||
@@ -24,15 +24,20 @@ public static class ScriptUsage
|
||||
/// <summary>Which seams use a script.</summary>
|
||||
/// <param name="UsedAsValue">An (any) VirtualTag or Calculation tag runs it as a value script.</param>
|
||||
/// <param name="UsedAsPredicate">An (any) scripted alarm runs it as its predicate.</param>
|
||||
public readonly record struct SeamUsage(bool UsedAsValue, bool UsedAsPredicate)
|
||||
/// <param name="UsedAsCalculation">An (any) Calculation tag runs it (implies <paramref name="UsedAsValue"/>).</param>
|
||||
public readonly record struct SeamUsage(bool UsedAsValue, bool UsedAsPredicate, bool UsedAsCalculation = false)
|
||||
{
|
||||
/// <summary>
|
||||
/// The editor analysis mode (<c>ScriptAnalysisModes</c>) 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 (<c>ScriptAnalysisModes</c>) a script should open in (lmxopcua#1025): Calculation mode
|
||||
/// whenever a Calculation tag runs it (lmxopcua#1065 — the deploy gate refuses <c>{{equip}}</c> 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.
|
||||
/// </summary>
|
||||
public string DefaultMode =>
|
||||
UsedAsPredicate && !UsedAsValue ? ScriptAnalysis.ScriptAnalysisModes.AlarmPredicate : ScriptAnalysis.ScriptAnalysisModes.Value;
|
||||
UsedAsCalculation ? ScriptAnalysis.ScriptAnalysisModes.Calculation
|
||||
: UsedAsPredicate && !UsedAsValue ? ScriptAnalysis.ScriptAnalysisModes.AlarmPredicate
|
||||
: ScriptAnalysis.ScriptAnalysisModes.Value;
|
||||
}
|
||||
|
||||
/// <summary>Classifies which seams use <paramref name="scriptId"/> (same rows, same Calculation parser as the delete check).</summary>
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -21,7 +21,8 @@ namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
|
||||
/// <item><b>Enabled scripted alarms</b> (a disabled plan is skipped by the alarm host) — predicate source,
|
||||
/// substituted the same way.</item>
|
||||
/// <item><b>Calculation tags of enabled Calculation drivers</b> — the source verbatim (the artifact injects it
|
||||
/// into the tag's TagConfig with no substitution).</item>
|
||||
/// into the tag's TagConfig with no substitution). A Calculation tag has no equipment, so the checker refuses a
|
||||
/// <c>{{equip}}</c> token in it outright (lmxopcua#1065).</item>
|
||||
/// </list>
|
||||
/// <para>
|
||||
/// When <see cref="EquipmentScriptPaths.SubstitutionPreservesCompilation"/> proves the substitution cannot
|
||||
|
||||
@@ -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<AlarmPredicateContext, bool>(source);
|
||||
CheckOne(checker, ScriptContextKind.AlarmPredicate, source).Passed.ShouldBe(predicateRuntime);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1065: a Calculation tag is raw/device-level — no equipment — and its seam never substitutes
|
||||
/// <c>{{equip}}</c>, 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).
|
||||
/// </summary>
|
||||
[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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1063 / #1065 — "the editor accepts ⇔ publish accepts", checked over one corpus in all three editor modes
|
||||
/// against the deploy gate's own checker (<see cref="RoslynDeployScriptChecker"/>, 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 <c>{{equip}}</c> was accepted by both and read Bad
|
||||
/// 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).
|
||||
/// </remarks>
|
||||
public sealed class EditorGateParityTests
|
||||
{
|
||||
private static readonly ScriptAnalysisService Svc = new();
|
||||
private static readonly RoslynDeployScriptChecker Gate = new();
|
||||
|
||||
public static TheoryData<string, string> 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<string, string>();
|
||||
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<ZB.MOM.WW.OtOpcUa.Core.VirtualTags.VirtualTagContext, object?>.WrapperPreamble
|
||||
+ "return 1;" + ScriptEvaluator<ZB.MOM.WW.OtOpcUa.Core.VirtualTags.VirtualTagContext, object?>.WrapperSuffix);
|
||||
var predicate = Svc.CompilationFor("return true;", ScriptAnalysisModes.AlarmPredicate).SyntaxTrees.Single().ToString();
|
||||
predicate.ShouldBe(ScriptEvaluator<ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.AlarmPredicateContext, bool>.WrapperPreamble
|
||||
+ "return true;" + ScriptEvaluator<ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.AlarmPredicateContext, bool>.WrapperSuffix);
|
||||
}
|
||||
}
|
||||
+29
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+20
@@ -211,6 +211,26 @@ public sealed class AdminOperationsActorScriptCompileGateTests : ControlPlaneAct
|
||||
reply.Message.ShouldContain("Calculation tag 'tag-calc' (plant/calc/cdev/sum)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1065: a Calculation tag has no equipment, and the Calculation seam never substitutes <c>{{equip}}</c>,
|
||||
/// so a Calculation script carrying it used to deploy clean and read <c>{{equip}}/speed</c> 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).
|
||||
/// </summary>
|
||||
[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()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user