fix(template-engine): validate CallShared/CallScript parameters object by name (#150)

The semantic validator treated each comma-separated argument after the
script name as a positional parameter and required the count to equal the
declared ParameterDefinitions. The runtime has no positional form: both
calls take ONE parameters object that ScriptArgs.Normalize turns into a
name -> value dictionary, so every Scripts.CallShared("X", new { ... })
was rejected unless exactly one parameter was declared, blocking deploy.

Call sites are now found with a Roslyn script-mode syntax parse (named
arguments and a trailing CancellationToken handled; calls in comments or
strings ignored). The parameters argument is classified as:
- anonymous object: validated by name (ordinal) - missing required
  parameter = error, undeclared member = warning, clear literal type
  mismatch per member = error (same conservative inference as before);
- any other expression (variable, dictionary, call, null): not checked;
- absent: error only if the target declares required parameters.

Required-ness comes from the shared InboundApiSchema parser (JSON Schema
'required' list; legacy array entries required unless required:false).
Positional-argument tests replaced by by-name CallShared/CallScript tests;
Component-TemplateEngine.md updated.
This commit is contained in:
Joseph Doherty
2026-11-28 06:55:58 -05:00
parent a4523e090e
commit 607ffc2e15
3 changed files with 525 additions and 528 deletions
@@ -310,7 +310,7 @@ Before a deployment is sent to a site, the Template Engine performs comprehensiv
Beyond compilation, the Template Engine performs static semantic checks:
- **Script call targets**: `Instance.CallScript()` and `Scripts.CallShared()` targets must reference scripts that exist in the flattened configuration or shared script library.
- **Argument compatibility**: Parameter count and data types at call sites must match the target script's parameter definitions.
- **Argument compatibility** (`ValidationCategory.ParameterMismatch`): `CallScript`/`CallShared` take one parameters object (anonymous object or dictionary, normalized by `ScriptArgs` into a name → value dictionary — there is no positional form), so call sites are checked by **name** (ScadaBridge#150). When the parameters argument is an anonymous object (`new { A = 1, B = x }`), every required declared parameter must be present (error), a member the target does not declare is a **warning**, and a member whose literal value clearly mismatches the declared type is an error (non-literal values are never type-flagged). Any other parameters expression (a variable, dictionary, method call, `null`) is not checked. A call with no parameters argument against a target that declares required parameters is an error. A trailing `CancellationToken` argument is ignored. Call sites are located with a Roslyn syntax parse, so calls inside comments or strings are not validated.
- **Return type compatibility**: If a script call's return value is used, the return type definition must match the caller's expectations.
- **Trigger operand types**: Alarm triggers and script conditional triggers must reference attributes with compatible data types (e.g., Range Violation requires numeric attributes).
- **Native alarm sources** (`ValidationCategory.NativeAlarmSourceInvalid`): `SemanticValidator.Validate` flags a `ResolvedNativeAlarmSource` when its `SourceReference` is empty, its `ConnectionName` is empty, or — when the caller supplies the alarm-capable connection set — its connection is unknown or not alarm-capable (protocol ∉ {`OpcUa`, `MxGateway`}). The alarm-capable connection set is an **optional, additive third parameter** to `Validate`; the empty-field checks always run, and the connection-binding check runs only when the set is provided.
@@ -1,5 +1,9 @@
using System.Text.Json;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using ZB.MOM.WW.ScadaBridge.Commons.Types;
using ZB.MOM.WW.ScadaBridge.Commons.Types.InboundApi;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
@@ -8,7 +12,8 @@ namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
/// <summary>
/// Semantic validation rules for a FlattenedConfiguration:
/// - CallScript/CallShared targets must reference existing scripts
/// - Parameter count and types must match
/// - The parameters object must supply every required declared parameter
/// (validated by name when it is an anonymous object; see ValidateCallParameters)
/// - Return type compatibility
/// - Trigger operand types: RangeViolation requires numeric attribute
/// - On-trigger script must exist
@@ -46,8 +51,8 @@ public class SemanticValidator
// literal leaf "Y"; the actual flattened script is the composed canonical
// "X.Y". Since the child segment is dynamic it cannot be statically resolved,
// so we accept the call as existing when ANY composed script has that leaf
// name. The positional arg-count/type checks already self-skip for these
// (their canonical name "X.Y" is not the literal key "Y" in the param map).
// name. The parameter checks already self-skip for these (their canonical
// name "X.Y" is not the literal key "Y" in the param map).
var composedLeafNames = new HashSet<string>(
configuration.Scripts
.Select(s => s.CanonicalName)
@@ -101,7 +106,7 @@ public class SemanticValidator
}
else
{
ValidateCallParameters(script.CanonicalName, call, sharedParamMap, errors);
ValidateCallParameters(script.CanonicalName, call, sharedParamMap, errors, warnings);
ValidateCallReturnType(script.CanonicalName, call, sharedReturnMap, errors);
}
}
@@ -131,7 +136,7 @@ public class SemanticValidator
script.CanonicalName));
}
ValidateCallParameters(script.CanonicalName, call, scriptParamMap, errors);
ValidateCallParameters(script.CanonicalName, call, scriptParamMap, errors, warnings);
ValidateCallReturnType(script.CanonicalName, call, scriptReturnMap, errors);
// Instance scripts cannot call alarm on-trigger scripts
@@ -358,76 +363,120 @@ public class SemanticValidator
}
}
/// <summary>
/// Parameter validation for a <c>CallScript</c>/<c>CallShared</c> call site.
/// The runtime has no positional form: both methods take ONE
/// <c>parameters</c> object which <see cref="ScriptArgs.Normalize"/> turns into
/// a name → value dictionary (ScadaBridge#150). So the check depends on what
/// that one argument is:
/// <list type="bullet">
/// <item><b>Absent</b> — the target receives no parameters; any REQUIRED
/// declared parameter is an error.</item>
/// <item><b>Anonymous object</b> (<c>new { A = 1, B = x }</c>) — validated by
/// NAME (ordinal, as the runtime dictionary is): a missing required parameter
/// is an error, a member the target does not declare is a warning, and a
/// member whose literal type clearly mismatches the declared type is an
/// error (same conservative inference as before — non-literals are never
/// flagged).</item>
/// <item><b>Anything else</b> (a variable, dictionary, method call,
/// <c>null</c>, …) — its keys can't be known statically, so nothing is
/// checked.</item>
/// </list>
/// </summary>
private static void ValidateCallParameters(
string callerName,
CallTarget call,
Dictionary<string, List<string>> paramMap,
List<ValidationEntry> errors)
Dictionary<string, IReadOnlyList<InboundApiSchemaField>> paramMap,
List<ValidationEntry> errors,
List<ValidationEntry> warnings)
{
if (!paramMap.TryGetValue(call.TargetName, out var expectedParams))
return;
if (!paramMap.TryGetValue(call.TargetName, out var declared))
return; // Target's definitions unknown/unparseable — don't guess.
if (call.ArgumentCount != expectedParams.Count)
switch (call.ParametersKind)
{
errors.Add(ValidationEntry.Error(ValidationCategory.ParameterMismatch,
$"Script '{callerName}' calls '{call.TargetName}' with {call.ArgumentCount} arguments but {expectedParams.Count} are expected.",
callerName));
// Count mismatch already reported — positional type matching below
// would be misaligned, so don't compound the noise.
return;
case CallParametersKind.None:
{
var missing = declared.Where(f => f.Required).Select(f => f.Name).ToList();
if (missing.Count > 0)
{
errors.Add(ValidationEntry.Error(ValidationCategory.ParameterMismatch,
$"Script '{callerName}' calls '{call.TargetName}' without a parameters object, but '{call.TargetName}' requires {FormatNames(missing)}.",
callerName));
}
return;
}
case CallParametersKind.Opaque:
return;
case CallParametersKind.AnonymousObject:
break;
default:
return;
}
ValidateArgumentTypes(callerName, call, expectedParams, errors);
}
var declaredByName = new Dictionary<string, InboundApiSchemaField>(StringComparer.Ordinal);
foreach (var field in declared)
declaredByName.TryAdd(field.Name, field);
/// <summary>
/// Argument-type validation. Compares each positionally-matched call
/// argument expression against the target's declared parameter type and
/// flags only CLEAR cross-category mismatches.
///
/// Conservatism (false-positive avoidance) — a parameter is checked only
/// when BOTH sides are confidently known:
/// <list type="bullet">
/// <item>Declared type must normalize to a known primitive (String, Integer,
/// Float, Boolean). <c>Object</c>/<c>List</c>/unknown declarations accept
/// anything — never flagged.</item>
/// <item>Argument expression type must be inferable from a literal
/// (string/char, integer, decimal, <c>true</c>/<c>false</c>). Variables,
/// member access, method/await chains, <c>null</c>, casts, object/array
/// initializers, and anything else infer to Unknown and are never flagged.</item>
/// <item>Integer⇄Float is treated as compatible (numeric widening) — never
/// flagged.</item>
/// </list>
/// </summary>
private static void ValidateArgumentTypes(
string callerName,
CallTarget call,
List<string> expectedParams,
List<ValidationEntry> errors)
{
// Argument expressions are aligned 1:1 with parameters here (count was
// verified equal by the caller). If the argument text couldn't be split
// (e.g. it wasn't captured), skip silently.
if (call.ArgumentExpressions.Count != expectedParams.Count)
return;
// A member whose name couldn't be determined (not valid C# for an
// anonymous type anyway) makes the supplied-name set incomplete, so the
// missing-required check would be a guess — skip it in that case.
var allNamesKnown = call.ParameterMembers.All(m => m.Name is not null);
var supplied = new HashSet<string>(
call.ParameterMembers.Where(m => m.Name is not null).Select(m => m.Name!),
StringComparer.Ordinal);
for (var i = 0; i < expectedParams.Count; i++)
if (allNamesKnown)
{
var declared = NormalizeType(expectedParams[i]);
if (declared is null)
continue; // Object/List/unknown declaration accepts anything.
var actual = InferLiteralType(call.ArgumentExpressions[i]);
if (actual is null)
continue; // Can't confidently infer the argument's type.
if (!IsAssignable(actual.Value, declared.Value))
var missing = declared
.Where(f => f.Required && !supplied.Contains(f.Name))
.Select(f => f.Name)
.ToList();
if (missing.Count > 0)
{
errors.Add(ValidationEntry.Error(ValidationCategory.ParameterMismatch,
$"Script '{callerName}' calls '{call.TargetName}' argument {i + 1} with type '{actual}' but parameter '{expectedParams[i]}' expects '{declared}'.",
$"Script '{callerName}' calls '{call.TargetName}' without required {FormatNames(missing)}.",
callerName));
}
}
foreach (var member in call.ParameterMembers)
{
if (member.Name is null)
continue;
if (!declaredByName.TryGetValue(member.Name, out var field))
{
// Not an error: the runtime passes the extra entry through and the
// target simply never reads it. Most likely a typo, so warn.
warnings.Add(ValidationEntry.Warning(ValidationCategory.ParameterMismatch,
$"Script '{callerName}' passes parameter '{member.Name}' to '{call.TargetName}', which does not declare it.",
callerName));
continue;
}
var expected = NormalizeType(field.Schema.Type);
if (expected is null)
continue; // object/array/unknown declaration accepts anything.
var actual = InferLiteralType(member.Expression);
if (actual is null)
continue; // Can't confidently infer the member's type.
if (!IsAssignable(actual.Value, expected.Value))
{
errors.Add(ValidationEntry.Error(ValidationCategory.ParameterMismatch,
$"Script '{callerName}' calls '{call.TargetName}' with parameter '{member.Name}' of type '{actual}' but it expects '{expected}'.",
callerName));
}
}
static string FormatNames(List<string> names) =>
(names.Count == 1 ? "parameter " : "parameters ")
+ string.Join(", ", names.Select(n => $"'{n}'"));
}
/// <summary>
@@ -478,64 +527,46 @@ public class SemanticValidator
}
}
private static Dictionary<string, List<string>> BuildParameterMap(IReadOnlyList<ResolvedScript> scripts)
private static Dictionary<string, IReadOnlyList<InboundApiSchemaField>> BuildParameterMap(IReadOnlyList<ResolvedScript> scripts)
{
var result = new Dictionary<string, List<string>>(StringComparer.Ordinal);
var result = new Dictionary<string, IReadOnlyList<InboundApiSchemaField>>(StringComparer.Ordinal);
foreach (var script in scripts)
{
// Per-parameter declared TYPE in declared order (raw type strings).
// One entry per parameter, so the existing count check is preserved
// and positional matching has the types it needs.
var parameters = ParseParameterTypes(script.ParameterDefinitions);
result[script.CanonicalName] = parameters;
// An unparseable definition leaves the target out of the map, so its
// call sites are not parameter-checked (never a false positive).
var parameters = ParseParameterFields(script.ParameterDefinitions);
if (parameters is not null)
result[script.CanonicalName] = parameters;
}
return result;
}
/// <summary>
/// Parses a parameter definitions JSON string (JSON Schema or legacy flat
/// array) and returns the declared parameter TYPE for each parameter, in
/// declared order. Names are not needed for positional call validation; the
/// returned count equals the parameter count (preserving the count check).
/// Parses a parameter definitions JSON string (JSON Schema object form, or
/// the legacy flat <c>[{name,type,required}]</c> array) into its declared
/// fields — name, required flag and type — via the shared
/// <see cref="InboundApiSchema"/> parser, so "required" means exactly what it
/// means everywhere else (JSON Schema: listed in <c>required</c>; legacy:
/// required unless <c>required</c> is explicitly false).
/// </summary>
/// <param name="parameterDefinitionsJson">JSON Schema or legacy flat-array string; null/empty returns an empty list.</param>
/// <returns>The per-parameter raw type strings (e.g. "Int32", "string", "List").</returns>
internal static List<string> ParseParameterTypes(string? parameterDefinitionsJson)
/// <param name="parameterDefinitionsJson">The definition JSON; null/empty means "no parameters".</param>
/// <returns>The declared fields (empty for no parameters), or null when the JSON can't be parsed.</returns>
internal static IReadOnlyList<InboundApiSchemaField>? ParseParameterFields(string? parameterDefinitionsJson)
{
if (string.IsNullOrWhiteSpace(parameterDefinitionsJson))
return [];
try
{
using var doc = JsonDocument.Parse(parameterDefinitionsJson);
// JSON Schema: { type:"object", properties:{ name:{ type:"integer" }, ... } }
if (doc.RootElement.ValueKind == JsonValueKind.Object)
{
if (doc.RootElement.TryGetProperty("properties", out var props)
&& props.ValueKind == JsonValueKind.Object)
{
return props.EnumerateObject()
.Select(p => p.Value.ValueKind == JsonValueKind.Object
&& p.Value.TryGetProperty("type", out var t)
&& t.ValueKind == JsonValueKind.String
? t.GetString() ?? "unknown"
: "unknown")
.ToList();
}
}
// Legacy flat form: [{ name, type, required? }]
else if (doc.RootElement.ValueKind == JsonValueKind.Array)
{
return doc.RootElement.EnumerateArray()
.Select(e => e.TryGetProperty("type", out var t) ? t.GetString() ?? "unknown" : "unknown")
.ToList();
}
// No $ref resolver: an unresolved library ref only makes that field's
// schema shape-only, which the type check then treats as unknown.
var parsed = InboundApiSchema.ParseWithRefs(parameterDefinitionsJson, resolveRef: null);
return parsed.Schema?.Fields ?? [];
}
catch (JsonException)
{
return null;
}
return [];
}
/// <summary>
@@ -577,151 +608,126 @@ public class SemanticValidator
return result;
}
private static readonly CSharpParseOptions ScriptParseOptions =
CSharpParseOptions.Default
.WithKind(SourceCodeKind.Script)
.WithLanguageVersion(LanguageVersion.Latest);
/// <summary>
/// Extracts call targets from script code by simple pattern matching.
/// Looks for CallScript("name", ...) and CallShared("name", ...) patterns.
/// Extracts call targets from script code by parsing it with Roslyn and
/// finding every <c>CallScript(...)</c> / <c>CallShared(...)</c> invocation
/// (unqualified or receiver-qualified — <c>Instance.</c>, <c>Scripts.</c>,
/// <c>Parent.</c>, <c>Children["x"].</c>) whose script-name argument is a
/// string literal. Calls inside comments or string literals are not calls and
/// are ignored; a non-literal script name can't be resolved and is skipped.
/// </summary>
/// <param name="code">The script source code to scan.</param>
/// <returns>The list of call targets found (both <c>CallScript</c> and <c>CallShared</c> invocations).</returns>
internal static List<CallTarget> ExtractCallTargets(string code)
{
var results = new List<CallTarget>();
if (string.IsNullOrEmpty(code))
return results;
ExtractCallsOfType(code, "CallScript", false, results);
ExtractCallsOfType(code, "CallShared", true, results);
var root = CSharpSyntaxTree.ParseText(code, ScriptParseOptions).GetRoot();
foreach (var invocation in root.DescendantNodes().OfType<InvocationExpressionSyntax>())
{
var nameNode = invocation.Expression switch
{
IdentifierNameSyntax id => id,
MemberAccessExpressionSyntax { Name: IdentifierNameSyntax id } => id,
MemberBindingExpressionSyntax { Name: IdentifierNameSyntax id } => id,
_ => null,
};
if (nameNode is null)
continue;
var methodName = nameNode.Identifier.ValueText;
bool isShared;
if (methodName == "CallShared") isShared = true;
else if (methodName == "CallScript") isShared = false;
else continue;
var args = invocation.ArgumentList.Arguments;
var nameArg = FindArgument(args, 0, "scriptName");
if (nameArg?.Expression is not LiteralExpressionSyntax nameLiteral
|| !nameLiteral.IsKind(SyntaxKind.StringLiteralExpression))
continue;
// The single parameters object (positional slot 1 or `parameters:`).
// A third argument (CallShared's CancellationToken) is irrelevant here.
var paramArg = FindArgument(args, 1, "parameters");
var kind = CallParametersKind.None;
IReadOnlyList<CallParameterMember> members = [];
if (paramArg is not null)
{
if (paramArg.Expression is AnonymousObjectCreationExpressionSyntax anon)
{
kind = CallParametersKind.AnonymousObject;
members = anon.Initializers
.Select(m => new CallParameterMember(
m.NameEquals?.Name.Identifier.ValueText ?? InferAnonymousMemberName(m.Expression),
m.Expression.ToString()))
.ToList();
}
else
{
kind = CallParametersKind.Opaque;
}
}
results.Add(new CallTarget
{
TargetName = nameLiteral.Token.ValueText,
IsShared = isShared,
ParametersKind = kind,
ParameterMembers = members,
// The declared type the result is assigned into, if the
// call is the whole initializer of a typed local declaration.
AssignedToType = ExtractAssignedToType(code, nameNode.SpanStart)
});
}
return results;
}
private static void ExtractCallsOfType(string code, string methodName, bool isShared, List<CallTarget> results)
/// <summary>
/// Finds an invocation argument by C# binding rules: a named argument
/// (<c>name: value</c>) wins; otherwise the positional argument at
/// <paramref name="position"/>, provided every argument before it is
/// positional too.
/// </summary>
private static ArgumentSyntax? FindArgument(SeparatedSyntaxList<ArgumentSyntax> args, int position, string name)
{
var searchPattern = methodName + "(";
int pos = 0;
while (pos < code.Length)
foreach (var arg in args)
{
var idx = code.IndexOf(searchPattern, pos, StringComparison.Ordinal);
if (idx < 0) break;
var argsStart = idx + searchPattern.Length;
var target = ExtractStringArgument(code, argsStart);
if (target != null)
{
// First argument is the script name; the rest are the call's
// positional arguments.
var args = SplitCallArguments(code, argsStart);
var argExpressions = args.Count > 1
? args.GetRange(1, args.Count - 1)
: new List<string>();
results.Add(new CallTarget
{
TargetName = target,
IsShared = isShared,
ArgumentCount = argExpressions.Count,
ArgumentExpressions = argExpressions,
// The declared type the result is assigned into, if the
// call is the whole initializer of a typed local declaration.
AssignedToType = ExtractAssignedToType(code, idx)
});
}
pos = argsStart;
if (arg.NameColon is not null && arg.NameColon.Name.Identifier.ValueText == name)
return arg;
}
if (position >= args.Count)
return null;
for (var i = 0; i <= position; i++)
{
if (args[i].NameColon is not null)
return null;
}
return args[position];
}
/// <summary>
/// Splits a call's argument list (starting just after the opening paren)
/// into top-level argument expressions, trimmed. Tracks parenthesis, brace,
/// and bracket nesting plus string/char literals so object initializers,
/// nested calls, collection expressions, and commas inside literals don't
/// produce spurious splits. Element 0 is the script-name argument.
/// The C# projection-initializer name of an anonymous-object member without
/// an explicit <c>Name =</c> (<c>new { x }</c> → <c>x</c>,
/// <c>new { a.B }</c> → <c>B</c>); null when none can be inferred.
/// </summary>
private static List<string> SplitCallArguments(string code, int startPos)
private static string? InferAnonymousMemberName(ExpressionSyntax expression) => expression switch
{
var args = new List<string>();
var depthParen = 1; // we start inside the call's own '('
var depthBraceBracket = 0;
var pos = startPos;
var argStart = startPos;
while (pos < code.Length)
{
var c = code[pos];
switch (c)
{
case '(':
depthParen++;
break;
case ')':
depthParen--;
if (depthParen == 0)
{
AddArg(code, argStart, pos, args);
return args;
}
break;
case '{':
case '[':
depthBraceBracket++;
break;
case '}':
case ']':
if (depthBraceBracket > 0) depthBraceBracket--;
break;
case ',' when depthParen == 1 && depthBraceBracket == 0:
AddArg(code, argStart, pos, args);
argStart = pos + 1;
break;
case '"':
case '\'':
// Skip the literal body so its delimiters/commas are ignored.
pos++;
while (pos < code.Length && code[pos] != c)
{
if (code[pos] == '\\') pos++; // skip escaped char
pos++;
}
break;
case '/':
// Skip C# line and block comments so commas inside them are ignored.
// A `/` inside a string literal is already consumed above, so we only
// reach here for real `/` tokens in code.
if (pos + 1 < code.Length)
{
if (code[pos + 1] == '/')
{
// Line comment: skip to end-of-line.
pos += 2;
while (pos < code.Length && code[pos] != '\n') pos++;
}
else if (code[pos + 1] == '*')
{
// Block comment: skip to closing `*/`.
pos += 2;
while (pos + 1 < code.Length && !(code[pos] == '*' && code[pos + 1] == '/'))
pos++;
if (pos + 1 < code.Length) pos++; // step over the `/`
}
}
break;
}
pos++;
}
// Unterminated call (shouldn't happen for compilable code) — best effort.
AddArg(code, argStart, code.Length, args);
return args;
static void AddArg(string code, int start, int end, List<string> acc)
{
var text = code[start..end].Trim();
// Only the trailing empty slice after a lone name (e.g. "foo",) is
// dropped; an empty arg list ("foo") still yields just the name.
if (text.Length > 0 || acc.Count == 0)
acc.Add(text);
}
}
IdentifierNameSyntax id => id.Identifier.ValueText,
MemberAccessExpressionSyntax { Name: IdentifierNameSyntax id } => id.Identifier.ValueText,
ConditionalAccessExpressionSyntax { WhenNotNull: MemberBindingExpressionSyntax { Name: IdentifierNameSyntax id } } => id.Identifier.ValueText,
_ => null,
};
/// <summary>
/// Inference — looks backwards from the call's start index for a typed
@@ -996,37 +1002,32 @@ public class SemanticValidator
|| (actual == ScriptType.Float && expected == ScriptType.Integer);
}
private static string? ExtractStringArgument(string code, int startPos)
/// <summary>What a call site passes as its single <c>parameters</c> argument.</summary>
internal enum CallParametersKind
{
// Skip whitespace
var pos = startPos;
while (pos < code.Length && char.IsWhiteSpace(code[pos])) pos++;
if (pos >= code.Length) return null;
// Expect a quote
var quote = code[pos];
if (quote != '"' && quote != '\'') return null;
pos++;
var nameStart = pos;
while (pos < code.Length && code[pos] != quote) pos++;
if (pos >= code.Length) return null;
return code[nameStart..pos];
/// <summary>No parameters argument — the target receives no parameters.</summary>
None,
/// <summary>An anonymous-object creation (<c>new { A = 1 }</c>) — names are known statically.</summary>
AnonymousObject,
/// <summary>Any other expression (variable, dictionary, call, <c>null</c>) — keys unknown statically.</summary>
Opaque,
}
/// <summary>One member of an anonymous-object parameters argument.</summary>
/// <param name="Name">The member (parameter) name, or null when it can't be determined.</param>
/// <param name="Expression">The member's value expression text.</param>
internal sealed record CallParameterMember(string? Name, string Expression);
internal record CallTarget
{
/// <summary>Name of the script being called.</summary>
public string TargetName { get; init; } = string.Empty;
/// <summary>True when the call is to a shared script via <c>CallShared</c>.</summary>
public bool IsShared { get; init; }
/// <summary>Number of non-name arguments passed to the call.</summary>
public int ArgumentCount { get; init; }
/// <summary>The trimmed text of each non-name positional argument expression, in order.</summary>
public IReadOnlyList<string> ArgumentExpressions { get; init; } = [];
/// <summary>What the call passes as its <c>parameters</c> argument.</summary>
public CallParametersKind ParametersKind { get; init; }
/// <summary>For <see cref="CallParametersKind.AnonymousObject"/>: the object's members, in order; otherwise empty.</summary>
public IReadOnlyList<CallParameterMember> ParameterMembers { get; init; } = [];
/// <summary>
/// The declared type token the call result is assigned into, when the
/// call is the whole initializer of a typed local declaration; otherwise
@@ -223,323 +223,313 @@ public class SemanticValidatorTests
Assert.DoesNotContain(result.Errors, e => e.Category == ValidationCategory.CallTargetNotFound);
}
/// <summary>Verifies that a parameter count mismatch returns an error.</summary>
[Fact]
public void Validate_ParameterCountMismatch_ReturnsError()
// ── Parameters-object validation (ScadaBridge#150) ──────────────────
//
// CallScript/CallShared take ONE parameters object (anonymous object or
// dictionary) that the runtime normalizes into a name → value dictionary.
// An anonymous object is validated by NAME; any other expression is opaque.
private const string ThreeParamsLegacy =
"[{\"name\":\"NotificationList\",\"type\":\"String\",\"required\":true}," +
"{\"name\":\"Subject\",\"type\":\"String\",\"required\":true}," +
"{\"name\":\"Body\",\"type\":\"String\",\"required\":true}]";
private ValidationResult ValidateCallShared(string callerCode, string? parameterDefinitions)
{
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Instance1",
Scripts = [new ResolvedScript { CanonicalName = "Caller", Code = callerCode }]
};
var shared = new List<ResolvedScript>
{
new() { CanonicalName = "SendNotificationExample", Code = "return null;", ParameterDefinitions = parameterDefinitions }
};
return _sut.Validate(config, shared);
}
private ValidationResult ValidateCallScript(string callerCode, string? parameterDefinitions)
{
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Instance1",
Scripts =
[
new ResolvedScript
{
CanonicalName = "Target",
Code = "var x = 1;",
ParameterDefinitions = "[{\"name\":\"a\",\"type\":\"Int32\"},{\"name\":\"b\",\"type\":\"String\"}]"
},
new ResolvedScript
{
CanonicalName = "Caller",
Code = "CallScript(\"Target\", 42);" // 1 arg but 2 expected
}
new ResolvedScript { CanonicalName = "Target", Code = "var x = 1;", ParameterDefinitions = parameterDefinitions },
new ResolvedScript { CanonicalName = "Caller", Code = callerCode }
]
};
return _sut.Validate(config);
}
private static void AssertNoParameterErrors(ValidationResult result) =>
Assert.DoesNotContain(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
/// <summary>Issue #150 repro: CallShared with an anonymous object supplying every declared parameter is valid.</summary>
[Fact]
public void CallShared_AnonymousObjectWithAllParams_NoError()
{
var result = ValidateCallShared(
"await Scripts.CallShared(\"SendNotificationExample\", new { NotificationList = \"Ops\", Subject = \"Hi\", Body = body });",
ThreeParamsLegacy);
AssertNoParameterErrors(result);
Assert.DoesNotContain(result.Warnings, w => w.Category == ValidationCategory.ParameterMismatch);
}
/// <summary>CallShared with an anonymous object missing a required parameter is an error naming it.</summary>
[Fact]
public void CallShared_AnonymousObjectMissingRequired_ReturnsError()
{
var result = ValidateCallShared(
"await Scripts.CallShared(\"SendNotificationExample\", new { NotificationList = \"Ops\", Subject = \"Hi\" });",
ThreeParamsLegacy);
Assert.Contains(result.Errors, e =>
e.Category == ValidationCategory.ParameterMismatch && e.Message.Contains("'Body'", StringComparison.Ordinal));
}
/// <summary>A missing parameter declared optional (required:false) is not an error.</summary>
[Fact]
public void CallShared_AnonymousObjectMissingOptional_NoError()
{
var result = ValidateCallShared(
"await Scripts.CallShared(\"SendNotificationExample\", new { Subject = \"Hi\" });",
"[{\"name\":\"Subject\",\"type\":\"String\"},{\"name\":\"Body\",\"type\":\"String\",\"required\":false}]");
AssertNoParameterErrors(result);
}
/// <summary>An extra member the target doesn't declare is a warning, not an error.</summary>
[Fact]
public void CallShared_AnonymousObjectUnknownName_WarnsButNoError()
{
var result = ValidateCallShared(
"await Scripts.CallShared(\"SendNotificationExample\", new { NotificationList = \"Ops\", Subject = \"Hi\", Body = \"b\", Bdy = \"typo\" });",
ThreeParamsLegacy);
Assert.True(result.IsValid);
Assert.Contains(result.Warnings, w =>
w.Category == ValidationCategory.ParameterMismatch && w.Message.Contains("'Bdy'", StringComparison.Ordinal));
}
/// <summary>A dictionary variable's keys can't be known statically — never flagged.</summary>
[Fact]
public void CallShared_DictionaryVariable_NoError()
{
var result = ValidateCallShared(
"var args = new Dictionary<string, object?> { [\"Subject\"] = \"Hi\" }; await Scripts.CallShared(\"SendNotificationExample\", args);",
ThreeParamsLegacy);
AssertNoParameterErrors(result);
}
/// <summary>No parameters argument against a target with required parameters is an error.</summary>
[Fact]
public void CallShared_NoArgumentsAgainstRequiredParams_ReturnsError()
{
var result = ValidateCallShared("await Scripts.CallShared(\"SendNotificationExample\");", ThreeParamsLegacy);
var result = _sut.Validate(config);
Assert.Contains(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
}
// ── Argument-type validation ────────────────────────────────────────
/// <summary>Verifies that passing a string for an integer parameter returns an error.</summary>
/// <summary>No parameters argument against a target that declares none is valid.</summary>
[Fact]
public void Validate_ArgumentTypeMismatch_StringForInteger_ReturnsError()
public void CallShared_NoArgumentsAgainstNoParams_NoError()
{
// Target expects (Integer a); caller passes a string literal.
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Instance1",
Scripts =
[
new ResolvedScript
{
CanonicalName = "Target",
Code = "var x = 1;",
ParameterDefinitions = "[{\"name\":\"a\",\"type\":\"Int32\"}]"
},
new ResolvedScript
{
CanonicalName = "Caller",
Code = "CallScript(\"Target\", \"hello\");"
}
]
};
var result = ValidateCallShared("await Scripts.CallShared(\"SendNotificationExample\");", null);
var result = _sut.Validate(config);
AssertNoParameterErrors(result);
}
/// <summary>A trailing CancellationToken argument doesn't disturb parsing of the parameters object.</summary>
[Fact]
public void CallShared_WithCancellationTokenArgument_ValidatesParametersObject()
{
var ok = ValidateCallShared(
"await Scripts.CallShared(\"SendNotificationExample\", new { NotificationList = \"a, b\", Subject = Fmt(\"x\", 1), Body = \"(b)\" }, CancellationToken.None);",
ThreeParamsLegacy);
AssertNoParameterErrors(ok);
var missing = ValidateCallShared(
"await Scripts.CallShared(\"SendNotificationExample\", new { Subject = \"x\" }, ct);",
ThreeParamsLegacy);
Assert.Contains(missing.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
var namedCt = ValidateCallShared(
"await Scripts.CallShared(\"SendNotificationExample\", cancellationToken: ct);",
null);
AssertNoParameterErrors(namedCt);
}
/// <summary>JSON Schema form: only the names listed in "required" are required.</summary>
[Fact]
public void CallShared_JsonSchemaRequiredList_Honored()
{
const string schema =
"{\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"integer\"},\"b\":{\"type\":\"string\"}},\"required\":[\"a\"]}";
AssertNoParameterErrors(ValidateCallShared("Scripts.CallShared(\"SendNotificationExample\", new { a = 1 });", schema));
Assert.Contains(
ValidateCallShared("Scripts.CallShared(\"SendNotificationExample\", new { b = \"x\" });", schema).Errors,
e => e.Category == ValidationCategory.ParameterMismatch && e.Message.Contains("'a'", StringComparison.Ordinal));
}
/// <summary>CallScript with an anonymous object supplying every declared parameter is valid.</summary>
[Fact]
public void CallScript_AnonymousObjectWithAllParams_NoError()
{
var result = ValidateCallScript(
"await Instance.CallScript(\"Target\", new { a = 42, b = \"hi\", c = true });",
"[{\"name\":\"a\",\"type\":\"Integer\"},{\"name\":\"b\",\"type\":\"String\"},{\"name\":\"c\",\"type\":\"Boolean\"}]");
AssertNoParameterErrors(result);
}
/// <summary>CallScript with an anonymous object missing a required parameter is an error.</summary>
[Fact]
public void CallScript_AnonymousObjectMissingRequired_ReturnsError()
{
var result = ValidateCallScript(
"CallScript(\"Target\", new { a = 42 });",
"[{\"name\":\"a\",\"type\":\"Int32\"},{\"name\":\"b\",\"type\":\"String\"}]");
Assert.Contains(result.Errors, e =>
e.Category == ValidationCategory.ParameterMismatch && e.Message.Contains("'b'", StringComparison.Ordinal));
}
/// <summary>CallScript: an unknown member name is a warning only.</summary>
[Fact]
public void CallScript_AnonymousObjectUnknownName_WarnsButNoError()
{
var result = ValidateCallScript(
"CallScript(\"Target\", new { a = 1, extra = 2 });",
"[{\"name\":\"a\",\"type\":\"Int32\"}]");
Assert.True(result.IsValid);
Assert.Contains(result.Warnings, w =>
w.Category == ValidationCategory.ParameterMismatch && w.Message.Contains("'extra'", StringComparison.Ordinal));
}
/// <summary>CallScript: name matching is ordinal, as the runtime dictionary is.</summary>
[Fact]
public void CallScript_AnonymousObjectWrongCase_ReturnsError()
{
var result = ValidateCallScript(
"CallScript(\"Target\", new { A = 1 });",
"[{\"name\":\"a\",\"type\":\"Int32\"}]");
Assert.Contains(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
}
/// <summary>CallScript: a projection initializer (<c>new { a }</c>) supplies the parameter named after the variable.</summary>
[Fact]
public void CallScript_ProjectionInitializer_SuppliesName()
{
var result = ValidateCallScript(
"var a = 1; var o = new { b = 2 }; CallScript(\"Target\", new { a, o.b });",
"[{\"name\":\"a\",\"type\":\"Int32\"},{\"name\":\"b\",\"type\":\"Int32\"}]");
AssertNoParameterErrors(result);
}
/// <summary>CallScript with a dictionary variable is never flagged.</summary>
[Fact]
public void CallScript_DictionaryVariable_NoError()
{
var result = ValidateCallScript(
"CallScript(\"Target\", Parameters);",
"[{\"name\":\"a\",\"type\":\"Int32\"}]");
AssertNoParameterErrors(result);
}
/// <summary>CallScript with a null parameters argument is opaque — not checked.</summary>
[Fact]
public void CallScript_NullParameters_NoError()
{
var result = ValidateCallScript(
"CallScript(\"Target\", null);",
"[{\"name\":\"a\",\"type\":\"Int32\"}]");
AssertNoParameterErrors(result);
}
/// <summary>CallScript with no arguments against required parameters is an error.</summary>
[Fact]
public void CallScript_NoArgumentsAgainstRequiredParams_ReturnsError()
{
var result = ValidateCallScript(
"CallScript(\"Target\");",
"[{\"name\":\"a\",\"type\":\"Int32\"},{\"name\":\"b\",\"type\":\"String\"}]");
Assert.Contains(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
}
/// <summary>CallScript with no arguments against a target with no parameters is valid.</summary>
[Fact]
public void CallScript_NoArgumentsAgainstNoParams_NoError()
{
AssertNoParameterErrors(ValidateCallScript("CallScript(\"Target\");", null));
AssertNoParameterErrors(ValidateCallScript("CallScript(\"Target\");", "[]"));
}
// ── Member-type validation (anonymous-object members) ───────────────
/// <summary>A string literal for an integer parameter is a type error.</summary>
[Fact]
public void Validate_MemberTypeMismatch_StringForInteger_ReturnsError()
{
var result = ValidateCallScript("CallScript(\"Target\", new { a = \"hello\" });", "[{\"name\":\"a\",\"type\":\"Int32\"}]");
Assert.Contains(result.Errors, e =>
e.Category == ValidationCategory.ParameterMismatch &&
e.Message.Contains("type", StringComparison.OrdinalIgnoreCase));
}
/// <summary>Verifies that passing a number for a string parameter returns an error.</summary>
/// <summary>A number literal for a string parameter is a type error.</summary>
[Fact]
public void Validate_ArgumentTypeMismatch_NumberForString_ReturnsError()
public void Validate_MemberTypeMismatch_NumberForString_ReturnsError()
{
// Target expects (String a); caller passes an integer literal.
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Instance1",
Scripts =
[
new ResolvedScript
{
CanonicalName = "Target",
Code = "var x = 1;",
ParameterDefinitions = "[{\"name\":\"a\",\"type\":\"String\"}]"
},
new ResolvedScript
{
CanonicalName = "Caller",
Code = "CallScript(\"Target\", 42);"
}
]
};
var result = _sut.Validate(config);
var result = ValidateCallScript("CallScript(\"Target\", new { a = 42 });", "[{\"name\":\"a\",\"type\":\"String\"}]");
Assert.Contains(result.Errors, e =>
e.Category == ValidationCategory.ParameterMismatch &&
e.Message.Contains("type", StringComparison.OrdinalIgnoreCase));
}
/// <summary>Verifies that passing a boolean for an integer parameter returns an error.</summary>
/// <summary>A boolean literal for an integer parameter is a type error.</summary>
[Fact]
public void Validate_ArgumentTypeMismatch_BooleanForInteger_ReturnsError()
public void Validate_MemberTypeMismatch_BooleanForInteger_ReturnsError()
{
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Instance1",
Scripts =
[
new ResolvedScript
{
CanonicalName = "Target",
Code = "var x = 1;",
ParameterDefinitions = "[{\"name\":\"a\",\"type\":\"Integer\"}]"
},
new ResolvedScript
{
CanonicalName = "Caller",
Code = "CallScript(\"Target\", true);"
}
]
};
var result = _sut.Validate(config);
Assert.Contains(result.Errors, e =>
e.Category == ValidationCategory.ParameterMismatch &&
e.Message.Contains("type", StringComparison.OrdinalIgnoreCase));
var result = ValidateCallScript("CallScript(\"Target\", new { a = true });", "[{\"name\":\"a\",\"type\":\"Integer\"}]");
Assert.Contains(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
}
/// <summary>Verifies that literals of the correct types produce no error.</summary>
/// <summary>An integer literal for a float parameter is accepted (numeric widening).</summary>
[Fact]
public void Validate_ArgumentTypeMatch_CorrectLiterals_NoError()
public void Validate_MemberType_IntegerLiteralForFloat_NoError()
{
// (Integer a, String b, Boolean c) called with matching literals.
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Instance1",
Scripts =
[
new ResolvedScript
{
CanonicalName = "Target",
Code = "var x = 1;",
ParameterDefinitions =
"[{\"name\":\"a\",\"type\":\"Integer\"},{\"name\":\"b\",\"type\":\"String\"},{\"name\":\"c\",\"type\":\"Boolean\"}]"
},
new ResolvedScript
{
CanonicalName = "Caller",
Code = "CallScript(\"Target\", 42, \"hi\", true);"
}
]
};
var result = _sut.Validate(config);
Assert.DoesNotContain(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
AssertNoParameterErrors(ValidateCallScript("CallScript(\"Target\", new { a = 5 });", "[{\"name\":\"a\",\"type\":\"Float\"}]"));
}
/// <summary>Verifies that passing an integer literal for a float parameter produces no error.</summary>
[Fact]
public void Validate_ArgumentType_IntegerLiteralForFloat_NoError()
/// <summary>Non-literal member expressions are never type-flagged.</summary>
[Theory]
[InlineData("v")]
[InlineData("42 + offset")]
[InlineData("\"a\" + x")]
[InlineData("null")]
[InlineData("Attributes[\"Temp\"].Value")]
public void Validate_MemberType_UnknownExpression_NoFalsePositive(string expression)
{
// Numeric widening: an integer literal is acceptable where a Float is declared.
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Instance1",
Scripts =
[
new ResolvedScript
{
CanonicalName = "Target",
Code = "var x = 1;",
ParameterDefinitions = "[{\"name\":\"a\",\"type\":\"Float\"}]"
},
new ResolvedScript
{
CanonicalName = "Caller",
Code = "CallScript(\"Target\", 5);"
}
]
};
var result = _sut.Validate(config);
Assert.DoesNotContain(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
AssertNoParameterErrors(ValidateCallScript(
$"CallScript(\"Target\", new {{ a = {expression} }});",
"[{\"name\":\"a\",\"type\":\"Integer\"}]"));
}
/// <summary>Verifies that an expression of unknown type does not produce a false positive.</summary>
/// <summary>An Object-typed parameter accepts any literal.</summary>
[Fact]
public void Validate_ArgumentType_UnknownExpression_NoFalsePositive()
public void Validate_MemberType_UntypedParameter_NoFalsePositive()
{
// The argument is a variable/expression whose type can't be statically
// inferred — must NOT be flagged even though it could be anything.
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Instance1",
Scripts =
[
new ResolvedScript
{
CanonicalName = "Target",
Code = "var x = 1;",
ParameterDefinitions = "[{\"name\":\"a\",\"type\":\"Integer\"}]"
},
new ResolvedScript
{
CanonicalName = "Caller",
Code = "var v = Attributes[\"Temp\"].Value; CallScript(\"Target\", v);"
}
]
};
var result = _sut.Validate(config);
Assert.DoesNotContain(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
}
/// <summary>Verifies that an object initializer argument does not produce a false positive.</summary>
[Fact]
public void Validate_ArgumentType_ObjectInitializerArgument_NoFalsePositive()
{
// Real-world call shape: a single anonymous-object argument. Object
// initializers can't be mapped to positional primitive params — skip.
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Instance1",
Scripts =
[
new ResolvedScript
{
CanonicalName = "Target",
Code = "var x = 1;",
ParameterDefinitions = "[{\"name\":\"a\",\"type\":\"Integer\"}]"
},
new ResolvedScript
{
CanonicalName = "Caller",
Code = "CallScript(\"Target\", new { a = 5 });"
}
]
};
var result = _sut.Validate(config);
Assert.DoesNotContain(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
}
/// <summary>Verifies that an untyped parameter does not produce a false positive.</summary>
[Fact]
public void Validate_ArgumentType_UntypedParameter_NoFalsePositive()
{
// Target declares an Object parameter — anything is assignable, no flag.
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Instance1",
Scripts =
[
new ResolvedScript
{
CanonicalName = "Target",
Code = "var x = 1;",
ParameterDefinitions = "[{\"name\":\"a\",\"type\":\"Object\"}]"
},
new ResolvedScript
{
CanonicalName = "Caller",
Code = "CallScript(\"Target\", \"anything\");"
}
]
};
var result = _sut.Validate(config);
Assert.DoesNotContain(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
}
/// <summary>Verifies that a compound expression starting with a literal does not produce a false positive.</summary>
[Fact]
public void Validate_ArgumentType_CompoundExpressionStartingWithLiteral_NoFalsePositive()
{
// `42 + offset` starts with an int literal but is a compound expression
// of unknown type — must NOT be classified or flagged.
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Instance1",
Scripts =
[
new ResolvedScript
{
CanonicalName = "Target",
Code = "var x = 1;",
ParameterDefinitions = "[{\"name\":\"a\",\"type\":\"String\"}]"
},
new ResolvedScript
{
CanonicalName = "Caller",
Code = "CallScript(\"Target\", 42 + offset);"
}
]
};
var result = _sut.Validate(config);
Assert.DoesNotContain(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
}
/// <summary>Verifies that a concatenated string expression does not produce a false positive.</summary>
[Fact]
public void Validate_ArgumentType_ConcatenatedStringExpression_NoFalsePositive()
{
// `"a" + x` starts with a string literal but is a concatenation of
// unknown overall type — be conservative, don't flag against Integer.
var config = new FlattenedConfiguration
{
InstanceUniqueName = "Instance1",
Scripts =
[
new ResolvedScript
{
CanonicalName = "Target",
Code = "var x = 1;",
ParameterDefinitions = "[{\"name\":\"a\",\"type\":\"Integer\"}]"
},
new ResolvedScript
{
CanonicalName = "Caller",
Code = "CallScript(\"Target\", \"a\" + x);"
}
]
};
var result = _sut.Validate(config);
Assert.DoesNotContain(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
AssertNoParameterErrors(ValidateCallScript("CallScript(\"Target\", new { a = \"anything\" });", "[{\"name\":\"a\",\"type\":\"Object\"}]"));
}
// ── Return-type validation ──────────────────────────────────────────
@@ -907,17 +897,23 @@ public class SemanticValidatorTests
public void ExtractCallTargets_MultipleCallTypes()
{
var code = @"
var x = CallScript(""Script1"", arg1, arg2);
var x = CallScript(""Script1"", new { a = 1, b = ""x, y"" });
CallShared(""Shared1"");
CallScript(""Script2"");
CallScript(""Script2"", args);
// CallScript(""InComment"");
var name = ""CallShared(\""InString\"")"";
";
var targets = SemanticValidator.ExtractCallTargets(code);
Assert.Equal(3, targets.Count);
Assert.Contains(targets, t => t.TargetName == "Script1" && !t.IsShared && t.ArgumentCount == 2);
Assert.Contains(targets, t => t.TargetName == "Shared1" && t.IsShared && t.ArgumentCount == 0);
Assert.Contains(targets, t => t.TargetName == "Script2" && !t.IsShared && t.ArgumentCount == 0);
Assert.Contains(targets, t => t.TargetName == "Script1" && !t.IsShared
&& t.ParametersKind == SemanticValidator.CallParametersKind.AnonymousObject
&& t.ParameterMembers.Select(m => m.Name).SequenceEqual(new[] { "a", "b" }));
Assert.Contains(targets, t => t.TargetName == "Shared1" && t.IsShared
&& t.ParametersKind == SemanticValidator.CallParametersKind.None);
Assert.Contains(targets, t => t.TargetName == "Script2" && !t.IsShared
&& t.ParametersKind == SemanticValidator.CallParametersKind.Opaque);
}
// ── HiLo validation ─────────────────────────────────────────────────────