コード例 #1
0
 public Compilation Compile(string assemblyInfoText)
 {
     return(VisualBasicCompilation.Create("Fake.dll")
            .WithOptions(new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, rootNamespace: "Fake"))
            .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
            .AddSyntaxTrees(VisualBasicSyntaxTree.ParseText(assemblyInfoText)));
 }
コード例 #2
0
        private static Compilation CreateCompilation(string source, string language, DiagnosticAnalyzer[] analyzers, string rootNamespace)
        {
            string fileName    = language == LanguageNames.CSharp ? "Test.cs" : "Test.vb";
            string projectName = "TestProject";

            var syntaxTree = language == LanguageNames.CSharp ?
                             CSharpSyntaxTree.ParseText(source, path: fileName) :
                             VisualBasicSyntaxTree.ParseText(source, path: fileName);

            if (language == LanguageNames.CSharp)
            {
                return(CSharpCompilation.Create(
                           projectName,
                           syntaxTrees: new[] { syntaxTree },
                           references: new[] { TestBase.MscorlibRef }));
            }
            else
            {
                return(VisualBasicCompilation.Create(
                           projectName,
                           syntaxTrees: new[] { syntaxTree },
                           references: new[] { TestBase.MscorlibRef },
                           options: new VisualBasicCompilationOptions(
                               OutputKind.DynamicallyLinkedLibrary,
                               rootNamespace: rootNamespace)));
            }
        }
コード例 #3
0
        public static object InvokeVBTestFunction(string code, string extraDefinitions = null)
        {
            var references = new[]
            {
                MetadataReference.CreateFromFile(Assembly.Load("NetStandard").Location),
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Assert).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(ScriptEngine).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(V8ScriptEngine).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(WindowsScriptEngine).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(ClearScriptTest).Assembly.Location),
                MetadataReference.CreateFromFile(Assembly.Load("System.Runtime").Location),
                MetadataReference.CreateFromFile(Assembly.Load("Microsoft.VisualBasic.Core").Location)
            };

            var syntaxTree = VisualBasicSyntaxTree.ParseText(MiscHelpers.FormatInvariant(@"
                Imports System
                Imports System.Linq
                Imports System.Runtime.InteropServices
                Imports Microsoft.ClearScript
                Imports Microsoft.ClearScript.Test
                Imports Microsoft.ClearScript.V8
                Imports Microsoft.ClearScript.Windows
                Imports Microsoft.VisualStudio.TestTools.UnitTesting
                {1}
                Module TestModule
                    Function TestFunction
                        {0}
                    End Function
                End Module
            ", code, extraDefinitions ?? string.Empty));

            var compilation = VisualBasicCompilation.Create(
                "VBTest_" + Guid.NewGuid().ToString(),
                new[] { syntaxTree },
                references,
                new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                );

            using (var stream = new MemoryStream())
            {
                var result = compilation.Emit(stream);
                if (!result.Success)
                {
                    var messageBuilder = new StringBuilder("Errors encountered during Visual Basic compilation:\n");
                    foreach (var diagnostic in result.Diagnostics)
                    {
                        messageBuilder.Append(diagnostic);
                        messageBuilder.Append('\n');
                    }

                    throw new OperationCanceledException(messageBuilder.ToString());
                }

                stream.Seek(0, SeekOrigin.Begin);
                return(AssemblyLoadContext.Default.LoadFromStream(stream).GetType("TestModule").InvokeMember("TestFunction", BindingFlags.InvokeMethod, null, null, ArrayHelpers.GetEmptyArray <object>()));
            }
        }
コード例 #4
0
 public override Compilation CreateCompilation(
     ImmutableArray <SyntaxTree> syntaxTrees,
     ImmutableArray <MetadataReference> metadataReferences)
 => VisualBasicCompilation.Create(
     Path.GetFileNameWithoutExtension(AssemblyFileName),
     syntaxTrees: syntaxTrees,
     references: metadataReferences,
     options: CompilationOptions);
コード例 #5
0
 internal static Compilation CreateVisualBasicCompilationWithCorlib(string source, string assemblyName = null)
 {
     return(VisualBasicCompilation.Create(
                assemblyName ?? Guid.NewGuid().ToString(),
                new[] { VisualBasic.SyntaxFactory.ParseSyntaxTree(source) },
                new[] { TestReferences.NetStandard13.SystemRuntime },
                new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)));
 }
コード例 #6
0
 internal static Compilation CreateVisualBasicCompilationWithMscorlib(string source, string assemblyName)
 {
     return(VisualBasicCompilation.Create(
                assemblyName,
                new[] { VisualBasic.SyntaxFactory.ParseSyntaxTree(source) },
                new[] { TestReferences.NetFx.v4_0_30319.mscorlib },
                new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)));
 }
コード例 #7
0
 protected override Compilation CreateCompilation(SyntaxTree syntaxTree, string assemblyName, IEnumerable <PortableExecutableReference> references)
 {
     return(VisualBasicCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)));
 }
コード例 #8
0
        public override CompilerResults CompileAssemblyFromSource(CompilerParameters cp, string code)
        {
            SyntaxTree codeTree = VisualBasicSyntaxTree.ParseText(code);
            VisualBasicCompilationOptions options = new VisualBasicCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                true,
                optimizationLevel: OptimizationLevel.Release,
                generalDiagnosticOption: ReportDiagnostic.Default);

            List <MetadataReference> references = new List <MetadataReference>();


            foreach (string reference in cp.ReferencedAssemblies)
            {
                references.Add(GetReference(reference));
            }

            AddExtraAssemblies(cp.ReferencedAssemblies, references);



            Compilation compilation = VisualBasicCompilation.Create(
                "_" + Guid.NewGuid().ToString("D"), new SyntaxTree[] { codeTree },
                references: references, options: options.WithEmbedVbCoreRuntime(true)
                );



            using (MemoryStream ms = new MemoryStream())
            {
                EmitResult results = compilation.Emit(ms);
                if (results.Success)
                {
                    return(new CompilerResults()
                    {
                        CompiledAssembly = Assembly.Load(ms.ToArray())
                    });
                }
                else
                {
                    CompilerResults result = new CompilerResults();
                    foreach (Diagnostic d in results.Diagnostics)
                    {
                        if (d.Severity == DiagnosticSeverity.Error)
                        {
                            result.Errors.Add(new CompilerError()
                            {
                                ErrorText   = d.GetMessage(),
                                ErrorNumber = d.Id,
                                Line        = d.Location.GetLineSpan().StartLinePosition.Line,
                                Column      = d.Location.GetLineSpan().StartLinePosition.Character
                            });
                        }
                    }
                    return(result);
                }
            }
        }
コード例 #9
0
ファイル: VBNetLanguage.cs プロジェクト: pakrym/TryRoslyn
        public Compilation CreateLibraryCompilation(string assemblyName, bool optimizationsEnabled)
        {
            var options = new VisualBasicCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                optimizationLevel: optimizationsEnabled ? OptimizationLevel.Release : OptimizationLevel.Debug
                );

            return(VisualBasicCompilation.Create(assemblyName, options: options, references: _references));
        }
コード例 #10
0
        /// <summary>
        /// Build script
        /// </summary>
        /// <param name="filenames">File names</param>
        /// <param name="references">References</param>
        /// <param name="releaseMode">Release mode (default=true)</param>
        /// <returns>Assembly</returns>
        public static Assembly CompileVBFiles(string[] filenames, string[] references, bool releaseMode = true)
        {
            var tree = filenames.Select(u => VisualBasicSyntaxTree.ParseText(
                                            File.ReadAllText(u),
                                            path: u,
                                            encoding: System.Text.Encoding.UTF8)).ToArray();
            var op = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: releaseMode ? OptimizationLevel.Release : OptimizationLevel.Debug);

            return(Assembly.Create(VisualBasicCompilation.Create("SmartContract", tree, CreateReferences(references), op)));
        }
コード例 #11
0
        public (bool success, Assembly asm, Byte[] rawAssembly) LoadSource(string source, string language)
        {
            dynamic compilation = new object();

            if (language == "csharp")
            {
                compilation = CSharpCompilation.Create("DynamicCode")
                              .WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
                              .AddReferences(AssemblyCache.Current.GetAllMetadataReferences())
                              .AddSyntaxTrees(CSharpSyntaxTree.ParseText(source));
            }
            else if (language == "vb")
            {
                compilation = VisualBasicCompilation.Create("DynamicCode")
                              .WithOptions(new VisualBasicCompilationOptions(OutputKind.WindowsApplication,
                                                                             embedVbCoreRuntime: true))
                              .AddReferences(AssemblyCache.Current.GetAllMetadataReferences())
                              .AddSyntaxTrees(VisualBasicSyntaxTree.ParseText(source));
            }

            ImmutableArray <Diagnostic> diagnostics = compilation.GetDiagnostics();
            var error = false;

            foreach (var diagnostic in diagnostics)
            {
                switch (diagnostic.Severity)
                {
                case DiagnosticSeverity.Info:
                    //Console.WriteLine(diag.ToString());
                    break;

                case DiagnosticSeverity.Warning:
                    //Console.WriteLine(diag.ToString());
                    break;

                case DiagnosticSeverity.Error:
                    error = true;
                    Console.WriteLine(diagnostic.ToString());
                    break;
                }
            }

            if (error)
            {
                return(false, null, null);
            }

            using (var outputAssembly = new MemoryStream())
            {
                compilation.Emit(outputAssembly);

                return(true, Assembly.Load(outputAssembly.ToArray()), outputAssembly.ToArray());
            }
        }
コード例 #12
0
 private static Compilation GenerateVisualBasicCode(FileInfo codeFile)
 {
     using (var stream = codeFile.OpenRead())
     {
         var codestr    = SourceText.From(stream);
         var options    = VisualBasicParseOptions.Default.WithLanguageVersion(Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic16);
         var syntaxTree = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseSyntaxTree(codestr, options);
         return(VisualBasicCompilation.Create(System.IO.Path.GetRandomFileName(), new[] { syntaxTree },
                                              GetReferences(), new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, deterministic: true)));
     }
 }
コード例 #13
0
        private static VisualBasicCompilation CreateCompilationWithMscorlib(string source, string assemblyName, IEnumerable <MetadataReference> references)
        {
            if (assemblyName == null)
            {
                assemblyName = TestBase.GetUniqueName();
            }
            var tree    = VisualBasicSyntaxTree.ParseText(source);
            var options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release);

            return(VisualBasicCompilation.Create(assemblyName, new[] { tree }, references, options));
        }
コード例 #14
0
        public Compilation CreateCompilationFromTree(SyntaxTree tree, IEnumerable <MetadataReference> references)
        {
            var compilationOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                                     .WithRootNamespace("TestProject")
                                     .WithGlobalImports(GlobalImport.Parse("System", "System.Collections.Generic", "System.Linq",
                                                                           "Microsoft.VisualBasic"));
            var compilation = VisualBasicCompilation.Create("Conversion", new[] { tree }, references)
                              .WithOptions(compilationOptions);

            return(compilation);
        }
コード例 #15
0
ファイル: VBNetLanguage.cs プロジェクト: Injac/TryRoslyn
        public Compilation CreateLibraryCompilation(string assemblyName, bool optimizationsEnabled)
        {
            var options = _roslynAbstraction.NewCompilationOptions <VisualBasicCompilationOptions>(OutputKind.DynamicallyLinkedLibrary);

            options = _roslynAbstraction.WithOptimizationLevel(
                options, optimizationsEnabled ? OptimizationLevelAbstraction.Release : OptimizationLevelAbstraction.Debug
                );

            return(VisualBasicCompilation.Create(assemblyName)
                   .WithOptions(options)
                   .AddReferences(_microsoftVisualBasicReference));
        }
コード例 #16
0
            internal static IEnumerable <ColorizedWord> ColorizeInternal(string code)
            {
                if (re.IsMatch(code))
                {
                    code = "__dummyfrom__=" + code;            // because From is contextual
                }
                code = code.Replace("...", "___threedots___"); // because ... is unusually hard to parse
                var ref_mscorlib   = MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location);
                var ref_system     = MetadataReference.CreateFromFile(typeof(Uri).GetTypeInfo().Assembly.Location);
                var ref_systemcore = MetadataReference.CreateFromFile(typeof(Enumerable).GetTypeInfo().Assembly.Location);
                var ref_systemcollectionsimmutable = MetadataReference.CreateFromFile(typeof(ImmutableArray <>).GetTypeInfo().Assembly.Location);
                var parse_options   = new VisualBasicParseOptions(kind: SourceCodeKind.Script);
                var compile_options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, globalImports: new[] { GlobalImport.Parse("System"), GlobalImport.Parse("System.Collections"), GlobalImport.Parse("System.Collections.Generic") });
                var compilationUnit = SyntaxFactory.ParseCompilationUnit(code, options: parse_options);
                var syntaxTree      = compilationUnit.SyntaxTree;
                var compilation     = VisualBasicCompilation.Create("dummyAssemblyName", new[] { syntaxTree }, new[] { ref_mscorlib, ref_system, ref_systemcore, ref_systemcollectionsimmutable }, compile_options);
                var semanticModel   = compilation.GetSemanticModel(syntaxTree, true);
                var w = new VBColorizingWalker()
                {
                    sm = semanticModel
                };

                w.Visit(syntaxTree.GetRoot());
                //
                var suppressNextEquals = false;

                foreach (var word in w.Words)
                {
                    if (word == null)
                    {
                        yield return(word);
                    }
                    else if (word.Text == "___threedots___")
                    {
                        yield return new ColorizedWord {
                                   Text = "..."
                        }
                    }
                    ;
                    else if (word.Text == "__dummyfrom__")
                    {
                        suppressNextEquals = true; continue;
                    }
                    else if (word.Text == "=" && suppressNextEquals)
                    {
                    }
                    else
                    {
                        word.Text = word.Text.Replace("___threedots___", "...").Replace("__dummyfrom__", "");
                        yield return(word);
                    }
                }
            }
コード例 #17
0
        /// <summary>
        /// Compile a file to an assembly.
        /// </summary>
        /// <param name="fileInfo">File to compile.</param>
        public Assembly CompileFile(FileInfo fileInfo)
        {
            Language language;

            switch (fileInfo.Extension)
            {
            case ".cs":
                language = Language.CSharp;
                break;

            case ".vb":
                language = Language.VisualBasic;
                break;

            default:
                throw new NotSupportedException("Not supported extension");
            }

            using (Stream stream = fileInfo.OpenRead())
            {
                SourceText text = SourceText.From(stream);
                SyntaxTree tree; Compilation compilation = default(Compilation);



                switch (language)
                {
                case Language.CSharp:
                    tree        = CSharpSyntaxTree.ParseText(text);
                    compilation = CSharpCompilation.Create(fileInfo.Name, new[] { tree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
                    break;

                case Language.VisualBasic:
                    tree        = VisualBasicSyntaxTree.ParseText(text);
                    compilation = VisualBasicCompilation.Create(fileInfo.Name, new[] { tree }, references, new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
                    break;
                }

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    var result = compilation.Emit(memoryStream);
                    if (result.Success)
                    {
                        return(Assembly.Load(memoryStream.GetBuffer()));
                    }
                    else
                    {
                        throw new CompilationException(result.Diagnostics);
                    }
                }
            }
        }
コード例 #18
0
        /// <summary>
        ///		Interpreta un texto
        /// </summary>
        protected override CompilationUnitModel ParseText(string strFileName, string strText)
        {
            CompilationUnitModel   objUnit = new CompilationUnitModel(strFileName);
            VisualBasicCompilation objCompilation;

            // Crea el modelo de compilación
            objCompilation = VisualBasicCompilation.Create("ParserText").AddSyntaxTrees(VisualBasicSyntaxTree.ParseText(strText));
            // Obtiene el árbol semántico
            objTreeSemantic = objCompilation.GetSemanticModel(objCompilation.SyntaxTrees[0], true);
            // Interpreta los nodos
            ParseNodes(objUnit, objTreeSemantic.SyntaxTree.GetRoot());
            // Devuelve la unidad de compilación
            return(objUnit);
        }
コード例 #19
0
        protected override EmitResult Compile(MetadataReference[] references, MemoryStream ms, List <SourceFile> sourceFiles)
        {
            VisualBasicCompilationOptions options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            IEnumerable <SyntaxTree> syntaxTrees = sourceFiles.Where(x => x.FileName.EndsWith(".vb"))
                                                   .Select(x => SyntaxFactory.ParseSyntaxTree(x.SourceCode));

            VisualBasicCompilation compilation = VisualBasicCompilation.Create("implementation.dll")
                                                 .WithOptions(options)
                                                 .AddSyntaxTrees(syntaxTrees)
                                                 .AddReferences(references);

            return(compilation.Emit(ms));
        }
コード例 #20
0
        /// <summary>
        ///		Interpreta un texto
        /// </summary>
        internal override CompilationUnitModel ParseText(string fileName, string text)
        {
            CompilationUnitModel   unit = new CompilationUnitModel(fileName);
            VisualBasicCompilation compilation;

            // Crea el modelo de compilación
            compilation = VisualBasicCompilation.Create("ParserText").AddSyntaxTrees(VisualBasicSyntaxTree.ParseText(text));
            // Obtiene el árbol semántico
            treeSemantic = compilation.GetSemanticModel(compilation.SyntaxTrees[0], true);
            // Interpreta los nodos
            ParseNodes(unit, treeSemantic.SyntaxTree.GetRoot());
            // Devuelve la unidad de compilación
            return(unit);
        }
コード例 #21
0
            public TestUtilityAnalyzer(string language, params string[] additionalPaths)
            {
                var         additionalFiles = additionalPaths.Select(x => new AnalyzerAdditionalFile(x)).ToImmutableArray <AdditionalText>();
                var         context         = new SonarAnalysisContext(new SonarAnalysisContextTest.DummyContext(), Enumerable.Empty <DiagnosticDescriptor>());
                Compilation compilation     = language switch
                {
                    LanguageNames.CSharp => CSharpCompilation.Create(null),
                    LanguageNames.VisualBasic => VisualBasicCompilation.Create(null),
                    _ => throw new InvalidOperationException($"Unexpected {nameof(language)}: {language}")
                };
                var c = new CompilationAnalysisContext(compilation, new AnalyzerOptions(additionalFiles), null, null, default);

                ReadParameters(context, c);
            }
コード例 #22
0
        [HttpPost("VisualBasic")] // POST: /SyntaxTree/VisualBasic
        public async Task <SyntaxTreeNode> VisualBasicPost(CancellationToken cancellationToken)
        {
            using var reader = new StreamReader(Request.Body, Encoding.UTF8);
            string body = await reader.ReadToEndAsync().ConfigureAwait(false);

            SyntaxTree tree = VisualBasicSyntaxTree.ParseText(body);
            SyntaxNode root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);

            Compilation    compilation = VisualBasicCompilation.Create("HelloWorld", new[] { tree });
            SemanticModel  model       = compilation.GetSemanticModel(tree);
            SyntaxTreeNode myRoot      = SyntaxTreeNode.CreateMyOwnTree(root, model);

            return(myRoot);
        }
コード例 #23
0
        public override async Task <(SyntaxTree syntaxTree, SemanticModel semModel)> GetDocumentModelsAsync(string fileName)
        {
            await Task.CompletedTask;
            var code = File.ReadAllText(fileName);

            var isCSharp = Path.GetExtension(fileName) == ".cs";

            var syntaxTree = isCSharp ? CSharpSyntaxTree.ParseText(code)
                                      : VisualBasicSyntaxTree.ParseText(code);

            Assert.IsNotNull(syntaxTree);

            var semModel = isCSharp ? CSharpCompilation.Create(string.Empty).AddSyntaxTrees(syntaxTree).GetSemanticModel(syntaxTree, ignoreAccessibility: true)
                                    : VisualBasicCompilation.Create(string.Empty).AddSyntaxTrees(syntaxTree).GetSemanticModel(syntaxTree, ignoreAccessibility: true);

            return(syntaxTree, semModel);
        }
コード例 #24
0
        public static VisualBasicCompilation CreateCompilation(
            IEnumerable <SyntaxTree> trees,
            IEnumerable <MetadataReference> references = null,
            VisualBasicCompilationOptions compOptions  = null,
            string assemblyName = "")
        {
            if (compOptions == null)
            {
                compOptions = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, "a.dll");
            }

            return(VisualBasicCompilation.Create(
                       string.IsNullOrEmpty(assemblyName) ? GetUniqueName() : assemblyName,
                       trees,
                       references,
                       compOptions));
        }
コード例 #25
0
        internal override Compilation Compile(string className, string generatedCode, string codeBehind, PortableExecutableReference[] references)
        {
            var syntaxTrees = new List <SyntaxTree> {
                VisualBasicSyntaxTree.ParseText(generatedCode)
            };

            if (!string.IsNullOrEmpty(codeBehind))
            {
                syntaxTrees.Add(CSharpSyntaxTree.ParseText(codeBehind));
            }

            var x = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary);


            return(VisualBasicCompilation.Create($"{className}_{Guid.NewGuid():D}.dll", syntaxTrees, references,
                                                 new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, false, null, null, "Script", null, null, OptionStrict.Off, true, true, false, null, false, OptimizationLevel.Release)));
        }
コード例 #26
0
        /// <summary>
        /// Compiles a Visual Basic source code file.
        /// </summary>
        /// <param name="sourceCodeFilePath">Path to the source code file.</param>
        /// <param name="assemblyFilePath">Path to the destination compiled file.</param>
        /// <returns>Result of the compilation.</returns>
        static EmitResult CompileVisualBasic(string sourceCodeFilePath, string assemblyFilePath)
        {
            string assemblyName = Path.GetFileNameWithoutExtension(assemblyFilePath);

            MetadataReference []          references = GetAssemblyReferences();
            VisualBasicCompilationOptions options    = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            SyntaxTree [] syntaxTree;
            using (Stream stream = File.OpenRead(sourceCodeFilePath)) {
                syntaxTree = new SyntaxTree [] { VisualBasicSyntaxTree.ParseText(SourceText.From(stream)) };
            }

            VisualBasicCompilation compilation = VisualBasicCompilation.Create(assemblyName, syntaxTree, references, options);

            using (Stream output = File.Create(assemblyFilePath)) {
                return(compilation.Emit(output));
            }
        }
コード例 #27
0
ファイル: GivesAccessTo.cs プロジェクト: zuvys/roslyn
        public void TestGivesAccessTo_CrossLanguageAndCompilation()
        {
            var csharpTree  = CSharpSyntaxTree.ParseText(@"
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""VB"")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS2"")]
internal class CS
{
}
");
            var csharpTree2 = CSharpSyntaxTree.ParseText(@"
internal class CS2
{
}
");
            var vbTree      = VisualBasicSyntaxTree.ParseText(@"
<assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS"")>
<assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""VB2"")>
Friend Class VB
End Class
");
            var vbTree2     = VisualBasicSyntaxTree.ParseText(@"
Friend Class VB2
End Class
");
            var csc         = (Compilation)CSharpCompilation.Create("CS", new[] { csharpTree }, new MetadataReference[] { TestBase.MscorlibRef });
            var CS          = csc.GlobalNamespace.GetMembers("CS").First() as INamedTypeSymbol;

            var csc2 = (Compilation)CSharpCompilation.Create("CS2", new[] { csharpTree2 }, new MetadataReference[] { TestBase.MscorlibRef });
            var CS2  = csc2.GlobalNamespace.GetMembers("CS2").First() as INamedTypeSymbol;

            var vbc = VisualBasicCompilation.Create("VB", new[] { vbTree }, new MetadataReference[] { TestBase.MscorlibRef });
            var VB  = vbc.GlobalNamespace.GetMembers("VB")[0] as INamedTypeSymbol;

            var vbc2 = VisualBasicCompilation.Create("VB2", new[] { vbTree2 }, new MetadataReference[] { TestBase.MscorlibRef });
            var VB2  = vbc2.GlobalNamespace.GetMembers("VB2")[0] as INamedTypeSymbol;

            Assert.True(CS.ContainingAssembly.GivesAccessTo(CS2.ContainingAssembly));
            Assert.True(CS.ContainingAssembly.GivesAccessTo(VB.ContainingAssembly));
            Assert.False(CS.ContainingAssembly.GivesAccessTo(VB2.ContainingAssembly));

            Assert.True(VB.ContainingAssembly.GivesAccessTo(VB2.ContainingAssembly));
            Assert.True(VB.ContainingAssembly.GivesAccessTo(CS.ContainingAssembly));
            Assert.False(VB.ContainingAssembly.GivesAccessTo(CS2.ContainingAssembly));
        }
コード例 #28
0
        public override CompilerResults CompileAssemblyFromDom(CompilerParameters options, params CodeCompileUnit[] compilationUnits)
        {
            var writer = new StringWriter();

            GenerateCodeFromCompileUnit(compilationUnits[0], writer, new CodeGeneratorOptions());
            var roslynTree       = SyntaxFactory.ParseSyntaxTree(writer.ToString(), null, "");
            var roslynOptions    = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var roslynReferences = new List <MetadataReference>();

            CheckAndAddReference(roslynReferences, System.Reflection.Assembly.Load("System.Private.CoreLib").Location);
            CheckAndAddReference(roslynReferences, System.Reflection.Assembly.Load("Microsoft.VisualBasic.Core").Location);
            CheckAndAddReference(roslynReferences, System.Reflection.Assembly.Load("System.Runtime").Location);
            CheckAndAddReference(roslynReferences, System.Reflection.Assembly.Load("System.Text.RegularExpressions").Location);
            foreach (var assembly in options.ReferencedAssemblies)
            {
                if (assembly == "System.dll")
                {
                    continue;
                }
                CheckAndAddReference(roslynReferences, assembly);
            }
            var roslynCompilation = VisualBasicCompilation.Create(Path.GetFileNameWithoutExtension(options.OutputAssembly), new[] { roslynTree }, options: roslynOptions, references: roslynReferences);
            var roslynAssembly    = new MemoryStream();
            var result            = roslynCompilation.Emit(roslynAssembly);

            if (!result.Success)
            {
                var error = result.Diagnostics.Where(e => e.Severity == DiagnosticSeverity.Error).FirstOrDefault();
                if (error != null)
                {
                    throw new InvalidOperationException(error.ToString());
                }
                throw new Exception();
            }
            var assemblyFile = Path.GetTempFileName();

            File.WriteAllBytes(assemblyFile, roslynAssembly.ToArray());
            var compilerResults = new CompilerResults(new TempFileCollection())
            {
                PathToAssembly = assemblyFile
            };

            return(compilerResults);
        }
コード例 #29
0
        public override CompilerResults CompileAssemblyFromDom(CompilerParameters options, params CodeCompileUnit[] compilationUnits)
        {
            var writer = new StringWriter();

            GenerateCodeFromCompileUnit(compilationUnits[0], writer, new CodeGeneratorOptions());
            var roslynTree       = SyntaxFactory.ParseSyntaxTree(writer.ToString(), null, "");
            var roslynOptions    = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var roslynReferences = new List <MetadataReference>();

            roslynReferences.Add(MetadataReference.CreateFromFile(typeof(Object).Assembly.Location));
            roslynReferences.Add(MetadataReference.CreateFromFile(typeof(System.Runtime.AssemblyTargetedPatchBandAttribute).Assembly.Location));
            roslynReferences.Add(MetadataReference.CreateFromFile(typeof(Microsoft.VisualBasic.Collection).Assembly.Location));
            foreach (var assembly in options.ReferencedAssemblies)
            {
                if (assembly == "System.dll")
                {
                    continue;
                }
                roslynReferences.Add(MetadataReference.CreateFromFile(assembly));
            }
            var roslynCompilation = VisualBasicCompilation.Create("expr", new[] { roslynTree }, options: roslynOptions, references: roslynReferences);
            var roslynAssembly    = new MemoryStream();
            var result            = roslynCompilation.Emit(roslynAssembly);

            if (!result.Success)
            {
                var error = result.Diagnostics.Where(e => e.Severity == DiagnosticSeverity.Error).FirstOrDefault();
                if (error != null)
                {
                    throw new InvalidOperationException(error.ToString());
                }
                throw new Exception();
            }
            var assemblyFile = Path.GetTempFileName();

            File.WriteAllBytes(assemblyFile, roslynAssembly.ToArray());
            var compilerResults = new CompilerResults(new TempFileCollection())
            {
                PathToAssembly = assemblyFile
            };

            return(compilerResults);
        }
コード例 #30
0
        public void Compile(string output, string[] sourceFiles, string[] libraries)
        {
            if (sourceFiles.Length > 0)
            {
                var syntaxTrees = new List <SyntaxTree>();
                var references  = new List <MetadataReference>();

                foreach (var file in sourceFiles)
                {
                    syntaxTrees.Add(VisualBasicSyntaxTree.ParseText(File.ReadAllText(file)));
                }

                foreach (var library in libraries)
                {
                    references.Add(MetadataReference.CreateFromFile(library));
                }

                var compilation = VisualBasicCompilation.Create(output, syntaxTrees, references);

                using (var memoryStream = new MemoryStream())
                {
                    var result = compilation.Emit(memoryStream);

                    if (result.Success)
                    {
                        using (var streamWriter = new StreamWriter(output))
                        {
                            streamWriter.Write(memoryStream.ToArray());
                        }

                        Finished?.Invoke(this, 0);
                    }
                    else
                    {
                        Finished?.Invoke(this, 1);
                    }
                }
            }
            else
            {
                throw new ArgumentException();
            }
        }