CodeFixService.cs 30.8 KB
Newer Older
1 2 3 4 5
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
6
using System.Composition;
7
using System.Linq;
H
Heejae Chang 已提交
8
using System.Diagnostics;
9
using System.Reflection;
10 11 12 13 14
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
15
using Microsoft.CodeAnalysis.ErrorLogger;
16 17 18 19 20 21 22 23 24
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CodeFixes
{
25
    using Editor.Shared.Utilities;
26 27 28
    using DiagnosticId = String;
    using LanguageKind = String;

29
    [Export(typeof(ICodeFixService)), Shared]
30
    internal partial class CodeFixService : ForegroundThreadAffinitizedObject, ICodeFixService
31
    {
32
        private readonly IDiagnosticAnalyzerService _diagnosticService;
33

34 35
        private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> _workspaceFixersMap;
        private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>> _projectFixersMap;
36 37

        // Shared by project fixers and workspace fixers.
38
        private ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>> _fixerToFixableIdsMap = ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>>.Empty;
39

40
        private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> _fixerPriorityMap;
41

42 43
        private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider> _analyzerReferenceToFixersMap;
        private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback _createProjectCodeFixProvider;
44

45
        private readonly ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> _suppressionProvidersMap;
J
Jonathon Marolf 已提交
46
        private readonly IEnumerable<Lazy<IErrorLoggerService>> _errorLoggers;
47

48
        private ImmutableDictionary<object, FixAllProviderInfo> _fixAllProviderMap;
49

50 51 52
        [ImportingConstructor]
        public CodeFixService(
            IDiagnosticAnalyzerService service,
J
Jonathon Marolf 已提交
53
            [ImportMany]IEnumerable<Lazy<IErrorLoggerService>> loggers,
54 55
            [ImportMany]IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> fixers,
            [ImportMany]IEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>> suppressionProviders)
56
            : base(assertIsForeground: false)
57
        {
J
Jonathon Marolf 已提交
58
            _errorLoggers = loggers;
59
            _diagnosticService = service;
60 61 62
            var fixersPerLanguageMap = fixers.ToPerLanguageMapWithMultipleLanguages();
            var suppressionProvidersPerLanguageMap = suppressionProviders.ToPerLanguageMapWithMultipleLanguages();

J
Jonathon Marolf 已提交
63
            _workspaceFixersMap = GetFixerPerLanguageMap(fixersPerLanguageMap, null);
A
Andrew Casey 已提交
64
            _suppressionProvidersMap = GetSuppressionProvidersPerLanguageMap(suppressionProvidersPerLanguageMap);
65 66

            // REVIEW: currently, fixer's priority is statically defined by the fixer itself. might considering making it more dynamic or configurable.
67
            _fixerPriorityMap = GetFixerPriorityPerLanguageMap(fixersPerLanguageMap);
68 69

            // Per-project fixers
70 71 72
            _projectFixersMap = new ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<string, List<CodeFixProvider>>>();
            _analyzerReferenceToFixersMap = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>();
            _createProjectCodeFixProvider = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback(r => new ProjectCodeFixProvider(r));
73
            _fixAllProviderMap = ImmutableDictionary<object, FixAllProviderInfo>.Empty;
74 75
        }

76 77
        public async Task<FirstDiagnosticResult> GetFirstDiagnosticWithFixAsync(
            Document document, TextSpan range, CancellationToken cancellationToken)
78 79 80 81 82 83 84 85
        {
            if (document == null || !document.IsOpen())
            {
                return default(FirstDiagnosticResult);
            }

            using (var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject())
            {
86
                var fullResult = await _diagnosticService.TryAppendDiagnosticsForSpanAsync(document, range, diagnostics.Object, cancellationToken: cancellationToken).ConfigureAwait(false);
87 88 89 90
                foreach (var diagnostic in diagnostics.Object)
                {
                    cancellationToken.ThrowIfCancellationRequested();

91
                    if (!range.IntersectsWith(diagnostic.TextSpan))
92 93 94 95 96 97 98 99 100 101 102
                    {
                        continue;
                    }

                    // REVIEW: 2 possible designs. 
                    // 1. find the first fix and then return right away. if the lightbulb is actually expanded, find all fixes for the line synchronously. or
                    // 2. kick off a task that finds all fixes for the given range here but return once we find the first one. 
                    // at the same time, let the task to run to finish. if the lightbulb is expanded, we just simply use the task to get all fixes.
                    //
                    // first approach is simpler, so I will implement that first. if the first approach turns out to be not good enough, then
                    // I will try the second approach which will be more complex but quicker
103
                    var hasFix = await ContainsAnyFix(document, diagnostic, cancellationToken).ConfigureAwait(false);
104 105 106 107 108 109 110 111 112 113
                    if (hasFix)
                    {
                        return new FirstDiagnosticResult(!fullResult, hasFix, diagnostic);
                    }
                }

                return new FirstDiagnosticResult(!fullResult, false, default(DiagnosticData));
            }
        }

C
CyrusNajmabadi 已提交
114
        public async Task<ImmutableArray<CodeFixCollection>> GetFixesAsync(Document document, TextSpan range, bool includeSuppressionFixes, CancellationToken cancellationToken)
115 116 117 118 119 120 121 122
        {
            // REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back
            // current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information 
            // (if it is up-to-date) or synchronously do the work at the spot.
            //
            // this design's weakness is that each side don't have enough information to narrow down works to do. it will most likely always do more works than needed.
            // sometimes way more than it is needed. (compilation)
            Dictionary<TextSpan, List<DiagnosticData>> aggregatedDiagnostics = null;
123
            foreach (var diagnostic in await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, cancellationToken: cancellationToken).ConfigureAwait(false))
124
            {
125
                if (diagnostic.IsSuppressed)
126 127 128 129
                {
                    continue;
                }

130 131 132 133 134 135
                cancellationToken.ThrowIfCancellationRequested();

                aggregatedDiagnostics = aggregatedDiagnostics ?? new Dictionary<TextSpan, List<DiagnosticData>>();
                aggregatedDiagnostics.GetOrAdd(diagnostic.TextSpan, _ => new List<DiagnosticData>()).Add(diagnostic);
            }

136
            if (aggregatedDiagnostics == null)
137
            {
C
CyrusNajmabadi 已提交
138
                return ImmutableArray<CodeFixCollection>.Empty;
139 140
            }

C
CyrusNajmabadi 已提交
141
            var result = ArrayBuilder<CodeFixCollection>.GetInstance();
142 143
            foreach (var spanAndDiagnostic in aggregatedDiagnostics)
            {
C
CyrusNajmabadi 已提交
144 145 146
                await AppendFixesAsync(
                    document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, 
                    result, cancellationToken).ConfigureAwait(false);
147 148
            }

C
CyrusNajmabadi 已提交
149
            if (result.Count > 0)
150 151
            {
                // sort the result to the order defined by the fixers
152
                var priorityMap = _fixerPriorityMap[document.Project.Language].Value;
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
                result.Sort((d1, d2) =>
                {
                    if (priorityMap.TryGetValue((CodeFixProvider)d1.Provider, out int priority1))
                    {
                        if (priorityMap.TryGetValue((CodeFixProvider)d2.Provider, out int priority2))
                        {
                            return priority1 - priority2;
                        }
                        else
                        {
                            return -1;
                        }
                    }
                    else
                    {
                        return 1;
                    }
                });
171 172
            }

173 174
            // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
            if (document.Project.Solution.Workspace.Kind != WorkspaceKind.Interactive && includeSuppressionFixes)
175 176 177
            {
                foreach (var spanAndDiagnostic in aggregatedDiagnostics)
                {
C
CyrusNajmabadi 已提交
178 179 180
                    await AppendSuppressionsAsync(
                        document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, 
                        result, cancellationToken).ConfigureAwait(false);
181 182 183
                }
            }

C
CyrusNajmabadi 已提交
184
            return result.ToImmutableAndFree();
185 186
        }

C
CyrusNajmabadi 已提交
187
        private async Task AppendFixesAsync(
188 189
            Document document,
            TextSpan span,
190
            IEnumerable<DiagnosticData> diagnostics,
C
CyrusNajmabadi 已提交
191
            ArrayBuilder<CodeFixCollection> result,
192 193
            CancellationToken cancellationToken)
        {
C
CyrusNajmabadi 已提交
194
            bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out var fixerMap);
195 196 197 198 199 200

            var projectFixersMap = GetProjectFixers(document.Project);
            var hasAnyProjectFixer = projectFixersMap.Any();

            if (!hasAnySharedFixer && !hasAnyProjectFixer)
            {
C
CyrusNajmabadi 已提交
201
                return;
202 203 204 205
            }

            var allFixers = new List<CodeFixProvider>();

206 207 208
            // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
            bool isInteractive = document.Project.Solution.Workspace.Kind == WorkspaceKind.Interactive;

209
            foreach (var diagnosticId in diagnostics.Select(d => d.Id).Distinct())
210 211 212
            {
                cancellationToken.ThrowIfCancellationRequested();

C
CyrusNajmabadi 已提交
213
                if (hasAnySharedFixer && fixerMap.Value.TryGetValue(diagnosticId, out var workspaceFixers))
214
                {
215 216 217 218 219 220 221 222
                    if (isInteractive)
                    {
                        allFixers.AddRange(workspaceFixers.Where(IsInteractiveCodeFixProvider));
                    }
                    else
                    {
                        allFixers.AddRange(workspaceFixers);
                    }
223 224
                }

C
CyrusNajmabadi 已提交
225
                if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out var projectFixers))
226
                {
227
                    Debug.Assert(!isInteractive);
228 229 230 231
                    allFixers.AddRange(projectFixers);
                }
            }

J
Jonathon Marolf 已提交
232
            var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
233 234 235 236 237

            foreach (var fixer in allFixers.Distinct())
            {
                cancellationToken.ThrowIfCancellationRequested();

C
CyrusNajmabadi 已提交
238 239 240 241 242
                await AppendFixesOrSuppressionsAsync(
                    document, span, diagnostics, result, fixer,
                    hasFix: d => this.GetFixableDiagnosticIds(fixer, extensionManager).Contains(d.Id),
                    getFixes: dxs => GetCodeFixesAsync(document, span, fixer, dxs, cancellationToken),
                    cancellationToken: cancellationToken).ConfigureAwait(false);
243 244 245
            }
        }

C
CyrusNajmabadi 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
        private async Task<ImmutableArray<CodeFix>> GetCodeFixesAsync(
            Document document, TextSpan span, CodeFixProvider fixer,
            ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
        {
            var fixes = ArrayBuilder<CodeFix>.GetInstance();
            var context = new CodeFixContext(document, span, diagnostics,
                // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs?
                (action, applicableDiagnostics) =>
                {
                    // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
                    lock (fixes)
                    {
                        fixes.Add(new CodeFix(document.Project, action, applicableDiagnostics));
                    }
                },
                verifyArguments: false,
                cancellationToken: cancellationToken);

            var task = fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask;
            await task.ConfigureAwait(false);
            return fixes.ToImmutableAndFree();
        }

C
CyrusNajmabadi 已提交
269 270 271
        private async Task AppendSuppressionsAsync(
            Document document, TextSpan span, IEnumerable<DiagnosticData> diagnostics, 
            ArrayBuilder<CodeFixCollection> result, CancellationToken cancellationToken)
272
        {
C
CyrusNajmabadi 已提交
273
            if (!_suppressionProvidersMap.TryGetValue(document.Project.Language, out var lazySuppressionProvider) || lazySuppressionProvider.Value == null)
274
            {
C
CyrusNajmabadi 已提交
275
                return;
276 277
            }

C
CyrusNajmabadi 已提交
278 279
            await AppendFixesOrSuppressionsAsync(
                document, span, diagnostics, result, lazySuppressionProvider.Value, 
C
CyrusNajmabadi 已提交
280 281 282 283
                hasFix: d => lazySuppressionProvider.Value.CanBeSuppressedOrUnsuppressed(d),
                getFixes: dxs => lazySuppressionProvider.Value.GetSuppressionsAsync(
                    document, span, dxs, cancellationToken), 
                cancellationToken: cancellationToken).ConfigureAwait(false);
284 285
        }

C
CyrusNajmabadi 已提交
286
        private async Task AppendFixesOrSuppressionsAsync(
287 288
            Document document,
            TextSpan span,
289
            IEnumerable<DiagnosticData> diagnosticsWithSameSpan,
C
CyrusNajmabadi 已提交
290
            ArrayBuilder<CodeFixCollection> result,
291 292
            object fixer,
            Func<Diagnostic, bool> hasFix,
293
            Func<ImmutableArray<Diagnostic>, Task<ImmutableArray<CodeFix>>> getFixes,
294 295
            CancellationToken cancellationToken)
        {
C
CyrusNajmabadi 已提交
296 297 298 299
            var allDiagnostics = 
                await diagnosticsWithSameSpan.OrderByDescending(d => d.Severity)
                                             .ToDiagnosticsAsync(document.Project, cancellationToken).ConfigureAwait(false);
            var diagnostics = allDiagnostics.WhereAsArray(hasFix);
300 301 302
            if (diagnostics.Length <= 0)
            {
                // this can happen for suppression case where all diagnostics can't be suppressed
C
CyrusNajmabadi 已提交
303
                return;
304
            }
S
Shyam N 已提交
305

J
Jonathon Marolf 已提交
306
            var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
307 308 309
            var fixes = await extensionManager.PerformFunctionAsync(fixer,
                () => getFixes(diagnostics),
                defaultValue: ImmutableArray<CodeFix>.Empty).ConfigureAwait(false);
S
Shyam N 已提交
310

C
CyrusNajmabadi 已提交
311
            if (fixes.IsDefaultOrEmpty)
312
            {
C
CyrusNajmabadi 已提交
313 314
                return;
            }
315

C
CyrusNajmabadi 已提交
316 317
            // If the fix provider supports fix all occurrences, then get the corresponding FixAllProviderInfo and fix all context.
            var fixAllProviderInfo = extensionManager.PerformFunction(fixer, () => ImmutableInterlocked.GetOrAdd(ref _fixAllProviderMap, fixer, FixAllProviderInfo.Create), defaultValue: null);
318

C
CyrusNajmabadi 已提交
319
            FixAllState fixAllState = null;
C
CyrusNajmabadi 已提交
320
            var supportedScopes = ImmutableArray<FixAllScope>.Empty;
C
CyrusNajmabadi 已提交
321 322 323 324 325 326 327 328
            if (fixAllProviderInfo != null)
            {
                var codeFixProvider = (fixer as CodeFixProvider) ?? new WrapperCodeFixProvider((ISuppressionFixProvider)fixer, diagnostics.Select(d => d.Id));
                fixAllState = FixAllState.Create(
                    fixAllProviderInfo.FixAllProvider,
                    document, fixAllProviderInfo, codeFixProvider, diagnostics,
                    this.GetDocumentDiagnosticsAsync, this.GetProjectDiagnosticsAsync);
                supportedScopes = fixAllProviderInfo.SupportedScopes;
329
            }
C
CyrusNajmabadi 已提交
330 331 332 333 334

            var codeFix = new CodeFixCollection(
                fixer, span, fixes, fixAllState,
                supportedScopes, diagnostics.First());
            result.Add(codeFix);
335 336
        }

337
        public CodeFixProvider GetSuppressionFixer(string language, IEnumerable<string> diagnosticIds)
338
        {
C
CyrusNajmabadi 已提交
339
            if (!_suppressionProvidersMap.TryGetValue(language, out var lazySuppressionProvider) || lazySuppressionProvider.Value == null)
340 341 342 343
            {
                return null;
            }

344
            return new WrapperCodeFixProvider(lazySuppressionProvider.Value, diagnosticIds);
345 346
        }

347 348 349 350
        private async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(document);
            var solution = document.Project.Solution;
351
            var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(solution, null, document.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
352
            Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId != null));
353
            return await diagnostics.ToDiagnosticsAsync(document.Project, cancellationToken).ConfigureAwait(false);
354 355 356 357 358 359 360 361
        }

        private async Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(project);

            if (includeAllDocumentDiagnostics)
            {
362 363
                // Get all diagnostics for the entire project, including document diagnostics.
                var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
364
                return await diagnostics.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
365 366 367
            }
            else
            {
368 369 370
                // Get all no-location diagnostics for the project, doesn't include document diagnostics.
                var diagnostics = await _diagnosticService.GetProjectDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
                Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId == null));
371
                return await diagnostics.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
372 373 374
            }
        }

375 376
        private async Task<bool> ContainsAnyFix(
            Document document, DiagnosticData diagnostic, CancellationToken cancellationToken)
377
        {
378 379
            var workspaceFixers = ImmutableArray<CodeFixProvider>.Empty;
            var hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out var fixerMap) && fixerMap.Value.TryGetValue(diagnostic.Id, out workspaceFixers);
C
CyrusNajmabadi 已提交
380
            var hasAnyProjectFixer = GetProjectFixers(document.Project).TryGetValue(diagnostic.Id, out var projectFixers);
381

382 383 384 385 386 387 388
            // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
            if (hasAnySharedFixer && document.Project.Solution.Workspace.Kind == WorkspaceKind.Interactive)
            {
                workspaceFixers = workspaceFixers.WhereAsArray(IsInteractiveCodeFixProvider);
                hasAnySharedFixer = workspaceFixers.Any();
            }

389
            Lazy<ISuppressionFixProvider> lazySuppressionProvider = null;
C
CyrusNajmabadi 已提交
390
            var hasSuppressionFixer = 
391 392 393 394
                _suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) &&
                lazySuppressionProvider.Value != null;

            if (!hasAnySharedFixer && !hasAnyProjectFixer && !hasSuppressionFixer)
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
            {
                return false;
            }

            var allFixers = ImmutableArray<CodeFixProvider>.Empty;
            if (hasAnySharedFixer)
            {
                allFixers = workspaceFixers;
            }

            if (hasAnyProjectFixer)
            {
                allFixers = allFixers.AddRange(projectFixers);
            }

410
            var dx = await diagnostic.ToDiagnosticAsync(document.Project, cancellationToken).ConfigureAwait(false);
411

412
            if (hasSuppressionFixer && lazySuppressionProvider.Value.CanBeSuppressedOrUnsuppressed(dx))
413 414 415 416
            {
                return true;
            }

417 418 419 420
            var fixes = new List<CodeFix>();
            var context = new CodeFixContext(document, dx,

                // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs?
421
                (action, applicableDiagnostics) =>
422 423 424 425
                {
                    // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
                    lock (fixes)
                    {
426
                        fixes.Add(new CodeFix(document.Project, action, applicableDiagnostics));
427 428 429 430 431
                    }
                },
                verifyArguments: false,
                cancellationToken: cancellationToken);

J
Jonathon Marolf 已提交
432 433
            var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();

434 435 436
            // we do have fixer. now let's see whether it actually can fix it
            foreach (var fixer in allFixers)
            {
J
Jonathon Marolf 已提交
437
                await extensionManager.PerformActionAsync(fixer, () => fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask).ConfigureAwait(false);
438
                foreach (var fix in fixes)
439
                {
440 441 442 443
                    if (!fix.Action.PerformFinalApplicabilityCheck)
                    {
                        return true;
                    }
444

445 446 447 448 449 450 451
                    // Have to see if this fix is still applicable.  Jump to the foreground thread
                    // to make that check.
                    var applicable = await Task.Factory.StartNew(() =>
                        {
                            this.AssertIsForeground();
                            return fix.Action.IsApplicable(document.Project.Solution.Workspace);
                        },
452
                        cancellationToken, TaskCreationOptions.None, ForegroundTaskScheduler).ConfigureAwait(false);
453 454 455 456 457 458 459
                    this.AssertIsBackground();

                    if (applicable)
                    {
                        return true;
                    }
                }
460 461 462 463 464
            }

            return false;
        }

465 466 467
        private bool IsInteractiveCodeFixProvider(CodeFixProvider provider)
        {
            // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
468 469
            return provider is FullyQualify.AbstractFullyQualifyCodeFixProvider ||
                   provider is AddImport.AbstractAddImportCodeFixProvider;
470 471
        }

472
        private static readonly Func<DiagnosticId, List<CodeFixProvider>> s_createList = _ => new List<CodeFixProvider>();
473

J
Jonathon Marolf 已提交
474
        private ImmutableArray<DiagnosticId> GetFixableDiagnosticIds(CodeFixProvider fixer, IExtensionManager extensionManager)
475
        {
J
Jonathon Marolf 已提交
476 477 478 479 480
            // If we are passed a null extension manager it means we do not have access to a document so there is nothing to 
            // show the user.  In this case we will log any exceptions that occur, but the user will not see them.
            if (extensionManager != null)
            {
                return extensionManager.PerformFunction(
481
                    fixer,
482
                    () => ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f)),
S
Shyam N 已提交
483
                    defaultValue: ImmutableArray<DiagnosticId>.Empty);
J
Jonathon Marolf 已提交
484 485 486 487
            }

            try
            {
488
                return ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f));
J
Jonathon Marolf 已提交
489 490 491 492 493 494 495
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception e)
            {
J
Jonathon Marolf 已提交
496 497
                foreach (var logger in _errorLoggers)
                {
498
                    logger.Value.LogException(fixer, e);
J
Jonathon Marolf 已提交
499
                }
J
Jonathon Marolf 已提交
500 501
                return ImmutableArray<DiagnosticId>.Empty;
            }
502 503
        }

504 505 506 507 508 509 510
        private static ImmutableArray<string> GetAndTestFixableDiagnosticIds(CodeFixProvider codeFixProvider)
        {
            var ids = codeFixProvider.FixableDiagnosticIds;
            if (ids.IsDefault)
            {
                throw new InvalidOperationException(
                    string.Format(
511
                        WorkspacesResources._0_returned_an_uninitialized_ImmutableArray,
512
                        codeFixProvider.GetType().Name + "." + nameof(CodeFixProvider.FixableDiagnosticIds)));
513 514 515 516 517
            }

            return ids;
        }

518
        private ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> GetFixerPerLanguageMap(
J
Jonathon Marolf 已提交
519 520
            Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage,
            IExtensionManager extensionManager)
521 522 523 524 525 526 527 528 529 530
        {
            var fixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>>();
            foreach (var languageKindAndFixers in fixersPerLanguage)
            {
                var lazyMap = new Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>(() =>
                {
                    var mutableMap = new Dictionary<DiagnosticId, List<CodeFixProvider>>();

                    foreach (var fixer in languageKindAndFixers.Value)
                    {
J
Jonathon Marolf 已提交
531
                        foreach (var id in this.GetFixableDiagnosticIds(fixer.Value, extensionManager))
532 533 534 535 536 537
                        {
                            if (string.IsNullOrWhiteSpace(id))
                            {
                                continue;
                            }

538
                            var list = mutableMap.GetOrAdd(id, s_createList);
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
                            list.Add(fixer.Value);
                        }
                    }

                    var immutableMap = ImmutableDictionary.CreateBuilder<DiagnosticId, ImmutableArray<CodeFixProvider>>();
                    foreach (var diagnosticIdAndFixers in mutableMap)
                    {
                        immutableMap.Add(diagnosticIdAndFixers.Key, diagnosticIdAndFixers.Value.AsImmutableOrEmpty());
                    }

                    return immutableMap.ToImmutable();
                }, isThreadSafe: true);

                fixerMap = fixerMap.Add(languageKindAndFixers.Key, lazyMap);
            }

            return fixerMap;
        }

A
Andrew Casey 已提交
558
        private static ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> GetSuppressionProvidersPerLanguageMap(
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
            Dictionary<LanguageKind, List<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>> suppressionProvidersPerLanguage)
        {
            var suppressionFixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ISuppressionFixProvider>>();
            foreach (var languageKindAndFixers in suppressionProvidersPerLanguage)
            {
                var suppressionFixerLazyMap = new Lazy<ISuppressionFixProvider>(() => languageKindAndFixers.Value.SingleOrDefault().Value);
                suppressionFixerMap = suppressionFixerMap.Add(languageKindAndFixers.Key, suppressionFixerLazyMap);
            }

            return suppressionFixerMap;
        }

        private static ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> GetFixerPriorityPerLanguageMap(
            Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage)
        {
            var languageMap = ImmutableDictionary.CreateBuilder<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>>();
            foreach (var languageAndFixers in fixersPerLanguage)
            {
                var lazyMap = new Lazy<ImmutableDictionary<CodeFixProvider, int>>(() =>
                {
                    var priorityMap = ImmutableDictionary.CreateBuilder<CodeFixProvider, int>();

                    var fixers = ExtensionOrderer.Order(languageAndFixers.Value);
                    for (var i = 0; i < fixers.Count; i++)
                    {
                        priorityMap.Add(fixers[i].Value, i);
                    }

                    return priorityMap.ToImmutable();
                }, isThreadSafe: true);

                languageMap.Add(languageAndFixers.Key, lazyMap);
            }

            return languageMap.ToImmutable();
        }

        private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> GetProjectFixers(Project project)
        {
598 599
            // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
            return project.Solution.Workspace.Kind == WorkspaceKind.Interactive
H
Heejae Chang 已提交
600
                ? ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty
601
                : _projectFixersMap.GetValue(project.AnalyzerReferences, pId => ComputeProjectFixers(project));
602 603 604 605
        }

        private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> ComputeProjectFixers(Project project)
        {
J
Jonathon Marolf 已提交
606
            var extensionManager = project.Solution.Workspace.Services.GetService<IExtensionManager>();
607 608 609
            ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Builder builder = null;
            foreach (var reference in project.AnalyzerReferences)
            {
610
                var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue(reference, _createProjectCodeFixProvider);
611 612
                foreach (var fixer in projectCodeFixerProvider.GetFixers(project.Language))
                {
J
Jonathon Marolf 已提交
613
                    var fixableIds = this.GetFixableDiagnosticIds(fixer, extensionManager);
614 615 616 617 618 619 620 621
                    foreach (var id in fixableIds)
                    {
                        if (string.IsNullOrWhiteSpace(id))
                        {
                            continue;
                        }

                        builder = builder ?? ImmutableDictionary.CreateBuilder<DiagnosticId, List<CodeFixProvider>>();
622
                        var list = builder.GetOrAdd(id, s_createList);
623 624 625 626 627 628 629 630 631 632 633 634 635 636
                        list.Add(fixer);
                    }
                }
            }

            if (builder == null)
            {
                return ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty;
            }

            return builder.ToImmutable();
        }
    }
}