CodeFixService.cs 37.1 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 21 22 23 24
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
        }

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

            using (var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject())
            {
R
Ravi Chande 已提交
86
                using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
87
                {
R
Ravi Chande 已提交
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 118 119
                    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);
                }
            }
        }
120

R
Ravi Chande 已提交
121 122 123 124 125 126 127 128 129 130 131
        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;
132 133
                }

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

            return null;
141 142
        }

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

159 160 161 162 163 164
                cancellationToken.ThrowIfCancellationRequested();

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

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

C
CyrusNajmabadi 已提交
170
            var result = ArrayBuilder<CodeFixCollection>.GetInstance();
171 172
            foreach (var spanAndDiagnostic in aggregatedDiagnostics)
            {
C
CyrusNajmabadi 已提交
173
                await AppendFixesAsync(
R
Ravi Chande 已提交
174
                    document, spanAndDiagnostic.Key, spanAndDiagnostic.Value,
C
CyrusNajmabadi 已提交
175
                    result, cancellationToken).ConfigureAwait(false);
176 177
            }

C
CyrusNajmabadi 已提交
178
            if (result.Count > 0)
179 180
            {
                // sort the result to the order defined by the fixers
181
                var priorityMap = _fixerPriorityMap[document.Project.Language].Value;
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
                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;
                    }
                });
200 201
            }

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

C
CyrusNajmabadi 已提交
213
            return result.ToImmutableAndFree();
214 215
        }

J
JieCarolHu 已提交
216
        public async Task<CodeFixCollection> GetFixesInProcAsync(Document document, TextSpan range, string diagnosticId, CancellationToken cancellationToken)
C
Carol Hu 已提交
217
        {
J
JieCarolHu 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
            var diagnostics = (await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, includeSuppressedDiagnostics:false,  diagnosticId, cancellationToken: cancellationToken).ConfigureAwait(false)).ToList();
            if (diagnostics.Count == 0)
            {
                return null;
            }

            bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out var fixerMap);

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

            if (!hasAnySharedFixer && !hasAnyProjectFixer)
            {
                return null;
            }

            var allFixers = new List<CodeFixProvider>();

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

            cancellationToken.ThrowIfCancellationRequested();

            if (hasAnySharedFixer && fixerMap.Value.TryGetValue(diagnosticId, out var workspaceFixers))
            {
                if (isInteractive)
                {
                    allFixers.AddRange(workspaceFixers.Where(IsInteractiveCodeFixProvider));
                }
                else
                {
                    allFixers.AddRange(workspaceFixers);
                }
            }

            if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out var projectFixers))
            {
                Debug.Assert(!isInteractive);
                allFixers.AddRange(projectFixers);
            }

            var primaryDiagnostic = await diagnostics[0].ToDiagnosticAsync(document.Project, cancellationToken).ConfigureAwait(false);
            var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();

            var result = ArrayBuilder<CodeFixCollection>.GetInstance();

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

                var fixes = await extensionManager.PerformFunctionAsync(fixer,
                    () => GetCodeFixesAsync(document, primaryDiagnostic.Location.SourceSpan, fixer, ImmutableArray.Create(primaryDiagnostic), cancellationToken),
                    defaultValue: ImmutableArray<CodeFix>.Empty).ConfigureAwait(false);

                if (fixes.IsDefaultOrEmpty)
                {
                    continue;
                }

                // 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);
                if (fixAllProviderInfo == null)
                {
                    // for now, we don't care about fixer that doesn't have fix all implementation
                    return null;
                }

                var diagnosticProvider = new FixAllPredefinedDiagnosticProvider(await diagnostics.ToDiagnosticsAsync(document.Project, cancellationToken).ConfigureAwait(false));
                var fixAllState = new FixAllState(
                    fixAllProvider: fixAllProviderInfo.FixAllProvider,
                    document: document,
                    codeFixProvider: fixer,
                    scope: FixAllScope.Document,
                    codeActionEquivalenceKey: fixes.First().Action.EquivalenceKey,
                    diagnosticIds: SpecializedCollections.SingletonEnumerable(diagnosticId),
                    fixAllDiagnosticProvider: diagnosticProvider);

                var codeFix = new CodeFixCollection(
                    fixer, primaryDiagnostic.Location.SourceSpan, fixes, fixAllState,
                    fixAllProviderInfo.SupportedScopes, primaryDiagnostic);

                result.Add(codeFix);
                break;
            }
C
Carol Hu 已提交
302 303 304

            // 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
J
JieCarolHu 已提交
305
            return result.ToImmutableAndFree().FirstOrDefault();
C
Carol Hu 已提交
306 307
        }

C
CyrusNajmabadi 已提交
308
        private async Task AppendFixesAsync(
309 310
            Document document,
            TextSpan span,
311
            IEnumerable<DiagnosticData> diagnostics,
C
CyrusNajmabadi 已提交
312
            ArrayBuilder<CodeFixCollection> result,
313 314
            CancellationToken cancellationToken)
        {
C
CyrusNajmabadi 已提交
315
            bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out var fixerMap);
316 317 318 319 320 321

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

            if (!hasAnySharedFixer && !hasAnyProjectFixer)
            {
C
CyrusNajmabadi 已提交
322
                return;
323 324 325 326
            }

            var allFixers = new List<CodeFixProvider>();

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

330
            foreach (var diagnosticId in diagnostics.Select(d => d.Id).Distinct())
331 332 333
            {
                cancellationToken.ThrowIfCancellationRequested();

C
CyrusNajmabadi 已提交
334
                if (hasAnySharedFixer && fixerMap.Value.TryGetValue(diagnosticId, out var workspaceFixers))
335
                {
336 337 338 339 340 341 342 343
                    if (isInteractive)
                    {
                        allFixers.AddRange(workspaceFixers.Where(IsInteractiveCodeFixProvider));
                    }
                    else
                    {
                        allFixers.AddRange(workspaceFixers);
                    }
344 345
                }

C
CyrusNajmabadi 已提交
346
                if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out var projectFixers))
347
                {
348
                    Debug.Assert(!isInteractive);
349 350 351 352
                    allFixers.AddRange(projectFixers);
                }
            }

J
Jonathon Marolf 已提交
353
            var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
354 355 356 357 358

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

C
CyrusNajmabadi 已提交
359 360 361 362 363
                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);
364 365 366
            }
        }

C
CyrusNajmabadi 已提交
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
        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);

385
            var task = fixer.RegisterCodeFixesAsync(context) ?? Task.CompletedTask;
C
CyrusNajmabadi 已提交
386 387 388 389
            await task.ConfigureAwait(false);
            return fixes.ToImmutableAndFree();
        }

C
CyrusNajmabadi 已提交
390
        private async Task AppendSuppressionsAsync(
R
Ravi Chande 已提交
391
            Document document, TextSpan span, IEnumerable<DiagnosticData> diagnostics,
C
CyrusNajmabadi 已提交
392
            ArrayBuilder<CodeFixCollection> result, CancellationToken cancellationToken)
393
        {
C
CyrusNajmabadi 已提交
394
            if (!_suppressionProvidersMap.TryGetValue(document.Project.Language, out var lazySuppressionProvider) || lazySuppressionProvider.Value == null)
395
            {
C
CyrusNajmabadi 已提交
396
                return;
397 398
            }

C
CyrusNajmabadi 已提交
399
            await AppendFixesOrSuppressionsAsync(
R
Ravi Chande 已提交
400
                document, span, diagnostics, result, lazySuppressionProvider.Value,
C
CyrusNajmabadi 已提交
401 402
                hasFix: d => lazySuppressionProvider.Value.CanBeSuppressedOrUnsuppressed(d),
                getFixes: dxs => lazySuppressionProvider.Value.GetSuppressionsAsync(
R
Ravi Chande 已提交
403
                    document, span, dxs, cancellationToken),
C
CyrusNajmabadi 已提交
404
                cancellationToken: cancellationToken).ConfigureAwait(false);
405 406
        }

C
CyrusNajmabadi 已提交
407
        private async Task AppendFixesOrSuppressionsAsync(
408 409
            Document document,
            TextSpan span,
410
            IEnumerable<DiagnosticData> diagnosticsWithSameSpan,
C
CyrusNajmabadi 已提交
411
            ArrayBuilder<CodeFixCollection> result,
412 413
            object fixer,
            Func<Diagnostic, bool> hasFix,
414
            Func<ImmutableArray<Diagnostic>, Task<ImmutableArray<CodeFix>>> getFixes,
415 416
            CancellationToken cancellationToken)
        {
R
Ravi Chande 已提交
417
            var allDiagnostics =
C
CyrusNajmabadi 已提交
418 419 420
                await diagnosticsWithSameSpan.OrderByDescending(d => d.Severity)
                                             .ToDiagnosticsAsync(document.Project, cancellationToken).ConfigureAwait(false);
            var diagnostics = allDiagnostics.WhereAsArray(hasFix);
421 422 423
            if (diagnostics.Length <= 0)
            {
                // this can happen for suppression case where all diagnostics can't be suppressed
C
CyrusNajmabadi 已提交
424
                return;
425
            }
S
Shyam N 已提交
426

J
Jonathon Marolf 已提交
427
            var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>();
428 429 430
            var fixes = await extensionManager.PerformFunctionAsync(fixer,
                () => getFixes(diagnostics),
                defaultValue: ImmutableArray<CodeFix>.Empty).ConfigureAwait(false);
S
Shyam N 已提交
431

C
CyrusNajmabadi 已提交
432
            if (fixes.IsDefaultOrEmpty)
433
            {
C
CyrusNajmabadi 已提交
434 435
                return;
            }
436

C
CyrusNajmabadi 已提交
437 438
            // 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);
439

C
CyrusNajmabadi 已提交
440
            FixAllState fixAllState = null;
C
CyrusNajmabadi 已提交
441
            var supportedScopes = ImmutableArray<FixAllScope>.Empty;
C
CyrusNajmabadi 已提交
442 443 444
            if (fixAllProviderInfo != null)
            {
                var codeFixProvider = (fixer as CodeFixProvider) ?? new WrapperCodeFixProvider((ISuppressionFixProvider)fixer, diagnostics.Select(d => d.Id));
445
                fixAllState = CreateFixAllState(
C
CyrusNajmabadi 已提交
446
                    fixAllProviderInfo.FixAllProvider,
C
Carol Hu 已提交
447
                    document, fixAllProviderInfo, codeFixProvider, diagnostics);
C
CyrusNajmabadi 已提交
448
                supportedScopes = fixAllProviderInfo.SupportedScopes;
449
            }
C
CyrusNajmabadi 已提交
450 451 452 453 454

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

457 458 459 460 461
        internal FixAllState CreateFixAllState(
            FixAllProvider fixAllProvider,
            Document document,
            FixAllProviderInfo fixAllProviderInfo,
            CodeFixProvider originalFixProvider,
C
Carol Hu 已提交
462
            IEnumerable<Diagnostic> originalFixDiagnostics)
463 464 465 466
        {
            var diagnosticIds = originalFixDiagnostics.Where(fixAllProviderInfo.CanBeFixed)
                                                      .Select(d => d.Id)
                                                      .ToImmutableHashSet();
C
Carol Hu 已提交
467

468 469 470 471 472 473 474 475 476 477 478
            var diagnosticProvider = new FixAllDiagnosticProvider(this, diagnosticIds);
            return new FixAllState(
                fixAllProvider: fixAllProvider,
                document: document,
                codeFixProvider: originalFixProvider,
                scope: FixAllScope.Document,
                codeActionEquivalenceKey: null,
                diagnosticIds: diagnosticIds,
                fixAllDiagnosticProvider: diagnosticProvider);
        }

479
        public CodeFixProvider GetSuppressionFixer(string language, IEnumerable<string> diagnosticIds)
480
        {
C
CyrusNajmabadi 已提交
481
            if (!_suppressionProvidersMap.TryGetValue(language, out var lazySuppressionProvider) || lazySuppressionProvider.Value == null)
482 483 484 485
            {
                return null;
            }

486
            return new WrapperCodeFixProvider(lazySuppressionProvider.Value, diagnosticIds);
487 488
        }

489 490 491 492
        private async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(document);
            var solution = document.Project.Solution;
493
            var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(solution, null, document.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false);
494
            Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId != null));
495
            return await diagnostics.ToDiagnosticsAsync(document.Project, cancellationToken).ConfigureAwait(false);
496 497 498 499 500 501 502 503
        }

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

            if (includeAllDocumentDiagnostics)
            {
504 505
                // 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);
506
                return await diagnostics.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
507 508 509
            }
            else
            {
510 511 512
                // 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));
513
                return await diagnostics.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
514 515 516
            }
        }

R
Ravi Chande 已提交
517
        private async Task<bool> ContainsAnyFixAsync(
518
            Document document, DiagnosticData diagnostic, CancellationToken cancellationToken)
519
        {
520 521
            var workspaceFixers = ImmutableArray<CodeFixProvider>.Empty;
            var hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out var fixerMap) && fixerMap.Value.TryGetValue(diagnostic.Id, out workspaceFixers);
C
CyrusNajmabadi 已提交
522
            var hasAnyProjectFixer = GetProjectFixers(document.Project).TryGetValue(diagnostic.Id, out var projectFixers);
523

524 525 526 527 528 529 530
            // 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();
            }

R
Ravi Chande 已提交
531
            var hasSuppressionFixer =
C
CyrusNajmabadi 已提交
532
                _suppressionProvidersMap.TryGetValue(document.Project.Language, out var lazySuppressionProvider) &&
533 534 535
                lazySuppressionProvider.Value != null;

            if (!hasAnySharedFixer && !hasAnyProjectFixer && !hasSuppressionFixer)
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
            {
                return false;
            }

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

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

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

553
            if (hasSuppressionFixer && lazySuppressionProvider.Value.CanBeSuppressedOrUnsuppressed(dx))
554 555 556 557
            {
                return true;
            }

558 559 560 561
            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?
562
                (action, applicableDiagnostics) =>
563 564 565 566
                {
                    // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
                    lock (fixes)
                    {
567
                        fixes.Add(new CodeFix(document.Project, action, applicableDiagnostics));
568 569 570 571 572
                    }
                },
                verifyArguments: false,
                cancellationToken: cancellationToken);

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

575 576 577
            // we do have fixer. now let's see whether it actually can fix it
            foreach (var fixer in allFixers)
            {
578
                await extensionManager.PerformActionAsync(fixer, () => fixer.RegisterCodeFixesAsync(context) ?? Task.CompletedTask).ConfigureAwait(false);
579
                foreach (var fix in fixes)
580
                {
581 582 583 584
                    if (!fix.Action.PerformFinalApplicabilityCheck)
                    {
                        return true;
                    }
585

586 587 588 589 590 591 592
                    // 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);
                        },
593
                        cancellationToken, TaskCreationOptions.None, ForegroundTaskScheduler).ConfigureAwait(false);
594 595 596 597 598 599 600
                    this.AssertIsBackground();

                    if (applicable)
                    {
                        return true;
                    }
                }
601 602 603 604 605
            }

            return false;
        }

606 607 608
        private bool IsInteractiveCodeFixProvider(CodeFixProvider provider)
        {
            // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
609 610
            return provider is FullyQualify.AbstractFullyQualifyCodeFixProvider ||
                   provider is AddImport.AbstractAddImportCodeFixProvider;
611 612
        }

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

J
Jonathon Marolf 已提交
615
        private ImmutableArray<DiagnosticId> GetFixableDiagnosticIds(CodeFixProvider fixer, IExtensionManager extensionManager)
616
        {
C
Carol Hu 已提交
617
            // 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 已提交
618 619 620 621
            // 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(
622
                    fixer,
623
                    () => ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f)),
S
Shyam N 已提交
624
                    defaultValue: ImmutableArray<DiagnosticId>.Empty);
J
Jonathon Marolf 已提交
625 626 627 628
            }

            try
            {
629
                return ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => GetAndTestFixableDiagnosticIds(f));
J
Jonathon Marolf 已提交
630 631 632 633 634 635 636
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception e)
            {
J
Jonathon Marolf 已提交
637 638
                foreach (var logger in _errorLoggers)
                {
639
                    logger.Value.LogException(fixer, e);
J
Jonathon Marolf 已提交
640
                }
J
Jonathon Marolf 已提交
641 642
                return ImmutableArray<DiagnosticId>.Empty;
            }
643 644
        }

645 646 647 648 649 650 651
        private static ImmutableArray<string> GetAndTestFixableDiagnosticIds(CodeFixProvider codeFixProvider)
        {
            var ids = codeFixProvider.FixableDiagnosticIds;
            if (ids.IsDefault)
            {
                throw new InvalidOperationException(
                    string.Format(
652
                        WorkspacesResources._0_returned_an_uninitialized_ImmutableArray,
653
                        codeFixProvider.GetType().Name + "." + nameof(CodeFixProvider.FixableDiagnosticIds)));
654 655 656 657 658
            }

            return ids;
        }

659
        private ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> GetFixerPerLanguageMap(
J
Jonathon Marolf 已提交
660 661
            Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage,
            IExtensionManager extensionManager)
662 663 664 665 666 667 668 669 670 671
        {
            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 已提交
672
                        foreach (var id in this.GetFixableDiagnosticIds(fixer.Value, extensionManager))
673 674 675 676 677 678
                        {
                            if (string.IsNullOrWhiteSpace(id))
                            {
                                continue;
                            }

679
                            var list = mutableMap.GetOrAdd(id, s_createList);
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
                            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 已提交
699
        private static ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> GetSuppressionProvidersPerLanguageMap(
700 701 702 703 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
            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)
        {
739 740
            // TODO (https://github.com/dotnet/roslyn/issues/4932): Don't restrict CodeFixes in Interactive
            return project.Solution.Workspace.Kind == WorkspaceKind.Interactive
H
Heejae Chang 已提交
741
                ? ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty
742
                : _projectFixersMap.GetValue(project.AnalyzerReferences, pId => ComputeProjectFixers(project));
743 744 745 746
        }

        private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> ComputeProjectFixers(Project project)
        {
J
Jonathon Marolf 已提交
747
            var extensionManager = project.Solution.Workspace.Services.GetService<IExtensionManager>();
748 749 750
            ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Builder builder = null;
            foreach (var reference in project.AnalyzerReferences)
            {
751
                var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue(reference, _createProjectCodeFixProvider);
752 753
                foreach (var fixer in projectCodeFixerProvider.GetFixers(project.Language))
                {
J
Jonathon Marolf 已提交
754
                    var fixableIds = this.GetFixableDiagnosticIds(fixer, extensionManager);
755 756 757 758 759 760 761 762
                    foreach (var id in fixableIds)
                    {
                        if (string.IsNullOrWhiteSpace(id))
                        {
                            continue;
                        }

                        builder = builder ?? ImmutableDictionary.CreateBuilder<DiagnosticId, List<CodeFixProvider>>();
763
                        var list = builder.GetOrAdd(id, s_createList);
764 765 766 767 768 769 770 771 772 773 774 775 776 777
                        list.Add(fixer);
                    }
                }
            }

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

            return builder.ToImmutable();
        }
    }
}