Skip to content

Commit

Permalink
Treat String.Empty as "", fixes #32
Browse files Browse the repository at this point in the history
  • Loading branch information
Suchiman committed Jun 1, 2018
1 parent 7caa191 commit d457b80
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 4 deletions.
47 changes: 47 additions & 0 deletions SerilogAnalyzer/SerilogAnalyzer.Test/AnalyzerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,53 @@ public static void Test()
VerifyCSharpDiagnostic(src, expected);
}

[TestMethod]
public void TestStringEmptyIsConstantMessageTemplate()
{
string src = @"
using Serilog;
using System;
class TypeName
{
public static void Test()
{
Log.Error(String.Empty);
Log.Error(string.Empty);
}
}";

VerifyCSharpDiagnostic(src);
}

[TestMethod]
public void TestStringEmptyWithTooManyArguments()
{
string src = @"
using Serilog;
using System;
class TypeName
{
public static void Test()
{
Log.Error(String.Empty, ""Hello"");
}
}";

var expected = new DiagnosticResult
{
Id = "Serilog003",
Message = String.Format("Error while binding properties: {0}", "There is no property that corresponds to this argument"),
Severity = DiagnosticSeverity.Error,
Locations = new[]
{
new DiagnosticResultLocation("Test0.cs", 9, 37, 7)
}
};
VerifyCSharpDiagnostic(src, expected);
}

[TestMethod]
public void TestDiagnosticLengthWithEscapes()
{
Expand Down
16 changes: 12 additions & 4 deletions SerilogAnalyzer/SerilogAnalyzer/DiagnosticAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,15 +146,23 @@ private static void AnalyzeSymbol(SyntaxNodeAnalysisContext context)
{
// can we at least get a computed constant value for it?
var constantValue = context.SemanticModel.GetConstantValue(argument.Expression, context.CancellationToken);
if (!constantValue.HasValue || !(constantValue.Value is string))
if (!constantValue.HasValue || !(constantValue.Value is string constString))
{
context.ReportDiagnostic(Diagnostic.Create(ConstantMessageTemplateRule, argument.Expression.GetLocation(), argument.Expression.ToString()));
continue;
INamedTypeSymbol StringType() => context.SemanticModel.Compilation.GetTypeByMetadataName("System.String");
if (context.SemanticModel.GetSymbolInfo(argument.Expression, context.CancellationToken).Symbol is IFieldSymbol field && field.Name == "Empty" && field.Type == StringType())
{
constString = "";
}
else
{
context.ReportDiagnostic(Diagnostic.Create(ConstantMessageTemplateRule, argument.Expression.GetLocation(), argument.Expression.ToString()));
continue;
}
}

// we can't map positions back from the computed string into the real positions
exactPositions = false;
messageTemplate = constantValue.Value as string;
messageTemplate = constString;
}

literalSpan = argument.Expression.GetLocation().SourceSpan;
Expand Down

0 comments on commit d457b80

Please sign in to comment.