/
AbstractInitializeParameterCodeRefactoringProvider.cs
256 lines (218 loc) · 11.7 KB
/
AbstractInitializeParameterCodeRefactoringProvider.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.InitializeParameter
{
internal abstract partial class AbstractInitializeParameterCodeRefactoringProvider<
TTypeDeclarationSyntax,
TParameterSyntax,
TStatementSyntax,
TExpressionSyntax> : CodeRefactoringProvider
where TTypeDeclarationSyntax : SyntaxNode
where TParameterSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TExpressionSyntax : SyntaxNode
{
protected abstract bool IsFunctionDeclaration(SyntaxNode node);
protected abstract bool IsImplicitConversion(Compilation compilation, ITypeSymbol source, ITypeSymbol destination);
protected abstract SyntaxNode GetBody(SyntaxNode functionDeclaration);
protected abstract Task<ImmutableArray<CodeAction>> GetRefactoringsForAllParametersAsync(
Document document,
SyntaxNode functionDeclaration,
IMethodSymbol method,
IBlockOperation? blockStatementOpt,
ImmutableArray<SyntaxNode> listOfParameterNodes,
TextSpan parameterSpan,
CleanCodeGenerationOptionsProvider fallbackOptions,
CancellationToken cancellationToken);
protected abstract Task<ImmutableArray<CodeAction>> GetRefactoringsForSingleParameterAsync(
Document document,
TParameterSyntax parameterSyntax,
IParameterSymbol parameter,
SyntaxNode functionDeclaration,
IMethodSymbol methodSymbol,
IBlockOperation? blockStatementOpt,
CleanCodeGenerationOptionsProvider fallbackOptions,
CancellationToken cancellationToken);
protected abstract void InsertStatement(
SyntaxEditor editor, SyntaxNode functionDeclaration, bool returnsVoid,
SyntaxNode? statementToAddAfter, TStatementSyntax statement);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, _, cancellationToken) = context;
// TODO: One could try to retrieve TParameterList and then filter out parameters that intersect with
// textSpan and use that as `parameterNodes`, where `selectedParameter` would be the first one.
var selectedParameter = await context.TryGetRelevantNodeAsync<TParameterSyntax>().ConfigureAwait(false);
if (selectedParameter == null)
return;
var functionDeclaration = selectedParameter.FirstAncestorOrSelf<SyntaxNode>(IsFunctionDeclaration);
if (functionDeclaration is null)
return;
var generator = SyntaxGenerator.GetGenerator(document);
var parameterNodes = generator.GetParameters(functionDeclaration);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
// we can't just call GetDeclaredSymbol on functionDeclaration because it could an anonymous function,
// so first we have to get the parameter symbol and then its containing method symbol
if (!TryGetParameterSymbol(selectedParameter, semanticModel, out var parameter, cancellationToken))
return;
var methodSymbol = (IMethodSymbol)parameter.ContainingSymbol;
if (methodSymbol.IsAbstract ||
methodSymbol.IsExtern ||
methodSymbol.PartialImplementationPart != null ||
methodSymbol.ContainingType.TypeKind == TypeKind.Interface)
{
return;
}
// We shouldn't offer a refactoring if the compilation doesn't contain the ArgumentNullException type,
// as we use it later on in our computations.
var argumentNullExceptionType = typeof(ArgumentNullException).FullName;
if (argumentNullExceptionType is null || semanticModel.Compilation.GetTypeByMetadataName(argumentNullExceptionType) is null)
return;
if (CanOfferRefactoring(functionDeclaration, semanticModel, syntaxFacts, cancellationToken, out var blockStatementOpt))
{
// Ok. Looks like the selected parameter could be refactored. Defer to subclass to
// actually determine if there are any viable refactorings here.
var refactorings = await GetRefactoringsForSingleParameterAsync(
document, selectedParameter, parameter, functionDeclaration, methodSymbol, blockStatementOpt, context.Options, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(refactorings, context.Span);
}
// List with parameterNodes that pass all checks
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var listOfPotentiallyValidParametersNodes);
foreach (var parameterNode in parameterNodes)
{
if (!TryGetParameterSymbol(parameterNode, semanticModel, out parameter, cancellationToken))
return;
// Update the list of valid parameter nodes
listOfPotentiallyValidParametersNodes.Add(parameterNode);
}
if (listOfPotentiallyValidParametersNodes.Count > 1)
{
// Looks like we can offer a refactoring for more than one parameter. Defer to subclass to
// actually determine if there are any viable refactorings here.
var refactorings = await GetRefactoringsForAllParametersAsync(
document, functionDeclaration, methodSymbol, blockStatementOpt,
listOfPotentiallyValidParametersNodes.ToImmutable(), selectedParameter.Span, context.Options, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(refactorings, context.Span);
}
return;
static bool TryGetParameterSymbol(
SyntaxNode parameterNode,
SemanticModel semanticModel,
[NotNullWhen(true)] out IParameterSymbol? parameter,
CancellationToken cancellationToken)
{
parameter = (IParameterSymbol?)semanticModel.GetDeclaredSymbol(parameterNode, cancellationToken);
return parameter != null && parameter.Name != "";
}
}
protected bool CanOfferRefactoring(
SyntaxNode functionDeclaration, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts,
CancellationToken cancellationToken, out IBlockOperation? blockStatementOpt)
{
blockStatementOpt = null;
var functionBody = GetBody(functionDeclaration);
if (functionBody == null)
{
// We support initializing parameters, even when the containing member doesn't have a
// body. This is useful for when the user is typing a new constructor and hasn't written
// the body yet.
return true;
}
// In order to get the block operation for the body of an anonymous function, we need to
// get it via `IAnonymousFunctionOperation.Body` instead of getting it directly from the body syntax.
var operation = semanticModel.GetOperation(
syntaxFacts.IsAnonymousFunctionExpression(functionDeclaration) ? functionDeclaration : functionBody,
cancellationToken);
if (operation == null)
{
return false;
}
switch (operation.Kind)
{
case OperationKind.AnonymousFunction:
blockStatementOpt = ((IAnonymousFunctionOperation)operation).Body;
break;
case OperationKind.Block:
blockStatementOpt = (IBlockOperation)operation;
break;
default:
return false;
}
return true;
}
protected static bool IsParameterReference(IOperation operation, IParameterSymbol parameter)
=> UnwrapImplicitConversion(operation) is IParameterReferenceOperation parameterReference &&
parameter.Equals(parameterReference.Parameter);
protected static IOperation UnwrapImplicitConversion(IOperation operation)
=> operation is IConversionOperation conversion && conversion.IsImplicit
? conversion.Operand
: operation;
protected static bool ContainsParameterReference(
SemanticModel semanticModel,
IOperation condition,
IParameterSymbol parameter,
CancellationToken cancellationToken)
{
foreach (var child in condition.Syntax.DescendantNodes().OfType<TExpressionSyntax>())
{
var childOperation = semanticModel.GetOperation(child, cancellationToken);
if (childOperation != null && IsParameterReference(childOperation, parameter))
return true;
}
return false;
}
protected static bool IsFieldOrPropertyAssignment(IOperation statement, INamedTypeSymbol containingType, [NotNullWhen(true)] out IAssignmentOperation? assignmentExpression)
=> IsFieldOrPropertyAssignment(statement, containingType, out assignmentExpression, out _);
protected static bool IsFieldOrPropertyAssignment(
IOperation statement, INamedTypeSymbol containingType,
[NotNullWhen(true)] out IAssignmentOperation? assignmentExpression,
[NotNullWhen(true)] out ISymbol? fieldOrProperty)
{
if (statement is IExpressionStatementOperation expressionStatement &&
expressionStatement.Operation is IAssignmentOperation assignment)
{
assignmentExpression = assignment;
return IsFieldOrPropertyReference(assignmentExpression.Target, containingType, out fieldOrProperty);
}
fieldOrProperty = null;
assignmentExpression = null;
return false;
}
protected static bool IsFieldOrPropertyReference(IOperation operation, INamedTypeSymbol containingType)
=> IsFieldOrPropertyAssignment(operation, containingType, out _);
protected static bool IsFieldOrPropertyReference(
IOperation? operation, INamedTypeSymbol containingType,
[NotNullWhen(true)] out ISymbol? fieldOrProperty)
{
if (operation is IMemberReferenceOperation memberReference &&
memberReference.Member.ContainingType.Equals(containingType))
{
if (memberReference.Member is IFieldSymbol or
IPropertySymbol)
{
fieldOrProperty = memberReference.Member;
return true;
}
}
fieldOrProperty = null;
return false;
}
}
}