Recommended reading to better understand source generators, Roslyn Source Generators Cookbook.
- DO generate code that looks as if a developer would write it manually.
- DO emit strings rather than using the Roslyn Syntax API for better performance.
- DO use consistent indentation and formatting in generated code.
- DO generators should use the
IIncrementalGenerator
interface. - DO set
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
in the source generator project and then don't use any of the banned APIs it lists. - DO set
<IsRoslynComponent>true</IsRoslynComponent>
in the source generator project to enable debugging support in Visual Studio. - DO disable the following Roslyn warning,
RS2008
, in the source generator project (that is,<NoWarn>$(NoWarn);RS2008</NoWarn>
). The reported issue is handled differently in the runtime repo. - DO emit diagnostics from a separate analyzer. The analyzer and source generator can be in the same assembly.
- DO cache intermediate results to avoid redundant computation.
- DO consider the impact on build time and optimize accordingly.
- DO have separate projects for testing the generator and testing the code generated by the generator.
- DO use the Roslyn Testing SDK to test the generator (and any corresponding analyzers).
- DON'T use the Roslyn Syntax API for emitting source code.
- DON'T perform expensive operations during the generation process unless absolutely necessary.
- DON'T emit code that introduces runtime dependencies not explicitly referenced by the project.
- DON'T emit code that would trigger compiler warnings in normal usage scenarios.
- DON'T emit diagnostics from the generator itself, emit them from an analyzer.