-
Notifications
You must be signed in to change notification settings - Fork 10k
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
Add source generator to emit public Program class definition #58199
Open
captainsafia
wants to merge
3
commits into
main
Choose a base branch
from
safia/public-program-gen
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
18 changes: 18 additions & 0 deletions
18
...AspNetCoreAnalyzers/src/SourceGenerators/Microsoft.AspNetCore.App.SourceGenerators.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
<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> |
44 changes: 44 additions & 0 deletions
44
src/Framework/AspNetCoreAnalyzers/src/SourceGenerators/PublicTopLevelProgramGenerator.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
// 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 | ||
{ | ||
private const string PublicPartialProgramClassSource = """ | ||
// <auto-generated /> | ||
public partial class Program { } | ||
"""; | ||
|
||
public void Initialize(IncrementalGeneratorInitializationContext context) | ||
{ | ||
var internalGeneratedProgramClass = context.CompilationProvider | ||
// Get the entry point associated with the compilation, this maps to the Main method definition | ||
.Select((compilation, cancellationToken) => compilation.GetEntryPoint(cancellationToken)) | ||
// Get the containing symbol of the entry point, this maps to the Program class | ||
.Select((symbol, _) => symbol?.ContainingSymbol) | ||
// If the program class is already public, we don't need to generate anything. | ||
.Select((symbol, _) => symbol?.DeclaredAccessibility == Accessibility.Public ? null : symbol) | ||
// If the discovered `Program` type is not a class then its not | ||
// generated and has been defined in source, so we can skip it | ||
.Select((symbol, _) => symbol is INamedTypeSymbol { TypeKind: TypeKind.Class } ? symbol : null) | ||
// If there are multiple partial declarations, then do nothing since we don't want | ||
// to trample on visibility explicitly set by the user | ||
.Select((symbol, _) => symbol is { DeclaringSyntaxReferences: { Length: 1 } declaringSyntaxReferences } ? declaringSyntaxReferences.Single() : null) | ||
// If the `Program` class is already declared in user code, we don't need to generate anything. | ||
.Select((declaringSyntaxReference, cancellationToken) => declaringSyntaxReference?.GetSyntax(cancellationToken) is ClassDeclarationSyntax ? null : declaringSyntaxReference); | ||
|
||
context.RegisterSourceOutput(internalGeneratedProgramClass, (context, result) => | ||
{ | ||
if (result is not null) | ||
{ | ||
context.AddSource("PublicTopLevelProgram.Generated.g.cs", PublicPartialProgramClassSource); | ||
} | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
134 changes: 134 additions & 0 deletions
134
...ramework/AspNetCoreAnalyzers/test/SourceGenerators/PublicTopLevelProgramGeneratorTests.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.g.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); | ||
} | ||
} |
48 changes: 48 additions & 0 deletions
48
src/Framework/AspNetCoreAnalyzers/test/Verifiers/CSharpSourceGeneratorVerifier.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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
RequestDelegateGenerator
but let me know if I missed something.