antlr / antlr4

ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files.
http://antlr.org
BSD 3-Clause "New" or "Revised" License
16.68k stars 3.23k forks source link

Mark all generated C# classes with [GeneratedCode] attribute #4624

Closed martinskuta closed 1 month ago

martinskuta commented 1 month ago

Hi,

we use ANTLR to generate a C# parser for our grammar and we run for each build static code analysis and for obvious reasons we exclude generated code, including the generated ANTLR classes. For ANTLR generated code we have to manually exclude the generated namespace from the inspection, because not all of the generated classes are marked with [GeneratedCode] attribute, none of the public nested classes are, only the top level parent ones for Parser/Visitor are marked as generated.

We are using NDepend and JetBrains InspectCode to analyse the code. With the changes to the CSharp target template I propose in this PR no further work has to be done to exclude ANTLR generated code from the inspection as both tools understand that attribute, as do probably any other C# static analysis tools.

sharwell commented 1 month ago

📝 This should not be necessary since the entire file is marked as generated code: https://github.com/antlr/antlr4/blob/5a68af0109d911e3bcd2e2c0eaaaecf25dbee66c/tool/resources/org/antlr/v4/tool/templates/codegen/CSharp/CSharp.stg#L244-L252

If a tool is failing to account for this designator at the top of the file, it would be considered a bug in that tool that should be corrected.

Even the C# compiler recognizes this: https://github.com/dotnet/roslyn/blob/d89c824648207390f5be355a782048812ba5f91e/src/Compilers/Core/Portable/SourceGeneration/GeneratedCodeUtilities.cs#L16

martinskuta commented 1 month ago

You are right. I didn't think about it this way, but makes sense that a symbol that is inside of a containing symbol that is generated should be also considered generated. My thinking was that if you create a partial class then you could create a nested class that would not be considered auto generated, but in that case the symbol would be the partial class without the attribute I assume.

Thx for the reply, I will report it to NDepend.