0

I have a C# source generator that can come across configuration issues in the data it reads, these are emitted as compile errors. Currently this looks something like this:

DiagnosticDescriptor errorType = new DiagnosticDescriptor(...);
Location? fileLocation = null;

context.ReportDiagnostic(Diagnostic.Create(errorType, fileLocation, DiagnosticSeverity.Error));

This correctly throws up an error but doesn't point to a useful location (when clicking or otherwise inspecting the error). I know the area in the generated text that the error is present in that I want to highlight but I'm not able to show an error for this because at this point the new source code is a string.

The Create method for Location doesn't seem to help for dynamic classes:

  • Create(SyntaxTree syntaxTree, TextSpan textSpan) - syntaxTree doesn't exist as the source generated text doesn't get parsed until the source generator has finished running.
  • Create(string filePath, TextSpan textSpan, LineositionSpan lineSpan) - filePath doesn't exist because this is a generated file and not something found on disk (I know they are written out at some point but we can't get that data as far as I know)

How do I add Location hints to source generation errors?

1
  • if i remember correctly, you have to wirte an separate normal analyzer for that. but you should be able to place the analyzer in the same project as the generator and to share code between them Commented Nov 4, 2022 at 0:06

1 Answer 1

1

The expectation here is you should not be providing diagnostics on your generated code, but rather diagnostics for the code you read in while doing the generation in the first place. The assumption is any errors in your generated code would more likely indicate a bug in the generator rather than the original code.

Sign up to request clarification or add additional context in comments.

2 Comments

" but rather diagnostics for the code you read in while doing the generation in the first place" oh cool and how would that work?
You can report diagnostics in the generator against whatever code you used as a source of generation. i.e. something wrong with an attribute? Report against that attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.