Passing through the Roslyn C # Compiler

I built the Roslyn source as described here .

I would like to add a breakpoint in the C # compiler and go through complicating this simple program:

using System; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { var result = 1 + 2; Console.WriteLine(result); } } } 

Where should I set a breakpoint? This should be at an early stage of the compilation process, as I would like to go through parsing and even lexing.

If I install CompilerExtension as a launch project and press F5 ("Start Debugging"), a copy of Visual Studio is launched using the newly created compiler. I would like not to start a new instance of Visual Studio every time I would like to go through the compiler. What is a good way to set up a small program that directly calls the compiler code on the above source?

+7
c # roslyn
source share
2 answers

Here's one approach suggested by Josh in the comment above.

  • Add the new Console Application project to the Roslyn solution.

  • Add these two links to the project:

enter image description here

A simple parser checker:

 using Microsoft.CodeAnalysis.CSharp; namespace TestCompiler { class Program { static void Main(string[] args) { var program_text = @" using System; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { var result = 2 + 3; Console.WriteLine(result); } } } "; var result = CSharpSyntaxTree.ParseText(program_text); } } } 
  • Add a breakpoint to the line that calls ParseText .

  • "Start debugging" and go to this line to delve into the parser.

A simple program to test the compiler with Emit :

 using System; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; namespace TestCompiler { class Program { static void Main(string[] args) { var program_text = @" using System; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { var result = 2 + 3; Console.WriteLine(result); } } } "; var syntax_tree = CSharpSyntaxTree.ParseText(program_text); var compilation = CSharpCompilation.Create( Guid.NewGuid().ToString("D"), new[] { syntax_tree }, new[] { MetadataReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\mscorlib.dll") }); var emit_result = compilation.Emit(new MemoryStream()); } } } 
+5
source share

If you want to have a simple program that calls the compiler, just consider using csc as your launch project. You can specify arguments to pass (for example, source files) from the debugging options in the project.

+2
source share

All Articles