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

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

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

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

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

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

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

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

46
        private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableArray<IConfigurationFixProvider>>> _configurationProvidersMap;
J
Jonathon Marolf 已提交
47
        private readonly IEnumerable<Lazy<IErrorLoggerService>> _errorLoggers;
48

49
        private ImmutableDictionary<object, FixAllProviderInfo> _fixAllProviderMap;
50

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

J
Jonathon Marolf 已提交
65
            _workspaceFixersMap = GetFixerPerLanguageMap(fixersPerLanguageMap, null);
66
            _configurationProvidersMap = GetConfigurationProvidersPerLanguageMap(configurationProvidersPerLanguageMap);
67 68

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

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

S
Sam Harwell 已提交
78
        public async Task<FirstDiagnosticResult> GetMostSevereFixableDiagnosticAsync(
79
            Document document, TextSpan range, CancellationToken cancellationToken)
80 81 82
        {
            if (document == null || !document.IsOpen())
            {
C
CyrusNajmabadi 已提交
83
                return default;
84 85
            }

C
Cyrus Najmabadi 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
            using var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject();
            using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            var linkedToken = linkedTokenSource.Token;

            // This flag is used by SuggestedActionsSource to track what solution is was
            // last able to get "full results" for.
            var isFullResult = await _diagnosticService.TryAppendDiagnosticsForSpanAsync(
                document, range, diagnostics.Object, cancellationToken: linkedToken).ConfigureAwait(false);

            var errorDiagnostics = diagnostics.Object.Where(d => d.Severity == DiagnosticSeverity.Error);
            var otherDiagnostics = diagnostics.Object.Where(d => d.Severity != DiagnosticSeverity.Error);

            // Kick off a task that will determine there's an Error Diagnostic with a fixer
            var errorDiagnosticsTask = Task.Run(
                () => GetFirstDiagnosticWithFixAsync(document, errorDiagnostics, range, linkedToken),
                linkedToken);

            // Kick off a task that will determine if any non-Error Diagnostic has a fixer
            var otherDiagnosticsTask = Task.Run(
                () => GetFirstDiagnosticWithFixAsync(document, otherDiagnostics, range, linkedToken),
                linkedToken);

            // If the error diagnostics task happens to complete with a non-null result before
            // the other diagnostics task, we can cancel the other task.
            var diagnostic = await errorDiagnosticsTask.ConfigureAwait(false)
                ?? await otherDiagnosticsTask.ConfigureAwait(false);
            linkedTokenSource.Cancel();

            return new FirstDiagnosticResult(partialResult: !isFullResult,
                                   hasFix: diagnostic != null,
                                   diagnostic: diagnostic);
R
Ravi Chande 已提交
118
        }
119

R
Ravi Chande 已提交
120 121 122 123 124 125 126 127 128 129 130
        private async Task<DiagnosticData> GetFirstDiagnosticWithFixAsync(
            Document document,
            IEnumerable<DiagnosticData> severityGroup,
            TextSpan range,
            CancellationToken cancellationToken)
        {
            foreach (var diagnostic in severityGroup)
            {
                if (!range.IntersectsWith(diagnostic.TextSpan))
                {
                    continue;
131 132
                }

R
Ravi Chande 已提交
133 134 135 136
                if (await ContainsAnyFixAsync(document, diagnostic, cancellationToken).ConfigureAwait(false))
                {
                    return diagnostic;
                }
137
            }
R
Ravi Chande 已提交
138 139

            return null;
140 141
        }

142
        public async Task<ImmutableArray<CodeFixCollection>> GetFixesAsync(Document document, TextSpan range, bool includeConfigurationFixes, CancellationToken cancellationToken)
143 144
        {
            // REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back
C
Carol Hu 已提交
145
            // current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information
146 147 148 149 150
            // (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;
151
            foreach (var diagnostic in await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, diagnosticIdOpt: null, includeConfigurationFixes, cancellationToken).ConfigureAwait(false))
152
            {
153
                if (diagnostic.IsSuppressed)
154 155 156 157
                {
                    continue;
                }

158 159
                cancellationToken.ThrowIfCancellationRequested();

C
Cyrus Najmabadi 已提交
160
                aggregatedDiagnostics ??= new Dictionary<TextSpan, List<DiagnosticData>>();
161 162 163
                aggregatedDiagnostics.GetOrAdd(diagnostic.TextSpan, _ => new List<DiagnosticData>()).Add(diagnostic);
            }

164
            if (aggregatedDiagnostics == null)
165
            {
C
CyrusNajmabadi 已提交
166
                return ImmutableArray<CodeFixCollection>.Empty;
167 168
            }

169
            using var resultDisposer = ArrayBuilder<CodeFixCollection>.GetInstance(out var result);
170 171
            foreach (var spanAndDiagnostic in aggregatedDiagnostics)
            {
C
CyrusNajmabadi 已提交
172
                await AppendFixesAsync(
D
dotnet-bot 已提交
173
                    document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, fixAllForInSpan: false,
C
CyrusNajmabadi 已提交
174
                    result, cancellationToken).ConfigureAwait(false);
175 176
            }

C
CyrusNajmabadi 已提交
177
            if (result.Count > 0)
178 179
            {
                // sort the result to the order defined by the fixers
180
                var priorityMap = _fixerPriorityMap[document.Project.Language].Value;
181 182
                result.Sort((d1, d2) =>
                {
C
Use var  
Cyrus Najmabadi 已提交
183
                    if (priorityMap.TryGetValue((CodeFixProvider)d1.Provider, out var priority1))
184
                    {
C
Use var  
Cyrus Najmabadi 已提交
185
                        if (priorityMap.TryGetValue((CodeFixProvider)d2.Provider, out var priority2))
186 187 188 189 190 191 192 193 194 195 196 197 198
                        {
                            return priority1 - priority2;
                        }
                        else
                        {
                            return -1;
                        }
                    }
                    else
                    {
                        return 1;
                    }
                });
199 200
            }

201
            // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
202
            if (document.Project.Solution.Workspace.Kind != WorkspaceKind.Interactive && includeConfigurationFixes)
203 204 205
            {
                foreach (var spanAndDiagnostic in aggregatedDiagnostics)
                {
206
                    await AppendConfigurationsAsync(
R
Ravi Chande 已提交
207
                        document, spanAndDiagnostic.Key, spanAndDiagnostic.Value,
C
CyrusNajmabadi 已提交
208
                        result, cancellationToken).ConfigureAwait(false);
209 210 211
                }
            }

212
            return result.ToImmutable();
213 214
        }

S
Sam Harwell 已提交
215
        public async Task<CodeFixCollection> GetDocumentFixAllForIdInSpanAsync(Document document, TextSpan range, string diagnosticId, CancellationToken cancellationToken)
C
Carol Hu 已提交
216
        {
J
JieCarolHu 已提交
217
            var diagnostics = (await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, diagnosticId, includeSuppressedDiagnostics: false, cancellationToken: cancellationToken).ConfigureAwait(false)).ToList();
J
JieCarolHu 已提交
218 219 220 221 222
            if (diagnostics.Count == 0)
            {
                return null;
            }

223
            using var resultDisposer = ArrayBuilder<CodeFixCollection>.GetInstance(out var result);
D
dotnet-bot 已提交
224
            await AppendFixesAsync(document, range, diagnostics, fixAllForInSpan: true, result, cancellationToken).ConfigureAwait(false);
C
Carol Hu 已提交
225 226 227

            // TODO: Just get the first fix for now until we have a way to config user's preferred fix
            // https://github.com/dotnet/roslyn/issues/27066
228
            return result.ToImmutable().FirstOrDefault();
C
Carol Hu 已提交
229 230
        }

S
Sam Harwell 已提交
231
        public async Task<Document> ApplyCodeFixesForSpecificDiagnosticIdAsync(Document document, string diagnosticId, IProgressTracker progressTracker, CancellationToken cancellationToken)
J
JieCarolHu 已提交
232 233 234 235
        {
            var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            var textSpan = new TextSpan(0, tree.Length);

S
Sam Harwell 已提交
236
            var fixCollection = await GetDocumentFixAllForIdInSpanAsync(
J
JieCarolHu 已提交
237 238 239
                document, textSpan, diagnosticId, cancellationToken).ConfigureAwait(false);
            if (fixCollection == null)
            {
J
JieCarolHu 已提交
240
                return document;
J
JieCarolHu 已提交
241 242 243 244 245
            }

            var fixAllService = document.Project.Solution.Workspace.Services.GetService<IFixAllGetFixesService>();

            var solution = await fixAllService.GetFixAllChangedSolutionAsync(
J
JieCarolHu 已提交
246
                fixCollection.FixAllState.CreateFixAllContext(progressTracker, cancellationToken)).ConfigureAwait(false);
J
JieCarolHu 已提交
247 248 249 250

            return solution.GetDocument(document.Id);
        }

C
CyrusNajmabadi 已提交
251
        private async Task AppendFixesAsync(
252 253
            Document document,
            TextSpan span,
254
            IEnumerable<DiagnosticData> diagnostics,
J
JieCarolHu 已提交
255
            bool fixAllForInSpan,
C
CyrusNajmabadi 已提交
256
            ArrayBuilder<CodeFixCollection> result,
257 258
            CancellationToken cancellationToken)
        {
C
Use var  
Cyrus Najmabadi 已提交
259
            var hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out var fixerMap);
260 261 262 263 264 265

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

            if (!hasAnySharedFixer && !hasAnyProjectFixer)
            {
C
CyrusNajmabadi 已提交
266
                return;
267 268 269 270
            }

            var allFixers = new List<CodeFixProvider>();

271
            // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
C
Use var  
Cyrus Najmabadi 已提交
272
            var isInteractive = document.Project.Solution.Workspace.Kind == WorkspaceKind.Interactive;
273

274
            foreach (var diagnosticId in diagnostics.Select(d => d.Id).Distinct())
275 276 277
            {
                cancellationToken.ThrowIfCancellationRequested();

C
CyrusNajmabadi 已提交
278
                if (hasAnySharedFixer && fixerMap.Value.TryGetValue(diagnosticId, out var workspaceFixers))
279
                {
280 281 282 283 284 285 286 287
                    if (isInteractive)
                    {
                        allFixers.AddRange(workspaceFixers.Where(IsInteractiveCodeFixProvider));
                    }
                    else
                    {
                        allFixers.AddRange(workspaceFixers);
                    }
288 289
                }

C
CyrusNajmabadi 已提交
290
                if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out var projectFixers))
291
                {
292
                    Debug.Assert(!isInteractive);
293 294 295 296
                    allFixers.AddRange(projectFixers);
                }
            }

J
Jonathon Marolf 已提交
297
            var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
298 299 300 301 302

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

303
                await AppendFixesOrConfigurationsAsync(
J
JieCarolHu 已提交
304
                    document, span, diagnostics, fixAllForInSpan, result, fixer,
C
CyrusNajmabadi 已提交
305
                    hasFix: d => this.GetFixableDiagnosticIds(fixer, extensionManager).Contains(d.Id),
J
JieCarolHu 已提交
306 307 308 309 310 311 312 313 314 315 316 317 318
                    getFixes: dxs =>
                    {
                        if (fixAllForInSpan)
                        {
                            var primaryDiagnostic = dxs.First();
                            return GetCodeFixesAsync(document, primaryDiagnostic.Location.SourceSpan, fixer, ImmutableArray.Create(primaryDiagnostic), cancellationToken);

                        }
                        else
                        {
                            return GetCodeFixesAsync(document, span, fixer, dxs, cancellationToken);
                        }
                    },
C
CyrusNajmabadi 已提交
319
                    cancellationToken: cancellationToken).ConfigureAwait(false);
J
JieCarolHu 已提交
320 321 322

                // Just need the first result if we are doing fix all in span
                if (fixAllForInSpan && result.Any()) return;
323 324 325
            }
        }

C
CyrusNajmabadi 已提交
326 327 328 329
        private async Task<ImmutableArray<CodeFix>> GetCodeFixesAsync(
            Document document, TextSpan span, CodeFixProvider fixer,
            ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken)
        {
330
            using var fixesDisposer = ArrayBuilder<CodeFix>.GetInstance(out var fixes);
C
CyrusNajmabadi 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343
            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);

344
            var task = fixer.RegisterCodeFixesAsync(context) ?? Task.CompletedTask;
C
CyrusNajmabadi 已提交
345
            await task.ConfigureAwait(false);
346
            return fixes.ToImmutable();
C
CyrusNajmabadi 已提交
347 348
        }

349
        private async Task AppendConfigurationsAsync(
R
Ravi Chande 已提交
350
            Document document, TextSpan span, IEnumerable<DiagnosticData> diagnostics,
C
CyrusNajmabadi 已提交
351
            ArrayBuilder<CodeFixCollection> result, CancellationToken cancellationToken)
352
        {
353
            if (!_configurationProvidersMap.TryGetValue(document.Project.Language, out var lazyConfigurationProviders) || lazyConfigurationProviders.Value == null)
354
            {
C
CyrusNajmabadi 已提交
355
                return;
356 357
            }

358
            foreach (var provider in lazyConfigurationProviders.Value)
359
            {
360
                await AppendFixesOrConfigurationsAsync(
361 362 363 364 365 366
                    document, span, diagnostics, fixAllForInSpan: false, result, provider,
                    hasFix: d => provider.IsFixableDiagnostic(d),
                    getFixes: dxs => provider.GetFixesAsync(
                        document, span, dxs, cancellationToken),
                    cancellationToken: cancellationToken).ConfigureAwait(false);
            }
367 368
        }

369
        private async Task AppendFixesOrConfigurationsAsync<TCodeFixProvider>(
370 371
            Document document,
            TextSpan span,
372
            IEnumerable<DiagnosticData> diagnosticsWithSameSpan,
J
JieCarolHu 已提交
373
            bool fixAllForInSpan,
C
CyrusNajmabadi 已提交
374
            ArrayBuilder<CodeFixCollection> result,
375
            TCodeFixProvider fixer,
376
            Func<Diagnostic, bool> hasFix,
377
            Func<ImmutableArray<Diagnostic>, Task<ImmutableArray<CodeFix>>> getFixes,
378 379
            CancellationToken cancellationToken)
        {
R
Ravi Chande 已提交
380
            var allDiagnostics =
C
CyrusNajmabadi 已提交
381 382 383
                await diagnosticsWithSameSpan.OrderByDescending(d => d.Severity)
                                             .ToDiagnosticsAsync(document.Project, cancellationToken).ConfigureAwait(false);
            var diagnostics = allDiagnostics.WhereAsArray(hasFix);
384 385 386
            if (diagnostics.Length <= 0)
            {
                // this can happen for suppression case where all diagnostics can't be suppressed
C
CyrusNajmabadi 已提交
387
                return;
388
            }
S
Shyam N 已提交
389

J
Jonathon Marolf 已提交
390
            var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
391
            var fixes = await extensionManager.PerformFunctionAsync(fixer,
J
JieCarolHu 已提交
392
                 () => getFixes(diagnostics),
393
                defaultValue: ImmutableArray<CodeFix>.Empty).ConfigureAwait(false);
S
Shyam N 已提交
394

C
CyrusNajmabadi 已提交
395
            if (fixes.IsDefaultOrEmpty)
396
            {
C
CyrusNajmabadi 已提交
397 398
                return;
            }
399

C
CyrusNajmabadi 已提交
400 401
            // 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);
402

C
CyrusNajmabadi 已提交
403
            FixAllState fixAllState = null;
C
CyrusNajmabadi 已提交
404
            var supportedScopes = ImmutableArray<FixAllScope>.Empty;
C
CyrusNajmabadi 已提交
405 406
            if (fixAllProviderInfo != null)
            {
407
                var codeFixProvider = (fixer as CodeFixProvider) ?? new WrapperCodeFixProvider((IConfigurationFixProvider)fixer, diagnostics.Select(d => d.Id));
J
JieCarolHu 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425

                var diagnosticIds = diagnostics.Where(fixAllProviderInfo.CanBeFixed)
                                          .Select(d => d.Id)
                                          .ToImmutableHashSet();

                var diagnosticProvider = fixAllForInSpan
                    ? new FixAllPredefinedDiagnosticProvider(allDiagnostics)
                    : (FixAllContext.DiagnosticProvider)new FixAllDiagnosticProvider(this, diagnosticIds);

                fixAllState = new FixAllState(
                    fixAllProvider: fixAllProviderInfo.FixAllProvider,
                    document: document,
                    codeFixProvider: codeFixProvider,
                    scope: FixAllScope.Document,
                    codeActionEquivalenceKey: null,
                    diagnosticIds: diagnosticIds,
                    fixAllDiagnosticProvider: diagnosticProvider);

C
CyrusNajmabadi 已提交
426
                supportedScopes = fixAllProviderInfo.SupportedScopes;
427
            }
C
CyrusNajmabadi 已提交
428 429 430 431 432

            var codeFix = new CodeFixCollection(
                fixer, span, fixes, fixAllState,
                supportedScopes, diagnostics.First());
            result.Add(codeFix);
433
        }
D
dotnet-bot 已提交
434

435
        /// <summary> Looks explicitly for an <see cref="AbstractSuppressionCodeFixProvider"/>.</summary>
436
        public CodeFixProvider GetSuppressionFixer(string language, IEnumerable<string> diagnosticIds)
437
        {
438 439
            if (!_configurationProvidersMap.TryGetValue(language, out var lazyConfigurationProviders) ||
                lazyConfigurationProviders.Value.IsDefault)
440 441 442 443
            {
                return null;
            }

444
            // Explicitly looks for an AbstractSuppressionCodeFixProvider
445
            var fixer = lazyConfigurationProviders.Value.OfType<AbstractSuppressionCodeFixProvider>().FirstOrDefault();
446
            if (fixer == null)
447 448 449 450
            {
                return null;
            }

451
            return new WrapperCodeFixProvider(fixer, diagnosticIds);
452 453
        }

454 455 456 457
        private async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(document);
            var solution = document.Project.Solution;
458
            var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(solution, null, document.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
459
            Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId != null));
460
            return await diagnostics.ToDiagnosticsAsync(document.Project, cancellationToken).ConfigureAwait(false);
461 462 463 464 465 466 467 468
        }

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

            if (includeAllDocumentDiagnostics)
            {
469 470
                // 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);
471
                return await diagnostics.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
472 473 474
            }
            else
            {
475 476 477
                // 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));
478
                return await diagnostics.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
479 480 481
            }
        }

R
Ravi Chande 已提交
482
        private async Task<bool> ContainsAnyFixAsync(
483
            Document document, DiagnosticData diagnostic, CancellationToken cancellationToken)
484
        {
485 486
            var workspaceFixers = ImmutableArray<CodeFixProvider>.Empty;
            var hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out var fixerMap) && fixerMap.Value.TryGetValue(diagnostic.Id, out workspaceFixers);
C
CyrusNajmabadi 已提交
487
            var hasAnyProjectFixer = GetProjectFixers(document.Project).TryGetValue(diagnostic.Id, out var projectFixers);
488

489 490 491 492 493 494 495
            // 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();
            }

496 497 498
            var hasConfigurationFixer =
                _configurationProvidersMap.TryGetValue(document.Project.Language, out var lazyConfigurationProviders) &&
                !lazyConfigurationProviders.Value.IsDefaultOrEmpty;
499

500
            if (!hasAnySharedFixer && !hasAnyProjectFixer && !hasConfigurationFixer)
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
            {
                return false;
            }

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

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

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

518
            if (hasConfigurationFixer)
519
            {
520
                foreach (var lazyConfigurationProvider in lazyConfigurationProviders.Value)
521
                {
522
                    if (lazyConfigurationProvider.IsFixableDiagnostic(dx))
523 524 525 526
                    {
                        return true;
                    }
                }
527 528
            }

529 530 531 532
            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?
533
                (action, applicableDiagnostics) =>
534 535 536 537
                {
                    // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
                    lock (fixes)
                    {
538
                        fixes.Add(new CodeFix(document.Project, action, applicableDiagnostics));
539 540 541 542 543
                    }
                },
                verifyArguments: false,
                cancellationToken: cancellationToken);

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

546 547 548
            // we do have fixer. now let's see whether it actually can fix it
            foreach (var fixer in allFixers)
            {
549
                await extensionManager.PerformActionAsync(fixer, () => fixer.RegisterCodeFixesAsync(context) ?? Task.CompletedTask).ConfigureAwait(false);
550
                foreach (var fix in fixes)
551
                {
552 553 554 555
                    if (!fix.Action.PerformFinalApplicabilityCheck)
                    {
                        return true;
                    }
556

557 558
                    // Have to see if this fix is still applicable.  Jump to the foreground thread
                    // to make that check.
559
                    await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true, cancellationToken);
560
                    cancellationToken.ThrowIfCancellationRequested();
561 562 563 564

                    var applicable = fix.Action.IsApplicable(document.Project.Solution.Workspace);

                    await TaskScheduler.Default;
565 566 567 568 569 570

                    if (applicable)
                    {
                        return true;
                    }
                }
571 572 573 574 575
            }

            return false;
        }

576 577 578
        private bool IsInteractiveCodeFixProvider(CodeFixProvider provider)
        {
            // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
579 580
            return provider is FullyQualify.AbstractFullyQualifyCodeFixProvider ||
                   provider is AddImport.AbstractAddImportCodeFixProvider;
581 582
        }

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

J
Jonathon Marolf 已提交
585
        private ImmutableArray<DiagnosticId> GetFixableDiagnosticIds(CodeFixProvider fixer, IExtensionManager extensionManager)
586
        {
C
Carol Hu 已提交
587
            // If we are passed a null extension manager it means we do not have access to a document so there is nothing to
J
Jonathon Marolf 已提交
588 589 590 591
            // 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(
592
                    fixer,
593
                    () => ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f)),
S
Shyam N 已提交
594
                    defaultValue: ImmutableArray<DiagnosticId>.Empty);
J
Jonathon Marolf 已提交
595 596 597 598
            }

            try
            {
599
                return ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f));
J
Jonathon Marolf 已提交
600 601 602 603 604 605 606
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception e)
            {
J
Jonathon Marolf 已提交
607 608
                foreach (var logger in _errorLoggers)
                {
609
                    logger.Value.LogException(fixer, e);
J
Jonathon Marolf 已提交
610
                }
J
Jonathon Marolf 已提交
611 612
                return ImmutableArray<DiagnosticId>.Empty;
            }
613 614
        }

615 616 617 618 619 620 621
        private static ImmutableArray<string> GetAndTestFixableDiagnosticIds(CodeFixProvider codeFixProvider)
        {
            var ids = codeFixProvider.FixableDiagnosticIds;
            if (ids.IsDefault)
            {
                throw new InvalidOperationException(
                    string.Format(
622
                        WorkspacesResources._0_returned_an_uninitialized_ImmutableArray,
623
                        codeFixProvider.GetType().Name + "." + nameof(CodeFixProvider.FixableDiagnosticIds)));
624 625 626 627 628
            }

            return ids;
        }

629
        private ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> GetFixerPerLanguageMap(
J
Jonathon Marolf 已提交
630 631
            Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage,
            IExtensionManager extensionManager)
632 633 634 635 636 637 638 639 640 641
        {
            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 已提交
642
                        foreach (var id in this.GetFixableDiagnosticIds(fixer.Value, extensionManager))
643 644 645 646 647 648
                        {
                            if (string.IsNullOrWhiteSpace(id))
                            {
                                continue;
                            }

649
                            var list = mutableMap.GetOrAdd(id, s_createList);
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
                            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;
        }

669 670
        private static ImmutableDictionary<LanguageKind, Lazy<ImmutableArray<IConfigurationFixProvider>>> GetConfigurationProvidersPerLanguageMap(
            Dictionary<LanguageKind, List<Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>>> configurationProvidersPerLanguage)
671
        {
672 673
            var configurationFixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ImmutableArray<IConfigurationFixProvider>>>();
            foreach (var languageKindAndFixers in configurationProvidersPerLanguage)
674
            {
675 676
                var lazyConfigurationFixers = new Lazy<ImmutableArray<IConfigurationFixProvider>>(() => GetConfigurationFixProviders(languageKindAndFixers.Value));
                configurationFixerMap = configurationFixerMap.Add(languageKindAndFixers.Key, lazyConfigurationFixers);
677 678
            }

679 680 681 682
            return configurationFixerMap;

            static ImmutableArray<IConfigurationFixProvider> GetConfigurationFixProviders(List<Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>> languageKindAndFixers)
            {
683
                using var builderDisposer = ArrayBuilder<IConfigurationFixProvider>.GetInstance(out var builder);
684 685
                var orderedLanguageKindAndFixers = ExtensionOrderer.Order(languageKindAndFixers);
                foreach (var languageKindAndFixersValue in orderedLanguageKindAndFixers)
686 687 688 689
                {
                    builder.Add(languageKindAndFixersValue.Value);
                }

690
                return builder.ToImmutable();
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
            }
        }

        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)
        {
721 722
            // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
            return project.Solution.Workspace.Kind == WorkspaceKind.Interactive
H
Heejae Chang 已提交
723
                ? ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty
724
                : _projectFixersMap.GetValue(project.AnalyzerReferences, pId => ComputeProjectFixers(project));
725 726 727 728
        }

        private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> ComputeProjectFixers(Project project)
        {
J
Jonathon Marolf 已提交
729
            var extensionManager = project.Solution.Workspace.Services.GetService<IExtensionManager>();
730 731 732
            ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Builder builder = null;
            foreach (var reference in project.AnalyzerReferences)
            {
733
                var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue(reference, _createProjectCodeFixProvider);
734 735
                foreach (var fixer in projectCodeFixerProvider.GetFixers(project.Language))
                {
J
Jonathon Marolf 已提交
736
                    var fixableIds = this.GetFixableDiagnosticIds(fixer, extensionManager);
737 738 739 740 741 742 743
                    foreach (var id in fixableIds)
                    {
                        if (string.IsNullOrWhiteSpace(id))
                        {
                            continue;
                        }

C
Cyrus Najmabadi 已提交
744
                        builder ??= ImmutableDictionary.CreateBuilder<DiagnosticId, List<CodeFixProvider>>();
745
                        var list = builder.GetOrAdd(id, s_createList);
746 747 748 749 750 751 752 753 754 755 756 757 758 759
                        list.Add(fixer);
                    }
                }
            }

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

            return builder.ToImmutable();
        }
    }
}