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

Implement 'Prefer null check over type check' #53947

Merged
merged 19 commits into from
Jun 28, 2021
Merged
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
1 change: 1 addition & 0 deletions src/Analyzers/CSharp/Analyzers/CSharpAnalyzers.projitems
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@
<Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\Helpers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseIndexOrRangeOperator\MemberInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseInferredMemberName\CSharpUseInferredMemberNameDiagnosticAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseIsNullCheck\CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseIsNullCheck\CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseIsNullCheck\CSharpUseIsNullCheckForReferenceEqualsDiagnosticAnalyzer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseLocalFunction\CSharpUseLocalFunctionDiagnosticAnalyzer.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,9 @@
<data name="Use_is_null_check" xml:space="preserve">
<value>Use 'is null' check</value>
</data>
<data name="Prefer_null_check_over_type_check" xml:space="preserve">
<value>Prefer 'null' check over type check</value>
</data>
<data name="Use_simple_using_statement" xml:space="preserve">
<value>Use simple 'using' statement</value>
</data>
Expand Down Expand Up @@ -314,4 +317,7 @@
<data name="Blank_line_not_allowed_after_constructor_initializer_colon" xml:space="preserve">
<value>Blank line not allowed after constructor initializer colon</value>
</data>
<data name="Null_check_can_be_clarified" xml:space="preserve">
<value>Null check can be clarified</value>
</data>
</root>
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public CSharpUseNullCheckOverTypeCheckDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseNullCheckOverTypeCheckDiagnosticId,
EnforceOnBuildValues.UseNullCheckOverTypeCheck,
CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck,
CSharpAnalyzersResources.Prefer_null_check_over_type_check,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Null_check_can_be_clarified), AnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
}

public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;

protected override void InitializeWorker(AnalysisContext context)
{
context.RegisterCompilationStartAction(context =>
{
if (((CSharpCompilation)context.Compilation).LanguageVersion < LanguageVersion.CSharp9)
{
return;
}

context.RegisterOperationAction(c => AnalyzeIsTypeOperation(c), OperationKind.IsType);
context.RegisterOperationAction(c => AnalyzeNegatedPatternOperation(c), OperationKind.NegatedPattern);
Copy link
Member

Choose a reason for hiding this comment

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

👍

});
}

private static bool ShouldAnalyze(OperationAnalysisContext context, out ReportDiagnostic severity)
{
var option = context.Options.GetOption(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, context.Operation.Syntax.SyntaxTree, context.CancellationToken);
if (!option.Value)
{
severity = ReportDiagnostic.Default;
return false;
}

severity = option.Notification.Severity;
return true;
}

private void AnalyzeNegatedPatternOperation(OperationAnalysisContext context)
{
if (!ShouldAnalyze(context, out var severity) ||
context.Operation.Syntax is not UnaryPatternSyntax)
{
return;
}

var negatedPattern = (INegatedPatternOperation)context.Operation;
// Matches 'x is not MyType'
// InputType is the type of 'x'
// MatchedType is 'MyType'
// We check InheritsFromOrEquals so that we report a diagnostic on the following:
// 1. x is not object (which is also equivalent to 'is null' check)
// 2. derivedObj is parentObj (which is the same as the previous point).
// 3. str is string (where str is a string, this is also equivalent to 'is null' check).
// This doesn't match `x is not MyType y` because in such case, negatedPattern.Pattern will
// be `DeclarationPattern`, not `TypePattern`.
if (negatedPattern.Pattern is ITypePatternOperation typePatternOperation &&
typePatternOperation.InputType.InheritsFromOrEquals(typePatternOperation.MatchedType))
CyrusNajmabadi marked this conversation as resolved.
Show resolved Hide resolved
{
context.ReportDiagnostic(
DiagnosticHelper.Create(
Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null));
}
}

private void AnalyzeIsTypeOperation(OperationAnalysisContext context)
{
if (!ShouldAnalyze(context, out var severity) ||
context.Operation.Syntax is not BinaryExpressionSyntax)
{
return;
}

var isTypeOperation = (IIsTypeOperation)context.Operation;
// Matches 'x is MyType'
// isTypeOperation.TypeOperand is 'MyType'
// isTypeOperation.ValueOperand.Type is the type of 'x'.
// We check InheritsFromOrEquals for the same reason as stated in AnalyzeNegatedPatternOperation.
// This doesn't match `x is MyType y` because in such case, we have an IsPattern instead of IsType operation.
if (isTypeOperation.ValueOperand.Type is not null &&
isTypeOperation.ValueOperand.Type.InheritsFromOrEquals(isTypeOperation.TypeOperand))
CyrusNajmabadi marked this conversation as resolved.
Show resolved Hide resolved
{
context.ReportDiagnostic(
DiagnosticHelper.Create(
Descriptor, context.Operation.Syntax.GetLocation(), severity, additionalLocations: null, properties: null));
}
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/Analyzers/CSharp/CodeFixes/CSharpCodeFixes.projitems
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
<Compile Include="$(MSBuildThisFileDirectory)UseInferredMemberName\CSharpUseInferredMemberNameCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseIsNullCheck\CSharpUseIsNullCheckForCastAndEqualityOperatorCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseIsNullCheck\CSharpUseIsNullCheckForReferenceEqualsCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseIsNullCheck\CSharpUseNullCheckOverTypeCheckCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseNullPropagation\CSharpUseNullPropagationCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseObjectInitializer\CSharpUseObjectInitializerCodeFixProvider.cs" />
<Compile Include="$(MSBuildThisFileDirectory)UseObjectInitializer\UseInitializerHelpers.cs" />
Expand Down
Loading