Skip to content

Instantly share code, notes, and snippets.

@JohnnyJosep
Created January 9, 2019 12:42
Show Gist options
  • Select an option

  • Save JohnnyJosep/06da6a9742f59206411d2697626c54dc to your computer and use it in GitHub Desktop.

Select an option

Save JohnnyJosep/06da6a9742f59206411d2697626c54dc to your computer and use it in GitHub Desktop.
To create auto-generated code
/*
* Microsoft.CodeAnalysis.CSharp v.:2.10.0
* System.Runtime.Loader v.:4.3.0 />
*/
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
namespace Compiler
{
class Program
{
static Action<string> Write = Console.WriteLine;
public static void Main(string[] args)
{
Write("Let's compile!");
string codeToCompile = @"
using System;
namespace RoslynCompileSample
{
public class Writer
{
public void Write(string message)
{
Console.WriteLine($""you said '{message}!'"");
}
}
}";
Write("Parsing the code into the SyntaxTree");
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(codeToCompile);
string assemblyName = Path.GetRandomFileName();
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
MetadataReference[] references = new MetadataReference[]
{
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Private.CoreLib.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Console.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")),
};
Write("Compiling ...");
var compilation = CSharpCompilation.Create(assemblyName)
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddReferences(references)
.AddSyntaxTrees(syntaxTree);
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
Write("Compilation failed!");
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.Error.WriteLine("\t{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
}
else
{
Write("Compilation successful! Now instantiating and executing the code ...");
ms.Seek(0, SeekOrigin.Begin);
Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms);
var type= assembly.GetType("RoslynCompileSample.Writer");
var instance = assembly.CreateInstance("RoslynCompileSample.Writer");
var meth = type.GetMember("Write").First() as MethodInfo;
meth.Invoke(instance, new [] {"joel"});
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment