Skip to content
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

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions src/Faithlife.Analyzers/NullTestTernariesAnalyzer.cs
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",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
messageFormat: "Prefer null conditional operators over ternaries explicitly checking for null",
messageFormat: "Use null propagation",

The message from IDE0031 is simpler and appropriate.

category: "Usage",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
helpLinkUri: $"https://github.com/Faithlife/FaithlifeAnalyzers/wiki/{DiagnosticId}"
);
}
}
102 changes: 102 additions & 0 deletions tests/Faithlife.Analyzers.Tests/NullTestTernariesTests.cs
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
Copy link
Member

Choose a reason for hiding this comment

The 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.

Copy link
Member

Choose a reason for hiding this comment

The 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();
}
}