fix(editor): #1025 analyse scripted-alarm predicates as bool Run(AlarmPredicateContext) — predicate mode on the analysis endpoints, Monaco and the ScriptEdit page
This commit is contained in:
@@ -75,8 +75,19 @@ else
|
||||
<section class="panel rise mt-3">
|
||||
<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.
|
||||
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.AlarmPredicate">Scripted-alarm predicate (must return bool)</option>
|
||||
</select>
|
||||
</div>
|
||||
<MonacoEditor @key="presentation" @ref="_editor" Value="@_form.SourceCode" ValueChanged="value => ChangeSource(value, presentation, form)" Height="420px"
|
||||
AriaLabel="Script source code" ReadOnly="@_busy" MarkersChanged="report => OnMarkersChanged(report, presentation)" />
|
||||
AriaLabel="Script source code" ReadOnly="@_busy" Mode="@_mode" MarkersChanged="report => OnMarkersChanged(report, presentation)" />
|
||||
<ScriptProblemsList Report="_markers" OnSelect="marker => RevealProblemAsync(marker, presentation)" />
|
||||
<div class="form-text">SHA-256 hash is computed automatically on save.</div>
|
||||
</div>
|
||||
@@ -114,6 +125,7 @@ else
|
||||
private string _deleteMessage = "";
|
||||
private DeleteIntent? _deleteIntent;
|
||||
private MonacoEditor? _editor;
|
||||
private string _mode = ScriptAnalysisModes.Value;
|
||||
private ScriptProblemReport _markers = ScriptProblemReport.Empty;
|
||||
private sealed record DeleteIntent(string Id, byte[] RowVersion);
|
||||
|
||||
@@ -126,6 +138,10 @@ else
|
||||
{
|
||||
if (Current(generation) && !_busy && ReferenceEquals(form, _form)) form.SourceCode = value;
|
||||
}
|
||||
private void ChangeMode(string? value, long generation)
|
||||
{
|
||||
if (Current(generation)) _mode = ScriptAnalysisModes.IsPredicate(value) ? ScriptAnalysisModes.AlarmPredicate : ScriptAnalysisModes.Value;
|
||||
}
|
||||
private void OnMarkersChanged(ScriptProblemReport report, long generation)
|
||||
{
|
||||
if (Current(generation)) _markers = report;
|
||||
@@ -143,7 +159,7 @@ else
|
||||
++_confirmationEpoch;
|
||||
_loaded = _busy = _confirmDeleteVisible = false;
|
||||
_existing = null; _editor = null; _deleteIntent = null;
|
||||
_form = new(); _markers = ScriptProblemReport.Empty; _error = _loadError = null;
|
||||
_form = new(); _mode = ScriptAnalysisModes.Value; _markers = ScriptProblemReport.Empty; _error = _loadError = null;
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrEmpty(id))
|
||||
@@ -153,6 +169,12 @@ else
|
||||
var existing = await db.Scripts.AsNoTracking().FirstOrDefaultAsync(s => s.ScriptId == id);
|
||||
if (!Current(generation)) return;
|
||||
_existing = existing;
|
||||
if (existing is not null)
|
||||
{
|
||||
var usage = await ZB.MOM.WW.OtOpcUa.AdminUI.Uns.ScriptUsage.ClassifyAsync(db, id);
|
||||
if (!Current(generation)) return;
|
||||
_mode = usage.DefaultMode;
|
||||
}
|
||||
if (existing is not null)
|
||||
_form = new FormModel { ScriptId = existing.ScriptId, Name = existing.Name,
|
||||
SourceCode = existing.SourceCode, RowVersion = existing.RowVersion.ToArray() };
|
||||
|
||||
@@ -53,6 +53,13 @@
|
||||
/// </summary>
|
||||
[Parameter] public string? EquipmentId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Which seam the script is analysed as (<see cref="ScriptAnalysisModes"/>; lmxopcua#1025): null/<c>value</c> for a
|
||||
/// VirtualTag / Calculation script, <c>alarmPredicate</c> for a scripted-alarm predicate (must return <c>bool</c>).
|
||||
/// Changing it re-analyses the live editor.
|
||||
/// </summary>
|
||||
[Parameter] public string? Mode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Fires whenever Monaco's diagnostic marker set updates (after the 500 ms debounce, and only for the response
|
||||
/// to the CURRENT text — superseded responses are dropped in the JS). Feeds <c>ScriptProblemsList</c>; the
|
||||
@@ -67,6 +74,7 @@
|
||||
private readonly string _id = Guid.NewGuid().ToString("N");
|
||||
private string _lastSentValue = "";
|
||||
private string _lastSentAriaLabel = "";
|
||||
private string? _lastSentMode;
|
||||
private bool _lastSentReadOnly;
|
||||
private string AccessibleLabel => string.IsNullOrWhiteSpace(AriaLabel) ? "Code editor" : AriaLabel;
|
||||
private bool _disposed;
|
||||
@@ -86,6 +94,7 @@
|
||||
_lastSentValue = Value ?? "";
|
||||
var createdLabel = AccessibleLabel;
|
||||
var createdReadOnly = ReadOnly;
|
||||
var createdMode = Mode;
|
||||
_initializing = true;
|
||||
try
|
||||
{
|
||||
@@ -100,6 +109,7 @@
|
||||
language = Language,
|
||||
readOnly = createdReadOnly,
|
||||
equipmentId = EquipmentId,
|
||||
mode = Mode,
|
||||
maxSyncBytes = ScriptEditorLimits.MaxEditorSyncBytes,
|
||||
reportMarkers = MarkersChanged.HasDelegate,
|
||||
maxReportedMarkers = ScriptEditorLimits.MaxReportedMarkers,
|
||||
@@ -110,6 +120,7 @@
|
||||
_initialized = true;
|
||||
_lastSentAriaLabel = createdLabel;
|
||||
_lastSentReadOnly = createdReadOnly;
|
||||
_lastSentMode = createdMode;
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
@@ -137,6 +148,11 @@
|
||||
_lastSentReadOnly = ReadOnly;
|
||||
await SafeInvokeAsync("MonacoBlazor.setEditorOption", "set editor read-only state", _id, "readOnly", _lastSentReadOnly);
|
||||
}
|
||||
if (!_disposed && _initialized && !string.Equals(Mode, _lastSentMode, StringComparison.Ordinal))
|
||||
{
|
||||
_lastSentMode = Mode;
|
||||
await SafeInvokeAsync("MonacoBlazor.setMode", "set script analysis mode", _id, _lastSentMode);
|
||||
}
|
||||
if (!_disposed && _initialized && AccessibleLabel != _lastSentAriaLabel)
|
||||
{
|
||||
_lastSentAriaLabel = AccessibleLabel;
|
||||
|
||||
@@ -1,22 +1,43 @@
|
||||
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"/>.
|
||||
/// </summary>
|
||||
public static class ScriptAnalysisModes
|
||||
{
|
||||
/// <summary>A VirtualTag / Calculation 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>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);
|
||||
}
|
||||
|
||||
// EquipmentId (optional) carries the owning-equipment context the {{equip}}/<RefName> completion +
|
||||
// diagnostic need to resolve reference effective names. Null on the shared ScriptEdit page (no single
|
||||
// equipment) — the equip-ref features are then inert, matching the deploy gate (which only resolves per
|
||||
// owning equipment).
|
||||
public record DiagnoseRequest(string Code, string? EquipmentId = null);
|
||||
// owning equipment). Mode (optional) selects the seam the script is analysed as — see ScriptAnalysisModes.
|
||||
public record DiagnoseRequest(string Code, string? EquipmentId = null, string? Mode = null);
|
||||
public record DiagnoseResponse(IReadOnlyList<DiagnosticMarker> Markers);
|
||||
public record DiagnosticMarker(int Severity, int StartLineNumber, int StartColumn,
|
||||
int EndLineNumber, int EndColumn, string Message, string Code);
|
||||
|
||||
public record CompletionsRequest(string CodeText, int Line, int Column, string? EquipmentId = null);
|
||||
public record CompletionsRequest(string CodeText, int Line, int Column, string? EquipmentId = null, string? Mode = null);
|
||||
public record CompletionsResponse(IReadOnlyList<CompletionItem> Items);
|
||||
public record CompletionItem(string Label, string InsertText, string Detail, string Kind, int InsertTextRules = 0);
|
||||
|
||||
public record HoverRequest(string CodeText, int Line, int Column, string? EquipmentId = null);
|
||||
public record HoverRequest(string CodeText, int Line, int Column, string? EquipmentId = null, string? Mode = null);
|
||||
public record HoverResponse(string? Markdown);
|
||||
|
||||
public record SignatureHelpRequest(string CodeText, int Line, int Column);
|
||||
public record SignatureHelpRequest(string CodeText, int Line, int Column, string? Mode = null);
|
||||
public record SignatureHelpResponse(string? Label, IReadOnlyList<SignatureHelpParameter>? Parameters, int ActiveParameter);
|
||||
public record SignatureHelpParameter(string Label, string? Documentation);
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.VirtualTags;
|
||||
|
||||
@@ -27,8 +28,6 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;
|
||||
/// </remarks>
|
||||
public sealed class ScriptAnalysisService
|
||||
{
|
||||
private static readonly SandboxConfig Sandbox = ScriptSandbox.Build(typeof(VirtualTagContext));
|
||||
private static readonly string Preamble = BuildPreamble();
|
||||
private static readonly CSharpCompilationOptions CompileOptions = new(
|
||||
OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release,
|
||||
allowUnsafe: false, warningLevel: 4, nullableContextOptions: NullableContextOptions.Enable);
|
||||
@@ -44,52 +43,66 @@ public sealed class ScriptAnalysisService
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
// Mirrors ScriptEvaluator's wrapper EXACTLY (usings from the sandbox + the
|
||||
// Run(ScriptGlobals<VirtualTagContext>) shape), except the analysis return type is
|
||||
// `object` so a shared script stays valid regardless of any virtual tag's DataType.
|
||||
private static string BuildPreamble()
|
||||
{
|
||||
var usings = string.Join("\n", Sandbox.Imports.Select(i => $"using {i};"));
|
||||
var globalsType = $"global::{typeof(ScriptGlobals<>).Namespace}.ScriptGlobals<global::{typeof(VirtualTagContext).FullName}>";
|
||||
return usings + "\n\n"
|
||||
+ "namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;\n"
|
||||
+ "public static class CompiledScript\n{\n"
|
||||
+ $" public static object Run({globalsType} globals)\n {{\n"
|
||||
+ " var ctx = globals.ctx;\n#line 1\n";
|
||||
}
|
||||
|
||||
private static SyntaxTree WrapAndParse(string userSource, CancellationToken ct)
|
||||
=> CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + "\n }\n}\n", cancellationToken: ct);
|
||||
|
||||
/// <summary>
|
||||
/// The process-wide compilation every analysis derives from. Its sandbox reference set is bound ONCE
|
||||
/// (forced here by resolving <c>System.Object</c>); <see cref="CSharpCompilation.ReplaceSyntaxTree"/> keeps
|
||||
/// that binding, so a request only re-binds the user's tree instead of the whole reference set. It is
|
||||
/// immutable, so sharing it across circuits and requests is thread-safe.
|
||||
/// One analysis shape (lmxopcua#1025): the sandbox + wrapper the deploy gate compiles a seam's script with, and
|
||||
/// the process-wide <see cref="BaseCompilation"/> every analysis of that seam derives from. Its sandbox reference
|
||||
/// set is bound ONCE (forced by resolving <c>System.Object</c>); <see cref="CSharpCompilation.ReplaceSyntaxTree"/>
|
||||
/// keeps that binding, so a request only re-binds the user's tree. Immutable, so shared across circuits/requests.
|
||||
/// </summary>
|
||||
internal static readonly CSharpCompilation BaseCompilation = CreateBaseCompilation();
|
||||
|
||||
private static CSharpCompilation CreateBaseCompilation()
|
||||
private sealed class Shape
|
||||
{
|
||||
var compilation = CSharpCompilation.Create(
|
||||
"ScriptAnalysis", new[] { WrapAndParse("", CancellationToken.None) }, Sandbox.References, CompileOptions);
|
||||
_ = compilation.GetSpecialType(SpecialType.System_Object);
|
||||
return compilation;
|
||||
public Shape(Type contextType, string returnType)
|
||||
{
|
||||
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";
|
||||
var compilation = CSharpCompilation.Create(
|
||||
"ScriptAnalysis", new[] { Parse("", CancellationToken.None) }, Sandbox.References, CompileOptions);
|
||||
_ = compilation.GetSpecialType(SpecialType.System_Object);
|
||||
BaseCompilation = compilation;
|
||||
}
|
||||
|
||||
public SandboxConfig Sandbox { get; }
|
||||
public string Preamble { get; }
|
||||
public CSharpCompilation BaseCompilation { get; }
|
||||
|
||||
public SyntaxTree Parse(string userSource, CancellationToken ct)
|
||||
=> CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + "\n }\n}\n", cancellationToken: ct);
|
||||
}
|
||||
|
||||
private static readonly Shape ValueShape = new(typeof(VirtualTagContext), "object");
|
||||
private static readonly Shape PredicateShape = new(typeof(AlarmPredicateContext), "bool");
|
||||
|
||||
private static Shape ShapeFor(string? mode) => ScriptAnalysisModes.IsPredicate(mode) ? PredicateShape : ValueShape;
|
||||
|
||||
/// <summary>The process-wide value-shape compilation (test seam; the predicate shape has its own).</summary>
|
||||
internal static CSharpCompilation BaseCompilation => ValueShape.BaseCompilation;
|
||||
|
||||
// userSource is appended after Preamble, then the method/class are closed. Every analysis derives straight
|
||||
// from the shared BaseCompilation: the analysis endpoints are minimal-API handlers, so a scoped service lives
|
||||
// for one HTTP request and a per-instance lineage would never be more than one step long.
|
||||
private static (SyntaxTree Tree, CSharpCompilation Compilation, SemanticModel Model, int PreambleLength) Analyze(
|
||||
string userSource, CancellationToken ct)
|
||||
string userSource, string? mode, CancellationToken ct)
|
||||
{
|
||||
var tree = WrapAndParse(userSource, ct);
|
||||
var compilation = BaseCompilation.ReplaceSyntaxTree(BaseCompilation.SyntaxTrees[0], tree);
|
||||
return (tree, compilation, compilation.GetSemanticModel(tree), Preamble.Length);
|
||||
var shape = ShapeFor(mode);
|
||||
var tree = shape.Parse(userSource, ct);
|
||||
var compilation = shape.BaseCompilation.ReplaceSyntaxTree(shape.BaseCompilation.SyntaxTrees[0], tree);
|
||||
return (tree, compilation, compilation.GetSemanticModel(tree), shape.Preamble.Length);
|
||||
}
|
||||
|
||||
/// <summary>Test seam: the compilation one analysis of <paramref name="userSource"/> runs against.</summary>
|
||||
internal CSharpCompilation CompilationFor(string userSource) => Analyze(Normalize(userSource), CancellationToken.None).Compilation;
|
||||
/// <param name="userSource">The script source.</param>
|
||||
/// <param name="mode">The analysis mode (<see cref="ScriptAnalysisModes"/>); null = value.</param>
|
||||
internal CSharpCompilation CompilationFor(string userSource, string? mode = null)
|
||||
=> Analyze(Normalize(userSource), mode, CancellationToken.None).Compilation;
|
||||
|
||||
// editor (line,col) in USER-source coords -> physical offset in the wrapped document
|
||||
private static int OffsetInWrapped(string userSource, int line, int column, int preambleLength)
|
||||
@@ -121,7 +134,7 @@ public sealed class ScriptAnalysisService
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var code = Normalize(req.Code);
|
||||
var (tree, compilation, _, preambleLength) = Analyze(code, ct);
|
||||
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
|
||||
@@ -152,7 +165,9 @@ public sealed class ScriptAnalysisService
|
||||
// (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))
|
||||
markers.Add(ToMarker(tree.GetMappedLineSpan(inv.Span), 4, SetVirtualTagInertMessage, "OTSCRIPT_SETVTAG_INERT"));
|
||||
markers.Add(ToMarker(tree.GetMappedLineSpan(inv.Span), 4,
|
||||
ScriptAnalysisModes.IsPredicate(req.Mode) ? SetVirtualTagPredicateMessage : SetVirtualTagInertMessage,
|
||||
"OTSCRIPT_SETVTAG_INERT"));
|
||||
|
||||
return new DiagnoseResponse(Bound(markers));
|
||||
}
|
||||
@@ -228,6 +243,10 @@ public sealed class ScriptAnalysisService
|
||||
: m with { Message = ScriptProblems.Truncate(m.Message, ScriptEditorLimits.MaxDiagnosticMessageChars) })
|
||||
.ToList();
|
||||
|
||||
private const string SetVirtualTagPredicateMessage =
|
||||
"ctx.SetVirtualTag(...) throws in a scripted-alarm predicate: predicates must be side-effect free. The script " +
|
||||
"compiles and publishes, but every evaluation fails — move the write into a virtual tag the predicate reads.";
|
||||
|
||||
private const string SetVirtualTagInertMessage =
|
||||
"ctx.SetVirtualTag(...) has no effect at runtime: cross-tag writes are dropped in single-tag mode (the " +
|
||||
"cascade engine is not wired into the host). The script compiles and publishes, but this write will not " +
|
||||
@@ -282,7 +301,7 @@ public sealed class ScriptAnalysisService
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var code = Normalize(req.CodeText);
|
||||
var (tree, _, model, preambleLength) = Analyze(code, ct);
|
||||
var (tree, _, model, preambleLength) = Analyze(code, req.Mode, ct);
|
||||
var position = OffsetInWrapped(code, req.Line, req.Column, preambleLength);
|
||||
var root = await tree.GetRootAsync(ct);
|
||||
// position is the offset just AFTER the caret; -1 finds the token the caret sits at/just-after (e.g. the dot in "ctx.").
|
||||
@@ -402,7 +421,7 @@ public sealed class ScriptAnalysisService
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var code = Normalize(req.CodeText);
|
||||
var (tree, _, model, preambleLength) = Analyze(code, ct);
|
||||
var (tree, _, model, preambleLength) = Analyze(code, req.Mode, ct);
|
||||
var position = OffsetInWrapped(code, req.Line, req.Column, preambleLength);
|
||||
var token = tree.GetRoot(ct).FindToken(Math.Max(0, position - 1));
|
||||
|
||||
@@ -504,7 +523,7 @@ public sealed class ScriptAnalysisService
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var code = Normalize(req.CodeText);
|
||||
var (tree, _, model, preambleLength) = Analyze(code, ct);
|
||||
var (tree, _, model, preambleLength) = Analyze(code, req.Mode, ct);
|
||||
var position = OffsetInWrapped(code, req.Line, req.Column, preambleLength);
|
||||
var token = tree.GetRoot(ct).FindToken(Math.Max(0, position - 1));
|
||||
|
||||
|
||||
@@ -21,6 +21,42 @@ public static class ScriptUsage
|
||||
/// <summary>How many using rows are named in the refusal before it summarises the rest.</summary>
|
||||
private const int NamedLimit = 5;
|
||||
|
||||
/// <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)
|
||||
{
|
||||
/// <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.
|
||||
/// </summary>
|
||||
public string DefaultMode =>
|
||||
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>
|
||||
/// <param name="db">The config context.</param>
|
||||
/// <param name="scriptId">The script.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>Where the script is used.</returns>
|
||||
public static async Task<SeamUsage> ClassifyAsync(OtOpcUaConfigDbContext db, string scriptId, CancellationToken ct = default)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes every row that references <paramref name="scriptId"/>, or returns <see langword="null"/> when
|
||||
/// nothing does and the script may be deleted.
|
||||
|
||||
@@ -52,6 +52,9 @@
|
||||
// registered csharp providers (which only receive the model) can thread it into the {{equip}}/<RefName>
|
||||
// completion + diagnostics. Null on the shared ScriptEdit page (equip-ref features inert there).
|
||||
function equipmentIdOf(model) { return (model && model.__otEquipmentId) || null; }
|
||||
// The analysis mode (#1025): "alarmPredicate" analyses the script as a scripted-alarm predicate (bool Run), anything
|
||||
// else as a value script. Stamped on the model like the equipment id; changeable later via setMode.
|
||||
function modeOf(model) { return (model && model.__otMode) || null; }
|
||||
|
||||
function registerCSharpProviders() {
|
||||
monaco.languages.registerCompletionItemProvider("csharp", {
|
||||
@@ -59,7 +62,7 @@
|
||||
provideCompletionItems: async function (model, position, context, token) {
|
||||
try {
|
||||
const data = await postAnalysis("completions",
|
||||
{ codeText: model.getValue(), line: position.lineNumber, column: position.column, equipmentId: equipmentIdOf(model) },
|
||||
{ codeText: model.getValue(), line: position.lineNumber, column: position.column, equipmentId: equipmentIdOf(model), mode: modeOf(model) },
|
||||
token);
|
||||
if (!data) return { suggestions: [] };
|
||||
const word = model.getWordUntilPosition(position);
|
||||
@@ -97,7 +100,7 @@
|
||||
provideHover: async function (model, position, token) {
|
||||
try {
|
||||
const data = await postAnalysis("hover",
|
||||
{ codeText: model.getValue(), line: position.lineNumber, column: position.column, equipmentId: equipmentIdOf(model) },
|
||||
{ codeText: model.getValue(), line: position.lineNumber, column: position.column, equipmentId: equipmentIdOf(model), mode: modeOf(model) },
|
||||
token);
|
||||
if (!data || !data.markdown) return null;
|
||||
return { contents: [{ value: data.markdown }] };
|
||||
@@ -119,7 +122,7 @@
|
||||
provideSignatureHelp: async function (model, position, token) {
|
||||
try {
|
||||
const data = await postAnalysis("signature-help",
|
||||
{ codeText: model.getValue(), line: position.lineNumber, column: position.column },
|
||||
{ codeText: model.getValue(), line: position.lineNumber, column: position.column, mode: modeOf(model) },
|
||||
token);
|
||||
if (!data || !data.label) return null;
|
||||
return {
|
||||
@@ -145,7 +148,7 @@
|
||||
const resp = await fetch("/api/script-analysis/diagnostics", {
|
||||
method: "POST", credentials: "same-origin", signal: signal,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ code: model.getValue(), equipmentId: equipmentIdOf(model) })
|
||||
body: JSON.stringify({ code: model.getValue(), equipmentId: equipmentIdOf(model), mode: modeOf(model) })
|
||||
});
|
||||
if (!resp.ok) return [];
|
||||
const data = await resp.json();
|
||||
@@ -257,7 +260,7 @@
|
||||
});
|
||||
// Stamp the owning-equipment id on the model so the global csharp providers can thread it into the
|
||||
// {{equip}}/<RefName> completion + diagnostics (null on the shared ScriptEdit page).
|
||||
try { const m0 = editor.getModel(); if (m0) m0.__otEquipmentId = options.equipmentId || null; } catch (x) {}
|
||||
try { const m0 = editor.getModel(); if (m0) { m0.__otEquipmentId = options.equipmentId || null; m0.__otMode = options.mode || null; } } catch (x) {}
|
||||
const e = {
|
||||
editor: editor, dotNetRef: dotNetRef, dirty: false,
|
||||
maxSyncBytes: options.maxSyncBytes || 0, reportMarkers: !!options.reportMarkers,
|
||||
@@ -296,6 +299,13 @@
|
||||
editors[id] = e;
|
||||
if (options.language === "csharp") e.scheduleDiagnostics();
|
||||
}
|
||||
// Switches the analysis mode of a live editor (#1025) and re-runs diagnostics so the markers match the new seam.
|
||||
function setMode(id, mode) {
|
||||
const e = editors[id]; if (!e) return;
|
||||
const model = e.editor.getModel(); if (!model) return;
|
||||
model.__otMode = mode || null;
|
||||
if (e.scheduleDiagnostics) e.scheduleDiagnostics();
|
||||
}
|
||||
function setEditorOption(id, name, value) {
|
||||
const e = editors[id]; if (!e) return;
|
||||
// Note: monaco.editor.setTheme is global — it re-themes every editor on the page, not just this id.
|
||||
@@ -331,5 +341,5 @@
|
||||
delete editors[id];
|
||||
}
|
||||
|
||||
window.MonacoBlazor = { createEditor, setValue, getValue, setMarkers, setEditorOption, format, revealLine, dispose };
|
||||
window.MonacoBlazor = { createEditor, setMode, setValue, getValue, setMarkers, setEditorOption, format, revealLine, dispose };
|
||||
})();
|
||||
|
||||
Reference in New Issue
Block a user