Skip to content

Source generator tweaks #1178

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

Merged
merged 2 commits into from
Sep 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions JsonApiDotNetCore.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ JsonApiDotNetCore.ArgumentGuard.NotNull($EXPR$, $NAME$);</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=EnforceUsingStatementBraces/@EntryIndexedValue">WARNING</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=EnforceWhileStatementBraces/@EntryIndexedValue">WARNING</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=EventNeverSubscribedTo_002ELocal/@EntryIndexedValue">WARNING</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=LambdaExpressionMustBeStatic/@EntryIndexedValue">WARNING</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=LocalizableElement/@EntryIndexedValue">DO_NOT_SHOW</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=LoopCanBePartlyConvertedToQuery/@EntryIndexedValue">HINT</s:String>
<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=MemberCanBeInternal/@EntryIndexedValue">SUGGESTION</s:String>
Expand Down
236 changes: 115 additions & 121 deletions src/JsonApiDotNetCore.SourceGenerators/ControllerSourceGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Humanizer;
using Microsoft.CodeAnalysis;
Expand All @@ -11,166 +8,163 @@

#pragma warning disable RS2008 // Enable analyzer release tracking

namespace JsonApiDotNetCore.SourceGenerators
namespace JsonApiDotNetCore.SourceGenerators;
// To debug in Visual Studio (requires v17.2 or higher):
// - Set JsonApiDotNetCore.SourceGenerators as startup project
// - Add a breakpoint at the start of the Initialize or Execute method
// - Optional: change targetProject in Properties\launchSettings.json
// - Press F5

[Generator(LanguageNames.CSharp)]
public sealed class ControllerSourceGenerator : ISourceGenerator
{
// To debug in Visual Studio (requires v17.2 or higher):
// - Set JsonApiDotNetCore.SourceGenerators as startup project
// - Add a breakpoint at the start of the Initialize or Execute method
// - Optional: change targetProject in Properties\launchSettings.json
// - Press F5

[Generator(LanguageNames.CSharp)]
public sealed class ControllerSourceGenerator : ISourceGenerator
private const string Category = "JsonApiDotNetCore";

private static readonly DiagnosticDescriptor MissingInterfaceWarning = new("JADNC001", "Resource type does not implement IIdentifiable<TId>",
"Type '{0}' must implement IIdentifiable<TId> when using ResourceAttribute to auto-generate ASP.NET controllers", Category, DiagnosticSeverity.Warning,
true);

private static readonly DiagnosticDescriptor MissingIndentInTableError = new("JADNC900", "Internal error: Insufficient entries in IndentTable",
"Internal error: Missing entry in IndentTable for depth {0}", Category, DiagnosticSeverity.Warning, true);

// PERF: Heap-allocate the delegate only once, instead of per compilation.
private static readonly SyntaxReceiverCreator CreateSyntaxReceiver = static () => new TypeWithAttributeSyntaxReceiver();

public void Initialize(GeneratorInitializationContext context)
{
private const string Category = "JsonApiDotNetCore";
context.RegisterForSyntaxNotifications(CreateSyntaxReceiver);
}

private static readonly DiagnosticDescriptor MissingInterfaceWarning = new DiagnosticDescriptor("JADNC001",
"Resource type does not implement IIdentifiable<TId>",
"Type '{0}' must implement IIdentifiable<TId> when using ResourceAttribute to auto-generate ASP.NET controllers", Category,
DiagnosticSeverity.Warning, true);
public void Execute(GeneratorExecutionContext context)
{
var receiver = (TypeWithAttributeSyntaxReceiver?)context.SyntaxReceiver;

private static readonly DiagnosticDescriptor MissingIndentInTableError = new DiagnosticDescriptor("JADNC900",
"Internal error: Insufficient entries in IndentTable", "Internal error: Missing entry in IndentTable for depth {0}", Category,
DiagnosticSeverity.Warning, true);
if (receiver == null)
{
return;
}

// PERF: Heap-allocate the delegate only once, instead of per compilation.
private static readonly SyntaxReceiverCreator CreateSyntaxReceiver = () => new TypeWithAttributeSyntaxReceiver();
INamedTypeSymbol? resourceAttributeType = context.Compilation.GetTypeByMetadataName("JsonApiDotNetCore.Resources.Annotations.ResourceAttribute");
INamedTypeSymbol? identifiableOpenInterface = context.Compilation.GetTypeByMetadataName("JsonApiDotNetCore.Resources.IIdentifiable`1");
INamedTypeSymbol? loggerFactoryInterface = context.Compilation.GetTypeByMetadataName("Microsoft.Extensions.Logging.ILoggerFactory");

public void Initialize(GeneratorInitializationContext context)
if (resourceAttributeType == null || identifiableOpenInterface == null || loggerFactoryInterface == null)
{
context.RegisterForSyntaxNotifications(CreateSyntaxReceiver);
return;
}

public void Execute(GeneratorExecutionContext context)
var controllerNamesInUse = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var writer = new SourceCodeWriter(context, MissingIndentInTableError);

foreach (TypeDeclarationSyntax? typeDeclarationSyntax in receiver.TypeDeclarations)
{
var receiver = (TypeWithAttributeSyntaxReceiver)context.SyntaxReceiver;
// PERF: Note that our code runs on every keystroke in the IDE, which makes it critical to provide near-realtime performance.
// This means keeping an eye on memory allocations and bailing out early when compilations are cancelled while the user is still typing.
context.CancellationToken.ThrowIfCancellationRequested();

SemanticModel semanticModel = context.Compilation.GetSemanticModel(typeDeclarationSyntax.SyntaxTree);
INamedTypeSymbol? resourceType = semanticModel.GetDeclaredSymbol(typeDeclarationSyntax, context.CancellationToken);

if (receiver == null)
if (resourceType == null)
{
return;
continue;
}

INamedTypeSymbol resourceAttributeType = context.Compilation.GetTypeByMetadataName("JsonApiDotNetCore.Resources.Annotations.ResourceAttribute");
INamedTypeSymbol identifiableOpenInterface = context.Compilation.GetTypeByMetadataName("JsonApiDotNetCore.Resources.IIdentifiable`1");
INamedTypeSymbol loggerFactoryInterface = context.Compilation.GetTypeByMetadataName("Microsoft.Extensions.Logging.ILoggerFactory");
AttributeData? resourceAttributeData = FirstOrDefault(resourceType.GetAttributes(), resourceAttributeType,
static (data, type) => SymbolEqualityComparer.Default.Equals(data.AttributeClass, type));

if (resourceAttributeType == null || identifiableOpenInterface == null || loggerFactoryInterface == null)
if (resourceAttributeData == null)
{
return;
continue;
}

var controllerNamesInUse = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var writer = new SourceCodeWriter(context, MissingIndentInTableError);
TypedConstant endpointsArgument =
resourceAttributeData.NamedArguments.FirstOrDefault(static pair => pair.Key == "GenerateControllerEndpoints").Value;

foreach (TypeDeclarationSyntax typeDeclarationSyntax in receiver.TypeDeclarations)
if (endpointsArgument.Value != null && (JsonApiEndpointsCopy)endpointsArgument.Value == JsonApiEndpointsCopy.None)
{
// PERF: Note that our code runs on every keystroke in the IDE, which makes it critical to provide near-realtime performance.
// This means keeping an eye on memory allocations and bailing out early when compilations are cancelled while the user is still typing.
context.CancellationToken.ThrowIfCancellationRequested();

SemanticModel semanticModel = context.Compilation.GetSemanticModel(typeDeclarationSyntax.SyntaxTree);
INamedTypeSymbol resourceType = semanticModel.GetDeclaredSymbol(typeDeclarationSyntax, context.CancellationToken);

if (resourceType == null)
{
continue;
}

AttributeData resourceAttributeData = FirstOrDefault(resourceType.GetAttributes(), resourceAttributeType,
(data, type) => SymbolEqualityComparer.Default.Equals(data.AttributeClass, type));

if (resourceAttributeData == null)
{
continue;
}

TypedConstant endpointsArgument = resourceAttributeData.NamedArguments.FirstOrDefault(pair => pair.Key == "GenerateControllerEndpoints").Value;

if (endpointsArgument.Value != null && (JsonApiEndpointsCopy)endpointsArgument.Value == JsonApiEndpointsCopy.None)
{
continue;
}

TypedConstant controllerNamespaceArgument =
resourceAttributeData.NamedArguments.FirstOrDefault(pair => pair.Key == "ControllerNamespace").Value;

string controllerNamespace = GetControllerNamespace(controllerNamespaceArgument, resourceType);

INamedTypeSymbol identifiableClosedInterface = FirstOrDefault(resourceType.AllInterfaces, identifiableOpenInterface,
(@interface, openInterface) => @interface.IsGenericType &&
SymbolEqualityComparer.Default.Equals(@interface.ConstructedFrom, openInterface));
continue;
}

if (identifiableClosedInterface == null)
{
var diagnostic = Diagnostic.Create(MissingInterfaceWarning, typeDeclarationSyntax.GetLocation(), resourceType.Name);
context.ReportDiagnostic(diagnostic);
continue;
}
TypedConstant controllerNamespaceArgument =
resourceAttributeData.NamedArguments.FirstOrDefault(static pair => pair.Key == "ControllerNamespace").Value;

ITypeSymbol idType = identifiableClosedInterface.TypeArguments[0];
string controllerName = $"{resourceType.Name.Pluralize()}Controller";
JsonApiEndpointsCopy endpointsToGenerate = (JsonApiEndpointsCopy?)(int?)endpointsArgument.Value ?? JsonApiEndpointsCopy.All;
string? controllerNamespace = GetControllerNamespace(controllerNamespaceArgument, resourceType);

string sourceCode = writer.Write(resourceType, idType, endpointsToGenerate, controllerNamespace, controllerName, loggerFactoryInterface);
SourceText sourceText = SourceText.From(sourceCode, Encoding.UTF8);
INamedTypeSymbol? identifiableClosedInterface = FirstOrDefault(resourceType.AllInterfaces, identifiableOpenInterface,
static (@interface, openInterface) =>
@interface.IsGenericType && SymbolEqualityComparer.Default.Equals(@interface.ConstructedFrom, openInterface));

string fileName = GetUniqueFileName(controllerName, controllerNamesInUse);
context.AddSource(fileName, sourceText);
if (identifiableClosedInterface == null)
{
var diagnostic = Diagnostic.Create(MissingInterfaceWarning, typeDeclarationSyntax.GetLocation(), resourceType.Name);
context.ReportDiagnostic(diagnostic);
continue;
}
}

private static TElement FirstOrDefault<TElement, TContext>(ImmutableArray<TElement> source, TContext context, Func<TElement, TContext, bool> predicate)
{
// PERF: Using this method enables to avoid allocating a closure in the passed lambda expression.
// See https://www.jetbrains.com/help/resharper/2021.2/Fixing_Issues_Found_by_DPA.html#closures-in-lambda-expressions.
ITypeSymbol idType = identifiableClosedInterface.TypeArguments[0];
string controllerName = $"{resourceType.Name.Pluralize()}Controller";
JsonApiEndpointsCopy endpointsToGenerate = (JsonApiEndpointsCopy?)(int?)endpointsArgument.Value ?? JsonApiEndpointsCopy.All;

foreach (TElement element in source)
{
if (predicate(element, context))
{
return element;
}
}
string sourceCode = writer.Write(resourceType, idType, endpointsToGenerate, controllerNamespace, controllerName, loggerFactoryInterface);
SourceText sourceText = SourceText.From(sourceCode, Encoding.UTF8);

return default;
string fileName = GetUniqueFileName(controllerName, controllerNamesInUse);
context.AddSource(fileName, sourceText);
}
}

private static string GetControllerNamespace(TypedConstant controllerNamespaceArgument, INamedTypeSymbol resourceType)
private static TElement? FirstOrDefault<TElement, TContext>(ImmutableArray<TElement> source, TContext context, Func<TElement, TContext, bool> predicate)
{
// PERF: Using this method enables to avoid allocating a closure in the passed lambda expression.
// See https://www.jetbrains.com/help/resharper/2021.2/Fixing_Issues_Found_by_DPA.html#closures-in-lambda-expressions.

foreach (TElement element in source)
{
if (!controllerNamespaceArgument.IsNull)
if (predicate(element, context))
{
return (string)controllerNamespaceArgument.Value;
return element;
}
}

if (resourceType.ContainingNamespace.IsGlobalNamespace)
{
return null;
}
return default;
}

if (resourceType.ContainingNamespace.ContainingNamespace.IsGlobalNamespace)
{
return "Controllers";
}
private static string? GetControllerNamespace(TypedConstant controllerNamespaceArgument, INamedTypeSymbol resourceType)
{
if (!controllerNamespaceArgument.IsNull)
{
return (string?)controllerNamespaceArgument.Value;
}

return $"{resourceType.ContainingNamespace.ContainingNamespace}.Controllers";
if (resourceType.ContainingNamespace.IsGlobalNamespace)
{
return null;
}

private static string GetUniqueFileName(string controllerName, IDictionary<string, int> controllerNamesInUse)
if (resourceType.ContainingNamespace.ContainingNamespace.IsGlobalNamespace)
{
// We emit unique file names to prevent a failure in the source generator, but also because our test suite
// may contain two resources with the same class name in different namespaces. That works, as long as only
// one of its controllers gets registered.
return "Controllers";
}

if (controllerNamesInUse.TryGetValue(controllerName, out int lastIndex))
{
lastIndex++;
controllerNamesInUse[controllerName] = lastIndex;
return $"{resourceType.ContainingNamespace.ContainingNamespace}.Controllers";
}

return $"{controllerName}{lastIndex}.g.cs";
}
private static string GetUniqueFileName(string controllerName, IDictionary<string, int> controllerNamesInUse)
{
// We emit unique file names to prevent a failure in the source generator, but also because our test suite
// may contain two resources with the same class name in different namespaces. That works, as long as only
// one of its controllers gets registered.

controllerNamesInUse[controllerName] = 1;
return $"{controllerName}.g.cs";
if (controllerNamesInUse.TryGetValue(controllerName, out int lastIndex))
{
lastIndex++;
controllerNamesInUse[controllerName] = lastIndex;

return $"{controllerName}{lastIndex}.g.cs";
}

controllerNamesInUse[controllerName] = 1;
return $"{controllerName}.g.cs";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<IncludeBuildOutput>false</IncludeBuildOutput>
<NoWarn>$(NoWarn);NU5128</NoWarn>
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<IsRoslynComponent>true</IsRoslynComponent>
</PropertyGroup>

Expand Down
39 changes: 18 additions & 21 deletions src/JsonApiDotNetCore.SourceGenerators/JsonApiEndpointsCopy.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,23 @@
using System;
namespace JsonApiDotNetCore.SourceGenerators;

namespace JsonApiDotNetCore.SourceGenerators
// IMPORTANT: A copy of this type exists in the JsonApiDotNetCore project. Keep these in sync when making changes.
[Flags]
public enum JsonApiEndpointsCopy
{
// IMPORTANT: A copy of this type exists in the JsonApiDotNetCore project. Keep these in sync when making changes.
[Flags]
public enum JsonApiEndpointsCopy
{
None = 0,
GetCollection = 1,
GetSingle = 1 << 1,
GetSecondary = 1 << 2,
GetRelationship = 1 << 3,
Post = 1 << 4,
PostRelationship = 1 << 5,
Patch = 1 << 6,
PatchRelationship = 1 << 7,
Delete = 1 << 8,
DeleteRelationship = 1 << 9,
None = 0,
GetCollection = 1,
GetSingle = 1 << 1,
GetSecondary = 1 << 2,
GetRelationship = 1 << 3,
Post = 1 << 4,
PostRelationship = 1 << 5,
Patch = 1 << 6,
PatchRelationship = 1 << 7,
Delete = 1 << 8,
DeleteRelationship = 1 << 9,

Query = GetCollection | GetSingle | GetSecondary | GetRelationship,
Command = Post | PostRelationship | Patch | PatchRelationship | Delete | DeleteRelationship,
Query = GetCollection | GetSingle | GetSecondary | GetRelationship,
Command = Post | PostRelationship | Patch | PatchRelationship | Delete | DeleteRelationship,

All = Query | Command
}
All = Query | Command
}
Loading