Ejemplo n.º 1
0
        public DiagnosticTaggerWrapper(
            TestWorkspace workspace,
            IReadOnlyDictionary <string, ImmutableArray <DiagnosticAnalyzer> >?analyzerMap = null,
            IDiagnosticUpdateSource?updateSource = null,
            bool createTaggerProvider            = true)
        {
            _threadingContext = workspace.GetService <IThreadingContext>();
            _listenerProvider = workspace.GetService <IAsynchronousOperationListenerProvider>();

            var analyzerReference = new TestAnalyzerReferenceByLanguage(analyzerMap ?? DiagnosticExtensions.GetCompilerDiagnosticAnalyzersMap());

            workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference }));

            // Change the background analysis scope to OpenFiles instead of ActiveFile (default),
            // so that every diagnostic tagger test does not need to mark test files as "active" file.
            var csKey = new OptionKey2(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.CSharp);
            var vbKey = new OptionKey2(SolutionCrawlerOptions.BackgroundAnalysisScopeOption, LanguageNames.VisualBasic);

            workspace.SetOptions(workspace.Options
                                 .WithChangedOption(csKey, BackgroundAnalysisScope.OpenFiles)
                                 .WithChangedOption(vbKey, BackgroundAnalysisScope.OpenFiles));

            _workspace = workspace;

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

            if (!_registrationService.GetTestAccessor().TryGetWorkCoordinator(workspace, out var coordinator))
            {
                throw new InvalidOperationException();
            }

            AnalyzerService   = (DiagnosticAnalyzerService?)_registrationService.GetTestAccessor().AnalyzerProviders.SelectMany(pair => pair.Value).SingleOrDefault(lazyProvider => lazyProvider.Metadata.Name == WellKnownSolutionCrawlerAnalyzers.Diagnostic && lazyProvider.Metadata.HighPriorityForActiveFile)?.Value;
            DiagnosticService = (DiagnosticService)workspace.ExportProvider.GetExportedValue <IDiagnosticService>();

            if (updateSource is object)
            {
                DiagnosticService.Register(updateSource);
            }

            if (createTaggerProvider)
            {
                _ = TaggerProvider;
            }
        }