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: 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. - **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. - **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). - **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. - **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 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;
using ZB.MOM.WW.ScadaBridge.Commons.Types.InboundApi;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening; using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
@@ -8,7 +12,8 @@ namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
/// <summary> /// <summary>
/// Semantic validation rules for a FlattenedConfiguration: /// Semantic validation rules for a FlattenedConfiguration:
/// - CallScript/CallShared targets must reference existing scripts /// - 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 /// - Return type compatibility
/// - Trigger operand types: RangeViolation requires numeric attribute /// - Trigger operand types: RangeViolation requires numeric attribute
/// - On-trigger script must exist /// - On-trigger script must exist
@@ -46,8 +51,8 @@ public class SemanticValidator
// literal leaf "Y"; the actual flattened script is the composed canonical // literal leaf "Y"; the actual flattened script is the composed canonical
// "X.Y". Since the child segment is dynamic it cannot be statically resolved, // "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 // 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 // name. The parameter checks already self-skip for these (their canonical
// (their canonical name "X.Y" is not the literal key "Y" in the param map). // name "X.Y" is not the literal key "Y" in the param map).
var composedLeafNames = new HashSet<string>( var composedLeafNames = new HashSet<string>(
configuration.Scripts configuration.Scripts
.Select(s => s.CanonicalName) .Select(s => s.CanonicalName)
@@ -101,7 +106,7 @@ public class SemanticValidator
} }
else else
{ {
ValidateCallParameters(script.CanonicalName, call, sharedParamMap, errors); ValidateCallParameters(script.CanonicalName, call, sharedParamMap, errors, warnings);
ValidateCallReturnType(script.CanonicalName, call, sharedReturnMap, errors); ValidateCallReturnType(script.CanonicalName, call, sharedReturnMap, errors);
} }
} }
@@ -131,7 +136,7 @@ public class SemanticValidator
script.CanonicalName)); script.CanonicalName));
} }
ValidateCallParameters(script.CanonicalName, call, scriptParamMap, errors); ValidateCallParameters(script.CanonicalName, call, scriptParamMap, errors, warnings);
ValidateCallReturnType(script.CanonicalName, call, scriptReturnMap, errors); ValidateCallReturnType(script.CanonicalName, call, scriptReturnMap, errors);
// Instance scripts cannot call alarm on-trigger scripts // 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( private static void ValidateCallParameters(
string callerName, string callerName,
CallTarget call, CallTarget call,
Dictionary<string, List<string>> paramMap, Dictionary<string, IReadOnlyList<InboundApiSchemaField>> paramMap,
List<ValidationEntry> errors) List<ValidationEntry> errors,
List<ValidationEntry> warnings)
{ {
if (!paramMap.TryGetValue(call.TargetName, out var expectedParams)) if (!paramMap.TryGetValue(call.TargetName, out var declared))
return; return; // Target's definitions unknown/unparseable — don't guess.
if (call.ArgumentCount != expectedParams.Count) switch (call.ParametersKind)
{
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, errors.Add(ValidationEntry.Error(ValidationCategory.ParameterMismatch,
$"Script '{callerName}' calls '{call.TargetName}' with {call.ArgumentCount} arguments but {expectedParams.Count} are expected.", $"Script '{callerName}' calls '{call.TargetName}' without a parameters object, but '{call.TargetName}' requires {FormatNames(missing)}.",
callerName)); callerName));
// Count mismatch already reported — positional type matching below }
// would be misaligned, so don't compound the noise.
return; return;
} }
ValidateArgumentTypes(callerName, call, expectedParams, errors); case CallParametersKind.Opaque:
}
/// <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; return;
for (var i = 0; i < expectedParams.Count; i++) case CallParametersKind.AnonymousObject:
{ break;
var declared = NormalizeType(expectedParams[i]);
if (declared is null)
continue; // Object/List/unknown declaration accepts anything.
var actual = InferLiteralType(call.ArgumentExpressions[i]); default:
return;
}
var declaredByName = new Dictionary<string, InboundApiSchemaField>(StringComparer.Ordinal);
foreach (var field in declared)
declaredByName.TryAdd(field.Name, field);
// 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);
if (allNamesKnown)
{
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}' 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) if (actual is null)
continue; // Can't confidently infer the argument's type. continue; // Can't confidently infer the member's type.
if (!IsAssignable(actual.Value, declared.Value)) if (!IsAssignable(actual.Value, expected.Value))
{ {
errors.Add(ValidationEntry.Error(ValidationCategory.ParameterMismatch, 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}' with parameter '{member.Name}' of type '{actual}' but it expects '{expected}'.",
callerName)); callerName));
} }
} }
static string FormatNames(List<string> names) =>
(names.Count == 1 ? "parameter " : "parameters ")
+ string.Join(", ", names.Select(n => $"'{n}'"));
} }
/// <summary> /// <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) foreach (var script in scripts)
{ {
// Per-parameter declared TYPE in declared order (raw type strings). // An unparseable definition leaves the target out of the map, so its
// One entry per parameter, so the existing count check is preserved // call sites are not parameter-checked (never a false positive).
// and positional matching has the types it needs. var parameters = ParseParameterFields(script.ParameterDefinitions);
var parameters = ParseParameterTypes(script.ParameterDefinitions); if (parameters is not null)
result[script.CanonicalName] = parameters; result[script.CanonicalName] = parameters;
} }
return result; return result;
} }
/// <summary> /// <summary>
/// Parses a parameter definitions JSON string (JSON Schema or legacy flat /// Parses a parameter definitions JSON string (JSON Schema object form, or
/// array) and returns the declared parameter TYPE for each parameter, in /// the legacy flat <c>[{name,type,required}]</c> array) into its declared
/// declared order. Names are not needed for positional call validation; the /// fields — name, required flag and type — via the shared
/// returned count equals the parameter count (preserving the count check). /// <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> /// </summary>
/// <param name="parameterDefinitionsJson">JSON Schema or legacy flat-array string; null/empty returns an empty list.</param> /// <param name="parameterDefinitionsJson">The definition JSON; null/empty means "no parameters".</param>
/// <returns>The per-parameter raw type strings (e.g. "Int32", "string", "List").</returns> /// <returns>The declared fields (empty for no parameters), or null when the JSON can't be parsed.</returns>
internal static List<string> ParseParameterTypes(string? parameterDefinitionsJson) internal static IReadOnlyList<InboundApiSchemaField>? ParseParameterFields(string? parameterDefinitionsJson)
{ {
if (string.IsNullOrWhiteSpace(parameterDefinitionsJson)) if (string.IsNullOrWhiteSpace(parameterDefinitionsJson))
return []; return [];
try try
{ {
using var doc = JsonDocument.Parse(parameterDefinitionsJson); // No $ref resolver: an unresolved library ref only makes that field's
// JSON Schema: { type:"object", properties:{ name:{ type:"integer" }, ... } } // schema shape-only, which the type check then treats as unknown.
if (doc.RootElement.ValueKind == JsonValueKind.Object) var parsed = InboundApiSchema.ParseWithRefs(parameterDefinitionsJson, resolveRef: null);
{ return parsed.Schema?.Fields ?? [];
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();
}
} }
catch (JsonException) catch (JsonException)
{ {
return null;
} }
return [];
} }
/// <summary> /// <summary>
@@ -577,151 +608,126 @@ public class SemanticValidator
return result; return result;
} }
private static readonly CSharpParseOptions ScriptParseOptions =
CSharpParseOptions.Default
.WithKind(SourceCodeKind.Script)
.WithLanguageVersion(LanguageVersion.Latest);
/// <summary> /// <summary>
/// Extracts call targets from script code by simple pattern matching. /// Extracts call targets from script code by parsing it with Roslyn and
/// Looks for CallScript("name", ...) and CallShared("name", ...) patterns. /// 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> /// </summary>
/// <param name="code">The script source code to scan.</param> /// <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> /// <returns>The list of call targets found (both <c>CallScript</c> and <c>CallShared</c> invocations).</returns>
internal static List<CallTarget> ExtractCallTargets(string code) internal static List<CallTarget> ExtractCallTargets(string code)
{ {
var results = new List<CallTarget>(); var results = new List<CallTarget>();
if (string.IsNullOrEmpty(code))
return results;
ExtractCallsOfType(code, "CallScript", false, results); var root = CSharpSyntaxTree.ParseText(code, ScriptParseOptions).GetRoot();
ExtractCallsOfType(code, "CallShared", true, results);
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; 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 + "("; foreach (var arg in args)
int pos = 0;
while (pos < code.Length)
{ {
var idx = code.IndexOf(searchPattern, pos, StringComparison.Ordinal); if (arg.NameColon is not null && arg.NameColon.Name.Identifier.ValueText == name)
if (idx < 0) break; return arg;
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 (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> /// <summary>
/// Splits a call's argument list (starting just after the opening paren) /// The C# projection-initializer name of an anonymous-object member without
/// into top-level argument expressions, trimmed. Tracks parenthesis, brace, /// an explicit <c>Name =</c> (<c>new { x }</c> → <c>x</c>,
/// and bracket nesting plus string/char literals so object initializers, /// <c>new { a.B }</c> → <c>B</c>); null when none can be inferred.
/// nested calls, collection expressions, and commas inside literals don't
/// produce spurious splits. Element 0 is the script-name argument.
/// </summary> /// </summary>
private static List<string> SplitCallArguments(string code, int startPos) private static string? InferAnonymousMemberName(ExpressionSyntax expression) => expression switch
{ {
var args = new List<string>(); IdentifierNameSyntax id => id.Identifier.ValueText,
var depthParen = 1; // we start inside the call's own '(' MemberAccessExpressionSyntax { Name: IdentifierNameSyntax id } => id.Identifier.ValueText,
var depthBraceBracket = 0; ConditionalAccessExpressionSyntax { WhenNotNull: MemberBindingExpressionSyntax { Name: IdentifierNameSyntax id } } => id.Identifier.ValueText,
var pos = startPos; _ => null,
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);
}
}
/// <summary> /// <summary>
/// Inference — looks backwards from the call's start index for a typed /// 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); || (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 /// <summary>No parameters argument — the target receives no parameters.</summary>
var pos = startPos; None,
while (pos < code.Length && char.IsWhiteSpace(code[pos])) pos++; /// <summary>An anonymous-object creation (<c>new { A = 1 }</c>) — names are known statically.</summary>
AnonymousObject,
if (pos >= code.Length) return null; /// <summary>Any other expression (variable, dictionary, call, <c>null</c>) — keys unknown statically.</summary>
Opaque,
// 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>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 internal record CallTarget
{ {
/// <summary>Name of the script being called.</summary> /// <summary>Name of the script being called.</summary>
public string TargetName { get; init; } = string.Empty; public string TargetName { get; init; } = string.Empty;
/// <summary>True when the call is to a shared script via <c>CallShared</c>.</summary> /// <summary>True when the call is to a shared script via <c>CallShared</c>.</summary>
public bool IsShared { get; init; } public bool IsShared { get; init; }
/// <summary>Number of non-name arguments passed to the call.</summary> /// <summary>What the call passes as its <c>parameters</c> argument.</summary>
public int ArgumentCount { get; init; } public CallParametersKind ParametersKind { get; init; }
/// <summary>The trimmed text of each non-name positional argument expression, in order.</summary> /// <summary>For <see cref="CallParametersKind.AnonymousObject"/>: the object's members, in order; otherwise empty.</summary>
public IReadOnlyList<string> ArgumentExpressions { get; init; } = []; public IReadOnlyList<CallParameterMember> ParameterMembers { get; init; } = [];
/// <summary> /// <summary>
/// The declared type token the call result is assigned into, when the /// The declared type token the call result is assigned into, when the
/// call is the whole initializer of a typed local declaration; otherwise /// 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); Assert.DoesNotContain(result.Errors, e => e.Category == ValidationCategory.CallTargetNotFound);
} }
/// <summary>Verifies that a parameter count mismatch returns an error.</summary> // ── Parameters-object validation (ScadaBridge#150) ──────────────────
[Fact] //
public void Validate_ParameterCountMismatch_ReturnsError() // 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 var config = new FlattenedConfiguration
{ {
InstanceUniqueName = "Instance1", InstanceUniqueName = "Instance1",
Scripts = Scripts =
[ [
new ResolvedScript new ResolvedScript { CanonicalName = "Target", Code = "var x = 1;", ParameterDefinitions = parameterDefinitions },
{ new ResolvedScript { CanonicalName = "Caller", Code = callerCode }
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
}
] ]
}; };
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); Assert.Contains(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
} }
// ── Argument-type validation ──────────────────────────────────────── /// <summary>No parameters argument against a target that declares none is valid.</summary>
/// <summary>Verifies that passing a string for an integer parameter returns an error.</summary>
[Fact] [Fact]
public void Validate_ArgumentTypeMismatch_StringForInteger_ReturnsError() public void CallShared_NoArgumentsAgainstNoParams_NoError()
{ {
// Target expects (Integer a); caller passes a string literal. var result = ValidateCallShared("await Scripts.CallShared(\"SendNotificationExample\");", null);
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 = _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 => Assert.Contains(result.Errors, e =>
e.Category == ValidationCategory.ParameterMismatch && e.Category == ValidationCategory.ParameterMismatch &&
e.Message.Contains("type", StringComparison.OrdinalIgnoreCase)); 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] [Fact]
public void Validate_ArgumentTypeMismatch_NumberForString_ReturnsError() public void Validate_MemberTypeMismatch_NumberForString_ReturnsError()
{ {
// Target expects (String a); caller passes an integer literal. var result = ValidateCallScript("CallScript(\"Target\", new { a = 42 });", "[{\"name\":\"a\",\"type\":\"String\"}]");
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);
Assert.Contains(result.Errors, e => Assert.Contains(result.Errors, e =>
e.Category == ValidationCategory.ParameterMismatch && e.Category == ValidationCategory.ParameterMismatch &&
e.Message.Contains("type", StringComparison.OrdinalIgnoreCase)); 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] [Fact]
public void Validate_ArgumentTypeMismatch_BooleanForInteger_ReturnsError() public void Validate_MemberTypeMismatch_BooleanForInteger_ReturnsError()
{ {
var config = new FlattenedConfiguration var result = ValidateCallScript("CallScript(\"Target\", new { a = true });", "[{\"name\":\"a\",\"type\":\"Integer\"}]");
{ Assert.Contains(result.Errors, e => e.Category == ValidationCategory.ParameterMismatch);
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));
} }
/// <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] [Fact]
public void Validate_ArgumentTypeMatch_CorrectLiterals_NoError() public void Validate_MemberType_IntegerLiteralForFloat_NoError()
{ {
// (Integer a, String b, Boolean c) called with matching literals. AssertNoParameterErrors(ValidateCallScript("CallScript(\"Target\", new { a = 5 });", "[{\"name\":\"a\",\"type\":\"Float\"}]"));
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);
} }
/// <summary>Verifies that passing an integer literal for a float parameter produces no error.</summary> /// <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)
{
AssertNoParameterErrors(ValidateCallScript(
$"CallScript(\"Target\", new {{ a = {expression} }});",
"[{\"name\":\"a\",\"type\":\"Integer\"}]"));
}
/// <summary>An Object-typed parameter accepts any literal.</summary>
[Fact] [Fact]
public void Validate_ArgumentType_IntegerLiteralForFloat_NoError() public void Validate_MemberType_UntypedParameter_NoFalsePositive()
{ {
// Numeric widening: an integer literal is acceptable where a Float is declared. AssertNoParameterErrors(ValidateCallScript("CallScript(\"Target\", new { a = \"anything\" });", "[{\"name\":\"a\",\"type\":\"Object\"}]"));
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);
}
/// <summary>Verifies that an expression of unknown type does not produce a false positive.</summary>
[Fact]
public void Validate_ArgumentType_UnknownExpression_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);
} }
// ── Return-type validation ────────────────────────────────────────── // ── Return-type validation ──────────────────────────────────────────
@@ -907,17 +897,23 @@ public class SemanticValidatorTests
public void ExtractCallTargets_MultipleCallTypes() public void ExtractCallTargets_MultipleCallTypes()
{ {
var code = @" var code = @"
var x = CallScript(""Script1"", arg1, arg2); var x = CallScript(""Script1"", new { a = 1, b = ""x, y"" });
CallShared(""Shared1""); CallShared(""Shared1"");
CallScript(""Script2""); CallScript(""Script2"", args);
// CallScript(""InComment"");
var name = ""CallShared(\""InString\"")"";
"; ";
var targets = SemanticValidator.ExtractCallTargets(code); var targets = SemanticValidator.ExtractCallTargets(code);
Assert.Equal(3, targets.Count); Assert.Equal(3, targets.Count);
Assert.Contains(targets, t => t.TargetName == "Script1" && !t.IsShared && t.ArgumentCount == 2); Assert.Contains(targets, t => t.TargetName == "Script1" && !t.IsShared
Assert.Contains(targets, t => t.TargetName == "Shared1" && t.IsShared && t.ArgumentCount == 0); && t.ParametersKind == SemanticValidator.CallParametersKind.AnonymousObject
Assert.Contains(targets, t => t.TargetName == "Script2" && !t.IsShared && t.ArgumentCount == 0); && 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 ───────────────────────────────────────────────────── // ── HiLo validation ─────────────────────────────────────────────────────