Skip to content

Instantly share code, notes, and snippets.

@JohnWintellect
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnWintellect/78e065b7e60fcf6dffa8 to your computer and use it in GitHub Desktop.
Save JohnWintellect/78e065b7e60fcf6dffa8 to your computer and use it in GitHub Desktop.
Example of using the Roslyn Control Flow Analysis API
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Linq;
namespace ConsoleRoslyn
{
class Program
{
static void ProcessExample(String rawCode)
{
SyntaxTree code = CSharpSyntaxTree.ParseText(rawCode);
MetadataReference corLib = MetadataReference.CreateFromAssembly(typeof(object).Assembly);
CSharpCompilation compilation = CSharpCompilation.Create("TestCompilation",
new[] { code },
new[] { corLib });
SemanticModel semanticModel = compilation.GetSemanticModel(code);
CatchClauseSyntax theCatch = code.GetRoot().DescendantNodes().OfType<CatchClauseSyntax>().First();
ControlFlowAnalysis result = semanticModel.AnalyzeControlFlow(theCatch.Block);
Console.WriteLine("=======================================================================");
Console.WriteLine("{0}", theCatch.Block.ToString());
Console.WriteLine("Succeeded : {0}", result.Succeeded);
Console.WriteLine("Return statements : {0}", result?.ReturnStatements.Count() ?? 0);
Console.WriteLine("Endpoint reachable : {0}", result.EndPointIsReachable);
Console.WriteLine("Exit point count : {0}", result?.ExitPoints.Count() ?? 0);
}
static void Main(string[] args)
{
String code = @"
using System;
using System.IO;
class SimpleThrow
{
public void Example(Int32 i)
{
try
{
Console.WriteLine(""i = {0}"", i);
}
catch (FileNotFoundException)
{
Console.WriteLine(""Got an exception"");
throw;
}
}
}
";
ProcessExample(code);
code = @"
using System;
using System.IO;
class EatException
{
public void Example(Int32 i)
{
try
{
Console.WriteLine(""i = {0}"", i);
}
catch (FileNotFoundException)
{
}
}
}
";
ProcessExample(code);
code = @"
using System;
using System.IO;
class EatExceptionInOneCase
{
public void Example(Int32 i)
{
try
{
Console.WriteLine(""i = {0}"", i);
}
catch (FileNotFoundException)
{
if (i < 5)
{
throw;
}
}
}
}
";
ProcessExample(code);
code = @"
class EatExceptionWithReturn
{
public void Example(Int32 i)
{
try
{
Console.WriteLine(""i = {0}"", i);
}
catch (FileNotFoundException)
{
if (i < 5)
{
return;
}
else
{
throw;
}
}
}
}
";
ProcessExample(code);
code = @"
class EatExceptionWithReturn
{
static void Main()
{
try
{
String s = null;
if (s.Length > 0)
{
Console.WriteLine(""Too big"");
}
}
catch
{
goto BailOut;
}
Console.WriteLine(""You should not see this!"");
BailOut:
Console.WriteLine(""Bailed!"");
}
}
";
ProcessExample(code);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment