Search code examples
c#optimizationbuildsourcegenerators

How do C#'s IIncrementalGenerators know if the compiler is doing an optimised build?


I want to write an IIncrementalGenerator which has slightly different behaviour depending on if the compiler is doing a release or debug build. I know you in the CsProj you have the Optimize flag which controls some optimisations.

I want to check this Optimize flag during the Initialize call so that my generated code can perform more checks and generate more aggressive code which requires a lot more checks of the assembly. This isn't needed for debug builds as a simplified version of this can be generated which isn't as precise.

How do I get the state of Optimise or debug/release configurations in the Initialize call?


Solution

  • You can't change the generators steps based on the type of compile as there is no guarantee that the compiler instance will be restarted during the project configuration switch. The side effect of this is that the old project configuration will still be loaded into Roslyn.

    Instead you have to check these inside the build stages in the generator. If you get the CompilationProvider the setting can be found in the Compilation.Options.OptimizationLevel

    • CompilationLevel.Debug for unoptimized
    • CompilationLevel.Release for optimised

    Then you can respond accordingly in the generator stage