Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time source code modification using Roslyn

Is it possible to modify source code before compilation using Roslyn within MSBuild task on CI server? I've succeeded to do what I want in VS but I wonder if it is possible outside VS. Currently I'm looking at Workspace APIs and Compiler APIs and they seem to be the right tool to achieve that, but I'm still not sure is it possible at all? In particular I'm concerned about returning changes that I've done to MSBuild back to allow it to continue its job.

like image 724
Anton Moiseev Avatar asked Apr 26 '12 07:04

Anton Moiseev


3 Answers

This is definitely a scenario that we are thinking of. Today there are a couple of problems that make it a bit difficult:

  1. You can't use the Workspace APIs to load a project/solution as you are already inside of msbuild.
  2. To use the regular compiler APIs, you need to construct a compilation yourself which can be a bunch of work.

In the future, we'd like to provide a "Create a workspace from a csc/vbc command line string", which would make this a lot easier.

Take a look at Hooking into the compiler (csc.exe or vbc.exe) itself and Problem with using Roslyn in a MS Build Task for some previous discussion on this.

like image 140
Kevin Pilch Avatar answered Oct 20 '22 21:10

Kevin Pilch


regarding the question on Problem with using Roslyn in a MS Build Task,

  public class MyTask : Task

changing Task to AppDomainIsolatedTask is a quick fix. I don't have msdn account so I'll just post it here. Hope it can help.

like image 40
Tao Song Avatar answered Oct 20 '22 21:10

Tao Song


I have not personally been able to test this, (so if you will, treat this "answer" as a comment), but reading stuff about Roslyn, especially this blog entry, it looks like it should be possible (look for the "Rewrite" paragraph.

Apparently, you can construct a syntax tree from the source (not too surprising for a compiler I guess), then modify this using APIs, and finally write it back out to a string/file or whatever.

Also see MSDN about Roslyn syntax trees conceptually, and this walkthrough about "Syntax Transformation".

like image 1
Christian.K Avatar answered Oct 20 '22 21:10

Christian.K