예제 #1
0
        public async Task CheckPEReferencesSameAfterSolutionChangedTest()
        {
            using (var ws = new AdhocWorkspace())
            {
                var projectInfo = ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    "TestProject",
                    "TestProject",
                    LanguageNames.CSharp,
                    metadataReferences: ImmutableArray.Create<MetadataReference>(PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location)));

                var project = ws.AddProject(projectInfo);

                // get original references
                var compilation1 = await project.GetCompilationAsync();
                var references1 = compilation1.ExternalReferences;

                // just some arbitary action to create new snpahost that doesnt affect references
                var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "code.cs");
                var document = ws.AddDocument(info);

                // get new compilation
                var compilation2 = await document.Project.GetCompilationAsync();
                var references2 = compilation2.ExternalReferences;

                Assert.Equal(references1, references2);
            }
        }
예제 #2
0
        public static async Task <ImmutableArray <Diagnostic> > GetDiagnosticsAsync(DiagnosticAnalyzer analyzer, bool ignoreCompilationErrors, string source, params string[] additionalSources)
        {
            const string fileNamePrefix = "Source";
            const string projectName    = "Project";

            var projectId = ProjectId.CreateNewId(debugName: projectName);

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, projectName, projectName, LanguageNames.CSharp)
                           .AddMetadataReferences(projectId, new[] {
                CorlibReference,
                SystemCoreReference,
                SystemTextReference,
                SystemRuntimeReference,
                SystemThreadingTasksReference,
                XunitCoreReference,
                XunitAbstractionsReference,
                XunitAssertReference,
            });

            int count = 0;

            foreach (var text in new[] { source }.Concat(additionalSources))
            {
                var newFileName = $"{fileNamePrefix}{count++}.cs";
                var documentId  = DocumentId.CreateNewId(projectId, debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(text));
            }

            var project = solution.GetProject(projectId);

            project = project.WithCompilationOptions(((CSharpCompilationOptions)project.CompilationOptions).WithOutputKind(OutputKind.DynamicallyLinkedLibrary).WithWarningLevel(2));
            var compilation = await project.GetCompilationAsync();

            var compilationDiagnostics = compilation.GetDiagnostics();

            if (!ignoreCompilationErrors && compilationDiagnostics.Any())
            {
                Diagnostic error = compilationDiagnostics.First();
                throw new InvalidOperationException($"Compilation has errors. First error: {error.Id} {error.WarningLevel} {error.GetMessage()}");
            }

            var compilationWithAnalyzers = compilation
                                           .WithOptions(((CSharpCompilationOptions)compilation.Options)
                                                        .WithWarningLevel(4))
                                           .WithAnalyzers(ImmutableArray.Create(analyzer));

            var allDiagnostics = await compilationWithAnalyzers.GetAllDiagnosticsAsync();

            Assert.DoesNotContain(allDiagnostics, d => d.Id == "AD0001");

            return(await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync());
        }
 private static Document CreateDocument(string sourcePath)
 {
     var workspace = new AdhocWorkspace();
     var projectId = ProjectId.CreateNewId();
     var versionStamp = VersionStamp.Create();
     var projectInfo = ProjectInfo.Create(projectId, versionStamp, "NewProject", "Test", LanguageNames.CSharp);
     var newProject = workspace.AddProject(projectInfo);
     var source = File.ReadAllText(sourcePath);
     var sourceText = SourceText.From(source);
     return workspace.AddDocument(newProject.Id, Path.GetFileName(sourcePath), sourceText);
 }
예제 #4
0
        public async Task TestAddDocument_NameAndTextAsync()
        {
            using var ws = new AdhocWorkspace();
            var project = ws.AddProject("TestProject", LanguageNames.CSharp);
            var name    = "code.cs";
            var source  = "class C {}";
            var doc     = ws.AddDocument(project.Id, name, SourceText.From(source));

            Assert.Equal(name, doc.Name);
            Assert.Equal(source, (await doc.GetTextAsync()).ToString());
        }
        private Task <Project> CreateProject()
        {
            var fileNamePrefix  = "Test";
            var fileExt         = ".cs";
            var testProjectName = "TestProject";

            var projectId = ProjectId.CreateNewId(debugName: testProjectName);

            switch (TargetFramework)
            {
            case TargetFramework.NetStandard2_0:
                AddNuGetReference("NETStandard.Library", "2.0.3", "build/netstandard2.0/ref/");
                break;

            case TargetFramework.NetStandard2_1:
                AddNuGetReference("NETStandard.Library.Ref", "2.1.0", "ref/netstandard2.1/");
                break;

            case TargetFramework.Net48:
                AddNuGetReference("Microsoft.NETFramework.ReferenceAssemblies.net48", "1.0.0", "build/.NETFramework/v4.8/");
                break;
            }

            AddNuGetReference("System.Collections.Immutable", "1.5.0", "lib/netstandard2.0/");
            AddNuGetReference("System.Numerics.Vectors", "4.5.0", "ref/netstandard2.0/");
            AddNuGetReference("Microsoft.CSharp", "4.7.0", "lib/netstandard2.0/");  // To support dynamic type

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, testProjectName, testProjectName, LanguageNames.CSharp)
                           .WithProjectParseOptions(projectId, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion))
                           .AddMetadataReferences(projectId, References);

            var count = 0;

            AppendFile(FileName, SourceCode);

            foreach (var source in ApiReferences)
            {
                var newFileName = fileNamePrefix + count + fileExt;
                AppendFile(newFileName, source);
            }

            return(Task.FromResult(solution.GetProject(projectId)));

            void AppendFile(string filename, string content)
            {
                filename ??= fileNamePrefix + count + fileExt;
                var documentId = DocumentId.CreateNewId(projectId, debugName: filename);

                solution = solution.AddDocument(documentId, filename, SourceText.From(content), filePath: filename);
                count++;
            }
        }
예제 #6
0
        private Document CreateDocument(Project project, string name, string code)
        {
            var documentInfo = DocumentInfo.Create(
                id: DocumentId.CreateNewId(project.Id),
                name: name,
                sourceCodeKind: SourceCodeKind.Script,
                loader: TextLoader.From(TextAndVersion.Create(SourceText.From(code), VersionStamp.Create())));
            var document = workspace.AddDocument(documentInfo);

            return(document);
        }
예제 #7
0
        public async Task TestUpdateCSharpLanguageVersionAsync()
        {
            using (var ws = new AdhocWorkspace())
            {
                var projid = ws.AddProject("TestProject", LanguageNames.CSharp).Id;
                var docid1 = ws.AddDocument(projid, "A.cs", SourceText.From("public class A { }")).Id;
                var docid2 = ws.AddDocument(projid, "B.cs", SourceText.From("public class B { }")).Id;

                var pws  = new WorkspaceWithPartialSemantics(ws.CurrentSolution);
                var proj = pws.CurrentSolution.GetProject(projid);
                var comp = await proj.GetCompilationAsync();

                // change language version
                var parseOptions = proj.ParseOptions as CS.CSharpParseOptions;
                pws.SetParseOptions(projid, parseOptions.WithLanguageVersion(CS.LanguageVersion.CSharp3));

                // get partial semantics doc
                var frozen = pws.CurrentSolution.GetDocument(docid1).WithFrozenPartialSemantics(CancellationToken.None);
            }
        }
    public static async Task ScanHardcodedFromText(string documentName, string text, Action <SyntaxNodeOrToken, string> scannedFunction)
    {
        if (text == null)
        {
            throw new ArgumentNullException("text");
        }
        AdhocWorkspace ws      = new AdhocWorkspace();
        var            project = ws.AddProject(documentName + "Project", LanguageNames.CSharp);

        ws.AddDocument(project.Id, documentName, SourceText.From(text));
        await ScanHardcoded(ws, scannedFunction);
    }
예제 #9
0
        public void TestAddDocument_DocumentInfo()
        {
            using (var ws = new AdhocWorkspace())
            {
                var project = ws.AddProject("TestProject", LanguageNames.CSharp);
                var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "code.cs");
                var doc = ws.AddDocument(info);

                Assert.Equal(ws.CurrentSolution.GetDocument(info.Id), doc);
                Assert.Equal(info.Name, doc.Name);
            }
        }
예제 #10
0
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="fileSources">Classes in the form of MvxTestFileSources</param>
        /// <returns>A Solution created out of the Documents created from the source strings</returns>
        private static Solution CreateSolution(MvxTestFileSource[] fileSources)
        {
            string fileNamePrefix = DefaultFilePathPrefix;

            _coreProjectId  = ProjectId.CreateNewId(debugName: TestCoreProjectName);
            _droidProjectId = ProjectId.CreateNewId(debugName: TestDroidProjectName);
            _iosProjectId   = ProjectId.CreateNewId(debugName: TestIosProjectName);

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(_coreProjectId, TestCoreProjectName, TestCoreProjectName, LanguageNames.CSharp)
                           .AddProject(_droidProjectId, TestDroidProjectName, TestDroidProjectName, LanguageNames.CSharp)
                           .AddProject(_iosProjectId, TestIosProjectName, TestIosProjectName, LanguageNames.CSharp)
                           .AddMetadataReference(_coreProjectId, _corlibReference)
                           .AddMetadataReference(_coreProjectId, _systemCoreReference)
                           .AddMetadataReference(_coreProjectId, _cSharpSymbolsReference)
                           .AddMetadataReference(_coreProjectId, _codeAnalysisReference)
                           .AddMetadataReference(_coreProjectId, _mvvmCrossCoreReference)
                           .AddMetadataReference(_coreProjectId, _mvvmCrossPlatformReference)
                           .AddMetadataReference(_coreProjectId, _componentModelReference)
                           .AddMetadataReference(_coreProjectId, _objectModelReference)
                           .AddMetadataReference(_coreProjectId, _runtimeReference)
                           .AddMetadataReference(_droidProjectId, _corlibReference)
                           .AddMetadataReference(_droidProjectId, _systemCoreReference)
                           .AddMetadataReference(_droidProjectId, _cSharpSymbolsReference)
                           .AddMetadataReference(_droidProjectId, _codeAnalysisReference)
                           .AddMetadataReference(_droidProjectId, _mvvmCrossCoreReference)
                           .AddMetadataReference(_droidProjectId, _mvvmCrossDroidReference)
                           .AddMetadataReference(_droidProjectId, _componentModelReference)
                           .AddMetadataReference(_droidProjectId, _objectModelReference)
                           .AddProjectReference(_droidProjectId, new ProjectReference(_coreProjectId))
                           .AddMetadataReference(_iosProjectId, _corlibReference)
                           .AddMetadataReference(_iosProjectId, _systemCoreReference)
                           .AddMetadataReference(_iosProjectId, _cSharpSymbolsReference)
                           .AddMetadataReference(_iosProjectId, _codeAnalysisReference)
                           .AddMetadataReference(_iosProjectId, _mvvmCrossCoreReference)
                           .AddMetadataReference(_iosProjectId, _mvvmCrossIosReference)
                           .AddMetadataReference(_iosProjectId, _componentModelReference)
                           .AddMetadataReference(_iosProjectId, _objectModelReference)
                           .AddProjectReference(_iosProjectId, new ProjectReference(_coreProjectId));

            int count = 0;

            foreach (var fileSource in fileSources)
            {
                var newFileName = fileNamePrefix + count + "." + CSharpDefaultFileExt;
                var documentId  = DocumentId.CreateNewId(GetProjectId(fileSource), debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(fileSource.Source));
                count++;
            }

            return(solution);
        }
예제 #11
0
 private void LoadFolderDocuments(string folderName, AdhocWorkspace ws, ProjectId projectId)
 {
     foreach (var file in new DirectoryInfo(folderName).GetFiles("*.cs"))
     {
         var sourceText = SourceText.From(File.OpenRead(file.FullName));
         ws.AddDocument(projectId, file.Name, sourceText);
     }
     foreach (var dir in new DirectoryInfo(folderName).GetDirectories())
     {
         LoadFolderDocuments(dir.FullName, ws, projectId);
     }
 }
예제 #12
0
        public async Task TestOpenFileOnlyAnalyzerDiagnostics()
        {
            var workspace = new AdhocWorkspace();

            var project = workspace.AddProject(
                ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    "CSharpProject",
                    "CSharpProject",
                    LanguageNames.CSharp));

            var document = workspace.AddDocument(project.Id, "Empty.cs", SourceText.From(""));

            // create listener/service/analyzer
            var listener = new AsynchronousOperationListener();
            var service  = new MyDiagnosticAnalyzerService(new OpenFileOnlyAnalyzer(), listener);
            var analyzer = service.CreateIncrementalAnalyzer(workspace);

            // listen to events
            service.DiagnosticsUpdated += (s, a) =>
            {
                if (workspace.IsDocumentOpen(a.DocumentId))
                {
                    // check the diagnostics are reported
                    Assert.Equal(document.Id, a.DocumentId);
                    Assert.Equal(1, a.Diagnostics.Length);
                    Assert.Equal(OpenFileOnlyAnalyzer.s_syntaxRule.Id, a.Diagnostics[0].Id);
                }

                if (a.DocumentId == document.Id && !workspace.IsDocumentOpen(a.DocumentId))
                {
                    // check the diagnostics reported are cleared
                    Assert.Equal(0, a.Diagnostics.Length);
                }
            };

            // open document
            workspace.OpenDocument(document.Id);
            await analyzer.DocumentOpenAsync(document, CancellationToken.None).ConfigureAwait(false);

            // cause analysis
            await RunAllAnalysisAsync(analyzer, document).ConfigureAwait(false);

            // close document
            workspace.CloseDocument(document.Id);
            await analyzer.DocumentCloseAsync(document, CancellationToken.None).ConfigureAwait(false);

            await RunAllAnalysisAsync(analyzer, document).ConfigureAwait(false);

            // wait for all events to raised
            await listener.CreateWaitTask().ConfigureAwait(false);
        }
예제 #13
0
        private static Document GetDocumentFromIncompleteProject(AdhocWorkspace workspace)
        {
            var project = workspace.AddProject(
                ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    "CSharpProject",
                    "CSharpProject",
                    LanguageNames.CSharp).WithHasAllInformation(hasAllInformation: false));

            return(workspace.AddDocument(project.Id, "Empty.cs", SourceText.From("")));
        }
예제 #14
0
        public async Task TestCodeGeneration(string resourceBaseName, Language language)
        {
            var inputResourceName  = "BrightstarDB.CodeGeneration.Tests.GeneratorTestsResources." + resourceBaseName + "Input_" + language.ToString() + ".txt";
            var outputResourceName = "BrightstarDB.CodeGeneration.Tests.GeneratorTestsResources." + resourceBaseName + "Output_" + language.ToString() + ".txt";

            using (var inputStream = this.GetType().Assembly.GetManifestResourceStream(inputResourceName))
                using (var outputStream = this.GetType().Assembly.GetManifestResourceStream(outputResourceName))
                    using (var outputStreamReader = new StreamReader(outputStream))
                    {
                        var workspace    = new AdhocWorkspace();
                        var projectId    = ProjectId.CreateNewId();
                        var versionStamp = VersionStamp.Create();
                        var projectInfo  = ProjectInfo.Create(
                            projectId,
                            versionStamp,
                            "AdhocProject",
                            "AdhocProject",
                            language.ToSyntaxGeneratorLanguageName(),
                            metadataReferences: new[]
                        {
                            MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                            MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location),
                            MetadataReference.CreateFromFile(typeof(BrightstarException).Assembly.Location)
                        });
                        var project = workspace.AddProject(projectInfo);
                        workspace.AddDocument(projectId, "Source.cs", SourceText.From(inputStream));
                        var solution = workspace.CurrentSolution;

                        var results = await Generator
                                      .GenerateAsync(
                            language,
                            solution,
                            "BrightstarDB.CodeGeneration.Tests",
                            interfacePredicate : x => true);

                        var result = results
                                     .Aggregate(
                            new StringBuilder(),
                            (current, next) => current.AppendLine(next.ToString()),
                            x => x.ToString());

                        var expectedCode = outputStreamReader.ReadToEnd();

                        // make sure version changes don't break the tests
                        expectedCode = expectedCode.Replace("$VERSION$", typeof(BrightstarException).Assembly.GetName().Version.ToString());

                        //// useful when converting generated code to something that can be pasted into an expectation file
                        //var sanitisedResult = result.Replace("1.10.0.0", "$VERSION$");
                        //System.Diagnostics.Debug.WriteLine(sanitisedResult);

                        Assert.AreEqual(expectedCode, result);
                    }
        }
예제 #15
0
    static async Task TestScriptInstrumentingAsync()
    {
        var workspace   = new AdhocWorkspace();
        var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "TestProject", "TestProject", LanguageNames.CSharp);
        var project     = workspace.AddProject(projectInfo);
        var src         = SourceText.From(File.ReadAllText(@"C:\Users\ljw10\Documents\Visual Studio 2015\Projects\ScriptApplicationCS\CodeFile1.csx"));
        var document    = workspace.AddDocument(project.Id, "CodeFile1.csx", src).WithSourceCodeKind(SourceCodeKind.Script);

        document = await ReplayHost.InstrumentDocumentAsync(document, null, null, CancellationToken.None);

        Console.WriteLine($"{document.FilePath}\r\n{await document.GetTextAsync()}");
    }
예제 #16
0
        public void TestAddDocument_DocumentInfo()
        {
            using (var ws = new AdhocWorkspace())
            {
                var project = ws.AddProject("TestProject", LanguageNames.CSharp);
                var info    = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "code.cs");
                var doc     = ws.AddDocument(info);

                Assert.Equal(ws.CurrentSolution.GetDocument(info.Id), doc);
                Assert.Equal(info.Name, doc.Name);
            }
        }
예제 #17
0
        private static Project CreateProject(string[] sources, string[] filePaths)
        {
            if (filePaths != null && sources.Length != filePaths.Length)
            {
                throw new ArgumentException("Number of specified file paths does not match the number of sources");
            }

            if (filePaths != null && filePaths.Any(name => name == null))
            {
                throw new ArgumentException("File path can't be null");
            }

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp)
                           .AddMetadataReference(projectId, CorlibReference)
                           .AddMetadataReference(projectId, SystemCoreReference)
                           .AddMetadataReference(projectId, CSharpSymbolsReference)
                           .AddMetadataReference(projectId, CodeAnalysisReference);

            var count = 0;

            foreach (var source in sources)
            {
                var newFileName = filePaths != null
                    ? Path.GetFileName(filePaths[count])
                    : DefaultFilePathPrefix + count + "." + CSharpDefaultFileExt;

                var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName);
                solution = filePaths != null
                    ? solution.AddDocument(documentId, newFileName, SourceText.From(source), filePath : filePaths[count])
                    : solution.AddDocument(documentId, newFileName, SourceText.From(source));

                count++;
            }

            return(solution.GetProject(projectId));
        }
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <returns>A Project created out of the Documents created from the source strings</returns>
        private Project CreateProject(string[] sources, string language = LanguageNames.CSharp)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt        = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;

            ProjectId projectId = ProjectId.CreateNewId(debugName: TestProjectName);

            Solution solution = new AdhocWorkspace()
                                .CurrentSolution
                                .AddProject(projectId, TestProjectName, TestProjectName, language)
                                .AddMetadataReference(projectId, CorlibReference)
                                .AddMetadataReference(projectId, SystemCoreReference)
                                .AddMetadataReference(projectId, CSharpSymbolsReference)
                                .AddMetadataReference(projectId, CodeAnalysisReference)
                                .AddMetadataReference(projectId, SystemRuntimeExtensionsReference);

            int count = 0;

            foreach (string source in sources)
            {
                string     newFileName = fileNamePrefix + count + "." + fileExt;
                DocumentId documentId  = DocumentId.CreateNewId(projectId, debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(source));
                count++;
            }

            if (this.AdditionalCodeFiles != null)
            {
                count = 0;
                foreach (string source in this.AdditionalCodeFiles)
                {
                    string     newFileName = fileNamePrefix + "AdditionalFiles" + count + "." + fileExt;
                    DocumentId documentId  = DocumentId.CreateNewId(projectId, debugName: newFileName);
                    solution = solution.AddDocument(documentId, newFileName, SourceText.From(source));
                    count++;
                }
            }

            return(solution.GetProject(projectId));
        }
        public async Task UpdaterService()
        {
            var hostServices = s_composition.GetHostServices();

            using var workspace = new AdhocWorkspace(hostServices);

            var options = workspace.CurrentSolution.Options.WithChangedOption(
                RemoteHostOptions.SolutionChecksumMonitorBackOffTimeSpanInMS,
                1
                );

            workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options));

            var listenerProvider = (
                (IMefHostExportProvider)hostServices
                ).GetExportedValue <AsynchronousOperationListenerProvider>();

            var checksumUpdater = new SolutionChecksumUpdater(
                workspace,
                listenerProvider,
                CancellationToken.None
                );
            var service = workspace.Services.GetRequiredService <IRemoteHostClientProvider>();

            // make sure client is ready
            using var client = await service.TryGetRemoteHostClientAsync(CancellationToken.None);

            // add solution, change document
            workspace.AddSolution(
                SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default)
                );
            var project  = workspace.AddProject("proj", LanguageNames.CSharp);
            var document = workspace.AddDocument(project.Id, "doc.cs", SourceText.From("code"));

            workspace.ApplyTextChanges(
                document.Id,
                new[] { new TextChange(new TextSpan(0, 1), "abc") },
                CancellationToken.None
                );

            // wait for listener
            var workspaceListener = listenerProvider.GetWaiter(FeatureAttribute.Workspace);
            await workspaceListener.ExpeditedWaitAsync();

            var listener = listenerProvider.GetWaiter(FeatureAttribute.SolutionChecksumUpdater);
            await listener.ExpeditedWaitAsync();

            // checksum should already exist
            Assert.True(workspace.CurrentSolution.State.TryGetStateChecksums(out _));

            checksumUpdater.Shutdown();
        }
예제 #20
0
        public void LinkedFiles()
        {
            // We want to assert that if the open document is linked into multiple projects, we
            // update all documents at the same time with the changed text. Otherwise things will get
            // out of sync.
            var exportProvider = TestExportProvider.MinimumExportProviderFactoryWithCSharpAndVisualBasic.CreateExportProvider();

            using var workspace = new AdhocWorkspace();
            var textBufferFactoryService = exportProvider.GetExportedValue <ITextBufferFactoryService>();
            var buffer = textBufferFactoryService.CreateTextBuffer("Hello", textBufferFactoryService.TextContentType);
            var sourceTextContainer = buffer.AsTextContainer();

            // We're going to add two projects that both consume the same file
            const string FilePath    = "Z:\\Foo.cs";
            var          documentIds = new List <DocumentId>();

            for (var i = 0; i < 2; i++)
            {
                var projectId  = workspace.AddProject($"Project{i}", LanguageNames.CSharp).Id;
                var documentId = DocumentId.CreateNewId(projectId);
                workspace.AddDocument(DocumentInfo.Create(documentId, "Foo.cs", filePath: FilePath));
                workspace.OnDocumentOpened(documentId, sourceTextContainer);

                documentIds.Add(documentId);
            }

            // Confirm the files have been linked by file path. This isn't the core part of this test but without it
            // nothing else will work.
            Assert.Equal(documentIds, workspace.CurrentSolution.GetDocumentIdsWithFilePath(FilePath));
            Assert.Equal(new[] { documentIds.Last() }, workspace.CurrentSolution.GetDocument(documentIds.First()).GetLinkedDocumentIds());

            // Now the core test: first, if we make a modified version of the source text, and attempt to get the document for it,
            // both copies should be updated.
            var originalSnapshot = buffer.CurrentSnapshot;

            buffer.Insert(5, ", World!");

            var newDocumentWithChanges = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();

            // Since we're calling this on the current snapshot and we observed the text edit synchronously,
            // no forking actually should have happened.
            Assert.Same(workspace.CurrentSolution, newDocumentWithChanges.Project.Solution);
            Assert.Equal("Hello, World!", newDocumentWithChanges.GetTextSynchronously(CancellationToken.None).ToString());
            Assert.Equal("Hello, World!", newDocumentWithChanges.GetLinkedDocuments().Single().GetTextSynchronously(CancellationToken.None).ToString());

            // Now let's fetch back for the original snapshot. Both linked copies should be updated.
            var originalDocumentWithChanges = originalSnapshot.GetOpenDocumentInCurrentContextWithChanges();

            Assert.NotSame(workspace.CurrentSolution, originalDocumentWithChanges.Project.Solution);
            Assert.Equal("Hello", originalDocumentWithChanges.GetTextSynchronously(CancellationToken.None).ToString());
            Assert.Equal("Hello", originalDocumentWithChanges.GetLinkedDocuments().Single().GetTextSynchronously(CancellationToken.None).ToString());
        }
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <returns>A Project created out of the Documents created from the source strings</returns>
        private static Project CreateProject(string[]                           sources,
                                             Version dotNetVersion,
                                             string language = LanguageNames.CSharp,
                                             IEnumerable <MetadataReference> references = null)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt        = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;

            var options = language == LanguageNames.CSharp ? CSharpDefaultOptions : VisualBasicDefaultOptions;

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

            var refAssemblies = ReferenceAssemblies.GetCache(dotNetVersion ?? new Version(4, 5, 2));

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, TestProjectName, TestProjectName, language)
                           // Todo: rework assembly references for .NET Core, because currently mscorlib is always referenced
                           // need to reference nuget packages like .AddPackages in https://github.com/dotnet/roslyn-analyzers/blob/master/src/Test.Utilities/AdditionalMetadataReferences.cs
                           .AddMetadataReference(projectId, refAssemblies.GetMetadata("mscorlib.dll"))
                           .AddMetadataReference(projectId, refAssemblies.GetMetadata("System.Core.dll"))
                           .AddMetadataReference(projectId, refAssemblies.GetMetadata("System.dll"))
                           .AddMetadataReference(projectId, refAssemblies.GetMetadata("System.Xml.dll"))
                           .AddMetadataReference(projectId, refAssemblies.GetMetadata("System.Data.dll"))
                           .AddMetadataReference(projectId, CodeAnalysisReference)
                           .WithProjectCompilationOptions(projectId, options);

            if (references != null)
            {
                solution = solution.AddMetadataReferences(projectId, references);
            }

            int count = 0;

            foreach (var source in sources)
            {
                var newFileName = $"{fileNamePrefix}{count}.{fileExt}";
                var documentId  = DocumentId.CreateNewId(projectId, debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(source));
                count++;
            }

            var newProject = solution.GetProject(projectId);

            return(newProject);

            //var parseOptions = newProject.ParseOptions.WithFeatures(
            //        newProject.ParseOptions.Features.Concat(
            //            new[] { new KeyValuePair<string, string>("flow-analysis", "true") }));

            //return newProject.WithParseOptions(parseOptions);
        }
예제 #22
0
        public void TestAddDocument_NameAndText()
        {
            using (var ws = new AdhocWorkspace())
            {
                var project = ws.AddProject("TestProject", LanguageNames.CSharp);
                var name = "code.cs";
                var source = "class C {}";
                var doc = ws.AddDocument(project.Id, name, SourceText.From(source));

                Assert.Equal(name, doc.Name);
                Assert.Equal(source, doc.GetTextAsync().Result.ToString());
            }
        }
예제 #23
0
        public static Workspace Create(string text, string language = LanguageNames.CSharp)
        {
            var workspace = new AdhocWorkspace();

            var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "TestProject", "TestProject", language,
                                                 filePath: "D:\\Test.proj",
                                                 metadataReferences: new[] { s_corlibReference, s_systemCoreReference, s_systemReference });
            Project project = workspace.AddProject(projectInfo);

            workspace.AddDocument(project.Id, "TestDocument", SourceText.From(text));

            return(workspace);
        }
예제 #24
0
        Microsoft.CodeAnalysis.Document GetAnalysisDocument(string text)
        {
            var workspace = new AdhocWorkspace();

            string projectName  = "TestProject";
            var    projectId    = ProjectId.CreateNewId();
            var    versionStamp = VersionStamp.Create();
            var    projectInfo  = ProjectInfo.Create(projectId, versionStamp, projectName, projectName, LanguageNames.CSharp);
            var    sourceText   = SourceText.From(text);
            var    project      = workspace.AddProject(projectInfo);

            return(workspace.AddDocument(project.Id, "Program.cs", sourceText));
        }
예제 #25
0
        public TestHelper(string source)
        {
            Workspace = new AdhocWorkspace();

            string projName     = "NewProject";
            var    projectId    = ProjectId.CreateNewId();
            var    versionStamp = VersionStamp.Create();
            var    projectInfo  = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp);
            var    newProject   = Workspace.AddProject(projectInfo);
            var    sourceText   = SourceText.From(source);

            Document = Workspace.AddDocument(newProject.Id, "NewFile.cs", sourceText);
        }
예제 #26
0
    private static Document CreateDocument(string filename)
    {
        var workspace    = new AdhocWorkspace();
        var projectId    = ProjectId.CreateNewId();
        var versionStamp = VersionStamp.Create();
        var projectInfo  = ProjectInfo.Create(projectId, versionStamp, "NewProject", "projName", LanguageNames.CSharp);
        var newProject   = workspace.AddProject(projectInfo);
        var sourcePath   = $@"..\..\..\{filename}";
        var source       = File.ReadAllText(sourcePath);
        var sourceText   = SourceText.From(source);

        return(workspace.AddDocument(newProject.Id, filename, sourceText));
    }
        public static Project FromDirectory(params string[] directories)
        {
            var project = new AdhocWorkspace().AddProject(Guid.NewGuid().ToString(), LanguageNames.CSharp);
            var files   = directories.SelectMany(d => Directory.EnumerateFiles(d, "*.cs", SearchOption.AllDirectories)).ToArray();

            foreach (var path in files)
            {
                var fileInfo = new FileInfo(path);
                project = project.AddDocument(fileInfo.Name, File.ReadAllText(fileInfo.FullName)).Project;
            }

            return(project);
        }
        private static Document CreateDocumentWithoutText()
        {
            var project = ProjectInfo
                          .Create(ProjectId.CreateNewId(), VersionStamp.Default, "TestProject", "TestAssembly", LanguageNames.CSharp)
                          .WithFilePath("/TestProject.csproj");
            var workspace = new AdhocWorkspace();

            workspace.AddProject(project);
            var documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "Test.cshtml");
            var document     = workspace.AddDocument(documentInfo);

            return(document);
        }
예제 #29
0
 public static void InitWorkspace(AdhocWorkspace workspace, string code, int position)
 {
     string projName     = "NewProject";
     var    projectId    = ProjectId.CreateNewId();
     var    versionStamp = VersionStamp.Create();
     var    mscorlib     = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
     var    systemCore   = MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location);
     var    references   = new[] { mscorlib, systemCore };
     var    projectInfo  = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp, metadataReferences: references);
     var    newProject   = workspace.AddProject(projectInfo);
     var    sourceText   = SourceText.From(code);
     var    newDocument  = workspace.AddDocument(newProject.Id, "NewFile.cs", sourceText);
 }
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <returns>A Project created out of the Documents created from the source strings</returns>
        private static Project CreateProject(string[] sources, string language = LanguageNames.CSharp)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt        = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, TestProjectName, TestProjectName, language)
                           .AddMetadataReference(projectId, CorlibReference)
                           .AddMetadataReference(projectId, SystemReference)
                           .AddMetadataReference(projectId, SystemCoreReference)
                           .AddMetadataReference(projectId, CSharpSymbolsReference)
                           .AddMetadataReference(projectId, CodeAnalysisReference)
                           .AddMetadataReference(projectId, SystemRuntimeReference)
                           .AddMetadataReference(projectId, MigrationReference)
                           .AddMetadataReference(projectId, SerializationReference)
                           .AddMetadataReference(projectId, CryptoAlgoReference)
                           .AddMetadataReference(projectId, SystemDynamicRuntimeReference)
                           .AddMetadataReference(projectId, SystemLinqExpressionsReference)
                           .AddMetadataReference(projectId, NetStandard)
                           .AddMetadataReference(projectId, SystemObjectModelReference)
                           .AddMetadataReference(projectId, JsonNetReference);
            var compilationOptions = solution
                                     .GetProject(projectId)
                                     .CompilationOptions
                                     .WithOutputKind(OutputKind.DynamicallyLinkedLibrary);

            solution = solution
                       .WithProjectCompilationOptions(projectId, compilationOptions);

            int count = 0;

            foreach (var source in sources)
            {
                var newFileName = fileNamePrefix + count + "." + fileExt;
                var documentId  = DocumentId.CreateNewId(projectId, debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(source));
                count++;
            }
            var project = solution.GetProject(projectId);

            var ignore =
                "Assuming assembly reference 'System.Linq.Expressions, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' used by 'Newtonsoft.Json' matches identity 'System.Linq.Expressions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' of 'System.Linq.Expressions', you may need to supply runtime policy";

            var diangostics = project.GetCompilationAsync().Result.GetDiagnostics().Where(d => !d.GetMessage().Contains(ignore));

            diangostics.Should().BeEmpty();
            return(project);
        }
예제 #31
0
    public async Task PublicOptions()
    {
        using var workspace = new AdhocWorkspace();
        var csProject  = workspace.AddProject("CS", LanguageNames.CSharp);
        var vbProject  = workspace.AddProject("VB", LanguageNames.VisualBasic);
        var csDocument = workspace.AddDocument(csProject.Id, "File.cs", SourceText.From("class C { }"));
        var vbDocument = workspace.AddDocument(vbProject.Id, "File.vb", SourceText.From("Class C : End Class"));

        var updatedOptions = GetOptionSetWithChangedPublicOptions(workspace.CurrentSolution.Options);

        // Validate that options are read from specified OptionSet:

        ValidateCSharpOptions((CSharpSyntaxFormattingOptions)(await Formatter.GetOptionsAsync(csDocument, updatedOptions, CancellationToken.None)).Syntax !);
        ValidateVisualBasicOptions((VisualBasicSyntaxFormattingOptions)(await Formatter.GetOptionsAsync(vbDocument, updatedOptions, CancellationToken.None)).Syntax !);

        // Validate that options are read from solution snapshot as a fallback (we have no editorconfig file, so all options should fall back):

        var solutionWithUpdatedOptions   = workspace.CurrentSolution.WithOptions(updatedOptions);
        var csDocumentWithUpdatedOptions = solutionWithUpdatedOptions.GetRequiredDocument(csDocument.Id);
        var vbDocumentWithUpdatedOptions = solutionWithUpdatedOptions.GetRequiredDocument(vbDocument.Id);

        ValidateCSharpOptions((CSharpSyntaxFormattingOptions)(await Formatter.GetOptionsAsync(csDocumentWithUpdatedOptions, optionSet: null, CancellationToken.None)).Syntax !);
        ValidateVisualBasicOptions((VisualBasicSyntaxFormattingOptions)(await Formatter.GetOptionsAsync(vbDocumentWithUpdatedOptions, optionSet: null, CancellationToken.None)).Syntax !);
예제 #32
0
        public void Test1()
        {
            var file = $"{TestContext.CurrentContext.TestDirectory}/../../../TestRoslyn.cs";
            var assemblies = new[] { typeof(object), typeof(Enumerable), typeof(TestAttribute) }.Select(x => x.Assembly.Location).ToArray();

            var project = new AdhocWorkspace().AddProject("test", LanguageNames.CSharp);

            project = project.AddDocument(Path.GetFileName(file), File.ReadAllText(file)).Project;
            project = project.AddMetadataReferences(assemblies.Select(x => MetadataReference.CreateFromFile(x)));

            var compilation = project.GetCompilationAsync().GetAwaiter().GetResult();
            var c           = compilation.WithAnalyzers(ImmutableArray.Create((DiagnosticAnalyzer) new AssertEqualsAnalyzer()));
            var diagnostics = c.GetAnalyzerDiagnosticsAsync().GetAwaiter().GetResult();
        }
예제 #33
0
        Document AddDocument(Project testProject, string dir, string fileName, SourceText content)
        {
            DocumentInfo documentInfo = DocumentInfo.Create(
                DocumentId.CreateNewId(testProject.Id),
                fileName,
                new List <string> {
                dir
            },
                SourceCodeKind.Regular,
                TextLoader.From(TextAndVersion.Create(content, VersionStamp.Create())),
                Path.Combine(dir, fileName));

            return(workspace.AddDocument(documentInfo));
        }
        private static Document GetDocumentFromIncompleteProject(AdhocWorkspace workspace)
        {
            var project = workspace.AddProject(
                            ProjectInfo.Create(
                                ProjectId.CreateNewId(),
                                VersionStamp.Create(),
                                "CSharpProject",
                                "CSharpProject",
                                LanguageNames.CSharp).WithHasAllInformation(hasAllInformation: false));

            return workspace.AddDocument(project.Id, "Empty.cs", SourceText.From(""));
        }
예제 #35
0
        public async Task TestUpdateCSharpLanguageVersionAsync()
        {
            using (var ws = new AdhocWorkspace())
            {
                var projid = ws.AddProject("TestProject", LanguageNames.CSharp).Id;
                var docid1 = ws.AddDocument(projid, "A.cs", SourceText.From("public class A { }")).Id;
                var docid2 = ws.AddDocument(projid, "B.cs", SourceText.From("public class B { }")).Id;

                var pws = new WorkspaceWithPartialSemantics(ws.CurrentSolution);
                var proj = pws.CurrentSolution.GetProject(projid);
                var comp = await proj.GetCompilationAsync();

                // change language version
                var parseOptions = proj.ParseOptions as CS.CSharpParseOptions;
                pws.SetParseOptions(projid, parseOptions.WithLanguageVersion(CS.LanguageVersion.CSharp3));

                // get partial semantics doc
                var frozen = await pws.CurrentSolution.GetDocument(docid1).WithFrozenPartialSemanticsAsync(CancellationToken.None);
            }
        }
        public async Task TestOpenFileOnlyAnalyzerDiagnostics()
        {
            var workspace = new AdhocWorkspace();

            var project = workspace.AddProject(
                           ProjectInfo.Create(
                               ProjectId.CreateNewId(),
                               VersionStamp.Create(),
                               "CSharpProject",
                               "CSharpProject",
                               LanguageNames.CSharp));

            var document = workspace.AddDocument(project.Id, "Empty.cs", SourceText.From(""));

            // create listener/service/analyzer
            var listener = new AsynchronousOperationListener();
            var service = new MyDiagnosticAnalyzerService(new OpenFileOnlyAnalyzer(), listener);
            var analyzer = service.CreateIncrementalAnalyzer(workspace);

            // listen to events
            service.DiagnosticsUpdated += (s, a) =>
            {
                if (workspace.IsDocumentOpen(a.DocumentId))
                {
                    // check the diagnostics are reported
                    Assert.Equal(document.Id, a.DocumentId);
                    Assert.Equal(1, a.Diagnostics.Length);
                    Assert.Equal(OpenFileOnlyAnalyzer.s_syntaxRule.Id, a.Diagnostics[0].Id);
                }

                if (a.DocumentId == document.Id && !workspace.IsDocumentOpen(a.DocumentId))
                {
                    // check the diagnostics reported are cleared
                    Assert.Equal(0, a.Diagnostics.Length);
                }
            };

            // open document
            workspace.OpenDocument(document.Id);
            await analyzer.DocumentOpenAsync(document, CancellationToken.None).ConfigureAwait(false);

            // cause analysis
            await RunAllAnalysisAsync(analyzer, document).ConfigureAwait(false);

            // close document
            workspace.CloseDocument(document.Id);
            await analyzer.DocumentCloseAsync(document, CancellationToken.None).ConfigureAwait(false);

            await RunAllAnalysisAsync(analyzer, document).ConfigureAwait(false);

            // wait for all events to raised
            await listener.CreateWaitTask().ConfigureAwait(false);
        }