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
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Rename.ConflictEngine;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis;
using ICSharpCode.NRefactory6.CSharp.CodeGeneration;
using System.Globalization;
using System.Reflection;
using Microsoft.CodeAnalysis.Options;
namespace ICSharpCode.NRefactory6.CSharp.CodeRefactorings.EncapsulateField
{
internal abstract class AbstractEncapsulateFieldService : ILanguageService
{
static AbstractEncapsulateFieldService()
{
renameSymbolMethod = typeof (Renamer).GetMethod ("RenameSymbolAsync", BindingFlags.Static | BindingFlags.NonPublic, null, new Type [] { typeof(Solution), typeof(ISymbol), typeof(string), typeof(OptionSet), typeof(Func<Location, bool>), typeof(Func<IEnumerable<ISymbol>, bool?>), typeof(CancellationToken) }, null);
if (renameSymbolMethod == null)
throw new Exception ("Can't find RenameSymbolAsync method.");
}
public async Task<EncapsulateFieldResult> EncapsulateFieldAsync(Document document, TextSpan span, bool useDefaultBehavior, CancellationToken cancellationToken)
{
var fields = await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false);
if (fields == null || !fields.Any())
{
return null;
}
return new EncapsulateFieldResult(c => EncapsulateFieldResultAsync(document, span, useDefaultBehavior, c));
}
public async Task<IEnumerable<EncapsulateFieldCodeAction>> GetEncapsulateFieldCodeActionsAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var fields = (await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false)).ToImmutableArrayOrEmpty();
if (fields.Length == 0)
{
return SpecializedCollections.EmptyEnumerable<EncapsulateFieldCodeAction>();
}
if (fields.Length == 1)
{
// there is only one field
return EncapsulateOneField(document, span, fields[0], index: 0);
}
else
{
// there are multiple fields.
var current = SpecializedCollections.EmptyEnumerable<EncapsulateFieldCodeAction>();
if (span.IsEmpty)
{
// if there is no selection, get action for each field + all of them.
for (var i = 0; i < fields.Length; i++)
{
current = current.Concat(EncapsulateOneField(document, span, fields[i], i));
}
}
return current.Concat(EncapsulateAllFields(document, span));
}
}
private IEnumerable<EncapsulateFieldCodeAction> EncapsulateAllFields(Document document, TextSpan span)
{
var action1Text = Resources.EncapsulateFieldsUsages;
var action2Text = Resources.EncapsulateFields;
return new[]
{
new EncapsulateFieldCodeAction(new EncapsulateFieldResult(c => EncapsulateFieldResultAsync(document, span, true, c)), action1Text),
new EncapsulateFieldCodeAction(new EncapsulateFieldResult(c => EncapsulateFieldResultAsync(document, span, false, c)), action2Text)
};
}
private IEnumerable<EncapsulateFieldCodeAction> EncapsulateOneField(Document document, TextSpan span, IFieldSymbol field, int index)
{
var action1Text = string.Format(Resources.EncapsulateFieldUsages, field.Name);
var action2Text = string.Format(Resources.EncapsulateField, field.Name);
return new[]
{
new EncapsulateFieldCodeAction(new EncapsulateFieldResult(c => SingleEncapsulateFieldResultAsync(document, span, index, true, c)), action1Text),
new EncapsulateFieldCodeAction(new EncapsulateFieldResult(c => SingleEncapsulateFieldResultAsync(document, span, index, false, c)), action2Text)
};
}
private async Task<Result> SingleEncapsulateFieldResultAsync(Document document, TextSpan span, int index, bool updateReferences, CancellationToken cancellationToken)
{
var fields = (await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false)).ToImmutableArrayOrEmpty();
//Contract.Requires(fields.Length > index);
var field = fields[index];
var result = await EncapsulateFieldAsync(field, document, updateReferences, cancellationToken).ConfigureAwait(false);
if (result == null)
{
return new Result(document.Project.Solution, field);
}
return result;
}
private async Task<Result> EncapsulateFieldResultAsync(Document document, TextSpan span, bool updateReferences, CancellationToken cancellationToken)
{
// probably later we want to add field and reason why it failed.
var failedFieldSymbols = new List<IFieldSymbol>();
var fields = await GetFieldsAsync(document, span, cancellationToken).ConfigureAwait(false);
//Contract.Requires(fields.Any());
// For now, build up the multiple field case by encapsulating one at a time.
Result result = null;
foreach (var field in fields)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var compilation = semanticModel.Compilation;
var currentField = field.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol as IFieldSymbol;
// We couldn't resolve this field. skip it
if (currentField == null)
{
failedFieldSymbols.Add(field);
continue;
}
result = await EncapsulateFieldAsync(currentField, document, updateReferences, cancellationToken).ConfigureAwait(false);
if (result == null)
{
failedFieldSymbols.Add(field);
continue;
}
document = result.Solution.GetDocument(document.Id);
}
if (result == null)
{
return new Result(document.Project.Solution, fields.ToArray());
}
// add failed field symbol info
return result.WithFailedFields(failedFieldSymbols);
}
private async Task<Result> EncapsulateFieldAsync(IFieldSymbol field, Document document, bool updateReferences, CancellationToken cancellationToken)
{
var originalField = field;
var finalNames = GeneratePropertyAndFieldNames(field);
var finalFieldName = finalNames.Item1;
var generatedPropertyName = finalNames.Item2;
// Annotate the field declarations so we can find it after rename.
var fieldDeclaration = field.DeclaringSyntaxReferences.First();
var declarationAnnotation = new SyntaxAnnotation();
document = document.WithSyntaxRoot(fieldDeclaration.SyntaxTree.GetRoot(cancellationToken).ReplaceNode(fieldDeclaration.GetSyntax(cancellationToken),
fieldDeclaration.GetSyntax(cancellationToken).WithAdditionalAnnotations(declarationAnnotation)));
var solution = document.Project.Solution;
foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
{
var linkedDocument = solution.GetDocument(linkedDocumentId);
var linkedRoot = await linkedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var linkedFieldNode = linkedRoot.FindNode(fieldDeclaration.Span);
if (linkedFieldNode.Span != fieldDeclaration.Span)
{
continue;
}
var updatedRoot = linkedRoot.ReplaceNode(linkedFieldNode, linkedFieldNode.WithAdditionalAnnotations(declarationAnnotation));
solution = solution.WithDocumentSyntaxRoot(linkedDocumentId, updatedRoot);
}
document = solution.GetDocument(document.Id);
// Resolve the annotated symbol and prepare for rename.
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var compilation = semanticModel.Compilation;
field = field.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol as IFieldSymbol;
var solutionNeedingProperty = solution;
// We couldn't resolve field after annotating its declaration. Bail
if (field == null)
{
return null;
}
solutionNeedingProperty = await UpdateReferencesAsync(
updateReferences, solution, document, field, finalFieldName, generatedPropertyName, cancellationToken).ConfigureAwait(false);
document = solutionNeedingProperty.GetDocument(document.Id);
var markFieldPrivate = field.DeclaredAccessibility != Accessibility.Private;
var rewrittenFieldDeclaration = await RewriteFieldNameAndAccessibility(finalFieldName, markFieldPrivate, document, declarationAnnotation, cancellationToken).ConfigureAwait(false);
document = await Formatter.FormatAsync(document.WithSyntaxRoot(rewrittenFieldDeclaration), Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
solution = document.Project.Solution;
foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
{
var linkedDocument = solution.GetDocument(linkedDocumentId);
var updatedLinkedRoot = await RewriteFieldNameAndAccessibility(finalFieldName, markFieldPrivate, linkedDocument, declarationAnnotation, cancellationToken).ConfigureAwait(false);
var updatedLinkedDocument = await Formatter.FormatAsync(linkedDocument.WithSyntaxRoot(updatedLinkedRoot), Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
solution = updatedLinkedDocument.Project.Solution;
}
document = solution.GetDocument(document.Id);
semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
compilation = semanticModel.Compilation;
var newRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newDeclaration = newRoot.GetAnnotatedNodes<SyntaxNode>(declarationAnnotation).First();
field = semanticModel.GetDeclaredSymbol(newDeclaration, cancellationToken) as IFieldSymbol;
var generatedProperty = GenerateProperty(generatedPropertyName, finalFieldName, originalField.DeclaredAccessibility, originalField, field.ContainingType, new SyntaxAnnotation(), document, cancellationToken);
var solutionWithProperty = await AddPropertyAsync(document, document.Project.Solution, field, generatedProperty, cancellationToken).ConfigureAwait(false);
return new Result(solutionWithProperty, originalField.ToDisplayString(), Glyph.FieldPublic);
}
static Task<Solution> RenameSymbolAsync (Solution solution, ISymbol symbol, string newName, OptionSet options, Func<Location, bool> filter, Func<IEnumerable<ISymbol>, bool?> hasConflict = null, CancellationToken cancellationToken = default(CancellationToken))
{
return (Task<Solution>)renameSymbolMethod.Invoke (null, new object [] { solution, symbol, newName, options, filter, hasConflict, cancellationToken });
}
private async Task<Solution> UpdateReferencesAsync(
bool updateReferences, Solution solution, Document document, IFieldSymbol field, string finalFieldName, string generatedPropertyName, CancellationToken cancellationToken)
{
if (!updateReferences)
{
return solution;
}
if (field.IsReadOnly)
{
// Inside the constructor we want to rename references the field to the final field name.
var constructorSyntaxes = GetConstructorNodes(field.ContainingType).ToSet();
if (finalFieldName != field.Name && constructorSyntaxes.Count > 0)
{
solution = await RenameSymbolAsync(solution, field, finalFieldName, solution.Workspace.Options,
location => constructorSyntaxes.Any(c => c.Span.IntersectsWith(location.SourceSpan)), cancellationToken: cancellationToken).ConfigureAwait(false);
document = solution.GetDocument(document.Id);
var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
field = field.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol as IFieldSymbol;
}
// Outside the constructor we want to rename references to the field to final property name.
return await RenameSymbolAsync(solution, field, generatedPropertyName, solution.Workspace.Options,
location => !constructorSyntaxes.Any(c => c.Span.IntersectsWith(location.SourceSpan)), cancellationToken: cancellationToken).ConfigureAwait(false);
}
else
{
// Just rename everything.
return await Renamer.RenameSymbolAsync(solution, field, generatedPropertyName, solution.Workspace.Options, cancellationToken).ConfigureAwait(false);
}
}
internal abstract IEnumerable<SyntaxNode> GetConstructorNodes(INamedTypeSymbol containingType);
protected async Task<Solution> AddPropertyAsync(Document document, Solution destinationSolution, IFieldSymbol field, IPropertySymbol property, CancellationToken cancellationToken)
{
var codeGenerationService = new CSharpCodeGenerationService (document.Project.Solution.Workspace);
var fieldDeclaration = field.DeclaringSyntaxReferences.First();
var options = new CodeGenerationOptions(contextLocation: fieldDeclaration.SyntaxTree.GetLocation(fieldDeclaration.Span));
var destination = field.ContainingType;
var updatedDocument = await codeGenerationService.AddPropertyAsync(destinationSolution, destination, property, options, cancellationToken)
.ConfigureAwait(false);
updatedDocument = await Formatter.FormatAsync(updatedDocument, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);
updatedDocument = await Simplifier.ReduceAsync(updatedDocument, cancellationToken: cancellationToken).ConfigureAwait(false);
return updatedDocument.Project.Solution;
}
protected IPropertySymbol GenerateProperty(string propertyName, string fieldName, Accessibility accessibility, IFieldSymbol field, INamedTypeSymbol containingSymbol, SyntaxAnnotation annotation, Document document, CancellationToken cancellationToken)
{
var factory = document.GetLanguageService<SyntaxGenerator>();
var propertySymbol = annotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreatePropertySymbol(containingType: containingSymbol,
attributes: SpecializedCollections.EmptyList<AttributeData>(),
accessibility: ComputeAccessibility(accessibility, field.Type),
modifiers: new DeclarationModifiers().WithIsStatic (field.IsStatic).WithIsReadOnly (field.IsReadOnly).WithIsUnsafe (field.IsUnsafe()),
type: field.Type,
explicitInterfaceSymbol: null,
name: propertyName,
parameters: SpecializedCollections.EmptyList<IParameterSymbol>(),
getMethod: CreateGet(fieldName, field, factory),
setMethod: field.IsReadOnly || field.IsConst ? null : CreateSet(fieldName, field, factory)));
return Simplifier.Annotation.AddAnnotationToSymbol(
Formatter.Annotation.AddAnnotationToSymbol(propertySymbol));
}
protected abstract Tuple<string, string> GeneratePropertyAndFieldNames(IFieldSymbol field);
protected Accessibility ComputeAccessibility(Accessibility accessibility, ITypeSymbol type)
{
var computedAccessibility = accessibility;
if (accessibility == Accessibility.NotApplicable || accessibility == Accessibility.Private)
{
computedAccessibility = Accessibility.Public;
}
var returnTypeAccessibility = type.DetermineMinimalAccessibility();
return AccessibilityUtilities.Minimum(computedAccessibility, returnTypeAccessibility);
}
protected IMethodSymbol CreateSet(string originalFieldName, IFieldSymbol field, SyntaxGenerator factory)
{
var assigned = !field.IsStatic
? factory.MemberAccessExpression(
factory.ThisExpression(),
factory.IdentifierName(originalFieldName))
: factory.IdentifierName(originalFieldName);
var body = factory.ExpressionStatement(
factory.AssignmentStatement(
assigned.WithAdditionalAnnotations(Simplifier.Annotation),
factory.IdentifierName("value")));
return CodeGenerationSymbolFactory.CreateAccessorSymbol(SpecializedCollections.EmptyList<AttributeData>(),
Accessibility.NotApplicable,
new[] { body }.ToList());
}
protected IMethodSymbol CreateGet(string originalFieldName, IFieldSymbol field, SyntaxGenerator factory)
{
var body = factory.ReturnStatement(
factory.IdentifierName(originalFieldName));
return CodeGenerationSymbolFactory.CreateAccessorSymbol(SpecializedCollections.EmptyList<AttributeData>(),
Accessibility.NotApplicable,
new[] { body }.ToList());
}
private static readonly char[] s_underscoreCharArray = new[] { '_' };
protected string GeneratePropertyName(string fieldName)
{
// Trim leading underscores
var baseName = fieldName.TrimStart(s_underscoreCharArray);
// Trim leading "m_"
if (baseName.Length >= 2 && baseName[0] == 'm' && baseName[1] == '_')
{
baseName = baseName.Substring(2);
}
// Take original name if no characters left
if (baseName.Length == 0)
{
baseName = fieldName;
}
// Make the first character upper case using the "en-US" culture. See discussion at
// https://github.com/dotnet/roslyn/issues/5524.
var firstCharacter = EnUSCultureInfo.TextInfo.ToUpper(baseName[0]);
return firstCharacter.ToString() + baseName.Substring(1);
}
internal static readonly CultureInfo EnUSCultureInfo = new CultureInfo("en-US");
static MethodInfo renameSymbolMethod;
protected abstract Task<SyntaxNode> RewriteFieldNameAndAccessibility(string originalFieldName, bool makePrivate, Document document, SyntaxAnnotation declarationAnnotation, CancellationToken cancellationToken);
protected abstract Task<IEnumerable<IFieldSymbol>> GetFieldsAsync(Document document, TextSpan span, CancellationToken cancellationToken);
internal class Result
{
public Result(Solution solutionWithProperty, string name, Glyph glyph)
{
this.Solution = solutionWithProperty;
this.Name = name;
this.Glyph = glyph;
}
public Result(Solution solutionWithProperty, string name, Glyph glyph, List<IFieldSymbol> failedFieldSymbols) :
this(solutionWithProperty, name, glyph)
{
this.FailedFields = failedFieldSymbols.ToImmutableArrayOrEmpty();
}
public Result(Solution originalSolution, params IFieldSymbol[] fields) :
this(originalSolution, string.Empty, Glyph.Error)
{
this.FailedFields = fields.ToImmutableArrayOrEmpty();
}
public Solution Solution { get; }
public string Name { get; }
public Glyph Glyph { get; }
public ImmutableArray<IFieldSymbol> FailedFields { get; }
public Result WithFailedFields(List<IFieldSymbol> failedFieldSymbols)
{
if (failedFieldSymbols.Count == 0)
{
return this;
}
return new Result(Solution, Name, Glyph, failedFieldSymbols);
}
}
}
}
|