-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathAssignmentAnalyzer.cs
235 lines (202 loc) · 10.3 KB
/
AssignmentAnalyzer.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
namespace IDisposableAnalyzers;
using System.Collections.Immutable;
using System.Threading;
using Gu.Roslyn.AnalyzerExtensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class AssignmentAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(
Descriptors.IDISP001DisposeCreated,
Descriptors.IDISP003DisposeBeforeReassigning,
Descriptors.IDISP008DoNotMixInjectedAndCreatedForMember);
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(c => Handle(c), SyntaxKind.SimpleAssignmentExpression);
}
private static void Handle(SyntaxNodeAnalysisContext context)
{
if (!context.IsExcludedFromAnalysis() &&
context.Node is AssignmentExpressionSyntax { Left: { } left, Right: { } right } assignment &&
!left.IsKind(SyntaxKind.ElementAccessExpression) &&
context.SemanticModel.TryGetSymbol(left, context.CancellationToken, out var assignedSymbol))
{
if (LocalOrParameter.TryCreate(assignedSymbol, out var localOrParameter) &&
Disposable.IsCreation(right, context.SemanticModel, context.CancellationToken) &&
Disposable.ShouldDispose(localOrParameter, context.SemanticModel, context.CancellationToken))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptors.IDISP001DisposeCreated, assignment.GetLocation()));
}
if (IsReassignedWithCreated(assignment, context))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptors.IDISP003DisposeBeforeReassigning, assignment.GetLocation()));
}
if (assignedSymbol is IParameterSymbol { RefKind: RefKind.Ref } refParameter &&
refParameter.ContainingSymbol.DeclaredAccessibility != Accessibility.Private &&
context.SemanticModel.TryGetType(right, context.CancellationToken, out var type) &&
Disposable.IsAssignableFrom(type, context.Compilation))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptors.IDISP008DoNotMixInjectedAndCreatedForMember, context.Node.GetLocation()));
}
}
}
private static bool IsReassignedWithCreated(AssignmentExpressionSyntax assignment, SyntaxNodeAnalysisContext context)
{
if (assignment.Right is IdentifierNameSyntax { Identifier.ValueText: "value" } &&
assignment.FirstAncestor<AccessorDeclarationSyntax>() is { } accessor &&
accessor.IsKind(SyntaxKind.SetAccessorDeclaration))
{
return false;
}
if (assignment.Parent is UsingStatementSyntax)
{
return false;
}
if (Disposable.IsAlreadyAssignedWithCreated(assignment.Left, context.SemanticModel, context.CancellationToken, out var assignedSymbol))
{
switch (assignedSymbol)
{
case IPropertySymbol { ContainingType.MetadataName: "SerialDisposable`1", MetadataName: "Disposable" }:
case IPropertySymbol { ContainingType.MetadataName: "SerialDisposable", MetadataName: "Disposable" }:
case IPropertySymbol { ContainingType.MetadataName: "SingleAssignmentDisposable", MetadataName: "Disposable" }:
case IDiscardSymbol:
return false;
}
if (Disposable.IsDisposedBefore(assignedSymbol, assignment, context.SemanticModel, context.CancellationToken))
{
return false;
}
if (FieldOrProperty.TryCreate(assignedSymbol, out var fieldOrProperty))
{
if (context.Node.FirstAncestor<TypeDeclarationSyntax>() is { } containingType &&
InitializeAndCleanup.IsAssignedAndDisposed(fieldOrProperty, containingType, context.SemanticModel, context.CancellationToken))
{
return false;
}
if (Disposable.IsAssignedWithInjected(fieldOrProperty.Symbol, assignment, context.SemanticModel, context.CancellationToken))
{
return false;
}
}
if (IsNullChecked(assignedSymbol, assignment, context.SemanticModel, context.CancellationToken))
{
return false;
}
if (AssignedLocal() is { } local &&
Disposable.DisposesAfter(local, assignment, context.SemanticModel, context.CancellationToken))
{
return false;
}
return true;
ILocalSymbol? AssignedLocal()
{
if (assignment.TryFirstAncestor(out MemberDeclarationSyntax? memberDeclaration))
{
using var walker = VariableDeclaratorWalker.Borrow(memberDeclaration);
return walker.VariableDeclarators.TrySingle(
x => x is { Initializer.Value: { } value } &&
context.SemanticModel.TryGetSymbol(value, context.CancellationToken, out var symbol) &&
SymbolComparer.Equal(symbol, assignedSymbol),
out var match) &&
match.Initializer?.Value.IsExecutedBefore(assignment) == ExecutedBefore.Yes &&
context.SemanticModel.TryGetSymbol(match, context.CancellationToken, out ILocalSymbol? result)
? result
: null;
}
return null;
}
}
return false;
}
private static bool IsNullChecked(ISymbol symbol, SyntaxNode context, SemanticModel semanticModel, CancellationToken cancellationToken)
{
return context.TryFirstAncestor(out IfStatementSyntax? ifStatement) &&
ifStatement.Statement.Contains(context) &&
IsNullCheck(ifStatement.Condition);
bool IsNullCheck(ExpressionSyntax candidate)
{
switch (candidate)
{
case IsPatternExpressionSyntax isPattern:
if (IsSymbol(isPattern.Expression) &&
isPattern.Pattern is ConstantPatternSyntax constantPattern &&
constantPattern.Expression.IsKind(SyntaxKind.NullLiteralExpression))
{
return !IsAssignedBefore(ifStatement!);
}
break;
case BinaryExpressionSyntax binary
when binary.IsKind(SyntaxKind.EqualsExpression):
if (binary.Left.IsKind(SyntaxKind.NullLiteralExpression) &&
IsSymbol(binary.Right))
{
return !IsAssignedBefore(ifStatement!);
}
if (IsSymbol(binary.Left) &&
binary.Right.IsKind(SyntaxKind.NullLiteralExpression))
{
return !IsAssignedBefore(ifStatement!);
}
break;
case BinaryExpressionSyntax binary when binary.IsKind(SyntaxKind.LogicalAndExpression):
return IsNullCheck(binary.Left) || IsNullCheck(binary.Right);
case InvocationExpressionSyntax invocation:
if (invocation.Expression is IdentifierNameSyntax identifierName &&
invocation.ArgumentList.Arguments.Count == 2 &&
(identifierName.Identifier.ValueText == nameof(ReferenceEquals) ||
identifierName.Identifier.ValueText == nameof(Equals)))
{
if (invocation.ArgumentList.Arguments.TrySingle(x => x.Expression.IsKind(SyntaxKind.NullLiteralExpression), out _) &&
invocation.ArgumentList.Arguments.TrySingle(x => IsSymbol(x.Expression), out _))
{
return !IsAssignedBefore(ifStatement!);
}
}
else if (invocation.Expression is MemberAccessExpressionSyntax { Name: IdentifierNameSyntax memberIdentifier } &&
invocation.ArgumentList.Arguments.Count == 2 &&
(memberIdentifier.Identifier.ValueText == nameof(ReferenceEquals) ||
memberIdentifier.Identifier.ValueText == nameof(Equals)))
{
if (invocation.ArgumentList.Arguments.TrySingle(x => x.Expression.IsKind(SyntaxKind.NullLiteralExpression), out _) &&
invocation.ArgumentList.Arguments.TrySingle(x => IsSymbol(x.Expression), out _))
{
return !IsAssignedBefore(ifStatement!);
}
}
break;
}
return false;
}
bool IsSymbol(ExpressionSyntax expression)
{
if (expression is IdentifierNameSyntax identifierName)
{
return identifierName.Identifier.ValueText == symbol.Name;
}
if (symbol.IsEitherKind(SymbolKind.Field, SymbolKind.Property) &&
expression is MemberAccessExpressionSyntax { Expression: InstanceExpressionSyntax _, Name: IdentifierNameSyntax identifier })
{
return identifier.Identifier.ValueText == symbol.Name;
}
return false;
}
bool IsAssignedBefore(IfStatementSyntax nullCheck)
{
using var walker = AssignmentExecutionWalker.Borrow(nullCheck, SearchScope.Member, semanticModel, cancellationToken);
foreach (var assignment in walker.Assignments)
{
if (IsSymbol(assignment.Left) &&
assignment.SpanStart < context.SpanStart)
{
return true;
}
}
return false;
}
}
}