-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathCSharpRenameRewriterLanguageService.cs
1289 lines (1111 loc) · 57.4 KB
/
CSharpRenameRewriterLanguageService.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
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Simplification;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.PooledObjects;
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;
namespace Microsoft.CodeAnalysis.CSharp.Rename;
[ExportLanguageService(typeof(IRenameRewriterLanguageService), LanguageNames.CSharp), Shared]
internal class CSharpRenameConflictLanguageService : AbstractRenameRewriterLanguageService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpRenameConflictLanguageService()
{
}
#region "Annotation"
public override SyntaxNode AnnotateAndRename(RenameRewriterParameters parameters)
{
var renameAnnotationRewriter = new RenameRewriter(parameters);
return renameAnnotationRewriter.Visit(parameters.SyntaxRoot)!;
}
private class RenameRewriter : CSharpSyntaxRewriter
{
private readonly DocumentId _documentId;
private readonly RenameAnnotation _renameRenamableSymbolDeclaration;
private readonly Solution _solution;
private readonly string _replacementText;
private readonly string _originalText;
private readonly ImmutableArray<string> _possibleNameConflicts;
private readonly ImmutableDictionary<TextSpan, RenameLocation> _renameLocations;
private readonly ImmutableHashSet<TextSpan> _conflictLocations;
private readonly SemanticModel _semanticModel;
private readonly CancellationToken _cancellationToken;
private readonly ISymbol _renamedSymbol;
private readonly IAliasSymbol? _aliasSymbol;
private readonly Location? _renamableDeclarationLocation;
private readonly RenamedSpansTracker _renameSpansTracker;
private readonly bool _isVerbatim;
private readonly bool _replacementTextValid;
private readonly ISimplificationService _simplificationService;
private readonly ISemanticFactsService _semanticFactsService;
private readonly HashSet<SyntaxToken> _annotatedIdentifierTokens = [];
private readonly HashSet<InvocationExpressionSyntax> _invocationExpressionsNeedingConflictChecks = [];
private readonly AnnotationTable<RenameAnnotation> _renameAnnotations;
/// <summary>
/// Flag indicating if we should perform a rename inside string literals.
/// </summary>
private readonly bool _isRenamingInStrings;
/// <summary>
/// Flag indicating if we should perform a rename inside comment trivia.
/// </summary>
private readonly bool _isRenamingInComments;
/// <summary>
/// A map from spans of tokens needing rename within strings or comments to an optional
/// set of specific sub-spans within the token span that
/// have <see cref="_originalText"/> matches and should be renamed.
/// If this sorted set is null, it indicates that sub-spans to rename within the token span
/// are not available, and a regex match should be performed to rename
/// all <see cref="_originalText"/> matches within the span.
/// </summary>
private readonly ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> _stringAndCommentTextSpans;
public bool AnnotateForComplexification
{
get
{
return _skipRenameForComplexification > 0 && !_isProcessingComplexifiedSpans;
}
}
private int _skipRenameForComplexification;
private bool _isProcessingComplexifiedSpans;
private List<(TextSpan oldSpan, TextSpan newSpan)>? _modifiedSubSpans;
private SemanticModel? _speculativeModel;
private int _isProcessingTrivia;
private void AddModifiedSpan(TextSpan oldSpan, TextSpan newSpan)
{
newSpan = new TextSpan(oldSpan.Start, newSpan.Length);
if (!_isProcessingComplexifiedSpans)
{
_renameSpansTracker.AddModifiedSpan(_documentId, oldSpan, newSpan);
}
else
{
RoslynDebug.Assert(_modifiedSubSpans != null);
_modifiedSubSpans.Add((oldSpan, newSpan));
}
}
public RenameRewriter(RenameRewriterParameters parameters)
: base(visitIntoStructuredTrivia: true)
{
_documentId = parameters.Document.Id;
_renameRenamableSymbolDeclaration = parameters.RenamedSymbolDeclarationAnnotation;
_solution = parameters.OriginalSolution;
_replacementText = parameters.ReplacementText;
_originalText = parameters.OriginalText;
_possibleNameConflicts = parameters.PossibleNameConflicts;
_renameLocations = parameters.RenameLocations;
_conflictLocations = parameters.ConflictLocationSpans;
_cancellationToken = parameters.CancellationToken;
_semanticModel = parameters.SemanticModel;
_renamedSymbol = parameters.RenameSymbol;
_replacementTextValid = parameters.ReplacementTextValid;
_renameSpansTracker = parameters.RenameSpansTracker;
_isRenamingInStrings = parameters.IsRenamingInStrings;
_isRenamingInComments = parameters.IsRenamingInComments;
_stringAndCommentTextSpans = parameters.StringAndCommentTextSpans;
_renameAnnotations = parameters.RenameAnnotations;
_aliasSymbol = _renamedSymbol as IAliasSymbol;
_renamableDeclarationLocation = _renamedSymbol.Locations.FirstOrDefault(loc => loc.IsInSource && loc.SourceTree == _semanticModel.SyntaxTree);
_isVerbatim = _replacementText.StartsWith("@", StringComparison.Ordinal);
_simplificationService = parameters.Document.Project.Services.GetRequiredService<ISimplificationService>();
_semanticFactsService = parameters.Document.Project.Services.GetRequiredService<ISemanticFactsService>();
}
public override SyntaxNode? Visit(SyntaxNode? node)
{
if (node == null)
{
return node;
}
var isInConflictLambdaBody = false;
var lambdas = node.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax or ParenthesizedLambdaExpressionSyntax);
if (lambdas.Count() != 0)
{
foreach (var lambda in lambdas)
{
if (_conflictLocations.Any(cf => cf.Contains(lambda.Span)))
{
isInConflictLambdaBody = true;
break;
}
}
}
var shouldComplexifyNode = ShouldComplexifyNode(node, isInConflictLambdaBody);
SyntaxNode result;
// in case the current node was identified as being a complexification target of
// a previous node, we'll handle it accordingly.
if (shouldComplexifyNode)
{
_skipRenameForComplexification++;
result = base.Visit(node)!;
_skipRenameForComplexification--;
result = Complexify(node, result);
}
else
{
result = base.Visit(node)!;
}
return result;
}
private bool ShouldComplexifyNode(SyntaxNode node, bool isInConflictLambdaBody)
{
return !isInConflictLambdaBody &&
_skipRenameForComplexification == 0 &&
!_isProcessingComplexifiedSpans &&
_conflictLocations.Contains(node.Span) &&
(node is AttributeSyntax ||
node is AttributeArgumentSyntax ||
node is ConstructorInitializerSyntax ||
node is ExpressionSyntax ||
node is FieldDeclarationSyntax ||
node is StatementSyntax ||
node is CrefSyntax ||
node is XmlNameAttributeSyntax ||
node is TypeConstraintSyntax ||
node is BaseTypeSyntax);
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
var shouldCheckTrivia = _stringAndCommentTextSpans.ContainsKey(token.Span);
_isProcessingTrivia += shouldCheckTrivia ? 1 : 0;
var newToken = base.VisitToken(token);
_isProcessingTrivia -= shouldCheckTrivia ? 1 : 0;
// Handle Alias annotations
newToken = UpdateAliasAnnotation(newToken);
// Rename matches in strings and comments
newToken = RenameWithinToken(token, newToken);
// We don't want to annotate XmlName with RenameActionAnnotation
if (newToken.Parent.IsKind(SyntaxKind.XmlName))
{
return newToken;
}
var isRenameLocation = IsRenameLocation(token);
// if this is a reference location, or the identifier token's name could possibly
// be a conflict, we need to process this token
var isOldText = token.ValueText == _originalText;
var tokenNeedsConflictCheck =
isRenameLocation ||
token.ValueText == _replacementText ||
isOldText ||
_possibleNameConflicts.Contains(token.ValueText) ||
IsPossiblyDestructorConflict(token) ||
IsPropertyAccessorNameConflict(token);
if (tokenNeedsConflictCheck)
{
newToken = RenameAndAnnotateAsync(token, newToken, isRenameLocation, isOldText).WaitAndGetResult_CanCallOnBackground(_cancellationToken);
if (!_isProcessingComplexifiedSpans)
{
_invocationExpressionsNeedingConflictChecks.AddRange(token.GetAncestors<InvocationExpressionSyntax>());
}
}
return newToken;
}
private bool IsPropertyAccessorNameConflict(SyntaxToken token)
=> IsGetPropertyAccessorNameConflict(token)
|| IsSetPropertyAccessorNameConflict(token)
|| IsInitPropertyAccessorNameConflict(token);
private bool IsGetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.GetKeyword)
&& IsNameConflictWithProperty("get", token.Parent as AccessorDeclarationSyntax);
private bool IsSetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.SetKeyword)
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsInitPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.InitKeyword)
// using "set" here is intentional. The compiler generates set_PropName for both set and init accessors.
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsNameConflictWithProperty(string prefix, AccessorDeclarationSyntax? accessor)
=> accessor?.Parent?.Parent is PropertyDeclarationSyntax property // 3 null checks in one: accessor -> accessor list -> property declaration
&& _replacementText.Equals(prefix + "_" + property.Identifier.Text, StringComparison.Ordinal);
private bool IsPossiblyDestructorConflict(SyntaxToken token)
{
return _replacementText == "Finalize" &&
token.IsKind(SyntaxKind.IdentifierToken) &&
token.Parent.IsKind(SyntaxKind.DestructorDeclaration);
}
private SyntaxNode Complexify(SyntaxNode originalNode, SyntaxNode newNode)
{
_isProcessingComplexifiedSpans = true;
_modifiedSubSpans = [];
var annotation = new SyntaxAnnotation();
newNode = newNode.WithAdditionalAnnotations(annotation);
var speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
RoslynDebug.Assert(_speculativeModel != null, "expanding a syntax node which cannot be speculated?");
var oldSpan = originalNode.Span;
var expandParameter = originalNode.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax or ParenthesizedLambdaExpressionSyntax).Count() == 0;
newNode = _simplificationService.Expand(newNode,
_speculativeModel,
annotationForReplacedAliasIdentifier: null,
expandInsideNode: null,
expandParameter: expandParameter,
cancellationToken: _cancellationToken);
speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
newNode = base.Visit(newNode)!;
var newSpan = newNode.Span;
newNode = newNode.WithoutAnnotations(annotation);
newNode = _renameAnnotations.WithAdditionalAnnotations(newNode, new RenameNodeSimplificationAnnotation() { OriginalTextSpan = oldSpan });
_renameSpansTracker.AddComplexifiedSpan(_documentId, oldSpan, new TextSpan(oldSpan.Start, newSpan.Length), _modifiedSubSpans);
_modifiedSubSpans = null;
_isProcessingComplexifiedSpans = false;
_speculativeModel = null;
return newNode;
}
private async Task<SyntaxToken> RenameAndAnnotateAsync(SyntaxToken token, SyntaxToken newToken, bool isRenameLocation, bool isOldText)
{
try
{
if (_isProcessingComplexifiedSpans)
{
// Rename Token
if (isRenameLocation)
{
var annotation = _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().FirstOrDefault();
if (annotation != null)
{
newToken = RenameToken(token, newToken, annotation.Prefix, annotation.Suffix);
AddModifiedSpan(annotation.OriginalSpan, newToken.Span);
}
else
{
newToken = RenameToken(token, newToken, prefix: null, suffix: null);
}
}
return newToken;
}
var symbols = RenameUtilities.GetSymbolsTouchingPosition(token.Span.Start, _semanticModel, _solution.Services, _cancellationToken);
string? suffix = null;
var prefix = isRenameLocation && _renameLocations[token.Span].IsRenamableAccessor
? newToken.ValueText[..(newToken.ValueText.IndexOf('_') + 1)]
: null;
if (symbols.Length == 1)
{
var symbol = symbols[0];
if (symbol.IsConstructor())
{
symbol = symbol.ContainingSymbol;
}
var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, _solution, _cancellationToken).ConfigureAwait(false);
symbol = sourceDefinition ?? symbol;
if (symbol is INamedTypeSymbol namedTypeSymbol)
{
if (namedTypeSymbol.IsImplicitlyDeclared &&
namedTypeSymbol.IsDelegateType() &&
namedTypeSymbol.AssociatedSymbol != null)
{
suffix = "EventHandler";
}
}
// This is a conflicting namespace declaration token. Even if the rename results in conflict with this namespace
// conflict is not shown for the namespace so we are tracking this token
if (!isRenameLocation && symbol is INamespaceSymbol && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
return newToken;
}
}
// Rename Token
if (isRenameLocation && !this.AnnotateForComplexification)
{
var oldSpan = token.Span;
newToken = RenameToken(token, newToken, prefix, suffix);
AddModifiedSpan(oldSpan, newToken.Span);
}
var renameDeclarationLocations = await
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(_solution, symbols, _cancellationToken).ConfigureAwait(false);
var isNamespaceDeclarationReference = false;
if (isRenameLocation && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
isNamespaceDeclarationReference = true;
}
var isMemberGroupReference = _semanticFactsService.IsInsideNameOfExpression(_semanticModel, token.Parent, _cancellationToken);
var renameAnnotation =
new RenameActionAnnotation(
token.Span,
isRenameLocation,
prefix,
suffix,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: isOldText,
isNamespaceDeclarationReference: isNamespaceDeclarationReference,
isInvocationExpression: false,
isMemberGroupReference: isMemberGroupReference);
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, renameAnnotation, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = token.Span });
_annotatedIdentifierTokens.Add(token);
if (_renameRenamableSymbolDeclaration != null && _renamableDeclarationLocation == token.GetLocation())
{
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, _renameRenamableSymbolDeclaration);
}
return newToken;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable();
}
}
private RenameActionAnnotation? GetAnnotationForInvocationExpression(InvocationExpressionSyntax invocationExpression)
{
var identifierToken = default(SyntaxToken);
var expressionOfInvocation = invocationExpression.Expression;
while (expressionOfInvocation != null)
{
switch (expressionOfInvocation.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
identifierToken = ((SimpleNameSyntax)expressionOfInvocation).Identifier;
break;
case SyntaxKind.SimpleMemberAccessExpression:
identifierToken = ((MemberAccessExpressionSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.QualifiedName:
identifierToken = ((QualifiedNameSyntax)expressionOfInvocation).Right.Identifier;
break;
case SyntaxKind.AliasQualifiedName:
identifierToken = ((AliasQualifiedNameSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.ParenthesizedExpression:
expressionOfInvocation = ((ParenthesizedExpressionSyntax)expressionOfInvocation).Expression;
continue;
}
break;
}
if (identifierToken != default && !_annotatedIdentifierTokens.Contains(identifierToken))
{
var symbolInfo = _semanticModel.GetSymbolInfo(invocationExpression, _cancellationToken);
IEnumerable<ISymbol> symbols;
if (symbolInfo.Symbol == null)
{
return null;
}
else
{
symbols = [symbolInfo.Symbol];
}
var renameDeclarationLocations =
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(
_solution,
symbols,
_cancellationToken)
.WaitAndGetResult_CanCallOnBackground(_cancellationToken);
var renameAnnotation = new RenameActionAnnotation(
identifierToken.Span,
isRenameLocation: false,
prefix: null,
suffix: null,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: false,
isNamespaceDeclarationReference: false,
isInvocationExpression: true,
isMemberGroupReference: false);
return renameAnnotation;
}
return null;
}
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
{
var result = base.VisitInvocationExpression(node);
RoslynDebug.AssertNotNull(result);
if (_invocationExpressionsNeedingConflictChecks.Contains(node))
{
var renameAnnotation = GetAnnotationForInvocationExpression(node);
if (renameAnnotation != null)
{
result = _renameAnnotations.WithAdditionalAnnotations(result, renameAnnotation);
}
}
return result;
}
private bool IsRenameLocation(SyntaxToken token)
{
if (!_isProcessingComplexifiedSpans)
{
return _renameLocations.ContainsKey(token.Span);
}
else
{
RoslynDebug.Assert(_speculativeModel != null);
if (token.HasAnnotations(AliasAnnotation.Kind))
{
return false;
}
if (token.HasAnnotations(RenameAnnotation.Kind))
{
return _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().First().IsRenameLocation;
}
if (token.Parent is SimpleNameSyntax &&
!token.IsKind(SyntaxKind.GlobalKeyword) &&
token.Parent.Parent is (kind: SyntaxKind.AliasQualifiedName or SyntaxKind.QualifiedCref or SyntaxKind.QualifiedName))
{
var symbol = _speculativeModel.GetSymbolInfo(token.Parent, _cancellationToken).Symbol;
if (symbol != null && _renamedSymbol.Kind != SymbolKind.Local && _renamedSymbol.Kind != SymbolKind.RangeVariable &&
(Equals(symbol, _renamedSymbol) || SymbolKey.GetComparer(ignoreCase: true, ignoreAssemblyKeys: false).Equals(symbol.GetSymbolKey(), _renamedSymbol.GetSymbolKey())))
{
return true;
}
}
return false;
}
}
private SyntaxToken UpdateAliasAnnotation(SyntaxToken newToken)
{
if (_aliasSymbol != null && !this.AnnotateForComplexification && newToken.HasAnnotations(AliasAnnotation.Kind))
{
newToken = RenameUtilities.UpdateAliasAnnotation(newToken, _aliasSymbol, _replacementText);
}
return newToken;
}
private SyntaxToken RenameToken(SyntaxToken oldToken, SyntaxToken newToken, string? prefix, string? suffix)
{
var parent = oldToken.Parent!;
var currentNewIdentifier = _isVerbatim ? _replacementText[1..] : _replacementText;
var oldIdentifier = newToken.ValueText;
var isAttributeName = SyntaxFacts.IsAttributeName(parent);
if (isAttributeName)
{
if (oldIdentifier != _renamedSymbol.Name)
{
if (currentNewIdentifier.TryGetWithoutAttributeSuffix(out var withoutSuffix))
{
currentNewIdentifier = withoutSuffix;
}
}
}
else
{
if (!string.IsNullOrEmpty(prefix))
{
currentNewIdentifier = prefix + currentNewIdentifier;
}
if (!string.IsNullOrEmpty(suffix))
{
currentNewIdentifier += suffix;
}
}
// determine the canonical identifier name (unescaped, no unicode escaping, ...)
var valueText = currentNewIdentifier;
var kind = SyntaxFacts.GetKeywordKind(currentNewIdentifier);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var parsedIdentifier = SyntaxFactory.ParseName(currentNewIdentifier);
if (parsedIdentifier is IdentifierNameSyntax identifierName)
{
valueText = identifierName.Identifier.ValueText;
}
}
// TODO: we can't use escaped unicode characters in xml doc comments, so we need to pass the valuetext as text as well.
// <param name="\u... is invalid.
// if it's an attribute name we don't mess with the escaping because it might change overload resolution
newToken = _isVerbatim || (isAttributeName && oldToken.IsVerbatimIdentifier())
? newToken.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(newToken.LeadingTrivia, currentNewIdentifier, valueText, newToken.TrailingTrivia))
: newToken.CopyAnnotationsTo(SyntaxFactory.Identifier(newToken.LeadingTrivia, SyntaxKind.IdentifierToken, currentNewIdentifier, valueText, newToken.TrailingTrivia));
if (_replacementTextValid)
{
if (newToken.IsVerbatimIdentifier())
{
// a reference location should always be tried to be unescaped, whether it was escaped before rename
// or the replacement itself is escaped.
newToken = newToken.WithAdditionalAnnotations(Simplifier.Annotation);
}
else
{
newToken = CSharpSimplificationHelpers.TryEscapeIdentifierToken(newToken, parent);
}
}
return newToken;
}
private SyntaxToken RenameInStringLiteral(SyntaxToken oldToken, SyntaxToken newToken, ImmutableSortedSet<TextSpan>? subSpansToReplace, Func<SyntaxTriviaList, string, string, SyntaxTriviaList, SyntaxToken> createNewStringLiteral)
{
var originalString = newToken.ToString();
var replacedString = RenameUtilities.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText, subSpansToReplace);
if (replacedString != originalString)
{
var oldSpan = oldToken.Span;
newToken = createNewStringLiteral(newToken.LeadingTrivia, replacedString, replacedString, newToken.TrailingTrivia);
AddModifiedSpan(oldSpan, newToken.Span);
return newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return newToken;
}
private SyntaxToken RenameInTrivia(SyntaxToken token, IEnumerable<SyntaxTrivia> leadingOrTrailingTriviaList)
{
return token.ReplaceTrivia(leadingOrTrailingTriviaList, (oldTrivia, newTrivia) =>
{
if (newTrivia.IsSingleLineComment() || newTrivia.IsMultiLineComment())
{
return RenameInCommentTrivia(newTrivia);
}
return newTrivia;
});
}
private SyntaxTrivia RenameInCommentTrivia(SyntaxTrivia trivia)
{
var originalString = trivia.ToString();
var replacedString = RenameUtilities.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText);
if (replacedString != originalString)
{
var oldSpan = trivia.Span;
var newTrivia = SyntaxFactory.Comment(replacedString);
AddModifiedSpan(oldSpan, newTrivia.Span);
return trivia.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newTrivia, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return trivia;
}
private SyntaxToken RenameWithinToken(SyntaxToken oldToken, SyntaxToken newToken)
{
ImmutableSortedSet<TextSpan>? subSpansToReplace = null;
if (_isProcessingComplexifiedSpans ||
(_isProcessingTrivia == 0 &&
!_stringAndCommentTextSpans.TryGetValue(oldToken.Span, out subSpansToReplace)))
{
return newToken;
}
if (_isRenamingInStrings || subSpansToReplace?.Count > 0)
{
if (newToken.IsKind(SyntaxKind.StringLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.Literal);
}
else if (newToken.IsKind(SyntaxKind.InterpolatedStringTextToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, (leadingTrivia, text, value, trailingTrivia) =>
SyntaxFactory.Token(newToken.LeadingTrivia, SyntaxKind.InterpolatedStringTextToken, text, value, newToken.TrailingTrivia));
}
}
if (_isRenamingInComments)
{
if (newToken.IsKind(SyntaxKind.XmlTextLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.XmlTextLiteral);
}
else if (newToken.IsKind(SyntaxKind.IdentifierToken) && newToken.Parent.IsKind(SyntaxKind.XmlName) && newToken.ValueText == _originalText)
{
var newIdentifierToken = SyntaxFactory.Identifier(newToken.LeadingTrivia, _replacementText, newToken.TrailingTrivia);
newToken = newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newIdentifierToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldToken.Span }));
AddModifiedSpan(oldToken.Span, newToken.Span);
}
if (newToken.HasLeadingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.LeadingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithLeadingTrivia(updatedToken.LeadingTrivia);
}
}
if (newToken.HasTrailingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.TrailingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithTrailingTrivia(updatedToken.TrailingTrivia);
}
}
}
return newToken;
}
}
#endregion
#region "Declaration Conflicts"
public override bool LocalVariableConflict(
SyntaxToken token,
IEnumerable<ISymbol> newReferencedSymbols)
{
if (token.Parent is ExpressionSyntax(SyntaxKind.IdentifierName) expression &&
token.Parent.IsParentKind(SyntaxKind.InvocationExpression) &&
token.GetPreviousToken().Kind() != SyntaxKind.DotToken &&
token.GetNextToken().Kind() != SyntaxKind.DotToken)
{
var enclosingMemberDeclaration = expression.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (enclosingMemberDeclaration != null)
{
var locals = enclosingMemberDeclaration.GetLocalDeclarationMap()[token.ValueText];
if (locals.Length > 0)
{
// This unqualified invocation name matches the name of an existing local
// or parameter. Report a conflict if the matching local/parameter is not
// a delegate type.
var relevantLocals = newReferencedSymbols
.Where(s => s.MatchesKind(SymbolKind.Local, SymbolKind.Parameter) && s.Name == token.ValueText);
if (relevantLocals.Count() != 1)
{
return true;
}
var matchingLocal = relevantLocals.Single();
var invocationTargetsLocalOfDelegateType =
(matchingLocal.IsKind(SymbolKind.Local) && ((ILocalSymbol)matchingLocal).Type.IsDelegateType()) ||
(matchingLocal.IsKind(SymbolKind.Parameter) && ((IParameterSymbol)matchingLocal).Type.IsDelegateType());
return !invocationTargetsLocalOfDelegateType;
}
}
}
return false;
}
public override async Task<ImmutableArray<Location>> ComputeDeclarationConflictsAsync(
string replacementText,
ISymbol renamedSymbol,
ISymbol renameSymbol,
IEnumerable<ISymbol> referencedSymbols,
Solution baseSolution,
Solution newSolution,
IDictionary<Location, Location> reverseMappedLocations,
CancellationToken cancellationToken)
{
try
{
using var _ = ArrayBuilder<Location>.GetInstance(out var conflicts);
// If we're renaming a named type, we can conflict with members w/ our same name. Note:
// this doesn't apply to enums.
if (renamedSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } namedType)
AddSymbolSourceSpans(conflicts, namedType.GetMembers(renamedSymbol.Name), reverseMappedLocations);
// If we're contained in a named type (we may be a named type ourself!) then we have a
// conflict. NOTE(cyrusn): This does not apply to enums.
if (renamedSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } containingNamedType &&
containingNamedType.Name == renamedSymbol.Name)
{
AddSymbolSourceSpans(conflicts, [containingNamedType], reverseMappedLocations);
}
if (renamedSymbol.Kind is SymbolKind.Parameter or
SymbolKind.Local or
SymbolKind.RangeVariable)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
// If this is a parameter symbol for a partial method definition, be sure we visited
// the implementation part's body.
// https://github.com/dotnet/roslyn/issues/73772: also do this for properties
if (renamedSymbol is IParameterSymbol renamedParameterSymbol &&
renamedSymbol.ContainingSymbol is IMethodSymbol methodSymbol &&
methodSymbol.PartialImplementationPart != null)
{
var matchingParameterSymbol = methodSymbol.PartialImplementationPart.Parameters[renamedParameterSymbol.Ordinal];
token = matchingParameterSymbol.Locations.Single().FindToken(cancellationToken);
memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
}
else if (renamedSymbol.Kind == SymbolKind.Label)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LabelConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
else if (renamedSymbol.Kind == SymbolKind.Method)
{
conflicts.AddRange(DeclarationConflictHelpers.GetMembersWithConflictingSignatures((IMethodSymbol)renamedSymbol, trimOptionalParameters: false).Select(t => reverseMappedLocations[t]));
// we allow renaming overrides of VB property accessors with parameters in C#.
// VB has a special rule that properties are not allowed to have the same name as any of the parameters.
// Because this declaration in C# affects the property declaration in VB, we need to check this VB rule here in C#.
var properties = new List<ISymbol>();
foreach (var referencedSymbol in referencedSymbols)
{
var property = await RenameUtilities.TryGetPropertyFromAccessorOrAnOverrideAsync(
referencedSymbol, baseSolution, cancellationToken).ConfigureAwait(false);
if (property != null)
properties.Add(property);
}
AddConflictingParametersOfProperties(properties.Distinct(), replacementText, conflicts);
}
else if (renamedSymbol.Kind == SymbolKind.Alias)
{
// in C# there can only be one using with the same alias name in the same block (top of file of namespace).
// It's ok to redefine the alias in different blocks.
var location = renamedSymbol.Locations.Single();
var tree = location.SourceTree;
Contract.ThrowIfNull(tree);
var token = await tree.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentUsing = (UsingDirectiveSyntax)token.Parent!.Parent!.Parent!;
var namespaceDecl = token.Parent.Ancestors().OfType<BaseNamespaceDeclarationSyntax>().FirstOrDefault();
SyntaxList<UsingDirectiveSyntax> usings;
if (namespaceDecl != null)
{
usings = namespaceDecl.Usings;
}
else
{
var compilationUnit = (CompilationUnitSyntax)await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
usings = compilationUnit.Usings;
}
foreach (var usingDirective in usings)
{
if (usingDirective.Alias != null && usingDirective != currentUsing)
{
if (usingDirective.Alias.Name.Identifier.ValueText == currentUsing.Alias!.Name.Identifier.ValueText)
conflicts.Add(reverseMappedLocations[usingDirective.Alias.Name.GetLocation()]);
}
}
}
else if (renamedSymbol.Kind == SymbolKind.TypeParameter)
{
foreach (var location in renamedSymbol.Locations)
{
var token = await location.SourceTree!.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentTypeParameter = token.Parent!;
foreach (var typeParameter in ((TypeParameterListSyntax)currentTypeParameter.Parent!).Parameters)
{
if (typeParameter != currentTypeParameter && token.ValueText == typeParameter.Identifier.ValueText)
conflicts.Add(reverseMappedLocations[typeParameter.Identifier.GetLocation()]);
}
}
}
// if the renamed symbol is a type member, it's name should not conflict with a type parameter
if (renamedSymbol.ContainingType != null && renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name).Contains(renamedSymbol))
{
var conflictingLocations = renamedSymbol.ContainingType.TypeParameters
.Where(t => t.Name == renamedSymbol.Name)
.SelectMany(t => t.Locations);
foreach (var location in conflictingLocations)
{
var typeParameterToken = location.FindToken(cancellationToken);
conflicts.Add(reverseMappedLocations[typeParameterToken.GetLocation()]);
}
}
return conflicts.ToImmutableAndClear();
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable();
}
}
private static async Task<ISymbol?> GetVBPropertyFromAccessorOrAnOverrideAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
try
{
if (symbol.IsPropertyAccessor())
{
var property = ((IMethodSymbol)symbol).AssociatedSymbol!;
return property.Language == LanguageNames.VisualBasic ? property : null;
}
if (symbol.IsOverride && symbol.GetOverriddenMember() != null)
{
var originalSourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol.GetOverriddenMember(), solution, cancellationToken).ConfigureAwait(false);
if (originalSourceSymbol != null)
{
return await GetVBPropertyFromAccessorOrAnOverrideAsync(originalSourceSymbol, solution, cancellationToken).ConfigureAwait(false);
}
}
return null;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable();
}
}
private static void AddSymbolSourceSpans(
ArrayBuilder<Location> conflicts, IEnumerable<ISymbol> symbols,
IDictionary<Location, Location> reverseMappedLocations)
{
foreach (var symbol in symbols)
{
foreach (var location in symbol.Locations)
{
// reverseMappedLocations may not contain the location if the location's token
// does not contain the text of it's name (e.g. the getter of "int X { get; }"
// does not contain the text "get_X" so conflicting renames to "get_X" will not
// have added the getter to reverseMappedLocations).
if (location.IsInSource && reverseMappedLocations.TryGetValue(location, out var conflictingLocation))
{
conflicts.Add(conflictingLocation);
}
}
}
}
public override async Task<ImmutableArray<Location>> ComputeImplicitReferenceConflictsAsync(
ISymbol renameSymbol, ISymbol renamedSymbol, IEnumerable<ReferenceLocation> implicitReferenceLocations, CancellationToken cancellationToken)
{
// Handle renaming of symbols used for foreach
var implicitReferencesMightConflict = renameSymbol.Kind == SymbolKind.Property &&
string.Compare(renameSymbol.Name, "Current", StringComparison.OrdinalIgnoreCase) == 0;
implicitReferencesMightConflict =
implicitReferencesMightConflict ||
(renameSymbol.Kind == SymbolKind.Method &&
(string.Compare(renameSymbol.Name, WellKnownMemberNames.MoveNextMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetEnumeratorMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetAwaiter, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.DeconstructMethodName, StringComparison.OrdinalIgnoreCase) == 0));