Skip to content

Instantly share code, notes, and snippets.

@Antaris
Created July 13, 2015 10:03
Show Gist options
  • Save Antaris/76ff4f2535e6dd3396bb to your computer and use it in GitHub Desktop.
Save Antaris/76ff4f2535e6dd3396bb to your computer and use it in GitHub Desktop.
namespace CompileModuleExample
{
public class Greeter
{
public string GetMessage()
{
}
}
}
namespace CompileModuleExample.compiler.preprocess
{
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.Framework.Runtime.Roslyn;
using T = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree;
using F = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using K = Microsoft.CodeAnalysis.CSharp.SyntaxKind;
public class ImplementGreeterCompileModule : ICompileModule
{
public void AfterCompile(AfterCompileContext context)
{
// NoOp
}
public void BeforeCompile(BeforeCompileContext context)
{
// Get our Greeter class.
var syntaxMatch = context.Compilation.SyntaxTrees
.Select(s => new
{
Tree = s,
Root = s.GetRoot(),
Class = s.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().Where(cs => cs.Identifier.ValueText == "Greeter").SingleOrDefault()
})
.Where(a => a.Class != null)
.Single();
var tree = syntaxMatch.Tree;
var root = syntaxMatch.Root;
var classSyntax = syntaxMatch.Class;
// Get the method declaration.
var methodSyntax = classSyntax.Members
.OfType<MethodDeclarationSyntax>()
.Where(ms => ms.Identifier.ValueText == "GetMessage")
.Single();
// Let's implement the body.
var returnStatement = F.ReturnStatement(
F.LiteralExpression(
K.StringLiteralExpression,
F.Literal(F.TriviaList(), @"""Hello World!""", @"""Hello World!""", F.TriviaList())));
// Get the body block
var bodyBlock = methodSyntax.Body;
// Create a new body block, with our new statement.
var newBodyBlock = F.Block(new StatementSyntax[] { returnStatement });
// Get the revised root
var newRoot = (CompilationUnitSyntax)root.ReplaceNode(bodyBlock, newBodyBlock);
// Create a new syntax tree.
var newTree = T.Create(newRoot);
// Replace the compilation.
context.Compilation = context.Compilation.ReplaceSyntaxTree(tree, newTree);
}
}
}
{
"version": "1.0.0-*",
"dependencies": {
"Microsoft.CodeAnalysis.CSharp": "1.0.0-*",
"Microsoft.Framework.Runtime.Roslyn.Abstractions": "1.0.0-*"
},
"frameworks": {
"dnx451": {
"frameworkAssemblies": {
"System.Runtime": "4.0.10.0",
"System.Threading.Tasks": "4.0.0.0",
"System.Text.Encoding": "4.0.0.0"
}
},
"dnxcore50": {
"dependencies": {
"System.ComponentModel": "4.0.0-*",
"System.IO": "4.0.10-*",
"System.Reflection": "4.0.10-*",
"System.Runtime": "4.0.10-*",
"System.Runtime.Extensions": "4.0.10-*",
"System.Threading.Tasks": "4.0.10-*"
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment