AbstractChangeNamespaceService.cs 40.2 KB
Newer Older
J
Jonathon Marolf 已提交
1 2 3
// 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.
4

5
using System;
6 7 8 9 10 11 12 13 14 15
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
16
using Microsoft.CodeAnalysis.Host;
17 18 19 20 21
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.RemoveUnnecessaryImports;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
G
Gen Lu 已提交
22
using Microsoft.CodeAnalysis.Text;
23 24 25 26
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.ChangeNamespace
{
G
Gen Lu 已提交
27 28 29
    /// <summary>
    /// This intermediate class is used to hide method `TryGetReplacementReferenceSyntax` from <see cref="IChangeNamespaceService" />.
    /// </summary>
G
Gen Lu 已提交
30
    internal abstract class AbstractChangeNamespaceService : IChangeNamespaceService
31
    {
G
Gen Lu 已提交
32
        public abstract Task<bool> CanChangeNamespaceAsync(Document document, SyntaxNode container, CancellationToken cancellationToken);
G
Gen Lu 已提交
33

G
Gen Lu 已提交
34
        public abstract Task<Solution> ChangeNamespaceAsync(Document document, SyntaxNode container, string targetNamespace, CancellationToken cancellationToken);
35 36 37

        /// <summary>
        /// Try to get a new node to replace given node, which is a reference to a top-level type declared inside the 
G
Gen Lu 已提交
38
        /// namespace to be changed. If this reference is the right side of a qualified name, the new node returned would
39 40 41
        /// be the entire qualified name. Depends on whether <paramref name="newNamespaceParts"/> is provided, the name 
        /// in the new node might be qualified with this new namespace instead.
        /// </summary>
G
Gen Lu 已提交
42
        /// <param name="reference">A reference to a type declared inside the namespace to be changed, which is calculated 
43 44 45 46 47
        /// based on results from `SymbolFinder.FindReferencesAsync`.</param>
        /// <param name="newNamespaceParts">If specified, the namespace of original reference will be replaced with given 
        /// namespace in the replacement node.</param>
        /// <param name="old">The node to be replaced. This might be an ancestor of original </param>
        /// <param name="new">The replacement node.</param>
G
Gen Lu 已提交
48 49 50 51 52 53 54 55 56 57
        public abstract bool TryGetReplacementReferenceSyntax(SyntaxNode reference, ImmutableArray<string> newNamespaceParts, ISyntaxFactsService syntaxFacts, out SyntaxNode old, out SyntaxNode @new);
    }

    internal abstract class AbstractChangeNamespaceService<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax>
        : AbstractChangeNamespaceService
        where TNamespaceDeclarationSyntax : SyntaxNode
        where TCompilationUnitSyntax : SyntaxNode
        where TMemberDeclarationSyntax : SyntaxNode
    {
        private static readonly char[] s_dotSeparator = new[] { '.' };
58

G
Gen Lu 已提交
59
        /// <summary>
G
Gen Lu 已提交
60
        /// The annotation used to track applicable container in each document to be fixed.
G
Gen Lu 已提交
61
        /// </summary>
G
Gen Lu 已提交
62
        protected static SyntaxAnnotation ContainerAnnotation { get; } = new SyntaxAnnotation();
G
Gen Lu 已提交
63 64 65 66 67

        protected static SyntaxAnnotation WarningAnnotation { get; }
            = CodeActions.WarningAnnotation.Create(
                FeaturesResources.Warning_colon_changing_namespace_may_produce_invalid_code_and_change_code_meaning);

68 69 70 71 72
        protected abstract TCompilationUnitSyntax ChangeNamespaceDeclaration(
            TCompilationUnitSyntax root, ImmutableArray<string> declaredNamespaceParts, ImmutableArray<string> targetNamespaceParts);

        protected abstract SyntaxList<TMemberDeclarationSyntax> GetMemberDeclarationsInContainer(SyntaxNode compilationUnitOrNamespaceDecl);

G
Gen Lu 已提交
73 74
        protected abstract Task<SyntaxNode> TryGetApplicableContainerFromSpanAsync(Document document, TextSpan span, CancellationToken cancellationToken);

G
Gen Lu 已提交
75
        protected abstract string GetDeclaredNamespace(SyntaxNode container);
G
Gen Lu 已提交
76

G
Gen Lu 已提交
77 78 79 80 81 82 83 84 85 86
        /// <summary>
        /// Decide if we can change the namespace for provided <paramref name="container"/> based on the criteria listed for 
        /// <see cref="IChangeNamespaceService.CanChangeNamespaceAsync(Document, SyntaxNode, CancellationToken)"/>
        /// </summary>
        /// <returns>
        /// If namespace can be changed, returns a list of documents that linked to the provided document (including itself)
        /// and the corresponding container nodes in each document, which will later be used for annotation. Otherwise, a 
        /// default ImmutableArray is returned. Currently we only support linked document in multi-targeting project scenario.
        /// </returns>
        protected abstract Task<ImmutableArray<(DocumentId id, SyntaxNode container)>> GetValidContainersFromAllLinkedDocumentsAsync(Document document, SyntaxNode container, CancellationToken cancellationToken);
G
Gen Lu 已提交
87

88 89 90
        private static bool IsValidContainer(SyntaxNode container)
            => container is TCompilationUnitSyntax || container is TNamespaceDeclarationSyntax;

91 92 93
        protected static bool IsGlobalNamespace(ImmutableArray<string> parts)
            => parts.Length == 1 && parts[0].Length == 0;

G
Gen Lu 已提交
94
        public override async Task<bool> CanChangeNamespaceAsync(Document document, SyntaxNode container, CancellationToken cancellationToken)
G
Gen Lu 已提交
95
        {
96 97 98 99 100
            if (!IsValidContainer(container))
            {
                throw new ArgumentException(nameof(container));
            }

G
Gen Lu 已提交
101
            var applicableContainers = await GetValidContainersFromAllLinkedDocumentsAsync(document, container, cancellationToken).ConfigureAwait(false);
G
Gen Lu 已提交
102 103 104
            return !applicableContainers.IsDefault;
        }

G
Gen Lu 已提交
105 106 107
        public override async Task<Solution> ChangeNamespaceAsync(
            Document document,
            SyntaxNode container,
D
dotnet-bot 已提交
108
            string targetNamespace,
G
Gen Lu 已提交
109 110 111 112
            CancellationToken cancellationToken)
        {
            // Make sure given namespace name is valid, "" means global namespace.
            var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
D
dotnet-bot 已提交
113
            if (targetNamespace == null
G
Gen Lu 已提交
114 115
                || (targetNamespace.Length > 0 && !targetNamespace.Split(s_dotSeparator).All(syntaxFacts.IsValidIdentifier)))
            {
116 117 118 119 120 121
                throw new ArgumentException(nameof(targetNamespace));
            }

            if (!IsValidContainer(container))
            {
                throw new ArgumentException(nameof(container));
G
Gen Lu 已提交
122 123
            }

124 125
            var solution = document.Project.Solution;

G
Gen Lu 已提交
126
            var containersFromAllDocuments = await GetValidContainersFromAllLinkedDocumentsAsync(document, container, cancellationToken).ConfigureAwait(false);
G
Gen Lu 已提交
127 128 129 130 131 132 133 134 135 136 137 138
            if (containersFromAllDocuments.IsDefault)
            {
                return solution;
            }

            // No action required if declared namespace already matches target.
            var declaredNamespace = GetDeclaredNamespace(container);
            if (syntaxFacts.StringComparer.Equals(targetNamespace, declaredNamespace))
            {
                return solution;
            }

G
Gen Lu 已提交
139
            // Annotate the container nodes so we can still find and modify them after syntax tree has changed.
G
Gen Lu 已提交
140 141 142 143 144 145 146 147 148 149
            var annotatedSolution = await AnnotateContainersAsync(solution, containersFromAllDocuments, cancellationToken).ConfigureAwait(false);

            // Here's the entire process for changing namespace:
            // 1. Change the namespace declaration, fix references and add imports that might be necessary.
            // 2. Explicitly merge the diff to get a new solution.
            // 3. Remove added imports that are unnecessary.
            // 4. Do another explicit diff merge based on last merged solution.
            //
            // The reason for doing explicit diff merge twice is so merging after remove unnecessary imports can be correctly handled.

G
Gen Lu 已提交
150
            var documentIds = containersFromAllDocuments.SelectAsArray(pair => pair.id);
G
Gen Lu 已提交
151
            var solutionAfterNamespaceChange = annotatedSolution;
152
            using var _ = PooledHashSet<DocumentId>.GetInstance(out var referenceDocuments);
G
Gen Lu 已提交
153

154
            foreach (var documentId in documentIds)
G
Gen Lu 已提交
155
            {
156 157 158 159 160 161
                var (newSolution, refDocumentIds) =
                    await ChangeNamespaceInSingleDocumentAsync(solutionAfterNamespaceChange, documentId, declaredNamespace, targetNamespace, cancellationToken)
                        .ConfigureAwait(false);
                solutionAfterNamespaceChange = newSolution;
                referenceDocuments.AddRange(refDocumentIds);
            }
G
Gen Lu 已提交
162

163
            var solutionAfterFirstMerge = await MergeDiffAsync(solution, solutionAfterNamespaceChange, cancellationToken).ConfigureAwait(false);
G
Gen Lu 已提交
164

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
            // After changing documents, we still need to remove unnecessary imports related to our change.
            // We don't try to remove all imports that might become unnecessary/invalid after the namespace change, 
            // just ones that fully match the old/new namespace. Because it's hard to get it right and will almost 
            // certainly cause perf issue.
            // For example, if we are changing namespace `Foo.Bar` (which is the only namespace declaration with such name)
            // to `A.B`, the using of name `Bar` in a different file below would remain untouched, even it's no longer valid:
            //
            //      namespace Foo
            //      {
            //          using Bar;
            //          ~~~~~~~~~
            //      }
            //
            // Also, because we may have added different imports to document that triggered the refactoring
            // and the documents that reference affected types declared in changed namespace, we try to remove
            // unnecessary imports separately.

            var solutionAfterImportsRemoved = await RemoveUnnecessaryImportsAsync(
                solutionAfterFirstMerge,
                documentIds,
                GetAllNamespaceImportsForDeclaringDocument(declaredNamespace, targetNamespace),
                cancellationToken).ConfigureAwait(false);
G
Gen Lu 已提交
187

188 189 190 191 192
            solutionAfterImportsRemoved = await RemoveUnnecessaryImportsAsync(
                solutionAfterImportsRemoved,
                referenceDocuments.ToImmutableArray(),
                ImmutableArray.Create(declaredNamespace, targetNamespace),
                cancellationToken).ConfigureAwait(false);
G
Gen Lu 已提交
193

194
            return await MergeDiffAsync(solutionAfterFirstMerge, solutionAfterImportsRemoved, cancellationToken).ConfigureAwait(false);
G
Gen Lu 已提交
195 196
        }

G
Gen Lu 已提交
197 198 199 200 201 202
        protected async Task<ImmutableArray<(DocumentId, SyntaxNode)>> TryGetApplicableContainersFromAllDocumentsAsync(
            Solution solution,
            ImmutableArray<DocumentId> ids,
            TextSpan span,
            CancellationToken cancellationToken)
        {
G
Gen Lu 已提交
203
            // If the node specified by span doesn't meet the requirement to be an applicable container in any of the documents 
G
Gen Lu 已提交
204 205 206 207 208
            // (See `TryGetApplicableContainerFromSpanAsync`), or we are getting different namespace declarations among 
            // those documents, then we know we can't make a proper code change. We will return null and the check 
            // will return false. We use span of namespace declaration found in each document to decide if they are identical.            

            var documents = ids.SelectAsArray(id => solution.GetDocument(id));
209 210
            using var containersDisposer = ArrayBuilder<(DocumentId, SyntaxNode)>.GetInstance(ids.Length, out var containers);
            using var spanForContainersDisposer = PooledHashSet<TextSpan>.GetInstance(out var spanForContainers);
G
Gen Lu 已提交
211

212
            foreach (var document in documents)
G
Gen Lu 已提交
213
            {
214 215 216 217 218 219 220 221 222 223 224 225 226
                var container = await TryGetApplicableContainerFromSpanAsync(document, span, cancellationToken).ConfigureAwait(false);

                if (container is TNamespaceDeclarationSyntax)
                {
                    spanForContainers.Add(container.Span);
                }
                else if (container is TCompilationUnitSyntax)
                {
                    // In case there's no namespace declaration in the document, we used an empty span as key, 
                    // since a valid namespace declaration node can't have zero length.
                    spanForContainers.Add(default);
                }
                else
G
Gen Lu 已提交
227
                {
228
                    return default;
G
Gen Lu 已提交
229 230
                }

231
                containers.Add((document.Id, container));
G
Gen Lu 已提交
232
            }
233 234

            return spanForContainers.Count == 1 ? containers.ToImmutable() : default;
G
Gen Lu 已提交
235 236
        }

G
Gen Lu 已提交
237 238 239
        /// <summary>
        /// Mark container nodes with our annotation so we can keep track of them across syntax modifications.
        /// </summary>
G
Gen Lu 已提交
240 241 242 243 244 245
        protected async Task<Solution> AnnotateContainersAsync(Solution solution, ImmutableArray<(DocumentId, SyntaxNode)> containers, CancellationToken cancellationToken)
        {
            var solutionEditor = new SolutionEditor(solution);
            foreach (var (id, container) in containers)
            {
                var documentEditor = await solutionEditor.GetDocumentEditorAsync(id, cancellationToken).ConfigureAwait(false);
G
Gen Lu 已提交
246
                documentEditor.ReplaceNode(container, container.WithAdditionalAnnotations(ContainerAnnotation));
G
Gen Lu 已提交
247
            }
G
Gen Lu 已提交
248

G
Gen Lu 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
            return solutionEditor.GetChangedSolution();
        }

        protected async Task<bool> ContainsPartialTypeWithMultipleDeclarationsAsync(
            Document document, SyntaxNode container, CancellationToken cancellationToken)
        {
            var memberDecls = GetMemberDeclarationsInContainer(container);
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            var semanticFacts = document.GetLanguageService<ISemanticFactsService>();

            foreach (var memberDecl in memberDecls)
            {
                var memberSymbol = semanticModel.GetDeclaredSymbol(memberDecl, cancellationToken);

                // Simplify the check by assuming no multiple partial declarations in one document
                if (memberSymbol is ITypeSymbol typeSymbol
                    && typeSymbol.DeclaringSyntaxReferences.Length > 1
                    && semanticFacts.IsPartial(typeSymbol, cancellationToken))
                {
                    return true;
                }
            }
G
Gen Lu 已提交
271

G
Gen Lu 已提交
272 273 274 275 276 277 278 279 280 281
            return false;
        }

        protected static bool IsSupportedLinkedDocument(Document document, out ImmutableArray<DocumentId> allDocumentIds)
        {
            var solution = document.Project.Solution;
            var linkedDocumentIds = document.GetLinkedDocumentIds();

            // TODO: figure out how to properly determine if and how a document is linked using project system.

G
Gen Lu 已提交
282
            // If we found a linked document which is part of a project with different project file,
G
Gen Lu 已提交
283 284 285 286 287 288 289 290 291 292 293
            // then it's an actual linked file (i.e. not a multi-targeting project). We don't support that for now.
            if (linkedDocumentIds.Any(id =>
                    !PathUtilities.PathsEqual(solution.GetDocument(id).Project.FilePath, document.Project.FilePath)))
            {
                allDocumentIds = default;
                return false;
            }

            allDocumentIds = linkedDocumentIds.Add(document.Id);
            return true;
        }
294

G
Gen Lu 已提交
295 296 297
        private async Task<ImmutableArray<ISymbol>> GetDeclaredSymbolsInContainerAsync(
            Document document,
            SyntaxNode container,
298 299
            CancellationToken cancellationToken)
        {
G
Gen Lu 已提交
300 301
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            var declarations = GetMemberDeclarationsInContainer(container);
302
            var builder = ArrayBuilder<ISymbol>.GetInstance();
G
Gen Lu 已提交
303

304 305 306 307 308 309 310 311 312 313 314 315 316 317
            foreach (var declaration in declarations)
            {
                var symbol = semanticModel.GetDeclaredSymbol(declaration, cancellationToken);
                builder.AddIfNotNull(symbol);
            }

            return builder.ToImmutableAndFree();
        }

        private static ImmutableArray<string> GetNamespaceParts(string @namespace)
        {
            return @namespace?.Split(s_dotSeparator).ToImmutableArray() ?? default;
        }

318
        private static ImmutableArray<string> GetAllNamespaceImportsForDeclaringDocument(string oldNamespace, string newNamespace)
319
        {
320
            var parts = GetNamespaceParts(oldNamespace);
321 322 323 324 325 326
            var builder = ArrayBuilder<string>.GetInstance();
            for (var i = 1; i <= parts.Length; ++i)
            {
                builder.Add(string.Join(".", parts.Take(i)));
            }

327 328
            builder.Add(newNamespace);

329 330 331 332 333 334
            return builder.ToImmutableAndFree();
        }

        private ImmutableArray<SyntaxNode> CreateImports(Document document, ImmutableArray<string> names, bool withFormatterAnnotation)
        {
            var generator = SyntaxGenerator.GetGenerator(document);
335
            using var builderDisposer = ArrayBuilder<SyntaxNode>.GetInstance(names.Length, out var builder);
336 337 338 339 340
            for (var i = 0; i < names.Length; ++i)
            {
                builder.Add(CreateImport(generator, names[i], withFormatterAnnotation));
            }

341
            return builder.ToImmutable();
342 343 344 345 346 347 348 349 350
        }

        private static SyntaxNode CreateImport(SyntaxGenerator syntaxGenerator, string name, bool withFormatterAnnotation)
        {
            var import = syntaxGenerator.NamespaceImportDeclaration(name);
            if (withFormatterAnnotation)
            {
                import = import.WithAdditionalAnnotations(Formatter.Annotation);
            }
G
Gen Lu 已提交
351

352
            return import;
D
dotnet-bot 已提交
353
        }
354 355

        /// <summary>
G
Gen Lu 已提交
356 357
        /// Try to change the namespace declaration in the document (specified by <paramref name="id"/> in <paramref name="solution"/>).
        /// Returns a new solution after changing namespace, and a list of IDs for documents that also changed because they reference
358 359
        /// the types declared in the changed namespace (not include the document contains the declaration itself).
        /// </summary>
G
Gen Lu 已提交
360
        private async Task<(Solution, ImmutableArray<DocumentId>)> ChangeNamespaceInSingleDocumentAsync(
D
dotnet-bot 已提交
361 362 363 364
            Solution solution,
            DocumentId id,
            string oldNamespace,
            string newNamespace,
365 366 367
            CancellationToken cancellationToken)
        {
            var document = solution.GetDocument(id);
G
Gen Lu 已提交
368
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
G
Gen Lu 已提交
369
            var container = root.GetAnnotatedNodes(ContainerAnnotation).Single();
370

G
Gen Lu 已提交
371
            // Get types declared in the changing namespace, because we need to fix all references to them, 
372
            // e.g. change the namespace for qualified name, add imports to proper containers, etc.
G
Gen Lu 已提交
373
            var declaredSymbols = await GetDeclaredSymbolsInContainerAsync(document, container, cancellationToken).ConfigureAwait(false);
374 375 376

            var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);

N
nnpcYvIVl 已提交
377
            // Separating references to declaredSymbols into two groups based on whether it's located in the same 
378
            // document as the namespace declaration. This is because code change required for them are different.
379 380
            var refLocationsInCurrentDocument = new List<LocationForAffectedSymbol>();
            var refLocationsInOtherDocuments = new List<LocationForAffectedSymbol>();
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

            var refLocations = await Task.WhenAll(
                declaredSymbols.Select(declaredSymbol
                    => FindReferenceLocationsForSymbol(document, declaredSymbol, cancellationToken))).ConfigureAwait(false);

            foreach (var refLocation in refLocations.SelectMany(locs => locs))
            {
                if (refLocation.Document.Id == document.Id)
                {
                    refLocationsInCurrentDocument.Add(refLocation);
                }
                else
                {
                    Debug.Assert(!PathUtilities.PathsEqual(refLocation.Document.FilePath, document.FilePath));
                    refLocationsInOtherDocuments.Add(refLocation);
                }
            }

            var documentWithNewNamespace = await FixDeclarationDocumentAsync(document, refLocationsInCurrentDocument, oldNamespace, newNamespace, cancellationToken)
                .ConfigureAwait(false);
            var solutionWithChangedNamespace = documentWithNewNamespace.Project.Solution;

            var refLocationGroups = refLocationsInOtherDocuments.GroupBy(loc => loc.Document.Id);

            var fixedDocuments = await Task.WhenAll(
                refLocationGroups.Select(refInOneDocument =>
                    FixReferencingDocumentAsync(
                        solutionWithChangedNamespace.GetDocument(refInOneDocument.Key),
                        refInOneDocument,
                        newNamespace,
                        cancellationToken))).ConfigureAwait(false);

            var solutionWithFixedReferences = await MergeDocumentChangesAsync(solutionWithChangedNamespace, fixedDocuments, cancellationToken).ConfigureAwait(false);

            return (solutionWithFixedReferences, refLocationGroups.SelectAsArray(g => g.Key));
        }

        private static async Task<Solution> MergeDocumentChangesAsync(Solution originalSolution, Document[] changedDocuments, CancellationToken cancellationToken)
        {
            foreach (var document in changedDocuments)
            {
                originalSolution = originalSolution.WithDocumentSyntaxRoot(
                    document.Id,
                    await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false));
            }

            return originalSolution;
        }

G
Gen Lu 已提交
430
        private readonly struct LocationForAffectedSymbol
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
        {
            public LocationForAffectedSymbol(ReferenceLocation location, bool isReferenceToExtensionMethod)
            {
                ReferenceLocation = location;
                IsReferenceToExtensionMethod = isReferenceToExtensionMethod;
            }

            public ReferenceLocation ReferenceLocation { get; }

            public bool IsReferenceToExtensionMethod { get; }

            public Document Document => ReferenceLocation.Document;
        }

        private static async Task<ImmutableArray<LocationForAffectedSymbol>> FindReferenceLocationsForSymbol(
446 447
            Document document, ISymbol symbol, CancellationToken cancellationToken)
        {
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
            using var _ = ArrayBuilder<LocationForAffectedSymbol>.GetInstance(out var builder);

            var referencedSymbols = await FindReferencesAsync(symbol, document, cancellationToken).ConfigureAwait(false);
            builder.AddRange(referencedSymbols
                .Where(refSymbol => refSymbol.Definition.Equals(symbol))
                .SelectMany(refSymbol => refSymbol.Locations)
                .Select(location => new LocationForAffectedSymbol(location, isReferenceToExtensionMethod: false)));

            // So far we only have references to types declared in affected namespace. We also need to 
            // handle invocation of extension methods (in reduced form) that are declared in those types. 
            // Therefore additional calls to find references are needed for those extension methods.
            // This will returns all the references, not just in the reduced form. But we will
            // not further distinguish the usage. In the worst case, those references are redundant because
            // they are already covered by the type references found above.
            if (symbol is INamedTypeSymbol typeSymbol && typeSymbol.MightContainExtensionMethods)
463
            {
464
                foreach (var methodSymbol in typeSymbol.GetMembers().OfType<IMethodSymbol>())
465
                {
466
                    if (methodSymbol.IsExtensionMethod)
467
                    {
468 469 470 471
                        var referencedMethodSymbols = await FindReferencesAsync(methodSymbol, document, cancellationToken).ConfigureAwait(false);
                        builder.AddRange(referencedMethodSymbols
                            .SelectMany(refSymbol => refSymbol.Locations)
                            .Select(location => new LocationForAffectedSymbol(location, isReferenceToExtensionMethod: true)));
472 473 474
                    }
                }
            }
475 476

            return builder.ToImmutable();
G
Gen Lu 已提交
477
        }
478

G
Gen Lu 已提交
479 480 481 482 483 484 485 486 487 488 489 490 491
        private static async Task<ImmutableArray<ReferencedSymbol>> FindReferencesAsync(ISymbol symbol, Document document, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var progress = new StreamingProgressCollector(StreamingFindReferencesProgress.Instance);
            await SymbolFinder.FindReferencesAsync(
                symbolAndProjectId: SymbolAndProjectId.Create(symbol, document.Project.Id),
                solution: document.Project.Solution,
                documents: null,
                progress: progress,
                options: FindReferencesSearchOptions.Default,
                cancellationToken: cancellationToken).ConfigureAwait(false);

            return progress.GetReferencedSymbols();
492 493 494 495
        }

        private async Task<Document> FixDeclarationDocumentAsync(
            Document document,
496
            IReadOnlyList<LocationForAffectedSymbol> refLocations,
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
            string oldNamespace,
            string newNamespace,
            CancellationToken cancellationToken)
        {
            Debug.Assert(newNamespace != null);

            // 1. Fix references to the affected types in this document if necessary.
            // 2. Add usings for containing namespaces, in case we have references 
            //    relying on old namespace declaration for resolution. 
            //
            //      For example, in the code below, after we change namespace to 
            //      "A.B.C", we will need to add "using Foo.Bar;".     
            //
            //      namespace Foo.Bar.Baz
            //      {
            //          class C1
            //          {
            //               C2 _c2;    // C2 is define in namespace "Foo.Bar" in another document.
            //          }
            //      }
            //
            // 3. Change namespace declaration to target namespace.
            // 4. Simplify away unnecessary qualifications.

            var addImportService = document.GetLanguageService<IAddImportsService>();
G
Gen Lu 已提交
522
            ImmutableArray<SyntaxNode> containersToAddImports;
523 524 525 526 527 528

            var oldNamespaceParts = GetNamespaceParts(oldNamespace);
            var newNamespaceParts = GetNamespaceParts(newNamespace);

            if (refLocations.Count > 0)
            {
G
Gen Lu 已提交
529
                (document, containersToAddImports) = await FixReferencesAsync(document, this, addImportService, refLocations, newNamespaceParts, cancellationToken)
530 531 532 533 534 535
                    .ConfigureAwait(false);
            }
            else
            {
                // If there's no reference to types declared in this document,
                // we will use root node as import container.
G
Gen Lu 已提交
536
                containersToAddImports = ImmutableArray.Create(await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false));
537 538
            }

G
Gen Lu 已提交
539
            Debug.Assert(containersToAddImports.Length > 0);
540 541

            // Need to import all containing namespaces of old namespace and add them to the document (if it's not global namespace)
A
Andrew Hall 已提交
542 543 544
            // Include the new namespace in case there are multiple namespace declarations in
            // the declaring document. They may need a using statement added to correctly keep
            // references to the type inside it's new namespace
545
            var namesToImport = GetAllNamespaceImportsForDeclaringDocument(oldNamespace, newNamespace);
546 547 548 549 550 551

            var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
            var placeSystemNamespaceFirst = optionSet.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language);
            var documentWithAddedImports = await AddImportsInContainersAsync(
                    document,
                    addImportService,
G
Gen Lu 已提交
552
                    containersToAddImports,
553 554 555 556 557
                    namesToImport,
                    placeSystemNamespaceFirst,
                    cancellationToken).ConfigureAwait(false);

            var root = await documentWithAddedImports.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
G
Gen Lu 已提交
558

559 560 561 562
            root = ChangeNamespaceDeclaration((TCompilationUnitSyntax)root, oldNamespaceParts, newNamespaceParts)
                .WithAdditionalAnnotations(Formatter.Annotation);

            // Need to invoke formatter explicitly since we are doing the diff merge ourselves.
563
            root = Formatter.Format(root, Formatter.Annotation, documentWithAddedImports.Project.Solution.Workspace, optionSet, cancellationToken);
564 565 566 567 568 569 570 571

            root = root.WithAdditionalAnnotations(Simplifier.Annotation);
            var formattedDocument = documentWithAddedImports.WithSyntaxRoot(root);
            return await Simplifier.ReduceAsync(formattedDocument, optionSet, cancellationToken).ConfigureAwait(false);
        }

        private async Task<Document> FixReferencingDocumentAsync(
            Document document,
572
            IEnumerable<LocationForAffectedSymbol> refLocations,
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
            string newNamespace,
            CancellationToken cancellationToken)
        {
            // 1. Fully qualify all simple references (i.e. not via an alias) with new namespace.
            // 2. Add using of new namespace (for each reference's container).
            // 3. Try to simplify qualified names introduced from step(1).

            var addImportService = document.GetLanguageService<IAddImportsService>();
            var changeNamespaceService = document.GetLanguageService<IChangeNamespaceService>();

            var newNamespaceParts = GetNamespaceParts(newNamespace);

            var (documentWithRefFixed, containers) =
                await FixReferencesAsync(document, changeNamespaceService, addImportService, refLocations, newNamespaceParts, cancellationToken)
                    .ConfigureAwait(false);

            var optionSet = await documentWithRefFixed.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
            var placeSystemNamespaceFirst = optionSet.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, documentWithRefFixed.Project.Language);

            var documentWithAdditionalImports = await AddImportsInContainersAsync(
                documentWithRefFixed,
                addImportService,
                containers,
                ImmutableArray.Create(newNamespace),
                placeSystemNamespaceFirst,
                cancellationToken).ConfigureAwait(false);

            // Need to invoke formatter explicitly since we are doing the diff merge ourselves.
            var formattedDocument = await Formatter.FormatAsync(documentWithAdditionalImports, Formatter.Annotation, optionSet, cancellationToken)
                .ConfigureAwait(false);

            return await Simplifier.ReduceAsync(formattedDocument, optionSet, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Fix each reference and return a collection of proper containers (innermost container
        /// with imports) that new import should be added to based on reference locations.
        /// If <paramref name="newNamespaceParts"/> is specified (not default), the fix would be:
        ///     1. qualify the reference with new namespace and mark it for simplification, or
        ///     2. find and mark the qualified reference for simplification.
        /// Otherwise, there would be no namespace replacement.
        /// </summary>
        private async Task<(Document, ImmutableArray<SyntaxNode>)> FixReferencesAsync(
            Document document,
            IChangeNamespaceService changeNamespaceService,
            IAddImportsService addImportService,
619
            IEnumerable<LocationForAffectedSymbol> refLocations,
620 621 622 623 624
            ImmutableArray<string> newNamespaceParts,
            CancellationToken cancellationToken)
        {
            var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
            var root = editor.OriginalRoot;
625
            using var _ = PooledHashSet<SyntaxNode>.GetInstance(out var containers);
626 627 628 629 630 631

            var generator = SyntaxGenerator.GetGenerator(document);
            var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();

            // We need a dummy import to figure out the container for given reference.
            var dummyImport = CreateImport(generator, "Dummy", withFormatterAnnotation: false);
G
Gen Lu 已提交
632
            var abstractChangeNamespaceService = (AbstractChangeNamespaceService)changeNamespaceService;
633 634 635 636 637 638 639 640

            foreach (var refLoc in refLocations)
            {
                Debug.Assert(document.Id == refLoc.Document.Id);

                // Ignore references via alias. For simple cases where the alias is defined as the type we are interested,
                // it will be handled properly because it is one of the reference to the type symbol. Otherwise, we don't
                // attempt to make a potential fix, and user might end up with errors as a result.                    
641
                if (refLoc.ReferenceLocation.Alias != null)
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
                {
                    continue;
                }

                // Other documents in the solution might have changed after we calculated those ReferenceLocation, 
                // so we can't trust anything to be still up-to-date except their spans.

                // Get inner most node in case of type used as a base type. e.g.
                //
                //      public class Foo {}
                //      public class Bar : Foo {}
                //
                // For the reference to Foo where it is used as a base class, the BaseTypeSyntax and the TypeSyntax
                // have exact same span.

657 658
                var refNode = root.FindNode(refLoc.ReferenceLocation.Location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true);

G
Gen Lu 已提交
659
                // For invocation of extension method, we only need to add missing import.
660
                if (!refLoc.IsReferenceToExtensionMethod)
661
                {
662 663 664 665 666
                    if (abstractChangeNamespaceService.TryGetReplacementReferenceSyntax(
                            refNode, newNamespaceParts, syntaxFacts, out var oldNode, out var newNode))
                    {
                        editor.ReplaceNode(oldNode, newNode.WithAdditionalAnnotations(Simplifier.Annotation));
                    }
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
                }

                // Use a dummy import node to figure out which container the new import will be added to.
                var container = addImportService.GetImportContainer(root, refNode, dummyImport);
                containers.Add(container);
            }

            foreach (var container in containers)
            {
                editor.TrackNode(container);
            }

            var fixedDocument = editor.GetChangedDocument();
            root = await fixedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var result = (fixedDocument, containers.SelectAsArray(c => root.GetCurrentNode(c)));

            return result;
        }

        private async Task<Solution> RemoveUnnecessaryImportsAsync(
            Solution solution,
            ImmutableArray<DocumentId> ids,
            ImmutableArray<string> names,
            CancellationToken cancellationToken)
        {
692
            using var _ = PooledHashSet<DocumentId>.GetInstance(out var linkedDocumentsToSkip);
693 694 695 696
            var documentsToProcessBuilder = ArrayBuilder<Document>.GetInstance();

            foreach (var id in ids)
            {
697
                if (linkedDocumentsToSkip.Contains(id))
698 699 700 701 702
                {
                    continue;
                }

                var document = solution.GetDocument(id);
703
                linkedDocumentsToSkip.AddRange(document.GetLinkedDocumentIds());
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
                documentsToProcessBuilder.Add(document);

                document = await RemoveUnnecessaryImportsWorker(
                    document,
                    CreateImports(document, names, withFormatterAnnotation: false),
                    cancellationToken).ConfigureAwait(false);
                solution = document.Project.Solution;
            }

            var documentsToProcess = documentsToProcessBuilder.ToImmutableAndFree();

            var changeDocuments = await Task.WhenAll(documentsToProcess.Select(
                    doc => RemoveUnnecessaryImportsWorker(
                        doc,
                        CreateImports(doc, names, withFormatterAnnotation: false),
                        cancellationToken))).ConfigureAwait(false);

            return await MergeDocumentChangesAsync(solution, changeDocuments, cancellationToken).ConfigureAwait(false);

            Task<Document> RemoveUnnecessaryImportsWorker(
                Document doc,
                IEnumerable<SyntaxNode> importsToRemove,
                CancellationToken token)
            {
                var removeImportService = doc.GetLanguageService<IRemoveUnnecessaryImportsService>();
                var syntaxFacts = doc.GetLanguageService<ISyntaxFactsService>();

                return removeImportService.RemoveUnnecessaryImportsAsync(
                    doc,
                    import => importsToRemove.Any(importToRemove => syntaxFacts.AreEquivalent(importToRemove, import)),
                    token);
            }
        }

        /// <summary>
        /// Add imports for the namespace specified by <paramref name="names"/>
        /// to the provided <paramref name="containers"/>
        /// </summary>
        private async Task<Document> AddImportsInContainersAsync(
            Document document,
            IAddImportsService addImportService,
            ImmutableArray<SyntaxNode> containers,
            ImmutableArray<string> names,
            bool placeSystemNamespaceFirst,
            CancellationToken cancellationToken)
        {
            // Sort containers based on their span start, to make the result of 
            // adding imports deterministic. 
            if (containers.Length > 1)
            {
                containers = containers.Sort(SyntaxNodeSpanStartComparer.Instance);
            }

            var imports = CreateImports(document, names, withFormatterAnnotation: true);
            foreach (var container in containers)
            {
                // If the container is a namespace declaration, the context we pass to 
                // AddImportService must be a child of the declaration, otherwise the 
                // import will be added to root node instead.
                var contextLocation = container is TNamespaceDeclarationSyntax
                    ? container.DescendantNodes().First()
                    : container;

                var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
                var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
769 770
                var generator = document.GetLanguageService<SyntaxGenerator>();
                root = addImportService.AddImports(compilation, root, contextLocation, imports, generator, placeSystemNamespaceFirst, cancellationToken);
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
                document = document.WithSyntaxRoot(root);
            }

            return document;
        }

        private static async Task<Solution> MergeDiffAsync(Solution oldSolution, Solution newSolution, CancellationToken cancellationToken)
        {
            var diffMergingSession = new LinkedFileDiffMergingSession(oldSolution, newSolution, newSolution.GetChanges(oldSolution), logSessionInfo: false);
            var mergeResult = await diffMergingSession.MergeDiffsAsync(mergeConflictHandler: null, cancellationToken: cancellationToken).ConfigureAwait(false);
            return mergeResult.MergedSolution;
        }

        private class SyntaxNodeSpanStartComparer : IComparer<SyntaxNode>
        {
            private SyntaxNodeSpanStartComparer()
            {
            }

            public static SyntaxNodeSpanStartComparer Instance { get; } = new SyntaxNodeSpanStartComparer();

            public int Compare(SyntaxNode x, SyntaxNode y)
                => x.Span.Start - y.Span.Start;
        }
    }
}