AnalysisState.cs 35.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
11
using Microsoft.CodeAnalysis.Diagnostics.Telemetry;
12
using Roslyn.Utilities;
13
using static Microsoft.CodeAnalysis.Diagnostics.AnalyzerDriver;
14 15 16 17 18 19 20 21

namespace Microsoft.CodeAnalysis.Diagnostics
{
    /// <summary>
    /// Stores the partial analysis state for analyzers executed on a specific compilation.
    /// </summary>
    internal partial class AnalysisState
    {
22
        private readonly object _gate;
23 24 25

        /// <summary>
        /// Per-analyzer analysis state map.
26
        /// The integer value points to the index within the <see cref="_analyzerStates"/> array.
27
        /// </summary>
28 29 30 31 32 33
        private readonly ImmutableDictionary<DiagnosticAnalyzer, int> _analyzerStateMap;

        /// <summary>
        /// Per-analyzer analysis state.
        /// </summary>
        private readonly ImmutableArray<PerAnalyzerState> _analyzerStates;
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

        /// <summary>
        /// Compilation events corresponding to source tree, that are not completely processed for all analyzers.
        /// Events are dropped as and when they are fully processed by all analyzers.
        /// </summary>
        private readonly Dictionary<SyntaxTree, HashSet<CompilationEvent>> _pendingSourceEvents;

        /// <summary>
        /// Compilation events corresponding to the compilation (compilation start and completed events), that are not completely processed for all analyzers.
        /// </summary>
        private readonly HashSet<CompilationEvent> _pendingNonSourceEvents;

        /// <summary>
        /// Action counts per-analyzer.
        /// </summary>
49
        private ImmutableDictionary<DiagnosticAnalyzer, AnalyzerActionCounts> _lazyAnalyzerActionCountsMap;
50

51 52 53 54 55
        private readonly HashSet<SyntaxTree> _treesWithGeneratedSourceEvents;
        private readonly HashSet<ISymbol> _partialSymbolsWithGeneratedSourceEvents;
        private readonly CompilationData _compilationData;
        private bool _compilationStartGenerated;
        private bool _compilationEndGenerated;
56 57 58 59 60 61 62 63

        /// <summary>
        /// Cached semantic model for the compilation trees.
        /// PERF: This cache enables us to re-use semantic model's bound node cache across analyzer execution and diagnostic queries.
        /// </summary>
        private readonly ConditionalWeakTable<SyntaxTree, SemanticModel> _semanticModelsMap;

        private readonly ObjectPool<HashSet<CompilationEvent>> _compilationEventsPool;
64
        private readonly HashSet<CompilationEvent> _pooledEventsWithAnyActionsSet;
65

66 67 68 69 70 71 72
        // Create static pools for heavily allocated per-analyzer state objects - this helps in reducing allocations across CompilationWithAnalyzer instances.
        private const int PoolSize = 5000;
        private static readonly ObjectPool<AnalyzerStateData> s_analyzerStateDataPool = new ObjectPool<AnalyzerStateData>(() => new AnalyzerStateData(), PoolSize);
        private static readonly ObjectPool<DeclarationAnalyzerStateData> s_declarationAnalyzerStateDataPool = new ObjectPool<DeclarationAnalyzerStateData>(() => new DeclarationAnalyzerStateData(), PoolSize);
        private static readonly ObjectPool<Dictionary<int, DeclarationAnalyzerStateData>> s_currentlyAnalyzingDeclarationsMapPool = new ObjectPool<Dictionary<int, DeclarationAnalyzerStateData>>(() => new Dictionary<int, DeclarationAnalyzerStateData>(), PoolSize);
        private static readonly ObjectPool<PerAnalyzerState> s_perAnalyzerStatePool = new ObjectPool<PerAnalyzerState>(() => new PerAnalyzerState(s_analyzerStateDataPool, s_declarationAnalyzerStateDataPool, s_currentlyAnalyzingDeclarationsMapPool), PoolSize);

73
        public AnalysisState(ImmutableArray<DiagnosticAnalyzer> analyzers, CompilationData compilationData)
74
        {
75
            _gate = new object();
76
            _analyzerStateMap = CreateAnalyzerStateMap(analyzers, out _analyzerStates);
77
            _compilationData = compilationData;
78 79 80 81
            _pendingSourceEvents = new Dictionary<SyntaxTree, HashSet<CompilationEvent>>();
            _pendingNonSourceEvents = new HashSet<CompilationEvent>();
            _lazyAnalyzerActionCountsMap = null;
            _semanticModelsMap = new ConditionalWeakTable<SyntaxTree, SemanticModel>();
82 83 84 85
            _treesWithGeneratedSourceEvents = new HashSet<SyntaxTree>();
            _partialSymbolsWithGeneratedSourceEvents = new HashSet<ISymbol>();
            _compilationStartGenerated = false;
            _compilationEndGenerated = false;
86
            _compilationEventsPool = new ObjectPool<HashSet<CompilationEvent>>(() => new HashSet<CompilationEvent>());
87
            _pooledEventsWithAnyActionsSet = new HashSet<CompilationEvent>();
88 89
        }

90
        ~AnalysisState()
91
        {
92 93 94
            // Free the per-analyzer state tracking objects.
            foreach (var analyzerState in _analyzerStates)
            {
95 96 97 98 99 100 101 102 103 104 105
                var shouldReturnToPool = analyzerState.Free();

                // If we have too many symbols then just discard the state object from the pool - we don't want to hold onto really large dictionaries.
                if (shouldReturnToPool)
                {
                    s_perAnalyzerStatePool.Free(analyzerState);
                }
                else
                {
                    s_perAnalyzerStatePool.ForgetTrackedObject(analyzerState);
                }
106 107
            }
        }
108

109 110
        private static ImmutableDictionary<DiagnosticAnalyzer, int> CreateAnalyzerStateMap(ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<PerAnalyzerState> analyzerStates)
        {
111 112 113
            var statesBuilder = ImmutableArray.CreateBuilder<PerAnalyzerState>();
            var map = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, int>();
            var index = 0;
114 115
            foreach (var analyzer in analyzers)
            {
116
                statesBuilder.Add(s_perAnalyzerStatePool.Allocate());
117 118
                map[analyzer] = index;
                index++;
119 120
            }

121
            analyzerStates = statesBuilder.ToImmutable();
122 123 124
            return map.ToImmutable();
        }

125
        private PerAnalyzerState GetAnalyzerState(DiagnosticAnalyzer analyzer)
126
        {
127 128
            var index = _analyzerStateMap[analyzer];
            return _analyzerStates[index];
129 130
        }

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
        public async Task GenerateSimulatedCompilationEventsAsync(
            AnalysisScope analysisScope,
            Compilation compilation,
            Func<SyntaxTree, Compilation, CancellationToken, SemanticModel> getCachedSemanticModel,
            AnalyzerDriver driver,
            CancellationToken cancellationToken)
        {
            await EnsureAnalyzerActionCountsInitializedAsync(driver, cancellationToken).ConfigureAwait(false);

            // Compilation started event.
            GenerateSimulatedCompilatioNonSourceEvent(compilation, driver, started: true, cancellationToken: cancellationToken);

            // Symbol declared and compilation unit completed events.
            foreach (var tree in analysisScope.SyntaxTrees)
            {
                GenerateSimulatedCompilationSourceEvents(tree, compilation, getCachedSemanticModel, driver, cancellationToken);
            }

            // Compilation ended event.
            if (analysisScope.FilterTreeOpt == null)
            {
                GenerateSimulatedCompilatioNonSourceEvent(compilation, driver, started: false, cancellationToken: cancellationToken);
            }
        }

        private void GenerateSimulatedCompilationSourceEvents(
            SyntaxTree tree,
            Compilation compilation,
            Func<SyntaxTree, Compilation, CancellationToken, SemanticModel> getCachedSemanticModel,
            AnalyzerDriver driver,
            CancellationToken cancellationToken)
        {
            lock (_gate)
            {
                if (_treesWithGeneratedSourceEvents.Contains(tree))
                {
                    return;
                }
            }

            var globalNs = compilation.Assembly.GlobalNamespace;
            var symbols = GetDeclaredSymbolsInTree(tree, compilation, getCachedSemanticModel, cancellationToken);
            var compilationEvents = CreateCompilationEventsForTree(symbols.Concat(globalNs), tree, compilation);

            lock (_gate)
            {
                if (_treesWithGeneratedSourceEvents.Contains(tree))
                {
                    return;
                }

                OnCompilationEventsGenerated_NoLock(compilationEvents, tree, driver, cancellationToken);

                var added = _treesWithGeneratedSourceEvents.Add(tree);
                Debug.Assert(added);
            }
        }

        private IEnumerable<ISymbol> GetDeclaredSymbolsInTree(
            SyntaxTree tree,
            Compilation compilation,
            Func<SyntaxTree, Compilation, CancellationToken, SemanticModel> getCachedSemanticModel,
            CancellationToken cancellationToken)
        {
            var model = getCachedSemanticModel(tree, compilation, cancellationToken);
            var fullSpan = tree.GetRoot(cancellationToken).FullSpan;
            var declarationInfos = new List<DeclarationInfo>();
            model.ComputeDeclarationsInSpan(fullSpan, getSymbol: true, builder: declarationInfos, cancellationToken: cancellationToken);
199
            return declarationInfos.Select(declInfo => declInfo.DeclaredSymbol).Distinct().WhereNotNull();
200 201 202 203 204 205
        }

        private static ImmutableArray<CompilationEvent> CreateCompilationEventsForTree(IEnumerable<ISymbol> declaredSymbols, SyntaxTree tree, Compilation compilation)
        {
            var builder = ImmutableArray.CreateBuilder<CompilationEvent>();
            foreach (var symbol in declaredSymbols)
206 207
            {
                Debug.Assert(symbol.ContainingAssembly == compilation.Assembly);
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
                builder.Add(new SymbolDeclaredCompilationEvent(compilation, symbol));
            }

            builder.Add(new CompilationUnitCompletedEvent(compilation, tree));
            return builder.ToImmutable();
        }

        private void GenerateSimulatedCompilatioNonSourceEvent(Compilation compilation, AnalyzerDriver driver, bool started, CancellationToken cancellationToken)
        {
            lock (_gate)
            {
                var eventAlreadyGenerated = started ? _compilationStartGenerated : _compilationEndGenerated;
                if (eventAlreadyGenerated)
                {
                    return;
                }

                var compilationEvent = started ? (CompilationEvent)new CompilationStartedEvent(compilation) : new CompilationCompletedEvent(compilation);
                var events = ImmutableArray.Create(compilationEvent);
                OnCompilationEventsGenerated_NoLock(events, filterTreeOpt: null, driver: driver, cancellationToken: cancellationToken);

                if (started)
                {
                    _compilationStartGenerated = true;
                }
                else
                {
                    _compilationEndGenerated = true;
                }
            }
        }

240 241 242 243
        public async Task OnCompilationEventsGeneratedAsync(ImmutableArray<CompilationEvent> compilationEvents, AnalyzerDriver driver, CancellationToken cancellationToken)
        {
            await EnsureAnalyzerActionCountsInitializedAsync(driver, cancellationToken).ConfigureAwait(false);

244
            lock (_gate)
245
            {
246
                OnCompilationEventsGenerated_NoLock(compilationEvents, filterTreeOpt: null, driver: driver, cancellationToken: cancellationToken);
247 248 249
            }
        }

250
        private void OnCompilationEventsGenerated_NoLock(ImmutableArray<CompilationEvent> compilationEvents, SyntaxTree filterTreeOpt, AnalyzerDriver driver, CancellationToken cancellationToken)
251 252 253 254
        {
            Debug.Assert(_lazyAnalyzerActionCountsMap != null);

            // Add the events to our global pending events map.
255
            AddToEventsMap_NoLock(compilationEvents, filterTreeOpt);
256

257
            // Mark the events for analysis for each analyzer.
258
            ArrayBuilder<ISymbol> newPartialSymbols = null;
259
            Debug.Assert(_pooledEventsWithAnyActionsSet.Count == 0);
260 261 262
            foreach (var kvp in _analyzerStateMap)
            {
                var analyzer = kvp.Key;
263
                var analyzerState = _analyzerStates[kvp.Value];
264 265 266 267 268 269
                var actionCounts = _lazyAnalyzerActionCountsMap[analyzer];

                foreach (var compilationEvent in compilationEvents)
                {
                    if (HasActionsForEvent(compilationEvent, actionCounts))
                    {
270
                        _pooledEventsWithAnyActionsSet.Add(compilationEvent);
271 272

                        var symbolDeclaredEvent = compilationEvent as SymbolDeclaredCompilationEvent;
273
                        if (symbolDeclaredEvent?.DeclaringSyntaxReferences.Length > 1)
274
                        {
275 276 277 278 279 280 281 282 283 284
                            if (_partialSymbolsWithGeneratedSourceEvents.Contains(symbolDeclaredEvent.Symbol))
                            {
                                // already processed.
                                continue;
                            }
                            else
                            {
                                newPartialSymbols = newPartialSymbols ?? ArrayBuilder<ISymbol>.GetInstance();
                                newPartialSymbols.Add(symbolDeclaredEvent.Symbol);
                            }
285 286
                        }

287
                        analyzerState.OnCompilationEventGenerated(compilationEvent, actionCounts);
288 289 290
                    }
                }
            }
291 292 293 294 295 296 297 298 299

            foreach (var compilationEvent in compilationEvents)
            {
                if (!_pooledEventsWithAnyActionsSet.Remove(compilationEvent))
                {
                    // Event has no relevant actions to execute, so mark it as complete.  
                    UpdateEventsMap_NoLock(compilationEvent, add: false);
                }
            }
300 301 302 303 304 305

            if (newPartialSymbols != null)
            {
                _partialSymbolsWithGeneratedSourceEvents.AddAll(newPartialSymbols);
                newPartialSymbols.Free();
            }
306 307
        }

308
        private void AddToEventsMap_NoLock(ImmutableArray<CompilationEvent> compilationEvents, SyntaxTree filterTreeOpt)
309
        {
310 311 312 313 314 315
            if (filterTreeOpt != null)
            {
                AddPendingSourceEvents_NoLock(compilationEvents, filterTreeOpt);
                return;
            }

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 371 372 373 374 375 376
            foreach (var compilationEvent in compilationEvents)
            {
                UpdateEventsMap_NoLock(compilationEvent, add: true);
            }
        }

        private void UpdateEventsMap_NoLock(CompilationEvent compilationEvent, bool add)
        {
            var symbolEvent = compilationEvent as SymbolDeclaredCompilationEvent;
            if (symbolEvent != null)
            {
                // Add/remove symbol events.
                // Any diagnostics request for a tree should trigger symbol and syntax node analysis for symbols with at least one declaring reference in the tree.
                foreach (var location in symbolEvent.Symbol.Locations)
                {
                    if (location.SourceTree != null)
                    {
                        if (add)
                        {
                            AddPendingSourceEvent_NoLock(location.SourceTree, compilationEvent);
                        }
                        else
                        {
                            RemovePendingSourceEvent_NoLock(location.SourceTree, compilationEvent);
                        }
                    }
                }
            }
            else
            {
                // Add/remove compilation unit completed events.
                var compilationUnitCompletedEvent = compilationEvent as CompilationUnitCompletedEvent;
                if (compilationUnitCompletedEvent != null)
                {
                    var tree = compilationUnitCompletedEvent.SemanticModel.SyntaxTree;
                    if (add)
                    {
                        AddPendingSourceEvent_NoLock(tree, compilationEvent);
                    }
                    else
                    {
                        RemovePendingSourceEvent_NoLock(tree, compilationEvent);
                    }
                }
                else if (compilationEvent is CompilationStartedEvent || compilationEvent is CompilationCompletedEvent)
                {
                    // Add/remove compilation events.
                    if (add)
                    {
                        _pendingNonSourceEvents.Add(compilationEvent);
                    }
                    else
                    {
                        _pendingNonSourceEvents.Remove(compilationEvent);
                    }
                }
                else
                {
                    throw new InvalidOperationException("Unexpected compilation event of type " + compilationEvent.GetType().Name);
                }
            }
377
        }
378

379 380 381 382
        private void AddPendingSourceEvents_NoLock(ImmutableArray<CompilationEvent> compilationEvents, SyntaxTree tree)
        {
            HashSet<CompilationEvent> currentEvents;
            if (!_pendingSourceEvents.TryGetValue(tree, out currentEvents))
383
            {
384 385 386 387
                currentEvents = new HashSet<CompilationEvent>(compilationEvents);
                _pendingSourceEvents[tree] = currentEvents;
                _compilationData.RemoveCachedSemanticModel(tree);
                return;
388
            }
389 390

            currentEvents.AddAll(compilationEvents);
391 392 393 394 395 396 397
        }

        private void AddPendingSourceEvent_NoLock(SyntaxTree tree, CompilationEvent compilationEvent)
        {
            HashSet<CompilationEvent> currentEvents;
            if (!_pendingSourceEvents.TryGetValue(tree, out currentEvents))
            {
398
                currentEvents = new HashSet<CompilationEvent>();
399
                _pendingSourceEvents[tree] = currentEvents;
400
                _compilationData.RemoveCachedSemanticModel(tree);
401 402 403 404 405 406 407 408 409 410 411 412 413
            }

            currentEvents.Add(compilationEvent);
        }

        private void RemovePendingSourceEvent_NoLock(SyntaxTree tree, CompilationEvent compilationEvent)
        {
            HashSet<CompilationEvent> currentEvents;
            if (_pendingSourceEvents.TryGetValue(tree, out currentEvents))
            {
                if (currentEvents.Remove(compilationEvent) && currentEvents.Count == 0)
                {
                    _pendingSourceEvents.Remove(tree);
414
                    _compilationData.RemoveCachedSemanticModel(tree);
415 416 417 418 419 420 421 422
                }
            }
        }

        private async Task EnsureAnalyzerActionCountsInitializedAsync(AnalyzerDriver driver, CancellationToken cancellationToken)
        {
            if (_lazyAnalyzerActionCountsMap == null)
            {
423
                var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, AnalyzerActionCounts>();
424 425 426 427 428 429 430 431 432 433
                foreach (var analyzer in _analyzerStateMap.Keys)
                {
                    var actionCounts = await driver.GetAnalyzerActionCountsAsync(analyzer, cancellationToken).ConfigureAwait(false);
                    builder.Add(analyzer, actionCounts);
                }

                Interlocked.CompareExchange(ref _lazyAnalyzerActionCountsMap, builder.ToImmutable(), null);
            }
        }

434
        internal async Task<AnalyzerActionCounts> GetAnalyzerActionCountsAsync(DiagnosticAnalyzer analyzer, AnalyzerDriver driver, CancellationToken cancellationToken)
435 436 437 438 439
        {
            await EnsureAnalyzerActionCountsInitializedAsync(driver, cancellationToken).ConfigureAwait(false);
            return _lazyAnalyzerActionCountsMap[analyzer];
        }

440
        private static bool HasActionsForEvent(CompilationEvent compilationEvent, AnalyzerActionCounts actionCounts)
441 442 443 444 445 446 447 448 449 450 451 452
        {
            if (compilationEvent is CompilationStartedEvent)
            {
                return actionCounts.CompilationActionsCount > 0 ||
                    actionCounts.SyntaxTreeActionsCount > 0;
            }
            else if (compilationEvent is CompilationCompletedEvent)
            {
                return actionCounts.CompilationEndActionsCount > 0;
            }
            else if (compilationEvent is SymbolDeclaredCompilationEvent)
            {
453
                return actionCounts.SymbolActionsCount > 0 || actionCounts.HasAnyExecutableCodeActions;
454 455 456 457 458 459 460
            }
            else
            {
                return actionCounts.SemanticModelActionsCount > 0;
            }
        }

461
        private void OnSymbolDeclaredEventProcessed(SymbolDeclaredCompilationEvent symbolDeclaredEvent, ImmutableArray<DiagnosticAnalyzer> analyzers)
462 463 464
        {
            foreach (var analyzer in analyzers)
            {
465
                var analyzerState = GetAnalyzerState(analyzer);
466
                analyzerState.OnSymbolDeclaredEventProcessed(symbolDeclaredEvent);
467 468 469 470 471 472 473
            }
        }

        /// <summary>
        /// Invoke this method at completion of event processing for the given analysis scope.
        /// It updates the analysis state of this event for each analyzer and if the event has been fully processed for all analyzers, then removes it from our event cache.
        /// </summary>
474
        public void OnCompilationEventProcessed(CompilationEvent compilationEvent, AnalysisScope analysisScope)
475 476 477 478 479
        {
            // Analyze if the symbol and all its declaring syntax references are analyzed.
            var symbolDeclaredEvent = compilationEvent as SymbolDeclaredCompilationEvent;
            if (symbolDeclaredEvent != null)
            {
480
                OnSymbolDeclaredEventProcessed(symbolDeclaredEvent, analysisScope.Analyzers);
481 482 483
            }

            // Check if event is fully analyzed for all analyzers.
484
            foreach (var analyzerState in _analyzerStates)
485
            {
486
                if (!analyzerState.IsEventAnalyzed(compilationEvent))
487 488 489 490 491 492
                {
                    return;
                }
            }

            // Remove the event from event map.
493
            lock (_gate)
494 495 496 497 498 499 500 501
            {
                UpdateEventsMap_NoLock(compilationEvent, add: false);
            }
        }

        /// <summary>
        /// Gets pending events for given set of analyzers for the given syntax tree.
        /// </summary>
502
        public ImmutableArray<CompilationEvent> GetPendingEvents(ImmutableArray<DiagnosticAnalyzer> analyzers, SyntaxTree tree)
503
        {
504
            lock (_gate)
505 506 507 508 509 510 511 512 513 514
            {
                return GetPendingEvents_NoLock(analyzers, tree);
            }
        }

        private HashSet<CompilationEvent> GetPendingEvents_NoLock(ImmutableArray<DiagnosticAnalyzer> analyzers)
        {
            var uniqueEvents = _compilationEventsPool.Allocate();
            foreach (var analyzer in analyzers)
            {
515
                var analyzerState = GetAnalyzerState(analyzer);
516
                analyzerState.AddPendingEvents(uniqueEvents);
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
            }

            return uniqueEvents;
        }

        /// <summary>
        /// Gets pending events for given set of analyzers for the given syntax tree.
        /// </summary>
        private ImmutableArray<CompilationEvent> GetPendingEvents_NoLock(ImmutableArray<DiagnosticAnalyzer> analyzers, SyntaxTree tree)
        {
            HashSet<CompilationEvent> compilationEventsForTree;
            if (_pendingSourceEvents.TryGetValue(tree, out compilationEventsForTree))
            {
                if (compilationEventsForTree?.Count > 0)
                {
                    HashSet<CompilationEvent> pendingEvents = null;
                    try
                    {
                        pendingEvents = GetPendingEvents_NoLock(analyzers);
                        if (pendingEvents.Count > 0)
                        {
                            pendingEvents.IntersectWith(compilationEventsForTree);
                            return pendingEvents.ToImmutableArray();
                        }
                    }
                    finally
                    {
                        Free(pendingEvents);
                    }
                }
            }

            return ImmutableArray<CompilationEvent>.Empty;
        }

        /// <summary>
        /// Gets all pending events for given set of analyzers.
        /// </summary>
        /// <param name="analyzers"></param>
        /// <param name="includeSourceEvents">Indicates if source events (symbol declared, compilation unit completed event) should be included.</param>
        /// <param name="includeNonSourceEvents">Indicates if compilation wide events (compilation started and completed event) should be included.</param>
558
        public ImmutableArray<CompilationEvent> GetPendingEvents(ImmutableArray<DiagnosticAnalyzer> analyzers, bool includeSourceEvents, bool includeNonSourceEvents)
559
        {
560
            lock (_gate)
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
            {
                return GetPendingEvents_NoLock(analyzers, includeSourceEvents, includeNonSourceEvents);
            }
        }

        private ImmutableArray<CompilationEvent> GetPendingEvents_NoLock(ImmutableArray<DiagnosticAnalyzer> analyzers, bool includeSourceEvents, bool includeNonSourceEvents)
        {
            HashSet<CompilationEvent> pendingEvents = null, uniqueEvents = null;
            try
            {
                pendingEvents = GetPendingEvents_NoLock(analyzers);
                if (pendingEvents.Count == 0)
                {
                    return ImmutableArray<CompilationEvent>.Empty;
                }

                uniqueEvents = _compilationEventsPool.Allocate();

                if (includeSourceEvents)
                {
                    foreach (var compilationEvents in _pendingSourceEvents.Values)
                    {
                        foreach (var compilationEvent in compilationEvents)
                        {
                            uniqueEvents.Add(compilationEvent);
                        }
                    }
                }

                if (includeNonSourceEvents)
                {
                    foreach (var compilationEvent in _pendingNonSourceEvents)
                    {
                        uniqueEvents.Add(compilationEvent);
                    }
                }

                uniqueEvents.IntersectWith(pendingEvents);
                return uniqueEvents.ToImmutableArray();
            }
            finally
            {
                Free(pendingEvents);
                Free(uniqueEvents);
            }
        }

        private void Free(HashSet<CompilationEvent> events)
        {
            if (events != null)
            {
                events.Clear();
                _compilationEventsPool.Free(events);
            }
        }

        /// <summary>
        /// Returns true if we have any pending syntax analysis for given analysis scope.
        /// </summary>
620
        public bool HasPendingSyntaxAnalysis(AnalysisScope analysisScope)
621 622 623 624 625 626 627 628
        {
            if (analysisScope.IsTreeAnalysis && !analysisScope.IsSyntaxOnlyTreeAnalysis)
            {
                return false;
            }

            foreach (var analyzer in analysisScope.Analyzers)
            {
629
                var analyzerState = GetAnalyzerState(analyzer);
630
                if (analyzerState.HasPendingSyntaxAnalysis(analysisScope.FilterTreeOpt))
631 632 633 634 635 636 637 638 639 640 641
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Returns true if we have any pending symbol analysis for given analysis scope.
        /// </summary>
642
        public bool HasPendingSymbolAnalysis(AnalysisScope analysisScope)
643 644 645
        {
            Debug.Assert(analysisScope.FilterTreeOpt != null);

646
            var symbolDeclaredEvents = GetPendingSymbolDeclaredEvents(analysisScope.FilterTreeOpt);
647 648 649 650 651 652
            foreach (var symbolDeclaredEvent in symbolDeclaredEvents)
            {
                if (analysisScope.ShouldAnalyze(symbolDeclaredEvent.Symbol))
                {
                    foreach (var analyzer in analysisScope.Analyzers)
                    {
653
                        var analyzerState = GetAnalyzerState(analyzer);
654
                        if (analyzerState.HasPendingSymbolAnalysis(symbolDeclaredEvent.Symbol))
655 656 657 658 659 660 661 662 663 664
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }

665
        private ImmutableArray<SymbolDeclaredCompilationEvent> GetPendingSymbolDeclaredEvents(SyntaxTree tree)
666 667 668
        {
            Debug.Assert(tree != null);

669
            lock (_gate)
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
            {
                HashSet<CompilationEvent> compilationEvents;
                if (!_pendingSourceEvents.TryGetValue(tree, out compilationEvents))
                {
                    return ImmutableArray<SymbolDeclaredCompilationEvent>.Empty;
                }

                return compilationEvents.OfType<SymbolDeclaredCompilationEvent>().ToImmutableArray();
            }
        }

        /// <summary>
        /// Attempts to start processing a compilation event for the given analyzer.
        /// </summary>
        /// <returns>
685 686
        /// Returns false if the event has already been processed for the analyzer OR is currently being processed by another task.
        /// If true, then it returns a non-null <paramref name="state"/> representing partial analysis state for the given event for the given analyzer.
687
        /// </returns>
688
        public bool TryStartProcessingEvent(CompilationEvent compilationEvent, DiagnosticAnalyzer analyzer, out AnalyzerStateData state)
689
        {
690
            return GetAnalyzerState(analyzer).TryStartProcessingEvent(compilationEvent, out state);
691 692 693 694 695
        }

        /// <summary>
        /// Marks the given event as fully analyzed for the given analyzer.
        /// </summary>
696
        public void MarkEventComplete(CompilationEvent compilationEvent, DiagnosticAnalyzer analyzer)
697
        {
698
            GetAnalyzerState(analyzer).MarkEventComplete(compilationEvent);
699 700
        }

701 702 703 704 705 706 707 708 709 710 711
        /// <summary>
        /// Marks the given event as fully analyzed for the given analyzers.
        /// </summary>
        public void MarkEventComplete(CompilationEvent compilationEvent, IEnumerable<DiagnosticAnalyzer> analyzers)
        {
            foreach (var analyzer in analyzers)
            {
                GetAnalyzerState(analyzer).MarkEventComplete(compilationEvent);
            }
        }

712 713 714 715
        /// <summary>
        /// Attempts to start processing a symbol for the given analyzer's symbol actions.
        /// </summary>
        /// <returns>
716 717
        /// Returns false if the symbol has already been processed for the analyzer OR is currently being processed by another task.
        /// If true, then it returns a non-null <paramref name="state"/> representing partial analysis state for the given symbol for the given analyzer.
718
        /// </returns>
719
        public bool TryStartAnalyzingSymbol(ISymbol symbol, DiagnosticAnalyzer analyzer, out AnalyzerStateData state)
720
        {
721
            return GetAnalyzerState(analyzer).TryStartAnalyzingSymbol(symbol, out state);
722 723 724 725 726
        }

        /// <summary>
        /// Marks the given symbol as fully analyzed for the given analyzer.
        /// </summary>
727
        public void MarkSymbolComplete(ISymbol symbol, DiagnosticAnalyzer analyzer)
728
        {
729
            GetAnalyzerState(analyzer).MarkSymbolComplete(symbol);
730 731 732 733 734 735
        }

        /// <summary>
        /// Attempts to start processing a symbol declaration for the given analyzer's syntax node and code block actions.
        /// </summary>
        /// <returns>
736 737
        /// Returns false if the declaration has already been processed for the analyzer OR is currently being processed by another task.
        /// If true, then it returns a non-null <paramref name="state"/> representing partial analysis state for the given declaration for the given analyzer.
738
        /// </returns>
739
        public bool TryStartAnalyzingDeclaration(ISymbol symbol, int declarationIndex, DiagnosticAnalyzer analyzer, out DeclarationAnalyzerStateData state)
740
        {
741
            return GetAnalyzerState(analyzer).TryStartAnalyzingDeclaration(symbol, declarationIndex, out state);
742 743
        }

744
        /// <summary>
745
        /// True if the given symbol declaration is fully analyzed.
746
        /// </summary>
747
        public bool IsDeclarationComplete(ISymbol symbol, int declarationIndex)
748
        {
749
            foreach (var analyzerState in _analyzerStates)
750
            {
751
                if (!analyzerState.IsDeclarationComplete(symbol, declarationIndex))
752 753 754 755 756 757 758 759
                {
                    return false;
                }
            }

            return true;
        }

760 761 762
        /// <summary>
        /// Marks the given symbol declaration as fully analyzed for the given analyzer.
        /// </summary>
763
        public void MarkDeclarationComplete(ISymbol symbol, int declarationIndex, DiagnosticAnalyzer analyzer)
764
        {
765
            GetAnalyzerState(analyzer).MarkDeclarationComplete(symbol, declarationIndex);
766 767
        }

768 769 770
        /// <summary>
        /// Marks the given symbol declaration as fully analyzed for the given analyzers.
        /// </summary>
771
        public void MarkDeclarationComplete(ISymbol symbol, int declarationIndex, IEnumerable<DiagnosticAnalyzer> analyzers)
772 773 774
        {
            foreach (var analyzer in analyzers)
            {
775
                GetAnalyzerState(analyzer).MarkDeclarationComplete(symbol, declarationIndex);
776 777 778
            }
        }

779 780 781
        /// <summary>
        /// Marks all the symbol declarations for the given symbol as fully analyzed for all the given analyzers.
        /// </summary>
782
        public void MarkDeclarationsComplete(ISymbol symbol, IEnumerable<DiagnosticAnalyzer> analyzers)
783 784 785
        {
            foreach (var analyzer in analyzers)
            {
786
                GetAnalyzerState(analyzer).MarkDeclarationsComplete(symbol);
787 788 789 790 791 792 793
            }
        }

        /// <summary>
        /// Attempts to start processing a syntax tree for the given analyzer's syntax tree actions.
        /// </summary>
        /// <returns>
794 795
        /// Returns false if the tree has already been processed for the analyzer OR is currently being processed by another task.
        /// If true, then it returns a non-null <paramref name="state"/> representing partial syntax analysis state for the given tree for the given analyzer.
796
        /// </returns>
797
        public bool TryStartSyntaxAnalysis(SyntaxTree tree, DiagnosticAnalyzer analyzer, out AnalyzerStateData state)
798
        {
799
            return GetAnalyzerState(analyzer).TryStartSyntaxAnalysis(tree, out state);
800 801 802 803 804
        }

        /// <summary>
        /// Marks the given tree as fully syntactically analyzed for the given analyzer.
        /// </summary>
805
        public void MarkSyntaxAnalysisComplete(SyntaxTree tree, DiagnosticAnalyzer analyzer)
806
        {
807
            GetAnalyzerState(analyzer).MarkSyntaxAnalysisComplete(tree);
808
        }
809 810 811 812 813 814 815 816 817 818 819

        /// <summary>
        /// Marks the given tree as fully syntactically analyzed for the given analyzers.
        /// </summary>
        public void MarkSyntaxAnalysisComplete(SyntaxTree tree, IEnumerable<DiagnosticAnalyzer> analyzers)
        {
            foreach (var analyzer in analyzers)
            {
                GetAnalyzerState(analyzer).MarkSyntaxAnalysisComplete(tree);
            }
        }
820 821
    }
}