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>
|
||||
|
||||
Reference in New Issue
Block a user