ConflictResolver.cs 23.6 KB
Newer Older
T
Tomas Matousek 已提交
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2 3 4 5 6 7 8 9 10

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
11
using Microsoft.CodeAnalysis.ErrorReporting;
P
Pilchie 已提交
12 13 14
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
T
Tomas Matousek 已提交
15
using Microsoft.CodeAnalysis.PooledObjects;
P
Pilchie 已提交
16 17 18 19 20 21 22
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Rename.ConflictEngine
{
    internal static partial class ConflictResolver
    {
23
        private static readonly SymbolDisplayFormat s_metadataSymbolDisplayFormat = new SymbolDisplayFormat(
P
Pilchie 已提交
24 25 26 27 28 29 30 31 32 33
            globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included,
            typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
            genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeConstraints | SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
            memberOptions: SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeModifiers | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
            delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
            extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod,
            parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType,
            propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
            miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers);

34
        private const string s_metadataNameSeparators = " .,:<`>()\r\n";
P
Pilchie 已提交
35 36 37 38 39 40 41 42

        /// <summary>
        /// Performs the renaming of the symbol in the solution, identifies renaming conflicts and automatically resolves them where possible.
        /// </summary>
        /// <param name="renameLocationSet">The locations to perform the renaming at.</param>
        /// <param name="originalText">The original name of the identifier.</param>
        /// <param name="replacementText">The new name of the identifier</param>
        /// <param name="optionSet">The option for rename</param>
43
        /// <param name="hasConflict">Called after renaming references.  Can be used by callers to
44 45 46
        /// indicate if the new symbols that the reference binds to should be considered to be ok or
        /// are in conflict.  'true' means they are conflicts.  'false' means they are not conflicts.
        /// 'null' means that the default conflict check should be used.</param>
P
Pilchie 已提交
47 48 49
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A conflict resolution containing the new solution.</returns>
        public static Task<ConflictResolution> ResolveConflictsAsync(
50
            RenameLocations renameLocationSet,
P
Pilchie 已提交
51 52 53
            string originalText,
            string replacementText,
            OptionSet optionSet,
54
            Func<IEnumerable<ISymbol>, bool?> hasConflict,
P
Pilchie 已提交
55 56 57 58 59 60 61 62 63
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            // when someone e.g. renames a symbol from metadata through the API (IDE blocks this), we need to return
            var renameSymbolDeclarationLocation = renameLocationSet.Symbol.Locations.Where(loc => loc.IsInSource).FirstOrDefault();
            if (renameSymbolDeclarationLocation == null)
            {
                // Symbol "{0}" is not from source.
64
                throw new ArgumentException(string.Format(WorkspacesResources.Symbol_0_is_not_from_source, renameLocationSet.Symbol.Name));
P
Pilchie 已提交
65 66
            }

67
            var session = new Session(renameLocationSet, renameSymbolDeclarationLocation, originalText, replacementText, optionSet, hasConflict, cancellationToken);
P
Pilchie 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
            return session.ResolveConflictsAsync();
        }

        /// <summary>
        /// Used to find the symbols associated with the Invocation Expression surrounding the Token
        /// </summary>
        private static IEnumerable<ISymbol> SymbolsForEnclosingInvocationExpressionWorker(SyntaxNode invocationExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            var symbolInfo = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken);
            IEnumerable<ISymbol> symbols = null;
            if (symbolInfo.Symbol == null)
            {
                return null;
            }
            else
            {
                symbols = SpecializedCollections.SingletonEnumerable(symbolInfo.Symbol);
                return symbols;
            }
        }

        private static SyntaxNode GetExpansionTargetForLocationPerLanguage(SyntaxToken tokenOrNode, Document document)
        {
91
            var renameRewriterService = document.GetLanguageService<IRenameRewriterLanguageService>();
P
Pilchie 已提交
92 93 94 95
            var complexifiedTarget = renameRewriterService.GetExpansionTargetForLocation(tokenOrNode);
            return complexifiedTarget;
        }

96
        private static bool LocalVariableConflictPerLanguage(SyntaxToken tokenOrNode, Document document, IEnumerable<ISymbol> newReferencedSymbols)
P
Pilchie 已提交
97
        {
98
            var renameRewriterService = document.GetLanguageService<IRenameRewriterLanguageService>();
99
            var isConflict = renameRewriterService.LocalVariableConflict(tokenOrNode, newReferencedSymbols);
P
Pilchie 已提交
100 101 102 103 104
            return isConflict;
        }

        private static bool IsIdentifierValid_Worker(Solution solution, string replacementText, IEnumerable<ProjectId> projectIds, CancellationToken cancellationToken)
        {
105
            foreach (var language in projectIds.Select(p => solution.GetProject(p).Language).Distinct())
P
Pilchie 已提交
106
            {
107 108 109
                var languageServices = solution.Workspace.Services.GetLanguageServices(language);
                var renameRewriterLanguageService = languageServices.GetService<IRenameRewriterLanguageService>();
                var syntaxFactsLanguageService = languageServices.GetService<ISyntaxFactsService>();
P
Pilchie 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
                if (!renameRewriterLanguageService.IsIdentifierValid(replacementText, syntaxFactsLanguageService))
                {
                    return false;
                }
            }

            return true;
        }

        private static bool IsRenameValid(ConflictResolution conflictResolution, ISymbol renamedSymbol)
        {
            // if we rename an identifier and it now binds to a symbol from metadata this should be treated as
            // an invalid rename.
            return conflictResolution.ReplacementTextValid && renamedSymbol != null && renamedSymbol.Locations.Any(loc => loc.IsInSource);
        }

C
Cyrus Najmabadi 已提交
126
        private static async Task AddImplicitConflictsAsync(
P
Pilchie 已提交
127 128 129 130 131 132 133 134 135 136
            ISymbol renamedSymbol,
            ISymbol originalSymbol,
            IEnumerable<ReferenceLocation> implicitReferenceLocations,
            SemanticModel semanticModel,
            Location originalDeclarationLocation,
            int newDeclarationLocationStartingPosition,
            ConflictResolution conflictResolution,
            CancellationToken cancellationToken)
        {
            {
137
                var renameRewriterService = conflictResolution.NewSolution.Workspace.Services.GetLanguageServices(renamedSymbol.Language).GetService<IRenameRewriterLanguageService>();
P
Pilchie 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
                var implicitUsageConflicts = renameRewriterService.ComputePossibleImplicitUsageConflicts(renamedSymbol, semanticModel, originalDeclarationLocation, newDeclarationLocationStartingPosition, cancellationToken);
                foreach (var implicitUsageConflict in implicitUsageConflicts)
                {
                    conflictResolution.AddOrReplaceRelatedLocation(new RelatedLocation(implicitUsageConflict.SourceSpan, conflictResolution.OldSolution.GetDocument(implicitUsageConflict.SourceTree).Id, RelatedLocationType.UnresolvableConflict));
                }
            }

            if (implicitReferenceLocations.IsEmpty())
            {
                return;
            }

            foreach (var implicitReferenceLocationsPerLanguage in implicitReferenceLocations.GroupBy(loc => loc.Document.Project.Language))
            {
                // the location of the implicit reference defines the language rules to check.
                // E.g. foreach in C# using a MoveNext in VB that is renamed to MOVENEXT (within VB)
154
                var renameRewriterService = implicitReferenceLocationsPerLanguage.First().Document.Project.LanguageServices.GetService<IRenameRewriterLanguageService>();
C
Cyrus Najmabadi 已提交
155
                var implicitConflicts = await renameRewriterService.ComputeImplicitReferenceConflictsAsync(
P
Pilchie 已提交
156 157 158
                    originalSymbol,
                    renamedSymbol,
                    implicitReferenceLocationsPerLanguage,
C
Cyrus Najmabadi 已提交
159
                    cancellationToken).ConfigureAwait(false);
P
Pilchie 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

                foreach (var implicitConflict in implicitConflicts)
                {
                    conflictResolution.AddRelatedLocation(new RelatedLocation(implicitConflict.SourceSpan, conflictResolution.OldSolution.GetDocument(implicitConflict.SourceTree).Id, RelatedLocationType.UnresolvableConflict));
                }
            }
        }

        /// <summary>
        /// Computes an adds conflicts relating to declarations, which are independent of
        /// location-based checks. Examples of these types of conflicts include renaming a member to
        /// the same name as another member of a type: binding doesn't change (at least from the
        /// perspective of find all references), but we still need to track it.
        /// </summary>
        internal static async Task AddDeclarationConflictsAsync(
            ISymbol renamedSymbol,
            ISymbol renameSymbol,
177
            IEnumerable<SymbolAndProjectId> referencedSymbols,
P
Pilchie 已提交
178 179 180 181
            ConflictResolution conflictResolution,
            IDictionary<Location, Location> reverseMappedLocations,
            CancellationToken cancellationToken)
        {
182
            try
P
Pilchie 已提交
183
            {
J
JieCarolHu 已提交
184 185
                var project = conflictResolution.NewSolution.GetProject(renamedSymbol.ContainingAssembly, cancellationToken);

186 187 188 189
                if (renamedSymbol.ContainingSymbol.IsKind(SymbolKind.NamedType))
                {
                    var otherThingsNamedTheSame = renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name)
                                                           .Where(s => !s.Equals(renamedSymbol) &&
190 191 192
                                                                       string.Equals(s.MetadataName, renamedSymbol.MetadataName, StringComparison.Ordinal));

                    IEnumerable<ISymbol> otherThingsNamedTheSameExcludeMethodAndParameterizedProperty;
J
JieCarolHu 已提交
193 194 195 196

                    // Possibly overloaded symbols are excluded here and handled elsewhere
                    var semanticFactsService = project.LanguageServices.GetService<ISemanticFactsService>();
                    if (semanticFactsService.SupportsParameterizedProperties)
197 198
                    {
                        otherThingsNamedTheSameExcludeMethodAndParameterizedProperty = otherThingsNamedTheSame
J
JieCarolHu 已提交
199 200
                            .Where(s=> !s.MatchesKind(SymbolKind.Method, SymbolKind.Property) ||
                                !renamedSymbol.MatchesKind(SymbolKind.Method, SymbolKind.Property));
201 202 203 204 205 206 207 208
                    }
                    else
                    {
                        otherThingsNamedTheSameExcludeMethodAndParameterizedProperty = otherThingsNamedTheSame
                            .Where(s => s.Kind != SymbolKind.Method || renamedSymbol.Kind != SymbolKind.Method);
                    }

                    AddConflictingSymbolLocations(otherThingsNamedTheSameExcludeMethodAndParameterizedProperty, conflictResolution, reverseMappedLocations);
209
                }
210 211


212
                if (renamedSymbol.IsKind(SymbolKind.Namespace) && renamedSymbol.ContainingSymbol.IsKind(SymbolKind.Namespace))
213
                {
214 215 216 217 218 219
                    var otherThingsNamedTheSame = ((INamespaceSymbol)renamedSymbol.ContainingSymbol).GetMembers(renamedSymbol.Name)
                                                            .Where(s => !s.Equals(renamedSymbol) &&
                                                                        !s.IsKind(SymbolKind.Namespace) &&
                                                                        string.Equals(s.MetadataName, renamedSymbol.MetadataName, StringComparison.Ordinal));

                    AddConflictingSymbolLocations(otherThingsNamedTheSame, conflictResolution, reverseMappedLocations);
220 221
                }

222 223 224 225 226
                if (renamedSymbol.IsKind(SymbolKind.NamedType) && renamedSymbol.ContainingSymbol is INamespaceOrTypeSymbol)
                {
                    var otherThingsNamedTheSame = ((INamespaceOrTypeSymbol)renamedSymbol.ContainingSymbol).GetMembers(renamedSymbol.Name)
                                                            .Where(s => !s.Equals(renamedSymbol) &&
                                                                        string.Equals(s.MetadataName, renamedSymbol.MetadataName, StringComparison.Ordinal));
227

228 229 230 231 232
                    var conflictingSymbolLocations = otherThingsNamedTheSame.Where(s => !s.IsKind(SymbolKind.Namespace));
                    if (otherThingsNamedTheSame.Any(s => s.IsKind(SymbolKind.Namespace)))
                    {
                        conflictingSymbolLocations = conflictingSymbolLocations.Concat(renamedSymbol);
                    }
P
Pilchie 已提交
233

234 235
                    AddConflictingSymbolLocations(conflictingSymbolLocations, conflictResolution, reverseMappedLocations);
                }
P
Pilchie 已提交
236

237 238
                // Some types of symbols (namespaces, cref stuff, etc) might not have ContainingAssemblies
                if (renamedSymbol.ContainingAssembly != null)
P
Pilchie 已提交
239
                {
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
                    // There also might be language specific rules we need to include
                    var languageRenameService = project.LanguageServices.GetService<IRenameRewriterLanguageService>();
                    var languageConflicts = await languageRenameService.ComputeDeclarationConflictsAsync(
                        conflictResolution.ReplacementText,
                        renamedSymbol,
                        renameSymbol,
                        referencedSymbols,
                        conflictResolution.OldSolution,
                        conflictResolution.NewSolution,
                        reverseMappedLocations,
                        cancellationToken).ConfigureAwait(false);

                    foreach (var languageConflict in languageConflicts)
                    {
                        conflictResolution.AddOrReplaceRelatedLocation(new RelatedLocation(languageConflict.SourceSpan, conflictResolution.OldSolution.GetDocument(languageConflict.SourceTree).Id, RelatedLocationType.UnresolvableConflict));
                    }
P
Pilchie 已提交
256 257
                }
            }
258 259 260 261 262 263 264 265 266
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                // A NullReferenceException is happening in this method, but the dumps do not
                // contain information about this stack frame because this method is async and
                // therefore the exception filter in IdentifyConflictsAsync is insufficient.
                // See https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=378642

                throw ExceptionUtilities.Unreachable;
            }
P
Pilchie 已提交
267 268
        }

269 270
        internal static void AddConflictingParametersOfProperties(
            IEnumerable<ISymbol> properties, string newPropertyName, ArrayBuilder<Location> conflicts)
P
Pilchie 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
        {
            // check if the new property name conflicts with any parameter of the properties.
            // Note: referencedSymbols come from the original solution, so there is no need to reverse map the locations of the parameters
            foreach (var symbol in properties)
            {
                var prop = (IPropertySymbol)symbol;

                var conflictingParameter = prop.Parameters.FirstOrDefault(param => string.Compare(param.Name, newPropertyName, StringComparison.OrdinalIgnoreCase) == 0);

                if (conflictingParameter != null)
                {
                    conflicts.AddRange(conflictingParameter.Locations);
                }
            }
        }

        private static void AddConflictingSymbolLocations(IEnumerable<ISymbol> conflictingSymbols, ConflictResolution conflictResolution, IDictionary<Location, Location> reverseMappedLocations)
        {
            foreach (var newSymbol in conflictingSymbols)
            {
                foreach (var newLocation in newSymbol.Locations)
                {
                    if (newLocation.IsInSource)
                    {
C
CyrusNajmabadi 已提交
295
                        if (reverseMappedLocations.TryGetValue(newLocation, out var oldLocation))
P
Pilchie 已提交
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
                        {
                            conflictResolution.AddOrReplaceRelatedLocation(new RelatedLocation(oldLocation.SourceSpan, conflictResolution.OldSolution.GetDocument(oldLocation.SourceTree).Id, RelatedLocationType.UnresolvableConflict));
                        }
                    }
                }
            }
        }

        public static async Task<RenameDeclarationLocationReference[]> CreateDeclarationLocationAnnotationsAsync(
            Solution solution,
            IEnumerable<ISymbol> symbols,
            CancellationToken cancellationToken)
        {
            var renameDeclarationLocations = new RenameDeclarationLocationReference[symbols.Count()];

            int symbolIndex = 0;
            foreach (var symbol in symbols)
            {
                var locations = symbol.Locations;
                bool overriddenFromMetadata = false;

                if (symbol.IsOverride)
                {
                    var overriddenSymbol = symbol.OverriddenMember();

                    if (overriddenSymbol != null)
                    {
                        overriddenSymbol = await SymbolFinder.FindSourceDefinitionAsync(overriddenSymbol, solution, cancellationToken).ConfigureAwait(false);
                        overriddenFromMetadata = overriddenSymbol == null || overriddenSymbol.Locations.All(loc => loc.IsInMetadata);
                    }
                }

                var location = await GetSymbolLocationAsync(solution, symbol, cancellationToken).ConfigureAwait(false);
                if (location != null && location.IsInSource)
                {
                    renameDeclarationLocations[symbolIndex] = new RenameDeclarationLocationReference(solution.GetDocumentId(location.SourceTree), location.SourceSpan, overriddenFromMetadata, locations.Count());
                }
                else
                {
                    renameDeclarationLocations[symbolIndex] = new RenameDeclarationLocationReference(GetString(symbol), locations.Count());
                }

                symbolIndex++;
            }

            return renameDeclarationLocations;
        }

        private static string GetString(ISymbol symbol)
        {
            if (symbol.IsAnonymousType())
            {
348
                return symbol.ToDisplayParts(s_metadataSymbolDisplayFormat)
P
Pilchie 已提交
349 350 351 352 353
                    .WhereAsArray(p => p.Kind != SymbolDisplayPartKind.PropertyName && p.Kind != SymbolDisplayPartKind.FieldName)
                    .ToDisplayString();
            }
            else
            {
354
                return symbol.ToDisplayString(s_metadataSymbolDisplayFormat);
P
Pilchie 已提交
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
            }
        }

        /// <summary>
        /// Gives the First Location for a given Symbol by ordering the locations using DocumentId first and Location starting position second
        /// </summary>
        private static async Task<Location> GetSymbolLocationAsync(Solution solution, ISymbol symbol, CancellationToken cancellationToken)
        {
            var locations = symbol.Locations;

            var originalsourcesymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
            if (originalsourcesymbol != null)
            {
                locations = originalsourcesymbol.Locations;
            }

            var orderedLocations = locations.OrderBy(l => l.IsInSource ? solution.GetDocumentId(l.SourceTree).Id : Guid.Empty)
                .ThenBy(l => l.IsInSource ? l.SourceSpan.Start : int.MaxValue);

            return orderedLocations.FirstOrDefault();
        }

        private static bool HeuristicMetadataNameEquivalenceCheck(
            string oldMetadataName,
            string newMetadataName,
            string originalText,
            string replacementText)
        {
            if (string.Equals(oldMetadataName, newMetadataName, StringComparison.Ordinal))
            {
                return true;
            }

            var index = 0;
            index = newMetadataName.IndexOf(replacementText, 0);
            StringBuilder newMetadataNameBuilder = new StringBuilder();

            // Every loop updates the newMetadataName to resemble the oldMetadataName
            while (index != -1 && index < oldMetadataName.Length)
            {
                // This check is to ses if the part of string before the string match, matches
                if (!IsSubStringEqual(oldMetadataName, newMetadataName, index))
                {
                    return false;
                }

                // Ok to replace
                if (IsWholeIdentifier(newMetadataName, replacementText, index))
                {
                    newMetadataNameBuilder.Append(newMetadataName, 0, index);
                    newMetadataNameBuilder.Append(originalText);
                    newMetadataNameBuilder.Append(newMetadataName, index + replacementText.Length, newMetadataName.Length - (index + replacementText.Length));
                    newMetadataName = newMetadataNameBuilder.ToString();
                    newMetadataNameBuilder.Clear();
                }

                index = newMetadataName.IndexOf(replacementText, index + 1);
            }

            return string.Equals(newMetadataName, oldMetadataName, StringComparison.Ordinal);
        }

        private static bool IsSubStringEqual(
            string str1,
            string str2,
            int index)
        {
            Debug.Assert(index <= str1.Length && index <= str2.Length, "Index cannot be greater than the string");
            int currentIndex = 0;
            while (currentIndex < index)
            {
                if (str1[currentIndex] != str2[currentIndex])
                {
                    return false;
                }

                currentIndex++;
            }

            return true;
        }

        private static bool IsWholeIdentifier(
            string metadataName,
            string searchText,
            int index)
        {
            if (index == -1)
            {
                return false;
            }

            // Check for the previous char
            if (index != 0)
            {
450
                var previousChar = metadataName[index - 1];
P
Pilchie 已提交
451 452 453 454 455 456 457 458 459 460

                if (!IsIdentifierSeparator(previousChar))
                {
                    return false;
                }
            }

            // Check for the next char
            if (index + searchText.Length != metadataName.Length)
            {
461
                var nextChar = metadataName[index + searchText.Length];
P
Pilchie 已提交
462 463 464 465 466 467 468 469 470 471 472 473

                if (!IsIdentifierSeparator(nextChar))
                {
                    return false;
                }
            }

            return true;
        }

        private static bool IsIdentifierSeparator(char element)
        {
474
            return s_metadataNameSeparators.IndexOf(element) != -1;
P
Pilchie 已提交
475 476
        }
    }
477
}