forked from dotnet/roslyn-analyzers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AvoidSingleUseOfLocalJsonSerializerOptions.cs
328 lines (271 loc) · 12.3 KB
/
AvoidSingleUseOfLocalJsonSerializerOptions.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
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis;
using System.Collections.Immutable;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis.Operations;
using System.Diagnostics.CodeAnalysis;
using System;
using System.Collections.Generic;
namespace Microsoft.NetCore.Analyzers.Performance
{
using static MicrosoftNetCoreAnalyzersResources;
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AvoidSingleUseOfLocalJsonSerializerOptions : DiagnosticAnalyzer
{
internal static readonly DiagnosticDescriptor s_Rule = DiagnosticDescriptorHelper.Create(
id: "CA1869",
title: CreateLocalizableResourceString(nameof(AvoidSingleUseOfLocalJsonSerializerOptionsTitle)),
messageFormat: CreateLocalizableResourceString(nameof(AvoidSingleUseOfLocalJsonSerializerOptionsMessage)),
category: DiagnosticCategory.Performance,
ruleLevel: RuleLevel.IdeSuggestion,
description: CreateLocalizableResourceString(nameof(AvoidSingleUseOfLocalJsonSerializerOptionsDescription)),
isPortedFxCopRule: false,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_Rule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(OnCompilationStart);
}
private static void OnCompilationStart(CompilationStartAnalysisContext context)
{
Compilation compilation = context.Compilation;
compilation.TryGetOrCreateTypeByMetadataName(
WellKnownTypeNames.SystemTextJsonJsonSerializerOptions, out INamedTypeSymbol? jsonSerializerOptionsSymbol);
compilation.TryGetOrCreateTypeByMetadataName(
WellKnownTypeNames.SystemTextJsonJsonSerializer, out INamedTypeSymbol? jsonSerializerSymbol);
if (jsonSerializerOptionsSymbol is null || jsonSerializerSymbol is null)
{
return;
}
context.RegisterOperationAction(
context =>
{
var operation = (IObjectCreationOperation)context.Operation;
INamedTypeSymbol? typeSymbol = operation.Constructor?.ContainingType;
if (SymbolEqualityComparer.Default.Equals(typeSymbol, jsonSerializerOptionsSymbol))
{
if (IsCtorUsedAsArgumentForJsonSerializer(operation, jsonSerializerSymbol) ||
IsLocalUsedAsArgumentForJsonSerializerOnly(operation, jsonSerializerSymbol))
{
context.ReportDiagnostic(operation.CreateDiagnostic(s_Rule));
}
}
},
OperationKind.ObjectCreation);
}
private static bool IsCtorUsedAsArgumentForJsonSerializer(IObjectCreationOperation objCreationOperation, INamedTypeSymbol jsonSerializerSymbol)
{
IOperation operation = WalkUpConditional(objCreationOperation);
return operation.Parent is IArgumentOperation argumentOperation &&
IsArgumentForJsonSerializer(argumentOperation, jsonSerializerSymbol);
}
private static bool IsArgumentForJsonSerializer(IArgumentOperation argumentOperation, INamedTypeSymbol jsonSerializerSymbol)
{
return argumentOperation.Parent is IInvocationOperation invocationOperation &&
SymbolEqualityComparer.Default.Equals(invocationOperation.TargetMethod.ContainingType, jsonSerializerSymbol);
}
private static bool IsLocalUsedAsArgumentForJsonSerializerOnly(IObjectCreationOperation objCreation, INamedTypeSymbol jsonSerializerSymbol)
{
IOperation operation = WalkUpConditional(objCreation);
if (!IsLocalAssignment(operation, out List<ILocalSymbol>? localSymbols))
{
return false;
}
IBlockOperation? localBlock = objCreation.GetFirstParentBlock();
bool isSingleUseJsonSerializerInvocation = false;
foreach (IOperation descendant in localBlock.Descendants())
{
if (descendant is not ILocalReferenceOperation localRefOperation ||
!localSymbols.Contains(localRefOperation.Local))
{
continue;
}
// Avoid cases that would potentially make the local escape current block scope.
if (IsArgumentOfJsonSerializer(descendant, jsonSerializerSymbol, out bool isArgumentOfInvocation))
{
// Case: used more than once i.e: not single-use.
if (isSingleUseJsonSerializerInvocation)
{
return false;
}
isSingleUseJsonSerializerInvocation = true;
}
// Case: passed as argument of a non-JsonSerializer method.
else if (isArgumentOfInvocation)
{
return false;
}
if (IsFieldOrPropertyAssignment(descendant))
{
return false;
}
// Case: deconstruction assignment.
if (IsTupleForDeconstructionTargetingFieldOrProperty(descendant))
{
return false;
}
// Case: local goes into closure.
if (IsClosureOnLambdaOrLocalFunction(descendant, localBlock!))
{
return false;
}
}
return isSingleUseJsonSerializerInvocation;
}
[return: NotNullIfNotNull(nameof(operation))]
private static IOperation? WalkUpConditional(IOperation? operation)
{
if (operation is null)
return null;
while (operation.Parent is IConditionalOperation conditionalOperation)
{
operation = conditionalOperation;
}
return operation;
}
private static bool IsArgumentOfJsonSerializer(IOperation operation, INamedTypeSymbol jsonSerializerSymbol, out bool isArgumentOfInvocation)
{
if (operation.Parent is IArgumentOperation arg && arg.Parent is IInvocationOperation inv)
{
isArgumentOfInvocation = true;
return SymbolEqualityComparer.Default.Equals(inv.TargetMethod.ContainingType, jsonSerializerSymbol);
}
isArgumentOfInvocation = false;
return false;
}
private static bool IsFieldOrPropertyAssignment(IOperation operation)
{
IOperation? current = operation.Parent;
while (current is IAssignmentOperation assignment)
{
if (assignment.Target is IFieldReferenceOperation or IPropertyReferenceOperation)
{
return true;
}
current = current.Parent;
}
return false;
}
private static bool IsTupleForDeconstructionTargetingFieldOrProperty(IOperation operation)
{
IOperation? current = operation.Parent;
if (current is not ITupleOperation tuple)
{
return false;
}
Stack<int> depth = new Stack<int>();
depth.Push(tuple.Elements.IndexOf(operation));
// walk-up right-hand nested tuples.
while (tuple.Parent is ITupleOperation parent)
{
depth.Push(parent.Elements.IndexOf(tuple));
tuple = parent;
}
current = tuple.WalkUpConversion().Parent;
if (current is not IDeconstructionAssignmentOperation deconstruction)
{
return false;
}
// walk-down left-hand nested tuples and see if it targets a field or property.
if (deconstruction.Target is not ITupleOperation deconstructionTarget)
{
return false;
}
tuple = deconstructionTarget;
IOperation? target = null;
while (depth.Count > 0)
{
int idx = depth.Pop();
target = tuple.Elements[idx];
if (target is ITupleOperation targetAsTuple)
{
tuple = targetAsTuple;
}
else if (depth.Count > 0)
{
return false;
}
}
return target is IFieldReferenceOperation or IPropertyReferenceOperation;
}
private static bool IsClosureOnLambdaOrLocalFunction(IOperation operation, IBlockOperation localBlock)
{
if (!operation.IsWithinLambdaOrLocalFunction(out IOperation? lambdaOrLocalFunc))
{
return false;
}
IBlockOperation? block = lambdaOrLocalFunc switch
{
IAnonymousFunctionOperation lambda => lambda.Body,
ILocalFunctionOperation localFunc => localFunc.Body,
_ => throw new InvalidOperationException()
};
return block != localBlock;
}
private static bool IsLocalAssignment(IOperation operation, [NotNullWhen(true)] out List<ILocalSymbol>? localSymbols)
{
localSymbols = null;
IOperation? currentOperation = operation.Parent;
while (currentOperation is not null)
{
// for cases like:
// var options;
// options = new JsonSerializerOptions();
if (currentOperation is IExpressionStatementOperation)
{
IOperation? tmpOperation = operation.Parent;
while (tmpOperation is IAssignmentOperation assignment)
{
if (assignment.Target is IFieldReferenceOperation or IPropertyReferenceOperation)
{
return false;
}
else if (assignment.Target is ILocalReferenceOperation localRef)
{
localSymbols ??= new List<ILocalSymbol>();
localSymbols.Add(localRef.Local);
}
tmpOperation = assignment.Parent;
}
return localSymbols != null;
}
// For cases like:
// var options = new JsonSerializerOptions();
else if (currentOperation is IVariableDeclarationOperation declaration)
{
if (operation.Parent is IAssignmentOperation assignment)
{
foreach (IOperation children in assignment.Children)
{
if (children is IFieldReferenceOperation or IPropertyReferenceOperation)
{
return false;
}
}
}
var local = GetLocalSymbolFromDeclaration(declaration);
if (local != null)
{
localSymbols = new List<ILocalSymbol> { local };
}
return local != null;
}
currentOperation = currentOperation.Parent;
}
return false;
}
private static ILocalSymbol? GetLocalSymbolFromDeclaration(IVariableDeclarationOperation declaration)
{
if (declaration.Declarators.Length != 1)
{
return null;
}
IVariableDeclaratorOperation declarator = declaration.Declarators[0];
return declarator.Symbol;
}
}
}