-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathImmutabilityAnalyzer.cs
More file actions
429 lines (381 loc) · 13.6 KB
/
Copy pathImmutabilityAnalyzer.cs
File metadata and controls
429 lines (381 loc) · 13.6 KB
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
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using D2L.CodeStyle.Analyzers.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace D2L.CodeStyle.Analyzers.Immutability {
[DiagnosticAnalyzer( LanguageNames.CSharp )]
public sealed class ImmutabilityAnalyzer : DiagnosticAnalyzer {
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(
Diagnostics.ArraysAreMutable,
Diagnostics.DelegateTypesPossiblyMutable,
Diagnostics.DynamicObjectsAreMutable,
Diagnostics.EventMemberMutable,
Diagnostics.MemberIsNotReadOnly,
Diagnostics.NonImmutableTypeHeldByImmutable,
Diagnostics.TypeParameterIsNotKnownToBeImmutable,
Diagnostics.UnexpectedMemberKind,
Diagnostics.UnexpectedTypeKind,
Diagnostics.UnnecessaryMutabilityAnnotation,
Diagnostics.UnexpectedConditionalImmutability,
Diagnostics.ConflictingImmutability,
Diagnostics.InvalidAuditType,
Diagnostics.AnonymousFunctionsMayCaptureMutability,
Diagnostics.UnknownImmutabilityAssignmentKind,
Diagnostics.MissingTransitiveImmutableAttribute,
Diagnostics.InconsistentMethodAttributeApplication
);
private readonly ImmutableHashSet<string> m_additionalImmutableTypes;
public ImmutabilityAnalyzer() : this( ImmutableHashSet<string>.Empty ) { }
public ImmutabilityAnalyzer( ImmutableHashSet<string> additionalImmutableTypes ) {
m_additionalImmutableTypes = additionalImmutableTypes;
}
public override void Initialize( AnalysisContext context ) {
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis( GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics );
context.RegisterCompilationStartAction( CompilationStart );
}
public void CompilationStart(
CompilationStartAnalysisContext context
) {
if( !AnnotationsContext.TryCreate( context.Compilation, out AnnotationsContext annotationsContext ) ) {
return;
}
ImmutabilityContext immutabilityContext = ImmutabilityContext.Create( context.Compilation, annotationsContext, m_additionalImmutableTypes );
context.RegisterSymbolAction(
ctx => AnalyzeTypeDeclaration(
ctx,
annotationsContext,
immutabilityContext,
(INamedTypeSymbol)ctx.Symbol
),
SymbolKind.NamedType
);
context.RegisterSymbolAction(
ctx => AnalyzeMethodDeclarationConsistency(
ctx,
annotationsContext,
immutabilityContext,
(IMethodSymbol)ctx.Symbol
),
SymbolKind.Method
);
context.RegisterSymbolAction(
ctx => AnalyzeMember( ctx, annotationsContext, immutabilityContext ),
SymbolKind.Field,
SymbolKind.Property
);
context.RegisterSyntaxNodeAction(
ctx => {
IdentifierNameSyntax identifierName = (IdentifierNameSyntax)ctx.Node;
AnalyzeTypeArguments(
ctx,
annotationsContext,
immutabilityContext,
identifierName,
getArgumentLocation: _ => identifierName.Identifier.GetLocation()
);
},
SyntaxKind.IdentifierName
);
context.RegisterSyntaxNodeAction(
ctx => {
GenericNameSyntax genericName = (GenericNameSyntax)ctx.Node;
AnalyzeTypeArguments(
ctx,
annotationsContext,
immutabilityContext,
genericName,
getArgumentLocation: position => genericName.TypeArgumentList.Arguments[ position ].GetLocation()
);
},
SyntaxKind.GenericName
);
context.RegisterSymbolAction(
ctx => AnalyzeConditionalImmutabilityOnMethodDeclarations(
(IMethodSymbol)ctx.Symbol,
annotationsContext,
ctx.ReportDiagnostic,
ctx.CancellationToken
),
SymbolKind.Method
);
context.RegisterSyntaxNodeAction(
ctx => {
IMethodSymbol method = (IMethodSymbol)ctx.SemanticModel.GetDeclaredSymbol(
(LocalFunctionStatementSyntax)ctx.Node,
ctx.CancellationToken
);
AnalyzeConditionalImmutabilityOnMethodDeclarations(
method,
annotationsContext,
ctx.ReportDiagnostic,
ctx.CancellationToken
);
},
SyntaxKind.LocalFunctionStatement
);
context.RegisterSymbolAction(
ctx => AnalyzeConflictingImmutabilityOnTypeParameters(
ctx,
(INamedTypeSymbol)ctx.Symbol,
annotationsContext
),
SymbolKind.NamedType
);
context.RegisterSymbolAction(
ctx => AnalyzeConflictingImmutabilityOnMember(
ctx,
(INamedTypeSymbol)ctx.Symbol,
annotationsContext
),
SymbolKind.NamedType
);
}
private static void AnalyzeMember(
SymbolAnalysisContext ctx,
AnnotationsContext annotationsContext,
ImmutabilityContext immutabilityContext
) {
// We only care about checking static fields/properties. These
// are global variables, so we always want them to be immutable.
// The fields/properties of [Immutable] types get handled via
// AnalyzeTypeDeclaration.
if( !ctx.Symbol.IsStatic ) {
return;
}
// Ignore const things, which include enum names.
if( ctx.Symbol is IFieldSymbol f && f.IsConst ) {
return;
}
// We would like this check to run for generated code too, but
// there are two problems:
// (1) the easy one: we generate some static variables that are
// safe in practice but don't analyze well.
// (2) the hard one: resx code-gen generates some stuff that's
// safe in practice but doesn't analyze well.
if( ctx.Symbol.IsFromGeneratedCode() ) {
return;
}
var checker = new ImmutableDefinitionChecker(
compilation: ctx.Compilation,
diagnosticSink: ctx.ReportDiagnostic,
context: immutabilityContext,
annotationsContext: annotationsContext,
cancellationToken: ctx.CancellationToken
);
checker.CheckMember( ctx.Symbol );
}
private static void AnalyzeMethodDeclarationConsistency(
SymbolAnalysisContext ctx,
AnnotationsContext annotationsContext,
ImmutabilityContext immutabilityContext,
IMethodSymbol methodSymbol
) {
// Static methods can't implement interface methods
if( methodSymbol.IsStatic ) {
return;
}
ImmutableAttributeConsistencyChecker consistencyChecker = new ImmutableAttributeConsistencyChecker(
compilation: ctx.Compilation,
diagnosticSink: ctx.ReportDiagnostic,
context: immutabilityContext,
annotationsContext: annotationsContext
);
consistencyChecker.CheckMethodDeclaration( methodSymbol, ctx.CancellationToken );
}
private static void AnalyzeTypeDeclaration(
SymbolAnalysisContext ctx,
AnnotationsContext annotationsContext,
ImmutabilityContext immutabilityContext,
INamedTypeSymbol typeSymbol
) {
if( typeSymbol.IsImplicitlyDeclared ) {
return;
}
ImmutableAttributeConsistencyChecker consistencyChecker = new ImmutableAttributeConsistencyChecker(
compilation: ctx.Compilation,
diagnosticSink: ctx.ReportDiagnostic,
context: immutabilityContext,
annotationsContext: annotationsContext
);
consistencyChecker.CheckTypeDeclaration( typeSymbol, ctx.CancellationToken );
if( typeSymbol.TypeKind == TypeKind.Interface ) {
return;
}
if( !annotationsContext.Objects.Immutable.IsDefined( typeSymbol )
&& !annotationsContext.Objects.ConditionallyImmutable.IsDefined( typeSymbol )
&& !annotationsContext.Objects.ImmutableBaseClass.IsDefined( typeSymbol )
) {
return;
}
if( annotationsContext.Objects.ConditionallyImmutable.IsDefined( typeSymbol ) ) {
immutabilityContext = immutabilityContext.WithConditionalTypeParametersAsImmutable( typeSymbol );
}
ImmutableDefinitionChecker checker = new ImmutableDefinitionChecker(
compilation: ctx.Compilation,
diagnosticSink: ctx.ReportDiagnostic,
context: immutabilityContext,
annotationsContext: annotationsContext,
cancellationToken: ctx.CancellationToken
);
checker.CheckDeclaration( typeSymbol );
}
private static void AnalyzeTypeArguments(
SyntaxNodeAnalysisContext ctx,
AnnotationsContext annotationsContext,
ImmutabilityContext immutabilityContext,
SimpleNameSyntax syntax,
Func<int, Location> getArgumentLocation
) {
if( syntax.IsFromDocComment() ) {
// ignore things in doccomments such as crefs
return;
}
SymbolInfo info = ctx.SemanticModel.GetSymbolInfo( syntax, ctx.CancellationToken );
// Ignore anything that cannot have type arguments/parameters
if( !GetTypeParamsAndArgs( info.Symbol, out var typeParameters, out var typeArguments ) ) {
return;
}
int i = 0;
var paramArgPairs = typeParameters.Zip( typeArguments, ( p, a ) => (p, a, i++) );
foreach( var (parameter, argument, position) in paramArgPairs ) {
// TODO: this should eventually use information from ImmutableTypeInfo
// however the current information about immutable type parameters
// includes [Immutable] filling for what will instead be the upcoming
// [OnlyIf] (e.g. it would be broken for IEnumerable<>)
if( !annotationsContext.Objects.Immutable.IsDefined( parameter ) ) {
continue;
}
if( !immutabilityContext.IsImmutable(
new ImmutabilityQuery(
ImmutableTypeKind.Total,
argument
) { EnforceImmutableTypeParams = false },
getLocation: () => getArgumentLocation( position ),
out Diagnostic diagnostic
) ) {
// TODO: not necessarily a good diagnostic for this use-case
ctx.ReportDiagnostic( diagnostic );
}
}
}
private static void AnalyzeConditionalImmutabilityOnMethodDeclarations(
IMethodSymbol method,
AnnotationsContext annotationsContext,
Action<Diagnostic> diagnosticSink,
CancellationToken cancellationToken
) {
foreach( var parameter in method.TypeParameters ) {
// Check if the parameter has the [OnlyIf] attribute
if( !annotationsContext.Objects.OnlyIf.IsDefined( parameter ) ) {
continue;
}
// Create the diagnostic on the parameter (including the attribute)
diagnosticSink( Diagnostic.Create(
Diagnostics.UnexpectedConditionalImmutability,
parameter.DeclaringSyntaxReferences[ 0 ].GetSyntax( cancellationToken ).GetLocation()
) );
}
}
private static void AnalyzeConflictingImmutabilityOnTypeParameters(
SymbolAnalysisContext ctx,
INamedTypeSymbol namedTypeSymbol,
AnnotationsContext annotationsContext
) {
foreach( var parameter in namedTypeSymbol.TypeParameters ) {
// Check if the parameter has both the [Immutable] and the [OnlyIf] attributes
if( !annotationsContext.Objects.Immutable.IsDefined( parameter )
|| !annotationsContext.Objects.OnlyIf.IsDefined( parameter )
) {
return;
}
// Create the diagnostic on the parameter (excluding the attribute)
ctx.ReportDiagnostic(
Diagnostics.ConflictingImmutability,
parameter.Locations[0],
messageArgs: new[] {
"Immutable",
"ConditionallyImmutable.OnlyIf",
"typeparameter"
}
);
}
}
private static void AnalyzeConflictingImmutabilityOnMember(
SymbolAnalysisContext ctx,
INamedTypeSymbol symbol,
AnnotationsContext annotationsContext
) {
// Get information about immutability
bool hasImmutable = annotationsContext.Objects.Immutable.IsDefined( symbol );
bool hasConditionallyImmutable = annotationsContext.Objects.ConditionallyImmutable.IsDefined( symbol );
bool hasImmutableBase = annotationsContext.Objects.ImmutableBaseClass.IsDefined( symbol );
// Check if there are conflicting immutability attributes
if( hasImmutable && hasConditionallyImmutable ) {
// [Immutable] and [ConditionallyImmutable] both exist,
// so create a diagnostic
ctx.ReportDiagnostic(
Diagnostics.ConflictingImmutability,
symbol.Locations[ 0 ],
messageArgs: new object[] {
"Immutable",
"ConditionallyImmutable",
KindName( symbol )
}
);
}
if( hasImmutable && hasImmutableBase ) {
// [Immutable] and [ImmutableBaseClassAttribute] both exist,
// so create a diagnostic
ctx.ReportDiagnostic(
Diagnostics.ConflictingImmutability,
symbol.Locations[ 0 ],
messageArgs: new object[] {
"Immutable",
"ImmutableBaseClassAttribute",
KindName( symbol )
}
);
}
if( hasConditionallyImmutable && hasImmutableBase ) {
// [ConditionallyImmutable] and [ImmutableBaseClassAttribute] both exist,
// so create a diagnostic
ctx.ReportDiagnostic(
Diagnostics.ConflictingImmutability,
symbol.Locations[ 0 ],
messageArgs: new object[] {
"ConditionallyImmutable",
"ImmutableBaseClassAttribute",
KindName( symbol )
}
);
}
static string KindName( INamedTypeSymbol symbol ) => symbol.TypeKind switch {
TypeKind.Class => "class",
TypeKind.Interface => "interface",
TypeKind.Struct => "struct",
_ => symbol.TypeKind.ToString()
};
}
private static bool GetTypeParamsAndArgs( ISymbol type, out ImmutableArray<ITypeParameterSymbol> typeParameters, out ImmutableArray<ITypeSymbol> typeArguments ) {
switch( type ) {
case IMethodSymbol method:
typeParameters = method.TypeParameters;
typeArguments = method.TypeArguments;
return true;
case INamedTypeSymbol namedType:
typeParameters = namedType.TypeParameters;
typeArguments = namedType.TypeArguments;
return true;
default:
typeParameters = default;
typeArguments = default;
return false;
}
}
}
}