-
Notifications
You must be signed in to change notification settings - Fork 481
Description
When writing source generators, many users choose to generate the code using the syntax APIs because they find this approach useful for their scenario, even though AddSource only takes a SourceText, not syntax nodes. To get the SourceText from the syntax, the best way is to use AddSource(syntaxNode.GetText(Encoding.UTF8)) - this is more efficient than using syntaxNode.ToString() or syntaxNode.ToFullString() (which is the naive approach that most people would use) because it avoids the string allocation, which could be arbitrarily large. It would be helpful to have this documented in some of the source generator walkthroughs as a recommended/best practice for getting the text from a syntax in case the users choose to generate the code using the syntax APIs, to guide users to do the right thing.
Extracted from dotnet/roslyn#49082 (comment)
The best way to get a
SourceTextfrom aCompilationUnit, or anySyntaxNodein general, is to usesyntaxNode.GetText(Encoding.UTF8)- that way, no huge string should be allocated.
IMO, it would be a good idea to mention this somewhere in the docs for source generators, so that people do the right thing, as opposed to calling
syntaxNode.ToString().
...
Also, getting a
SourceTextfrom the syntax is already easy to do in a pretty good way, by usingsyntaxNode.GetText(Encoding.UTF8). This just needs to be documented so that source generator authors know that this is the recommended practice for getting the text from a syntax, in case they're using the syntax APIs to generate the source.