Fix MA0003 exclusions applied to the arguments of target-typed new expressions
What
To apply its exclusions (method names, number of parameters, excluded methods options, ...), MA0003 looked for the invocation that contains the argument by walking up the syntax, but it only considered InvocationExpression, ObjectCreationExpression and ElementAccessExpression. For an argument of a target-typed new(...), it found the enclosing call instead, and applied the exclusions of that method:
class Foo
{
Foo(bool value) { }
void Test(List<Foo> list)
{
list.Add(new Foo(true)); // MA0003 reported
list.Add(new(true)); // not reported: the exclusion of Add(x) was applied
}
}
Conversely, the exclusions of the constructor were not applied, e.g. M(new("key", null), true) with a KeyValuePair<string, object> parameter reported null, whereas new KeyValuePair<string, object>("key", null) is excluded.
Fix
The invoked member is now taken from the parent operation of the IArgumentOperation instead of the syntax: the method of an IInvocationOperation, the constructor of an IObjectCreationOperation (explicit or target-typed new), or the indexer of an IPropertyReferenceOperation. This also fixes the indexers of object initializers (new C { [true, false] = 0 }), for which the constructor of the created object was used.
An extension method called as an instance method (value.Method(x)) is bound to the method that takes the receiver as its first parameter, so it is reduced to match the arguments written in the code, like the symbol returned by GetSymbolInfo.
Tests
- Added
ImplicitCtor_InExcludedMethod_ShouldReportDiagnostic,ImplicitCtor_ExcludedCtor_ShouldNotReportDiagnostic(both failed before the fix),IndexerInObjectInitializer_ShouldReportDiagnosticandExtensionMethodCalledAsInstanceMethod_ExcludedMethod_ShouldNotReportDiagnostic. - The
NamedParametertests pass on roslyn5.9 (92 tests) and roslyn4.8 (89 tests).