Created
June 19, 2018 22:01
-
-
Save mvacha/6b8102e0c3c3eba90ee750b87fb2c122 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static Compilation Compile(string code) | |
{ | |
var parserOptions = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp7); | |
var parsedTree = CSharpSyntaxTree.ParseText(code, options: parserOptions); | |
//Assert parser success | |
Debug.Assert(!parsedTree.GetRoot().HasErrors()); | |
//Enable flow-analysis feature flag | |
var options = parsedTree.Options.WithFeatures(new[] { new KeyValuePair<string, string>("flow-analysis", "true") }); | |
parsedTree = parsedTree.WithRootAndOptions(parsedTree.GetRoot(), options); | |
//Compile and link with. mscorlib.dll | |
var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); | |
var compilation = CSharpCompilation.Create("MyCompilation", | |
syntaxTrees: new[] { parsedTree }, | |
references: new[] { mscorlib }); | |
return compilation; | |
} | |
static ControlFlowGraph GetTreeCFG(Compilation compilation) | |
{ | |
var tree = compilation.SyntaxTrees.Single(); | |
var root = tree.GetRoot(); | |
var semanticModel = compilation.GetSemanticModel(tree); | |
var firstMethod = root.DescendantNodes().OfType<BaseMethodDeclarationSyntax>().First(); | |
var firstMethodOper = semanticModel.GetOperation(firstMethod) as IMethodBodyOperation; | |
return ControlFlowGraph.Create(firstMethodOper); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment