コード例 #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 void TestAddSolution_SolutionInfo()
        {
            using (var ws = new AdhocWorkspace())
            {
                var pinfo = ProjectInfo.Create(
                        ProjectId.CreateNewId(),
                        version: VersionStamp.Default,
                        name: "TestProject",
                        assemblyName: "TestProject.dll",
                        language: LanguageNames.CSharp);

                var sinfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, projects: new ProjectInfo[] { pinfo });

                var solution = ws.AddSolution(sinfo);

                Assert.Same(ws.CurrentSolution, solution);
                Assert.Equal(solution.Id, sinfo.Id);

                Assert.Equal(sinfo.Projects.Count, solution.ProjectIds.Count);
                var project = solution.Projects.FirstOrDefault();
                Assert.NotNull(project);
                Assert.Equal(pinfo.Name, project.Name);
                Assert.Equal(pinfo.Id, project.Id);
                Assert.Equal(pinfo.AssemblyName, project.AssemblyName);
                Assert.Equal(pinfo.Language, project.Language);
            }
        }
コード例 #3
0
        internal void Test(
            Func<SyntaxGenerator, SyntaxNode> nodeCreator,
            string cs, string vb)
        {
            var hostServices = MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider());
            var workspace = new AdhocWorkspace(hostServices);

            if (cs != null)
            {
                var csharpCodeGenService = workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ICodeGenerationService>();
                var codeDefFactory = workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService<SyntaxGenerator>();

                var node = nodeCreator(codeDefFactory);
                node = node.NormalizeWhitespace();
                TokenUtilities.AssertTokensEqual(cs, node.ToFullString(), LanguageNames.CSharp);
            }

            if (vb != null)
            {
                var visualBasicCodeGenService = workspace.Services.GetLanguageServices(LanguageNames.VisualBasic).GetService<ICodeGenerationService>();
                var codeDefFactory = workspace.Services.GetLanguageServices(LanguageNames.VisualBasic).GetService<SyntaxGenerator>();

                var node = nodeCreator(codeDefFactory);
                node = node.NormalizeWhitespace();
                TokenUtilities.AssertTokensEqual(vb, node.ToString(), LanguageNames.VisualBasic);
            }
        }
コード例 #4
0
 public void TestPreviewCreationWithSolution()
 {
     using (var custom = new AdhocWorkspace())
     using (var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution))
     {
         Assert.NotNull(previewWorkspace.CurrentSolution);
     }
 }
コード例 #5
0
 public void TestAddProject_NameAndLanguage()
 {
     using (var ws = new AdhocWorkspace())
     {
         var project = ws.AddProject("TestProject", LanguageNames.CSharp);
         Assert.Same(project, ws.CurrentSolution.Projects.FirstOrDefault());
         Assert.Equal("TestProject", project.Name);
         Assert.Equal(LanguageNames.CSharp, project.Language);
     }
 }
コード例 #6
0
        public async Task CreateSolutionSnapshotId_Empty_Serialization()
        {
            var solution = new AdhocWorkspace().CurrentSolution;

            var snapshotService = (new SolutionChecksumServiceFactory()).CreateService(solution.Workspace.Services) as ISolutionChecksumService;
            using (var snapshot = await snapshotService.CreateChecksumAsync(solution, CancellationToken.None).ConfigureAwait(false))
            {
                await VerifySnapshotSerializationAsync(snapshotService, solution, snapshot.SolutionChecksum).ConfigureAwait(false);
            }
        }
コード例 #7
0
        public void TestCreateWithoutRequiredServices()
        {
            string commandLine = @"foo.cs";

            Assert.Throws<InvalidOperationException>(delegate
            {
                var ws = new AdhocWorkspace(); // only includes portable services
                var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory", ws);
            });
        }
コード例 #8
0
ファイル: WorkspaceTests.cs プロジェクト: XieShuquan/roslyn
        public void TestDefaultCompositionIncludesFeaturesLayer()
        {
            var ws = new AdhocWorkspace();

            var csservice = ws.Services.GetLanguageServices(LanguageNames.CSharp).GetService<Microsoft.CodeAnalysis.Completion.CompletionService>();
            Assert.NotNull(csservice);

            var vbservice = ws.Services.GetLanguageServices(LanguageNames.VisualBasic).GetService<Microsoft.CodeAnalysis.Completion.CompletionService>();
            Assert.NotNull(vbservice);
        }
コード例 #9
0
        public async Task CreateSolutionSnapshotId_Project_Serialization()
        {
            var solution = new AdhocWorkspace().CurrentSolution;
            var project = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp);

            var snapshotService = (new SolutionChecksumServiceFactory()).CreateService(solution.Workspace.Services) as ISolutionChecksumService;
            using (var snapshot = await snapshotService.CreateChecksumAsync(project.Solution, CancellationToken.None).ConfigureAwait(false))
            {
                await VerifySnapshotSerializationAsync(snapshotService, solution, snapshot.SolutionChecksum).ConfigureAwait(false);
            }
        }
コード例 #10
0
        public void AcquireCompletionService()
        {
            var workspace = new AdhocWorkspace();

            var document = workspace
                .AddProject("TestProject", LanguageNames.CSharp)
                .AddDocument("TestDocument.cs", "");

            var service = CompletionService.GetService(document);
            Assert.NotNull(service);
        }
コード例 #11
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);
            }
        }
コード例 #12
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());
            }
        }
コード例 #13
0
        public async Task CreateSolutionSnapshotId_Empty()
        {
            var solution = new AdhocWorkspace().CurrentSolution;

            var snapshotService = (new SolutionChecksumServiceFactory()).CreateService(solution.Workspace.Services) as ISolutionChecksumService;
            using (var snapshot = await snapshotService.CreateChecksumAsync(solution, CancellationToken.None).ConfigureAwait(false))
            {
                var solutionId = snapshot.SolutionChecksum;
                VerifyChecksumObjectInService(snapshotService, solutionId);
                VerifyChecksumInService(snapshotService, solutionId.Info, WellKnownChecksumObjects.SolutionChecksumObjectInfo);
                VerifyChecksumObjectInService(snapshotService, solutionId.Projects);

                Assert.Equal(solutionId.Projects.Count, 0);
            }
        }
コード例 #14
0
ファイル: SymbolEditorTests.cs プロジェクト: ralfkang/roslyn
        private Solution GetSolution(params string[] sources)
        {
            var ws = new AdhocWorkspace();
            var pid = ProjectId.CreateNewId();

            var docs = sources.Select((s, i) =>
                DocumentInfo.Create(
                    DocumentId.CreateNewId(pid),
                    name: "code" + i,
                    loader: TextLoader.From(TextAndVersion.Create(SourceText.From(s), VersionStamp.Default)))).ToList();

            var proj = ProjectInfo.Create(pid, VersionStamp.Default, "test", "test.dll", LanguageNames.CSharp, documents: docs,
                metadataReferences: new[] { TestReferences.NetFx.v4_0_30319.mscorlib });

            return ws.AddProject(proj).Solution;
        }
コード例 #15
0
        public async Task CreateSolutionSnapshotId_Project()
        {
            var solution = new AdhocWorkspace().CurrentSolution;
            var project = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp);

            var snapshotService = (new SolutionChecksumServiceFactory()).CreateService(solution.Workspace.Services) as ISolutionChecksumService;
            using (var snapshot = await snapshotService.CreateChecksumAsync(project.Solution, CancellationToken.None).ConfigureAwait(false))
            {
                var solutionId = snapshot.SolutionChecksum;
                VerifyChecksumObjectInService(snapshotService, solutionId);
                VerifyChecksumInService(snapshotService, solutionId.Info, WellKnownChecksumObjects.SolutionChecksumObjectInfo);
                VerifyChecksumObjectInService(snapshotService, solutionId.Projects);

                Assert.Equal(solutionId.Projects.Count, 1);
                VerifySnapshotInService(snapshotService, solutionId.Projects.ToProjectObjects(snapshotService)[0], 0, 0, 0, 0, 0);
            }
        }
コード例 #16
0
        public async Task TestHasSuccessfullyLoadedBeingFalseWhenFileOpened()
        {
            var workspace = new AdhocWorkspace();
            var document = GetDocumentFromIncompleteProject(workspace);

            // open document
            workspace.OpenDocument(document.Id);

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

            bool syntax = false;
            bool semantic = false;

            // listen to events
            service.DiagnosticsUpdated += (s, a) =>
            {
                switch (a.Diagnostics.Length)
                {
                    case 0:
                        return;
                    case 1:
                        syntax |= a.Diagnostics[0].Id == Analyzer.s_syntaxRule.Id;
                        semantic |= a.Diagnostics[0].Id == Analyzer.s_semanticRule.Id;
                        return;
                    default:
                        AssertEx.Fail("shouldn't reach here");
                        return;
                }
            };

            // now call each analyze method. none of them should run.
            await analyzer.AnalyzeSyntaxAsync(document, InvocationReasons.Empty, CancellationToken.None).ConfigureAwait(false);
            await analyzer.AnalyzeDocumentAsync(document, bodyOpt: null, reasons: InvocationReasons.Empty, cancellationToken: CancellationToken.None).ConfigureAwait(false);
            await analyzer.AnalyzeProjectAsync(document.Project, semanticsChanged: true, reasons: InvocationReasons.Empty, cancellationToken: CancellationToken.None).ConfigureAwait(false);

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

            // two should have been called.
            Assert.True(syntax);
            Assert.True(semantic);
        }
コード例 #17
0
        public void TestAddProject_ProjectInfo()
        {
            var info = ProjectInfo.Create(
                ProjectId.CreateNewId(),
                version: VersionStamp.Default,
                name: "TestProject",
                assemblyName: "TestProject.dll",
                language: LanguageNames.CSharp);

            using (var ws = new AdhocWorkspace())
            {
                var project = ws.AddProject(info);
                Assert.Equal(project, ws.CurrentSolution.Projects.FirstOrDefault());
                Assert.Equal(info.Name, project.Name);
                Assert.Equal(info.Id, project.Id);
                Assert.Equal(info.AssemblyName, project.AssemblyName);
                Assert.Equal(info.Language, project.Language);
            }
        }
コード例 #18
0
        public void AcquireCompletionService()
        {
            var hostServices = MefHostServices.Create(
                MefHostServices.DefaultAssemblies.Concat(
                    new[]
                    {
                        typeof(CompletionService).Assembly,
                        typeof(CSharpCompletionService).Assembly
                    }));

            var workspace = new AdhocWorkspace(hostServices);

            var document = workspace
                .AddProject("TestProject", LanguageNames.CSharp)
                .AddDocument("TestDocument.cs", "");

            var service = CompletionService.GetService(document);
            Assert.NotNull(service);
        }
コード例 #19
0
        public async Task TestHasSuccessfullyLoadedBeingFalse()
        {
            var workspace = new AdhocWorkspace();
            var document = GetDocumentFromIncompleteProject(workspace);

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

            // listen to events
            // check empty since this could be called to clear up existing diagnostics
            service.DiagnosticsUpdated += (s, a) => Assert.Empty(a.Diagnostics);

            // now call each analyze method. none of them should run.
            await RunAllAnalysisAsync(analyzer, document).ConfigureAwait(false);

            // wait for all events to raised
            await listener.CreateWaitTask().ConfigureAwait(false);
        }
コード例 #20
0
        public void TestLinkedFileSet(string startText, List<string> updatedTexts, string expectedMergedText, string languageName)
        {
            using (var workspace = new AdhocWorkspace())
            {
                var solution = workspace.CurrentSolution;
                var startSourceText = SourceText.From(startText);
                var documentIds = new List<DocumentId>();

                for (int i = 0; i < updatedTexts.Count; i++)
                {
                    var projectId = ProjectId.CreateNewId();
                    var documentId = DocumentId.CreateNewId(projectId);
                    documentIds.Add(documentId);

                    var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), "ProjectName" + i, "AssemblyName" + i, languageName);

                    solution = solution
                        .AddProject(projectInfo)
                        .AddDocument(documentId, "DocumentName", startSourceText, filePath: "FilePath");
                }

                var startingSolution = solution;
                var updatedSolution = solution;

                for (int i = 0; i < updatedTexts.Count; i++)
                {
                    var text = updatedTexts[i];
                    if (text != startText)
                    {
                        updatedSolution = updatedSolution
                            .WithDocumentText(documentIds[i], SourceText.From(text));
                    }
                }

                var mergedSolution = updatedSolution.WithMergedLinkedFileChangesAsync(startingSolution).Result;
                for (int i = 0; i < updatedTexts.Count; i++)
                {
                    Assert.Equal(expectedMergedText, mergedSolution.GetDocument(documentIds[i]).GetTextAsync().Result.ToString());
                }
            }
        }
コード例 #21
0
        public async Task CreateSolutionSnapshotId_Empty()
        {
            var solution = new AdhocWorkspace().CurrentSolution;

            var snapshotService = (new SolutionSynchronizationServiceFactory()).CreateService(solution.Workspace.Services) as ISolutionSynchronizationService;
            using (var snapshot = await snapshotService.CreatePinnedRemotableDataScopeAsync(solution, CancellationToken.None).ConfigureAwait(false))
            {
                var checksum = snapshot.SolutionChecksum;
                var solutionSyncObject = snapshotService.GetRemotableData(checksum, CancellationToken.None);

                VerifySynchronizationObjectInService(snapshotService, solutionSyncObject);

                var solutionObject = await snapshotService.GetValueAsync<SolutionStateChecksums>(checksum).ConfigureAwait(false);
                VerifyChecksumInService(snapshotService, solutionObject.Info, WellKnownSynchronizationKinds.SolutionAttributes);

                var projectsSyncObject = snapshotService.GetRemotableData(solutionObject.Projects.Checksum, CancellationToken.None);
                VerifySynchronizationObjectInService(snapshotService, projectsSyncObject);

                Assert.Equal(solutionObject.Projects.Count, 0);
            }
        }
コード例 #22
0
        public async Task ImmediatelyDerivedTypes_CSharp_AliasedNames()
        {
            var solution = new AdhocWorkspace().CurrentSolution;

            // create portable assembly with an abstract base class
            solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.CSharp, @"
namespace N
{
    public abstract class BaseClass { }
}
", MscorlibRefPortable);

            // create a normal assembly with a type derived from the portable abstract base
            solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @"
using N;
using Alias1 = N.BaseClass;

namespace M
{
    using Alias2 = Alias1;

    public class DerivedClass : Alias2 { }
}
", MscorlibRef, solution.Projects.Single(pid => pid.Name == "PortableProject").Id);

            // get symbols for types
            var portableCompilation = await solution.Projects.Single(p => p.Name == "PortableProject").GetCompilationAsync();
            var baseClassSymbol = portableCompilation.GetTypeByMetadataName("N.BaseClass");

            var normalCompilation = await solution.Projects.Single(p => p.Name == "NormalProject").GetCompilationAsync();
            var derivedClassSymbol = normalCompilation.GetTypeByMetadataName("M.DerivedClass");

            // verify that the symbols are different (due to retargeting)
            Assert.NotEqual(baseClassSymbol, derivedClassSymbol.BaseType);

            // verify that the dependent types of `N.BaseClass` correctly resolve to `M.DerivedCLass`
            var derivedFromBase = await DependentTypeFinder.FindImmediatelyDerivedClassesAsync(baseClassSymbol, solution, CancellationToken.None);
            var derivedDependentType = derivedFromBase.Single();
            Assert.Equal(derivedClassSymbol, derivedDependentType);
        }
コード例 #23
0
        public async Task TestHasSuccessfullyLoadedBeingFalse()
        {
            var workspace = new AdhocWorkspace();
            var document = GetDocumentFromIncompleteProject(workspace);

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

            // listen to events
            // check empty since this could be called to clear up existing diagnostics
            service.DiagnosticsUpdated += (s, a) => Assert.Empty(a.Diagnostics);

            // now call each analyze method. none of them should run.
            await analyzer.AnalyzeSyntaxAsync(document, InvocationReasons.Empty, CancellationToken.None).ConfigureAwait(false);
            await analyzer.AnalyzeDocumentAsync(document, bodyOpt: null, reasons: InvocationReasons.Empty, cancellationToken: CancellationToken.None).ConfigureAwait(false);
            await analyzer.AnalyzeProjectAsync(document.Project, semanticsChanged: true, reasons: InvocationReasons.Empty, cancellationToken: CancellationToken.None).ConfigureAwait(false);

            // wait for all events to raised
            await listener.CreateWaitTask().ConfigureAwait(false);
        }
コード例 #24
0
        protected void AssertFormat(
            string expected,
            string code,
            IEnumerable<TextSpan> spans,
            string language,
            bool debugMode = false,
            Dictionary<OptionKey, object> changedOptionSet = null,
            bool treeCompare = true,
            ParseOptions parseOptions = null)
        {
            using (var workspace = new AdhocWorkspace())
            {
                var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", language);
                if (parseOptions != null)
                {
                    project = project.WithParseOptions(parseOptions);
                }

                var document = project.AddDocument("Document", SourceText.From(code));

                var syntaxTree = document.GetSyntaxTreeAsync().Result;

                var options = workspace.Options;
                if (changedOptionSet != null)
                {
                    foreach (var entry in changedOptionSet)
                    {
                        options = options.WithChangedOption(entry.Key, entry.Value);
                    }
                }

                var root = syntaxTree.GetRoot();
                AssertFormat(workspace, expected, root, spans, options, document.GetTextAsync().Result);

                // format with node and transform
                AssertFormatWithTransformation(workspace, expected, root, spans, options, treeCompare, parseOptions);
            }
        }
コード例 #25
0
        private async Task<Solution> GetSolutionAsync(ISolutionChecksumService service, ChecksumScope snapshot)
        {
            var workspace = new AdhocWorkspace();

            var solutionInfo = await GetValueAsync<SolutionChecksumObjectInfo>(service, snapshot.SolutionChecksum.Info, WellKnownChecksumObjects.SolutionChecksumObjectInfo).ConfigureAwait(false);

            var projects = new List<ProjectInfo>();
            foreach (var projectSnapshot in snapshot.SolutionChecksum.Projects.ToProjectObjects(service))
            {
                var documents = new List<DocumentInfo>();
                foreach (var documentSnapshot in projectSnapshot.Documents.ToDocumentObjects(service))
                {
                    var documentInfo = await GetValueAsync<DocumentChecksumObjectInfo>(service, documentSnapshot.Info, WellKnownChecksumObjects.DocumentChecksumObjectInfo).ConfigureAwait(false);
                    var text = await GetValueAsync<SourceText>(service, documentSnapshot.Text, WellKnownChecksumObjects.SourceText).ConfigureAwait(false);

                    // TODO: do we need version?
                    documents.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create())),
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var p2p = new List<ProjectReference>();
                foreach (var checksum in projectSnapshot.ProjectReferences)
                {
                    var reference = await GetValueAsync<ProjectReference>(service, checksum, WellKnownChecksumObjects.ProjectReference).ConfigureAwait(false);
                    p2p.Add(reference);
                }
                var metadata = new List<MetadataReference>();
                foreach (var checksum in projectSnapshot.MetadataReferences)
                {
                    var reference = await GetValueAsync<MetadataReference>(service, checksum, WellKnownChecksumObjects.MetadataReference).ConfigureAwait(false);
                    metadata.Add(reference);
                }

                var analyzers = new List<AnalyzerReference>();
                foreach (var checksum in projectSnapshot.AnalyzerReferences)
                {
                    var reference = await GetValueAsync<AnalyzerReference>(service, checksum, WellKnownChecksumObjects.AnalyzerReference).ConfigureAwait(false);
                    analyzers.Add(reference);
                }

                var additionals = new List<DocumentInfo>();
                foreach (var documentSnapshot in projectSnapshot.AdditionalDocuments.ToDocumentObjects(service))
                {
                    var documentInfo = await GetValueAsync<DocumentChecksumObjectInfo>(service, documentSnapshot.Info, WellKnownChecksumObjects.DocumentChecksumObjectInfo).ConfigureAwait(false);
                    var text = await GetValueAsync<SourceText>(service, documentSnapshot.Text, WellKnownChecksumObjects.SourceText).ConfigureAwait(false);

                    // TODO: do we need version?
                    additionals.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create())),
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var projectInfo = await GetValueAsync<ProjectChecksumObjectInfo>(service, projectSnapshot.Info, WellKnownChecksumObjects.ProjectChecksumObjectInfo).ConfigureAwait(false);
                var compilationOptions = await GetValueAsync<CompilationOptions>(service, projectSnapshot.CompilationOptions, WellKnownChecksumObjects.CompilationOptions).ConfigureAwait(false);
                var parseOptions = await GetValueAsync<ParseOptions>(service, projectSnapshot.ParseOptions, WellKnownChecksumObjects.ParseOptions).ConfigureAwait(false);

                projects.Add(
                    ProjectInfo.Create(
                        projectInfo.Id, projectInfo.Version, projectInfo.Name, projectInfo.AssemblyName,
                        projectInfo.Language, projectInfo.FilePath, projectInfo.OutputFilePath,
                        compilationOptions, parseOptions,
                        documents, p2p, metadata, analyzers, additionals));
            }

            return workspace.AddSolution(SolutionInfo.Create(solutionInfo.Id, solutionInfo.Version, solutionInfo.FilePath, projects));
        }
コード例 #26
0
        public async Task VerifyRefactoringAsync(
            string source,
            string expected,
            TextSpan span,
            string[] additionalSources          = null,
            string equivalenceKey               = null,
            CodeVerificationOptions options     = null,
            CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            using (Workspace workspace = new AdhocWorkspace())
            {
                Project project = WorkspaceFactory.AddProject(workspace.CurrentSolution, options);

                Document document = WorkspaceFactory.AddDocument(project, source, additionalSources ?? Array.Empty <string>());

                SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                ImmutableArray <Diagnostic> compilerDiagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken);

                if (options == null)
                {
                    options = Options;
                }

                VerifyCompilerDiagnostics(compilerDiagnostics, options);
                CodeAction action = null;

                var context = new CodeRefactoringContext(
                    document,
                    span,
                    a =>
                {
                    if (equivalenceKey == null ||
                        string.Equals(a.EquivalenceKey, equivalenceKey, StringComparison.Ordinal))
                    {
                        if (action == null)
                        {
                            action = a;
                        }
                    }
                },
                    CancellationToken.None);

                await RefactoringProvider.ComputeRefactoringsAsync(context).ConfigureAwait(false);

                Assert.True(action != null, "No code refactoring has been registered.");

                document = await document.ApplyCodeActionAsync(action).ConfigureAwait(false);

                semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                ImmutableArray <Diagnostic> newCompilerDiagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken);

                VerifyCompilerDiagnostics(newCompilerDiagnostics, options);

                if (!options.AllowNewCompilerDiagnostics)
                {
                    VerifyNoNewCompilerDiagnostics(compilerDiagnostics, newCompilerDiagnostics, options);
                }

                string actual = await document.ToFullStringAsync(simplify : true, format : true, cancellationToken).ConfigureAwait(false);

                Assert.Equal(expected, actual);
            }
        }
コード例 #27
0
        public static async Task <List <CustomSuggestion> > GetCodeCompletion(SourceInfo sourceInfo)
        {
            var refs = CompileResources.PortableExecutableCompletionReferences;

            List <string> usings = new() { "System",
                                           "System.IO",
                                           "System.Collections.Generic",
                                           "System.Collections",
                                           "System.Console",
                                           "System.Diagnostics",
                                           "System.Dynamic",
                                           "System.Linq",
                                           "System.Linq.Expressions",
                                           "System.Net.Http",
                                           "System.Text",
                                           "System.Net",
                                           "System.Threading.Tasks",
                                           "System.Numerics" };
            var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && File.Exists(a.Location) && !a.FullName.Contains("JSInterop.WebAssembly")).ToList();

            var partTypes = MefHostServices.DefaultAssemblies.Concat(assemblies)
                            .Distinct()?
                            .SelectMany(x => x?.GetTypes())?
                            .ToArray();

            var compositionContext = new ContainerConfiguration()
                                     .WithParts(partTypes)
                                     .CreateContainer();
            var host = MefHostServices.Create(compositionContext);

            var workspace = new AdhocWorkspace(host);

            string scriptCode         = sourceInfo.SourceCode;
            var    _                  = typeof(Microsoft.CodeAnalysis.CSharp.Formatting.CSharpFormattingOptions);
            var    compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings);

            if (refs == null || refs.Count == 0)
            {
                return(null);
            }

            var scriptProjectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Script", "Script", LanguageNames.CSharp, isSubmission: true)
                                    .WithMetadataReferences(refs)
                                    .WithCompilationOptions(compilationOptions);

            var scriptProject      = workspace.AddProject(scriptProjectInfo);
            var scriptDocumentInfo = DocumentInfo.Create(
                DocumentId.CreateNewId(scriptProject.Id), "Script",
                sourceCodeKind: SourceCodeKind.Script,
                loader: TextLoader.From(TextAndVersion.Create(SourceText.From(scriptCode), VersionStamp.Create())));
            var scriptDocument = workspace.AddDocument(scriptDocumentInfo);

            // cursor position is at the end
            int position          = sourceInfo.LineNumberOffsetFromTemplate;
            var completionService = CompletionService.GetService(scriptDocument);
            var results           = await completionService.GetCompletionsAsync(scriptDocument, position);

            if (results == null && sourceInfo.LineNumberOffsetFromTemplate < sourceInfo.SourceCode.Length)
            {
                sourceInfo.LineNumberOffsetFromTemplate++;
                await GetCodeCompletion(sourceInfo);
            }

            if (sourceInfo.SourceCode[sourceInfo.LineNumberOffsetFromTemplate - 1].ToString() == "(")
            {
                sourceInfo.LineNumberOffsetFromTemplate--;
                results = completionService.GetCompletionsAsync(scriptDocument, sourceInfo.LineNumberOffsetFromTemplate).Result;
            }

            //Method parameters
            var overloads      = GetMethodOverloads(scriptCode, position);
            var suggestionList = new List <CustomSuggestion>();

            if (results != null)
            {
                try
                {
                    suggestionList.AddRange(results.Items.Select(completion => new CustomSuggestion()
                    {
                        Label         = completion.Properties.ContainsKey("SymbolName") ? completion.Properties["SymbolName"] : completion.DisplayText,
                        InsertText    = completion.Properties.ContainsKey("SymbolName") ? completion.Properties["SymbolName"] : completion.DisplayText,
                        Kind          = completion.Properties.ContainsKey("SymbolKind") ? completion.Properties["SymbolKind"] : "8",
                        Detail        = completion.Tags != null && completion.Tags.Length > 0 ? completion.Tags[0] : "None",
                        Documentation = completion.Tags != null && completion.Tags.Length > 1 ? completion.Tags[1] : "None"
                    }));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error from: \r\n{JsonConvert.SerializeObject(results)}\r\n{ex.Message}\r\n{ex.StackTrace}");
                    throw;
                }
            }

            if (overloads.Count == 0)
            {
                return(suggestionList);
            }
            suggestionList = new List <CustomSuggestion>();
            var builder = ImmutableArray.CreateBuilder <CompletionItem>();

            foreach ((string description, string documentation) in overloads)
            {
                suggestionList.Add(new CustomSuggestion()
                {
                    Label         = description.Split('(', ')')[1],
                    InsertText    = description.Split('(', ')')[1],
                    Kind          = "8",
                    Detail        = documentation,
                    Documentation = documentation
                });
            }
            return(suggestionList);
        }
コード例 #28
0
ファイル: ModelBuilder.cs プロジェクト: simonferquel/simcim
        private void BuildFactoryClass(Dictionary <string, CimTypeDeclaration> typeDeclMap)
        {
            var workspace = new AdhocWorkspace();
            var generator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp);
            var classDecl = generator.ClassDeclaration("InfrastructureObjectMapper",
                                                       accessibility: Accessibility.Public,
                                                       interfaceTypes: new SyntaxNode[] { SyntaxHelper.IInfrastructureObjectMapperType });
            var members = new List <SyntaxNode>();

            members.Add(SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName("string"), "CimNamespace").WithExpressionBody(
                            SyntaxFactory.ArrowExpressionClause(SyntaxFactory.ParseExpression($"\"{_options.CimNamespace}\"")))
                        .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                        .AddModifiers(SyntaxHelper.Public));

            members.Add(SyntaxFactory.MethodDeclaration(SyntaxHelper.IInfrastructureObjectType, "Create")
                        .AddModifiers(SyntaxHelper.Public)
                        .AddParameterListParameters(SyntaxFactory.Parameter(SyntaxFactory.Identifier("scope")).WithType(SyntaxHelper.IInfrastructureObjectScopeType))
                        .AddParameterListParameters(SyntaxFactory.Parameter(SyntaxFactory.Identifier("cimInstance")).WithType(SyntaxFactory.ParseTypeName("CimInstance")))
                        .AddBodyStatements(
                            SyntaxFactory.ParseStatement("if(cimInstance == null){ return null; }"),
                            SyntaxFactory.SwitchStatement(SyntaxFactory.ParseExpression("cimInstance.CimSystemProperties.ClassName"))
                            .AddSections(typeDeclMap.Where(kvp => !kvp.Value.IsAbstract && !kvp.Value.IsAssociation).Select(kvp => GenerateSwitchCase(kvp.Value)).ToArray())
                            .AddSections(SyntaxFactory.SwitchSection().AddLabels(SyntaxFactory.DefaultSwitchLabel()).AddStatements(SyntaxFactory.ParseStatement("throw new KeyNotFoundException();")))
                            )
                        );

            members.Add(
                SyntaxFactory.FieldDeclaration(
                    SyntaxFactory.VariableDeclaration(SyntaxFactory.ParseTypeName("Dictionary<Type, string>"))
                    .AddVariables(SyntaxFactory.VariableDeclarator("_typeMap").WithInitializer(
                                      SyntaxFactory.EqualsValueClause(
                                          SyntaxFactory.ObjectCreationExpression(SyntaxFactory.ParseTypeName("Dictionary<Type, string>"))
                                          .WithInitializer(
                                              SyntaxFactory.InitializerExpression(SyntaxKind.CollectionInitializerExpression)
                                              .AddExpressions(typeDeclMap.Where(kvp => !kvp.Value.IsAssociation).Select(kvp => GenerateTypeMapInitializerExpression(kvp.Value)).ToArray())
                                              )
                                          )
                                      )
                                  )
                    )
                .AddModifiers(SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxHelper.Static)

                );

            members.Add(
                SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("string"), "TryResolveType")
                .AddModifiers(SyntaxHelper.Public)
                .AddParameterListParameters(SyntaxFactory.Parameter(SyntaxFactory.Identifier("type")).WithType(SyntaxFactory.ParseTypeName("Type")))
                .AddBodyStatements(SyntaxFactory.ParseStatement(@"if(_typeMap.TryGetValue(type, out var result))
                    {
                        return result;
                    }"), SyntaxFactory.ParseStatement("return null;")
                                   )
                );

            classDecl = generator.AddMembers(classDecl, members);
            var namespaceDecl = generator.NamespaceDeclaration(_options.CSharpNamespace, classDecl);
            var finalDoc      = generator.CompilationUnit(
                generator.NamespaceImportDeclaration("Microsoft.Management.Infrastructure"),
                generator.NamespaceImportDeclaration("System"),
                generator.NamespaceImportDeclaration("System.Collections.Generic"),
                generator.NamespaceImportDeclaration("SimCim.Core"),
                namespaceDecl).NormalizeWhitespace();

            File.WriteAllText(Path.Join(_options.OutputDir, "InfrastructureObjectMapper.cs"), finalDoc.ToFullString(), Encoding.UTF8);
        }
コード例 #29
0
        private async Task <Solution> GetSolutionAsync(ISolutionSynchronizationService service, PinnedRemotableDataScope syncScope)
        {
            var workspace = new AdhocWorkspace();

            var solutionObject = await service.GetValueAsync <SolutionStateChecksums>(syncScope.SolutionChecksum);

            var solutionInfo = await service.GetValueAsync <SolutionInfo.SolutionAttributes>(solutionObject.Info).ConfigureAwait(false);

            var projects = new List <ProjectInfo>();

            foreach (var projectObject in solutionObject.Projects.ToProjectObjects(service))
            {
                var projectInfo = await service.GetValueAsync <ProjectInfo.ProjectAttributes>(projectObject.Info).ConfigureAwait(false);

                if (!workspace.Services.IsSupported(projectInfo.Language))
                {
                    continue;
                }

                var documents = new List <DocumentInfo>();
                foreach (var documentObject in projectObject.Documents.ToDocumentObjects(service))
                {
                    var documentInfo = await service.GetValueAsync <DocumentInfo.DocumentAttributes>(documentObject.Info).ConfigureAwait(false);

                    var text = await service.GetValueAsync <SourceText>(documentObject.Text).ConfigureAwait(false);

                    // TODO: do we need version?
                    documents.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create())),
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var p2p = new List <ProjectReference>();
                foreach (var checksum in projectObject.ProjectReferences)
                {
                    var reference = await service.GetValueAsync <ProjectReference>(checksum).ConfigureAwait(false);

                    p2p.Add(reference);
                }

                var metadata = new List <MetadataReference>();
                foreach (var checksum in projectObject.MetadataReferences)
                {
                    var reference = await service.GetValueAsync <MetadataReference>(checksum).ConfigureAwait(false);

                    metadata.Add(reference);
                }

                var analyzers = new List <AnalyzerReference>();
                foreach (var checksum in projectObject.AnalyzerReferences)
                {
                    var reference = await service.GetValueAsync <AnalyzerReference>(checksum).ConfigureAwait(false);

                    analyzers.Add(reference);
                }

                var additionals = new List <DocumentInfo>();
                foreach (var documentObject in projectObject.AdditionalDocuments.ToDocumentObjects(service))
                {
                    var documentInfo = await service.GetValueAsync <DocumentInfo.DocumentAttributes>(documentObject.Info).ConfigureAwait(false);

                    var text = await service.GetValueAsync <SourceText>(documentObject.Text).ConfigureAwait(false);

                    // TODO: do we need version?
                    additionals.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create())),
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var compilationOptions = await service.GetValueAsync <CompilationOptions>(projectObject.CompilationOptions).ConfigureAwait(false);

                var parseOptions = await service.GetValueAsync <ParseOptions>(projectObject.ParseOptions).ConfigureAwait(false);

                projects.Add(
                    ProjectInfo.Create(
                        projectInfo.Id, projectInfo.Version, projectInfo.Name, projectInfo.AssemblyName,
                        projectInfo.Language, projectInfo.FilePath, projectInfo.OutputFilePath,
                        compilationOptions, parseOptions,
                        documents, p2p, metadata, analyzers, additionals, projectInfo.IsSubmission));
            }

            return(workspace.AddSolution(SolutionInfo.Create(solutionInfo.Id, solutionInfo.Version, solutionInfo.FilePath, projects)));
        }
コード例 #30
0
        private static CompilationResult CompileInternal(string originalName, string cSharpSafeName, MemberDeclarationSyntax @class, IndexDefinition definition)
        {
            var name = cSharpSafeName + "." + Guid.NewGuid() + IndexExtension;

            var @namespace = RoslynHelper.CreateNamespace(IndexNamespace)
                             .WithMembers(SyntaxFactory.SingletonList(@class));

            var res = GetUsingDirectiveAndSyntaxTreesAndReferences(definition);

            var compilationUnit = SyntaxFactory.CompilationUnit()
                                  .WithUsings(RoslynHelper.CreateUsings(res.UsingDirectiveSyntaxes))
                                  .WithMembers(SyntaxFactory.SingletonList <MemberDeclarationSyntax>(@namespace))
                                  .NormalizeWhitespace();

            SyntaxNode formattedCompilationUnit;

            using (var workspace = new AdhocWorkspace())
            {
                formattedCompilationUnit = Formatter.Format(compilationUnit, workspace);
            }

            string sourceFile = null;

            if (EnableDebugging)
            {
                sourceFile = Path.Combine(Path.GetTempPath(), name + ".cs");
                File.WriteAllText(sourceFile, formattedCompilationUnit.ToFullString(), Encoding.UTF8);
            }

            var st = EnableDebugging
                ? SyntaxFactory.ParseSyntaxTree(File.ReadAllText(sourceFile), path: sourceFile, encoding: Encoding.UTF8)
                : SyntaxFactory.ParseSyntaxTree(formattedCompilationUnit.ToFullString());

            res.SyntaxTrees.Add(st);

            var compilation = CSharpCompilation.Create(
                assemblyName: name,
                syntaxTrees: res.SyntaxTrees,
                references: res.References,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                .WithOptimizationLevel(EnableDebugging ? OptimizationLevel.Debug : OptimizationLevel.Release)
                );

            var code = formattedCompilationUnit.SyntaxTree.ToString();

            var asm = new MemoryStream();
            var pdb = EnableDebugging ? new MemoryStream() : null;

            var result = compilation.Emit(asm, pdb, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb));

            if (result.Success == false)
            {
                IEnumerable <Diagnostic> failures = result.Diagnostics
                                                    .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);

                var sb = new StringBuilder();
                sb.AppendLine($"Failed to compile index {originalName}");
                sb.AppendLine();
                sb.AppendLine(code);
                sb.AppendLine();

                foreach (var diagnostic in failures)
                {
                    sb.AppendLine(diagnostic.ToString());
                }

                throw new IndexCompilationException(sb.ToString());
            }

            asm.Position = 0;

            Assembly assembly;

            if (EnableDebugging)
            {
                pdb.Position = 0;
                assembly     = AssemblyLoadContext.Default.LoadFromStream(asm, pdb);
            }
            else
            {
                assembly = AssemblyLoadContext.Default.LoadFromStream(asm);
            }

            return(new CompilationResult
            {
                Code = code,
                Type = assembly.GetType($"{IndexNamespace}.{cSharpSafeName}")
            });
        }
コード例 #31
0
        /// <summary>
        /// Creates a solution that will be used as parent for the sources that need to be checked.
        /// </summary>
        /// <param name="projectId">The project identifier to use.</param>
        /// <param name="language">The language for which the solution is being created.</param>
        /// <returns>The created solution.</returns>
        protected virtual Solution CreateSolution(ProjectId projectId, string language)
        {
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true);

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

            solution.Workspace.Options =
                solution.Workspace.Options
                .WithChangedOption(FormattingOptions.IndentationSize, language, this.IndentationSize)
                .WithChangedOption(FormattingOptions.TabSize, language, this.TabSize)
                .WithChangedOption(FormattingOptions.UseTabs, language, this.UseTabs);

            var settings = this.GetSettings();

            StyleCopSettings defaultSettings = new StyleCopSettings();

            if (this.IndentationSize != defaultSettings.Indentation.IndentationSize ||
                this.UseTabs != defaultSettings.Indentation.UseTabs ||
                this.TabSize != defaultSettings.Indentation.TabSize)
            {
                var indentationSettings = $@"
{{
  ""settings"": {{
    ""indentation"": {{
      ""indentationSize"": {this.IndentationSize},
      ""useTabs"": {this.UseTabs.ToString().ToLowerInvariant()},
      ""tabSize"": {this.TabSize}
    }}
  }}
}}
";

                if (string.IsNullOrEmpty(settings))
                {
                    settings = indentationSettings;
                }
                else
                {
                    JObject mergedSettings = JsonConvert.DeserializeObject <JObject>(settings);
                    mergedSettings.Merge(JsonConvert.DeserializeObject <JObject>(indentationSettings));
                    settings = JsonConvert.SerializeObject(mergedSettings);
                }
            }

            if (!string.IsNullOrEmpty(settings))
            {
                var documentId = DocumentId.CreateNewId(projectId);
                solution = solution.AddAdditionalDocument(documentId, SettingsHelper.SettingsFileName, settings);
            }

            ParseOptions parseOptions = solution.GetProject(projectId).ParseOptions;

            return(solution.WithProjectParseOptions(projectId, parseOptions.WithDocumentationMode(DocumentationMode.Diagnose)));
        }
コード例 #32
0
 private static Solution CreateSolution(AdhocWorkspace workspace)
 {
     return(workspace.CurrentSolution);
 }
コード例 #33
0
ファイル: SolutionSizeTests.cs プロジェクト: GloryChou/roslyn
        private static Solution CreateSolution(int solutionSize)
        {
            var info = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create());

            var workspace = new AdhocWorkspace();
            workspace.AddSolution(info);

            var solution = workspace.CurrentSolution;
            var project = solution.AddProject("proj1", "proj1", LanguageNames.CSharp);

            var current = 0;
            for (var i = 0; true; i++)
            {
                var size = current + 1234;
                if (current + size >= solutionSize)
                {
                    break;
                }

                project = project.AddDocument("doc" + i, new string('a', size)).Project;
                current += size;
            }

            var left = solutionSize - current;
            if (left > 0)
            {
                project = project.AddDocument("docLast", new string('a', left)).Project;
            }

            return project.Solution;
        }
コード例 #34
0
        public async Task Format()
        {
            using (ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext context))
            {
                var json = await context.ReadForMemoryAsync(RequestBodyStream(), "studio-tasks/format");

                if (json == null)
                {
                    throw new BadRequestException("No JSON was posted.");
                }

                if (json.TryGet(nameof(FormattedExpression.Expression), out string expressionAsString) == false)
                {
                    throw new BadRequestException("'Expression' property was not found.");
                }

                if (string.IsNullOrWhiteSpace(expressionAsString))
                {
                    NoContentStatus();
                    return;
                }

                var type = IndexDefinitionHelper.DetectStaticIndexType(expressionAsString, reduce: null);

                FormattedExpression formattedExpression;
                switch (type)
                {
                case IndexType.Map:
                case IndexType.MapReduce:
                    using (var workspace = new AdhocWorkspace())
                    {
                        var expression = SyntaxFactory
                                         .ParseExpression(expressionAsString)
                                         .NormalizeWhitespace();

                        var result = Formatter.Format(expression, workspace);

                        if (result.ToString().IndexOf("Could not format:", StringComparison.Ordinal) > -1)
                        {
                            throw new BadRequestException();
                        }

                        formattedExpression = new FormattedExpression
                        {
                            Expression = result.ToString()
                        };
                    }
                    break;

                case IndexType.JavaScriptMap:
                case IndexType.JavaScriptMapReduce:
                    formattedExpression = new FormattedExpression
                    {
                        Expression = JSBeautify.Apply(expressionAsString)
                    };
                    break;

                default:
                    throw new NotSupportedException($"Unknown index type '{type}'.");
                }

                await using (var writer = new AsyncBlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    context.Write(writer, formattedExpression.ToJson());
                }
            }
        }
コード例 #35
0
ファイル: Helpers.cs プロジェクト: kentcb/PCLMock
        public static async Task GenerateAndVerifyMocksUsingEmbeddedResources(
            Type fixtureType,
            string testName,
            Language language,
            IEnumerable <MetadataReference> metadataReferences = default,
            IPlugin[] plugins = default,
            // Should only be enabled temporarily to overwrite expected output with the actual output, making it easy to update
            // expected output files when code changes necessitate.
            bool overwriteExpectedOutput = false)
        {
            var resourceBaseName   = $"{fixtureType.FullName}Resources.";
            var inputResourceName  = $"{resourceBaseName}{testName}Input_{language}.txt";
            var outputResourceName = $"{resourceBaseName}{testName}Output_{language}.txt";
            var platformPath       = Path.GetDirectoryName(typeof(object).Assembly.Location);

            // Manually add some references that are always required.
            var supplementedMetadataReferences = (metadataReferences ?? Enumerable.Empty <MetadataReference>())
                                                 .Concat(
                new[]
            {
                MetadataReference.CreateFromFile(Path.Combine(platformPath, "System.Runtime.dll")),
                MetadataReference.CreateFromFile(typeof(System.Linq.Expressions.Expression).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(MockBase <>).Assembly.Location),
            });

            using (var inputStream = typeof(Helpers).Assembly.GetManifestResourceStream(inputResourceName))
            {
                var projectInfo = ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    "AdhocProject",
                    "AdhocProject",
                    language.ToSyntaxGeneratorLanguageName(),
                    compilationOptions: language == Language.CSharp
                        ? (CompilationOptions) new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                        : new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                    metadataReferences: supplementedMetadataReferences);

                // Create an adhoc workspace and project containing the input source.
                var workspace = new AdhocWorkspace();
                var project   = workspace
                                .AddProject(projectInfo)
                                .AddDocument("Source.cs", SourceText.From(inputStream))
                                .Project;
                var compilation = await project.GetCompilationAsync();

                var diagnostics = compilation.GetDiagnostics();

                // Ensure there are no issues with the input project, otherwise it might be confusing to understand issues with the generated mocks.
                Assert.Empty(diagnostics);

                var logSink = new StringLogSink()
                              .WithMinimumLevel(LogLevel.Warn);
                var generatedMocks = Generator.GenerateMocks(
                    logSink,
                    language,
                    ImmutableList.Create(compilation),
                    (plugins ?? Enumerable.Empty <IPlugin>()).ToImmutableList(),
                    x => true,
                    x => "The.Namespace",
                    x => $"{x.Name}Mock");

                var log = logSink.ToString();
                // There shouldn't be any errors or warnings in the log or something has gone wrong generating mocks.
                Assert.Equal("", log);

                var generatedMocksAggregated = generatedMocks
                                               .Aggregate(
                    new StringBuilder(),
                    (acc, next) =>
                {
                    if (next != null)
                    {
                        acc.AppendLine(next.ToFullString());
                    }

                    return(acc);
                },
                    acc => acc.ToString())
                                               .NormalizeLineEndings();

                using (var outputStream = typeof(Helpers).Assembly.GetManifestResourceStream(outputResourceName))
                    using (var outputStreamReader = new StreamReader(outputStream))
                    {
                        var expectedCode = outputStreamReader.ReadToEnd();

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

                        // useful when converting generated code to something that can be pasted into an expectation file
                        var sanitisedResult = generatedMocksAggregated.Replace(typeof(MockBase <>).Assembly.GetName().Version.ToString(), "$VERSION$");

                        if (overwriteExpectedOutput)
                        {
                            var currentDirectory = Path.GetDirectoryName(typeof(Helpers).Assembly.Location);
                            var outputDirectory  = Path.Combine(currentDirectory, @"..\..\..\", "CodeGeneration", "Plugins", $"{fixtureType.Name}Resources");
                            var outputFileName   = Path.Combine(outputDirectory, $"{testName}Output_{language}.txt");

                            if (!File.Exists(outputFileName))
                            {
                                throw new InvalidOperationException(@"Asked to overwrite output, but cannot determine output path.");
                            }

                            File.WriteAllText(outputFileName, sanitisedResult);

                            Assert.True(false, "Output successfully overwritten - now disable the overwriteExpectedOutput flag.");
                        }

                        Assert.Equal(expectedCode, generatedMocksAggregated);
                    }

                // Now combine the original code with the generated code and make sure there are no problems.
                var workspaceWithGeneratedCode = new AdhocWorkspace();
                var projectWithGeneratedCode   = workspaceWithGeneratedCode
                                                 .AddProject(projectInfo)
                                                 .AddDocument("Source.cs", SourceText.From(inputStream))
                                                 .Project
                                                 .AddDocument("GeneratedSource.cs", SourceText.From(generatedMocksAggregated))
                                                 .Project;
                var compilationWithGeneratedCode = await projectWithGeneratedCode.GetCompilationAsync();

                var diagnosticsToIgnore = new HashSet <string>(
                    new []
                {
                    // Don't require assembly identities to match exactly because PCLMock is built against netstandard whereas we're running
                    // tests against a specific platform. This means, e.g. System.Linq.Expressions won't be the exact same assembly.
                    "CS1701",
                });
                var diagnosticsWithGeneratedCode = compilationWithGeneratedCode
                                                   .GetDiagnostics()
                                                   .Where(diagnostic => !diagnosticsToIgnore.Contains(diagnostic.Id))
                                                   .ToImmutableArray();

                // Ensure there are no issues with the input project, otherwise it might be confusing to understand issues with the generated mocks.
                Assert.Empty(diagnostics);
            }
        }
コード例 #36
0
        internal static async Task <Regex> SourceGenRegexAsync(
            string pattern, RegexOptions?options = null, TimeSpan?matchTimeout = null, CancellationToken cancellationToken = default)
        {
            Assert.True(options is not null || matchTimeout is null);
            string attr = $"[RegexGenerator({SymbolDisplay.FormatLiteral(pattern, quote: true)}";

            if (options is not null)
            {
                attr += $", {string.Join(" | ", options.ToString().Split(',').Select(o => $"RegexOptions.{o.Trim()}"))}";
                if (matchTimeout is not null)
                {
                    attr += string.Create(CultureInfo.InvariantCulture, $", {(int)matchTimeout.Value.TotalMilliseconds}");
                }
            }
            attr += ")]";

            // Create the source boilerplate for the pattern
            string code = $@"
                using System.Text.RegularExpressions;
                public partial class C
                {{
                    {attr}
                    public static partial Regex Get();
                }}";


            // Use a cached compilation to save a little time.  Rather than creating an entirely new workspace
            // for each test, just create a single compilation, cache it, and then replace its syntax tree
            // on each test.
            if (s_compilation is not Compilation comp)
            {
                // Create the project containing the source.
                var proj = new AdhocWorkspace()
                           .AddSolution(SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create()))
                           .AddProject("Test", "test.dll", "C#")
                           .WithMetadataReferences(s_refs)
                           .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                                                   .WithNullableContextOptions(NullableContextOptions.Enable))
                           .WithParseOptions(new CSharpParseOptions(LanguageVersion.Preview))
                           .AddDocument("RegexGenerator.g.cs", SourceText.From("// Empty", Encoding.UTF8)).Project;
                Assert.True(proj.Solution.Workspace.TryApplyChanges(proj.Solution));

                s_compilation = comp = await proj !.GetCompilationAsync(CancellationToken.None).ConfigureAwait(false);
                Debug.Assert(comp is not null);
            }

            comp = comp.ReplaceSyntaxTree(comp.SyntaxTrees.First(), CSharpSyntaxTree.ParseText(SourceText.From(code, Encoding.UTF8), s_previewParseOptions));

            // Run the generator
            GeneratorDriverRunResult generatorResults = s_generatorDriver.RunGenerators(comp !, cancellationToken).GetRunResult();

            if (generatorResults.Diagnostics.Length != 0)
            {
                throw new ArgumentException(
                          string.Join(Environment.NewLine, generatorResults.Diagnostics) + Environment.NewLine +
                          string.Join(Environment.NewLine, generatorResults.GeneratedTrees.Select(t => NumberLines(t.ToString()))));
            }

            // Compile the assembly to a stream
            var dll = new MemoryStream();

            comp = comp.AddSyntaxTrees(generatorResults.GeneratedTrees.ToArray());
            EmitResult results = comp.Emit(dll, options: s_emitOptions, cancellationToken: cancellationToken);

            if (!results.Success || results.Diagnostics.Length != 0)
            {
                throw new ArgumentException(
                          string.Join(Environment.NewLine, results.Diagnostics.Concat(generatorResults.Diagnostics)) + Environment.NewLine +
                          string.Join(Environment.NewLine, generatorResults.GeneratedTrees.Select(t => NumberLines(t.ToString()))));
            }
            dll.Position = 0;

            // Load the assembly into its own AssemblyLoadContext.
            var      alc = new RegexLoadContext(Environment.CurrentDirectory);
            Assembly a   = alc.LoadFromStream(dll);

            // Instantiate a regex using the newly created static Get method that was source generated.
            Regex r = (Regex)a.GetType("C") !.GetMethod("Get") !.Invoke(null, null) !;

            // Issue an unload on the ALC, so it'll be collected once the Regex instance is collected
            alc.Unload();

            return(r);
        }
コード例 #37
0
        public async Task <bool> Execute(CancellationToken cancellationToken)
        {
            try
            {
                var projectName = Path.GetFileNameWithoutExtension(ProjectPath);
                var projectId   = !string.IsNullOrEmpty(ProjectGuid) && Guid.TryParse(ProjectGuid, out var projectIdGuid)
                    ? ProjectId.CreateFromSerialized(projectIdGuid)
                    : ProjectId.CreateNewId();


                this.Log.LogDebug($"ProjectGuid: {ProjectGuid}");
                this.Log.LogDebug($"ProjectID: {projectId}");

                var languageName       = GetLanguageName(ProjectPath);
                var documents          = GetDocuments(Compile, projectId).ToList();
                var metadataReferences = GetMetadataReferences(Reference).ToList();

                foreach (var doc in documents)
                {
                    this.Log.LogDebug($"Document: {doc.FilePath}");
                }
                foreach (var reference in metadataReferences)
                {
                    this.Log.LogDebug($"Reference: {reference.Display}");
                }

                var projectInfo = ProjectInfo.Create(
                    projectId,
                    VersionStamp.Create(),
                    projectName,
                    projectName,
                    languageName,
                    ProjectPath,
                    TargetPath,
                    CreateCompilationOptions(OutputType, languageName),
                    documents: documents,
                    metadataReferences: metadataReferences
                    );
                this.Log.LogDebug($"Project: {projectInfo}");

                var workspace = new AdhocWorkspace();
                workspace.AddProject(projectInfo);

                var project = workspace.CurrentSolution.Projects.Single();

                var stopwatch   = Stopwatch.StartNew();
                var compilation = await project.GetCompilationAsync(cancellationToken);

                this.Log.LogInformation($"GetCompilation completed in {stopwatch.ElapsedMilliseconds}ms.");

                if (compilation.ReferencedAssemblyNames.All(name => name.Name != HagarAssemblyShortName))
                {
                    return(false);
                }

                var generator = new CodeGenerator(compilation);
                stopwatch.Restart();
                var syntax = await generator.GenerateCode(cancellationToken);

                this.Log.LogInformation($"GenerateCode completed in {stopwatch.ElapsedMilliseconds}ms.");
                stopwatch.Restart();

                var normalized = syntax.NormalizeWhitespace();
                this.Log.LogInformation($"NormalizeWhitespace completed in {stopwatch.ElapsedMilliseconds}ms.");
                stopwatch.Restart();

                var source = normalized.ToFullString();
                this.Log.LogInformation($"Generate source from syntax completed in {stopwatch.ElapsedMilliseconds}ms.");
                stopwatch.Restart();
                using (var sourceWriter = new StreamWriter(this.CodeGenOutputFile))
                {
                    sourceWriter.WriteLine("#if !EXCLUDE_GENERATED_CODE");
                    foreach (var warningNum in SuppressCompilerWarnings)
                    {
                        await sourceWriter.WriteLineAsync($"#pragma warning disable {warningNum}");
                    }
                    if (!string.IsNullOrWhiteSpace(source))
                    {
                        await sourceWriter.WriteLineAsync(source);
                    }
                    foreach (var warningNum in SuppressCompilerWarnings)
                    {
                        await sourceWriter.WriteLineAsync($"#pragma warning restore {warningNum}");
                    }
                    sourceWriter.WriteLine("#endif");
                }
                this.Log.LogInformation($"Write source to disk completed in {stopwatch.ElapsedMilliseconds}ms.");

                return(true);
            }
            catch (ReflectionTypeLoadException rtle)
            {
                foreach (var ex in rtle.LoaderExceptions)
                {
                    this.Log.LogDebug($"Exception: {ex}");
                }
                throw;
            }
        }
コード例 #38
0
        static void Main(string[] args)
        {
            // Get a workspace
            var workspace = new AdhocWorkspace();

            // Get the SyntaxGenerator for the specified language
            var generator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp);


            // Create using/Imports directives
            var usingDirectives = generator.NamespaceImportDeclaration("System");

            // Generate two private fields
            var lastNameField = generator.FieldDeclaration("_lastName",
                                                           generator.TypeExpression(SpecialType.System_String),
                                                           Accessibility.Private);
            var firstNameField = generator.FieldDeclaration("_firstName",
                                                            generator.TypeExpression(SpecialType.System_String),
                                                            Accessibility.Private);

            // Generate two properties with explicit get/set
            var lastNameProperty = generator.PropertyDeclaration("LastName",
                                                                 generator.TypeExpression(SpecialType.System_String), Accessibility.Public,
                                                                 getAccessorStatements: new SyntaxNode[]
                                                                 { generator.ReturnStatement(generator.IdentifierName("_lastName")) },
                                                                 setAccessorStatements: new SyntaxNode[]
                                                                 { generator.AssignmentStatement(generator.IdentifierName("_lastName"),
                                                                                                 generator.IdentifierName("value")) });
            var firstNameProperty = generator.PropertyDeclaration("FirstName",
                                                                  generator.TypeExpression(SpecialType.System_String),
                                                                  Accessibility.Public,
                                                                  getAccessorStatements: new SyntaxNode[]
                                                                  { generator.ReturnStatement(generator.IdentifierName("_firstName")) },
                                                                  setAccessorStatements: new SyntaxNode[]
                                                                  { generator.AssignmentStatement(generator.IdentifierName("_firstName"),
                                                                                                  generator.IdentifierName("value")) });

            // Generate the method body for the Clone method
            var cloneMethodBody = generator.ReturnStatement(generator.
                                                            InvocationExpression(generator.IdentifierName("MemberwiseClone")));

            // Generate the Clone method declaration
            var cloneMethoDeclaration = generator.MethodDeclaration("Clone", null,
                                                                    null, null,
                                                                    Accessibility.Public,
                                                                    DeclarationModifiers.Virtual,
                                                                    new SyntaxNode[] { cloneMethodBody });

            // Generate a SyntaxNode for the interface's name you want to implement
            var ICloneableInterfaceType = generator.IdentifierName("ICloneable");

            // Explicit ICloneable.Clone implemenation
            var cloneMethodWithInterfaceType = generator.
                                               AsPublicInterfaceImplementation(cloneMethoDeclaration,
                                                                               ICloneableInterfaceType);

            // Generate parameters for the class' constructor
            var constructorParameters = new SyntaxNode[] {
                generator.ParameterDeclaration("LastName",
                                               generator.TypeExpression(SpecialType.System_String)),
                generator.ParameterDeclaration("FirstName",
                                               generator.TypeExpression(SpecialType.System_String))
            };

            // Generate the class' constructor
            var constructor = generator.ConstructorDeclaration("Person",
                                                               constructorParameters, Accessibility.Public);

            // An array of SyntaxNode as the class members
            var members = new SyntaxNode[] { lastNameField,
                                             firstNameField, lastNameProperty, firstNameProperty,
                                             cloneMethodWithInterfaceType, constructor };

            // Generate the class
            var classDefinition = generator.ClassDeclaration(
                "Person", typeParameters: null,
                accessibility: Accessibility.Public,
                modifiers: DeclarationModifiers.Abstract,
                baseType: null,
                interfaceTypes: new SyntaxNode[] { ICloneableInterfaceType },
                members: members);


            //
            // Declare a namespace
            var namespaceDeclaration = generator.NamespaceDeclaration("MyTypes", classDefinition);


            /************************************************************
             * Application class code
             *************************************************************/
            List <SyntaxNode> usingDirectivesList = new List <SyntaxNode>();

            usingDirectivesList.Add(generator.NamespaceImportDeclaration("P.Runtime"));
            usingDirectivesList.Add(generator.NamespaceImportDeclaration("System.Collections.Generic"));

            // Generate a SyntaxNode for the interface's name for StateImpl
            var StateImplInterface = generator.IdentifierName("StateImpl");


            var applicationClass = generator.ClassDeclaration(
                "Application",
                accessibility: Accessibility.Public,
                interfaceTypes: new SyntaxNode[] { StateImplInterface }
                );

            //
            // Declare a namespace
            var programNameSpaceDeclaration = generator.NamespaceDeclaration("SimpleMachine", applicationClass);

            // Get a CompilationUnit (code file) for the generated code
            var newNode = generator.CompilationUnit(usingDirectivesList[0], usingDirectivesList[1], namespaceDeclaration, programNameSpaceDeclaration).
                          NormalizeWhitespace();
            StringBuilder sb = new StringBuilder();

            using (StringWriter writer = new StringWriter(sb))
            {
                newNode.WriteTo(writer);
                Console.WriteLine(writer);
            }
        }
コード例 #39
0
        public async Task ImmediatelyDerivedInterfaces_CrossLanguage()
        {
            var solution = new AdhocWorkspace().CurrentSolution;

            // create portable assembly with an interface
            solution = AddProjectWithMetadataReferences(solution, "PortableProject", LanguageNames.VisualBasic, @"
Namespace N
    Public Interface IBaseInterface
    End Interface
End Namespace
", MscorlibRefPortable);

            // create a normal assembly with a type implementing that interface
            solution = AddProjectWithMetadataReferences(solution, "NormalProject", LanguageNames.CSharp, @"
using N;
namespace M
{
    public class ImplementingClass : IBaseInterface { }
}
", MscorlibRef, solution.Projects.Single(pid => pid.Name == "PortableProject").Id);

            // get symbols for types
            var portableCompilation = await solution.Projects.Single(p => p.Name == "PortableProject").GetCompilationAsync();
            var baseInterfaceSymbol = portableCompilation.GetTypeByMetadataName("N.IBaseInterface");

            var normalCompilation = await solution.Projects.Single(p => p.Name == "NormalProject").GetCompilationAsync();
            var implementingClassSymbol = normalCompilation.GetTypeByMetadataName("M.ImplementingClass");

            // verify that the symbols are different (due to retargeting)
            Assert.NotEqual(baseInterfaceSymbol, implementingClassSymbol.Interfaces.Single());

            // verify that the implementing types of `N.IBaseInterface` correctly resolve to `M.ImplementingClass`
            var typesThatImplementInterface = await DependentTypeFinder.FindImmediatelyDerivedAndImplementingTypesAsync(
                baseInterfaceSymbol, solution, CancellationToken.None);
            Assert.Equal(implementingClassSymbol, typesThatImplementInterface.Single());
        }
コード例 #40
0
        public async Task TestUpdatedDocumentHasTextVersionAsync()
        {
            var pid      = ProjectId.CreateNewId();
            var text     = SourceText.From("public class C { }");
            var version  = VersionStamp.Create();
            var docInfo  = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
            var projInfo = ProjectInfo.Create(
                pid,
                version: VersionStamp.Default,
                name: "TestProject",
                assemblyName: "TestProject.dll",
                language: LanguageNames.CSharp,
                documents: new[] { docInfo });

            using var ws = new AdhocWorkspace();
            ws.AddProject(projInfo);
            var doc = ws.CurrentSolution.GetDocument(docInfo.Id);

            Assert.False(doc.TryGetText(out var currentText));
            Assert.False(doc.TryGetTextVersion(out var currentVersion));

            // cause text to load and show that TryGet now works for text and version
            currentText = await doc.GetTextAsync();

            Assert.True(doc.TryGetText(out currentText));
            Assert.True(doc.TryGetTextVersion(out currentVersion));
            Assert.Equal(version, currentVersion);

            // change document
            var root = await doc.GetSyntaxRootAsync();

            var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation());

            Assert.NotSame(root, newRoot);
            var newDoc = doc.WithSyntaxRoot(newRoot);

            Assert.NotSame(doc, newDoc);

            // text is now unavailable since it must be constructed from tree
            Assert.False(newDoc.TryGetText(out currentText));

            // version is available because it is cached
            Assert.True(newDoc.TryGetTextVersion(out currentVersion));

            // access it the hard way
            var actualVersion = await newDoc.GetTextVersionAsync();

            // version is the same
            Assert.Equal(currentVersion, actualVersion);

            // accessing text version did not cause text to be constructed.
            Assert.False(newDoc.TryGetText(out currentText));

            // now access text directly (force it to be constructed)
            var actualText = await newDoc.GetTextAsync();

            actualVersion = await newDoc.GetTextVersionAsync();

            // prove constructing text did not introduce a new version
            Assert.Equal(currentVersion, actualVersion);
        }
コード例 #41
0
ファイル: FindReferencesTests.cs プロジェクト: zhxjdwh/roslyn
        public async Task PinvokeMethodReferences_CS()
        {
            var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(
                @"

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
static class Module1
{
	[DllImport(""kernel32"", EntryPoint = ""CreateDirectoryA"", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    public static extern int CreateDirectory(string lpPathName);

        private static int prop;
        public static int Prop1
        {
            get { return prop; }
            set
            {
                CreateDirectory(""T"");
                // Method Call 1
                prop = value;
                prop = null;
            }
        }

        public static void Main()
        {
            CreateDirectory(""T""); // Method Call 2            
            NormalMethod(); // Method Call 1
            NormalMethod(); // Method Call 2
        }

        public static void NormalMethod()
        {
        }
    }
                ");

            ProjectId  prj1Id = ProjectId.CreateNewId();
            DocumentId docId  = DocumentId.CreateNewId(prj1Id);

            var sln = new AdhocWorkspace().CurrentSolution
                      .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.CSharp)
                      .AddMetadataReference(prj1Id, MscorlibRef)
                      .AddDocument(docId, "testFile", tree.GetText());

            Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication));

            tree = await prj.GetDocument(docId).GetSyntaxTreeAsync();

            Compilation comp = await prj.GetCompilationAsync();

            SemanticModel semanticModel = comp.GetSemanticModel(tree);

            List <Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax> methodlist = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax>().ToList();
            SyntaxNode declareMethod = methodlist.ElementAt(0);
            SyntaxNode normalMethod  = methodlist.ElementAt(2);

            // pinvoke method calls
            var symbol     = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(2, references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol     = semanticModel.GetDeclaredSymbol(normalMethod);
            references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(2, references.ElementAt(0).Locations.Count());
        }
コード例 #42
0
ファイル: FindReferencesTests.cs プロジェクト: zhxjdwh/roslyn
        public async Task PinvokeMethodReferences_VB()
        {
            var tree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(
                @"
Module Module1
        Declare Function CreateDirectory Lib ""kernel32"" Alias ""CreateDirectoryA"" (ByVal lpPathName As String) As Integer
 
        Private prop As Integer
        Property Prop1 As Integer
            Get
                Return prop
            End Get
            Set(value As Integer)
                CreateDirectory(""T"")  ' Method Call 1
                prop = value
                prop = Nothing
            End Set
        End Property

        Sub Main()
          CreateDirectory(""T"") 'Method Call 2            
          NormalMethod() ' Method Call 1
          NormalMethod() ' Method Call 2
       End Sub

       Sub NormalMethod()
       End Sub
 End Module
            ");

            ProjectId  prj1Id = ProjectId.CreateNewId();
            DocumentId docId  = DocumentId.CreateNewId(prj1Id);

            Solution sln = new AdhocWorkspace().CurrentSolution
                           .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.VisualBasic)
                           .AddMetadataReference(prj1Id, MscorlibRef)
                           .AddDocument(docId, "testFile", tree.GetText());

            Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new VisualBasic.VisualBasicCompilationOptions(OutputKind.ConsoleApplication, embedVbCoreRuntime: true));

            tree = await prj.GetDocument(docId).GetSyntaxTreeAsync();

            Compilation comp = await prj.GetCompilationAsync();

            SemanticModel semanticModel = comp.GetSemanticModel(tree);

            SyntaxNode declareMethod = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.VisualBasic.Syntax.DeclareStatementSyntax>().FirstOrDefault();
            SyntaxNode normalMethod  = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.VisualBasic.Syntax.MethodStatementSyntax>().ToList()[1];

            // declared method calls
            var symbol     = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol     = semanticModel.GetDeclaredSymbol(normalMethod);
            references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());
        }
コード例 #43
0
        public void Build()
        {
            var workspace = new AdhocWorkspace();
            var generator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp);

            var classDecl = generator.StructDeclaration(_declaration.CSharpName + "Association",
                                                        accessibility: Accessibility.Public);
            var members = new List <SyntaxNode>();

            members.Add(SyntaxFactory.FieldDeclaration(SyntaxFactory.VariableDeclaration(SyntaxHelper.AssociationResolverType))
                        .AddDeclarationVariables(SyntaxFactory.VariableDeclarator("_resolver").WithInitializer(
                                                     SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression(
                                                                                         $"new AssociationResolver(\"{_declaration.Name}\", \"{_sourceProperty.ReferenceClassName}\", \"{_targetProperty.ReferenceClassName}\", \"{_sourceProperty.Name}\", \"{_targetProperty.Name}\")"))
                                                     ))
                        .AddModifiers(SyntaxHelper.Private, SyntaxHelper.Static));

            members.Add(SyntaxFactory.FieldDeclaration(SyntaxFactory.VariableDeclaration(SyntaxHelper.IInfrastructureObjectScopeType))
                        .AddDeclarationVariables(SyntaxFactory.VariableDeclarator("_scope"))
                        .AddModifiers(SyntaxHelper.Private));

            members.Add(SyntaxFactory.ConstructorDeclaration(_declaration.CSharpName + "Association")
                        .AddModifiers(SyntaxHelper.Public)
                        .AddParameterListParameters(
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("scope")).WithType(SyntaxHelper.IInfrastructureObjectScopeType)
                            )
                        .WithBody(SyntaxHelper.ParseBlock("_scope = scope;"))
                        );

            var targetReturnType = _targetProperty.ResolveType(_typeRepository, out var targetIsCimObject);
            var sourceReturnType = _sourceProperty.ResolveType(_typeRepository, out var sourceIsCimObject);

            members.Add(SyntaxFactory.MethodDeclaration(SyntaxHelper.EnumerableOf(targetReturnType), _targetProperty.Name)
                        .AddModifiers(SyntaxHelper.Public)
                        .AddParameterListParameters(
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("in" + _sourceProperty.Name)).WithType(sourceReturnType),
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("options")).WithType(SyntaxHelper.CimOperationOptionsType)
                            .WithDefault(
                                SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("null"))
                                )
                            )
                        .WithBody(SyntaxHelper.ParseBlock(
                                      "var scope = _scope;",
                                      $"var instances = _resolver.ResolveTarget(scope, in{_sourceProperty.Name}{(sourceIsCimObject ? ".AsCimInstance()" : string.Empty)}, options);",
                                      targetIsCimObject ? $"return instances.Select(i => ({targetReturnType})scope.Mapper.Create(scope, i));" : "return instances;"
                                      )
                                  ));

            members.Add(SyntaxFactory.MethodDeclaration(SyntaxHelper.EnumerableOf(sourceReturnType), _sourceProperty.Name)
                        .AddModifiers(SyntaxHelper.Public)
                        .AddParameterListParameters(
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("in" + _targetProperty.Name)).WithType(targetReturnType),
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("options")).WithType(SyntaxHelper.CimOperationOptionsType)
                            .WithDefault(
                                SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("null"))
                                )
                            )
                        .WithBody(SyntaxHelper.ParseBlock(
                                      "var scope = _scope;",
                                      $"var instances = _resolver.ResolveSource(scope, in{_targetProperty.Name}{(targetIsCimObject ? ".AsCimInstance()" : string.Empty)}, options);",
                                      sourceIsCimObject ? $"return instances.Select(i => ({sourceReturnType})scope.Mapper.Create(scope, i));" : "return instances;"
                                      )
                                  ));


            members.Add(SyntaxFactory.MethodDeclaration(SyntaxHelper.ObservableOf(targetReturnType), _targetProperty.Name + "Async")
                        .AddModifiers(SyntaxHelper.Public)
                        .AddParameterListParameters(
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("in" + _sourceProperty.Name)).WithType(sourceReturnType),
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("options")).WithType(SyntaxHelper.CimOperationOptionsType)
                            .WithDefault(
                                SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("null"))
                                )
                            )
                        .WithBody(SyntaxHelper.ParseBlock(
                                      "var scope = _scope;",
                                      $"var instances = _resolver.ResolveTargetAsync(scope, in{_sourceProperty.Name}{(sourceIsCimObject ? ".AsCimInstance()" : string.Empty)}, options);",
                                      targetIsCimObject ? $"return instances.Select(i => ({targetReturnType})scope.Mapper.Create(scope, i));" : "return instances;"
                                      )
                                  ));

            members.Add(SyntaxFactory.MethodDeclaration(SyntaxHelper.ObservableOf(sourceReturnType), _sourceProperty.Name + "Async")
                        .AddModifiers(SyntaxHelper.Public)
                        .AddParameterListParameters(
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("in" + _targetProperty.Name)).WithType(targetReturnType),
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("options")).WithType(SyntaxHelper.CimOperationOptionsType)
                            .WithDefault(
                                SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("null"))
                                )
                            )
                        .WithBody(SyntaxHelper.ParseBlock(
                                      "var scope = _scope;",
                                      $"var instances = _resolver.ResolveSourceAsync(scope, in{_targetProperty.Name}{(targetIsCimObject ? ".AsCimInstance()" : string.Empty)}, options);",
                                      sourceIsCimObject ? $"return instances.Select(i => ({sourceReturnType})scope.Mapper.Create(scope, i));" : "return instances;"
                                      )
                                  ));


            classDecl = generator.AddMembers(classDecl, members);

            var namespaceDecl = generator.NamespaceDeclaration(_options.CSharpNamespace, classDecl);


            var finalDoc = generator.CompilationUnit(
                generator.NamespaceImportDeclaration("Microsoft.Management.Infrastructure"),
                generator.NamespaceImportDeclaration("Microsoft.Management.Infrastructure.Options"),
                generator.NamespaceImportDeclaration("SimCim.Core"),
                generator.NamespaceImportDeclaration("System"),
                generator.NamespaceImportDeclaration("System.Collections.Generic"),
                generator.NamespaceImportDeclaration("System.Linq"),
                generator.NamespaceImportDeclaration("System.Reactive.Linq"),
                namespaceDecl).NormalizeWhitespace();

            File.WriteAllText(Path.Join(_options.OutputDir, "Association" + _declaration.CSharpName + ".cs"), finalDoc.ToFullString(), Encoding.UTF8);
        }
コード例 #44
0
 private static async Task TestAnalyzerAsync(
     AdhocWorkspace workspace,
     Document document,
     DiagnosticAnalyzer diagnosticAnalyzer,
     Func <bool, bool, ImmutableArray <DiagnosticData>, (bool, bool)> resultSetter,
コード例 #45
0
ファイル: ModelBuilder.cs プロジェクト: simonferquel/simcim
        private void BuildSimCimScopeExtensions(Dictionary <string, CimTypeDeclaration> typeDeclMap)
        {
            var workspace = new AdhocWorkspace();
            var generator = SyntaxGenerator.GetGenerator(workspace, LanguageNames.CSharp);
            var classDecl = generator.ClassDeclaration("SimCimScopeExtensions",
                                                       accessibility: Accessibility.Public,
                                                       modifiers: DeclarationModifiers.Static);

            var members = new List <SyntaxNode>();

            members.Add(SyntaxFactory.StructDeclaration("AllAssociations")
                        .AddModifiers(SyntaxHelper.Public)
                        .AddMembers(
                            SyntaxFactory.FieldDeclaration(SyntaxFactory.VariableDeclaration(SyntaxHelper.IInfrastructureObjectScopeType))
                            .AddDeclarationVariables(SyntaxFactory.VariableDeclarator("_scope"))
                            .AddModifiers(SyntaxHelper.Private),
                            SyntaxFactory.ConstructorDeclaration("AllAssociations")
                            .AddModifiers(SyntaxHelper.Public)
                            .AddParameterListParameters(
                                SyntaxFactory.Parameter(SyntaxFactory.Identifier("scope")).WithType(SyntaxHelper.IInfrastructureObjectScopeType)
                                )
                            .WithBody(SyntaxHelper.ParseBlock("_scope = scope;")
                                      )
                            )
                        .AddMembers(
                            typeDeclMap.Values.Where(v => v.IsAssociation && !v.IsAbstract)
                            .Select(a => SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(a.CSharpName + "Association"), a.CSharpName)
                                    .AddModifiers(SyntaxHelper.Public)
                                    .WithExpressionBody(SyntaxFactory.ArrowExpressionClause(SyntaxFactory.ParseExpression($"new {a.CSharpName}Association(_scope)")))
                                    .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)))
                            .Cast <MemberDeclarationSyntax>().ToArray()
                            )
                        );

            members.Add(
                SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName("AllAssociations"), "Associations")
                .AddModifiers(SyntaxHelper.Public, SyntaxHelper.Static)
                .AddParameterListParameters(
                    SyntaxFactory.Parameter(SyntaxFactory.Identifier("scope")).WithType(SyntaxHelper.IInfrastructureObjectScopeType).AddModifiers(SyntaxHelper.This)
                    )
                .AddBodyStatements(
                    SyntaxFactory.ParseStatement($"return new AllAssociations(scope);")
                    )
                );

            foreach (var type in typeDeclMap.Values)
            {
                if (type.IsSingleton)
                {
                    members.Add(
                        SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName(type.CSharpName), "Get" + type.CSharpName)
                        .AddModifiers(SyntaxHelper.Public, SyntaxHelper.Static)
                        .AddParameterListParameters(
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("scope")).WithType(SyntaxHelper.IInfrastructureObjectScopeType).AddModifiers(SyntaxHelper.This)
                            )
                        .AddBodyStatements(
                            SyntaxFactory.ParseStatement($"return scope.EnumerateInstances<{type.CSharpName}>().Single();")
                            )
                        );
                    members.Add(
                        SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName($"Task<{type.CSharpName}>"), "Get" + type.CSharpName + "Async")
                        .AddModifiers(SyntaxHelper.Public, SyntaxHelper.Static)
                        .AddParameterListParameters(
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("scope")).WithType(SyntaxHelper.IInfrastructureObjectScopeType).AddModifiers(SyntaxHelper.This),
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("options"))
                            .WithType(SyntaxHelper.CimOperationOptionsType)
                            .WithDefault(SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("null")))
                            )
                        .AddBodyStatements(
                            SyntaxFactory.ParseStatement($"return scope.EnumerateInstancesAsync<{type.CSharpName}>(options).ToTask();")
                            )
                        );
                }
                else if (type.IsEvent(typeDeclMap))
                {
                    members.Add(
                        SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName($"IObservable<BookmarkedEvent<{type.CSharpName}>>"), $"SubscribeTo{type.CSharpName}")
                        .AddModifiers(SyntaxHelper.Public, SyntaxHelper.Static)
                        .AddParameterListParameters(
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("scope")).WithType(SyntaxHelper.IInfrastructureObjectScopeType).AddModifiers(SyntaxHelper.This),
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("pollingIntervalSeconds"))
                            .WithType(SyntaxFactory.ParseTypeName("double?"))
                            .WithDefault(SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("null"))),
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("wqlFilter"))
                            .WithType(SyntaxFactory.ParseTypeName("string"))
                            .WithDefault(SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("null"))),
                            SyntaxFactory.Parameter(SyntaxFactory.Identifier("options"))
                            .WithType(SyntaxHelper.CimOperationOptionsType)
                            .WithDefault(SyntaxFactory.EqualsValueClause(SyntaxFactory.ParseExpression("null")))
                            )
                        .AddBodyStatements(
                            SyntaxFactory.ParseStatement($"return scope.SubscribeToEvents<{type.CSharpName}>(pollingIntervalSeconds, wqlFilter, options);")
                            )
                        );
                }
            }

            classDecl = generator.AddMembers(classDecl, members);
            var namespaceDecl = generator.NamespaceDeclaration(_options.CSharpNamespace, classDecl);
            var finalDoc      = generator.CompilationUnit(
                generator.NamespaceImportDeclaration("Microsoft.Management.Infrastructure"),
                generator.NamespaceImportDeclaration("Microsoft.Management.Infrastructure.Options"),
                generator.NamespaceImportDeclaration("SimCim.Core"),
                generator.NamespaceImportDeclaration("System"),
                generator.NamespaceImportDeclaration("System.Collections.Generic"),
                generator.NamespaceImportDeclaration("System.Linq"),
                generator.NamespaceImportDeclaration("System.Reactive.Threading.Tasks"),
                generator.NamespaceImportDeclaration("System.Threading.Tasks"),
                namespaceDecl).NormalizeWhitespace();

            File.WriteAllText(Path.Join(_options.OutputDir, "InfrastructureObjectScopeExtensions.cs"), finalDoc.ToFullString(), Encoding.UTF8);
        }
コード例 #46
0
 protected abstract Task Refactor(AdhocWorkspace workspace, Document document, SyntaxNode root);
コード例 #47
0
 static IComplierExtension()
 {
     _workSpace = new AdhocWorkspace();
     _workSpace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId("formatter"), VersionStamp.Default));
     _options = new CSharpParseOptions(LanguageVersion.Latest);
 }
コード例 #48
0
 static CSharpSyntaxBase()
 {
     _workSpace = new AdhocWorkspace();
     _workSpace.AddSolution(SolutionInfo.Create(SolutionId.CreateNewId("formatter"), VersionStamp.Default));
     _options = new CSharpParseOptions(LanguageVersion.Latest, preprocessorSymbols: new[] { "RELEASE" });
 }
コード例 #49
0
        /// <nodoc />
        private static SyntaxNode CreateSourceFile(ResourceData data, string namespaceName, string className, bool isPublic, string languageName)
        {
            var workspace = new AdhocWorkspace();
            var generator = SyntaxGenerator.GetGenerator(workspace, languageName);

            var accessibility       = isPublic ? Accessibility.Public : Accessibility.Internal;
            var resourceManagerType = generator.IdentifierName("global::System.Resources.ResourceManager");
            var cultureInfoType     = generator.IdentifierName("global::System.Globalization.CultureInfo");

            var stringClassMember = new List <SyntaxNode>()
            {
                generator.FieldDeclaration(
                    name: "resourceMan",
                    type: resourceManagerType,
                    accessibility: Accessibility.Private,
                    modifiers: DeclarationModifiers.Static
                    ),

                generator.FieldDeclaration(
                    name: "resourceCulture",
                    type: cultureInfoType,
                    accessibility: Accessibility.Private,
                    modifiers: DeclarationModifiers.Static
                    ),

                generator.AddAttributes(
                    generator.PropertyDeclaration(
                        name: "ResourceManager",
                        type: resourceManagerType,
                        accessibility: accessibility,
                        modifiers: DeclarationModifiers.ReadOnly | DeclarationModifiers.Static,
                        getAccessorStatements: new SyntaxNode[]
                {
                    generator.IfStatement(
                        condition: generator.InvocationExpression(
                            generator.MemberAccessExpression(
                                generator.IdentifierName("global::System.Object"),
                                generator.IdentifierName("ReferenceEquals")),
                            generator.IdentifierName("resourceMan"),
                            generator.NullLiteralExpression()
                            ),
                        trueStatements: new SyntaxNode[]
                    {
                        generator.LocalDeclarationStatement(
                            resourceManagerType,
                            "temp",
                            generator.ObjectCreationExpression(
                                resourceManagerType,
                                generator.LiteralExpression(string.IsNullOrEmpty(namespaceName) ? className : $"{namespaceName}.{className}"),
                                generator.MemberAccessExpression(
                                    generator.TypeOfExpression(generator.IdentifierName(className)),
                                    "Assembly"
                                    )
                                )
                            ),
                        generator.AssignmentStatement(
                            generator.IdentifierName("resourceMan"),
                            generator.IdentifierName("temp")
                            )
                    }
                        ),
                    generator.ReturnStatement(generator.IdentifierName("resourceMan")),
                }
                        ),
                    GetEditorBrowsableAttribute(generator)
                    ).WithLeadingTrivia(
                    GetDocComment("Returns the cached ResourceManager instance used by this class.")),

                generator.AddAttributes(
                    generator.PropertyDeclaration(
                        name: "Culture",
                        type: cultureInfoType,
                        accessibility: accessibility,
                        modifiers: DeclarationModifiers.Static,
                        getAccessorStatements: new SyntaxNode[]
                {
                    generator.ReturnStatement(generator.IdentifierName("resourceCulture")),
                },
                        setAccessorStatements: new SyntaxNode[]
                {
                    generator.AssignmentStatement(
                        generator.IdentifierName("resourceCulture"),
                        generator.IdentifierName("value")
                        )
                }
                        ),
                    GetEditorBrowsableAttribute(generator)
                    ).WithLeadingTrivia(
                    GetDocComment("Overrides the current thread's CurrentUICulture property for all resource lookups using this strongly typed resource class.")),
            };

            foreach (var stringValue in data.StringValues)
            {
                var stringProperty = generator.PropertyDeclaration(
                    name: stringValue.Name,
                    type: generator.TypeExpression(SpecialType.System_String),
                    accessibility: accessibility,
                    modifiers: DeclarationModifiers.ReadOnly | DeclarationModifiers.Static,
                    getAccessorStatements: new SyntaxNode[]
                {
                    generator.ReturnStatement(
                        generator.InvocationExpression(
                            generator.MemberAccessExpression(
                                generator.IdentifierName("ResourceManager"),
                                "GetString"
                                ),
                            generator.LiteralExpression(stringValue.Name),
                            generator.IdentifierName("resourceCulture")
                            )
                        )
                }
                    ).WithLeadingTrivia(GetDocComment(stringValue.Comment ?? stringValue.Value));

                stringClassMember.Add(stringProperty);
            }

            var generatedClass = generator.AddAttributes(
                generator.ClassDeclaration(
                    className,
                    accessibility: accessibility,
                    modifiers: DeclarationModifiers.ReadOnly | DeclarationModifiers.Static,
                    members: stringClassMember
                    ).WithLeadingTrivia(GetDocComment("A strongly-typed resource class, for looking up localized strings, etc.")),
                generator.Attribute("global::System.CodeDom.Compiler.GeneratedCodeAttribute",
                                    generator.LiteralExpression(s_toolAssemblyName.Name),
                                    generator.LiteralExpression(s_toolAssemblyName.Version.ToString())
                                    ),
                generator.Attribute("global::System.Diagnostics.DebuggerNonUserCodeAttribute()"),
                generator.Attribute("global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()")
                );

            var compilationUnit = string.IsNullOrEmpty(namespaceName)
                ? generator.CompilationUnit(
                generator.NamespaceImportDeclaration("System"),
                generatedClass
                )
                : generator.CompilationUnit(
                generator.NamespaceDeclaration(namespaceName,
                                               generator.NamespaceImportDeclaration("System"),
                                               generatedClass)
                );

            return(compilationUnit.WithLeadingTrivia(SyntaxFactory.ParseLeadingTrivia($@"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by: {s_toolAssemblyName.Name} version: {s_toolAssemblyName.Version}
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
")
                                                     ));
        }
コード例 #50
0
 public void TestPreviewCreationWithSolution()
 {
     using var custom           = new AdhocWorkspace();
     using var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution);
     Assert.NotNull(previewWorkspace.CurrentSolution);
 }
コード例 #51
0
        public async Task OptionSet_Serialization_CustomValue()
        {
            var workspace = new AdhocWorkspace();

            workspace.Options = workspace.Options.WithChangedOption(CodeStyleOptions.QualifyFieldAccess, LanguageNames.CSharp, new CodeStyleOption<bool>(false, NotificationOption.Error))
                                                 .WithChangedOption(CodeStyleOptions.QualifyMethodAccess, LanguageNames.VisualBasic, new CodeStyleOption<bool>(true, NotificationOption.Warning))
                                                 .WithChangedOption(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, new CodeStyleOption<bool>(false, NotificationOption.Suggestion))
                                                 .WithChangedOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic, new CodeStyleOption<bool>(true, NotificationOption.None));

            await VerifyOptionSetsAsync(workspace, LanguageNames.CSharp).ConfigureAwait(false);
            await VerifyOptionSetsAsync(workspace, LanguageNames.VisualBasic).ConfigureAwait(false);
        }
コード例 #52
0
        public static Diagnostic[] RunPurityAnalyzer(string content, Maybe <string> secondFileContent, bool secondFileIsInDifferentProject, params MetadataReference[] additionalReferences)
        {
            var workspace = new AdhocWorkspace();

            var solution = workspace.CurrentSolution;

            var projectId = ProjectId.CreateNewId();

            solution = AddNewProjectToWorkspace(solution, "NewProject", projectId, additionalReferences);

            var documentId = DocumentId.CreateNewId(projectId);

            solution = AddNewSourceFile(solution, content, "NewFile.cs", documentId);

            if (secondFileContent.HasValue)
            {
                DocumentId secondDocumentId;

                if (secondFileIsInDifferentProject)
                {
                    var secondProjectId = ProjectId.CreateNewId();

                    solution = AddNewProjectToWorkspace(solution, "NewProject2", secondProjectId, additionalReferences);

                    secondDocumentId = DocumentId.CreateNewId(secondProjectId);

                    solution = solution.AddProjectReference(projectId, new ProjectReference(secondProjectId));
                }
                else
                {
                    secondDocumentId = DocumentId.CreateNewId(projectId);
                }


                solution = AddNewSourceFile(solution, secondFileContent.GetValue(), "NewFile2.cs", secondDocumentId);
            }

            PurityAnalyzerAnalyzer.GetSemanticModelForSyntaxTreeAsync = async tree =>
            {
                var document = solution.GetDocument(tree);

                return(await document.GetSemanticModelAsync());
            };

            var result = solution.GetProject(projectId).GetCompilationAsync().Result
                         .WithAnalyzers(ImmutableArray.Create <DiagnosticAnalyzer>(new PurityAnalyzerAnalyzer()));

            var results = result.GetAllDiagnosticsAsync().Result;

            var compilationErrors = results.Where(x => !IsFromPurityAnalyzer(x))
                                    .Where(x => x.Severity == DiagnosticSeverity.Error).ToList();

            if (compilationErrors.Any())
            {
                throw new Exception("Error in compilation" + Environment.NewLine + String.Join(Environment.NewLine, compilationErrors.Select(x => x.GetMessage())));
            }

            var ad0001Results = results.Where(x => x.Descriptor.Id == "AD0001").ToArray();

            if (ad0001Results.Any())
            {
                throw new Exception(ad0001Results.First().GetMessage());
            }

            bool IsFromPurityAnalyzer(Diagnostic x)
            {
                return(x.Descriptor.Id == PurityAnalyzerAnalyzer.PurityDiagnosticId || x.Descriptor.Id == PurityAnalyzerAnalyzer.ReturnsNewObjectDiagnosticId || x.Descriptor.Id == PurityAnalyzerAnalyzer.GenericParameterNotUsedAsObjectDiagnosticId);
            }

            var diagnostics = results.Where(IsFromPurityAnalyzer).ToArray();

            if (diagnostics.Any())
            {
                foreach (var diag in diagnostics)
                {
                    Console.WriteLine(diag);
                }
            }

            return(diagnostics);
        }
コード例 #53
0
ファイル: Verifier.cs プロジェクト: wachulski/sonar-csharp
        private static void VerifyAnalyzer(IEnumerable <DocumentInfo> documents, string fileExtension, SonarDiagnosticAnalyzer diagnosticAnalyzer, ParseOptions options = null,
                                           params MetadataReference[] additionalReferences)
        {
            HookSuppression();

            var parseOptions = GetParseOptionsAlternatives(options, fileExtension);

            using (var workspace = new AdhocWorkspace())
            {
                var project = CreateProject(fileExtension, GeneratedAssemblyName, workspace, additionalReferences);
                documents.ToList().ForEach(document => project = project.AddDocument(document.Name, document.Content).Project); // side effect on purpose (project is immutable)

                var issueLocationCollector = new IssueLocationCollector();

                foreach (var parseOption in parseOptions)
                {
                    if (parseOption != null)
                    {
                        project = project.WithParseOptions(parseOption);
                    }

                    var compilation = project.GetCompilationAsync().Result;

                    var diagnostics = GetDiagnostics(compilation, diagnosticAnalyzer);

                    var expectedIssues = issueLocationCollector
                                         .GetExpectedIssueLocations(compilation.SyntaxTrees.Skip(1).First().GetText().Lines)
                                         .ToList();

                    foreach (var diagnostic in diagnostics)
                    {
                        string issueId;
                        VerifyIssue(expectedIssues, issue => issue.IsPrimary, diagnostic.Location, diagnostic.GetMessage(), out issueId);

                        diagnostic.AdditionalLocations
                        .Select((location, i) => diagnostic.GetSecondaryLocation(i))
                        .OrderBy(x => x.Location.GetLineNumberToReport())
                        .ThenBy(x => x.Location.GetLineSpan().StartLinePosition.Character)
                        .ToList()
                        .ForEach(secondaryLocation =>
                        {
                            VerifyIssue(expectedIssues, issue => issue.IssueId == issueId && !issue.IsPrimary,
                                        secondaryLocation.Location, secondaryLocation.Message, out issueId);
                        });
                    }

                    if (expectedIssues.Count != 0)
                    {
                        Execute.Assertion.FailWith($"Issue expected but not raised on line(s) {string.Join(",", expectedIssues.Select(i => i.LineNumber))}.");
                    }

                    // When there are no diagnostics reported from the test (for example the FileLines analyzer
                    // does not report in each call to Verifier.VerifyAnalyzer) we skip the check for the extension
                    // method.
                    if (diagnostics.Any())
                    {
                        ExtensionMethodsCalledForAllDiagnostics(diagnosticAnalyzer).Should().BeTrue("The ReportDiagnosticWhenActive should be used instead of ReportDiagnostic");
                    }
                }
            }
        }
コード例 #54
0
        public async Task Run()
        {
            var op     = new AzureAsyncOperation();
            var restOp = new RestException();

            var files = Settings.Instance.FileSystem.GetFiles(Settings.Instance.OutputDirectory, "*.cs",
                                                              SearchOption.AllDirectories).
                        ToDictionary(each => each, each => Settings.Instance.FileSystem.ReadFileAsText(each));

            var projectId = ProjectId.CreateNewId();
            var solution  = new AdhocWorkspace().CurrentSolution
                            .AddProject(projectId, "MyProject", "MyProject", LanguageNames.CSharp)
                            .AddMetadataReference(projectId, Mscorlib)
                            .AddMetadataReference(projectId, AppDomain.CurrentDomain.GetAssemblies()
                                                  .Where(
                                                      a =>
                                                      string.Compare(a.GetName().Name, "Microsoft.Rest.ClientRuntime.Azure",
                                                                     StringComparison.OrdinalIgnoreCase) == 0)
                                                  .Select(a => MetadataReference.CreateFromFile(a.Location)).Single())
                            .AddMetadataReference(projectId, AppDomain.CurrentDomain.GetAssemblies()
                                                  .Where(
                                                      a =>
                                                      string.Compare(a.GetName().Name, "Microsoft.Rest.ClientRuntime",
                                                                     StringComparison.OrdinalIgnoreCase) == 0)
                                                  .Select(a => MetadataReference.CreateFromFile(a.Location)).Single())
                            .AddMetadataReference(projectId, AppDomain.CurrentDomain.GetAssemblies()
                                                  .Where(a => string.Compare(a.GetName().Name, "System", StringComparison.OrdinalIgnoreCase) == 0)
                                                  .Select(a => MetadataReference.CreateFromFile(a.Location)).Single());

            // Add existing files
            foreach (var file in files.Keys)
            {
                var documentId = DocumentId.CreateNewId(projectId);
                solution = solution.AddDocument(documentId, file, SourceText.From(files[file]));
            }

            // Simplify docs and add to
            foreach (var proj in solution.Projects)
            {
                foreach (var document in proj.Documents)
                {
                    var newRoot = await document.GetSyntaxRootAsync();

                    // get the namespaces used in the file
                    var names = new GetQualifiedNames().GetNames(newRoot);

                    // add the usings that we found
                    newRoot = new AddUsingsRewriter(names).Visit(newRoot);

                    // tell roslyn to simplify where it can
                    newRoot = new SimplifyNamesRewriter().Visit(newRoot);
                    var doc = document.WithSyntaxRoot(newRoot);

                    // reduce the code
                    var text = Simplifier.ReduceAsync(doc)
                               .Result.GetTextAsync()
                               .Result.ToString()
                               // get rid of any BOMs
                               .Trim('\x00EF', '\x00BB', '\x00BF', '\uFEFF', '\u200B');


                    // special cases the simplifier can't handle.
                    text = text.
                           Replace("[Newtonsoft.Json.JsonConverter(", "[JsonConverter(").
                           Replace("[System.Runtime.Serialization.EnumMember(", "[EnumMember(").
                           Replace("[Newtonsoft.Json.JsonProperty(", "[JsonProperty(").
                           Replace("[Newtonsoft.Json.JsonProperty]", "[JsonProperty]").
                           Replace("[Newtonsoft.Json.JsonObject]", "[JsonObject]").
                           Replace("[Microsoft.Rest.Serialization.JsonTransformation]", "[JsonTransformation]").
                           Replace("[Newtonsoft.Json.JsonExtensionData]", "[JsonExtensionData]");

                    // Write out the files back to their original location
                    var output = Path.Combine(Settings.Instance.FileSystem.CurrentDirectory, document.Name);
                    Settings.Instance.FileSystem.WriteFile(output, text);
                }
            }
        }
コード例 #55
0
        public async Task EmptySpan()
        {
            using (var workspace = new AdhocWorkspace())
            {
                var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
                var document = project.AddDocument("Document", SourceText.From(""));

                var syntaxTree = await document.GetSyntaxTreeAsync();
                var result = await Formatter.FormatAsync(syntaxTree.GetRoot(CancellationToken.None), TextSpan.FromBounds(0, 0), workspace, cancellationToken: CancellationToken.None);
            }
        }
コード例 #56
0
        private static Workspace GetWorkspaceFromBuild(this StLogger.Build build, params string[] preprocessorSymbols)
        {
            StLogger.Project csproj = build.Children.OfType <StLogger.Project>().FirstOrDefault();
            if (csproj == null)
            {
                throw new InvalidOperationException("cannot find cs project build");
            }

            StLogger.Item[] compileItems = Array.Empty <StLogger.Item>();
            var             properties   = new Dictionary <string, StLogger.Property>();

            foreach (StLogger.Folder folder in csproj.Children.OfType <StLogger.Folder>())
            {
                if (folder.Name == "Items")
                {
                    StLogger.Folder compileFolder = folder.Children.OfType <StLogger.Folder>().FirstOrDefault(x => x.Name == "Compile");
                    if (compileFolder == null)
                    {
                        throw new InvalidOperationException("failed to get compililation documents");
                    }

                    compileItems = compileFolder.Children.OfType <StLogger.Item>().ToArray();
                }
                else if (folder.Name == "Properties")
                {
                    properties = folder.Children.OfType <StLogger.Property>().ToDictionary(x => x.Name);
                }
            }

            StLogger.Item[] assemblies = Array.Empty <StLogger.Item>();
            foreach (StLogger.Target target in csproj.Children.OfType <StLogger.Target>())
            {
                if (target.Name == "ResolveReferences")
                {
                    StLogger.Folder folder = target.Children.OfType <StLogger.Folder>().Where(x => x.Name == "TargetOutputs").FirstOrDefault();
                    if (folder == null)
                    {
                        throw new InvalidOperationException("cannot find result of resolving assembly");
                    }

                    assemblies = folder.Children.OfType <StLogger.Item>().ToArray();
                }
            }

            var     ws            = new AdhocWorkspace();
            Project roslynProject = ws.AddProject(Path.GetFileNameWithoutExtension(csproj.ProjectFile), Microsoft.CodeAnalysis.LanguageNames.CSharp);
            var     projectDir    = properties["ProjectDir"].Value;
            Guid    pguid         = properties.ContainsKey("ProjectGuid") ? Guid.Parse(properties["ProjectGuid"].Value) : Guid.NewGuid();
            var     projectGuid   = ProjectId.CreateFromSerialized(pguid);

            foreach (StLogger.Item compile in compileItems)
            {
                var filePath    = compile.Text;
                var absFilePath = Path.Combine(projectDir, filePath);
                roslynProject = roslynProject.AddDocument(filePath, File.ReadAllText(absFilePath)).Project;
            }

            foreach (StLogger.Item asm in assemblies)
            {
                roslynProject = roslynProject.AddMetadataReference(MetadataReference.CreateFromFile(asm.Text));
            }

            var compopt = roslynProject.CompilationOptions as CSharpCompilationOptions;

            compopt = roslynProject.CompilationOptions as CSharpCompilationOptions;
            compopt = compopt ?? new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            OutputKind kind;

            switch (properties["OutputType"].Value)
            {
            case "Exe":
                kind = OutputKind.ConsoleApplication;
                break;

            case "Library":
                kind = OutputKind.DynamicallyLinkedLibrary;
                break;

            default:
                kind = OutputKind.DynamicallyLinkedLibrary;
                break;
            }

            roslynProject = roslynProject.WithCompilationOptions(compopt.WithOutputKind(kind).WithAllowUnsafe(true));
            var parseopt = roslynProject.ParseOptions as CSharpParseOptions;

            roslynProject = roslynProject.WithParseOptions(parseopt.WithPreprocessorSymbols(preprocessorSymbols));
            if (!ws.TryApplyChanges(roslynProject.Solution))
            {
                throw new InvalidOperationException("failed to apply solution changes to workspace");
            }

            return(ws);
        }
コード例 #57
0
        internal async Task <(Compilation compilation, List <MetadataReference> metadata)> CreateCompilationAsync(IEnumerable <string> paths, IEnumerable <string> assemblies, IEnumerable <string> preprocessors = null, Regex[] filters = null)
        {
            Console.WriteLine("Creating workspace...");

            var ws           = new AdhocWorkspace();
            var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default);

            ws.AddSolution(solutionInfo);
            var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "CSharpExample", "CSharpExample", "C#");

            ws.AddProject(projectInfo);
            if (paths != null)
            {
                foreach (var path in paths)
                {
                    if (path.StartsWith("http://") || path.StartsWith("https://"))
                    {
                        await DownloadDocumentsAsync(path, ws, projectInfo.Id, filters).ConfigureAwait(false);
                    }
                    else if (path.EndsWith(".zip"))
                    {
                        LoadCompressedDocuments(path, ws, projectInfo.Id, filters);
                    }
                    else
                    {
                        LoadFolderDocuments(path, ws, projectInfo.Id, filters);
                    }
                }
            }
            Console.WriteLine("Compiling...");
            var project = ws.CurrentSolution.Projects.Single();
            List <MetadataReference> metadata = new List <MetadataReference>();

            if (assemblies != null)
            {
                foreach (var assm in assemblies)
                {
                    IEnumerable <FileInfo> files = Enumerable.Empty <FileInfo>();
                    if (File.Exists(assm))
                    {
                        files = new FileInfo[] { new FileInfo(assm) };
                    }
                    else
                    {
                        string recursive   = Path.DirectorySeparatorChar + "**" + Path.DirectorySeparatorChar;
                        bool   isRecursive = false;
                        var    d           = assm;
                        var    fn          = Path.GetFileName(assm);
                        if (d.Contains(recursive))
                        {
                            d           = d.Substring(0, d.IndexOf(recursive));
                            isRecursive = true;
                        }
                        else if (Directory.Exists(d))
                        {
                            fn = null;
                        }
                        else
                        {
                            d = Path.GetDirectoryName(d);
                        }
                        var dir = new DirectoryInfo(d);
                        if (!dir.Exists)
                        {
                            throw new DirectoryNotFoundException(d);
                        }
                        if (string.IsNullOrEmpty(fn))
                        {
                            files = dir.GetFiles("*.dll", isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                        }
                        else
                        {
                            var di = new DirectoryInfo(d);
                            files = dir.GetFiles(fn, isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                        }
                    }
                    foreach (var item in files)
                    {
                        var metaref = MetadataReference.CreateFromFile(item.FullName);
                        project = project.AddMetadataReference(metaref);
                        metadata.Add(metaref);
                    }
                }
            }

            //Ensure mscorlib is referenced
            string mscorlib = typeof(System.Enum).Assembly.Location;

            if (File.Exists(mscorlib))
            {
                project = project.WithParseOptions(new Microsoft.CodeAnalysis.CSharp.CSharpParseOptions(Microsoft.CodeAnalysis.CSharp.LanguageVersion.Latest, DocumentationMode.Parse, SourceCodeKind.Regular, preprocessors));
                var metaref = MetadataReference.CreateFromFile(mscorlib);
                project = project.AddMetadataReference(metaref);
            }

            var comp = await project.GetCompilationAsync().ConfigureAwait(false);

            return(comp, metadata);
        }
コード例 #58
0
 protected virtual void ConfigureWorkspace(AdhocWorkspace workspace)
 {
 }
コード例 #59
0
        public void TestLoadTextSync()
        {
            var files = GetAnalyzerReferenceSolutionFiles();

            CreateFiles(files);

            using (var ws = new AdhocWorkspace(DesktopMefHostServices.DefaultServices))
            {
                var projectFullPath = Path.Combine(this.SolutionDirectory.Path, @"AnalyzerSolution\CSharpProject_AnalyzerReference.csproj");

                var loader = new MSBuildProjectLoader(ws);
                var infos = loader.LoadProjectInfoAsync(projectFullPath).Result;

                var doc = infos[0].Documents[0];
                var tav = doc.TextLoader.LoadTextAndVersionSynchronously(ws, doc.Id, CancellationToken.None);

                var adoc = infos[0].AdditionalDocuments.First(a => a.Name == "XamlFile.xaml");
                var atav = adoc.TextLoader.LoadTextAndVersionSynchronously(ws, adoc.Id, CancellationToken.None);
                Assert.Contains("Window", atav.Text.ToString(), StringComparison.Ordinal);
            }
        }
コード例 #60
0
        private async Task DownloadDocumentsAsync(string uri, AdhocWorkspace ws, ProjectId projectId, Regex[] filters)
        {
            var handler = new HttpClientHandler()
            {
                AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
            };
            var client             = new HttpClient(handler);
            HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get, uri);

            msg.Headers.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("DotNetOMDGenerator", "1.0"));
            Console.WriteLine("Downloading " + uri + "...");
            using (var result = await client.SendAsync(msg, HttpCompletionOption.ResponseHeadersRead))
            {
                var content = result.EnsureSuccessStatusCode().Content;
                using (var s = await content.ReadAsStreamAsync())
                {
                    var headers  = result.Headers.ToArray();
                    var filename = Path.GetTempFileName();
                    var name     = content.Headers.ContentDisposition?.FileName;
                    if (content.Headers.ContentType?.MediaType == "application/zip")
                    {
                        var length = content.Headers.ContentLength;
                        using (var f = System.IO.File.OpenWrite(filename))
                        {
                            var  buffer = new byte[65536];
                            long read   = 0;
                            int  count  = -1;
                            while (count != 0)
                            {
                                count = await s.ReadAsync(buffer, 0, buffer.Length);

                                if (count > 0)
                                {
                                    await f.WriteAsync(buffer, 0, count);
                                }
                                read += count;
                                if (length.HasValue)
                                {
                                    Console.Write($"         \r{(read * 100.0 / length.Value).ToString("0.0")}%  ({(length.Value / 1024d / 1024d).ToString("0.0")}mb)");
                                }
                                else
                                {
                                    Console.Write($"         \r{read} bytes...");
                                }
                            }
                            Console.WriteLine();
                        }
                        LoadCompressedDocuments(filename, ws, projectId, filters);
                        File.Delete(filename);
                    }
                    else if (content.Headers.ContentType?.MediaType == "text/plain")
                    {
                        var sourceText = SourceText.From(s);
                        ws.AddDocument(projectId, name ?? "Unknown.cs", sourceText);
                    }
                    else
                    {
                        throw new Exception("Invalid or missing content type: " + content.Headers.ContentType?.MediaType);
                    }
                }
            }
        }