public DiagnosticTaggerWrapper(
     TestWorkspace workspace,
     Dictionary<string, DiagnosticAnalyzer[]> analyzerMap = null,
     bool createTaggerProvider = true)
     : this(workspace, CreateDiagnosticAnalyzerService(analyzerMap), updateSource: null, createTaggerProvider: createTaggerProvider)
 {
 }
        internal override async Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync(
            TestWorkspace workspace, string fixAllActionId, object fixProviderData)
        {
            var providerAndFixer = GetOrCreateDiagnosticProviderAndFixer(workspace, fixProviderData);

            var provider = providerAndFixer.Item1;
            Document document;
            TextSpan span;
            string annotation = null;
            if (!TryGetDocumentAndSelectSpan(workspace, out document, out span))
            {
                document = GetDocumentAndAnnotatedSpan(workspace, out annotation, out span);
            }

            using (var testDriver = new TestDiagnosticAnalyzerDriver(document.Project, provider))
            {
                var diagnostics = await testDriver.GetAllDiagnosticsAsync(provider, document, span);
                AssertNoAnalyzerExceptionDiagnostics(diagnostics);

                var fixer = providerAndFixer.Item2;
                var ids = new HashSet<string>(fixer.FixableDiagnosticIds);
                var dxs = diagnostics.Where(d => ids.Contains(d.Id)).ToList();
                return await GetDiagnosticAndFixesAsync(dxs, provider, fixer, testDriver, document, span, annotation, fixAllActionId);
            }
        }
 public DiagnosticTaggerWrapper(
     TestWorkspace workspace,
     IDiagnosticUpdateSource updateSource,
     bool createTaggerProvider = true)
     : this(workspace, null, updateSource, createTaggerProvider)
 {
 }
Esempio n. 4
0
 private static async Task WaitForWorkspaceOperationsToComplete(TestWorkspace workspace)
 {
     var workspaceWaiter = workspace.ExportProvider
         .GetExports<IAsynchronousOperationListener, FeatureMetadata>()
         .First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter;
     await workspaceWaiter.CreateWaitTask().ConfigureAwait(true);
 }
        internal override async Task<IEnumerable<Tuple<Diagnostic, CodeFixCollection>>> GetDiagnosticAndFixesAsync(
            TestWorkspace workspace, string fixAllActionId, object fixProviderData)
        {
            var providerAndFixer = CreateDiagnosticProviderAndFixer(workspace);

            var provider = providerAndFixer.Item1;
            Document document;
            TextSpan span;
            string annotation = null;
            if (!TryGetDocumentAndSelectSpan(workspace, out document, out span))
            {
                document = GetDocumentAndAnnotatedSpan(workspace, out annotation, out span);
            }

            using (var testDriver = new TestDiagnosticAnalyzerDriver(document.Project, provider, includeSuppressedDiagnostics: IncludeSuppressedDiagnostics))
            {
                var fixer = providerAndFixer.Item2;
                var diagnostics = (await testDriver.GetAllDiagnosticsAsync(provider, document, span))
                    .Where(d => fixer.CanBeSuppressedOrUnsuppressed(d));

                var filteredDiagnostics = FilterDiagnostics(diagnostics);

                var wrapperCodeFixer = new WrapperCodeFixProvider(fixer, filteredDiagnostics.Select(d => d.Id));
                return await GetDiagnosticAndFixesAsync(filteredDiagnostics, provider, wrapperCodeFixer, testDriver, document, span, annotation, fixAllActionId);
            }
        }
        internal static IList<ITagSpan<IErrorTag>> GetErrorsFromUpdateSource(TestWorkspace workspace, TestHostDocument document, DiagnosticsUpdatedArgs updateArgs)
        {
            var source = new TestDiagnosticUpdateSource();

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

            var optionsService = workspace.Services.GetService<IOptionService>();
            var diagnosticService = new DiagnosticService(SpecializedCollections.SingletonEnumerable<IDiagnosticUpdateSource>(source), listeners);

            var foregroundService = workspace.GetService<IForegroundNotificationService>();  //new TestForegroundNotificationService();

            var buffer = document.GetTextBuffer();
            var provider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners);
            var tagger = provider.CreateTagger<IErrorTag>(buffer);

            source.RaiseDiagnosticsUpdated(updateArgs);

            listener.CreateWaitTask().PumpingWait();

            var snapshot = buffer.CurrentSnapshot;
            var spans = tagger.GetTags(new NormalizedSnapshotSpanCollection(new SnapshotSpan(snapshot, 0, snapshot.Length))).ToImmutableArray();

            ((IDisposable)tagger).Dispose();

            return spans;
        }
        private async Task TestWithOptionsAsync(TestWorkspace workspace, params Action<object>[] expectedResults)
        {
            var testDocument = workspace.DocumentWithCursor;
            var position = testDocument.CursorPosition.GetValueOrDefault();
            var documentId = workspace.GetDocumentId(testDocument);
            var document = workspace.CurrentSolution.GetDocument(documentId);

            var provider = new SemanticQuickInfoProvider(
                workspace.GetService<IProjectionBufferFactoryService>(),
                workspace.GetService<IEditorOptionsFactoryService>(),
                workspace.GetService<ITextEditorFactoryService>(),
                workspace.GetService<IGlyphService>(),
                workspace.GetService<ClassificationTypeMap>());

            await TestWithOptionsAsync(document, provider, position, expectedResults);

            // speculative semantic model
            if (await CanUseSpeculativeSemanticModelAsync(document, position))
            {
                var buffer = testDocument.TextBuffer;
                using (var edit = buffer.CreateEdit())
                {
                    var currentSnapshot = buffer.CurrentSnapshot;
                    edit.Replace(0, currentSnapshot.Length, currentSnapshot.GetText());
                    edit.Apply();
                }

                await TestWithOptionsAsync(document, provider, position, expectedResults);
            }
        }
        internal override IEnumerable<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixes(TestWorkspace workspace, string fixAllActionId)
        {
            var providerAndFixer = CreateDiagnosticProviderAndFixer(workspace);

            var provider = providerAndFixer.Item1;
            Document document;
            TextSpan span;
            string annotation = null;
            if (!TryGetDocumentAndSelectSpan(workspace, out document, out span))
            {
                document = GetDocumentAndAnnotatedSpan(workspace, out annotation, out span);
            }           

            using (var testDriver = new TestDiagnosticAnalyzerDriver(document.Project, provider, includeSuppressedDiagnostics: IncludeSuppressedDiagnostics))
            {
                var fixer = providerAndFixer.Item2;
                var diagnostics = testDriver.GetAllDiagnostics(provider, document, span)
                    .Where(d => fixer.CanBeSuppressedOrUnsuppressed(d))
                    .ToImmutableArray();

                if (!IncludeUnsuppressedDiagnostics)
                {
                    diagnostics = diagnostics.WhereAsArray(d => d.IsSuppressed);
                }

                var wrapperCodeFixer = new WrapperCodeFixProvider(fixer, diagnostics);
                return GetDiagnosticAndFixes(diagnostics, provider, wrapperCodeFixer, testDriver, document, span, annotation, fixAllActionId);
            }
        }
        internal static IList<ITagSpan<IErrorTag>> GetErrorsFromUpdateSource(TestWorkspace workspace, TestHostDocument document, DiagnosticsUpdatedArgs updateArgs)
        {
            var source = new TestDiagnosticUpdateSource();

            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>();
            var diagnosticService = new DiagnosticService(SpecializedCollections.SingletonEnumerable<IDiagnosticUpdateSource>(source), diagnosticListeners);

            var squiggleWaiter = new ErrorSquiggleWaiter();
            var foregroundService = new TestForegroundNotificationService();

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

            source.RaiseDiagnosticsUpdated(updateArgs);

            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));

            taggerSource.TestOnly_Dispose();

            return spans;
        }
Esempio n. 10
0
        public void TestGetDiagnostics1()
        {
            using (var workspace = new TestWorkspace(TestExportProvider.ExportProviderWithCSharpAndVisualBasic))
            {
                var set = new ManualResetEvent(false);
                var document = workspace.CurrentSolution.AddProject("TestProject", "TestProject", LanguageNames.CSharp).AddDocument("TestDocument", string.Empty);

                var source = new TestDiagnosticUpdateSource(false, null);
                var diagnosticService = new DiagnosticService(AggregateAsynchronousOperationListener.EmptyListeners);
                diagnosticService.Register(source);

                diagnosticService.DiagnosticsUpdated += (s, o) => { set.Set(); };

                var id = Tuple.Create(workspace, document);
                var diagnostic = RaiseDiagnosticEvent(set, source, workspace, document.Project.Id, document.Id, id);

                var data1 = diagnosticService.GetDiagnostics(workspace, null, null, null, false, CancellationToken.None);
                Assert.Equal(diagnostic, data1.Single());

                var data2 = diagnosticService.GetDiagnostics(workspace, document.Project.Id, null, null, false, CancellationToken.None);
                Assert.Equal(diagnostic, data2.Single());

                var data3 = diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, null, false, CancellationToken.None);
                Assert.Equal(diagnostic, data3.Single());

                var data4 = diagnosticService.GetDiagnostics(workspace, document.Project.Id, document.Id, id, false, CancellationToken.None);
                Assert.Equal(diagnostic, data4.Single());
            }
        }
Esempio n. 11
0
 private static void WaitForWorkspaceOperationsToComplete(TestWorkspace workspace)
 {
     var workspasceWaiter = workspace.ExportProvider
         .GetExports<IAsynchronousOperationListener, FeatureMetadata>()
         .First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter;
     workspasceWaiter.CreateWaitTask().PumpingWait();
 }
Esempio n. 12
0
        protected async Task TestActionsOnLinkedFiles(
            TestWorkspace workspace,
            string expectedText,
            int index,
            IList<CodeAction> actions,
            string expectedPreviewContents = null,
            bool compareTokens = true)
        {
            var operations = await VerifyInputsAndGetOperationsAsync(index, actions);

            await VerifyPreviewContents(workspace, expectedPreviewContents, operations);

            var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First();
            applyChangesOperation.Apply(workspace, new ProgressTracker(), CancellationToken.None);

            foreach (var document in workspace.Documents)
            {
                var fixedRoot = await workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync();
                var actualText = compareTokens ? fixedRoot.ToString() : fixedRoot.ToFullString();

                if (compareTokens)
                {
                    TokenUtilities.AssertTokensEqual(expectedText, actualText, GetLanguage());
                }
                else
                {
                    Assert.Equal(expectedText, actualText);
                }
            }
        }
Esempio n. 13
0
            public AdornmentManagerTester()
            {
                _subjectBuffer = EditorFactory.CreateBuffer(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, "Hi There");

                _textView = new Mock<IWpfTextView>();
                var aggregatorService = new Mock<IViewTagAggregatorFactoryService>();
                _adornmentLayer = new Mock<IAdornmentLayer>();
                _aggregator = new Mock<ITagAggregator<Tag>>();

                var layerName = "LayerName";

                _textView.Setup(tv => tv.GetAdornmentLayer(layerName)).Returns(_adornmentLayer.Object);
                _textView.SetupGet(tv => tv.VisualElement).Returns(new FrameworkElement());

                aggregatorService.Setup(a => a.CreateTagAggregator<Tag>(_textView.Object)).Returns(_aggregator.Object);

                var textViewModel = new Mock<ITextViewModel>();
                textViewModel.Setup(tvm => tvm.VisualBuffer).Returns(_subjectBuffer);
                _textView.Setup(tv => tv.TextViewModel).Returns(textViewModel.Object);

                var workspace = new TestWorkspace();

                var listener = new AggregateAsynchronousOperationListener(
                    Enumerable.Empty<Lazy<IAsynchronousOperationListener, FeatureMetadata>>(),
                    FeatureAttribute.LineSeparators);
                Manager = AdornmentManager<Tag>.Create(_textView.Object,
                                                       aggregatorService.Object,
                                                       listener,
                                                       adornmentLayerName: layerName);
            }
        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;
            }
        }
Esempio n. 15
0
 public void Dispose()
 {
     if (this.Workspace != null)
     {
         this.Workspace.Dispose();
         this.Workspace = null;
     }
 }
 protected override void AssertNoContent(
     TestWorkspace workspace,
     Document document,
     int position)
 {
     var provider = CreateProvider(workspace);
     Assert.Null(provider.GetItemAsync(document, position, CancellationToken.None).Result);
 }
Esempio n. 17
0
 public void Dispose()
 {
     if (_workspace != null)
     {
         _workspace.Dispose();
         _workspace = null;
     }
 }
Esempio n. 18
0
 protected Document GetDocumentAndAnnotatedSpan(TestWorkspace workspace, out string annotation, out TextSpan span)
 {
     var hostDocument = workspace.Documents.Single(d => d.AnnotatedSpans.Any());
     var annotatedSpan = hostDocument.AnnotatedSpans.Single();
     annotation = annotatedSpan.Key;
     span = annotatedSpan.Value.Single();
     return workspace.CurrentSolution.GetDocument(hostDocument.Id);
 }
        internal override IEnumerable<Diagnostic> GetDiagnostics(TestWorkspace workspace)
        {
            var providerAndFixer = CreateDiagnosticProviderAndFixer(workspace);

            var provider = providerAndFixer.Item1;
            TextSpan span;
            var document = GetDocumentAndSelectSpan(workspace, out span);
            return DiagnosticProviderTestUtilities.GetAllDiagnostics(provider, document, span);
        }
Esempio n. 20
0
        private async void AssertResetInteractive(
            TestWorkspace workspace,
            Project project,
            bool buildSucceeds,
            List<string> expectedReferences = null,
            List<string> expectedUsings = null)
        {
            expectedReferences = expectedReferences ?? new List<string>();
            expectedUsings = expectedUsings ?? new List<string>();

            InteractiveWindowTestHost testHost = new InteractiveWindowTestHost();
            List<string> executedSubmissionCalls = new List<string>();
            EventHandler<string> ExecuteSubmission = (_, code) => { executedSubmissionCalls.Add(code); };

            testHost.Evaluator.OnExecute += ExecuteSubmission;

            IWaitIndicator waitIndicator = workspace.GetService<IWaitIndicator>();
            IEditorOptionsFactoryService editorOptionsFactoryService = workspace.GetService<IEditorOptionsFactoryService>();
            var editorOptions = editorOptionsFactoryService.GetOptions(testHost.Window.CurrentLanguageBuffer);
            var newLineCharacter = editorOptions.GetNewLineCharacter();

            TestResetInteractive resetInteractive = new TestResetInteractive(
                waitIndicator,
                editorOptionsFactoryService,
                CreateReplReferenceCommand,
                CreateImport,
                buildSucceeds: buildSucceeds)
            {
                References = ImmutableArray.CreateRange(GetProjectReferences(workspace, project)),
                ReferenceSearchPaths = ImmutableArray.Create("rsp1", "rsp2"),
                SourceSearchPaths = ImmutableArray.Create("ssp1", "ssp2"),
                ProjectNamespaces = ImmutableArray.Create("System", "ResetInteractiveTestsDocument", "VisualBasicResetInteractiveTestsDocument"),
                NamespacesToImport = ImmutableArray.Create("System", "ResetInteractiveTestsDocument"),
                ProjectDirectory = "pj",
            };

            await resetInteractive.Execute(testHost.Window, "Interactive C#");

            // Validate that the project was rebuilt.
            Assert.Equal(1, resetInteractive.BuildProjectCount);
            Assert.Equal(0, resetInteractive.CancelBuildProjectCount);

            var expectedSubmissions = new List<string>();
            if (expectedReferences.Any())
            {
                expectedSubmissions.AddRange(expectedReferences.Select(r => r + newLineCharacter));
            }
            if (expectedUsings.Any())
            {
                expectedSubmissions.Add(string.Join(newLineCharacter, expectedUsings) + newLineCharacter);
            }

            AssertEx.Equal(expectedSubmissions, executedSubmissionCalls);

            testHost.Evaluator.OnExecute -= ExecuteSubmission;
        }
        internal override async Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(TestWorkspace workspace)
        {
            var providerAndFixer = CreateDiagnosticProviderAndFixer(workspace);

            var provider = providerAndFixer.Item1;
            TextSpan span;
            var document = GetDocumentAndSelectSpan(workspace, out span);
            var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(provider, document, span);
            return FilterDiagnostics(diagnostics);
        }
Esempio n. 22
0
        protected static async Task<string> TokenFormatAsync(
            TestWorkspace workspace,
            ITextBuffer buffer,
            int indentationLine,
            char ch)
        {
            await TokenFormatWorkerAsync(workspace, buffer, indentationLine, ch);

            return buffer.CurrentSnapshot.GetText();
        }
Esempio n. 23
0
        protected static async Task<int> GetSmartTokenFormatterIndentationWorkerAsync(
            TestWorkspace workspace,
            ITextBuffer buffer,
            int indentationLine,
            char ch)
        {
            await TokenFormatWorkerAsync(workspace, buffer, indentationLine, ch);

            return buffer.CurrentSnapshot.GetLineFromLineNumber(indentationLine).GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(TestEditorOptions.Instance);
        }
Esempio n. 24
0
        protected static string TokenFormat(
            TestWorkspace workspace,
            ITextBuffer buffer,
            int indentationLine,
            char ch)
        {
            TokenFormatWorker(workspace, buffer, indentationLine, ch);

            return buffer.CurrentSnapshot.GetText();
        }
Esempio n. 25
0
        public void SolutionAdded_Complex()
        {
            using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler))
            {
                var solution = GetInitialSolutionInfo(workspace);

                var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solution));
                Assert.Equal(10, worker.SyntaxDocumentIds.Count);
            }
        }
        public EncapsulateFieldTestState(TestWorkspace workspace)
        {
            Workspace = workspace;
            _testDocument = Workspace.Documents.Single(d => d.CursorPosition.HasValue || d.SelectedSpans.Any());
            TargetDocument = Workspace.CurrentSolution.GetDocument(_testDocument.Id);

            var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback;
            var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => NotificationMessage = message);
            notificationService.NotificationCallback = callback;
        }
Esempio n. 27
0
        public RenameTrackingTestState(
            string markup,
            string languageName,
            bool onBeforeGlobalSymbolRenamedReturnValue = true,
            bool onAfterGlobalSymbolRenamedReturnValue = true)
        {
            this.Workspace = CreateTestWorkspace(markup, languageName, TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic());

            _hostDocument = Workspace.Documents.First();
            _view = _hostDocument.GetTextView();
            _view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value));
            _editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view);
            _historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value;
            _mockRefactorNotifyService = new MockRefactorNotifyService
            {
                OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue,
                OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue
            };

            var optionService = this.Workspace.Services.GetService<IOptionService>();

            // Mock the action taken by the workspace INotificationService
            var notificationService = Workspace.Services.GetService<INotificationService>() as INotificationServiceCallback;
            var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message);
            notificationService.NotificationCallback = callback;

            var tracker = new RenameTrackingTaggerProvider(
                _historyRegistry,
                Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
                Workspace.ExportProvider.GetExport<IInlineRenameService>().Value,
                Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value,
                SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService),
                Workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>());

            _tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer());

            if (languageName == LanguageNames.CSharp)
            {
                _codeFixProvider = new CSharpRenameTrackingCodeFixProvider(
                    Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
                    _historyRegistry,
                    SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
            }
            else if (languageName == LanguageNames.VisualBasic)
            {
                _codeFixProvider = new VisualBasicRenameTrackingCodeFixProvider(
                    Workspace.ExportProvider.GetExport<Host.IWaitIndicator>().Value,
                    _historyRegistry,
                    SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
            }
            else
            {
                throw new ArgumentException("Invalid langauge name: " + languageName, "languageName");
            }
        }
 private static void RefactoringSetup(TestWorkspace workspace, CodeRefactoringProvider provider, List<CodeAction> refactorings, out ICodeActionEditHandlerService editHandler, out EditorLayerExtensionManager.ExtensionManager extensionManager, out VisualStudio.Text.ITextBuffer textBuffer)
 {
     var document = GetDocument(workspace);
     var span = document.GetSyntaxRootAsync().Result.Span;
     var context = new CodeRefactoringContext(document, span, (a) => refactorings.Add(a), CancellationToken.None);
     provider.ComputeRefactoringsAsync(context).Wait();
     var action = refactorings.Single();
     editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
     extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>() as EditorLayerExtensionManager.ExtensionManager;
     textBuffer = document.GetTextAsync().Result.Container.GetTextBuffer();
 }
        internal async override Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(TestWorkspace workspace)
        {
            var providerAndFixer = GetOrCreateDiagnosticProviderAndFixer(workspace);

            var provider = providerAndFixer.Item1;
            TextSpan span;
            var document = GetDocumentAndSelectSpan(workspace, out span);
            var allDiagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(provider, document, span);
            AssertNoAnalyzerExceptionDiagnostics(allDiagnostics);
            return allDiagnostics;
        }
Esempio n. 30
0
 private async Task<CodeRefactoring> GetCodeRefactoringAsync(
     CodeRefactoringProvider provider,
     TestWorkspace workspace)
 {
     var document = GetDocument(workspace);
     var span = workspace.Documents.Single(d => !d.IsLinkFile && d.SelectedSpans.Count == 1).SelectedSpans.Single();
     var actions = new List<CodeAction>();
     var context = new CodeRefactoringContext(document, span, (a) => actions.Add(a), CancellationToken.None);
     await provider.ComputeRefactoringsAsync(context);
     return actions.Count > 0 ? new CodeRefactoring(provider, actions) : null;
 }
Esempio n. 31
0
 protected override TestWorkspace CreateWorkspace()
 {
     return(TestWorkspace.CreateCSharp(
                new string[] { string.Empty, },
                new CSharpParseOptions[] { new CSharpParseOptions(kind: SourceCodeKind.Regular), }));
 }
Esempio n. 32
0
 public TestWorkspace GetWorkspace()
 {
     _workspace = _workspace ?? CreateWorkspace();
     return(_workspace);
 }
Esempio n. 33
0
 public TestWorkspace GetWorkspace(ExportProvider exportProvider = null)
 {
     _workspace = _workspace ?? CreateWorkspace(exportProvider);
     return(_workspace);
 }
Esempio n. 34
0
        internal static TestWorkspace Create(
            XElement workspaceElement,
            bool completed                = true,
            bool openDocuments            = true,
            ExportProvider exportProvider = null,
            string workspaceKind          = null,
            IDocumentServiceProvider documentServiceProvider = null)
        {
            if (workspaceElement.Name != WorkspaceElementName)
            {
                throw new ArgumentException();
            }

            exportProvider ??= TestExportProvider.ExportProviderWithCSharpAndVisualBasic;

            var workspace = new TestWorkspace(exportProvider, workspaceKind);

            var projectNameToTestHostProject = new Dictionary <string, TestHostProject>();
            var projectElementToProjectName  = new Dictionary <XElement, string>();
            var filePathToTextBufferMap      = new Dictionary <string, ITextBuffer>();
            var projectIdentifier            = 0;
            var documentIdentifier           = 0;

            foreach (var projectElement in workspaceElement.Elements(ProjectElementName))
            {
                var project = CreateProject(
                    workspaceElement,
                    projectElement,
                    exportProvider,
                    workspace,
                    filePathToTextBufferMap,
                    documentServiceProvider,
                    ref projectIdentifier,
                    ref documentIdentifier);
                Assert.False(projectNameToTestHostProject.ContainsKey(project.Name), $"The workspace XML already contains a project with name {project.Name}");
                projectNameToTestHostProject.Add(project.Name, project);
                projectElementToProjectName.Add(projectElement, project.Name);
                workspace.Projects.Add(project);
            }

            var documentFilePaths = new HashSet <string>();

            foreach (var project in projectNameToTestHostProject.Values)
            {
                foreach (var document in project.Documents)
                {
                    Assert.True(document.IsLinkFile || documentFilePaths.Add(document.FilePath));

                    workspace.Documents.Add(document);
                }
            }

            var submissions = CreateSubmissions(workspace, workspaceElement.Elements(SubmissionElementName), exportProvider);

            foreach (var submission in submissions)
            {
                projectNameToTestHostProject.Add(submission.Name, submission);
                workspace.Documents.Add(submission.Documents.Single());
            }

            var solution = new TestHostSolution(projectNameToTestHostProject.Values.ToArray());

            workspace.AddTestSolution(solution);

            foreach (var projectElement in workspaceElement.Elements(ProjectElementName))
            {
                foreach (var projectReference in projectElement.Elements(ProjectReferenceElementName))
                {
                    var fromName = projectElementToProjectName[projectElement];
                    var toName   = projectReference.Value;

                    var fromProject = projectNameToTestHostProject[fromName];
                    var toProject   = projectNameToTestHostProject[toName];

                    var aliases = projectReference.Attributes(AliasAttributeName).Select(a => a.Value).ToImmutableArray();

                    workspace.OnProjectReferenceAdded(fromProject.Id, new ProjectReference(toProject.Id, aliases.Any() ? aliases : default));
                }
            }

            for (var i = 1; i < submissions.Count; i++)
            {
                if (submissions[i].CompilationOptions == null)
                {
                    continue;
                }

                for (var j = i - 1; j >= 0; j--)
                {
                    if (submissions[j].CompilationOptions != null)
                    {
                        workspace.OnProjectReferenceAdded(submissions[i].Id, new ProjectReference(submissions[j].Id));
                        break;
                    }
                }
            }

            foreach (var project in projectNameToTestHostProject.Values)
            {
                foreach (var document in project.Documents)
                {
                    if (openDocuments)
                    {
                        // This implicitly opens the document in the workspace by fetching the container.
                        document.GetOpenTextContainer();
                    }
                }
            }

            return(workspace);
        }
Esempio n. 35
0
        private static IList <TestHostProject> CreateSubmissions(
            TestWorkspace workspace,
            IEnumerable <XElement> submissionElements,
            ExportProvider exportProvider)
        {
            var submissions     = new List <TestHostProject>();
            var submissionIndex = 0;

            foreach (var submissionElement in submissionElements)
            {
                var submissionName = "Submission" + (submissionIndex++);

                var languageName = GetLanguage(workspace, submissionElement);

                // The document
                var markupCode = submissionElement.NormalizedValue();
                MarkupTestFile.GetPositionAndSpans(markupCode,
                                                   out var code, out var cursorPosition, out IDictionary <string, ImmutableArray <TextSpan> > spans);

                var languageServices = workspace.Services.GetLanguageServices(languageName);

                // The project

                var document  = new TestHostDocument(exportProvider, languageServices, code, submissionName, cursorPosition, spans, SourceCodeKind.Script);
                var documents = new List <TestHostDocument> {
                    document
                };

                if (languageName == NoCompilationConstants.LanguageName)
                {
                    submissions.Add(
                        new TestHostProject(
                            languageServices,
                            compilationOptions: null,
                            parseOptions: null,
                            assemblyName: submissionName,
                            projectName: submissionName,
                            references: null,
                            documents: documents,
                            isSubmission: true));
                    continue;
                }

                var syntaxFactory      = languageServices.GetService <ISyntaxTreeFactoryService>();
                var compilationFactory = languageServices.GetService <ICompilationFactoryService>();
                var compilationOptions = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary);

                var parseOptions = syntaxFactory.GetDefaultParseOptions().WithKind(SourceCodeKind.Script);

                var references = CreateCommonReferences(workspace, submissionElement);

                var project = new TestHostProject(
                    languageServices,
                    compilationOptions,
                    parseOptions,
                    submissionName,
                    submissionName,
                    references,
                    documents,
                    isSubmission: true);

                submissions.Add(project);
            }

            return(submissions);
        }
        private static TestHostProject CreateProject(
            XElement workspaceElement,
            XElement projectElement,
            ExportProvider exportProvider,
            TestWorkspace workspace,
            Dictionary <XElement, string> projectElementToAssemblyName,
            Dictionary <XElement, string> documentElementToFilePath,
            Dictionary <string, ITextBuffer> filePathToTextBufferMap,
            ref int projectId,
            ref int documentId)
        {
            var language = GetLanguage(workspace, projectElement);

            var assemblyName = GetAssemblyName(workspace, projectElement, ref projectId);

            projectElementToAssemblyName.Add(projectElement, assemblyName);

            string filePath;

            if (projectElement.Attribute(FilePathAttributeName) != null)
            {
                filePath = projectElement.Attribute(FilePathAttributeName).Value;
                if (string.Compare(filePath, NullFilePath, StringComparison.Ordinal) == 0)
                {
                    // allow explicit null file path
                    filePath = null;
                }
            }
            else
            {
                filePath = assemblyName +
                           (language == LanguageNames.CSharp ? ".csproj" :
                            language == LanguageNames.VisualBasic ? ".vbproj" : ("." + language));
            }

            var contentTypeRegistryService = exportProvider.GetExportedValue <IContentTypeRegistryService>();
            var languageServices           = workspace.Services.GetLanguageServices(language);

            var compilationOptions = CreateCompilationOptions(workspace, projectElement, language);
            var parseOptions       = GetParseOptions(projectElement, language, languageServices);

            var references = CreateReferenceList(workspace, projectElement);
            var analyzers  = CreateAnalyzerList(workspace, projectElement);

            var documents        = new List <TestHostDocument>();
            var documentElements = projectElement.Elements(DocumentElementName).ToList();

            foreach (var documentElement in documentElements)
            {
                var document = CreateDocument(
                    workspace,
                    workspaceElement,
                    documentElement,
                    language,
                    exportProvider,
                    languageServices,
                    filePathToTextBufferMap,
                    ref documentId);

                documents.Add(document);
                documentElementToFilePath.Add(documentElement, document.FilePath);
            }

            return(new TestHostProject(languageServices, compilationOptions, parseOptions, assemblyName, references, documents, filePath: filePath, analyzerReferences: analyzers));
        }
Esempio n. 37
0
        private static TestHostProject CreateProject(
            XElement workspaceElement,
            XElement projectElement,
            ExportProvider exportProvider,
            TestWorkspace workspace,
            IDocumentServiceProvider documentServiceProvider,
            ref int projectId,
            ref int documentId)
        {
            AssertNoChildText(projectElement);

            var language = GetLanguage(workspace, projectElement);

            var assemblyName = GetAssemblyName(workspace, projectElement, ref projectId);

            string filePath;

            var projectName = projectElement.Attribute(ProjectNameAttribute)?.Value ?? assemblyName;

            if (projectElement.Attribute(FilePathAttributeName) != null)
            {
                filePath = projectElement.Attribute(FilePathAttributeName).Value;
                if (string.Compare(filePath, NullFilePath, StringComparison.Ordinal) == 0)
                {
                    // allow explicit null file path
                    filePath = null;
                }
            }
            else
            {
                filePath = projectName +
                           (language == LanguageNames.CSharp ? ".csproj" :
                            language == LanguageNames.VisualBasic ? ".vbproj" : ("." + language));
            }

            var languageServices = workspace.Services.GetLanguageServices(language);

            var parseOptions       = GetParseOptions(projectElement, language, languageServices);
            var compilationOptions = CreateCompilationOptions(workspace, projectElement, language, parseOptions);
            var rootNamespace      = GetRootNamespace(workspace, compilationOptions, projectElement);

            var references = CreateReferenceList(workspace, projectElement);
            var analyzers  = CreateAnalyzerList(projectElement);

            var documents        = new List <TestHostDocument>();
            var documentElements = projectElement.Elements(DocumentElementName).ToList();

            foreach (var documentElement in documentElements)
            {
                var document = CreateDocument(
                    workspace,
                    workspaceElement,
                    documentElement,
                    exportProvider,
                    languageServices,
                    documentServiceProvider,
                    ref documentId);

                documents.Add(document);
            }

            var additionalDocuments        = new List <TestHostDocument>();
            var additionalDocumentElements = projectElement.Elements(AdditionalDocumentElementName).ToList();

            foreach (var additionalDocumentElement in additionalDocumentElements)
            {
                var document = CreateDocument(
                    workspace,
                    workspaceElement,
                    additionalDocumentElement,
                    exportProvider,
                    languageServices,
                    documentServiceProvider,
                    ref documentId);

                additionalDocuments.Add(document);
            }

            var analyzerConfigDocuments = new List <TestHostDocument>();
            var analyzerConfigElements  = projectElement.Elements(AnalyzerConfigDocumentElementName).ToList();

            foreach (var analyzerConfigElement in analyzerConfigElements)
            {
                var document = CreateDocument(
                    workspace,
                    workspaceElement,
                    analyzerConfigElement,
                    exportProvider,
                    languageServices,
                    documentServiceProvider,
                    ref documentId);

                analyzerConfigDocuments.Add(document);
            }

            return(new TestHostProject(languageServices, compilationOptions, parseOptions, assemblyName, projectName, references, documents, additionalDocuments, analyzerConfigDocuments, filePath: filePath, analyzerReferences: analyzers, defaultNamespace: rootNamespace));
        }
        private static TestHostDocument CreateDocument(
            TestWorkspace workspace,
            XElement workspaceElement,
            XElement documentElement,
            string language,
            ExportProvider exportProvider,
            HostLanguageServices languageServiceProvider,
            Dictionary <string, ITextBuffer> filePathToTextBufferMap,
            ref int documentId)
        {
            string markupCode;
            string filePath;

            var  isLinkFileAttribute = documentElement.Attribute(IsLinkFileAttributeName);
            bool isLinkFile          = isLinkFileAttribute != null && ((bool?)isLinkFileAttribute).HasValue && ((bool?)isLinkFileAttribute).Value;

            if (isLinkFile)
            {
                // This is a linked file. Use the filePath and markup from the referenced document.

                var originalProjectName  = documentElement.Attribute(LinkAssemblyNameAttributeName);
                var originalDocumentPath = documentElement.Attribute(LinkFilePathAttributeName);

                if (originalProjectName == null || originalDocumentPath == null)
                {
                    throw new ArgumentException("Linked file specified without LinkAssemblyName or LinkFilePath.");
                }

                var originalProjectNameStr  = originalProjectName.Value;
                var originalDocumentPathStr = originalDocumentPath.Value;

                var originalProject = workspaceElement.Elements(ProjectElementName).First(p =>
                {
                    var assemblyName = p.Attribute(AssemblyNameAttributeName);
                    return(assemblyName != null && assemblyName.Value == originalProjectNameStr);
                });

                if (originalProject == null)
                {
                    throw new ArgumentException("Linked file's LinkAssemblyName '{0}' project not found.", originalProjectNameStr);
                }

                var originalDocument = originalProject.Elements(DocumentElementName).First(d =>
                {
                    var documentPath = d.Attribute(FilePathAttributeName);
                    return(documentPath != null && documentPath.Value == originalDocumentPathStr);
                });

                if (originalDocument == null)
                {
                    throw new ArgumentException("Linked file's LinkFilePath '{0}' file not found.", originalDocumentPathStr);
                }

                markupCode = originalDocument.NormalizedValue();
                filePath   = GetFilePath(workspace, originalDocument, ref documentId);
            }
            else
            {
                markupCode = documentElement.NormalizedValue();
                filePath   = GetFilePath(workspace, documentElement, ref documentId);
            }

            var folders        = GetFolders(documentElement);
            var optionsElement = documentElement.Element(ParseOptionsElementName);

            // TODO: Allow these to be specified.
            var codeKind = SourceCodeKind.Regular;

            if (optionsElement != null)
            {
                var attr = optionsElement.Attribute(KindAttributeName);
                codeKind = attr == null
                    ? SourceCodeKind.Regular
                    : (SourceCodeKind)Enum.Parse(typeof(SourceCodeKind), attr.Value);
            }

            var contentTypeLanguageService = languageServiceProvider.GetService <IContentTypeLanguageService>();
            var contentType = contentTypeLanguageService.GetDefaultContentType();

            string code;
            int?   cursorPosition;
            IDictionary <string, IList <TextSpan> > spans;

            MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans);

            // For linked files, use the same ITextBuffer for all linked documents
            ITextBuffer textBuffer;

            if (!filePathToTextBufferMap.TryGetValue(filePath, out textBuffer))
            {
                textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code);
                filePathToTextBufferMap.Add(filePath, textBuffer);
            }

            return(new TestHostDocument(exportProvider, languageServiceProvider, textBuffer, filePath, cursorPosition, spans, codeKind, folders, isLinkFile));
        }
        private static CompilationOptions CreateCompilationOptions(TestWorkspace workspace, string language, XElement compilationOptionsElement)
        {
            var rootNamespace    = new VisualBasicCompilationOptions(OutputKind.ConsoleApplication).RootNamespace;
            var globalImports    = new List <GlobalImport>();
            var reportDiagnostic = ReportDiagnostic.Default;

            if (compilationOptionsElement != null)
            {
                globalImports = compilationOptionsElement.Elements(GlobalImportElementName)
                                .Select(x => GlobalImport.Parse(x.Value)).ToList();
                var rootNamespaceAttribute = compilationOptionsElement.Attribute(RootNamespaceAttributeName);
                if (rootNamespaceAttribute != null)
                {
                    rootNamespace = rootNamespaceAttribute.Value;
                }

                var reportDiagnosticAttribute = compilationOptionsElement.Attribute(ReportDiagnosticAttributeName);
                if (reportDiagnosticAttribute != null)
                {
                    reportDiagnostic = (ReportDiagnostic)Enum.Parse(typeof(ReportDiagnostic), (string)reportDiagnosticAttribute);
                }

                var outputTypeAttribute = compilationOptionsElement.Attribute(OutputTypeAttributeName);
                if (outputTypeAttribute != null &&
                    outputTypeAttribute.Value == "WindowsRuntimeMetadata")
                {
                    if (rootNamespaceAttribute == null)
                    {
                        rootNamespace = new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).RootNamespace;
                    }

                    return(language == LanguageNames.CSharp
                       ? (CompilationOptions) new CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata)
                       : new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).WithGlobalImports(globalImports)
                           .WithRootNamespace(rootNamespace));
                }
            }
            else
            {
                // Add some common global imports by default for VB
                globalImports.Add(GlobalImport.Parse("System"));
                globalImports.Add(GlobalImport.Parse("System.Collections.Generic"));
                globalImports.Add(GlobalImport.Parse("System.Linq"));
            }

            // TODO: Allow these to be specified.
            var languageServices   = workspace.Services.GetLanguageServices(language);
            var compilationOptions = languageServices.GetService <ICompilationFactoryService>().GetDefaultCompilationOptions();

            compilationOptions = compilationOptions.WithOutputKind(OutputKind.DynamicallyLinkedLibrary)
                                 .WithGeneralDiagnosticOption(reportDiagnostic)
                                 .WithSourceReferenceResolver(SourceFileResolver.Default)
                                 .WithXmlReferenceResolver(XmlFileResolver.Default)
                                 .WithMetadataReferenceResolver(new AssemblyReferenceResolver(MetadataFileReferenceResolver.Default, MetadataFileReferenceProvider.Default))
                                 .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);

            if (language == LanguageNames.VisualBasic)
            {
                compilationOptions = ((VisualBasicCompilationOptions)compilationOptions).WithRootNamespace(rootNamespace)
                                     .WithGlobalImports(globalImports);
            }

            return(compilationOptions);
        }
        public static TestWorkspace CreateWorkspace(
            XElement workspaceElement,
            bool completed                = true,
            bool openDocuments            = true,
            ExportProvider exportProvider = null,
            string workspaceKind          = null)
        {
            SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());

            if (workspaceElement.Name != WorkspaceElementName)
            {
                throw new ArgumentException();
            }

            exportProvider = exportProvider ?? TestExportProvider.ExportProviderWithCSharpAndVisualBasic;

            var workspace = new TestWorkspace(exportProvider, workspaceKind);

            var projectMap = new Dictionary <string, TestHostProject>();
            var documentElementToFilePath    = new Dictionary <XElement, string>();
            var projectElementToAssemblyName = new Dictionary <XElement, string>();
            var filePathToTextBufferMap      = new Dictionary <string, ITextBuffer>();
            int projectIdentifier            = 0;
            int documentIdentifier           = 0;

            foreach (var projectElement in workspaceElement.Elements(ProjectElementName))
            {
                var project = CreateProject(
                    workspaceElement,
                    projectElement,
                    exportProvider,
                    workspace,
                    projectElementToAssemblyName,
                    documentElementToFilePath,
                    filePathToTextBufferMap,
                    ref projectIdentifier,
                    ref documentIdentifier);
                Assert.False(projectMap.ContainsKey(project.AssemblyName));
                projectMap.Add(project.AssemblyName, project);
                workspace.Projects.Add(project);
            }

            var documentFilePaths = new HashSet <string>();

            foreach (var project in projectMap.Values)
            {
                foreach (var document in project.Documents)
                {
                    Assert.True(document.IsLinkFile || documentFilePaths.Add(document.FilePath));
                }
            }

            var submissions = CreateSubmissions(workspace, workspaceElement.Elements(SubmissionElementName), exportProvider);

            foreach (var submission in submissions)
            {
                projectMap.Add(submission.AssemblyName, submission);
            }

            var solution = new TestHostSolution(projectMap.Values.ToArray());

            workspace.AddTestSolution(solution);

            foreach (var projectElement in workspaceElement.Elements(ProjectElementName))
            {
                foreach (var projectReference in projectElement.Elements(ProjectReferenceElementName))
                {
                    var fromName = projectElementToAssemblyName[projectElement];
                    var toName   = projectReference.Value;

                    var fromProject = projectMap[fromName];
                    var toProject   = projectMap[toName];

                    var aliases = projectReference.Attributes(AliasAttributeName).Select(a => a.Value).ToImmutableArray();

                    workspace.OnProjectReferenceAdded(fromProject.Id, new ProjectReference(toProject.Id, aliases.Any() ? aliases : default(ImmutableArray <string>)));
                }
            }

            for (int i = 1; i < submissions.Count; i++)
            {
                workspace.OnProjectReferenceAdded(submissions[i].Id, new ProjectReference(submissions[i - 1].Id));
            }

            foreach (var project in projectMap.Values)
            {
                foreach (var document in project.Documents)
                {
                    if (openDocuments)
                    {
                        workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer(), isCurrentContext: !document.IsLinkFile);
                    }

                    workspace.Documents.Add(document);
                }
            }

            return(workspace);
        }
        private static IList <MetadataReference> CreateCommonReferences(TestWorkspace workspace, XElement element)
        {
            var references = new List <MetadataReference>();

            var net45 = element.Attribute(CommonReferencesNet45AttributeName);

            if (net45 != null &&
                ((bool?)net45).HasValue &&
                ((bool?)net45).Value)
            {
                references = new List <MetadataReference> {
                    TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929
                };
                if (GetLanguage(workspace, element) == LanguageNames.VisualBasic)
                {
                    references.Add(TestBase.MsvbRef);
                    references.Add(TestBase.SystemXmlRef);
                    references.Add(TestBase.SystemXmlLinqRef);
                }
            }

            var commonReferencesAttribute = element.Attribute(CommonReferencesAttributeName);

            if (commonReferencesAttribute != null &&
                ((bool?)commonReferencesAttribute).HasValue &&
                ((bool?)commonReferencesAttribute).Value)
            {
                references = new List <MetadataReference> {
                    TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929
                };
                if (GetLanguage(workspace, element) == LanguageNames.VisualBasic)
                {
                    references.Add(TestBase.MsvbRef_v4_0_30319_17929);
                    references.Add(TestBase.SystemXmlRef);
                    references.Add(TestBase.SystemXmlLinqRef);
                }
            }

            var winRT = element.Attribute(CommonReferencesWinRTAttributeName);

            if (winRT != null &&
                ((bool?)winRT).HasValue &&
                ((bool?)winRT).Value)
            {
                references = new List <MetadataReference>(TestBase.WinRtRefs.Length);
                references.AddRange(TestBase.WinRtRefs);
                if (GetLanguage(workspace, element) == LanguageNames.VisualBasic)
                {
                    references.Add(TestBase.MsvbRef_v4_0_30319_17929);
                    references.Add(TestBase.SystemXmlRef);
                    references.Add(TestBase.SystemXmlLinqRef);
                }
            }

            var portable = element.Attribute(CommonReferencesPortableAttributeName);

            if (portable != null &&
                ((bool?)portable).HasValue &&
                ((bool?)portable).Value)
            {
                references = new List <MetadataReference>(TestBase.PortableRefsMinimal.Length);
                references.AddRange(TestBase.PortableRefsMinimal);
            }

            var systemRuntimeFacade = element.Attribute(CommonReferenceFacadeSystemRuntimeAttributeName);

            if (systemRuntimeFacade != null &&
                ((bool?)systemRuntimeFacade).HasValue &&
                ((bool?)systemRuntimeFacade).Value)
            {
                references.Add(TestBase.SystemRuntimeFacadeRef);
            }

            return(references);
        }
        private static TestHostProject CreateProject(
            XElement workspaceElement,
            XElement projectElement,
            ExportProvider exportProvider,
            TestWorkspace workspace,
            IDocumentServiceProvider documentServiceProvider,
            ref int projectId,
            ref int documentId)
        {
            AssertNoChildText(projectElement);

            var language = GetLanguage(workspace, projectElement);

            var assemblyName = GetAssemblyName(workspace, projectElement, ref projectId);

            string filePath;

            var projectName = projectElement.Attribute(ProjectNameAttribute)?.Value ?? assemblyName;

            if (projectElement.Attribute(FilePathAttributeName) != null)
            {
                filePath = projectElement.Attribute(FilePathAttributeName).Value;
                if (string.Compare(filePath, NullFilePath, StringComparison.Ordinal) == 0)
                {
                    // allow explicit null file path
                    filePath = null;
                }
            }
            else
            {
                filePath = projectName +
                           (language == LanguageNames.CSharp ? ".csproj" :
                            language == LanguageNames.VisualBasic ? ".vbproj" : ("." + language));
            }

            var languageServices = workspace.Services.GetLanguageServices(language);

            var parseOptions       = GetParseOptions(projectElement, language, languageServices);
            var compilationOptions = CreateCompilationOptions(workspace, projectElement, language, parseOptions);
            var rootNamespace      = GetRootNamespace(workspace, compilationOptions, projectElement);

            var references = CreateReferenceList(workspace, projectElement);
            var analyzers  = CreateAnalyzerList(projectElement);

            var documents        = new List <TestHostDocument>();
            var documentElements = projectElement.Elements(DocumentElementName).ToList();

            foreach (var documentElement in documentElements)
            {
                var document = CreateDocument(
                    workspace,
                    workspaceElement,
                    documentElement,
                    exportProvider,
                    languageServices,
                    documentServiceProvider,
                    ref documentId);

                documents.Add(document);
            }

            foreach (var sourceGeneratedDocumentElement in projectElement.Elements(DocumentFromSourceGeneratorElementName))
            {
                var name = GetFileName(workspace, sourceGeneratedDocumentElement, ref documentId);

                var markupCode = sourceGeneratedDocumentElement.NormalizedValue();
                MarkupTestFile.GetPositionAndSpans(markupCode,
                                                   out var code, out var cursorPosition, out IDictionary <string, ImmutableArray <TextSpan> > spans);

                var documentFilePath = typeof(SingleFileTestGenerator).Assembly.GetName().Name + '\\' + typeof(SingleFileTestGenerator).FullName + '\\' + name;
                var document         = new TestHostDocument(exportProvider, languageServices, code, name, documentFilePath, cursorPosition, spans, isSourceGenerated: true);
                documents.Add(document);

                analyzers.Add(new TestGeneratorReference(new SingleFileTestGenerator(code, name)));
            }

            var additionalDocuments        = new List <TestHostDocument>();
            var additionalDocumentElements = projectElement.Elements(AdditionalDocumentElementName).ToList();

            foreach (var additionalDocumentElement in additionalDocumentElements)
            {
                var document = CreateDocument(
                    workspace,
                    workspaceElement,
                    additionalDocumentElement,
                    exportProvider,
                    languageServices,
                    documentServiceProvider,
                    ref documentId);

                additionalDocuments.Add(document);
            }

            var analyzerConfigDocuments = new List <TestHostDocument>();
            var analyzerConfigElements  = projectElement.Elements(AnalyzerConfigDocumentElementName).ToList();

            foreach (var analyzerConfigElement in analyzerConfigElements)
            {
                var document = CreateDocument(
                    workspace,
                    workspaceElement,
                    analyzerConfigElement,
                    exportProvider,
                    languageServices,
                    documentServiceProvider,
                    ref documentId);

                analyzerConfigDocuments.Add(document);
            }

            return(new TestHostProject(languageServices, compilationOptions, parseOptions, assemblyName, projectName, references, documents, additionalDocuments, analyzerConfigDocuments, filePath: filePath, analyzerReferences: analyzers, defaultNamespace: rootNamespace));
        }
        private static CompilationOptions CreateCompilationOptions(TestWorkspace workspace, string language, XElement compilationOptionsElement, ParseOptions parseOptions)
        {
            var rootNamespace      = new VisualBasicCompilationOptions(OutputKind.ConsoleApplication).RootNamespace;
            var globalImports      = new List <GlobalImport>();
            var reportDiagnostic   = ReportDiagnostic.Default;
            var cryptoKeyFile      = (string)null;
            var strongNameProvider = (StrongNameProvider)null;
            var delaySign          = (bool?)null;
            var checkOverflow      = false;
            var allowUnsafe        = false;
            var outputKind         = OutputKind.DynamicallyLinkedLibrary;
            var nullable           = NullableContextOptions.Disable;

            if (compilationOptionsElement != null)
            {
                globalImports = compilationOptionsElement.Elements(GlobalImportElementName)
                                .Select(x => GlobalImport.Parse(x.Value)).ToList();
                var rootNamespaceAttribute = compilationOptionsElement.Attribute(RootNamespaceAttributeName);
                if (rootNamespaceAttribute != null)
                {
                    rootNamespace = rootNamespaceAttribute.Value;
                }

                var outputKindAttribute = compilationOptionsElement.Attribute(OutputKindName);
                if (outputKindAttribute != null)
                {
                    outputKind = (OutputKind)Enum.Parse(typeof(OutputKind), outputKindAttribute.Value);
                }

                var checkOverflowAttribute = compilationOptionsElement.Attribute(CheckOverflowAttributeName);
                if (checkOverflowAttribute != null)
                {
                    checkOverflow = (bool)checkOverflowAttribute;
                }

                var allowUnsafeAttribute = compilationOptionsElement.Attribute(AllowUnsafeAttributeName);
                if (allowUnsafeAttribute != null)
                {
                    allowUnsafe = (bool)allowUnsafeAttribute;
                }

                var reportDiagnosticAttribute = compilationOptionsElement.Attribute(ReportDiagnosticAttributeName);
                if (reportDiagnosticAttribute != null)
                {
                    reportDiagnostic = (ReportDiagnostic)Enum.Parse(typeof(ReportDiagnostic), (string)reportDiagnosticAttribute);
                }

                var cryptoKeyFileAttribute = compilationOptionsElement.Attribute(CryptoKeyFileAttributeName);
                if (cryptoKeyFileAttribute != null)
                {
                    cryptoKeyFile = (string)cryptoKeyFileAttribute;
                }

                var strongNameProviderAttribute = compilationOptionsElement.Attribute(StrongNameProviderAttributeName);
                if (strongNameProviderAttribute != null)
                {
                    var type = Type.GetType((string)strongNameProviderAttribute);
                    // DesktopStrongNameProvider and SigningTestHelpers.VirtualizedStrongNameProvider do
                    // not have a default constructor but constructors with optional parameters.
                    // Activator.CreateInstance does not work with this.
                    if (type == typeof(DesktopStrongNameProvider))
                    {
                        strongNameProvider = SigningTestHelpers.DefaultDesktopStrongNameProvider;
                    }
                    else
                    {
                        strongNameProvider = (StrongNameProvider)Activator.CreateInstance(type);
                    }
                }

                var delaySignAttribute = compilationOptionsElement.Attribute(DelaySignAttributeName);
                if (delaySignAttribute != null)
                {
                    delaySign = (bool)delaySignAttribute;
                }

                var nullableAttribute = compilationOptionsElement.Attribute(NullableAttributeName);
                if (nullableAttribute != null)
                {
                    nullable = (NullableContextOptions)Enum.Parse(typeof(NullableContextOptions), nullableAttribute.Value);
                }

                var outputTypeAttribute = compilationOptionsElement.Attribute(OutputTypeAttributeName);
                if (outputTypeAttribute != null &&
                    outputTypeAttribute.Value == "WindowsRuntimeMetadata")
                {
                    if (rootNamespaceAttribute == null)
                    {
                        rootNamespace = new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).RootNamespace;
                    }

                    // VB needs Compilation.ParseOptions set (we do the same at the VS layer)
                    return(language == LanguageNames.CSharp
                       ? new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata, allowUnsafe: allowUnsafe)
                       : new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).WithGlobalImports(globalImports).WithRootNamespace(rootNamespace)
                           .WithParseOptions((VisualBasicParseOptions)parseOptions ?? VisualBasicParseOptions.Default));
                }
            }
            else
            {
                // Add some common global imports by default for VB
                globalImports.Add(GlobalImport.Parse("System"));
                globalImports.Add(GlobalImport.Parse("System.Collections.Generic"));
                globalImports.Add(GlobalImport.Parse("System.Linq"));
            }

            // TODO: Allow these to be specified.
            var languageServices   = workspace.Services.GetLanguageServices(language);
            var metadataService    = workspace.Services.GetService <IMetadataService>();
            var compilationOptions = languageServices.GetService <ICompilationFactoryService>().GetDefaultCompilationOptions();

            compilationOptions = compilationOptions.WithOutputKind(outputKind)
                                 .WithGeneralDiagnosticOption(reportDiagnostic)
                                 .WithSourceReferenceResolver(SourceFileResolver.Default)
                                 .WithXmlReferenceResolver(XmlFileResolver.Default)
                                 .WithMetadataReferenceResolver(new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(ImmutableArray <string> .Empty, null)))
                                 .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)
                                 .WithCryptoKeyFile(cryptoKeyFile)
                                 .WithStrongNameProvider(strongNameProvider)
                                 .WithDelaySign(delaySign)
                                 .WithOverflowChecks(checkOverflow);

            if (language == LanguageNames.CSharp)
            {
                compilationOptions = ((CSharpCompilationOptions)compilationOptions).WithAllowUnsafe(allowUnsafe).WithNullableContextOptions(nullable);
            }

            if (language == LanguageNames.VisualBasic)
            {
                // VB needs Compilation.ParseOptions set (we do the same at the VS layer)
                compilationOptions = ((VisualBasicCompilationOptions)compilationOptions).WithRootNamespace(rootNamespace)
                                     .WithGlobalImports(globalImports)
                                     .WithParseOptions((VisualBasicParseOptions)parseOptions ??
                                                       VisualBasicParseOptions.Default);
            }

            return(compilationOptions);
        }
        private static TestHostDocument CreateDocument(
            TestWorkspace workspace,
            XElement workspaceElement,
            XElement documentElement,
            ExportProvider exportProvider,
            HostLanguageServices languageServiceProvider,
            IDocumentServiceProvider documentServiceProvider,
            ref int documentId)
        {
            var isLinkFileAttribute = documentElement.Attribute(IsLinkFileAttributeName);
            var isLinkFile          = isLinkFileAttribute != null && ((bool?)isLinkFileAttribute).HasValue && ((bool?)isLinkFileAttribute).Value;

            if (isLinkFile)
            {
                // This is a linked file. Use the filePath and markup from the referenced document.

                var originalAssemblyName = documentElement.Attribute(LinkAssemblyNameAttributeName)?.Value;
                var originalProjectName  = documentElement.Attribute(LinkProjectNameAttributeName)?.Value;

                if (originalAssemblyName == null && originalProjectName == null)
                {
                    throw new ArgumentException($"Linked files must specify either a {LinkAssemblyNameAttributeName} or {LinkProjectNameAttributeName}");
                }

                var originalProject = workspaceElement.Elements(ProjectElementName).FirstOrDefault(p =>
                {
                    if (originalAssemblyName != null)
                    {
                        return(p.Attribute(AssemblyNameAttributeName)?.Value == originalAssemblyName);
                    }
                    else
                    {
                        return(p.Attribute(ProjectNameAttribute)?.Value == originalProjectName);
                    }
                });

                if (originalProject == null)
                {
                    if (originalProjectName != null)
                    {
                        throw new ArgumentException($"Linked file's {LinkProjectNameAttributeName} '{originalProjectName}' project not found.");
                    }
                    else
                    {
                        throw new ArgumentException($"Linked file's {LinkAssemblyNameAttributeName} '{originalAssemblyName}' project not found.");
                    }
                }

                var originalDocumentPath = documentElement.Attribute(LinkFilePathAttributeName)?.Value;

                if (originalDocumentPath == null)
                {
                    throw new ArgumentException($"Linked files must specify a {LinkFilePathAttributeName}");
                }

                documentElement = originalProject.Elements(DocumentElementName).FirstOrDefault(d =>
                {
                    return(d.Attribute(FilePathAttributeName)?.Value == originalDocumentPath);
                });

                if (documentElement == null)
                {
                    throw new ArgumentException($"Linked file's LinkFilePath '{originalDocumentPath}' file not found.");
                }
            }

            var markupCode = documentElement.NormalizedValue();
            var fileName   = GetFileName(workspace, documentElement, ref documentId);

            var folders        = GetFolders(documentElement);
            var optionsElement = documentElement.Element(ParseOptionsElementName);

            // TODO: Allow these to be specified.
            var codeKind = SourceCodeKind.Regular;

            if (optionsElement != null)
            {
                var attr = optionsElement.Attribute(KindAttributeName);
                codeKind = attr == null
                    ? SourceCodeKind.Regular
                    : (SourceCodeKind)Enum.Parse(typeof(SourceCodeKind), attr.Value);
            }

            TestFileMarkupParser.GetPositionAndSpans(markupCode,
                                                     out var code, out int?cursorPosition, out ImmutableDictionary <string, ImmutableArray <TextSpan> > spans);

            var testDocumentServiceProvider = GetDocumentServiceProvider(documentElement);

            if (documentServiceProvider == null)
            {
                documentServiceProvider = testDocumentServiceProvider;
            }
            else if (testDocumentServiceProvider != null)
            {
                AssertEx.Fail($"The document attributes on file {fileName} conflicted");
            }

            return(new TestHostDocument(
                       exportProvider, languageServiceProvider, code, fileName, fileName, cursorPosition, spans, codeKind, folders, isLinkFile, documentServiceProvider));
        }