forked from space-wizards/RobustToolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPreferGenericVariantAnalyzer.cs
238 lines (196 loc) · 9.67 KB
/
PreferGenericVariantAnalyzer.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
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Robust.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class PreferGenericVariantAnalyzer : DiagnosticAnalyzer
{
private const string AttributeType = "Robust.Shared.Analyzers.PreferGenericVariantAttribute";
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(
UseGenericVariantDescriptor, UseGenericVariantInvalidUsageDescriptor,
UseGenericVariantAttributeValueErrorDescriptor);
private static readonly DiagnosticDescriptor UseGenericVariantDescriptor = new(
Diagnostics.IdUseGenericVariant,
"Consider using the generic variant of this method",
"Consider using the generic variant of this method to avoid potential allocations",
"Usage",
DiagnosticSeverity.Warning,
true,
"Consider using the generic variant of this method to avoid potential allocations.");
private static readonly DiagnosticDescriptor UseGenericVariantInvalidUsageDescriptor = new(
Diagnostics.IdUseGenericVariantInvalidUsage,
"Invalid generic variant provided",
"Generic variant provided mismatches the amount of type parameters of non-generic variant",
"Usage",
DiagnosticSeverity.Error,
true,
"The non-generic variant should have at least as many type parameter at the beginning of the method as there are generic type parameters on the generic variant.");
private static readonly DiagnosticDescriptor UseGenericVariantAttributeValueErrorDescriptor = new(
Diagnostics.IdUseGenericVariantAttributeValueError,
"Failed resolving generic variant value",
"Failed resolving generic variant value: {0}",
"Usage",
DiagnosticSeverity.Error,
true,
"Consider using nameof to avoid any typos.");
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.ReportDiagnostics | GeneratedCodeAnalysisFlags.Analyze);
context.EnableConcurrentExecution();
context.RegisterOperationAction(CheckForGenericVariant, OperationKind.Invocation);
}
private void CheckForGenericVariant(OperationAnalysisContext obj)
{
if(obj.Operation is not IInvocationOperation invocationOperation) return;
var preferGenericAttribute = obj.Compilation.GetTypeByMetadataName(AttributeType);
string genericVariant = null;
AttributeData foundAttribute = null;
foreach (var attribute in invocationOperation.TargetMethod.GetAttributes())
{
if (!SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, preferGenericAttribute))
continue;
genericVariant = attribute.ConstructorArguments[0].Value as string ?? invocationOperation.TargetMethod.Name;
foundAttribute = attribute;
break;
}
if(genericVariant == null) return;
var maxTypeParams = 0;
var typeTypeSymbol = obj.Compilation.GetTypeByMetadataName("System.Type");
foreach (var parameter in invocationOperation.TargetMethod.Parameters)
{
if(!SymbolEqualityComparer.Default.Equals(parameter.Type, typeTypeSymbol)) break;
maxTypeParams++;
}
if (maxTypeParams == 0)
{
obj.ReportDiagnostic(
Diagnostic.Create(UseGenericVariantInvalidUsageDescriptor,
foundAttribute.ApplicationSyntaxReference?.GetSyntax().GetLocation()));
return;
}
IMethodSymbol genericVariantMethod = null;
foreach (var member in invocationOperation.TargetMethod.ContainingType.GetMembers())
{
if (member is not IMethodSymbol methodSymbol
|| methodSymbol.Name != genericVariant
|| !methodSymbol.IsGenericMethod
|| methodSymbol.TypeParameters.Length > maxTypeParams
|| methodSymbol.Parameters.Length > invocationOperation.TargetMethod.Parameters.Length - methodSymbol.TypeParameters.Length
) continue;
var typeParamCount = methodSymbol.TypeParameters.Length;
var failedParamComparison = false;
var objType = obj.Compilation.GetSpecialType(SpecialType.System_Object);
for (int i = 0; i < methodSymbol.Parameters.Length; i++)
{
if (methodSymbol.Parameters[i].Type is ITypeParameterSymbol && SymbolEqualityComparer.Default.Equals(invocationOperation.TargetMethod.Parameters[i + typeParamCount].Type, objType))
continue;
if (!SymbolEqualityComparer.Default.Equals(methodSymbol.Parameters[i].Type,
invocationOperation.TargetMethod.Parameters[i + typeParamCount].Type))
{
failedParamComparison = true;
break;
}
}
if(failedParamComparison) continue;
genericVariantMethod = methodSymbol;
}
if (genericVariantMethod == null)
{
obj.ReportDiagnostic(Diagnostic.Create(
UseGenericVariantAttributeValueErrorDescriptor,
foundAttribute.ApplicationSyntaxReference?.GetSyntax().GetLocation(),
genericVariant));
return;
}
var typeOperands = new string[genericVariantMethod.TypeParameters.Length];
for (var i = 0; i < genericVariantMethod.TypeParameters.Length; i++)
{
switch (invocationOperation.Arguments[i].Value)
{
//todo figure out if ILocalReferenceOperation, IPropertyReferenceOperation or IFieldReferenceOperation is referencing static typeof assignments
case ITypeOfOperation typeOfOperation:
typeOperands[i] = typeOfOperation.TypeOperand.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
continue;
default:
return;
}
}
obj.ReportDiagnostic(Diagnostic.Create(
UseGenericVariantDescriptor,
invocationOperation.Syntax.GetLocation(),
ImmutableDictionary.CreateRange(new Dictionary<string, string>()
{
{"typeOperands", string.Join(",", typeOperands)}
})));
}
}
[ExportCodeFixProvider(LanguageNames.CSharp)]
public class PreferGenericVariantCodeFixProvider : CodeFixProvider
{
private static string Title(string method, string[] types) => $"Use {method}<{string.Join(",", types)}>.";
public override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync();
if(root == null) return;
foreach (var diagnostic in context.Diagnostics)
{
if (!diagnostic.Properties.TryGetValue("typeOperands", out var typeOperandsRaw)
|| typeOperandsRaw == null) continue;
var node = root.FindNode(diagnostic.Location.SourceSpan);
if (node is ArgumentSyntax argumentSyntax)
node = argumentSyntax.Expression;
if(node is not InvocationExpressionSyntax invocationExpression)
continue;
var typeOperands = typeOperandsRaw.Split(',');
context.RegisterCodeFix(
CodeAction.Create(
Title(invocationExpression.Expression.ToString(), typeOperands),
c => FixAsync(context.Document, invocationExpression, typeOperands, c),
Title(invocationExpression.Expression.ToString(), typeOperands)),
diagnostic);
}
}
private async Task<Document> FixAsync(
Document contextDocument,
InvocationExpressionSyntax invocationExpression,
string[] typeOperands,
CancellationToken cancellationToken)
{
var memberAccess = (MemberAccessExpressionSyntax)invocationExpression.Expression;
var root = (CompilationUnitSyntax) await contextDocument.GetSyntaxRootAsync(cancellationToken);
var arguments = new ArgumentSyntax[invocationExpression.ArgumentList.Arguments.Count - typeOperands.Length];
var types = new TypeSyntax[typeOperands.Length];
for (int i = 0; i < typeOperands.Length; i++)
{
types[i] = ((TypeOfExpressionSyntax)invocationExpression.ArgumentList.Arguments[i].Expression).Type;
}
Array.Copy(
invocationExpression.ArgumentList.Arguments.ToArray(),
typeOperands.Length,
arguments,
0,
arguments.Length);
memberAccess = memberAccess.WithName(SyntaxFactory.GenericName(memberAccess.Name.Identifier,
SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(types))));
root = root!.ReplaceNode(invocationExpression,
invocationExpression.WithArgumentList(invocationExpression.ArgumentList.WithArguments(SyntaxFactory.SeparatedList(arguments)))
.WithExpression(memberAccess));
return contextDocument.WithSyntaxRoot(root);
}
public override ImmutableArray<string> FixableDiagnosticIds =>
ImmutableArray.Create(Diagnostics.IdUseGenericVariant);
}