From 607ffc2e159e9726d18555a7e35a1a2aa34e3da1 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Sat, 28 Nov 2026 06:55:58 -0500 Subject: [PATCH] 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. --- docs/requirements/Component-TemplateEngine.md | 2 +- .../Validation/SemanticValidator.cs | 491 +++++++-------- .../Validation/SemanticValidatorTests.cs | 560 +++++++++--------- 3 files changed, 525 insertions(+), 528 deletions(-) diff --git a/docs/requirements/Component-TemplateEngine.md b/docs/requirements/Component-TemplateEngine.md index 619af992..836b8925 100644 --- a/docs/requirements/Component-TemplateEngine.md +++ b/docs/requirements/Component-TemplateEngine.md @@ -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. diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Validation/SemanticValidator.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Validation/SemanticValidator.cs index 16b490e9..67e5b2f1 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Validation/SemanticValidator.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Validation/SemanticValidator.cs @@ -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; /// /// 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( 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 } } + /// + /// Parameter validation for a CallScript/CallShared call site. + /// The runtime has no positional form: both methods take ONE + /// parameters object which turns into + /// a name → value dictionary (ScadaBridge#150). So the check depends on what + /// that one argument is: + /// + /// Absent — the target receives no parameters; any REQUIRED + /// declared parameter is an error. + /// Anonymous object (new { A = 1, B = x }) — 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). + /// Anything else (a variable, dictionary, method call, + /// null, …) — its keys can't be known statically, so nothing is + /// checked. + /// + /// private static void ValidateCallParameters( string callerName, CallTarget call, - Dictionary> paramMap, - List errors) + Dictionary> paramMap, + List errors, + List 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(StringComparer.Ordinal); + foreach (var field in declared) + declaredByName.TryAdd(field.Name, field); - /// - /// 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: - /// - /// Declared type must normalize to a known primitive (String, Integer, - /// Float, Boolean). Object/List/unknown declarations accept - /// anything — never flagged. - /// Argument expression type must be inferable from a literal - /// (string/char, integer, decimal, true/false). Variables, - /// member access, method/await chains, null, casts, object/array - /// initializers, and anything else infer to Unknown and are never flagged. - /// Integer⇄Float is treated as compatible (numeric widening) — never - /// flagged. - /// - /// - private static void ValidateArgumentTypes( - string callerName, - CallTarget call, - List expectedParams, - List 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( + 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 names) => + (names.Count == 1 ? "parameter " : "parameters ") + + string.Join(", ", names.Select(n => $"'{n}'")); } /// @@ -478,64 +527,46 @@ public class SemanticValidator } } - private static Dictionary> BuildParameterMap(IReadOnlyList scripts) + private static Dictionary> BuildParameterMap(IReadOnlyList scripts) { - var result = new Dictionary>(StringComparer.Ordinal); + var result = new Dictionary>(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; } /// - /// 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 [{name,type,required}] array) into its declared + /// fields — name, required flag and type — via the shared + /// parser, so "required" means exactly what it + /// means everywhere else (JSON Schema: listed in required; legacy: + /// required unless required is explicitly false). /// - /// JSON Schema or legacy flat-array string; null/empty returns an empty list. - /// The per-parameter raw type strings (e.g. "Int32", "string", "List"). - internal static List ParseParameterTypes(string? parameterDefinitionsJson) + /// The definition JSON; null/empty means "no parameters". + /// The declared fields (empty for no parameters), or null when the JSON can't be parsed. + internal static IReadOnlyList? 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 []; } /// @@ -577,151 +608,126 @@ public class SemanticValidator return result; } + private static readonly CSharpParseOptions ScriptParseOptions = + CSharpParseOptions.Default + .WithKind(SourceCodeKind.Script) + .WithLanguageVersion(LanguageVersion.Latest); + /// - /// 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 CallScript(...) / CallShared(...) invocation + /// (unqualified or receiver-qualified — Instance., Scripts., + /// Parent., Children["x"].) 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. /// /// The script source code to scan. /// The list of call targets found (both CallScript and CallShared invocations). internal static List ExtractCallTargets(string code) { var results = new List(); + 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()) + { + 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 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 results) + /// + /// Finds an invocation argument by C# binding rules: a named argument + /// (name: value) wins; otherwise the positional argument at + /// , provided every argument before it is + /// positional too. + /// + private static ArgumentSyntax? FindArgument(SeparatedSyntaxList 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(); - - 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]; } /// - /// 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 Name = (new { x } → x, + /// new { a.B } → B); null when none can be inferred. /// - private static List SplitCallArguments(string code, int startPos) + private static string? InferAnonymousMemberName(ExpressionSyntax expression) => expression switch { - var args = new List(); - 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 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, + }; /// /// 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) + /// What a call site passes as its single parameters argument. + 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]; + /// No parameters argument — the target receives no parameters. + None, + /// An anonymous-object creation (new { A = 1 }) — names are known statically. + AnonymousObject, + /// Any other expression (variable, dictionary, call, null) — keys unknown statically. + Opaque, } + /// One member of an anonymous-object parameters argument. + /// The member (parameter) name, or null when it can't be determined. + /// The member's value expression text. + internal sealed record CallParameterMember(string? Name, string Expression); + internal record CallTarget { /// Name of the script being called. public string TargetName { get; init; } = string.Empty; /// True when the call is to a shared script via CallShared. public bool IsShared { get; init; } - /// Number of non-name arguments passed to the call. - public int ArgumentCount { get; init; } - /// The trimmed text of each non-name positional argument expression, in order. - public IReadOnlyList ArgumentExpressions { get; init; } = []; + /// What the call passes as its parameters argument. + public CallParametersKind ParametersKind { get; init; } + /// For : the object's members, in order; otherwise empty. + public IReadOnlyList ParameterMembers { get; init; } = []; /// /// The declared type token the call result is assigned into, when the /// call is the whole initializer of a typed local declaration; otherwise diff --git a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Validation/SemanticValidatorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Validation/SemanticValidatorTests.cs index 9630fc41..338d622a 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Validation/SemanticValidatorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Validation/SemanticValidatorTests.cs @@ -223,323 +223,313 @@ public class SemanticValidatorTests Assert.DoesNotContain(result.Errors, e => e.Category == ValidationCategory.CallTargetNotFound); } - /// Verifies that a parameter count mismatch returns an error. - [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 + { + 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); + + /// Issue #150 repro: CallShared with an anonymous object supplying every declared parameter is valid. + [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); + } + + /// CallShared with an anonymous object missing a required parameter is an error naming it. + [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)); + } + + /// A missing parameter declared optional (required:false) is not an error. + [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); + } + + /// An extra member the target doesn't declare is a warning, not an error. + [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)); + } + + /// A dictionary variable's keys can't be known statically — never flagged. + [Fact] + public void CallShared_DictionaryVariable_NoError() + { + var result = ValidateCallShared( + "var args = new Dictionary { [\"Subject\"] = \"Hi\" }; await Scripts.CallShared(\"SendNotificationExample\", args);", + ThreeParamsLegacy); + + AssertNoParameterErrors(result); + } + + /// No parameters argument against a target with required parameters is an error. + [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 ──────────────────────────────────────── - - /// Verifies that passing a string for an integer parameter returns an error. + /// No parameters argument against a target that declares none is valid. [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); + } + + /// A trailing CancellationToken argument doesn't disturb parsing of the parameters object. + [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); + } + + /// JSON Schema form: only the names listed in "required" are required. + [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)); + } + + /// CallScript with an anonymous object supplying every declared parameter is valid. + [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); + } + + /// CallScript with an anonymous object missing a required parameter is an error. + [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)); + } + + /// CallScript: an unknown member name is a warning only. + [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)); + } + + /// CallScript: name matching is ordinal, as the runtime dictionary is. + [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); + } + + /// CallScript: a projection initializer (new { a }) supplies the parameter named after the variable. + [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); + } + + /// CallScript with a dictionary variable is never flagged. + [Fact] + public void CallScript_DictionaryVariable_NoError() + { + var result = ValidateCallScript( + "CallScript(\"Target\", Parameters);", + "[{\"name\":\"a\",\"type\":\"Int32\"}]"); + + AssertNoParameterErrors(result); + } + + /// CallScript with a null parameters argument is opaque — not checked. + [Fact] + public void CallScript_NullParameters_NoError() + { + var result = ValidateCallScript( + "CallScript(\"Target\", null);", + "[{\"name\":\"a\",\"type\":\"Int32\"}]"); + + AssertNoParameterErrors(result); + } + + /// CallScript with no arguments against required parameters is an error. + [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); + } + + /// CallScript with no arguments against a target with no parameters is valid. + [Fact] + public void CallScript_NoArgumentsAgainstNoParams_NoError() + { + AssertNoParameterErrors(ValidateCallScript("CallScript(\"Target\");", null)); + AssertNoParameterErrors(ValidateCallScript("CallScript(\"Target\");", "[]")); + } + + // ── Member-type validation (anonymous-object members) ─────────────── + + /// A string literal for an integer parameter is a type error. + [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)); } - /// Verifies that passing a number for a string parameter returns an error. + /// A number literal for a string parameter is a type error. [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)); } - /// Verifies that passing a boolean for an integer parameter returns an error. + /// A boolean literal for an integer parameter is a type error. [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); } - /// Verifies that literals of the correct types produce no error. + /// An integer literal for a float parameter is accepted (numeric widening). [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\"}]")); } - /// Verifies that passing an integer literal for a float parameter produces no error. - [Fact] - public void Validate_ArgumentType_IntegerLiteralForFloat_NoError() + /// Non-literal member expressions are never type-flagged. + [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\"}]")); } - /// Verifies that an expression of unknown type does not produce a false positive. + /// An Object-typed parameter accepts any literal. [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); - } - - /// Verifies that an object initializer argument does not produce a false positive. - [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); - } - - /// Verifies that an untyped parameter does not produce a false positive. - [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); - } - - /// Verifies that a compound expression starting with a literal does not produce a false positive. - [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); - } - - /// Verifies that a concatenated string expression does not produce a false positive. - [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 ─────────────────────────────────────────────────────