-
Notifications
You must be signed in to change notification settings - Fork 10.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add source generator to emit public Program class definition (#58199)
* Add source generator to emit public Program class definition * Add more checks and test cases * Use GetEntrypoint API and transformations for better caching * Address feedback
- Loading branch information
1 parent
886f6ae
commit 15f0a89
Showing
10 changed files
with
273 additions
and
0 deletions.
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(static (compilation, cancellationToken) => compilation.GetEntryPoint(cancellationToken)) | ||
// Get the containing symbol of the entry point, this maps to the Program class | ||
.Select(static (symbol, _) => symbol?.ContainingSymbol) | ||
// If the program class is already public, we don't need to generate anything. | ||
.Select(static (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(static (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(static (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(static (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); | ||
} | ||
} |
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