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

3 4
#define SIMULATED_EVENT_QUEUE

5 6 7
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
8
using System.Diagnostics;
9
using System.Linq;
10 11
using System.Threading;
using System.Threading.Tasks;
12
using Microsoft.CodeAnalysis.Diagnostics.Telemetry;
13
using Microsoft.CodeAnalysis.Text;
M
Manish Vasani 已提交
14
using Roslyn.Utilities;
15
using static Microsoft.CodeAnalysis.Diagnostics.AnalyzerDriver;
16 17 18 19 20 21

namespace Microsoft.CodeAnalysis.Diagnostics
{
    public class CompilationWithAnalyzers
    {
        private readonly Compilation _compilation;
22
        private readonly CompilationData _compilationData;
23 24
        private readonly ImmutableArray<DiagnosticAnalyzer> _analyzers;
        private readonly CompilationWithAnalyzersOptions _analysisOptions;
25
        private readonly CancellationToken _cancellationToken;
26

27 28 29 30
        /// <summary>
        /// Pool of <see cref="AnalyzerDriver"/>s used for analyzer execution.
        /// </summary>
        private readonly ObjectPool<AnalyzerDriver> _driverPool;
31

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
        /// <summary>
        /// Contains the partial analysis state per-analyzer. It tracks:
        /// 1. Global set of pending compilation events. This is used to populate the event queue for analyzer execution.
        /// 2. Per-analyzer set of pending compilation events, symbols, declarations, etc. Each of these pending entities has a <see cref="AnalysisState.AnalyzerStateData"/> state object to track partial analysis.
        /// </summary>
        private readonly AnalysisState _analysisState;

        /// <summary>
        /// Cache of the current analysis results:
        /// 1. Local and non-local diagnostics.
        /// 2. Analyzer execution times, if <see cref="CompilationWithAnalyzersOptions.LogAnalyzerExecutionTime"/> is true.
        /// </summary>
        private readonly AnalysisResult _analysisResult;

        /// <summary>
        /// Set of exception diagnostics reported for exceptions thrown by the analyzers.
        /// </summary>
        private readonly ConcurrentSet<Diagnostic> _exceptionDiagnostics = new ConcurrentSet<Diagnostic>();

        /// <summary>
        /// Lock to track the set of active tasks computing tree diagnostics and task computing compilation diagnostics.
        /// </summary>
        private readonly object _executingTasksLock = new object();
        private readonly Dictionary<SyntaxTree, Tuple<Task, CancellationTokenSource>> _executingConcurrentTreeTasksOpt;
        private Tuple<Task, CancellationTokenSource> _executingCompilationOrNonConcurrentTreeTask;

        /// <summary>
        /// Used to generate a unique token for each tree diagnostics request.
        /// The token is used to determine the priority of each request.
        /// Each new tree diagnostic request gets an incremented token value and has higher priority over other requests for the same tree.
        /// Compilation diagnostics requests always have the lowest priority.
        /// </summary>
        private int _currentToken = 0;

        /// <summary>
        /// Map from active tasks computing tree diagnostics to their token number.
        /// </summary>
        private readonly Dictionary<Task, int> _concurrentTreeTaskTokensOpt;
70

71 72 73 74
        /// <summary>
        /// Pool of event queues to serve each diagnostics request.
        /// </summary>
        private static readonly ObjectPool<AsyncQueue<CompilationEvent>> s_eventQueuePool = new ObjectPool<AsyncQueue<CompilationEvent>>(() => new AsyncQueue<CompilationEvent>());
75
        private static readonly AsyncQueue<CompilationEvent> s_EmptyEventQueue = new AsyncQueue<CompilationEvent>();
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97


        /// <summary>
        /// Underlying <see cref="Compilation"/> with a non-null <see cref="Compilation.EventQueue"/>, used to drive analyzer execution.
        /// </summary>
        public Compilation Compilation => _compilation;

        /// <summary>
        /// Analyzers to execute on the compilation.
        /// </summary>
        public ImmutableArray<DiagnosticAnalyzer> Analyzers => _analyzers;

        /// <summary>
        /// Options to configure analyzer execution.
        /// </summary>
        public CompilationWithAnalyzersOptions AnalysisOptions => _analysisOptions;

        /// <summary>
        /// An optional cancellation token which can be used to cancel analysis.
        /// Note: This token is only used if the API invoked to get diagnostics doesn't provide a cancellation token.
        /// </summary>
        public CancellationToken CancellationToken => _cancellationToken;
98 99 100 101 102 103 104 105 106

        /// <summary>
        /// Creates a new compilation by attaching diagnostic analyzers to an existing compilation.
        /// </summary>
        /// <param name="compilation">The original compilation.</param>
        /// <param name="analyzers">The set of analyzers to include in future analyses.</param>
        /// <param name="options">Options that are passed to analyzers.</param>
        /// <param name="cancellationToken">A cancellation token that can be used to abort analysis.</param>
        public CompilationWithAnalyzers(Compilation compilation, ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerOptions options, CancellationToken cancellationToken)
107
            : this(compilation, analyzers, new CompilationWithAnalyzersOptions(options, onAnalyzerException: null, analyzerExceptionFilter: null, concurrentAnalysis: true, logAnalyzerExecutionTime: true, reportSuppressedDiagnostics: false), cancellationToken)
108 109 110 111 112 113 114 115 116 117
        {
        }

        /// <summary>
        /// Creates a new compilation by attaching diagnostic analyzers to an existing compilation.
        /// </summary>
        /// <param name="compilation">The original compilation.</param>
        /// <param name="analyzers">The set of analyzers to include in future analyses.</param>
        /// <param name="analysisOptions">Options to configure analyzer execution.</param>
        public CompilationWithAnalyzers(Compilation compilation, ImmutableArray<DiagnosticAnalyzer> analyzers, CompilationWithAnalyzersOptions analysisOptions)
118
            : this(compilation, analyzers, analysisOptions, cancellationToken: CancellationToken.None)
119 120 121 122 123 124 125
        {
        }

        private CompilationWithAnalyzers(Compilation compilation, ImmutableArray<DiagnosticAnalyzer> analyzers, CompilationWithAnalyzersOptions analysisOptions, CancellationToken cancellationToken)
        {
            VerifyArguments(compilation, analyzers, analysisOptions);

126
            compilation = compilation
127 128
                .WithOptions(compilation.Options.WithReportSuppressedDiagnostics(analysisOptions.ReportSuppressedDiagnostics))
                .WithEventQueue(new AsyncQueue<CompilationEvent>());
129
            _compilation = compilation;
130 131 132 133
            _analyzers = analyzers;
            _analysisOptions = analysisOptions;
            _cancellationToken = cancellationToken;

134 135
            _compilationData = new CompilationData(_compilation);
            _analysisState = new AnalysisState(analyzers, _compilationData);
136
            _analysisResult = new AnalysisResult(analysisOptions.LogAnalyzerExecutionTime, analyzers);
137
            _driverPool = new ObjectPool<AnalyzerDriver>(() => _compilation.AnalyzerForLanguage(analyzers, AnalyzerManager.Instance));
138 139 140 141 142 143 144
            _executingConcurrentTreeTasksOpt = analysisOptions.ConcurrentAnalysis ? new Dictionary<SyntaxTree, Tuple<Task, CancellationTokenSource>>() : null;
            _concurrentTreeTaskTokensOpt = analysisOptions.ConcurrentAnalysis ? new Dictionary<Task, int>() : null;
            _executingCompilationOrNonConcurrentTreeTask = null;
        }

        private void AddExceptionDiagnostic(Exception exception, DiagnosticAnalyzer analyzer, Diagnostic diagnostic)
        {
C
Cyrus Najmabadi 已提交
145
            _analysisOptions.OnAnalyzerException?.Invoke(exception, analyzer, diagnostic);
146 147 148 149 150 151 152

            _exceptionDiagnostics.Add(diagnostic);
        }

        #region Helper methods for public API argument validation

        private static void VerifyArguments(Compilation compilation, ImmutableArray<DiagnosticAnalyzer> analyzers, CompilationWithAnalyzersOptions analysisOptions)
153
        {
154 155 156 157 158
            if (compilation == null)
            {
                throw new ArgumentNullException(nameof(compilation));
            }

159 160 161 162
            if (analysisOptions == null)
            {
                throw new ArgumentNullException(nameof(analysisOptions));
            }
163

164
            VerifyAnalyzersArgumentForStaticApis(analyzers);
M
Manish Vasani 已提交
165 166
        }

167
        private static void VerifyAnalyzersArgumentForStaticApis(ImmutableArray<DiagnosticAnalyzer> analyzers, bool allowDefaultOrEmpty = false)
168 169 170
        {
            if (analyzers.IsDefaultOrEmpty)
            {
171 172 173 174 175
                if (allowDefaultOrEmpty)
                {
                    return;
                }

176 177 178 179 180 181 182
                throw new ArgumentException(CodeAnalysisResources.ArgumentCannotBeEmpty, nameof(analyzers));
            }

            if (analyzers.Any(a => a == null))
            {
                throw new ArgumentException(CodeAnalysisResources.ArgumentElementCannotBeNull, nameof(analyzers));
            }
183 184 185 186 187 188

            if (analyzers.Distinct().Length != analyzers.Length)
            {
                // Has duplicate analyzer instances.
                throw new ArgumentException(CodeAnalysisResources.DuplicateAnalyzerInstances, nameof(analyzers));
            }
189 190
        }

191
        private void VerifyAnalyzersArgument(ImmutableArray<DiagnosticAnalyzer> analyzers)
M
Manish Vasani 已提交
192
        {
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
            VerifyAnalyzersArgumentForStaticApis(analyzers);

            if (analyzers.Any(a => !_analyzers.Contains(a)))
            {
                throw new ArgumentException(CodeAnalysisResources.UnsupportedAnalyzerInstance, nameof(analyzers));
            }
        }

        private void VerifyAnalyzerArgument(DiagnosticAnalyzer analyzer)
        {
            VerifyAnalyzerArgumentForStaticApis(analyzer);

            if (!_analyzers.Contains(analyzer))
            {
                throw new ArgumentException(CodeAnalysisResources.UnsupportedAnalyzerInstance, nameof(analyzer));
            }
        }

        private static void VerifyAnalyzerArgumentForStaticApis(DiagnosticAnalyzer analyzer)
        {
            if (analyzer == null)
            {
                throw new ArgumentException(CodeAnalysisResources.ArgumentCannotBeEmpty, nameof(analyzer));
            }
        }

        private void VerifyExistingAnalyzersArgument(ImmutableArray<DiagnosticAnalyzer> analyzers)
        {
            VerifyAnalyzersArgumentForStaticApis(analyzers);

            if (analyzers.Any(a => !_analyzers.Contains(a)))
            {
                throw new ArgumentException(CodeAnalysisResources.UnsupportedAnalyzerInstance, nameof(_analyzers));
            }

            if (analyzers.Distinct().Length != analyzers.Length)
            {
                // Has duplicate analyzer instances.
                throw new ArgumentException(CodeAnalysisResources.DuplicateAnalyzerInstances, nameof(analyzers));
            }
        }

        private void VerifyModel(SemanticModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (!_compilation.ContainsSyntaxTree(model.SyntaxTree))
            {
                throw new ArgumentException(CodeAnalysisResources.InvalidTree, nameof(model));
            }
        }

        private void VerifyTree(SyntaxTree tree)
        {
            if (tree == null)
            {
                throw new ArgumentNullException(nameof(tree));
            }

            if (!_compilation.ContainsSyntaxTree(tree))
            {
                throw new ArgumentException(CodeAnalysisResources.InvalidTree, nameof(tree));
            }
        }

        #endregion

        /// <summary>
        /// Returns diagnostics produced by all <see cref="Analyzers"/>.
        /// </summary>
        public Task<ImmutableArray<Diagnostic>> GetAnalyzerDiagnosticsAsync()
        {
            return GetAnalyzerDiagnosticsAsync(_cancellationToken);
        }

        /// <summary>
        /// Returns diagnostics produced by all <see cref="Analyzers"/>.
        /// </summary>
        public async Task<ImmutableArray<Diagnostic>> GetAnalyzerDiagnosticsAsync(CancellationToken cancellationToken)
        {
            return await GetAnalyzerDiagnosticsAsync(Analyzers, includeCompilerDiagnostics: false, cancellationToken: cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Returns diagnostics produced by given <paramref name="analyzers"/>.
        /// </summary>
        /// <param name="analyzers">Analyzers whose diagnostics are required. All the given analyzers must be from the analyzers passed into the constructor of <see cref="CompilationWithAnalyzers"/>.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<ImmutableArray<Diagnostic>> GetAnalyzerDiagnosticsAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, CancellationToken cancellationToken)
        {
            VerifyExistingAnalyzersArgument(analyzers);

            return await GetAnalyzerDiagnosticsAsync(analyzers, includeCompilerDiagnostics: false, cancellationToken: cancellationToken).ConfigureAwait(false);
        }

        private async Task<ImmutableArray<Diagnostic>> GetAnalyzerDiagnosticsAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, bool includeCompilerDiagnostics, CancellationToken cancellationToken)
        {
            return await GetAnalyzerDiagnosticsCoreAsync(analyzers, includeCompilerDiagnostics, includeSourceEvents: true, includeNonSourceEvents: true, forceCompleteCompilation: true, cancellationToken: cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Returns all diagnostics produced by compilation and by all <see cref="Analyzers"/>.
        /// </summary>
        public Task<ImmutableArray<Diagnostic>> GetAllDiagnosticsAsync()
        {
            return GetAllDiagnosticsAsync(_cancellationToken);
        }

        /// <summary>
        /// Returns all diagnostics produced by compilation and by all <see cref="Analyzers"/>.
        /// </summary>
        public async Task<ImmutableArray<Diagnostic>> GetAllDiagnosticsAsync(CancellationToken cancellationToken)
        {
            var diagnostics = await GetAnalyzerDiagnosticsAsync(Analyzers, includeCompilerDiagnostics: true, cancellationToken: cancellationToken).ConfigureAwait(false);
            return diagnostics.AddRange(_exceptionDiagnostics);
        }

        /// <summary>
        /// Returns diagnostics produced by compilation actions of all <see cref="Analyzers"/>.
        /// </summary>
        public async Task<ImmutableArray<Diagnostic>> GetAnalyzerCompilationDiagnosticsAsync(CancellationToken cancellationToken)
        {
            return await GetAnalyzerCompilationDiagnosticsCoreAsync(Analyzers, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Returns diagnostics produced by compilation actions of given <paramref name="analyzers"/>.
        /// </summary>
        /// <param name="analyzers">Analyzers whose diagnostics are required. All the given analyzers must be from the analyzers passed into the constructor of <see cref="CompilationWithAnalyzers"/>.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<ImmutableArray<Diagnostic>> GetAnalyzerCompilationDiagnosticsAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, CancellationToken cancellationToken)
        {
            VerifyExistingAnalyzersArgument(analyzers);

            return await GetAnalyzerCompilationDiagnosticsCoreAsync(analyzers, cancellationToken).ConfigureAwait(false);
        }

        private async Task<ImmutableArray<Diagnostic>> GetAnalyzerCompilationDiagnosticsCoreAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, CancellationToken cancellationToken)
        {
            // PERF: Don't force complete compilation diagnostics (declaration + method body diagnostics) for compiler analyzer as we want to return just the compiler declaration diagnostics.
            var forceCompleteCompilation = !(analyzers.SingleOrDefault() is CompilerDiagnosticAnalyzer);

            if (forceCompleteCompilation)
            {
                // Force analyze entire compilation's source tree events.
                await GetAnalyzerDiagnosticsCoreAsync(analyzers, includeCompilerDiagnostics: false, includeSourceEvents: true, includeNonSourceEvents: false, forceCompleteCompilation: true, cancellationToken: cancellationToken).ConfigureAwait(false);
            }

            // Now analyze the non-source events.
            return await GetAnalyzerDiagnosticsCoreAsync(analyzers, includeCompilerDiagnostics: false, includeSourceEvents: false, includeNonSourceEvents: true, forceCompleteCompilation: forceCompleteCompilation, cancellationToken: cancellationToken).ConfigureAwait(false);
        }

        private async Task<ImmutableArray<Diagnostic>> GetAnalyzerDiagnosticsCoreAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, bool includeCompilerDiagnostics, bool includeSourceEvents, bool includeNonSourceEvents, bool forceCompleteCompilation, CancellationToken cancellationToken)
        {
            Debug.Assert(!includeCompilerDiagnostics || forceCompleteCompilation);

            await WaitForActiveAnalysisTasksAsync(cancellationToken).ConfigureAwait(false);

            var diagnostics = ImmutableArray<Diagnostic>.Empty;
            var analysisScope = new AnalysisScope(_compilation, analyzers, _analysisOptions.ConcurrentAnalysis, categorizeDiagnostics: true);

            Action generateCompilationEvents = () =>
            {
                if (forceCompleteCompilation)
                {
                    // Invoke GetDiagnostics to populate the compilation's CompilationEvent queue.
                    // Discard the returned diagnostics.
                    var compDiagnostics = _compilation.GetDiagnostics(cancellationToken);
                    if (includeCompilerDiagnostics)
                    {
                        diagnostics = compDiagnostics;
                    }
                }
            };

371 372
            Func<AsyncQueue<CompilationEvent>> getEventQueue = () =>
                GetPendingEvents(analyzers, includeSourceEvents, includeNonSourceEvents);
373 374

            // Compute the analyzer diagnostics for the given analysis scope.
375
            await ComputeAnalyzerDiagnosticsAsync(analysisScope, generateCompilationEvents, getEventQueue, newTaskToken: 0, cancellationToken: cancellationToken).ConfigureAwait(false);
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407

            // Return computed analyzer diagnostics for the given analysis scope.
            var analyzerDiagnostics = _analysisResult.GetDiagnostics(analysisScope, getLocalDiagnostics: includeSourceEvents, getNonLocalDiagnostics: includeNonSourceEvents);
            return diagnostics.AddRange(analyzerDiagnostics);
        }

        /// <summary>
        /// Returns syntax diagnostics produced by all <see cref="Analyzers"/> from analyzing the given <paramref name="tree"/>.
        /// Depending on analyzers' behavior, returned diagnostics can have locations outside the tree,
        /// and some diagnostics that would be reported for the tree by an analysis of the complete compilation
        /// can be absent.
        /// </summary>
        /// <param name="tree">Syntax tree to analyze.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<ImmutableArray<Diagnostic>> GetAnalyzerSyntaxDiagnosticsAsync(SyntaxTree tree, CancellationToken cancellationToken)
        {
            VerifyTree(tree);

            return await GetAnalyzerSyntaxDiagnosticsCoreAsync(tree, Analyzers, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Returns syntax diagnostics produced by given <paramref name="analyzers"/> from analyzing the given <paramref name="tree"/>.
        /// Depending on analyzers' behavior, returned diagnostics can have locations outside the tree,
        /// and some diagnostics that would be reported for the tree by an analysis of the complete compilation
        /// can be absent.
        /// </summary>
        /// <param name="tree">Syntax tree to analyze.</param>
        /// <param name="analyzers">Analyzers whose diagnostics are required. All the given analyzers must be from the analyzers passed into the constructor of <see cref="CompilationWithAnalyzers"/>.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<ImmutableArray<Diagnostic>> GetAnalyzerSyntaxDiagnosticsAsync(SyntaxTree tree, ImmutableArray<DiagnosticAnalyzer> analyzers, CancellationToken cancellationToken)
        {
408 409 410 411
            try
            {
                VerifyTree(tree);
                VerifyExistingAnalyzersArgument(analyzers);
412

413 414 415 416 417 418
                return await GetAnalyzerSyntaxDiagnosticsCoreAsync(tree, analyzers, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
419 420 421 422
        }

        private async Task<ImmutableArray<Diagnostic>> GetAnalyzerSyntaxDiagnosticsCoreAsync(SyntaxTree tree, ImmutableArray<DiagnosticAnalyzer> analyzers, CancellationToken cancellationToken)
        {
423 424 425
            try
            {
                var taskToken = Interlocked.Increment(ref _currentToken);
426

427 428
                var analysisScope = new AnalysisScope(analyzers, tree, filterSpan: null, syntaxAnalysis: true, concurrentAnalysis: _analysisOptions.ConcurrentAnalysis, categorizeDiagnostics: true);
                Action generateCompilationEvents = null;
429
                Func<AsyncQueue<CompilationEvent>> getEventQueue = () => s_EmptyEventQueue;
430

431 432
                // Compute the analyzer diagnostics for the given analysis scope.
                await ComputeAnalyzerDiagnosticsAsync(analysisScope, generateCompilationEvents, getEventQueue, taskToken, cancellationToken).ConfigureAwait(false);
433

434 435 436 437 438 439 440
                // Return computed analyzer diagnostics for the given analysis scope.
                return _analysisResult.GetDiagnostics(analysisScope, getLocalDiagnostics: true, getNonLocalDiagnostics: false);
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
441 442 443 444 445 446 447 448 449 450 451 452 453
        }

        /// <summary>
        /// Returns semantic diagnostics produced by all <see cref="Analyzers"/> from analyzing the given <paramref name="model"/>, optionally scoped to a <paramref name="filterSpan"/>.
        /// Depending on analyzers' behavior, returned diagnostics can have locations outside the tree,
        /// and some diagnostics that would be reported for the tree by an analysis of the complete compilation
        /// can be absent.
        /// </summary>
        /// <param name="model">Semantic model representing the syntax tree to analyze.</param>
        /// <param name="filterSpan">An optional span within the tree to scope analysis.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<ImmutableArray<Diagnostic>> GetAnalyzerSemanticDiagnosticsAsync(SemanticModel model, TextSpan? filterSpan, CancellationToken cancellationToken)
        {
454 455 456
            try
            {
                VerifyModel(model);
457

458 459 460 461 462 463
                return await GetAnalyzerSemanticDiagnosticsCoreAsync(model, filterSpan, Analyzers, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
464 465 466
        }

        /// <summary>
467 468 469 470
        /// Returns semantic diagnostics produced by all <see cref="Analyzers"/> from analyzing the given <paramref name="model"/>, optionally scoped to a <paramref name="filterSpan"/>.
        /// Depending on analyzers' behavior, returned diagnostics can have locations outside the tree,
        /// and some diagnostics that would be reported for the tree by an analysis of the complete compilation
        /// can be absent.
471
        /// </summary>
472 473 474 475 476
        /// <param name="model">Semantic model representing the syntax tree to analyze.</param>
        /// <param name="filterSpan">An optional span within the tree to scope analysis.</param>
        /// <param name="analyzers">Analyzers whose diagnostics are required. All the given analyzers must be from the analyzers passed into the constructor of <see cref="CompilationWithAnalyzers"/>.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<ImmutableArray<Diagnostic>> GetAnalyzerSemanticDiagnosticsAsync(SemanticModel model, TextSpan? filterSpan, ImmutableArray<DiagnosticAnalyzer> analyzers, CancellationToken cancellationToken)
477
        {
478 479
            VerifyModel(model);
            VerifyExistingAnalyzersArgument(analyzers);
480

481 482 483 484 485
            return await GetAnalyzerSemanticDiagnosticsCoreAsync(model, filterSpan, analyzers, cancellationToken).ConfigureAwait(false);
        }

        private async Task<ImmutableArray<Diagnostic>> GetAnalyzerSemanticDiagnosticsCoreAsync(SemanticModel model, TextSpan? filterSpan, ImmutableArray<DiagnosticAnalyzer> analyzers, CancellationToken cancellationToken)
        {
486 487 488
            try
            {
                var taskToken = Interlocked.Increment(ref _currentToken);
489

490
                var analysisScope = new AnalysisScope(analyzers, model.SyntaxTree, filterSpan, syntaxAnalysis: false, concurrentAnalysis: _analysisOptions.ConcurrentAnalysis, categorizeDiagnostics: true);
491

492 493
                // Below invocation will force GetDiagnostics on the model's tree to generate compilation events.
                Action generateCompilationEvents = () =>
494 495 496 497 498 499
                {
                    var mappedModel = _compilationData.GetOrCreateCachedSemanticModel(model.SyntaxTree, _compilation, cancellationToken);

                    // Invoke GetDiagnostics to populate the compilation's event queue.
                    mappedModel.GetDeclarationDiagnostics();
                };
500

501
                Func<AsyncQueue<CompilationEvent>> getEventQueue = () => GetPendingEvents(analyzers, model.SyntaxTree);
502

503 504 505 506
                // Compute the analyzer diagnostics for the given analysis scope.
                // We need to loop till symbol analysis is complete for any partial symbols being processed for other tree diagnostic requests.
                do
                {
507 508
                    await ComputeAnalyzerDiagnosticsAsync(analysisScope, generateCompilationEvents, getEventQueue, taskToken, cancellationToken).ConfigureAwait(false);
                } while (_analysisOptions.ConcurrentAnalysis && _analysisState.HasPendingSymbolAnalysis(analysisScope));
509

510 511 512 513
                // Return computed analyzer diagnostics for the given analysis scope.
                return _analysisResult.GetDiagnostics(analysisScope, getLocalDiagnostics: true, getNonLocalDiagnostics: false);
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
514
            {
515
                throw ExceptionUtilities.Unreachable;
516
            }
517
        }
518

519
        private async Task ComputeAnalyzerDiagnosticsAsync(AnalysisScope analysisScope, Action generateCompilationEventsOpt, Func<AsyncQueue<CompilationEvent>> getEventQueue, int newTaskToken, CancellationToken cancellationToken)
520
        {
521 522
            try
            {
523 524 525
                AnalyzerDriver driver = null;
                Task computeTask = null;
                CancellationTokenSource cts;
526

527
                try
528
                {
529 530
                    // Get the analyzer driver to execute analysis.
                    driver = await GetAnalyzerDriverAsync(cancellationToken).ConfigureAwait(false);
531

532 533 534
                    // Driver must have been initialized.
                    Debug.Assert(driver.WhenInitializedTask != null);
                    Debug.Assert(!driver.WhenInitializedTask.IsCanceled);
535

536
                    cancellationToken.ThrowIfCancellationRequested();
537

538 539 540 541 542 543 544 545 546
#if SIMULATED_EVENT_QUEUE
                    await _analysisState.GenerateSimulatedCompilationEventsAsync(analysisScope, _compilation, _compilationData.GetOrCreateCachedSemanticModel, driver, cancellationToken).ConfigureAwait(false);
#else
                    generateCompilationEventsOpt?.Invoke();

                    // Populate the events cache from the generated compilation events.
                    await PopulateEventsCacheAsync(cancellationToken).ConfigureAwait(false);
#endif

547 548 549 550 551 552
                    // Track if this task was suspended by another tree diagnostics request for the same tree.
                    // If so, we wait for the high priority requests to complete before restarting analysis.
                    bool suspendend;
                    do
                    {
                        suspendend = false;
553

554
                        // Create a new cancellation source to allow higher priority requests to suspend our analysis.
555
                        using (cts = new CancellationTokenSource())
556
                        {
557 558
                            // Link the cancellation source with client supplied cancellation source, so the public API callee can also cancel analysis.
                            using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken))
559
                            {
560 561 562 563 564
                                try
                                {
                                    // Core task to compute analyzer diagnostics.
                                    Func<Tuple<Task, CancellationTokenSource>> getComputeTask = () => Tuple.Create(
                                        Task.Run(async () =>
565 566 567
                                        {
                                            try
                                            {
568 569 570
                                                AsyncQueue<CompilationEvent> eventQueue = null;
                                                try
                                                {
571 572
                                                    // Get event queue with pending events to analyze.
                                                    eventQueue = getEventQueue();
573

574 575
                                                    // Execute analyzer driver on the given analysis scope with the given event queue.
                                                    await ComputeAnalyzerDiagnosticsCoreAsync(driver, eventQueue, analysisScope, cancellationToken: linkedCts.Token).ConfigureAwait(false);
576 577 578 579 580
                                                }
                                                finally
                                                {
                                                    FreeEventQueue(eventQueue);
                                                }
581
                                            }
582
                                            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
583
                                            {
584
                                                throw ExceptionUtilities.Unreachable;
585
                                            }
586
                                        },
587
                                            linkedCts.Token),
588
                                        cts);
589

590 591
                                    // Wait for higher priority tree document tasks to complete.
                                    computeTask = await SetActiveAnalysisTaskAsync(getComputeTask, analysisScope.FilterTreeOpt, newTaskToken, cancellationToken).ConfigureAwait(false);
592

593
                                    cancellationToken.ThrowIfCancellationRequested();
594

595
                                    await computeTask.ConfigureAwait(false);
596
                                }
597 598 599 600 601 602 603
                                catch (OperationCanceledException ex)
                                {
                                    cancellationToken.ThrowIfCancellationRequested();
                                    if (!cts.IsCancellationRequested)
                                    {
                                        throw ex;
                                    }
604

605 606 607 608 609 610 611
                                    suspendend = true;
                                }
                                finally
                                {
                                    ClearExecutingTask(computeTask, analysisScope.FilterTreeOpt);
                                    computeTask = null;
                                }
612
                            }
613
                        }
614 615 616 617 618 619
                    } while (suspendend);
                }
                finally
                {
                    FreeDriver(driver);
                }
620
            }
621
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
622
            {
623
                throw ExceptionUtilities.Unreachable;
624 625 626 627 628
            }
        }

        private async Task<AnalyzerDriver> GetAnalyzerDriverAsync(CancellationToken cancellationToken)
        {
629
            cancellationToken.ThrowIfCancellationRequested();
630

631 632
            // Get instance of analyzer driver from the driver pool.
            AnalyzerDriver driver = _driverPool.Allocate();
633

634 635 636 637
            try
            {
                // Start the initialization task, if required.
                if (driver.WhenInitializedTask == null)
638
                {
639
                    driver.Initialize(_compilation, _analysisOptions, _compilationData, categorizeDiagnostics: true, cancellationToken: cancellationToken);
640 641
                }

642 643 644
                // Wait for driver initialization to complete: this executes the Initialize and CompilationStartActions to compute all registered actions per-analyzer.
                await driver.WhenInitializedTask.ConfigureAwait(false);

645
                return driver;
646
            }
647
            catch (OperationCanceledException)
648
            {
649 650
                FreeDriver(driver);
                throw;
651 652 653 654 655 656 657
            }
        }

        private void FreeDriver(AnalyzerDriver driver)
        {
            if (driver != null)
            {
658 659
                // Throw away the driver instance if the initialization didn't succeed.
                if (driver.WhenInitializedTask == null || driver.WhenInitializedTask.IsCanceled)
660 661 662 663 664 665 666 667
                {
                    _driverPool.ForgetTrackedObject(driver);
                }
                else
                {
                    _driverPool.Free(driver);
                }
            }
668 669 670
        }

        /// <summary>
671
        /// Core method for executing analyzers.
672
        /// </summary>
673
        private async Task ComputeAnalyzerDiagnosticsCoreAsync(AnalyzerDriver driver, AsyncQueue<CompilationEvent> eventQueue, AnalysisScope analysisScope, CancellationToken cancellationToken)
674
        {
675
            try
676
            {
677 678
                Debug.Assert(!driver.WhenInitializedTask.IsCanceled);

679
                if (eventQueue.Count > 0 || _analysisState.HasPendingSyntaxAnalysis(analysisScope))
680
                {
681 682 683 684 685 686 687 688 689
                    try
                    {
                        // Perform analysis to compute new diagnostics.
                        Debug.Assert(!eventQueue.IsCompleted);
                        await driver.AttachQueueAndProcessAllEventsAsync(eventQueue, analysisScope, _analysisState, cancellationToken: cancellationToken).ConfigureAwait(false);
                    }
                    finally
                    {
                        // Update the diagnostic results based on the diagnostics reported on the driver.
690
                        _analysisResult.StoreAnalysisResult(analysisScope, driver, _compilation);
691
                    }
692 693
                }
            }
694
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
695 696 697
            {
                throw ExceptionUtilities.Unreachable;
            }
698
        }
699

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 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
        private Task<Task> SetActiveAnalysisTaskAsync(Func<Tuple<Task, CancellationTokenSource>> getNewAnalysisTask, SyntaxTree treeOpt, int newTaskToken, CancellationToken cancellationToken)
        {
            if (treeOpt != null)
            {
                return SetActiveTreeAnalysisTaskAsync(getNewAnalysisTask, treeOpt, newTaskToken, cancellationToken);
            }
            else
            {
                return SetActiveCompilationAnalysisTaskAsync(getNewAnalysisTask, cancellationToken);
            }
        }

        private async Task<Task> SetActiveCompilationAnalysisTaskAsync(Func<Tuple<Task, CancellationTokenSource>> getNewCompilationTask, CancellationToken cancellationToken)
        {
            while (true)
            {
                // Wait for all active tasks, compilation analysis tasks have lowest priority.
                await WaitForActiveAnalysisTasksAsync(cancellationToken).ConfigureAwait(false);

                lock (_executingTasksLock)
                {
                    if ((_executingConcurrentTreeTasksOpt == null || _executingConcurrentTreeTasksOpt.Count == 0) &&
                        _executingCompilationOrNonConcurrentTreeTask == null)
                    {
                        _executingCompilationOrNonConcurrentTreeTask = getNewCompilationTask();
                        return _executingCompilationOrNonConcurrentTreeTask.Item1;
                    }
                }
            }
        }

        private async Task WaitForActiveAnalysisTasksAsync(CancellationToken cancellationToken)
        {
            var executingTasks = ArrayBuilder<Tuple<Task, CancellationTokenSource>>.GetInstance();

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                lock (_executingTasksLock)
                {
                    if (_executingConcurrentTreeTasksOpt?.Count > 0)
                    {
                        executingTasks.AddRange(_executingConcurrentTreeTasksOpt.Values);
                    }

                    if (_executingCompilationOrNonConcurrentTreeTask != null)
                    {
                        executingTasks.Add(_executingCompilationOrNonConcurrentTreeTask);
                    }
                }

                if (executingTasks.Count == 0)
                {
                    executingTasks.Free();
                    return;
                }

                foreach (var task in executingTasks)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await task.Item1.ConfigureAwait(false);
                }

                executingTasks.Clear();
            }
        }

        private async Task<Task> SetActiveTreeAnalysisTaskAsync(Func<Tuple<Task, CancellationTokenSource>> getNewTreeAnalysisTask, SyntaxTree tree, int newTaskToken, CancellationToken cancellationToken)
        {
770
            try
771
            {
772
                while (true)
773
                {
774 775
                    // For concurrent analysis, we must wait for any executing tree task with higher tokens.
                    Tuple<Task, CancellationTokenSource> executingTreeTask = null;
776

777
                    lock (_executingTasksLock)
778
                    {
779
                        if (!_analysisOptions.ConcurrentAnalysis)
780
                        {
781 782 783 784 785 786 787 788 789 790
                            // For non-concurrent analysis, just suspend the executing task, if any.
                            if (_executingCompilationOrNonConcurrentTreeTask != null)
                            {
                                SuspendAnalysis_NoLock(_executingCompilationOrNonConcurrentTreeTask.Item1, _executingCompilationOrNonConcurrentTreeTask.Item2);
                                _executingCompilationOrNonConcurrentTreeTask = null;
                            }

                            var newTask = getNewTreeAnalysisTask();
                            _executingCompilationOrNonConcurrentTreeTask = newTask;
                            return newTask.Item1;
791 792
                        }

793 794 795 796 797
                        Debug.Assert(_executingConcurrentTreeTasksOpt != null);
                        Debug.Assert(_concurrentTreeTaskTokensOpt != null);

                        if (!_executingConcurrentTreeTasksOpt.TryGetValue(tree, out executingTreeTask) ||
                            _concurrentTreeTaskTokensOpt[executingTreeTask.Item1] < newTaskToken)
798
                        {
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
                            if (executingTreeTask != null)
                            {
                                SuspendAnalysis_NoLock(executingTreeTask.Item1, executingTreeTask.Item2);
                            }

                            if (_executingCompilationOrNonConcurrentTreeTask != null)
                            {
                                SuspendAnalysis_NoLock(_executingCompilationOrNonConcurrentTreeTask.Item1, _executingCompilationOrNonConcurrentTreeTask.Item2);
                                _executingCompilationOrNonConcurrentTreeTask = null;
                            }

                            var newTask = getNewTreeAnalysisTask();
                            _concurrentTreeTaskTokensOpt[newTask.Item1] = newTaskToken;
                            _executingConcurrentTreeTasksOpt[tree] = newTask;
                            return newTask.Item1;
814 815 816
                        }
                    }

817 818 819
                    await executingTreeTask.Item1.ConfigureAwait(false);
                }
            }
820
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
821 822
            {
                throw ExceptionUtilities.Unreachable;
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
            }
        }

        private void SuspendAnalysis_NoLock(Task computeTask, CancellationTokenSource cts)
        {
            if (!computeTask.IsCompleted)
            {
                // Suspend analysis.
                cts.Cancel();
            }
        }

        private void ClearExecutingTask(Task computeTask, SyntaxTree treeOpt)
        {
            if (computeTask != null)
            {
                lock (_executingTasksLock)
                {
                    Tuple<Task, CancellationTokenSource> executingTask;
                    if (treeOpt != null && _analysisOptions.ConcurrentAnalysis)
                    {
                        Debug.Assert(_executingConcurrentTreeTasksOpt != null);
                        Debug.Assert(_concurrentTreeTaskTokensOpt != null);

                        if (_executingConcurrentTreeTasksOpt.TryGetValue(treeOpt, out executingTask) &&
                            executingTask.Item1 == computeTask)
                        {
                            _executingConcurrentTreeTasksOpt.Remove(treeOpt);
                        }

                        if (_concurrentTreeTaskTokensOpt.ContainsKey(computeTask))
                        {
                            _concurrentTreeTaskTokensOpt.Remove(computeTask);
                        }
                    }
                    else if (_executingCompilationOrNonConcurrentTreeTask?.Item1 == computeTask)
                    {
                        _executingCompilationOrNonConcurrentTreeTask = null;
                    }
                }
            }
        }

        private async Task PopulateEventsCacheAsync(CancellationToken cancellationToken)
        {
            if (_compilation.EventQueue.Count > 0)
            {
                AnalyzerDriver driver = null;
                try
                {
                    driver = await GetAnalyzerDriverAsync(cancellationToken).ConfigureAwait(false);
                    cancellationToken.ThrowIfCancellationRequested();

                    var compilationEvents = DequeueGeneratedCompilationEvents();
                    await _analysisState.OnCompilationEventsGeneratedAsync(compilationEvents, driver, cancellationToken).ConfigureAwait(false);
                }
                finally
                {
                    FreeDriver(driver);
                }
            }
        }

        private ImmutableArray<CompilationEvent> DequeueGeneratedCompilationEvents()
        {
            var builder = ImmutableArray.CreateBuilder<CompilationEvent>();

            CompilationEvent compilationEvent;
            while (_compilation.EventQueue.TryDequeue(out compilationEvent))
            {
                builder.Add(compilationEvent);
            }

            return builder.ToImmutable();
        }

899
        private AsyncQueue<CompilationEvent> GetPendingEvents(ImmutableArray<DiagnosticAnalyzer> analyzers, SyntaxTree tree)
900 901 902 903 904
        {
            var eventQueue = s_eventQueuePool.Allocate();
            Debug.Assert(!eventQueue.IsCompleted);
            Debug.Assert(eventQueue.Count == 0);

905
            foreach (var compilationEvent in _analysisState.GetPendingEvents(analyzers, tree))
906
            {
907
                eventQueue.TryEnqueue(compilationEvent);
908 909 910 911 912
            }

            return eventQueue;
        }

913
        private AsyncQueue<CompilationEvent> GetPendingEvents(ImmutableArray<DiagnosticAnalyzer> analyzers, bool includeSourceEvents, bool includeNonSourceEvents)
914 915 916 917 918 919 920
        {
            Debug.Assert(includeSourceEvents || includeNonSourceEvents);

            var eventQueue = s_eventQueuePool.Allocate();
            Debug.Assert(!eventQueue.IsCompleted);
            Debug.Assert(eventQueue.Count == 0);

921
            foreach (var compilationEvent in _analysisState.GetPendingEvents(analyzers, includeSourceEvents, includeNonSourceEvents))
922
            {
923
                eventQueue.TryEnqueue(compilationEvent);
924 925 926 927 928 929 930
            }

            return eventQueue;
        }

        private void FreeEventQueue(AsyncQueue<CompilationEvent> eventQueue)
        {
931
            if (eventQueue == null || ReferenceEquals(eventQueue, s_EmptyEventQueue))
932 933 934 935 936 937 938 939 940 941 942 943
            {
                return;
            }

            Debug.Assert(!eventQueue.IsCompleted);
            if (eventQueue.Count > 0)
            {
                CompilationEvent discarded;
                while (eventQueue.TryDequeue(out discarded)) ;
            }

            s_eventQueuePool.Free(eventQueue);
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
        }

        /// <summary>
        /// Given a set of compiler or <see cref="DiagnosticAnalyzer"/> generated <paramref name="diagnostics"/>, returns the effective diagnostics after applying the below filters:
        /// 1) <see cref="CompilationOptions.SpecificDiagnosticOptions"/> specified for the given <paramref name="compilation"/>.
        /// 2) <see cref="CompilationOptions.GeneralDiagnosticOption"/> specified for the given <paramref name="compilation"/>.
        /// 3) Diagnostic suppression through applied <see cref="System.Diagnostics.CodeAnalysis.SuppressMessageAttribute"/>.
        /// 4) Pragma directives for the given <paramref name="compilation"/>.
        /// </summary>
        public static IEnumerable<Diagnostic> GetEffectiveDiagnostics(IEnumerable<Diagnostic> diagnostics, Compilation compilation)
        {
            if (diagnostics == null)
            {
                throw new ArgumentNullException(nameof(diagnostics));
            }

            if (compilation == null)
            {
                throw new ArgumentNullException(nameof(compilation));
            }

965
            var suppressMessageState = new SuppressMessageAttributeState(compilation);
966
            foreach (var diagnostic in diagnostics.ToImmutableArray())
967 968 969
            {
                if (diagnostic != null)
                {
970
                    var effectiveDiagnostic = compilation.Options.FilterDiagnostic(diagnostic);
971
                    if (effectiveDiagnostic != null)
972
                    {
973
                        effectiveDiagnostic = suppressMessageState.ApplySourceSuppressions(effectiveDiagnostic);
974 975 976 977 978 979 980 981
                        yield return effectiveDiagnostic;
                    }
                }
            }
        }

        /// <summary>
        /// Returns true if all the diagnostics that can be produced by this analyzer are suppressed through options.
982 983 984 985 986 987
        /// <param name="analyzer">Analyzer to be checked for suppression.</param>
        /// <param name="options">Compilation options.</param>
        /// <param name="onAnalyzerException">
        /// Optional delegate which is invoked when an analyzer throws an exception.
        /// Delegate can do custom tasks such as report the given analyzer exception diagnostic, report a non-fatal watson for the exception, etc.
        /// </param>
988
        /// </summary>
989 990 991 992
        public static bool IsDiagnosticAnalyzerSuppressed(
            DiagnosticAnalyzer analyzer,
            CompilationOptions options,
            Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException = null)
993
        {
994
            VerifyAnalyzerArgumentForStaticApis(analyzer);
995 996 997 998 999 1000

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

1001
            var analyzerExecutor = AnalyzerExecutor.CreateForSupportedDiagnostics(onAnalyzerException, AnalyzerManager.Instance);
M
Manish Vasani 已提交
1002
            return AnalyzerDriver.IsDiagnosticAnalyzerSuppressed(analyzer, options, AnalyzerManager.Instance, analyzerExecutor);
1003
        }
1004 1005 1006 1007 1008 1009 1010 1011

        /// <summary>
        /// This method should be invoked when the analyzer host is disposing off the given <paramref name="analyzers"/>.
        /// It clears the cached internal state (supported descriptors, registered actions, exception handlers, etc.) for analyzers.
        /// </summary>
        /// <param name="analyzers">Analyzers whose state needs to be cleared.</param>
        public static void ClearAnalyzerState(ImmutableArray<DiagnosticAnalyzer> analyzers)
        {
1012
            VerifyAnalyzersArgumentForStaticApis(analyzers, allowDefaultOrEmpty: true);
1013 1014 1015

            AnalyzerManager.Instance.ClearAnalyzerState(analyzers);
        }
1016 1017

        /// <summary>
1018
        /// Gets telemetry info for the given analyzer, such as count of registered actions, the total execution time (if <see cref="CompilationWithAnalyzersOptions.LogAnalyzerExecutionTime"/> is true), etc.
1019
        /// </summary>
1020
        public async Task<AnalyzerTelemetryInfo> GetAnalyzerTelemetryInfoAsync(DiagnosticAnalyzer analyzer, CancellationToken cancellationToken)
1021 1022 1023
        {
            VerifyAnalyzerArgument(analyzer);

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
            try
            {
                var actionCounts = await GetAnalyzerActionCountsAsync(analyzer, cancellationToken).ConfigureAwait(false);
                var executionTime = GetAnalyzerExecutionTime(analyzer);
                return new AnalyzerTelemetryInfo(actionCounts, executionTime);
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
1034 1035 1036 1037 1038 1039 1040
        }

        /// <summary>
        /// Gets the count of registered actions for the analyzer.
        /// </summary>
        private async Task<AnalyzerActionCounts> GetAnalyzerActionCountsAsync(DiagnosticAnalyzer analyzer, CancellationToken cancellationToken)
        {
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
            AnalyzerDriver driver = null;
            try
            {
                driver = await GetAnalyzerDriverAsync(cancellationToken).ConfigureAwait(false);
                cancellationToken.ThrowIfCancellationRequested();
                return await _analysisState.GetAnalyzerActionCountsAsync(analyzer, driver, cancellationToken).ConfigureAwait(false);
            }
            finally
            {
                FreeDriver(driver);
            }
        }

        /// <summary>
        /// Gets the execution time for the given analyzer.
        /// </summary>
1057
        private TimeSpan GetAnalyzerExecutionTime(DiagnosticAnalyzer analyzer)
1058 1059 1060
        {
            if (!_analysisOptions.LogAnalyzerExecutionTime)
            {
1061
                return default(TimeSpan);
1062 1063 1064 1065
            }

            return _analysisResult.GetAnalyzerExecutionTime(analyzer);
        }
1066 1067
    }
}