forked from dotnet/roslyn
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCSharpAsAndNullCheckDiagnosticAnalyzer.cs
172 lines (146 loc) · 6.61 KB
/
CSharpAsAndNullCheckDiagnosticAnalyzer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching
{
/// <summary>
/// Looks for code of the form:
///
/// var x = o as Type;
/// if (x != null) ...
///
/// and converts it to:
///
/// if (o is Type x) ...
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpAsAndNullCheckDiagnosticAnalyzer : AbstractCodeStyleDiagnosticAnalyzer, IBuiltInAnalyzer
{
public bool OpenFileOnly(Workspace workspace) => false;
public CSharpAsAndNullCheckDiagnosticAnalyzer()
: base(IDEDiagnosticIds.InlineAsTypeCheckId,
new LocalizableResourceString(
nameof(FeaturesResources.Use_pattern_matching), FeaturesResources.ResourceManager, typeof(FeaturesResources)))
{
}
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(SyntaxNodeAction, SyntaxKind.IfStatement);
}
private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
{
var options = syntaxContext.Options;
var syntaxTree = syntaxContext.Node.SyntaxTree;
var cancellationToken = syntaxContext.CancellationToken;
var optionSet = options.GetDocumentOptionSetAsync(syntaxTree, cancellationToken).GetAwaiter().GetResult();
if (optionSet == null)
{
return;
}
var styleOption = optionSet.GetOption(CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck);
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
return;
}
var severity = styleOption.Notification.Value;
// look for the form "if (a != null)" or "if (null != a)"
var ifStatement = (IfStatementSyntax)syntaxContext.Node;
// "x is Type y" is only available in C# 7.0 and above. Don't offer this refactoring
// in projects targetting a lesser version.
if (((CSharpParseOptions)ifStatement.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp7)
{
return;
}
// If has to be in a block so we can at least look for a preceding local variable declaration.
if (!ifStatement.Parent.IsKind(SyntaxKind.Block))
{
return;
}
// We need to find the leftmost expression in teh if-condition. If this is a
// "x != null" expression the we can replace it with "o as Type x".
var condition = GetLeftmostCondition(ifStatement.Condition);
if (!condition.IsKind(SyntaxKind.NotEqualsExpression))
{
return;
}
// look for the form "x != null" or "null != x".
if (!IsNullCheckExpression(condition.Left, condition.Right) &&
!IsNullCheckExpression(condition.Right, condition.Left))
{
return;
}
var conditionName = condition.Left is IdentifierNameSyntax
? (IdentifierNameSyntax)condition.Left
: (IdentifierNameSyntax)condition.Right;
// Now make sure the previous statement is "var a = ..."
var parentBlock = (BlockSyntax)ifStatement.Parent;
var ifIndex = parentBlock.Statements.IndexOf(ifStatement);
if (ifIndex == 0)
{
return;
}
var previousStatement = parentBlock.Statements[ifIndex - 1];
if (!previousStatement.IsKind(SyntaxKind.LocalDeclarationStatement))
{
return;
}
var localDeclarationStatement = (LocalDeclarationStatementSyntax)previousStatement;
var variableDeclaration = localDeclarationStatement.Declaration;
if (variableDeclaration.Variables.Count != 1)
{
return;
}
var declarator = variableDeclaration.Variables[0];
if (declarator.Initializer == null)
{
return;
}
if (!Equals(declarator.Identifier.ValueText, conditionName.Identifier.ValueText))
{
return;
}
// Make sure the initializer has the form "... = expr as Type;
var initializerValue = declarator.Initializer.Value;
if (!initializerValue.IsKind(SyntaxKind.AsExpression))
{
return;
}
// Looks good!
var additionalLocations = ImmutableArray.Create(
localDeclarationStatement.GetLocation(),
ifStatement.GetLocation(),
condition.GetLocation(),
initializerValue.GetLocation());
// Put a diagnostic with the appropriate severity on the declaration-statement itself.
syntaxContext.ReportDiagnostic(Diagnostic.Create(
CreateDescriptor(this.DescriptorId, severity),
localDeclarationStatement.GetLocation(),
additionalLocations));
}
private BinaryExpressionSyntax GetLeftmostCondition(ExpressionSyntax condition)
{
switch (condition.Kind())
{
case SyntaxKind.ParenthesizedExpression:
return GetLeftmostCondition(((ParenthesizedExpressionSyntax)condition).Expression);
case SyntaxKind.ConditionalExpression:
return GetLeftmostCondition(((ConditionalExpressionSyntax)condition).Condition);
case SyntaxKind.LogicalAndExpression:
case SyntaxKind.LogicalOrExpression:
return GetLeftmostCondition(((BinaryExpressionSyntax)condition).Left);
}
return condition as BinaryExpressionSyntax;
}
private bool IsNullCheckExpression(ExpressionSyntax left, ExpressionSyntax right) =>
left.IsKind(SyntaxKind.IdentifierName) && right.IsKind(SyntaxKind.NullLiteralExpression);
public DiagnosticAnalyzerCategory GetAnalyzerCategory()
{
return DiagnosticAnalyzerCategory.SemanticDocumentAnalysis;
}
}
}