Merge scripting follow-ups: one shared compile rule for editor + gate, CS0161/injection now flagged in the editor (#1063), worker applies the result materialisation cap (#1064), {{equip}} in Calculation scripts refused at gate + editor (#1065)
This commit is contained in:
@@ -764,7 +764,8 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp
|
||||
LoadTimeout: LoadTimeout,
|
||||
CompileThreads: _compileThreads,
|
||||
WorkerSid: WorkerSid,
|
||||
HeartbeatSilenceLimit: _heartbeatSilenceLimit);
|
||||
HeartbeatSilenceLimit: _heartbeatSilenceLimit,
|
||||
MaxResultElements: _options.MaxResultElements);
|
||||
return new WorkerShard(label, isolation,
|
||||
(onExiting, ct) => WorkerConnection.StartAsync(spec, _log, OnLogs, onExiting, ct),
|
||||
OnWorkerExit, _log);
|
||||
|
||||
@@ -102,6 +102,11 @@ internal sealed record BatchSubmission(string Key, EvalRequest Request, TimeSpan
|
||||
/// Ask the worker to run the soft clock from each run's start (lmxopcua#827; see <see cref="WorkerConnection.WorkerSoftClock"/>).
|
||||
/// False (tests only) keeps the pre-#827 host clock, which is also what a worker that does not echo it gets.
|
||||
/// </param>
|
||||
/// <param name="MaxResultElements">
|
||||
/// <c>Scripting:MaxResultElements</c> (lmxopcua#1064): the element cap the worker holds a value script's returned
|
||||
/// sequence to while materialising it inside the run — the same rule the in-process guard applies (#1059). 0 = the
|
||||
/// worker's default.
|
||||
/// </param>
|
||||
internal sealed record WorkerLaunchSpec(
|
||||
string Shard,
|
||||
string WorkerPath,
|
||||
@@ -117,7 +122,8 @@ internal sealed record WorkerLaunchSpec(
|
||||
string? WorkerSid = null,
|
||||
bool WorkerSoftClock = true,
|
||||
TimeSpan? HeartbeatSilenceLimit = null,
|
||||
bool TestStallReaderOnDiag = false)
|
||||
bool TestStallReaderOnDiag = false,
|
||||
int MaxResultElements = 0)
|
||||
{
|
||||
/// <summary>The default compile timeout.</summary>
|
||||
public static readonly TimeSpan DefaultLoadTimeout = TimeSpan.FromSeconds(60);
|
||||
@@ -448,6 +454,7 @@ internal sealed class WorkerConnection : IAsyncDisposable
|
||||
CompileThreads = (uint)Math.Max(0, spec.CompileThreads),
|
||||
WorkerSoftClock = spec.WorkerSoftClock,
|
||||
TestStallReaderOnDiag = spec.TestStallReaderOnDiag,
|
||||
MaxResultElements = (uint)Math.Max(0, spec.MaxResultElements),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -53,6 +53,11 @@ message Hello {
|
||||
// Test seam (lmxopcua#789): the worker's reader stops reading for good at the first DiagnosticsRequest while its
|
||||
// heartbeats go on, so the host's write-stall check can be exercised against a real worker. Never set in production.
|
||||
bool test_stall_reader_on_diag = 12;
|
||||
// lmxopcua#1064: Scripting:MaxResultElements. A value script's returned sequence is materialised inside the run and
|
||||
// held to this element cap, exactly as the in-process ScriptRunGuard does (ScriptResultMaterializer, #1059) — so a
|
||||
// lazy sequence is enumerated in the worker's run (under its deadlines), and an over-cap result fails the script the
|
||||
// same way in both runners. 0 = the worker's default (ScriptingOptions.DefaultMaxResultElements).
|
||||
uint32 max_result_elements = 13;
|
||||
}
|
||||
|
||||
message Ready {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -39,8 +39,14 @@ public sealed class ScriptResultException : InvalidOperationException
|
||||
/// non-terminating loop are still only contained by the guard's after-the-fact allocation sample and its timeout
|
||||
/// (an orphaned thread). Only <c>Scripting:Runner=OutOfProcess</c> contains those. See docs/VirtualTags.md.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The ONE result rule for both runners (lmxopcua#1064): the in-process <see cref="ScriptRunGuard"/> and the
|
||||
/// out-of-process <c>ScriptWorker</c> both call <see cref="Materialize"/> right after a value script returns,
|
||||
/// inside the run, with the node's <c>Scripting:MaxResultElements</c> (the worker receives it in its
|
||||
/// <c>Hello</c>). Public for that reason only.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class ScriptResultMaterializer
|
||||
public static class ScriptResultMaterializer
|
||||
{
|
||||
/// <summary>Materialises <paramref name="value"/> as described on the type.</summary>
|
||||
/// <param name="value">The script's returned value.</param>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -77,6 +77,7 @@ internal sealed class WorkerHost
|
||||
private int _maxFrameBytes = ScriptWorkerFrameCodec.DefaultMaxFrameBytes;
|
||||
private int _queueCapacity = 4096;
|
||||
private TimeSpan _hardGrace = TimeSpan.FromSeconds(1);
|
||||
private int _maxResultElements = ScriptingOptions.DefaultMaxResultElements;
|
||||
private TimeSpan _heartbeatInterval = TimeSpan.FromSeconds(1);
|
||||
|
||||
/// <summary>
|
||||
@@ -160,6 +161,7 @@ internal sealed class WorkerHost
|
||||
if (hello.HardGraceMs > 0) _hardGrace = TimeSpan.FromMilliseconds(hello.HardGraceMs);
|
||||
if (hello.HeartbeatIntervalMs > 0) _heartbeatInterval = TimeSpan.FromMilliseconds(hello.HeartbeatIntervalMs);
|
||||
if (hello.CompileThreads > 0) _compileThreads = (int)Math.Min(hello.CompileThreads, 64);
|
||||
if (hello.MaxResultElements > 0) _maxResultElements = (int)Math.Min(hello.MaxResultElements, int.MaxValue);
|
||||
_workerSoftClock = hello.WorkerSoftClock;
|
||||
_testStallReaderOnDiag = hello.TestStallReaderOnDiag;
|
||||
// lmxopcua#1014: no PE-cache key or directory any more — the host verifies, compiles and signs, and sends a
|
||||
@@ -458,6 +460,11 @@ internal sealed class WorkerHost
|
||||
try
|
||||
{
|
||||
object? value = script.Run(inputs, logger, clock, cts.Token, out var isPredicate);
|
||||
// lmxopcua#1064: the in-process guard's result rule (#1059), applied here too and still inside the run —
|
||||
// this eval is registered with the watchdog and its allocation sample is still open — so a returned lazy
|
||||
// sequence is enumerated under the run's deadlines and held to Scripting:MaxResultElements, and an
|
||||
// over-cap or open-slot sequence fails the script with the same message in both runners.
|
||||
if (!isPredicate) value = ScriptResultMaterializer.Materialize(value, _maxResultElements);
|
||||
if (isPredicate)
|
||||
{
|
||||
result.Predicate = (bool)value!;
|
||||
|
||||
Reference in New Issue
Block a user