Skip to content

Commit

Permalink
Provide analyzer for removing unneeded public partial class Program (#…
Browse files Browse the repository at this point in the history
…58482)

* Provide analyzer for removing unneeded public partial class Program

* Update tests and fix async call

* Address feedback

* Add test for public partial class with members

* Reorganize checks and add tests
  • Loading branch information
captainsafia committed Feb 11, 2025
1 parent a74dc5a commit 0853101
Show file tree
Hide file tree
Showing 5 changed files with 405 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -223,4 +223,14 @@ internal static class DiagnosticDescriptors
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
helpLinkUri: "https://aka.ms/aspnet/analyzers");

internal static readonly DiagnosticDescriptor PublicPartialProgramClassNotRequired = new(
"ASP0027",
new LocalizableResourceString(nameof(Resources.Analyzer_PublicPartialProgramClass_Title), Resources.ResourceManager, typeof(Resources)),
new LocalizableResourceString(nameof(Resources.Analyzer_PublicPartialProgramClass_Message), Resources.ResourceManager, typeof(Resources)),
"Usage",
DiagnosticSeverity.Info,
isEnabledByDefault: true,
helpLinkUri: "https://aka.ms/aspnet/analyzers",
customTags: WellKnownDiagnosticTags.Unnecessary);
}
62 changes: 34 additions & 28 deletions src/Framework/AspNetCoreAnalyzers/src/Analyzers/Resources.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -321,4 +321,10 @@
<data name="Analyzer_OverriddenAuthorizeAttribute_Title" xml:space="preserve">
<value>[Authorize] overridden by [AllowAnonymous] from farther away</value>
</data>
</root>
<data name="Analyzer_PublicPartialProgramClass_Message" xml:space="preserve">
<value>Using public partial class Program { } to make the generated Program class public is no longer required in ASP.NET Core apps. See https://aka.ms/aspnetcore-warnings/ASP0027 for more details.</value>
</data>
<data name="Analyzer_PublicPartialProgramClass_Title" xml:space="preserve">
<value>Unnecessary public Program class declaration</value>
</data>
</root>
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;

namespace Microsoft.AspNetCore.Analyzers;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class PublicPartialProgramClassAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DiagnosticDescriptors.PublicPartialProgramClassNotRequired);

public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(context =>
{
var syntaxNode = context.Node;
if (IsPublicPartialClassProgram(syntaxNode))
{
context.ReportDiagnostic(Diagnostic.Create(
DiagnosticDescriptors.PublicPartialProgramClassNotRequired,
syntaxNode.GetLocation()));
}
}, SyntaxKind.ClassDeclaration);
}

private static bool IsPublicPartialClassProgram(SyntaxNode syntaxNode)
{
return syntaxNode is ClassDeclarationSyntax { Modifiers: { } modifiers } classDeclaration
&& classDeclaration.Parent is CompilationUnitSyntax parentNode
&& classDeclaration is { Identifier.ValueText: "Program" }
&& (classDeclaration.Members == null || classDeclaration.Members.Count == 0) // Skip non-empty declarations
&& modifiers is { Count: > 1 }
&& modifiers.Any(SyntaxKind.PublicKeyword)
&& modifiers.Any(SyntaxKind.PartialKeyword)
&& parentNode.DescendantNodes().Count() > 1;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Immutable;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Analyzers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;

namespace Microsoft.AspNetCore.Fixers;

[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
public class PublicPartialProgramClassFixer : CodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds { get; } = [DiagnosticDescriptors.PublicPartialProgramClassNotRequired.Id];

public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;

public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(
CodeAction.Create("Remove unnecessary public partial class Program declaration",
async cancellationToken =>
{
var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken).ConfigureAwait(false);
var root = await context.Document.GetSyntaxRootAsync(cancellationToken);
if (root is null)
{
return context.Document;
}

var classDeclaration = root.FindNode(diagnostic.Location.SourceSpan)
.FirstAncestorOrSelf<ClassDeclarationSyntax>();
if (classDeclaration is null)
{
return context.Document;
}
editor.RemoveNode(classDeclaration, SyntaxRemoveOptions.KeepExteriorTrivia);
return editor.GetChangedDocument();
},
equivalenceKey: DiagnosticDescriptors.PublicPartialProgramClassNotRequired.Id),
diagnostic);
}

return Task.CompletedTask;
}
}
Loading

0 comments on commit 0853101

Please sign in to comment.