简体   繁体   中英

C# source generators: How to debug compiler errors in the generated code?

I am experimenting with C# source generators . I have spent about a day on it, and I find it a very frustrating and painful experience. IntelliSense is extremely unreliable. It occasionally works, but most often it does not, and I have not been able to figure out any system to it. (Restarting Visual Studio does not help.)

But more fundamentally, I have great trouble debugging errors in the generated code. When I make a mistake in the template in the source generator and try to compile, I might get errors like "Method must have a return type" in the generated file. But when I double-click on the error, it doesn't take me to the generated code. That makes it extremely hard to see what is wrong with it.

Is there a trick to it? Is there any way to inspect the generated code when it fails to compile? And more generally, what governs when the generated code is available for IntelliSense and when it is not ?

I am using Visual Studio Professional 2022 version 17.1.6 and ReSharper 2022.1.

Thanks in advance!

I have found a partial solution to my problem.

First, do not use the ReSharper builder in Visual Studio when working with source generators. It does not give proper error messages. Instead, run do.net build from a command line. You'll get much better error messages that way.

In fact, part of my problem may be due to bugs or limitations in ReSharper (though I have not investigated this, so that is pure speculation).

Second, you can test the innards of your source generator without running the source generation at compile time .

  1. Refactor your source generator and extract a helper class (we can call it SourceGeneratorHelper.cs ) that takes your input (eg XML) and produces output (eg a StringBuilder ).
  2. Make a separate C# test project SourceGeneratorHelperTest.csproj for testing the class SourceGeneratorHelper.cs . In this project, reference your source generator project as if it were a regular project - ie, DO NOT USE OutputItemType="Analyzer" in your project reference.
  3. Now you can unit test the innards of your source generator. You can also dump the generated C# code to a file and inspect it.

Moreover, as NightOwl888 pointed out, I can add this to the referencing project in order to get it to spit out the generated files to disk ( as explained in this article ):

<PropertyGroup>
    <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>

I have not solved the IntelliSense problem, but now I can at least endure working with this generator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM