Skip to content

Commit

Permalink
Fix S3878 FP: Jagged arrays (#9102)
Browse files Browse the repository at this point in the history
  • Loading branch information
CristianAmbrosini authored Apr 17, 2024
1 parent 0e6d4b6 commit 1409c5a
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,19 @@ protected sealed override void Initialize(SonarAnalysisContext context) =>
context.RegisterNodeAction(Language.GeneratedCodeRecognizer, c =>
{
if (LastArgumentIfArrayCreation(c.Node) is { } lastArgument
&& IsParamParameter(c.SemanticModel, c.Node, lastArgument))
&& ParameterSymbol(c.SemanticModel, c.Node, lastArgument) is { IsParams: true } param
&& !IsJaggedArrayParam(param))
{
c.ReportIssue(Diagnostic.Create(rule, lastArgument.GetLocation()));
c.ReportIssue(rule, lastArgument.GetLocation());
}
}, ExpressionKinds);

private bool IsParamParameter(SemanticModel model, SyntaxNode invocation, TArgumentNode argument) =>
private IParameterSymbol ParameterSymbol(SemanticModel model, SyntaxNode invocation, TArgumentNode argument) =>
model.GetSymbolInfo(invocation).Symbol is IMethodSymbol methodSymbol
&& Language.MethodParameterLookup(invocation, methodSymbol).TryGetSymbol(argument, out var param)
&& param.IsParams;
? param
: null;

private static bool IsJaggedArrayParam(IParameterSymbol param) =>
param.Type is IArrayTypeSymbol { ElementType: IArrayTypeSymbol };
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
_ = new MyClass2([1], [1, 2, 3]); // Noncompliant
_ = new MyClass2([1, 2, 3], 1);

_ = new MyClass3([1, 2, 3], [4, 5, 6]); // Noncompliant FP
_ = new MyClass3([1, 2, 3], [4, 5, 6]); // Compliant: jagged array

_ = new MyClass4(class1, new(1, [1, .. array])); // Compliant
_ = new MyClass4([class1, new(1, [1, .. array])]); // Noncompliant, outer collection raises, despite the nested spread operator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public class Repro6894

public void Method(params object[] args) { }
public void MethodArray(params Array[] args) { }
public void MethodJuggedArray(params int[][] args) { }
public void MethodJaggedArray(params int[][] args) { }

public void CallMethod()
{
Expand All @@ -95,7 +95,7 @@ public void CallMethod()
MethodArray(new String[] { "1", "2" }, new String[] { "1", "2" }); // Noncompliant, FP. Elements in args: [System.String[], System.String[]]
MethodArray(new int[] { 1, 2 }, new int[] { 1, 2 }); // Noncompliant, FP. Elements in args: [System.Int32[], System.Int32[]]

MethodJuggedArray(new int[] { 1, 2 }); // Noncompliant, FP. Elements in args: [System.Object[]]
MethodJaggedArray(new int[] { 1, 2 }); // Compliant: jagged array [System.Object[]]
}
}

Expand Down

0 comments on commit 1409c5a

Please sign in to comment.