Compile-time source code modification using Roslyn

南笙酒味 提交于 2019-11-29 02:31:57

问题


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.


回答1:


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.




回答2:


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.




回答3:


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".



来源:https://stackoverflow.com/questions/10328700/compile-time-source-code-modification-using-roslyn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!