Joel
Joel

Reputation: 352

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. For instance, if I have code that is excluded with #if/#else, I would like my analyzer to not work on that code. Similarly, I would like #beginregion/#endregion and the like to not show up for my analyzer.

Is there a way to get a post-preprocessed compilation or syntax tree from 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:

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

Upvotes: 0

Views: 312

Answers (1)

Jason Malinowski
Jason Malinowski

Reputation: 19021

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

For #regions on the other hand those aren't special; 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.

Upvotes: 1

Related Questions