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)-syntaxTreedoesn'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)-filePathdoesn'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?
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.