Skip to content

Commit

Permalink
Fix NRE due to array instantiation w/o initializer (#2398)
Browse files Browse the repository at this point in the history
  • Loading branch information
andrei-epure-sonarsource authored and duncanp-sonar committed Apr 24, 2019
1 parent c2366e4 commit 22c93d8
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -435,14 +435,15 @@ public static FormatStringArgument Create(ExpressionSyntax expression, SemanticM
{
var type = semanticModel.GetTypeInfo(expression).Type;
var arraySize = -1;
if (type.Is(TypeKind.Array))
if (type != null && type.Is(TypeKind.Array))
{
if (expression is ImplicitArrayCreationExpressionSyntax implicitArray)
{
arraySize = implicitArray.Initializer.Expressions.Count;
}

if (expression is ArrayCreationExpressionSyntax array)
if (expression is ArrayCreationExpressionSyntax array &&
array.Initializer != null)
{
arraySize = array.Initializer.Expressions.Count;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,14 @@ public void StringFormatTypoFreeValidator()
new StringFormatValidator(),
workingOptions);
}

[TestMethod]
[TestCategory("Rule")]
public void StringFormatEdgeCasesValidator()
{
Verifier.VerifyAnalyzer(@"TestCases\StringFormatEdgeCasesValidator.cs",
new StringFormatValidator(),
workingOptions);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Text;

namespace Tests.Diagnostics
{
public class StringFormatEdgeCasesValidator
{
// See https://github.com/SonarSource/sonar-dotnet/issues/2392
void EdgeCases(string bar)
{
var builder = new StringBuilder();
builder.AppendFormat("&invoice={0}", Foo(bar));
builder.AppendFormat("&invoice={0}", new object[0]);
builder.AppendFormat("&invoice={0}", new object[1] { 1 });
builder.AppendFormat("&invoice={0}", new [] { 1 });
builder.AppendFormat("&rm=2", new object[0]);
builder.AppendFormat("&rm=2", new[] { 1 }); // Noncompliant
builder.AppendFormat("&rm=2", new object[0] { } ); // Noncompliant
builder.AppendFormat("&rm=2", new object[1] { "a" } ); // Noncompliant
}

string Foo(string bar)
{
return "";
}
}
}

0 comments on commit 22c93d8

Please sign in to comment.