Ejemplo n.º 1
0
 public static (SyntaxTree, SemanticModel) Compile(string classDeclaration, bool isCSharp = true,
                                                   params AssemblyReference[] references)
 {
     using (var workspace = new AdhocWorkspace())
     {
         var document = workspace.CurrentSolution.AddProject("project", "project.dll", isCSharp ? LanguageNames.CSharp : LanguageNames.VisualBasic)
                        .AddMetadataReference(AssemblyReferenceService.GetMetadataReference(AssemblyReference.FromFramework("mscorlib.dll")))
                        .AddMetadataReference(AssemblyReferenceService.GetMetadataReference(AssemblyReference.FromFramework("System.dll")))
                        .AddMetadataReference(AssemblyReferenceService.GetMetadataReference(AssemblyReference.FromFramework("System.Core.dll")))
                        .AddMetadataReferences(references.Select(AssemblyReferenceService.GetMetadataReference))
                        .AddDocument("Class1", classDeclaration);
         var compilation = document.Project.GetCompilationAsync().Result;
         var tree        = compilation.SyntaxTrees.First();
         return(tree, compilation.GetSemanticModel(tree));
     }
 }
Ejemplo n.º 2
0
        private static Project CreateProject(string fileExtension, string assemblyName, AdhocWorkspace workspace,
                                             params AssemblyReference[] additionalReferences)
        {
            var language = fileExtension == CSharpFileExtension
                ? LanguageNames.CSharp
                : LanguageNames.VisualBasic;

            var project = workspace.CurrentSolution.AddProject(assemblyName, $"{assemblyName}.dll", language)
                          .AddMetadataReference(AssemblyReferenceService.GetMetadataReference(AssemblyReference.FromFramework("mscorlib.dll")))
                          .AddMetadataReference(AssemblyReferenceService.GetMetadataReference(AssemblyReference.FromFramework("System.dll")))
                          .AddMetadataReference(AssemblyReferenceService.GetMetadataReference(AssemblyReference.FromFramework("System.Core.dll")))
                          .AddMetadataReferences(additionalReferences.Select(AssemblyReferenceService.GetMetadataReference));

            // adding an extra file to the project
            // this won't trigger any issues, but it keeps a reference to the original ParseOption, so
            // if an analyzer/codefix changes the language version, Roslyn throws an ArgumentException
            project = project.AddDocument("ExtraEmptyFile.g" + fileExtension, string.Empty).Project;

            return(project);
        }