ConflictResolver.cs 21.9 KB
Newer Older
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 11 12 13 14 15 16 17 18 19 20

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;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Rename.ConflictEngine
{
    internal static partial class ConflictResolver
    {
21
        private static readonly SymbolDisplayFormat s_metadataSymbolDisplayFormat = new SymbolDisplayFormat(
P
Pilchie 已提交
22 23 24 25 26 27 28 29 30 31
            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);

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

        /// <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>
41 42 43 44
        /// <param name="hasConflict">Called after renaming references.  Can be used by callers to 
        /// 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 已提交
45 46 47
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A conflict resolution containing the new solution.</returns>
        public static Task<ConflictResolution> ResolveConflictsAsync(
48
            RenameLocations renameLocationSet,
P
Pilchie 已提交
49 50 51
            string originalText,
            string replacementText,
            OptionSet optionSet,
52
            Func<IEnumerable<ISymbol>, bool?> hasConflict,
P
Pilchie 已提交
53 54 55 56 57 58 59 60 61
            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.
62
                throw new ArgumentException(string.Format(WorkspacesResources.Symbol_0_is_not_from_source, renameLocationSet.Symbol.Name));
P
Pilchie 已提交
63 64
            }

65
            var session = new Session(renameLocationSet, renameSymbolDeclarationLocation, originalText, replacementText, optionSet, hasConflict, cancellationToken);
P
Pilchie 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
            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)
        {
89
            var renameRewriterService = document.Project.LanguageServices.GetService<IRenameRewriterLanguageService>();
P
Pilchie 已提交
90 91 92 93
            var complexifiedTarget = renameRewriterService.GetExpansionTargetForLocation(tokenOrNode);
            return complexifiedTarget;
        }

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

        private static bool IsIdentifierValid_Worker(Solution solution, string replacementText, IEnumerable<ProjectId> projectIds, CancellationToken cancellationToken)
        {
103
            foreach (var language in projectIds.Select(p => solution.GetProject(p).Language).Distinct())
P
Pilchie 已提交
104
            {
105 106 107
                var languageServices = solution.Workspace.Services.GetLanguageServices(language);
                var renameRewriterLanguageService = languageServices.GetService<IRenameRewriterLanguageService>();
                var syntaxFactsLanguageService = languageServices.GetService<ISyntaxFactsService>();
P
Pilchie 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
                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 已提交
124
        private static async Task AddImplicitConflictsAsync(
P
Pilchie 已提交
125 126 127 128 129 130 131 132 133 134
            ISymbol renamedSymbol,
            ISymbol originalSymbol,
            IEnumerable<ReferenceLocation> implicitReferenceLocations,
            SemanticModel semanticModel,
            Location originalDeclarationLocation,
            int newDeclarationLocationStartingPosition,
            ConflictResolution conflictResolution,
            CancellationToken cancellationToken)
        {
            {
135
                var renameRewriterService = conflictResolution.NewSolution.Workspace.Services.GetLanguageServices(renamedSymbol.Language).GetService<IRenameRewriterLanguageService>();
P
Pilchie 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
                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)
152
                var renameRewriterService = implicitReferenceLocationsPerLanguage.First().Document.Project.LanguageServices.GetService<IRenameRewriterLanguageService>();
C
Cyrus Najmabadi 已提交
153
                var implicitConflicts = await renameRewriterService.ComputeImplicitReferenceConflictsAsync(
P
Pilchie 已提交
154 155 156
                    originalSymbol,
                    renamedSymbol,
                    implicitReferenceLocationsPerLanguage,
C
Cyrus Najmabadi 已提交
157
                    cancellationToken).ConfigureAwait(false);
P
Pilchie 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

                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,
            IEnumerable<ISymbol> referencedSymbols,
            ConflictResolution conflictResolution,
            IDictionary<Location, Location> reverseMappedLocations,
            CancellationToken cancellationToken)
        {
180
            if (renamedSymbol.ContainingSymbol.IsKind(SymbolKind.NamedType))
P
Pilchie 已提交
181 182
            {
                var otherThingsNamedTheSame = renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name)
J
Jared Parsons 已提交
183
                                                       .Where(s => !s.Equals(renamedSymbol) &&
184 185
                                                                   string.Equals(s.MetadataName, renamedSymbol.MetadataName, StringComparison.Ordinal) &&
                                                                   (s.Kind != SymbolKind.Method || renamedSymbol.Kind != SymbolKind.Method));
P
Pilchie 已提交
186 187 188 189

                AddConflictingSymbolLocations(otherThingsNamedTheSame, conflictResolution, reverseMappedLocations);
            }

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

            if (renamedSymbol.IsKind(SymbolKind.Namespace) && renamedSymbol.ContainingSymbol.IsKind(SymbolKind.Namespace))
            {
                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);
            }

            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));

                var conflictingSymbolLocations = otherThingsNamedTheSame.Where(s => !s.IsKind(SymbolKind.Namespace));
                if (otherThingsNamedTheSame.Any(s => s.IsKind(SymbolKind.Namespace)))
                {
                    conflictingSymbolLocations = conflictingSymbolLocations.Concat(renamedSymbol);
                }

                AddConflictingSymbolLocations(conflictingSymbolLocations, conflictResolution, reverseMappedLocations);
            }

P
Pilchie 已提交
216 217 218 219 220 221
            // Some types of symbols (namespaces, cref stuff, etc) might not have ContainingAssemblies
            if (renamedSymbol.ContainingAssembly != null)
            {
                var project = conflictResolution.NewSolution.GetProject(renamedSymbol.ContainingAssembly, cancellationToken);

                // There also might be language specific rules we need to include
222
                var languageRenameService = project.LanguageServices.GetService<IRenameRewriterLanguageService>();
P
Pilchie 已提交
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
                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));
                }
            }
        }

        internal static void AddConflictingParametersOfProperties(IEnumerable<ISymbol> properties, string newPropertyName, List<Location> conflicts)
        {
            // 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)
                    {
                        Location oldLocation;
                        if (reverseMappedLocations.TryGetValue(newLocation, out oldLocation))
                        {
                            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())
            {
319
                return symbol.ToDisplayParts(s_metadataSymbolDisplayFormat)
P
Pilchie 已提交
320 321 322 323 324
                    .WhereAsArray(p => p.Kind != SymbolDisplayPartKind.PropertyName && p.Kind != SymbolDisplayPartKind.FieldName)
                    .ToDisplayString();
            }
            else
            {
325
                return symbol.ToDisplayString(s_metadataSymbolDisplayFormat);
P
Pilchie 已提交
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
            }
        }

        /// <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)
            {
421
                var previousChar = metadataName[index - 1];
P
Pilchie 已提交
422 423 424 425 426 427 428 429 430 431

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

            // Check for the next char
            if (index + searchText.Length != metadataName.Length)
            {
432
                var nextChar = metadataName[index + searchText.Length];
P
Pilchie 已提交
433 434 435 436 437 438 439 440 441 442 443 444

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

            return true;
        }

        private static bool IsIdentifierSeparator(char element)
        {
445
            return s_metadataNameSeparators.IndexOf(element) != -1;
P
Pilchie 已提交
446 447
        }
    }
448
}