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
@@ -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