-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Add source generator to emit public Program class definition #58199
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
7163cb0
707bd27
3bc89cd
7477d54
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
captainsafia marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| <PropertyGroup> | ||
| <TargetFramework>netstandard2.0</TargetFramework> | ||
| <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules> | ||
| <IsPackable>false</IsPackable> | ||
| <IsAnalyzersProject>true</IsAnalyzersProject> | ||
| <AddPublicApiAnalyzers>false</AddPublicApiAnalyzers> | ||
| <Nullable>enable</Nullable> | ||
| <WarnOnNullable>true</WarnOnNullable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <Reference Include="Microsoft.CodeAnalysis.CSharp" PrivateAssets="All" /> | ||
| <Reference Include="Microsoft.CodeAnalysis.Common" PrivateAssets="All" /> | ||
| <Reference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" PrivateAssets="All" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Linq; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
|
|
||
| namespace Microsoft.AspNetCore.SourceGenerators; | ||
|
|
||
| [Generator] | ||
| public class PublicProgramSourceGenerator : IIncrementalGenerator | ||
| { | ||
| public void Initialize(IncrementalGeneratorInitializationContext context) | ||
| { | ||
| var internalGeneratedProgramClass = context.CompilationProvider.Select((compilation, cancellationToken) => | ||
| { | ||
| var program = compilation.GetTypeByMetadataName("Program"); | ||
|
||
| // If the program class is already public, we don't need to generate anything. | ||
| if (program is null || program.DeclaredAccessibility == Accessibility.Public) | ||
amcasey marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| return null; | ||
| } | ||
| // If the discovered `Program` type is an interface, struct or generic type then its not | ||
| // generated and has been defined in source, so we can skip it | ||
| if (program.TypeKind == TypeKind.Struct || program.TypeKind == TypeKind.Interface || program.IsGenericType) | ||
|
||
| { | ||
| return null; | ||
| } | ||
| // If there are multiple partial declarations, then do nothing since we don't want | ||
| // to trample on visibility explicitly set by the user | ||
| if (program.DeclaringSyntaxReferences.Length > 1) | ||
| { | ||
| return null; | ||
| } | ||
| // If the `Program` class is already declared in user code, we don't need to generate anything. | ||
| if (program.DeclaringSyntaxReferences.SingleOrDefault()?.GetSyntax(cancellationToken) is ClassDeclarationSyntax) | ||
amcasey marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| return null; | ||
| } | ||
| return program; | ||
| }); | ||
|
|
||
| context.RegisterSourceOutput(internalGeneratedProgramClass, (context, symbol) => | ||
| { | ||
| if (symbol is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var output = """ | ||
| // <auto-generated /> | ||
| public partial class Program { } | ||
| """; | ||
| context.AddSource("PublicTopLevelProgram.Generated.cs", output); | ||
| }); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using VerifyCS = Microsoft.AspNetCore.Analyzers.Verifiers.CSharpSourceGeneratorVerifier<Microsoft.AspNetCore.SourceGenerators.PublicProgramSourceGenerator>; | ||
|
|
||
| namespace Microsoft.AspNetCore.SourceGenerators.Tests; | ||
|
|
||
| public class PublicTopLevelProgramGeneratorTests | ||
| { | ||
| [Fact] | ||
| public async Task GeneratesSource_ProgramWithTopLevelStatements() | ||
| { | ||
| var source = """ | ||
| using Microsoft.AspNetCore.Builder; | ||
|
|
||
| var app = WebApplication.Create(); | ||
|
|
||
| app.MapGet("/", () => "Hello, World!"); | ||
|
|
||
| app.Run(); | ||
| """; | ||
|
|
||
| var expected = """ | ||
| // <auto-generated /> | ||
| public partial class Program { } | ||
| """; | ||
|
|
||
| await VerifyCS.VerifyAsync(source, "PublicTopLevelProgram.Generated.cs", expected); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DoesNotGeneratesSource_IfProgramIsAlreadyPublic() | ||
| { | ||
| var source = """ | ||
| using Microsoft.AspNetCore.Builder; | ||
|
|
||
| var app = WebApplication.Create(); | ||
|
|
||
| app.MapGet("/", () => "Hello, World!"); | ||
|
|
||
| app.Run(); | ||
|
|
||
| public partial class Program { } | ||
| """; | ||
|
|
||
| await VerifyCS.VerifyAsync(source); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DoesNotGeneratesSource_IfProgramDeclaresExplicitInternalAccess() | ||
| { | ||
| var source = """ | ||
| using Microsoft.AspNetCore.Builder; | ||
|
|
||
| var app = WebApplication.Create(); | ||
|
|
||
| app.MapGet("/", () => "Hello, World!"); | ||
|
|
||
| app.Run(); | ||
|
|
||
| internal partial class Program { } | ||
| """; | ||
|
|
||
| await VerifyCS.VerifyAsync(source); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DoesNotGeneratorSource_ExplicitPublicProgramClass() | ||
| { | ||
| var source = """ | ||
| using Microsoft.AspNetCore.Builder; | ||
|
|
||
| public class Program | ||
| { | ||
| public static void Main() | ||
| { | ||
| var app = WebApplication.Create(); | ||
|
|
||
| app.MapGet("/", () => "Hello, World!"); | ||
|
|
||
| app.Run(); | ||
| } | ||
| } | ||
| """; | ||
|
|
||
| await VerifyCS.VerifyAsync(source); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DoesNotGeneratorSource_ExplicitInternalProgramClass() | ||
| { | ||
| var source = """ | ||
| using Microsoft.AspNetCore.Builder; | ||
|
|
||
| internal class Program | ||
| { | ||
| public static void Main() | ||
| { | ||
| var app = WebApplication.Create(); | ||
|
|
||
| app.MapGet("/", () => "Hello, World!"); | ||
|
|
||
| app.Run(); | ||
| } | ||
| } | ||
| """; | ||
|
|
||
| await VerifyCS.VerifyAsync(source); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("interface")] | ||
| [InlineData("struct")] | ||
| public async Task DoesNotGeneratorSource_ExplicitInternalProgramType(string type) | ||
| { | ||
| var source = $$""" | ||
| using Microsoft.AspNetCore.Builder; | ||
|
|
||
| internal {{type}} Program | ||
| { | ||
| public static void Main(string[] args) | ||
| { | ||
| var app = WebApplication.Create(); | ||
|
|
||
| app.MapGet("/", () => "Hello, World!"); | ||
|
|
||
| app.Run(); | ||
| } | ||
| } | ||
| """; | ||
|
|
||
| await VerifyCS.VerifyAsync(source); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Text; | ||
| using Microsoft.AspNetCore.Analyzers.WebApplicationBuilder; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp.Testing; | ||
| using Microsoft.CodeAnalysis.Testing; | ||
| using Microsoft.CodeAnalysis.Testing.Verifiers; | ||
| using Microsoft.CodeAnalysis.Text; | ||
|
|
||
| namespace Microsoft.AspNetCore.Analyzers.Verifiers; | ||
|
|
||
| public static partial class CSharpSourceGeneratorVerifier<TSourceGenerator> | ||
| where TSourceGenerator : IIncrementalGenerator, new() | ||
| { | ||
| public static async Task VerifyAsync(string source, string generatedFileName, string generatedSource) | ||
| { | ||
| var test = new CSharpSourceGeneratorTest<TSourceGenerator, DefaultVerifier> | ||
| { | ||
| TestState = | ||
| { | ||
| Sources = { source.ReplaceLineEndings() }, | ||
| OutputKind = OutputKind.ConsoleApplication, | ||
| GeneratedSources = | ||
| { | ||
| (typeof(TSourceGenerator), generatedFileName, SourceText.From(generatedSource, Encoding.UTF8)) | ||
| }, | ||
| ReferenceAssemblies = CSharpAnalyzerVerifier<WebApplicationBuilderAnalyzer>.GetReferenceAssemblies() | ||
| }, | ||
| }; | ||
| await test.RunAsync(CancellationToken.None); | ||
| } | ||
|
|
||
| public static async Task VerifyAsync(string source) | ||
| { | ||
| var test = new CSharpSourceGeneratorTest<TSourceGenerator, DefaultVerifier> | ||
| { | ||
| TestState = | ||
| { | ||
| Sources = { source.ReplaceLineEndings() }, | ||
| OutputKind = OutputKind.ConsoleApplication, | ||
| ReferenceAssemblies = CSharpAnalyzerVerifier<WebApplicationBuilderAnalyzer>.GetReferenceAssemblies() | ||
| }, | ||
| }; | ||
| await test.RunAsync(CancellationToken.None); | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@wtgodbe Can you sanity check my packaging changes here? I think it's correct given what we had to do in .NEt 8 for the
RequestDelegateGeneratorbut let me know if I missed something.