简体   繁体   English

在 Roslyn 分析器中分析后预处理器代码

[英]Analyze post-preprocessor code in Roslyn analyzer

I'm writing a Roslyn analyzer (actually source generator, but they largely share the same API), and I would like to have it analyze only post-processor code.我正在编写一个 Roslyn 分析器(实际上是源生成器,但它们在很大程度上共享相同的 API),我想让它只分析后处理器代码。 For instance, if I have code that is excluded with #if/#else, I would like my analyzer to not work on that code.例如,如果我有使用#if/#else 排除的代码,我希望我的分析器不能处理该代码。 Similarly, I would like #beginregion/#endregion and the like to not show up for my analyzer.同样,我希望#beginregion/#endregion 等不要出现在我的分析仪中。

Is there a way to get a post-preprocessed compilation or syntax tree from Roslyn?有没有办法从 Roslyn 获得预处理后的编译或语法树? I can do something like the following, but it will throw away all of my original location info and I am guessing that my compilations semantic model will know nothing about the newly generated syntax tree:我可以执行以下操作,但它会丢弃我所有的原始位置信息,我猜我的编译语义 model 对新生成的语法树一无所知:

var preprocessorSymbols = candidate.SyntaxTree.Options.PreprocessorSymbolNames;
var parseOptions = CSharpParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols);
var newSyntaxTree = CSharpSyntaxTree.ParseText(candidate.SyntaxTree.ToString(), parseOptions);

The Roslyn parser already will have skipped code inside the #if/#else that isn't active, because the parser itself is the one processing those. Roslyn 解析器已经跳过了 #if/#else 中不活动的代码,因为解析器本身就是处理这些代码的那个。 The skipped text is still represented as trivia inside of the tree which is data attached to a syntax node, but there aren't regular syntax nodes at all.跳过的文本仍然表示为树内的琐事,它是附加到语法节点的数据,但根本没有常规语法节点。 So your analyzer can't stumble on a syntax node that represents code inside of a disabled #if, because it doesn't exist in the first place.因此,您的分析器不会偶然发现表示禁用#if 内代码的语法节点,因为它首先不存在。

For #regions on the other hand those aren't special;另一方面,对于#regions,这些并不特别; the syntax tree contains additional trivia where those are;语法树包含额外的琐事; you can walk those and find them if you want to exclude code inside of that.如果您想排除其中的代码,您可以步行并找到它们。 You'd have to be a bit more specific for your needs if you want further details.如果您想了解更多详细信息,则必须更具体地满足您的需求。

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

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