Skip to content
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

Fixed handling of generics for DataLoader #5695

Merged
merged 1 commit into from
Jan 18, 2023
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
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text;
using HotChocolate.Types.Analyzers.Helpers;
using HotChocolate.Types.Analyzers.Inspectors;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
Expand Down Expand Up @@ -31,9 +32,7 @@ public class DataLoaderGenerator : ISyntaxGenerator
DiagnosticSeverity.Error,
isEnabledByDefault: true);

public void Initialize(IncrementalGeneratorPostInitializationContext context)
{
}
public void Initialize(IncrementalGeneratorPostInitializationContext context) { }

public bool Consume(ISyntaxInfo syntaxInfo)
=> syntaxInfo is DataLoaderInfo or ModuleInfo or DataLoaderDefaultsInfo;
Expand All @@ -57,7 +56,7 @@ compilation.AssemblyName is null

var processed = new HashSet<string>(StringComparer.Ordinal);
var dataLoaders = new List<DataLoaderInfo>();
var sourceText = new StringBuilder();
var sourceText = StringBuilderPool.Get();

sourceText.AppendLine("// <auto-generated/>");
sourceText.AppendLine("#nullable enable");
Expand Down Expand Up @@ -119,6 +118,7 @@ compilation.AssemblyName is null
}
else
{
keyType = keyArg.Type;
kind = DataLoaderKind.Cache;
}

Expand Down Expand Up @@ -159,6 +159,8 @@ compilation.AssemblyName is null
WellKnownFileNames.DataLoaderFile,
SourceText.From(sourceText.ToString(), Encoding.UTF8));
}

StringBuilderPool.Return(sourceText);
}

private static void GenerateDataLoader(
Expand All @@ -172,7 +174,7 @@ private static void GenerateDataLoader(
Dictionary<int, string> services,
StringBuilder sourceText)
{
var isScoped = dataLoader.IsScoped ?? defaults.Scoped ?? false;
var isScoped = dataLoader.IsScoped ?? defaults.Scoped ?? false;
var isPublic = dataLoader.IsPublic ?? defaults.IsPublic ?? true;
var isInterfacePublic = dataLoader.IsInterfacePublic ?? defaults.IsInterfacePublic ?? true;

Expand All @@ -198,21 +200,17 @@ private static void GenerateDataLoader(
if (kind is DataLoaderKind.Batch or DataLoaderKind.Cache)
{
sourceText.Append(" : global::GreenDonut.IDataLoader<");
sourceText.Append("global::");
sourceText.Append(ToTypeName(keyType));
sourceText.Append(keyType.ToFullyQualified());
sourceText.Append(", ");
sourceText.Append("global::");
sourceText.Append(ToTypeName(valueType));
sourceText.Append(valueType.ToFullyQualified());
sourceText.Append(">");
}
else if (kind is DataLoaderKind.Group)
{
sourceText.Append(" : global::GreenDonut.IDataLoader<");
sourceText.Append("global::");
sourceText.Append(ToTypeName(keyType));
sourceText.Append(keyType.ToFullyQualified());
sourceText.Append(", ");
sourceText.Append("global::");
sourceText.Append(ToTypeName(valueType));
sourceText.Append(valueType.ToFullyQualified());
sourceText.Append("[]>");
}

Expand All @@ -234,39 +232,34 @@ private static void GenerateDataLoader(
if (kind is DataLoaderKind.Batch)
{
sourceText.Append(" : global::GreenDonut.BatchDataLoader<");
sourceText.Append("global::");
sourceText.Append(ToTypeName(keyType));
sourceText.Append(keyType.ToFullyQualified());
sourceText.Append(", ");
sourceText.Append("global::");
sourceText.Append(ToTypeName(valueType));
sourceText.Append(valueType.ToFullyQualified());
sourceText.Append(">");
}
else if (kind is DataLoaderKind.Group)
{
sourceText.Append(" : global::GreenDonut.GroupedDataLoader<");
sourceText.Append("global::");
sourceText.Append(ToTypeName(keyType));
sourceText.Append(keyType.ToFullyQualified());
sourceText.Append(", ");
sourceText.Append("global::");
sourceText.Append(ToTypeName(valueType));
sourceText.Append(valueType.ToFullyQualified());
sourceText.Append(">");
}
else if (kind is DataLoaderKind.Cache)
{
sourceText.Append(" : global::GreenDonut.CacheDataLoader<");
sourceText.Append("global::");
sourceText.Append(ToTypeName(keyType));
sourceText.Append(keyType.ToFullyQualified());
sourceText.Append(", ");
sourceText.Append("global::");
sourceText.Append(ToTypeName(valueType));
sourceText.Append(valueType.ToFullyQualified());
sourceText.Append(">");
}

sourceText.Append(", ");
sourceText.AppendLine(interfaceName);
sourceText.AppendLine(" {");

sourceText.AppendLine(" private readonly IServiceProvider _services;");
sourceText.AppendLine(
" private readonly global::System.IServiceProvider _services;");
sourceText.AppendLine();

if (kind is DataLoaderKind.Batch or DataLoaderKind.Group)
Expand All @@ -279,7 +272,7 @@ private static void GenerateDataLoader(
.Append(Indent)
.Append(Indent)
.Append(Indent)
.AppendLine("IServiceProvider services,");
.AppendLine("global::System.IServiceProvider services,");
sourceText
.Append(Indent)
.Append(Indent)
Expand Down Expand Up @@ -307,7 +300,7 @@ private static void GenerateDataLoader(
.Append(Indent)
.Append(Indent)
.Append(Indent)
.AppendLine("IServiceProvider services,");
.AppendLine("global::System.IServiceProvider services,");
sourceText
.Append(Indent)
.Append(Indent)
Expand All @@ -324,47 +317,45 @@ private static void GenerateDataLoader(

sourceText.AppendLine(" {");
sourceText.AppendLine(" _services = services ??");
sourceText.AppendLine(" throw new ArgumentNullException(nameof(services));");
sourceText.Append(" throw new global::")
.AppendLine("System.ArgumentNullException(nameof(services));");
sourceText.AppendLine(" }");
sourceText.AppendLine();

if (kind is DataLoaderKind.Batch)
{
sourceText.Append($" protected override async {WellKnownTypes.Task}<");
sourceText.Append($"global::{ReadOnlyDictionary}<");
sourceText.Append("global::");
sourceText.Append(ToTypeName(keyType));
sourceText.Append(", global::");
sourceText.Append(ToTypeName(valueType));
sourceText.Append($" protected override async global::{WellKnownTypes.Task}<");
sourceText.Append($"{ReadOnlyDictionary}<");
sourceText.Append(keyType.ToFullyQualified());
sourceText.Append(", ");
sourceText.Append(valueType.ToFullyQualified());
sourceText.Append(">> ");
sourceText.AppendLine("LoadBatchAsync(");
sourceText.Append($" global::{ReadOnlyList}<");
sourceText.AppendLine($"global::{ToTypeName(keyType)}> keys,");
sourceText.Append($" {ReadOnlyList}<");
sourceText.AppendLine($"{keyType.ToFullyQualified()}> keys,");
sourceText.AppendLine($" global::{WellKnownTypes.CancellationToken} ct)");
}
else if (kind is DataLoaderKind.Group)
{
sourceText.Append($" protected override async {WellKnownTypes.Task}<");
sourceText.Append($"global::{Lookup}<");
sourceText.Append("global::");
sourceText.Append(ToTypeName(keyType));
sourceText.Append(", global::");
sourceText.Append(ToTypeName(valueType));
sourceText.Append($" protected override async global::{WellKnownTypes.Task}<");
sourceText.Append($"{Lookup}<");
sourceText.Append(keyType.ToFullyQualified());
sourceText.Append(", ");
sourceText.Append(valueType.ToFullyQualified());
sourceText.Append(">> ");
sourceText.AppendLine("LoadGroupedBatchAsync(");
sourceText.Append($" global::{ReadOnlyList}<");
sourceText.AppendLine($"global::{ToTypeName(keyType)}> keys,");
sourceText.Append($" {ReadOnlyList}<");
sourceText.AppendLine($"{keyType.ToFullyQualified()}> keys,");
sourceText.AppendLine($" global::{WellKnownTypes.CancellationToken} ct)");
}
else if (kind is DataLoaderKind.Cache)
{
sourceText.Append($" protected override async {WellKnownTypes.Task}<");
sourceText.Append("global::");
sourceText.Append(ToTypeName(valueType));
sourceText.Append($" protected override async global::{WellKnownTypes.Task}<");
sourceText.Append(valueType.ToFullyQualified());
sourceText.Append("> ");
sourceText.AppendLine("LoadSingleAsync(");
sourceText.AppendLine($" global::{ToTypeName(keyType)} key,");
sourceText.AppendLine($" global::{WellKnownTypes.CancellationToken} ct)");
sourceText.AppendLine($" {keyType.ToFullyQualified()} key,");
sourceText.AppendLine($" {WellKnownTypes.CancellationToken} ct)");
}

sourceText.AppendLine(" {");
Expand All @@ -382,6 +373,7 @@ private static void GenerateDataLoader(
sourceText.Append($" var p{item.Key} = ");
sourceText.Append("scope.ServiceProvider.GetRequiredService<");
sourceText.Append(item.Value);
TestLog.Log("scoped: " + item.Value);
sourceText.AppendLine(">();");
}
}
Expand All @@ -391,11 +383,12 @@ private static void GenerateDataLoader(
{
sourceText.Append($" var p{item.Key} = _services.GetRequiredService<");
sourceText.Append(item.Value);
TestLog.Log("non scoped: " + item.Value);
sourceText.AppendLine(">();");
}
}

sourceText.Append(" return await global::");
sourceText.Append(" return await ");
sourceText.Append(dataLoader.ContainingType);
sourceText.Append(".");
sourceText.Append(dataLoader.MethodName);
Expand Down Expand Up @@ -468,9 +461,8 @@ private static void GenerateDataLoaderRegistrations(
.Append(Indent)
.Append(Indent)
.Append("builder.AddDataLoader<")
.Append("global::")
.Append(dataLoader.InterfaceFullName)
.Append(", global::")
.Append(", ")
.Append(dataLoader.FullName)
.AppendLine(">();");
}
Expand All @@ -493,7 +485,7 @@ private void InspectDataLoaderParameters(
for (var i = 1; i < dataLoader.MethodSymbol.Parameters.Length; i++)
{
var argument = dataLoader.MethodSymbol.Parameters[i];
var argumentType = ToTypeName(argument.Type);
var argumentType = argument.Type.ToFullyQualified();

if (IsCancellationToken(argumentType))
{
Expand All @@ -515,7 +507,7 @@ private void InspectDataLoaderParameters(
private static bool IsKeysArgument(ITypeSymbol type)
{
if (type is INamedTypeSymbol { IsGenericType: true, TypeArguments.Length: 1 } namedType &&
ReadOnlyList.Equals(ToTypeName(namedType), Ordinal))
ReadOnlyList.Equals(ToTypeNameNoGenerics(namedType), Ordinal))
{
return true;
}
Expand All @@ -526,7 +518,7 @@ private static bool IsKeysArgument(ITypeSymbol type)
private static ITypeSymbol ExtractKeyType(ITypeSymbol type)
{
if (type is INamedTypeSymbol { IsGenericType: true, TypeArguments.Length: 1 } namedType &&
ReadOnlyList.Equals(ToTypeName(namedType), Ordinal))
ReadOnlyList.Equals(ToTypeNameNoGenerics(namedType), Ordinal))
{
return namedType.TypeArguments[0];
}
Expand All @@ -535,10 +527,8 @@ private static ITypeSymbol ExtractKeyType(ITypeSymbol type)
}

private static bool IsCancellationToken(string typeName)
=> string.Equals(typeName, WellKnownTypes.CancellationToken);

private static string ToTypeName(ITypeSymbol type)
=> $"{type.ContainingNamespace}.{type.Name}";
=> string.Equals(typeName, WellKnownTypes.CancellationToken) ||
string.Equals(typeName, GlobalCancellationToken);

private static bool IsReturnTypeDictionary(ITypeSymbol returnType, ITypeSymbol keyType)
{
Expand All @@ -562,7 +552,7 @@ private static bool IsReturnTypeLookup(ITypeSymbol returnType, ITypeSymbol keyTy
{
var resultType = namedType.TypeArguments[0];

if (ToTypeName(resultType).Equals(Lookup, Ordinal) &&
if (ToTypeNameNoGenerics(resultType).Equals(Lookup, Ordinal) &&
resultType is INamedTypeSymbol { TypeArguments.Length: 2 } dictionaryType &&
dictionaryType.TypeArguments[0].Equals(keyType, SymbolEqualityComparer.Default))
{
Expand All @@ -574,11 +564,11 @@ private static bool IsReturnTypeLookup(ITypeSymbol returnType, ITypeSymbol keyTy

private static bool IsReadOnlyDictionary(ITypeSymbol type)
{
if (!ToTypeName(type).Equals(ReadOnlyDictionary, Ordinal))
if (!ToTypeNameNoGenerics(type).Equals(ReadOnlyDictionary, Ordinal))
{
foreach (var interfaceSymbol in type.Interfaces)
{
if (ToTypeName(interfaceSymbol).Equals(ReadOnlyDictionary, Ordinal))
if (ToTypeNameNoGenerics(interfaceSymbol).Equals(ReadOnlyDictionary, Ordinal))
{
return true;
}
Expand Down Expand Up @@ -608,4 +598,7 @@ private static ITypeSymbol ExtractValueType(ITypeSymbol returnType, DataLoaderKi

throw new InvalidOperationException();
}

private static string ToTypeNameNoGenerics(ITypeSymbol typeSymbol)
=> $"{typeSymbol.ContainingNamespace}.{typeSymbol.Name}";
}
Loading