Skip to content

Commit

Permalink
Fix S2234: Check for parameter types before reporting it as bug (#1458)
Browse files Browse the repository at this point in the history
  • Loading branch information
valhristov authored and duncanp-sonar committed Jun 8, 2018
1 parent 716c7f4 commit 22ecb04
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -117,15 +117,14 @@ private static void AnalyzeArguments(SyntaxNodeAnalysisContext analysisContext,
var parameterName = parameter.Name;

if (string.IsNullOrEmpty(identifierName) ||
!parameterNames.Contains(identifierName))
!parameterNames.Contains(identifierName) ||
!IdentifierWithSameNameAndTypeExists(parameter))
{
continue;
}

if (identifierArgument is PositionalIdentifierArgument positional &&
(parameter.IsParams ||
!identifierNames.Contains(parameterName) ||
identifierName == parameterName))
(parameter.IsParams || identifierName == parameterName))
{
continue;
}
Expand All @@ -149,6 +148,14 @@ private static void AnalyzeArguments(SyntaxNodeAnalysisContext analysisContext,
additionalLocations: secondaryLocations,
messageArgs: methodSymbol.Name));
}

bool IdentifierWithSameNameAndTypeExists(IParameterSymbol parameter) =>
identifierArguments.Any(ia =>
ia.IdentifierName == parameter.Name &&
GetTypeSymbol(ia.ArgumentSyntax.Expression).DerivesOrImplements(parameter.Type));

ITypeSymbol GetTypeSymbol(SyntaxNode syntaxNode) =>
analysisContext.SemanticModel.GetTypeInfo(syntaxNode).ConvertedType;
}

private static List<IdentifierArgument> GetIdentifierArguments(ArgumentListSyntax argumentList)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ namespace Tests.Diagnostics
public class Params
{
public void method(int i, int k = 5, params int[] rest)
// ^^^^^^ Secondary [0]
{
}

Expand All @@ -21,8 +20,7 @@ public void call2()
{
int i = 0, j = 5, rest = 6, l = 7;
var k = new[] { i, l };
method(i, k : rest, rest : k); //Noncompliant [0]
// ^^^^^^
method(i, k : rest, rest : k); // Compliant, code will not compile if suggestion is applied
}
}

Expand Down Expand Up @@ -142,4 +140,24 @@ public void Bar()
new System. ()
}
}

class Program
{
void Struct(DateTime a, string b)
{
Bar1(a, b); // Compliant
}

void ClassAndInterface(Boo a, string b)
{
Bar2(a, b); // Compliant
Bar3(a, b); // Compliant
Bar3(b: a, a: b); // Compliant
}
void Bar1(DateTime b, string a) { }
void Bar2(Boo b, string a) { }
void Bar3(IBoo b, string a) { }
}
interface IBoo { }
class Boo : IBoo { }
}

0 comments on commit 22ecb04

Please sign in to comment.