Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Syntax Tree from SymbolAnalysisContext

Tags:

c#

roslyn

I need to access the syntax tree (the complete source file text) from a given SymbolAnalysisContext. I found that I can call context.Compilation.SyntaxTrees but which one to pick from these? Is there another way?

like image 644
David Avatar asked Feb 20 '26 00:02

David


1 Answers

A symbol can be defined in one or more SyntaxTrees, or in Metadata (by reference). You can get all of them via ISymbol.Locations, which:

Gets the locations where the symbol was originally defined, either in source or metadata. Some symbols (for example, partial classes) may be defined in more than one location.

If you're only interrested in the ones defined in your sources, you can do something like this:

var syntaxTrees = from x in context.Symbol.Locations
                  where x.IsInSource
                  select x.SourceTree;
like image 118
m0sa Avatar answered Feb 22 '26 15:02

m0sa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!