Example #1
0
 public PreviewSolutionCrawlerRegistrationServiceFactory(IDiagnosticAnalyzerService analyzerService)
 {
     // this service is directly tied to DiagnosticAnalyzerService and
     // depends on its implementation.
     _analyzerService = analyzerService as DiagnosticAnalyzerService;
     Contract.ThrowIfNull(_analyzerService);
 }
Example #2
0
 public TestDiagnosticAnalyzerDriver(Workspace workspace, Project project, bool includeSuppressedDiagnostics = false)
 {
     Assert.IsType <MockDiagnosticUpdateSourceRegistrationService>(((IMefHostExportProvider)workspace.Services.HostServices).GetExportedValue <IDiagnosticUpdateSourceRegistrationService>());
     _diagnosticAnalyzerService = Assert.IsType <DiagnosticAnalyzerService>(((IMefHostExportProvider)workspace.Services.HostServices).GetExportedValue <IDiagnosticAnalyzerService>());
     _diagnosticAnalyzerService.CreateIncrementalAnalyzer(project.Solution.Workspace);
     _includeSuppressedDiagnostics = includeSuppressedDiagnostics;
 }
        public DiagnosticIncrementalAnalyzer(
            DiagnosticAnalyzerService analyzerService,
            int correlationId,
            Workspace workspace,
            HostDiagnosticAnalyzers hostAnalyzers,
            DiagnosticAnalyzerInfoCache analyzerInfoCache,
            AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
        {
            Contract.ThrowIfNull(analyzerService);

            AnalyzerService             = analyzerService;
            Workspace                   = workspace;
            HostAnalyzers               = hostAnalyzers;
            DiagnosticAnalyzerInfoCache = analyzerInfoCache;
            HostDiagnosticUpdateSource  = hostDiagnosticUpdateSource;
            PersistentStorageService    = workspace.Services.GetRequiredService <IPersistentStorageService>();

            _correlationId = correlationId;

            _stateManager = new StateManager(hostAnalyzers, PersistentStorageService, analyzerInfoCache);
            _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;
            _telemetry = new DiagnosticAnalyzerTelemetry();

            _diagnosticAnalyzerRunner         = new InProcOrRemoteHostAnalyzerRunner(analyzerService.Listener, analyzerInfoCache, HostDiagnosticUpdateSource);
            _projectCompilationsWithAnalyzers = new ConditionalWeakTable <Project, CompilationWithAnalyzers?>();
        }
        private async System.Threading.Tasks.Task SyncBuildErrorsAndReportAsync(
            DiagnosticAnalyzerService diagnosticService, Solution solution, ImmutableDictionary <ProjectId, ImmutableArray <DiagnosticData> > map)
        {
            // make those errors live errors
            await diagnosticService.SynchronizeWithBuildAsync(_workspace, map).ConfigureAwait(false);

            // raise events for ones left-out
            var buildErrors = GetBuildErrors().Except(map.Values.SelectMany(v => v)).GroupBy(k => k.DocumentId);

            foreach (var group in buildErrors)
            {
                if (group.Key == null)
                {
                    foreach (var projectGroup in group.GroupBy(g => g.ProjectId))
                    {
                        Contract.ThrowIfNull(projectGroup.Key);
                        ReportBuildErrors(projectGroup.Key, solution, projectGroup.ToImmutableArray());
                    }

                    continue;
                }

                ReportBuildErrors(group.Key, solution, group.ToImmutableArray());
            }
        }
        private static void GetTagSource(TestWorkspace workspace, DiagnosticServiceWaiter diagnosticWaiter, ErrorSquiggleWaiter squiggleWaiter, out Analyzer analyzer, out DiagnosticAnalyzerService analyzerService, out DiagnosticsSquiggleTaggerProvider.TagSource taggerSource)
        {
            analyzer = new Analyzer();
            var analyzerMap = new Dictionary <string, ImmutableArray <DiagnosticAnalyzer> >()
            {
                { LanguageNames.CSharp, ImmutableArray.Create <DiagnosticAnalyzer>(analyzer) }
            };

            analyzerService = new DiagnosticAnalyzerService(analyzerMap.ToImmutableDictionary());

            var diagnosticListeners = SpecializedCollections.SingletonEnumerable(new Lazy <IAsynchronousOperationListener, FeatureMetadata>(
                                                                                     () => diagnosticWaiter, new FeatureMetadata(new Dictionary <string, object>()
            {
                { "FeatureName", FeatureAttribute.DiagnosticService }
            })));

            var diagnosticService = new DiagnosticService(SpecializedCollections.SingletonEnumerable <IDiagnosticUpdateSource>(analyzerService), diagnosticListeners);

            var document = workspace.Documents.First();
            var buffer   = document.GetTextBuffer();

            var foregroundService = new TestForegroundNotificationService();
            var optionsService    = workspace.Services.GetService <IOptionService>();

            taggerSource = new DiagnosticsSquiggleTaggerProvider.TagSource(buffer, foregroundService, diagnosticService, optionsService, squiggleWaiter);
        }
        public void TestGetFirstDiagnosticWithFixAsync()
        {
            var diagnosticService = new DiagnosticAnalyzerService(DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());

            var fixers     = CreateFixers();
            var fixService = new CodeFixService(
                diagnosticService, fixers, SpecializedCollections.EmptyEnumerable <Lazy <ISuppressionFixProvider, CodeChangeProviderMetadata> >());

            var code = @"
    a
";

            using (var workspace =
                       CSharpWorkspaceFactory.CreateWorkspaceFromFile(code))
            {
                var incrementalAnalzyer = (IIncrementalAnalyzerProvider)diagnosticService;

                // register diagnostic engine to solution crawler
                var analyzer = incrementalAnalzyer.CreateIncrementalAnalyzer(workspace);

                var reference = new MockAnalyzerReference();
                var project   = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference);
                var document  = project.Documents.Single();
                var unused    = fixService.GetFirstDiagnosticWithFixAsync(document, TextSpan.FromBounds(0, 0), CancellationToken.None).Result;

                var fixer1 = fixers.Single().Value as MockFixer;
                var fixer2 = reference.Fixer as MockFixer;

                // check to make sure both of them are called.
                Assert.True(fixer1.Called);
                Assert.True(fixer2.Called);
            }
        }
 public DiagnosticIncrementalAnalyzer(DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, AnalyzerManager analyzerManager)
 {
     _correlationId = correlationId;
     _owner = owner;
     _workspace = workspace;
     _analyzerManager = analyzerManager;
 }
        private DiagnosticTaggerWrapper(TestWorkspace workspace, DiagnosticAnalyzerService analyzerService, IDiagnosticUpdateSource updateSource)
        {
            if (updateSource == null)
            {
                updateSource = analyzerService;
            }

            this.workspace = workspace;

            this.registrationService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>();
            registrationService.Register(workspace);

            this.asyncListener = new AsynchronousOperationListener();
            var listeners = AsynchronousOperationListener.CreateListeners(
                ValueTuple.Create(FeatureAttribute.DiagnosticService, asyncListener),
                ValueTuple.Create(FeatureAttribute.ErrorSquiggles, asyncListener));

            this.analyzerService = analyzerService;
            var diagnosticService = new DiagnosticService(SpecializedCollections.SingletonEnumerable(updateSource), listeners);

            this.TaggerProvider = new DiagnosticsSquiggleTaggerProvider(
                workspace.Services.GetService <IOptionService>(), diagnosticService,
                workspace.GetService <IForegroundNotificationService>(), listeners);

            if (analyzerService != null)
            {
                this.incrementalAnalyzers   = ImmutableArray.Create(analyzerService.CreateIncrementalAnalyzer(workspace));
                this.solutionCrawlerService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>() as SolutionCrawlerRegistrationService;
            }
        }
Example #9
0
 public DiagnosticIncrementalAnalyzer(DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, AnalyzerManager analyzerManager)
 {
     _correlationId   = correlationId;
     _owner           = owner;
     _workspace       = workspace;
     _analyzerManager = analyzerManager;
 }
 public DiagnosticIncrementalAnalyzer(DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, WorkspaceAnalyzerManager workspaceAnalyzerManager, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
     : base(workspace, hostDiagnosticUpdateSource)
 {
     _correlationId            = correlationId;
     _owner                    = owner;
     _workspaceAnalyzerManager = workspaceAnalyzerManager;
 }
Example #11
0
        private async Task SyncBuildErrorsAndReportAsync(DiagnosticAnalyzerService diagnosticService, InProgressState inProgressState)
        {
            var solution = inProgressState.Solution;
            var map      = await inProgressState.GetLiveDiagnosticsPerProjectAsync().ConfigureAwait(false);

            // make those errors live errors
            await diagnosticService.SynchronizeWithBuildAsync(_workspace, map).ConfigureAwait(false);

            // raise events for ones left-out
            var buildErrors = GetBuildErrors().Except(map.Values.SelectMany(v => v)).GroupBy(k => k.DocumentId);

            foreach (var group in buildErrors)
            {
                if (group.Key == null)
                {
                    foreach (var projectGroup in group.GroupBy(g => g.ProjectId))
                    {
                        Contract.ThrowIfNull(projectGroup.Key);
                        ReportBuildErrors(projectGroup.Key, solution, projectGroup.ToImmutableArray());
                    }

                    continue;
                }

                ReportBuildErrors(group.Key, solution, group.ToImmutableArray());
            }
        }
Example #12
0
        private static bool CheckTelemetry(DiagnosticAnalyzerService service, DiagnosticAnalyzer analyzer)
        {
            if (analyzer.IsCompilerAnalyzer())
            {
                return(true);
            }

            ImmutableArray <DiagnosticDescriptor> diagDescriptors;

            try
            {
                // SupportedDiagnostics is potentially user code and can throw an exception.
                diagDescriptors = service != null?service.GetDiagnosticDescriptors(analyzer) : analyzer.SupportedDiagnostics;
            }
            catch (Exception)
            {
                return(false);
            }

            if (diagDescriptors == null)
            {
                return(false);
            }

            // find if the first diagnostic in this analyzer allows telemetry
            DiagnosticDescriptor diagnostic = diagDescriptors.Length > 0 ? diagDescriptors[0] : null;

            return(diagnostic == null ? false : diagnostic.CustomTags.Any(t => t == WellKnownDiagnosticTags.Telemetry));
        }
        public override async Task SynchronizeWithBuildAsync(DiagnosticAnalyzerService.BatchUpdateToken token, Project project, ImmutableArray<DiagnosticData> diagnostics)
        {
            if (!PreferBuildErrors(project.Solution.Workspace))
            {
                // prefer live errors over build errors
                return;
            }

            using (var poolObject = SharedPools.Default<HashSet<string>>().GetPooledObject())
            {
                var lookup = CreateDiagnosticIdLookup(diagnostics);

                foreach (var stateSet in _stateManager.GetBuildOnlyStateSets(token.GetCache(_stateManager, s_cacheCreator), project))
                {
                    var descriptors = HostAnalyzerManager.GetDiagnosticDescriptors(stateSet.Analyzer);
                    var liveDiagnostics = ConvertToLiveDiagnostics(lookup, descriptors, poolObject.Object);

                    // we are using Default so that things like LB can't use cached information
                    var projectTextVersion = VersionStamp.Default;
                    var semanticVersion = await project.GetDependentSemanticVersionAsync(CancellationToken.None).ConfigureAwait(false);

                    var state = stateSet.GetState(StateType.Project);
                    var existingDiagnostics = await state.TryGetExistingDataAsync(project, CancellationToken.None).ConfigureAwait(false);

                    var mergedDiagnostics = MergeDiagnostics(liveDiagnostics, GetExistingDiagnostics(existingDiagnostics));
                    await state.PersistAsync(project, new AnalysisData(projectTextVersion, semanticVersion, mergedDiagnostics), CancellationToken.None).ConfigureAwait(false);
                    RaiseDiagnosticsCreated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), mergedDiagnostics);
                }
            }
        }
Example #14
0
        public PreviewSolutionCrawlerRegistrationServiceFactory(IDiagnosticAnalyzerService analyzerService, IAsynchronousOperationListenerProvider listenerProvider)
        {
            // this service is directly tied to DiagnosticAnalyzerService and
            // depends on its implementation.
            _analyzerService = (DiagnosticAnalyzerService)analyzerService;

            _listener = listenerProvider.GetListener(FeatureAttribute.DiagnosticService);
        }
Example #15
0
        public static bool AllowsTelemetry(DiagnosticAnalyzerService service, DiagnosticAnalyzer analyzer, ProjectId projectIdOpt)
        {
            if (s_telemetryCache.TryGetValue(analyzer, out var value))
            {
                return(value.Value);
            }

            return(s_telemetryCache.GetValue(analyzer, a => new StrongBox <bool>(CheckTelemetry(service, a))).Value);
        }
        public DiagnosticIncrementalAnalyzer(DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, AnalyzerManager analyzerManager)
        {
            _owner = owner;
            _correlationId = correlationId;
            _memberRangeMap = new MemberRangeMap();
            _analyzersAndState = new DiagnosticAnalyzersAndStates(this, workspace, analyzerManager);
            _executor = new AnalyzerExecutor(this);

            _diagnosticLogAggregator = new DiagnosticLogAggregator(_owner);
        }
Example #17
0
        public DiagnosticIncrementalAnalyzer(DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, AnalyzerManager analyzerManager)
        {
            _owner             = owner;
            _correlationId     = correlationId;
            _memberRangeMap    = new MemberRangeMap();
            _analyzersAndState = new DiagnosticAnalyzersAndStates(this, workspace, analyzerManager);
            _executor          = new AnalyzerExecutor(this);

            _diagnosticLogAggregator = new DiagnosticLogAggregator(_owner);
        }
            public InProcOrRemoteHostAnalyzerRunner(DiagnosticAnalyzerService owner, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
            {
                _owner = owner;
                _hostDiagnosticUpdateSourceOpt = hostDiagnosticUpdateSource;

                // currently option is a bit wierd since it is not part of snapshot and
                // we can't load all options without loading all language specific dlls.
                // we have tracking issue for this.
                // https://github.com/dotnet/roslyn/issues/13643
                _lastOptionSetPerLanguage = new ConcurrentDictionary <string, ValueTuple <OptionSet, CustomAsset> >();
            }
        protected static IEnumerable <ITagSpan <IErrorTag> > GetErrorSpans(TestWorkspace workspace, ImmutableDictionary <string, ImmutableArray <DiagnosticAnalyzer> > analyzerMap = null)
        {
            var registrationService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>();

            registrationService.Register(workspace);

            var diagnosticWaiter    = new DiagnosticServiceWaiter();
            var diagnosticListeners = SpecializedCollections.SingletonEnumerable(new Lazy <IAsynchronousOperationListener, FeatureMetadata>(
                                                                                     () => diagnosticWaiter, new FeatureMetadata(new Dictionary <string, object>()
            {
                { "FeatureName", FeatureAttribute.DiagnosticService }
            })));

            var optionsService = workspace.Services.GetService <IOptionService>();

            DiagnosticAnalyzerService analyzerService = null;

            if (analyzerMap == null || analyzerMap.Count == 0)
            {
                var compilerAnalyzersMap = DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap();
                analyzerService = new TestDiagnosticAnalyzerService(compilerAnalyzersMap);
            }
            else
            {
                analyzerService = new TestDiagnosticAnalyzerService(analyzerMap);
            }

            var diagnosticService = new DiagnosticService(SpecializedCollections.SingletonEnumerable <IDiagnosticUpdateSource>(analyzerService), diagnosticListeners);

            var document = workspace.Documents.First();
            var buffer   = document.GetTextBuffer();

            var squiggleWaiter    = new ErrorSquiggleWaiter();
            var foregroundService = new TestForegroundNotificationService();
            var taggerSource      = new DiagnosticsSquiggleTaggerProvider.TagSource(buffer, foregroundService, diagnosticService, optionsService, squiggleWaiter);

            var service = workspace.Services.GetService <ISolutionCrawlerRegistrationService>() as SolutionCrawlerRegistrationService;

            service.WaitUntilCompletion_ForTestingPurposesOnly(workspace, ImmutableArray.Create(analyzerService.CreateIncrementalAnalyzer(workspace)));

            diagnosticWaiter.CreateWaitTask().PumpingWait();
            squiggleWaiter.CreateWaitTask().PumpingWait();

            var snapshot     = buffer.CurrentSnapshot;
            var intervalTree = taggerSource.GetTagIntervalTreeForBuffer(buffer);
            var spans        = intervalTree.GetIntersectingSpans(new SnapshotSpan(snapshot, 0, snapshot.Length)).ToImmutableArray();

            taggerSource.TestOnly_Dispose();

            registrationService.Unregister(workspace);

            return(spans);
        }
        public TestDiagnosticAnalyzerDriver(Workspace workspace, bool includeSuppressedDiagnostics = false)
        {
            var mefServices = (IMefHostExportProvider)workspace.Services.HostServices;

            Assert.IsType <MockDiagnosticUpdateSourceRegistrationService>(mefServices.GetExportedValue <IDiagnosticUpdateSourceRegistrationService>());
            _diagnosticAnalyzerService = Assert.IsType <DiagnosticAnalyzerService>(mefServices.GetExportedValue <IDiagnosticAnalyzerService>());

            GlobalOptions   = mefServices.GetExportedValue <IGlobalOptionService>();
            FallbackOptions = GlobalOptions.CreateProvider();

            _diagnosticAnalyzerService.CreateIncrementalAnalyzer(workspace);
            _includeSuppressedDiagnostics = includeSuppressedDiagnostics;
        }
Example #21
0
        private static async System.Threading.Tasks.Task CleanupAllLiveErrors(
            DiagnosticAnalyzerService diagnosticService, IDisposable batchUpdateToken,
            Solution solution, InprogressState state, IEnumerable <Project> projects)
        {
            foreach (var project in projects)
            {
                foreach (var document in project.Documents)
                {
                    await SynchronizeWithBuildAsync(diagnosticService, batchUpdateToken, document, ImmutableArray <DiagnosticData> .Empty).ConfigureAwait(false);
                }

                await SynchronizeWithBuildAsync(diagnosticService, batchUpdateToken, project, ImmutableArray <DiagnosticData> .Empty).ConfigureAwait(false);
            }
        }
Example #22
0
 public DiagnosticIncrementalAnalyzer(
     DiagnosticAnalyzerService owner,
     int correlationId,
     Workspace workspace,
     HostAnalyzerManager analyzerManager,
     AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
     : base(owner, workspace, analyzerManager, hostDiagnosticUpdateSource)
 {
     _correlationId  = correlationId;
     _memberRangeMap = new MemberRangeMap();
     _executor       = new AnalyzerExecutor(this);
     _eventQueue     = new SimpleTaskQueue(TaskScheduler.Default);
     _stateManager   = new StateManager(analyzerManager);
     _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;
 }
        public DiagnosticIncrementalAnalyzer(
            DiagnosticAnalyzerService owner,
            int correlationId,
            Workspace workspace,
            HostAnalyzerManager analyzerManager,
            AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
            : base(owner, workspace, analyzerManager, hostDiagnosticUpdateSource)
        {
            _correlationId = correlationId;
            _memberRangeMap = new MemberRangeMap();
            _executor = new AnalyzerExecutor(this);

            _stateManager = new StateManager(analyzerManager);
            _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;
        }
Example #24
0
        public DiagnosticIncrementalAnalyzer(
            DiagnosticAnalyzerService owner,
            int correlationId,
            Workspace workspace,
            WorkspaceAnalyzerManager workspaceAnalyzerManager,
            AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
            : base(workspace, hostDiagnosticUpdateSource)
        {
            _owner             = owner;
            _correlationId     = correlationId;
            _memberRangeMap    = new MemberRangeMap();
            _analyzersAndState = new DiagnosticAnalyzersAndStates(this, workspace, workspaceAnalyzerManager);
            _executor          = new AnalyzerExecutor(this);

            _diagnosticLogAggregator = new DiagnosticLogAggregator(_owner);
        }
 public DiagnosticIncrementalAnalyzer(
     DiagnosticAnalyzerService owner,
     int correlationId,
     Workspace workspace,
     HostAnalyzerManager analyzerManager,
     AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
     : base(owner, workspace, analyzerManager, hostDiagnosticUpdateSource)
 {
     _correlationId = correlationId;
     _memberRangeMap = new MemberRangeMap();
     _executor = new AnalyzerExecutor(this);
     _eventQueue = new SimpleTaskQueue(TaskScheduler.Default);
     _stateManager = new StateManager(analyzerManager);
     _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;
     _solutionCrawlerAnalysisState = new SolutionCrawlerAnalysisState(analyzerManager);
 }
        public DiagnosticIncrementalAnalyzer(
            DiagnosticAnalyzerService owner,
            int correlationId,
            Workspace workspace,
            HostAnalyzerManager hostAnalyzerManager,
            AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
            : base(owner, workspace, hostAnalyzerManager, hostDiagnosticUpdateSource)
        {
            _correlationId = correlationId;

            _stateManager = new StateManager(hostAnalyzerManager);
            _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;

            _executor           = new Executor(this);
            _compilationManager = new CompilationManager(this);
        }
Example #27
0
        private static async System.Threading.Tasks.Task SynchronizeWithBuildAsync <T>(
            DiagnosticAnalyzerService diagnosticService, IDisposable batchUpdateToken,
            T item, ImmutableArray <DiagnosticData> liveErrors)
        {
            var project = item as Project;

            if (project != null)
            {
                await diagnosticService.SynchronizeWithBuildAsync(batchUpdateToken, project, liveErrors).ConfigureAwait(false);

                return;
            }

            // must be not null
            var document = item as Document;
            await diagnosticService.SynchronizeWithBuildAsync(batchUpdateToken, document, liveErrors).ConfigureAwait(false);
        }
Example #28
0
        private static void GetDocumentAndExtensionManager(
            DiagnosticAnalyzerService diagnosticService,
            TestWorkspace workspace,
            out Document document,
            out EditorLayerExtensionManager.ExtensionManager extensionManager,
            MockAnalyzerReference?analyzerReference = null)
        {
            var incrementalAnalyzer = (IIncrementalAnalyzerProvider)diagnosticService;

            // register diagnostic engine to solution crawler
            _ = incrementalAnalyzer.CreateIncrementalAnalyzer(workspace);

            var reference = analyzerReference ?? new MockAnalyzerReference();
            var project   = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference);

            document         = project.Documents.Single();
            extensionManager = (EditorLayerExtensionManager.ExtensionManager)document.Project.Solution.Workspace.Services.GetRequiredService <IExtensionManager>();
        }
        public override async Task SynchronizeWithBuildAsync(DiagnosticAnalyzerService.BatchUpdateToken token, Document document, ImmutableArray<DiagnosticData> diagnostics)
        {
            var workspace = document.Project.Solution.Workspace;
            if (!PreferBuildErrors(workspace))
            {
                // prefer live errors over build errors
                return;
            }

            // check whether, for opened documents, we want to prefer live diagnostics
            if (PreferLiveErrorsOnOpenedFiles(workspace) && workspace.IsDocumentOpen(document.Id))
            {
                // enqueue re-analysis of open documents.
                this.Owner.Reanalyze(workspace, documentIds: SpecializedCollections.SingletonEnumerable(document.Id), highPriority: true);
                return;
            }

            using (var poolObject = SharedPools.Default<HashSet<string>>().GetPooledObject())
            {
                var lookup = CreateDiagnosticIdLookup(diagnostics);

                foreach (var stateSet in _stateManager.GetBuildOnlyStateSets(token.GetCache(_stateManager, s_cacheCreator), document.Project))
                {
                    // we are using Default so that things like LB can't use cached information
                    var textVersion = VersionStamp.Default;
                    var semanticVersion = await document.Project.GetDependentSemanticVersionAsync(CancellationToken.None).ConfigureAwait(false);

                    // clear document and project live errors
                    await PersistAndReportAsync(stateSet, StateType.Project, document, textVersion, semanticVersion, ImmutableArray<DiagnosticData>.Empty).ConfigureAwait(false);
                    await PersistAndReportAsync(stateSet, StateType.Syntax, document, textVersion, semanticVersion, ImmutableArray<DiagnosticData>.Empty).ConfigureAwait(false);

                    var descriptors = HostAnalyzerManager.GetDiagnosticDescriptors(stateSet.Analyzer);
                    var liveDiagnostics = ConvertToLiveDiagnostics(lookup, descriptors, poolObject.Object);

                    // REVIEW: for now, we are putting build error in document state rather than creating its own state.
                    //         reason is so that live error can take over it as soon as possible
                    //         this also means there can be slight race where it will clean up eventually. if live analysis runs for syntax but didn't run
                    //         for document yet, then we can have duplicated entries in the error list until live analysis catch.
                    await PersistAndReportAsync(stateSet, StateType.Document, document, textVersion, semanticVersion, liveDiagnostics).ConfigureAwait(false);
                }
            }
        }
Example #30
0
        private async System.Threading.Tasks.Task SyncBuildErrorsAndReportAsync <T>(
            DiagnosticAnalyzerService diagnosticService, IDisposable batchUpdateToken, Solution solution,
            Func <DiagnosticData, bool> liveDiagnosticChecker, IEnumerable <KeyValuePair <T, HashSet <DiagnosticData> > > items)
        {
            foreach (var kv in items)
            {
                // get errors that can be reported by live diagnostic analyzer
                var liveErrors = kv.Value.Where(liveDiagnosticChecker).ToImmutableArray();

                // make those errors live errors
                await SynchronizeWithBuildAsync(diagnosticService, batchUpdateToken, kv.Key, liveErrors).ConfigureAwait(false);

                // raise events for ones left-out
                if (liveErrors.Length != kv.Value.Count)
                {
                    var buildErrors = kv.Value.Except(liveErrors).ToImmutableArray();
                    ReportBuildErrors(kv.Key, buildErrors);
                }
            }
        }
        private async System.Threading.Tasks.Task CleanupAllLiveErrorsIfNeededAsync(DiagnosticAnalyzerService diagnosticService, Solution solution, InprogressState state)
        {
            if (_workspace.Options.GetOption(InternalDiagnosticsOptions.BuildErrorIsTheGod))
            {
                await CleanupAllLiveErrors(diagnosticService, solution.ProjectIds).ConfigureAwait(false);

                return;
            }

            if (_workspace.Options.GetOption(InternalDiagnosticsOptions.ClearLiveErrorsForProjectBuilt))
            {
                await CleanupAllLiveErrors(diagnosticService, state.GetProjectsBuilt(solution)).ConfigureAwait(false);

                return;
            }

            await CleanupAllLiveErrors(diagnosticService, state.GetProjectsWithoutErrors(solution)).ConfigureAwait(false);

            return;
        }
        public DiagnosticIncrementalAnalyzer(
            DiagnosticAnalyzerService analyzerService,
            int correlationId,
            Workspace workspace,
            DiagnosticAnalyzerInfoCache analyzerInfoCache)
        {
            Contract.ThrowIfNull(analyzerService);

            AnalyzerService          = analyzerService;
            Workspace                = workspace;
            _documentTrackingService = workspace.Services.GetRequiredService <IDocumentTrackingService>();

            _correlationId = correlationId;

            _stateManager = new StateManager(workspace, analyzerInfoCache);
            _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;
            _telemetry = new DiagnosticAnalyzerTelemetry();

            _diagnosticAnalyzerRunner         = new InProcOrRemoteHostAnalyzerRunner(analyzerInfoCache, analyzerService.Listener);
            _projectCompilationsWithAnalyzers = new ConditionalWeakTable <Project, CompilationWithAnalyzers?>();
        }
Example #33
0
        private DiagnosticTaggerWrapper(
            TestWorkspace workspace,
            Dictionary <string, DiagnosticAnalyzer[]> analyzerMap,
            IDiagnosticUpdateSource updateSource,
            bool createTaggerProvider)
        {
            _asyncListener = new AsynchronousOperationListener();
            _listeners     = AsynchronousOperationListener.CreateListeners(
                ValueTuple.Create(FeatureAttribute.DiagnosticService, _asyncListener),
                ValueTuple.Create(FeatureAttribute.ErrorSquiggles, _asyncListener));

            if (analyzerMap != null || updateSource == null)
            {
                AnalyzerService = CreateDiagnosticAnalyzerService(analyzerMap, _asyncListener);
            }

            if (updateSource == null)
            {
                updateSource = AnalyzerService;
            }

            _workspace = workspace;

            _registrationService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>();
            _registrationService.Register(workspace);

            DiagnosticService = new DiagnosticService(_listeners);
            DiagnosticService.Register(updateSource);

            if (createTaggerProvider)
            {
                var taggerProvider = this.TaggerProvider;
            }

            if (AnalyzerService != null)
            {
                _incrementalAnalyzers   = ImmutableArray.Create(AnalyzerService.CreateIncrementalAnalyzer(workspace));
                _solutionCrawlerService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>() as SolutionCrawlerRegistrationService;
            }
        }
Example #34
0
        private DiagnosticTaggerWrapper(
            TestWorkspace workspace,
            Dictionary <string, DiagnosticAnalyzer[]> analyzerMap,
            IDiagnosticUpdateSource updateSource,
            bool createTaggerProvider)
        {
            _threadingContext = workspace.GetService <IThreadingContext>();
            _listenerProvider = workspace.GetService <IAsynchronousOperationListenerProvider>();

            if (analyzerMap != null || updateSource == null)
            {
                AnalyzerService = CreateDiagnosticAnalyzerService(analyzerMap, _listenerProvider.GetListener(FeatureAttribute.DiagnosticService));
            }

            if (updateSource == null)
            {
                updateSource = AnalyzerService;
            }

            _workspace = workspace;

            _registrationService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>();
            _registrationService.Register(workspace);

            DiagnosticService = new DiagnosticService(_listenerProvider, Array.Empty <Lazy <IEventListener, EventListenerMetadata> >());
            DiagnosticService.Register(updateSource);

            if (createTaggerProvider)
            {
                var taggerProvider = this.TaggerProvider;
            }

            if (AnalyzerService != null)
            {
                _incrementalAnalyzers   = ImmutableArray.Create(AnalyzerService.CreateIncrementalAnalyzer(workspace));
                _solutionCrawlerService = workspace.Services.GetService <ISolutionCrawlerRegistrationService>() as SolutionCrawlerRegistrationService;
            }
        }
Example #35
0
        public DiagnosticIncrementalAnalyzer(
            DiagnosticAnalyzerService owner,
            int correlationId,
            Workspace workspace,
            HostAnalyzerManager hostAnalyzerManager,
            AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
        {
            Contract.ThrowIfNull(owner);

            Owner                      = owner;
            Workspace                  = workspace;
            HostAnalyzerManager        = hostAnalyzerManager;
            HostDiagnosticUpdateSource = hostDiagnosticUpdateSource;
            DiagnosticLogAggregator    = new DiagnosticLogAggregator(owner);

            _correlationId = correlationId;

            _stateManager = new StateManager(hostAnalyzerManager);
            _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;

            _executor           = new Executor(this);
            _compilationManager = new CompilationManager(this);
        }
        public DiagnosticIncrementalAnalyzer(
            DiagnosticAnalyzerService analyzerService,
            int correlationId,
            Workspace workspace,
            DiagnosticAnalyzerInfoCache analyzerInfoCache,
            AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
        {
            Contract.ThrowIfNull(analyzerService);

            AnalyzerService             = analyzerService;
            Workspace                   = workspace;
            DiagnosticAnalyzerInfoCache = analyzerInfoCache;
            HostDiagnosticUpdateSource  = hostDiagnosticUpdateSource;
            DiagnosticLogAggregator     = new DiagnosticLogAggregator(analyzerService);

            _correlationId = correlationId;

            _stateManager = new StateManager(analyzerInfoCache);
            _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;

            _diagnosticAnalyzerRunner         = new InProcOrRemoteHostAnalyzerRunner(AnalyzerService, HostDiagnosticUpdateSource);
            _projectCompilationsWithAnalyzers = new ConditionalWeakTable <Project, CompilationWithAnalyzers?>();
        }
 public override Task SynchronizeWithBuildAsync(DiagnosticAnalyzerService.BatchUpdateToken token, Document document, ImmutableArray<DiagnosticData> diagnostics)
 {
     // V2 engine doesn't do anything. 
     // it means live error always win over build errors. build errors that can't be reported by live analyzer
     // are already taken cared by engine
     return SpecializedTasks.EmptyTask;
 }
 public DiagnosticLogAggregator(DiagnosticAnalyzerService owner)
 {
     _owner = owner;
     _analyzerInfoMap = ImmutableDictionary<Type, AnalyzerInfo>.Empty;
 }
        private static bool CheckTelemetry(DiagnosticAnalyzerService service, DiagnosticAnalyzer analyzer)
        {
            if (analyzer.IsCompilerAnalyzer())
            {
                return true;
            }

            ImmutableArray<DiagnosticDescriptor> diagDescriptors;
            try
            {
                // SupportedDiagnostics is potentially user code and can throw an exception.
                diagDescriptors = service != null ? service.GetDiagnosticDescriptors(analyzer) : analyzer.SupportedDiagnostics;
            }
            catch (Exception)
            {
                return false;
            }

            if (diagDescriptors == null)
            {
                return false;
            }

            // find if the first diagnostic in this analyzer allows telemetry
            DiagnosticDescriptor diagnostic = diagDescriptors.Length > 0 ? diagDescriptors[0] : null;
            return diagnostic == null ? false : diagnostic.CustomTags.Any(t => t == WellKnownDiagnosticTags.Telemetry);
        }
 public DiagnosticIncrementalAnalyzer(DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, HostAnalyzerManager hostAnalyzerManager, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
     : base(owner, workspace, hostAnalyzerManager, hostDiagnosticUpdateSource)
 {
     _correlationId = correlationId;
 }
        public static bool AllowsTelemetry(DiagnosticAnalyzerService service, DiagnosticAnalyzer analyzer, ProjectId projectIdOpt)
        {
            StrongBox<bool> value;
            if (s_telemetryCache.TryGetValue(analyzer, out value))
            {
                return value.Value;
            }

            return s_telemetryCache.GetValue(analyzer, a => new StrongBox<bool>(CheckTelemetry(service, a))).Value;
        }