DiagnosticIncrementalAnalyzer.cs 46.1 KB
Newer Older
1 2 3 4 5 6 7 8 9
// 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.Threading;
using System.Threading.Tasks;
10
using Microsoft.CodeAnalysis.Diagnostics.Log;
11 12 13 14 15 16
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
17
using Microsoft.CodeAnalysis.Shared.TestHooks;
18 19 20 21
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;

22
namespace Microsoft.CodeAnalysis.Diagnostics.EngineV1
23
{
24
    internal partial class DiagnosticIncrementalAnalyzer : BaseDiagnosticIncrementalAnalyzer
25 26 27 28 29 30 31
    {
        private static readonly ImmutableArray<StateType> s_documentScopeStateTypes = ImmutableArray.Create<StateType>(StateType.Syntax, StateType.Document);

        private readonly int _correlationId;
        private readonly DiagnosticAnalyzerService _owner;
        private readonly MemberRangeMap _memberRangeMap;
        private readonly AnalyzerExecutor _executor;
32 33
        private readonly StateManager _stateManger;
        private readonly SimpleTaskQueue _eventQueue;
M
Manish Vasani 已提交
34

35 36
        private DiagnosticLogAggregator _diagnosticLogAggregator;

M
Manish Vasani 已提交
37
        public DiagnosticIncrementalAnalyzer(
38 39 40 41
            DiagnosticAnalyzerService owner,
            int correlationId,
            Workspace workspace,
            HostAnalyzerManager analyzerManager,
M
Manish Vasani 已提交
42 43
            AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
            : base(workspace, hostDiagnosticUpdateSource)
44 45 46 47 48
        {
            _owner = owner;
            _correlationId = correlationId;
            _memberRangeMap = new MemberRangeMap();
            _executor = new AnalyzerExecutor(this);
49 50 51 52 53
            _eventQueue = new SimpleTaskQueue(TaskScheduler.Default);

            _stateManger = new StateManager(analyzerManager);
            _stateManger.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;

54 55 56
            _diagnosticLogAggregator = new DiagnosticLogAggregator(_owner);
        }

57 58 59 60 61 62 63 64 65 66 67 68 69
        private void OnProjectAnalyzerReferenceChanged(object sender, ProjectAnalyzerReferenceChangedEventArgs e)
        {
            if (e.Removed.Length == 0)
            {
                // nothing to refresh
                return;
            }

            // guarantee order of the events.
            var asyncToken = _owner.Listener.BeginAsyncOperation(nameof(OnProjectAnalyzerReferenceChanged));
            _eventQueue.ScheduleTask(() => ClearProjectStatesAsync(e.Project, e.Removed, CancellationToken.None), CancellationToken.None).CompletesAsyncOperation(asyncToken);
        }

70
        public override Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
71 72 73 74
        {
            using (Logger.LogBlock(FunctionId.Diagnostics_DocumentOpen, GetOpenLogMessage, document, cancellationToken))
            {
                // we remove whatever information we used to have on document open/close and re-calcuate diagnostics
H
Heejae Chang 已提交
75
                // we had to do this since some diagnostic analyzer change its behavior based on whether the document is opend or not.
76
                // so we can't use cached information.
77
                return ClearDocumentStatesAsync(document, _stateManger.GetStateSets(document.Project), cancellationToken);
78 79 80
            }
        }

81
        public override Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
82 83 84 85 86 87 88
        {
            using (Logger.LogBlock(FunctionId.Diagnostics_DocumentReset, GetResetLogMessage, document, cancellationToken))
            {
                // we don't need the info for closed file
                _memberRangeMap.Remove(document.Id);

                // we remove whatever information we used to have on document open/close and re-calcuate diagnostics
H
Heejae Chang 已提交
89
                // we had to do this since some diagnostic analyzer change its behavior based on whether the document is opend or not.
90
                // so we can't use cached information.
91
                return ClearDocumentStatesAsync(document, _stateManger.GetStateSets(document.Project), cancellationToken);
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
            }
        }

        private bool CheckOption(Workspace workspace, string language, bool documentOpened)
        {
            var optionService = workspace.Services.GetService<IOptionService>();
            if (optionService == null || optionService.GetOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, language))
            {
                return true;
            }

            if (documentOpened)
            {
                return true;
            }

            return false;
        }

111
        public override async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
        {
            await AnalyzeSyntaxAsync(document, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false);
        }

        private async Task AnalyzeSyntaxAsync(Document document, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
        {
            try
            {
                if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen()))
                {
                    return;
                }

                var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
                var dataVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
                var versions = new VersionArgument(textVersion, dataVersion);

                var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
                var fullSpan = root == null ? null : (TextSpan?)root.FullSpan;

M
Manish Vasani 已提交
132
                var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, _diagnosticLogAggregator, HostDiagnosticUpdateSource, cancellationToken);
133 134
                var openedDocument = document.IsOpen();

135
                foreach (var stateSet in _stateManger.GetOrUpdateStateSets(document.Project))
136
                {
137
                    if (userDiagnosticDriver.IsAnalyzerSuppressed(stateSet.Analyzer))
138
                    {
139
                        await HandleSuppressedAnalyzerAsync(document, stateSet, StateType.Syntax, cancellationToken).ConfigureAwait(false);
140
                    }
H
Heejae Chang 已提交
141 142
                    else if (ShouldRunAnalyzerForStateType(userDiagnosticDriver, stateSet.Analyzer, StateType.Syntax, diagnosticIds) &&
                        (skipClosedFileChecks || ShouldRunAnalyzerForClosedFile(openedDocument, stateSet.Analyzer)))
143
                    {
144
                        var data = await _executor.GetSyntaxAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false);
145 146
                        if (data.FromCache)
                        {
147
                            RaiseDiagnosticsUpdated(StateType.Syntax, document.Id, stateSet.Analyzer, new SolutionArgument(document), data.Items);
148 149 150
                            continue;
                        }

151
                        var state = stateSet.GetState(StateType.Syntax);
152 153
                        await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);

154
                        RaiseDiagnosticsUpdatedIfNeeded(StateType.Syntax, document, stateSet.Analyzer, data.OldItems, data.Items);
155 156 157 158 159 160 161 162 163
                    }
                }
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

164
        public override async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
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 199 200 201 202 203 204 205 206 207
        {
            await AnalyzeDocumentAsync(document, bodyOpt, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false);
        }

        private async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
        {
            try
            {
                if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen()))
                {
                    return;
                }

                var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
                var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
                var dataVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);

                var versions = new VersionArgument(textVersion, dataVersion, projectVersion);
                if (bodyOpt == null)
                {
                    await AnalyzeDocumentAsync(document, versions, diagnosticIds, skipClosedFileChecks, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    // only open file can go this route
                    await AnalyzeBodyDocumentAsync(document, bodyOpt, versions, cancellationToken).ConfigureAwait(false);
                }
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

        private async Task AnalyzeBodyDocumentAsync(Document document, SyntaxNode member, VersionArgument versions, CancellationToken cancellationToken)
        {
            try
            {
                // syntax facts service must exist, otherwise, this method won't have called.
                var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
                var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
                var memberId = syntaxFacts.GetMethodLevelMemberId(root, member);

M
Manish Vasani 已提交
208 209
                var spanBasedDriver = new DiagnosticAnalyzerDriver(document, member.FullSpan, root, _diagnosticLogAggregator, HostDiagnosticUpdateSource, cancellationToken);
                var documentBasedDriver = new DiagnosticAnalyzerDriver(document, root.FullSpan, root, _diagnosticLogAggregator, HostDiagnosticUpdateSource, cancellationToken);
210

211 212
                foreach (var stateSet in _stateManger.GetOrUpdateStateSets(document.Project))
                {
213
                    bool supportsSemanticInSpan;
214
                    if (spanBasedDriver.IsAnalyzerSuppressed(stateSet.Analyzer))
215
                    {
216
                        await HandleSuppressedAnalyzerAsync(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false);
217
                    }
H
Heejae Chang 已提交
218
                    else if (ShouldRunAnalyzerForStateType(spanBasedDriver, stateSet.Analyzer, StateType.Document, out supportsSemanticInSpan))
219 220 221
                    {
                        var userDiagnosticDriver = supportsSemanticInSpan ? spanBasedDriver : documentBasedDriver;

222
                        var ranges = _memberRangeMap.GetSavedMemberRange(stateSet.Analyzer, document);
223
                        var data = await _executor.GetDocumentBodyAnalysisDataAsync(
224
                            stateSet, versions, userDiagnosticDriver, root, member, memberId, supportsSemanticInSpan, ranges).ConfigureAwait(false);
225

226
                        _memberRangeMap.UpdateMemberRange(stateSet.Analyzer, document, versions.TextVersion, memberId, member.FullSpan, ranges);
227

228
                        var state = stateSet.GetState(StateType.Document);
229 230 231 232
                        await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);

                        if (data.FromCache)
                        {
233
                            RaiseDiagnosticsUpdated(StateType.Document, document.Id, stateSet.Analyzer, new SolutionArgument(document), data.Items);
234 235 236
                            continue;
                        }

237
                        RaiseDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet.Analyzer, data.OldItems, data.Items);
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
                    }
                }
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

        private async Task AnalyzeDocumentAsync(Document document, VersionArgument versions, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
        {
            try
            {
                var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
                var fullSpan = root == null ? null : (TextSpan?)root.FullSpan;

M
Manish Vasani 已提交
254
                var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, _diagnosticLogAggregator, HostDiagnosticUpdateSource, cancellationToken);
255 256
                bool openedDocument = document.IsOpen();

257 258 259
                foreach (var stateSet in _stateManger.GetOrUpdateStateSets(document.Project))
                {
                    if (userDiagnosticDriver.IsAnalyzerSuppressed(stateSet.Analyzer))
260
                    {
261
                        await HandleSuppressedAnalyzerAsync(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false);
262
                    }
H
Heejae Chang 已提交
263 264
                    else if (ShouldRunAnalyzerForStateType(userDiagnosticDriver, stateSet.Analyzer, StateType.Document, diagnosticIds) &&
                        (skipClosedFileChecks || ShouldRunAnalyzerForClosedFile(openedDocument, stateSet.Analyzer)))
265
                    {
266
                        var data = await _executor.GetDocumentAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false);
267 268
                        if (data.FromCache)
                        {
269
                            RaiseDiagnosticsUpdated(StateType.Document, document.Id, stateSet.Analyzer, new SolutionArgument(document), data.Items);
270 271 272 273 274
                            continue;
                        }

                        if (openedDocument)
                        {
275
                            _memberRangeMap.Touch(stateSet.Analyzer, document, versions.TextVersion);
276 277
                        }

278
                        var state = stateSet.GetState(StateType.Document);
279 280
                        await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);

281
                        RaiseDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet.Analyzer, data.OldItems, data.Items);
282 283 284 285 286 287 288 289 290
                    }
                }
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

291
        public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
        {
            await AnalyzeProjectAsync(project, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false);
        }

        private async Task AnalyzeProjectAsync(Project project, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
        {
            try
            {
                if (!skipClosedFileChecks && !CheckOption(project.Solution.Workspace, project.Language, documentOpened: project.Documents.Any(d => d.IsOpen())))
                {
                    return;
                }

                var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
                var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
M
Manish Vasani 已提交
307
                var userDiagnosticDriver = new DiagnosticAnalyzerDriver(project, _diagnosticLogAggregator, HostDiagnosticUpdateSource, cancellationToken);
308

309
                var versions = new VersionArgument(VersionStamp.Default, semanticVersion, projectVersion);
310
                foreach (var stateSet in _stateManger.GetOrUpdateStateSets(project))
311
                {
312
                    if (userDiagnosticDriver.IsAnalyzerSuppressed(stateSet.Analyzer))
313
                    {
314
                        await HandleSuppressedAnalyzerAsync(project, stateSet, cancellationToken).ConfigureAwait(false);
315
                    }
H
Heejae Chang 已提交
316 317
                    else if (ShouldRunAnalyzerForStateType(userDiagnosticDriver, stateSet.Analyzer, StateType.Project, diagnosticIds) &&
                        (skipClosedFileChecks || ShouldRunAnalyzerForClosedFile(openedDocument: false, analyzer: stateSet.Analyzer)))
318
                    {
319
                        var data = await _executor.GetProjectAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false);
320 321
                        if (data.FromCache)
                        {
322
                            RaiseDiagnosticsUpdated(StateType.Project, project.Id, stateSet.Analyzer, new SolutionArgument(project), data.Items);
323 324 325
                            continue;
                        }

326
                        var state = stateSet.GetState(StateType.Project);
327 328
                        await state.PersistAsync(project, data.ToPersistData(), cancellationToken).ConfigureAwait(false);

329
                        RaiseDiagnosticsUpdatedIfNeeded(project, stateSet.Analyzer, data.OldItems, data.Items);
330 331 332 333 334 335 336 337 338
                    }
                }
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

339
        public override void RemoveDocument(DocumentId documentId)
340 341 342 343 344
        {
            using (Logger.LogBlock(FunctionId.Diagnostics_RemoveDocument, GetRemoveLogMessage, documentId, CancellationToken.None))
            {
                _memberRangeMap.Remove(documentId);

345
                foreach (var stateSet in _stateManger.GetStateSets(documentId.ProjectId))
346
                {
347
                    stateSet.Remove(documentId);
348

349 350
                    var solutionArgs = new SolutionArgument(null, documentId.ProjectId, documentId);
                    foreach (var stateType in s_documentScopeStateTypes)
351
                    {
352
                        RaiseDiagnosticsUpdated(stateType, documentId, stateSet.Analyzer, solutionArgs, ImmutableArray<DiagnosticData>.Empty);
353 354 355 356 357
                    }
                }
            }
        }

358
        public override void RemoveProject(ProjectId projectId)
359 360 361
        {
            using (Logger.LogBlock(FunctionId.Diagnostics_RemoveProject, GetRemoveLogMessage, projectId, CancellationToken.None))
            {
362
                foreach (var stateSet in _stateManger.GetStateSets(projectId))
363
                {
364
                    stateSet.Remove(projectId);
365 366

                    var solutionArgs = new SolutionArgument(null, projectId, null);
367
                    RaiseDiagnosticsUpdated(StateType.Project, projectId, stateSet.Analyzer, solutionArgs, ImmutableArray<DiagnosticData>.Empty);
368 369
                }
            }
370 371

            _stateManger.RemoveStateSet(projectId);
372 373
        }

374
        public override async Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, List<DiagnosticData> diagnostics, CancellationToken cancellationToken)
375 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
        {
            try
            {
                var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
                var syntaxVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
                var semanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);

                var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                var result = true;
                result &= await TryGetLatestDiagnosticsAsync(
                    StateType.Syntax, document, range, root, diagnostics, false,
                    (t, d) => t.Equals(textVersion) && d.Equals(syntaxVersion),
                    GetSyntaxDiagnosticsAsync, cancellationToken).ConfigureAwait(false);

                result &= await TryGetLatestDiagnosticsAsync(
                    StateType.Document, document, range, root, diagnostics, false,
                    (t, d) => t.Equals(textVersion) && d.Equals(semanticVersion),
                    GetSemanticDiagnosticsAsync, cancellationToken).ConfigureAwait(false);

                return result;
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

403
        public override async Task<IEnumerable<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan range, CancellationToken cancellationToken)
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
        {
            try
            {
                var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
                var syntaxVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
                var semanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);

                var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                var result = true;
                using (var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject())
                {
                    result &= await TryGetLatestDiagnosticsAsync(
                            StateType.Syntax, document, range, root, diagnostics.Object, true,
                        (t, d) => t.Equals(textVersion) && d.Equals(syntaxVersion),
                        GetSyntaxDiagnosticsAsync, cancellationToken).ConfigureAwait(false);

                    result &= await TryGetLatestDiagnosticsAsync(
                            StateType.Document, document, range, root, diagnostics.Object, true,
                        (t, d) => t.Equals(textVersion) && d.Equals(semanticVersion),
                        GetSemanticDiagnosticsAsync, cancellationToken).ConfigureAwait(false);

                    // must be always up-to-date
                    Debug.Assert(result);
                    if (diagnostics.Object.Count > 0)
                    {
                        return diagnostics.Object.ToImmutableArray();
                    }

                    return SpecializedCollections.EmptyEnumerable<DiagnosticData>();
                }
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

        private async Task<bool> TryGetLatestDiagnosticsAsync(
443
            StateType stateType, Document document, TextSpan range, SyntaxNode root,
444 445
            List<DiagnosticData> diagnostics, bool requireUpToDateDocumentDiagnostic,
            Func<VersionStamp, VersionStamp, bool> versionCheck,
446
            Func<DiagnosticAnalyzerDriver, DiagnosticAnalyzer, Task<IEnumerable<DiagnosticData>>> getDiagnostics,
447 448 449 450 451 452 453 454
            CancellationToken cancellationToken)
        {
            try
            {
                bool result = true;
                var fullSpan = root == null ? null : (TextSpan?)root.FullSpan;

                // Share the diagnostic analyzer driver across all analyzers.
M
Manish Vasani 已提交
455 456
                var spanBasedDriver = new DiagnosticAnalyzerDriver(document, range, root, _diagnosticLogAggregator, HostDiagnosticUpdateSource, cancellationToken);
                var documentBasedDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, _diagnosticLogAggregator, HostDiagnosticUpdateSource, cancellationToken);
457

458 459
                foreach (var stateSet in _stateManger.GetOrCreateStateSets(document.Project))
                {
460
                    bool supportsSemanticInSpan;
461
                    if (!spanBasedDriver.IsAnalyzerSuppressed(stateSet.Analyzer) &&
H
Heejae Chang 已提交
462
                        ShouldRunAnalyzerForStateType(spanBasedDriver, stateSet.Analyzer, stateType, out supportsSemanticInSpan))
463 464 465 466
                    {
                        var userDiagnosticDriver = supportsSemanticInSpan ? spanBasedDriver : documentBasedDriver;

                        result &= await TryGetLatestDiagnosticsAsync(
467
                            stateSet, stateType, document, range, root, diagnostics, requireUpToDateDocumentDiagnostic,
468 469 470 471 472 473 474 475 476 477 478 479 480
                            versionCheck, getDiagnostics, supportsSemanticInSpan, userDiagnosticDriver, cancellationToken).ConfigureAwait(false);
                    }
                }

                return result;
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

        private async Task<bool> TryGetLatestDiagnosticsAsync(
481
            StateSet stateSet, StateType stateType, Document document, TextSpan range, SyntaxNode root,
482 483
            List<DiagnosticData> diagnostics, bool requireUpToDateDocumentDiagnostic,
            Func<VersionStamp, VersionStamp, bool> versionCheck,
484
            Func<DiagnosticAnalyzerDriver, DiagnosticAnalyzer, Task<IEnumerable<DiagnosticData>>> getDiagnostics,
485 486 487 488 489 490 491 492 493 494
            bool supportsSemanticInSpan,
            DiagnosticAnalyzerDriver userDiagnosticDriver,
            CancellationToken cancellationToken)
        {
            try
            {
                var shouldInclude = (Func<DiagnosticData, bool>)(d => range.IntersectsWith(d.TextSpan));

                // make sure we get state even when none of our analyzer has ran yet. 
                // but this shouldn't create analyzer that doesnt belong to this project (language)
495 496 497 498 499
                var state = stateSet.GetState(stateType);

                // see whether we can use existing info
                var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
                if (existingData != null && versionCheck(existingData.TextVersion, existingData.DataVersion))
500
                {
501
                    if (existingData.Items == null)
502 503 504 505
                    {
                        return true;
                    }

506 507
                    diagnostics.AddRange(existingData.Items.Where(shouldInclude));
                    return true;
508 509 510 511 512 513 514 515
                }

                // check whether we want up-to-date document wide diagnostics
                if (stateType == StateType.Document && !supportsSemanticInSpan && !requireUpToDateDocumentDiagnostic)
                {
                    return false;
                }

516
                var dx = await getDiagnostics(userDiagnosticDriver, stateSet.Analyzer).ConfigureAwait(false);
517 518 519 520 521 522 523 524 525 526 527 528 529 530
                if (dx != null)
                {
                    // no state yet
                    diagnostics.AddRange(dx.Where(shouldInclude));
                }

                return true;
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

H
Heejae Chang 已提交
531
        private bool ShouldRunAnalyzerForClosedFile(bool openedDocument, DiagnosticAnalyzer analyzer)
532 533 534 535 536 537 538
        {
            // we have opened document, doesnt matter
            if (openedDocument)
            {
                return true;
            }

539
            return _owner.GetDiagnosticDescriptors(analyzer).Any(d => d.DefaultSeverity != DiagnosticSeverity.Hidden);
540 541
        }

H
Heejae Chang 已提交
542
        private bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzerDriver driver, DiagnosticAnalyzer analyzer,
543
            StateType stateTypeId, ImmutableHashSet<string> diagnosticIds)
544 545
        {
            bool discarded;
H
Heejae Chang 已提交
546
            return ShouldRunAnalyzerForStateType(driver, analyzer, stateTypeId, out discarded, diagnosticIds, _owner.GetDiagnosticDescriptors);
547 548
        }

H
Heejae Chang 已提交
549
        private static bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzerDriver driver, DiagnosticAnalyzer analyzer, StateType stateTypeId,
550 551
            out bool supportsSemanticInSpan, ImmutableHashSet<string> diagnosticIds = null, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getDescriptor = null)
        {
H
Heejae Chang 已提交
552
            Debug.Assert(!driver.IsAnalyzerSuppressed(analyzer));
553 554

            supportsSemanticInSpan = false;
H
Heejae Chang 已提交
555
            if (diagnosticIds != null && getDescriptor(analyzer).All(d => !diagnosticIds.Contains(d.Id)))
556 557 558 559 560 561 562
            {
                return false;
            }

            switch (stateTypeId)
            {
                case StateType.Syntax:
H
Heejae Chang 已提交
563
                    return analyzer.SupportsSyntaxDiagnosticAnalysis(driver);
564 565

                case StateType.Document:
H
Heejae Chang 已提交
566
                    return analyzer.SupportsSemanticDiagnosticAnalysis(driver, out supportsSemanticInSpan);
567 568

                case StateType.Project:
H
Heejae Chang 已提交
569
                    return analyzer.SupportsProjectDiagnosticAnalysis(driver);
570 571 572 573 574 575 576 577 578 579 580 581 582

                default:
                    throw ExceptionUtilities.Unreachable;
            }
        }

        // internal for testing purposes only.
        internal void ForceAnalyzeAllDocuments(Project project, DiagnosticAnalyzer analyzer, CancellationToken cancellationToken)
        {
            var diagnosticIds = _owner.GetDiagnosticDescriptors(analyzer).Select(d => d.Id).ToImmutableHashSet();
            ReanalyzeAllDocumentsAsync(project, diagnosticIds, cancellationToken).Wait(cancellationToken);
        }

583
        public override void LogAnalyzerCountSummary()
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 620 621 622 623 624
        {
            DiagnosticAnalyzerLogger.LogAnalyzerCrashCountSummary(_correlationId, _diagnosticLogAggregator);
            DiagnosticAnalyzerLogger.LogAnalyzerTypeCountSummary(_correlationId, _diagnosticLogAggregator);

            // reset the log aggregator
            _diagnosticLogAggregator = new DiagnosticLogAggregator(_owner);
        }

        private static bool CheckSyntaxVersions(Document document, AnalysisData existingData, VersionArgument versions)
        {
            if (existingData == null)
            {
                return false;
            }

            return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) &&
                   document.CanReusePersistedSyntaxTreeVersion(versions.DataVersion, existingData.DataVersion);
        }

        private static bool CheckSemanticVersions(Document document, AnalysisData existingData, VersionArgument versions)
        {
            if (existingData == null)
            {
                return false;
            }

            return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) &&
                   document.Project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion);
        }

        private static bool CheckSemanticVersions(Project project, AnalysisData existingData, VersionArgument versions)
        {
            if (existingData == null)
            {
                return false;
            }

            return project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion);
        }

        private void RaiseDiagnosticsUpdatedIfNeeded(
625
            StateType type, Document document, DiagnosticAnalyzer analyzer, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
626 627 628 629
        {
            var noItems = existingItems.Length == 0 && newItems.Length == 0;
            if (!noItems)
            {
630
                RaiseDiagnosticsUpdated(type, document.Id, analyzer, new SolutionArgument(document), newItems);
631 632 633
            }
        }

634 635
        private void RaiseDiagnosticsUpdatedIfNeeded(
            Project project, DiagnosticAnalyzer analyzer, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
636 637 638 639
        {
            var noItems = existingItems.Length == 0 && newItems.Length == 0;
            if (!noItems)
            {
640
                RaiseDiagnosticsUpdated(StateType.Project, project.Id, analyzer, new SolutionArgument(project), newItems);
641 642 643 644
            }
        }

        private void RaiseDiagnosticsUpdated(
645
            StateType type, object key, DiagnosticAnalyzer analyzer, SolutionArgument solution, ImmutableArray<DiagnosticData> diagnostics)
646 647 648
        {
            if (_owner != null)
            {
649
                var id = new ArgumentKey(analyzer, type, key);
650
                _owner.RaiseDiagnosticsUpdated(this,
651
                    new DiagnosticsUpdatedArgs(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId, diagnostics));
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
            }
        }

        private ImmutableArray<DiagnosticData> UpdateDocumentDiagnostics(
            AnalysisData existingData, ImmutableArray<TextSpan> range, ImmutableArray<DiagnosticData> memberDiagnostics,
            SyntaxTree tree, SyntaxNode member, int memberId)
        {
            // get old span
            var oldSpan = range[memberId];

            // get old diagnostics
            var diagnostics = existingData.Items;

            // check quick exit cases
            if (diagnostics.Length == 0 && memberDiagnostics.Length == 0)
            {
                return diagnostics;
            }

            // simple case
            if (diagnostics.Length == 0 && memberDiagnostics.Length > 0)
            {
                return memberDiagnostics;
            }

            // regular case
            var result = new List<DiagnosticData>();

            // update member location
            Contract.Requires(member.FullSpan.Start == oldSpan.Start);
            var delta = member.FullSpan.End - oldSpan.End;

            var replaced = false;
            foreach (var diagnostic in diagnostics)
            {
                if (diagnostic.TextSpan.Start < oldSpan.Start)
                {
                    result.Add(diagnostic);
                    continue;
                }

                if (!replaced)
                {
                    result.AddRange(memberDiagnostics);
                    replaced = true;
                }

                if (oldSpan.End <= diagnostic.TextSpan.Start)
                {
                    result.Add(UpdatePosition(diagnostic, tree, delta));
                    continue;
                }
            }

            // if it haven't replaced, replace it now
            if (!replaced)
            {
                result.AddRange(memberDiagnostics);
                replaced = true;
            }

            return result.ToImmutableArray();
        }

        private DiagnosticData UpdatePosition(DiagnosticData diagnostic, SyntaxTree tree, int delta)
        {
            var start = Math.Min(Math.Max(diagnostic.TextSpan.Start + delta, 0), tree.Length);
            var newSpan = new TextSpan(start, start >= tree.Length ? 0 : diagnostic.TextSpan.Length);

            var mappedLineInfo = tree.GetMappedLineSpan(newSpan);
            var originalLineInfo = tree.GetLineSpan(newSpan);

            return new DiagnosticData(
                diagnostic.Id,
                diagnostic.Category,
                diagnostic.Message,
                diagnostic.MessageFormat,
                diagnostic.Severity,
                diagnostic.DefaultSeverity,
                diagnostic.IsEnabledByDefault,
                diagnostic.WarningLevel,
                diagnostic.CustomTags,
734
                diagnostic.Properties,
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 770 771 772 773 774 775 776 777 778 779 780 781 782
                diagnostic.Workspace,
                diagnostic.ProjectId,
                diagnostic.DocumentId,
                newSpan,
                mappedFilePath: mappedLineInfo.HasMappedPath ? mappedLineInfo.Path : null,
                mappedStartLine: mappedLineInfo.StartLinePosition.Line,
                mappedStartColumn: mappedLineInfo.StartLinePosition.Character,
                mappedEndLine: mappedLineInfo.EndLinePosition.Line,
                mappedEndColumn: mappedLineInfo.EndLinePosition.Character,
                originalFilePath: originalLineInfo.Path,
                originalStartLine: originalLineInfo.StartLinePosition.Line,
                originalStartColumn: originalLineInfo.StartLinePosition.Character,
                originalEndLine: originalLineInfo.EndLinePosition.Line,
                originalEndColumn: originalLineInfo.EndLinePosition.Character,
                description: diagnostic.Description,
                helpLink: diagnostic.HelpLink);
        }

        private static IEnumerable<DiagnosticData> GetDiagnosticData(Document document, TextSpan? span, IEnumerable<Diagnostic> diagnostics)
        {
            return diagnostics != null ? diagnostics.Where(dx => ShouldIncludeDiagnostic(dx, span)).Select(d => DiagnosticData.Create(document, d)) : null;
        }

        private static bool ShouldIncludeDiagnostic(Diagnostic diagnostic, TextSpan? span)
        {
            if (diagnostic == null)
            {
                return false;
            }

            if (span == null)
            {
                return true;
            }

            if (diagnostic.Location == null)
            {
                return false;
            }

            return span.Value.Contains(diagnostic.Location.SourceSpan);
        }

        private static IEnumerable<DiagnosticData> GetDiagnosticData(Project project, IEnumerable<Diagnostic> diagnostics)
        {
            return diagnostics != null ? diagnostics.Select(d => DiagnosticData.Create(project, d)) : null;
        }

783
        private static async Task<IEnumerable<DiagnosticData>> GetSyntaxDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
784
        {
785
            using (Logger.LogBlock(FunctionId.Diagnostics_SyntaxDiagnostic, GetSyntaxLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken))
786 787 788
            {
                try
                {
789
                    Contract.ThrowIfNull(analyzer);
790

791
                    var diagnostics = await userDiagnosticDriver.GetSyntaxDiagnosticsAsync(analyzer).ConfigureAwait(false);
792 793 794 795 796 797 798 799 800
                    return GetDiagnosticData(userDiagnosticDriver.Document, userDiagnosticDriver.Span, diagnostics);
                }
                catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
                {
                    throw ExceptionUtilities.Unreachable;
                }
            }
        }

801
        private static async Task<IEnumerable<DiagnosticData>> GetSemanticDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
802
        {
803
            using (Logger.LogBlock(FunctionId.Diagnostics_SemanticDiagnostic, GetSemanticLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken))
804 805 806
            {
                try
                {
807
                    Contract.ThrowIfNull(analyzer);
808

809
                    var diagnostics = await userDiagnosticDriver.GetSemanticDiagnosticsAsync(analyzer).ConfigureAwait(false);
810 811 812 813 814 815 816 817 818
                    return GetDiagnosticData(userDiagnosticDriver.Document, userDiagnosticDriver.Span, diagnostics);
                }
                catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
                {
                    throw ExceptionUtilities.Unreachable;
                }
            }
        }

819
        private static async Task<IEnumerable<DiagnosticData>> GetProjectDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer, Action<Project, DiagnosticAnalyzer, CancellationToken> forceAnalyzeAllDocuments)
820
        {
821
            using (Logger.LogBlock(FunctionId.Diagnostics_ProjectDiagnostic, GetProjectLogMessage, userDiagnosticDriver.Project, analyzer, userDiagnosticDriver.CancellationToken))
822 823 824
            {
                try
                {
825
                    Contract.ThrowIfNull(analyzer);
826

827
                    var diagnostics = await userDiagnosticDriver.GetProjectDiagnosticsAsync(analyzer, forceAnalyzeAllDocuments).ConfigureAwait(false);
828 829 830 831 832 833 834 835 836
                    return GetDiagnosticData(userDiagnosticDriver.Project, diagnostics);
                }
                catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
                {
                    throw ExceptionUtilities.Unreachable;
                }
            }
        }

837
        private async Task ClearDocumentStatesAsync(Document document, IEnumerable<StateSet> states, CancellationToken cancellationToken)
838 839 840 841
        {
            try
            {
                // Compiler + User diagnostics
842
                foreach (var state in states)
843
                {
844
                    foreach (var stateType in s_documentScopeStateTypes)
845
                    {
846
                        await ClearDocumentStateAsync(document, state.Analyzer, stateType, state.GetState(stateType), cancellationToken).ConfigureAwait(false);
847 848 849 850 851 852 853 854 855
                    }
                }
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

856
        private async Task ClearDocumentStateAsync(Document document, DiagnosticAnalyzer analyzer, StateType type, DiagnosticState state, CancellationToken cancellationToken)
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
        {
            try
            {
                // remove memory cache
                state.Remove(document.Id);

                // remove persistent cache
                await state.PersistAsync(document, AnalysisData.Empty, cancellationToken).ConfigureAwait(false);

                // raise diagnostic updated event
                var documentId = type == StateType.Project ? null : document.Id;
                var projectId = document.Project.Id;
                var key = documentId ?? (object)projectId;
                var solutionArgs = new SolutionArgument(document.Project.Solution, projectId, documentId);

872
                RaiseDiagnosticsUpdated(type, key, analyzer, solutionArgs, ImmutableArray<DiagnosticData>.Empty);
873 874 875 876 877 878 879
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

880 881 882 883 884 885 886 887 888 889 890 891 892 893
        private async Task ClearProjectStatesAsync(Project project, IEnumerable<StateSet> states, CancellationToken cancellationToken)
        {
            foreach (var document in project.Documents)
            {
                await ClearDocumentStatesAsync(document, states, cancellationToken).ConfigureAwait(false);
            }

            foreach (var state in states)
            {
                await ClearProjectStateAsync(project, state.Analyzer, state.GetState(StateType.Project), cancellationToken).ConfigureAwait(false);
            }
        }

        private async Task ClearProjectStateAsync(Project project, DiagnosticAnalyzer analyzer, DiagnosticState state, CancellationToken cancellationToken)
894 895 896 897 898 899 900 901 902 903 904
        {
            try
            {
                // remove memory cache
                state.Remove(project.Id);

                // remove persistent cache
                await state.PersistAsync(project, AnalysisData.Empty, cancellationToken).ConfigureAwait(false);

                // raise diagnostic updated event
                var solutionArgs = new SolutionArgument(project);
905
                RaiseDiagnosticsUpdated(StateType.Project, project.Id, analyzer, solutionArgs, ImmutableArray<DiagnosticData>.Empty);
906 907 908 909 910 911 912
            }
            catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

913
        private async Task HandleSuppressedAnalyzerAsync(Document document, StateSet stateSet, StateType type, CancellationToken cancellationToken)
914
        {
915
            var state = stateSet.GetState(type);
916 917 918
            var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
            if (existingData != null && existingData.Items.Length > 0)
            {
919
                await ClearDocumentStateAsync(document, stateSet.Analyzer, type, state, cancellationToken).ConfigureAwait(false);
920 921 922
            }
        }

923
        private async Task HandleSuppressedAnalyzerAsync(Project project, StateSet stateSet, CancellationToken cancellationToken)
924
        {
925
            var state = stateSet.GetState(StateType.Project);
926 927 928
            var existingData = await state.TryGetExistingDataAsync(project, cancellationToken).ConfigureAwait(false);
            if (existingData != null && existingData.Items.Length > 0)
            {
929
                await ClearProjectStateAsync(project, stateSet.Analyzer, state, cancellationToken).ConfigureAwait(false);
930 931 932
            }
        }

933
        private static string GetSyntaxLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer)
934
        {
935
            return string.Format("syntax: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString());
936 937
        }

938
        private static string GetSemanticLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer)
939
        {
940
            return string.Format("semantic: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString());
941 942
        }

943
        private static string GetProjectLogMessage(Project project, DiagnosticAnalyzer analyzer)
944
        {
945
            return string.Format("project: {0}, {1}", project.FilePath ?? project.Name, analyzer.ToString());
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
        }

        private static string GetResetLogMessage(Document document)
        {
            return string.Format("document reset: {0}", document.FilePath ?? document.Name);
        }

        private static string GetOpenLogMessage(Document document)
        {
            return string.Format("document open: {0}", document.FilePath ?? document.Name);
        }

        private static string GetRemoveLogMessage(DocumentId id)
        {
            return string.Format("document remove: {0}", id.ToString());
        }

        private static string GetRemoveLogMessage(ProjectId id)
        {
            return string.Format("project remove: {0}", id.ToString());
        }

        #region unused 
969
        public override Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
970 971 972 973 974 975
        {
            return SpecializedTasks.EmptyTask;
        }
        #endregion
    }
}