/
UseConditionalAccessAnalyzer.cs
445 lines (349 loc) · 15.2 KB
/
UseConditionalAccessAnalyzer.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// Copyright (c) Josef Pihrt and Contributors. 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 System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using Roslynator.CSharp;
using Roslynator.CSharp.Syntax;
namespace Roslynator.CSharp.Analysis;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class UseConditionalAccessAnalyzer : BaseDiagnosticAnalyzer
{
private static ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics;
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
if (_supportedDiagnostics.IsDefault)
Immutable.InterlockedInitialize(ref _supportedDiagnostics, DiagnosticRules.UseConditionalAccess);
return _supportedDiagnostics;
}
}
public override void Initialize(AnalysisContext context)
{
base.Initialize(context);
context.RegisterCompilationStartAction(startContext =>
{
if (((CSharpCompilation)startContext.Compilation).LanguageVersion < LanguageVersion.CSharp6)
return;
startContext.RegisterSyntaxNodeAction(f => AnalyzeIfStatement(f), SyntaxKind.IfStatement);
startContext.RegisterSyntaxNodeAction(f => AnalyzeBinaryExpression(f), SyntaxKind.LogicalAndExpression);
startContext.RegisterSyntaxNodeAction(f => AnalyzeBinaryExpression(f), SyntaxKind.LogicalOrExpression);
});
}
private static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context)
{
var ifStatement = (IfStatementSyntax)context.Node;
if (!ifStatement.IsSimpleIf())
return;
if (ifStatement.ContainsDiagnostics)
return;
if (ifStatement.SpanContainsDirectives())
return;
NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(
ifStatement.Condition,
allowedStyles: NullCheckStyles.NotEqualsToNull | NullCheckStyles.IsNotNull);
ExpressionSyntax expression = nullCheck.Expression;
if (expression is null)
return;
SimpleMemberInvocationStatementInfo invocationInfo = SyntaxInfo.SimpleMemberInvocationStatementInfo(ifStatement.SingleNonBlockStatementOrDefault());
ExpressionSyntax expression2 = invocationInfo.Expression;
if (expression2 is null)
return;
ITypeSymbol typeSymbol = context.SemanticModel.GetTypeSymbol(expression);
if (typeSymbol is null)
return;
if (typeSymbol.IsNullableType())
{
if (!expression2.IsKind(SyntaxKind.SimpleMemberAccessExpression))
return;
var memberAccess = (MemberAccessExpressionSyntax)expression2;
if (memberAccess.Name is not IdentifierNameSyntax identifierName)
return;
if (!string.Equals(identifierName.Identifier.ValueText, "Value", StringComparison.Ordinal))
return;
expression2 = memberAccess.Expression;
}
if (!CSharpFactory.AreEquivalent(expression, expression2))
return;
if (ifStatement.IsInExpressionTree(context.SemanticModel, context.CancellationToken))
return;
DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.UseConditionalAccess, ifStatement);
}
private static void AnalyzeBinaryExpression(SyntaxNodeAnalysisContext context)
{
var binaryExpression = (BinaryExpressionSyntax)context.Node;
if (binaryExpression.ContainsDiagnostics)
return;
SyntaxKind kind = binaryExpression.Kind();
if (binaryExpression.WalkUpParentheses().IsParentKind(kind))
return;
if (binaryExpression.IsInExpressionTree(context.SemanticModel, context.CancellationToken))
return;
(ExpressionSyntax left, ExpressionSyntax right) = GetFixableExpressions(binaryExpression, kind, context.SemanticModel, context.CancellationToken);
if (left is null)
return;
ISymbol operatorSymbol = context.SemanticModel.GetSymbol(binaryExpression, context.CancellationToken);
if (operatorSymbol?.Name == WellKnownMemberNames.BitwiseOrOperatorName)
{
INamedTypeSymbol containingType = operatorSymbol.ContainingType;
if (containingType.SpecialType != SpecialType.System_Boolean
&& !ExistsImplicitConversionToBoolean(containingType))
{
return;
}
}
DiagnosticHelpers.ReportDiagnostic(
context,
DiagnosticRules.UseConditionalAccess,
Location.Create(binaryExpression.SyntaxTree, TextSpan.FromBounds(left.SpanStart, right.Span.End)));
static bool ExistsImplicitConversionToBoolean(INamedTypeSymbol typeSymbol)
{
foreach (ISymbol member in typeSymbol.GetMembers(WellKnownMemberNames.ImplicitConversionName))
{
if (member.Kind == SymbolKind.Method)
{
var methodSymbol = (IMethodSymbol)member;
if (methodSymbol.ReturnType.SpecialType == SpecialType.System_Boolean)
return true;
}
}
return false;
}
}
private static bool IsFixable(
ExpressionSyntax left,
ExpressionSyntax right,
SyntaxKind binaryExpressionKind,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
NullCheckStyles allowedStyles = (binaryExpressionKind == SyntaxKind.LogicalAndExpression)
? (NullCheckStyles.NotEqualsToNull | NullCheckStyles.IsNotNull)
: (NullCheckStyles.EqualsToNull | NullCheckStyles.IsNull);
NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(left, semanticModel, allowedStyles: allowedStyles, cancellationToken: cancellationToken);
ExpressionSyntax expression = nullCheck.Expression;
if (expression is null)
return false;
ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression, cancellationToken);
if (typeSymbol is null)
return false;
if (!typeSymbol.IsReferenceTypeOrNullableType())
return false;
if (right is null)
return false;
if (!ValidateRightExpression(right, binaryExpressionKind, semanticModel, cancellationToken))
return false;
if (CSharpUtility.ContainsOutArgumentWithLocalOrParameter(right, semanticModel, cancellationToken))
return false;
ExpressionSyntax e = FindExpressionThatCanBeConditionallyAccessed(expression, right, isNullable: !typeSymbol.IsReferenceType, semanticModel, cancellationToken);
return e is not null;
}
internal static ExpressionSyntax FindExpressionThatCanBeConditionallyAccessed(
ExpressionSyntax expressionToFind,
ExpressionSyntax expression,
SemanticModel semanticModel,
CancellationToken cancellationToken = default)
{
return FindExpressionThatCanBeConditionallyAccessed(
expressionToFind: expressionToFind,
expression: expression,
isNullable: false,
semanticModel: semanticModel,
cancellationToken: cancellationToken);
}
internal static ExpressionSyntax FindExpressionThatCanBeConditionallyAccessed(
ExpressionSyntax expressionToFind,
ExpressionSyntax expression,
bool isNullable,
SemanticModel semanticModel,
CancellationToken cancellationToken = default)
{
if (expression.IsKind(SyntaxKind.LogicalNotExpression))
expression = ((PrefixUnaryExpressionSyntax)expression).Operand;
SyntaxKind kind = expressionToFind.Kind();
SyntaxToken firstToken = expression.GetFirstToken();
int start = firstToken.SpanStart;
SyntaxNode node = firstToken.Parent;
while (node?.SpanStart == start)
{
if (kind == node.Kind()
&& node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.ElementAccessExpression)
&& semanticModel.GetTypeSymbol(node.Parent, cancellationToken)?.Kind != SymbolKind.PointerType
&& CSharpFactory.AreEquivalent(expressionToFind, node))
{
if (!isNullable)
return (ExpressionSyntax)node;
if (node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)
&& (((MemberAccessExpressionSyntax)node.Parent).Name is IdentifierNameSyntax identifierName)
&& string.Equals(identifierName.Identifier.ValueText, "Value", StringComparison.Ordinal)
&& node.Parent.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.ElementAccessExpression))
{
return (ExpressionSyntax)node.Parent;
}
return null;
}
node = node.Parent;
}
return null;
}
private static bool ValidateRightExpression(
ExpressionSyntax expression,
SyntaxKind binaryExpressionKind,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (binaryExpressionKind == SyntaxKind.LogicalAndExpression)
{
switch (expression.Kind())
{
case SyntaxKind.LessThanExpression:
case SyntaxKind.GreaterThanExpression:
case SyntaxKind.LessThanOrEqualExpression:
case SyntaxKind.GreaterThanOrEqualExpression:
case SyntaxKind.EqualsExpression:
{
expression = ((BinaryExpressionSyntax)expression)
.Right?
.WalkDownParentheses();
if (expression is null)
return false;
Optional<object> optional = semanticModel.GetConstantValue(expression, cancellationToken);
return optional.HasValue
&& optional.Value is not null;
}
case SyntaxKind.NotEqualsExpression:
{
return ((BinaryExpressionSyntax)expression)
.Right?
.WalkDownParentheses()
.Kind() == SyntaxKind.NullLiteralExpression;
}
case SyntaxKind.IsPatternExpression:
{
var isPatternExpression = (IsPatternExpressionSyntax)expression;
PatternSyntax pattern = isPatternExpression.Pattern;
if (pattern is ConstantPatternSyntax constantPattern)
{
return !constantPattern.Expression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression);
}
else if (pattern.IsKind(SyntaxKind.NotPattern))
{
pattern = ((UnaryPatternSyntax)pattern).Pattern;
// x != null && x.P is not T;
if (pattern is ConstantPatternSyntax constantPattern2)
return constantPattern2.Expression.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression);
}
return true;
}
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.InvocationExpression:
case SyntaxKind.ElementAccessExpression:
case SyntaxKind.LogicalNotExpression:
case SyntaxKind.IsExpression:
case SyntaxKind.AsExpression:
{
return true;
}
default:
{
return false;
}
}
}
else if (binaryExpressionKind == SyntaxKind.LogicalOrExpression)
{
switch (expression.Kind())
{
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.InvocationExpression:
case SyntaxKind.ElementAccessExpression:
case SyntaxKind.LogicalNotExpression:
return true;
default:
return false;
}
}
Debug.Fail(binaryExpressionKind.ToString());
return false;
}
internal static (ExpressionSyntax left, ExpressionSyntax right) GetFixableExpressions(
BinaryExpressionSyntax binaryExpression,
SyntaxKind kind,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
ExpressionSyntax e = binaryExpression;
ExpressionSyntax left;
ExpressionSyntax right = null;
while (true)
{
ExpressionSyntax last = GetLastChild(e);
if (last is not null)
{
e = last;
}
else
{
while (e != binaryExpression
&& IsFirstChild(e))
{
e = (ExpressionSyntax)e.Parent;
}
if (e == binaryExpression)
break;
e = GetPreviousSibling(e);
}
if (!e.IsKind(kind, SyntaxKind.ParenthesizedExpression))
{
if (right is null)
{
right = e;
}
else
{
left = e;
if (!binaryExpression.ContainsDirectives(TextSpan.FromBounds(left.SpanStart, right.Span.End))
&& IsFixable(left, right, kind, semanticModel, cancellationToken))
{
return (left, right);
}
right = left;
}
}
}
return default;
ExpressionSyntax GetLastChild(SyntaxNode node)
{
SyntaxKind kind2 = node.Kind();
if (kind2 == kind)
return ((BinaryExpressionSyntax)node).Right;
if (kind2 == SyntaxKind.ParenthesizedExpression)
return ((ParenthesizedExpressionSyntax)node).Expression;
return null;
}
ExpressionSyntax GetPreviousSibling(SyntaxNode node)
{
SyntaxNode parent = node.Parent;
if (parent.IsKind(kind))
{
var logicalAnd = (BinaryExpressionSyntax)parent;
if (logicalAnd.Right == node)
return logicalAnd.Left;
}
return null;
}
bool IsFirstChild(SyntaxNode node)
{
SyntaxNode parent = node.Parent;
if (parent.IsKind(kind))
return ((BinaryExpressionSyntax)parent).Left == node;
return true;
}
}
}