0

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);

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I feel a bit obtuse for not seeing it this way immediately, but it makes a ton of sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.