dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
18.88k stars 4.01k forks source link

Source generated syntax trees should report IsGenerated #49326

Open chsienki opened 3 years ago

chsienki commented 3 years ago

We should add GeneratedKind.SourceGenerator and have any syntax trees added by a generator return this value.

We should also update the original bool version of the property to report true for this value.

mavasani commented 3 years ago

@chsienki Should we close out https://github.com/dotnet/roslyn/issues/48480?

ericstj commented 3 years ago

Will this impact the way the compiler raises diagnostics for generated code? I can imagine there are a set of compiler checks we'd want to be ignored for generated code to simplify code-generators (eg: style analyzers) where there are others that we would want to be honored (obsolete, nullable annotations). cc @AaronRobinsonMSFT

jmarolf commented 3 years ago

Will this impact the way the compiler raises diagnostics for generated code?

Each analyzer can choose whether it needs to analyze generated code or not via the ConfigureGeneratedCodeAnalysis method.

https://github.com/dotnet/roslyn/blob/f52afd963b21a472d78d5fe17fec8e65fbd10f74/src/Compilers/Core/Portable/DiagnosticAnalyzer/DiagnosticAnalysisContext.cs#L214-L219

Today all analyzers that come with the SDK that are required for code correctness (for example security analyzers) look at generated code.

sharwell commented 3 years ago

💭 It seems desirable to continue requiring source generators to emit the // <auto-generated/> header at the top of the file.

eerhardt commented 3 years ago

Looking at https://github.com/dotnet/runtime/pull/53275, the change is appending the .g suffix to the file to indicate this is a generated file.

How many different ways are source generators supposed to mark their files as "generated"? So far I see:

  1. emitting // <auto-generated/> header
  2. naming the file .g.cs
  3. calling ConfigureGeneratedCodeAnalysis
  4. any more?

What are the recommendations for dotnet/runtime source generators should do to mark their code as "generated"?

AaronRobinsonMSFT commented 3 years ago

@sharwell Is the following the appropriate way to add the comment?

SyntaxFactory.Comment("<auto-generated/>").ToString()
sharwell commented 3 years ago

@AaronRobinsonMSFT SyntaxFactory.Comment would be more for cases where you are generating a SyntaxTree. For cases where you are generating a string, rather than use ToString() like that line you could just add "// <auto-generated/>" directly.

333fred commented 2 years ago

@chsienki can you fill out the API proposal template for this?

chsienki commented 2 years ago

Added https://github.com/dotnet/roslyn/issues/56810 to track the API