コード例 #1
0
        public static void CreateAssemblyDefinition(string code)
        {
            Microsoft.CodeAnalysis.SyntaxTree syntaxTree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(code);

            System.Collections.Generic.IReadOnlyCollection <
                Microsoft.CodeAnalysis.MetadataReference> _references = new[] {
                Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(System.Reflection.Binder).Assembly.Location),
                Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(System.ValueTuple <>).Assembly.Location)
            };

            bool enableOptimisations = true;

            Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions options =
                new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(
                    Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary,
                    optimizationLevel: enableOptimisations ? Microsoft.CodeAnalysis.OptimizationLevel.Release : Microsoft.CodeAnalysis.OptimizationLevel.Debug,
                    allowUnsafe: true
                    );


            Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create(
                assemblyName: "InMemoryAssembly", options: options)
                                                             .AddReferences(_references)
                                                             .AddSyntaxTrees(syntaxTree);

            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(stream);

            if (emitResult.Success)
            {
                stream.Seek(0, System.IO.SeekOrigin.Begin);
                // System.Reflection.Metadata.AssemblyDefinition assembly = System.Reflection.Metadata.AssemblyDefinition.ReadAssembly(stream);
            }
        }
コード例 #2
0
 async Task LoadExceptionList()
 {
     classes.Add("System.Exception");
     try {
         Microsoft.CodeAnalysis.Compilation compilation    = null;
         Microsoft.CodeAnalysis.ProjectId   dummyProjectId = null;
         if (IdeApp.ProjectOperations.CurrentSelectedProject != null)
         {
             compilation = await TypeSystemService.GetCompilationAsync(IdeApp.ProjectOperations.CurrentSelectedProject);
         }
         if (compilation == null)
         {
             //no need to unload this assembly context, it's not cached.
             dummyProjectId = Microsoft.CodeAnalysis.ProjectId.CreateNewId("GetExceptionsProject");
             compilation    = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("GetExceptions")
                              .AddReferences(MetadataReferenceCache.LoadReference(dummyProjectId, System.Reflection.Assembly.GetAssembly(typeof(object)).Location))                                                        //corlib
                              .AddReferences(MetadataReferenceCache.LoadReference(dummyProjectId, System.Reflection.Assembly.GetAssembly(typeof(Uri)).Location));                                                          //System.dll
         }
         var exceptionClass = compilation.GetTypeByMetadataName("System.Exception");
         foreach (var t in compilation.GlobalNamespace.GetAllTypes().Where((arg) => arg.IsDerivedFromClass(exceptionClass)))
         {
             classes.Add(t.GetFullMetadataName());
         }
         if (dummyProjectId != null)
         {
             MetadataReferenceCache.RemoveReferences(dummyProjectId);
         }
     } catch (Exception e) {
         LoggingService.LogError("Failed to obtain exceptions list in breakpoint dialog.", e);
     }
     await Runtime.RunInMainThread(() => {
         entryExceptionType.SetCodeCompletionList(classes.ToList());
     });
 }
コード例 #3
0
        } // End Sub Test 
        
        
        // emit the compilation result into a byte array.
        // throw an exception with corresponding message
        // if there are errors
        private static byte[] EmitToArray
        (
            this Microsoft.CodeAnalysis.Compilation compilation
        )
        {
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                // emit result into a stream
                Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(stream);

                if (!emitResult.Success)
                {
                    // if not successful, throw an exception
                    Microsoft.CodeAnalysis.Diagnostic firstError =
                        emitResult
                            .Diagnostics
                            .FirstOrDefault
                            (
                                diagnostic =>
                                    diagnostic.Severity ==
                                    Microsoft.CodeAnalysis.DiagnosticSeverity.Error
                            );

                    throw new System.Exception(firstError?.GetMessage());
                }

                // get the byte array from a stream
                return stream.ToArray();
            } // End Using stream
            
        } // End Function EmitToArray 
コード例 #4
0
        async Task LoadExceptionList()
        {
            classes.Add("System.Exception");
            try {
                Microsoft.CodeAnalysis.Compilation compilation = null;
                MonoDevelopWorkspace workspace = null;

                var project = IdeApp.ProjectOperations.CurrentSelectedProject;
                if (project != null)
                {
                    var roslynProj = IdeApp.TypeSystemService.GetProject(project);
                    if (roslynProj != null)
                    {
                        workspace   = (MonoDevelopWorkspace)roslynProj.Solution.Workspace;
                        compilation = await roslynProj.GetCompilationAsync();
                    }
                }

                if (compilation == null)
                {
                    // TypeSystemService.Workspace always returns a workspace,
                    // even if it might be empty.
                    workspace = workspace ?? (MonoDevelopWorkspace)IdeServices.TypeSystemService.Workspace;
                    var service = workspace.MetadataReferenceManager;
                    var corlib  = service.GetOrCreateMetadataReferenceSnapshot(System.Reflection.Assembly.GetAssembly(typeof(object)).Location, MetadataReferenceProperties.Assembly);
                    var system  = service.GetOrCreateMetadataReferenceSnapshot(System.Reflection.Assembly.GetAssembly(typeof(Uri)).Location, MetadataReferenceProperties.Assembly);

                    //no need to unload this assembly context, it's not cached.
                    compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("GetExceptions")
                                  .AddReferences(corlib)
                                  .AddReferences(system);
                }
                var exceptionClass = compilation.GetTypeByMetadataName("System.Exception");
                foreach (var t in compilation.GlobalNamespace.GetAllTypes().Where((arg) => arg.IsDerivedFromClass(exceptionClass)))
                {
                    classes.Add(t.GetFullMetadataName());
                }
            } catch (Exception e) {
                LoggingService.LogError("Failed to obtain exceptions list in breakpoint dialog.", e);
            }
            await Runtime.RunInMainThread(() => {
                entryExceptionType.SetCodeCompletionList(classes.ToList());
            });
        }
コード例 #5
0
        private static void CreateCsCompilation(string code)
        {
            Microsoft.CodeAnalysis.SyntaxTree syntaxTree =
                Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(code);

            string assemblyName = System.Guid.NewGuid().ToString();

            System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references =
                GetAssemblyReferences();

            Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create(
                assemblyName,
                new[] { syntaxTree },
                references,
                new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(
                    Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary)
                );

            // byte[] compilationResult = compilation.EmitToArray();
            // System.Reflection.Assembly.Load(compilationResult);

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms);
                ThrowExceptionIfCompilationFailure(result);
                ms.Seek(0, System.IO.SeekOrigin.Begin);


                System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms);
#if NET46
                // Different in full .Net framework
                System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray());
#endif
            }


            // _compilation = compilation;
        }
コード例 #6
0
        } // End Sub CheckCompilationResult

        private static void CreateCompilation2(string code)
        {
            Microsoft.CodeAnalysis.SyntaxTree syntaxTree =
                Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(code);

            string assemblyName = System.Guid.NewGuid().ToString();

            System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references =
                GetAssemblyReferences();


            Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions co =
                new Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions
                (
                    Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary
                );

            co.WithOptionStrict(Microsoft.CodeAnalysis.VisualBasic.OptionStrict.Off);
            co.WithOptionExplicit(false);
            co.WithOptionInfer(true);


            Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.Create(
                assemblyName,
                new[] { syntaxTree },
                references,
                co
                );


            // WTF !!!
            // byte[] compilationResult = compilation.EmitToArray();


            // Load the resulting assembly into the domain.
            // System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(compilationResult);

            /*
             * // get the type Program from the assembly
             * System.Type programType = assembly.GetType("Program");
             *
             * // Get the static Main() method info from the type
             * System.Reflection.MethodInfo method = programType.GetMethod("Main");
             *
             * // invoke Program.Main() static method
             * method.Invoke(null, null);
             */



            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms);
                ThrowExceptionIfCompilationFailure(result);
                ms.Seek(0, System.IO.SeekOrigin.Begin);


                System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms);
#if NET46
                // Different in full .Net framework
                System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray());
#endif
            }
        }
コード例 #7
0
        private static void CreateCompilationMultiFile(string[] filenames)
        {
            string assemblyName = System.Guid.NewGuid().ToString();

            System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references =
                GetAssemblyReferences();

            Microsoft.CodeAnalysis.SyntaxTree[] syntaxTrees = new Microsoft.CodeAnalysis.SyntaxTree[filenames.Length];

            Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions op = null;

            for (int i = 0; i < filenames.Length; ++i)
            {
                string fileContent = System.IO.File.ReadAllText(filenames[i], System.Text.Encoding.UTF8);
                syntaxTrees[i] = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(
                    fileContent
                    , op
                    , filenames[i]
                    , System.Text.Encoding.UTF8
                    );
            }



            Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions co =
                new Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions
                (
                    Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary
                );

            co.WithOptionStrict(Microsoft.CodeAnalysis.VisualBasic.OptionStrict.Off);
            co.WithOptionExplicit(false);
            co.WithOptionInfer(true);


            Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.Create(
                assemblyName,
                syntaxTrees,
                references,
                co
                );


            // byte[] compilationResult = compilation.EmitToArray();

            using (System.IO.MemoryStream dllStream = new System.IO.MemoryStream())
            {
                using (System.IO.MemoryStream pdbStream = new System.IO.MemoryStream())
                {
                    Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(dllStream, pdbStream);
                    if (!emitResult.Success)
                    {
                        CheckCompilationResult(emitResult);
                    } // End if (!emitResult.Success)
                }     // End Using pdbStream
            }         // End Using dllStream



            /*
             * // get the type Program from the assembly
             * System.Type programType = assembly.GetType("Program");
             *
             * // Get the static Main() method info from the type
             * System.Reflection.MethodInfo method = programType.GetMethod("Main");
             *
             * // invoke Program.Main() static method
             * method.Invoke(null, null);
             */

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms);
                ThrowExceptionIfCompilationFailure(result);
                ms.Seek(0, System.IO.SeekOrigin.Begin);


                System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms);
#if NET46
                // Different in full .Net framework
                System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray());
#endif
            } // End Using ms
        }
コード例 #8
0
 internal static Microsoft.CodeAnalysis.INamedTypeSymbol GetTypeBySystemType <T>(this Microsoft.CodeAnalysis.Compilation compilation)
 {
     return(compilation.GetTypeByMetadataName(typeof(T).FullName));
 }