简体   繁体   English

使用Roslyn编译时编译源代码

[英]Compile-time source code modification using Roslyn

Is it possible to modify source code before compilation using Roslyn within MSBuild task on CI server? 是否可以在CI服务器上的MSBuild任务中使用Roslyn进行编译之前修改源代码? I've succeeded to do what I want in VS but I wonder if it is possible outside VS. 我已经成功地在VS中做了我想要的但是我想知道在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? 目前我正在研究Workspace API和Compiler API,它们似乎是实现这一目标的正确工具,但我仍然不确定它是否可行? In particular I'm concerned about returning changes that I've done to MSBuild back to allow it to continue its job. 特别是我担心返回我对MSBuild所做的更改以允许它继续工作。

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. 您不能使用Workspace API加载项目/解决方案,因为您已经在msbuild中。
  2. To use the regular compiler APIs, you need to construct a compilation yourself which can be a bunch of work. 要使用常规编译器API,您需要自己构建一个编译,这可能是一堆工作。

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. 将来,我们想提供一个“从csc / vbc命令行字符串创建工作区”,这将使这更容易。

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. 看一下钩子编译器(csc.exe或vbc.exe)本身以及在MS Build Task中使用Roslyn的问题,以前的讨论。

regarding the question on Problem with using Roslyn in a MS Build Task , 关于在MS构建任务中使用Roslyn的问题

  public class MyTask : Task

changing Task to AppDomainIsolatedTask is a quick fix. 将任务更改为AppDomainIsolatedTask是一个快速修复。 I don't have msdn account so I'll just post it here. 我没有msdn帐户所以我会在这里发布。 Hope it can help. 希望它可以提供帮助。

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. 我个人没有能够测试这个,(所以如果你愿意,把这个“答案”当作评论),但是阅读关于Roslyn的内容,尤其是这篇博客文章,它看起来应该是可能的 (寻找“重写” “段落。

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. 显然,你可以从源代码构造一个语法树(对于我猜的编译器来说并不太令人惊讶),然后使用API​​修改它,最后将它写回字符串/文件或其他任何东西。

Also see MSDN about Roslyn syntax trees conceptually, and this walkthrough about "Syntax Transformation". 另请参阅MSDN关于Roslyn语法树的概念,以及关于“语法转换”的演练

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM