-
Notifications
You must be signed in to change notification settings - Fork 11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Prefer null conditional over ternaries #75
base: master
Are you sure you want to change the base?
Changes from all commits
dc701c9
01f90e5
cc54c9e
7293055
49cde01
2e8aed7
247751a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
using System.Collections.Immutable; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
|
||
namespace Faithlife.Analyzers | ||
{ | ||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public sealed class NullTestTernariesAnalyzer : DiagnosticAnalyzer | ||
{ | ||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
|
||
context.RegisterCompilationStartAction(compilationStartAnalysisContext => | ||
{ | ||
compilationStartAnalysisContext.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.ConditionalExpression); | ||
}); | ||
} | ||
|
||
private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context) | ||
{ | ||
var expression = (ConditionalExpressionSyntax) context.Node; | ||
var falseValue = expression.WhenFalse; | ||
var trueValue = expression.WhenTrue; | ||
|
||
if (expression.Condition is BinaryExpressionSyntax binaryExpression) | ||
{ | ||
var lExpression = binaryExpression.Left; | ||
var rExpression = binaryExpression.Right; | ||
|
||
if ((falseValue.Kind() == SyntaxKind.NullLiteralExpression || trueValue.Kind() == SyntaxKind.NullLiteralExpression) && (lExpression.Kind() == SyntaxKind.NullLiteralExpression || rExpression.Kind() == SyntaxKind.NullLiteralExpression)) | ||
{ | ||
context.ReportDiagnostic(Diagnostic.Create(s_rule, expression.GetLocation())); | ||
} | ||
} | ||
else if (expression.Condition is MemberAccessExpressionSyntax memberAccessExpression) | ||
{ | ||
if (memberAccessExpression.Kind() == SyntaxKind.SimpleMemberAccessExpression && memberAccessExpression.Name.Identifier.Text == "HasValue") | ||
{ | ||
context.ReportDiagnostic(Diagnostic.Create(s_rule, expression.GetLocation())); | ||
} | ||
} | ||
else if (expression.Condition is PrefixUnaryExpressionSyntax prefixUnaryExpression && expression.Condition.Kind() == SyntaxKind.LogicalNotExpression) | ||
{ | ||
if (((MemberAccessExpressionSyntax) prefixUnaryExpression.Operand).Name.Identifier.Text == "HasValue") | ||
{ | ||
context.ReportDiagnostic(Diagnostic.Create(s_rule, expression.GetLocation())); | ||
} | ||
} | ||
} | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_rule); | ||
|
||
public const string DiagnosticId = "FL0015"; | ||
|
||
private static readonly DiagnosticDescriptor s_rule = new( | ||
id: DiagnosticId, | ||
title: "Null Checking Ternaries Usage", | ||
messageFormat: "Prefer null conditional operators over ternaries explicitly checking for null", | ||
category: "Usage", | ||
defaultSeverity: DiagnosticSeverity.Warning, | ||
isEnabledByDefault: true, | ||
helpLinkUri: $"https://github.com/Faithlife/FaithlifeAnalyzers/wiki/{DiagnosticId}" | ||
); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using NUnit.Framework; | ||
|
||
namespace Faithlife.Analyzers.Tests | ||
{ | ||
[TestFixture] | ||
public class NullTestTernariesTests : CodeFixVerifier | ||
{ | ||
[TestCase("Person person = null;", "var firstName = person?.FirstName;")] | ||
[TestCase("var person = new Person { FirstName = \"Bob\", LastName = \"Dole\" };", "var firstName = person.Age?.BirthYear;")] | ||
public void ValidUsage(string declaration, string ternary) | ||
{ | ||
string validProgram = $@" | ||
namespace TestApplication | ||
{{ | ||
public class Person | ||
{{ | ||
public string FirstName {{ get; set; }} | ||
public string LastName {{ get; set; }} | ||
public Age? Age {{ get; set; }} | ||
}} | ||
|
||
public struct Age | ||
{{ | ||
public int? InYears {{ get; set; }} | ||
|
||
public int? BirthYear | ||
{{ | ||
get | ||
{{ | ||
return System.DateTime.Now.Year - InYears; | ||
}} | ||
}} | ||
}} | ||
|
||
internal static class TestClass | ||
{{ | ||
public static void UtilityMethod() | ||
{{ | ||
{declaration} | ||
{ternary} | ||
}} | ||
}} | ||
}}"; | ||
|
||
VerifyCSharpDiagnostic(validProgram); | ||
} | ||
|
||
[TestCase("var firstName = person != null ? person.FirstName : null;")] | ||
[TestCase("var firstName = person == null ? null : person.FirstName;")] | ||
Comment on lines
+50
to
+51
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These are already handled by IDE0031; we shouldn't create (or maintain) functionality that duplicates built-in analysers. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. (These tests shouldn't just be deleted; they should be moved to the "good" test (even though they're not good code) to verify that the analyser isn't alerting on them.) |
||
[TestCase("var firstName = person.Age.HasValue ? person.Age.Value.BirthYear : null;")] | ||
[TestCase("var firstName = !person.Age.HasValue ? null : person.Age.Value.BirthYear;")] | ||
public void InvalidUsage(string badExample) | ||
{ | ||
var brokenProgram = $@" | ||
namespace TestApplication | ||
{{ | ||
public class Person | ||
{{ | ||
public string FirstName {{ get; set; }} | ||
public string LastName {{ get; set; }} | ||
public Age? Age {{ get; set; }} | ||
}} | ||
|
||
public struct Age | ||
{{ | ||
public int? InYears {{ get; set; }} | ||
|
||
public int? BirthYear | ||
{{ | ||
get | ||
{{ | ||
return System.DateTime.Now.Year - InYears; | ||
}} | ||
}} | ||
}} | ||
|
||
internal static class TestClass | ||
{{ | ||
public static void UtilityMethod() | ||
{{ | ||
var person = new Person {{ FirstName = ""Bob"", LastName = ""Dole"" }}; | ||
{badExample} | ||
}} | ||
}} | ||
}}"; | ||
|
||
var expected = new DiagnosticResult | ||
{ | ||
Id = NullTestTernariesAnalyzer.DiagnosticId, | ||
Message = "Prefer null conditional operators over ternaries explicitly checking for null", | ||
Severity = DiagnosticSeverity.Warning, | ||
Locations = new[] { new DiagnosticResultLocation("Test0.cs", 29, 20) }, | ||
}; | ||
|
||
VerifyCSharpDiagnostic(brokenProgram, expected); | ||
} | ||
|
||
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() => new NullTestTernariesAnalyzer(); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The message from IDE0031 is simpler and appropriate.