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

Revert to generating resolvers and type-hints. #898

Merged
merged 1 commit into from
Jan 22, 2025
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,17 @@ public interface IWellKnownSerializationTypes
public class MessagePackFormatterNameMapper : ISerializationFormatterNameMapper
{
readonly string userDefinedFormatterNamespace;
readonly bool allowToMapUserDefinedFormatter;

public IWellKnownSerializationTypes WellKnownTypes => MessagePackWellKnownSerializationTypes.Instance;

public MessagePackFormatterNameMapper(string userDefinedFormatterNamespace)
public MessagePackFormatterNameMapper(string userDefinedFormatterNamespace, bool allowToMapUserDefinedFormatter)
{
userDefinedFormatterNamespace = string.IsNullOrWhiteSpace(userDefinedFormatterNamespace) ? "MessagePack.Formatters" : userDefinedFormatterNamespace;
if (!userDefinedFormatterNamespace.StartsWith("global::")) userDefinedFormatterNamespace = "global::" + userDefinedFormatterNamespace;

this.userDefinedFormatterNamespace = userDefinedFormatterNamespace;
this.allowToMapUserDefinedFormatter = allowToMapUserDefinedFormatter;
}

public bool TryMapGeneric(MagicOnionTypeInfo type, [NotNullWhen(true)] out string? formatterName, [NotNullWhen(true)] out string? formatterConstructorArgs)
Expand All @@ -52,7 +54,7 @@ public bool TryMapGeneric(MagicOnionTypeInfo type, [NotNullWhen(true)] out strin
formatterName = $"{mappedFormatterName}<{genericTypeArgs}>";
formatterConstructorArgs = "()";
}
else
else if (allowToMapUserDefinedFormatter)
{
// User-defined generic types
formatterName = $"{userDefinedFormatterNamespace}{(string.IsNullOrWhiteSpace(userDefinedFormatterNamespace) ? "" : ".")}{type.ToDisplayName(MagicOnionTypeInfo.DisplayNameFormat.Namespace | MagicOnionTypeInfo.DisplayNameFormat.WithoutGenericArguments)}Formatter<{genericTypeArgs}>";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ public static string Build(GenerationContext generationContext, MagicOnionServic

writer.AppendLine($$"""
// <auto-generated />
#pragma warning disable CS0618 // 'member' is obsolete: 'text'
#pragma warning disable CS0612 // 'member' is obsolete
#pragma warning disable CS8019 // Unnecessary using directive.
#pragma warning disable

""");
if (!string.IsNullOrEmpty(generationContext.Namespace))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace MagicOnion.Client.SourceGenerator.CodeGen.MessagePack;

internal class MessagePackFormatterResolverGenerator(bool emitGenericFormatterInstantiationAndTypeHints) : ISerializerFormatterGenerator
internal class MessagePackFormatterResolverGenerator() : ISerializerFormatterGenerator
{
public (string HintNameSuffix, string Source) Build(GenerationContext generationContext, SerializationFormatterCodeGenContext ctx)
{
Expand Down Expand Up @@ -49,10 +49,7 @@ partial class {{generationContext.InitializerPartialTypeName}}

EmitResolver(ctx, writer);
EmitGetFormatterHelper(ctx, writer);
if (emitGenericFormatterInstantiationAndTypeHints)
{
EmitTypeHints(ctx, writer);
}
EmitTypeHints(ctx, writer);

writer.AppendLineWithFormat($$"""
}
Expand Down Expand Up @@ -97,9 +94,7 @@ static FormatterCache()

void EmitGetFormatterHelper(SerializationFormatterCodeGenContext ctx, StringBuilder writer)
{
var formatterRegistrations = emitGenericFormatterInstantiationAndTypeHints
? ctx.FormatterRegistrations
: ctx.FormatterRegistrations.Where(x => x is EnumSerializationInfo).ToArray();
var formatterRegistrations = ctx.FormatterRegistrations;

writer.AppendLineWithFormat($$"""
static class MessagePackGeneratedGetFormatterHelper
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ static void EmitHeader(GenerationContext generationContext, StringBuilder writer
{
writer.AppendLine("""
// <auto-generated />
#pragma warning disable CS0618 // 'member' is obsolete: 'text'
#pragma warning disable CS0612 // 'member' is obsolete
#pragma warning disable CS8019 // Unnecessary using directive.
#pragma warning disable

""");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,7 @@ static void EmitHeader(GenerationContext generationContext, StringBuilder writer
{
writer.AppendLine("""
// <auto-generated />
#pragma warning disable CS0618 // 'member' is obsolete: 'text'
#pragma warning disable CS0612 // 'member' is obsolete
#pragma warning disable CS0414 // The private field 'field' is assigned but its value is never used
#pragma warning disable CS8019 // Unnecessary using directive.
#pragma warning disable CS1522 // Empty switch block
#pragma warning disable CS1998 // This async method lacks 'await' operators and will run synchronously.
#pragma warning disable

""");
}
Expand Down
9 changes: 4 additions & 5 deletions src/MagicOnion.Client.SourceGenerator/GenerationContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,15 @@ public enum SerializerType
public record GenerationOptions(
SerializerType Serializer,
bool DisableAutoRegistration,
string MessagePackFormatterNamespace,
bool EnableStreamingHubDiagnosticHandler,
string GenerateFileHintNamePrefix
)
string GenerateFileHintNamePrefix,
IReadOnlyDictionary<string, object> AdditionalOptions)
{
public static GenerationOptions Default { get; } = new (
SerializerType.MessagePack,
DisableAutoRegistration: false,
MessagePackFormatterNamespace: "MessagePack.Formatters",
EnableStreamingHubDiagnosticHandler: false,
GenerateFileHintNamePrefix: string.Empty
GenerateFileHintNamePrefix: string.Empty,
AdditionalOptions: new Dictionary<string, object>()
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ public partial class MagicOnionClientSourceGenerator
public const string MagicOnionClientGenerationAttributeName = $"{MagicOnionClientGenerationAttributeShortName}Attribute";
public const string MagicOnionClientGenerationAttributeFullName = $"MagicOnion.Client.{MagicOnionClientGenerationAttributeName}";

public const string MagicOnionClientGenerationOptionAttributeShortName = "MagicOnionClientGenerationOption";
public const string MagicOnionClientGenerationOptionAttributeName = $"{MagicOnionClientGenerationOptionAttributeShortName}Attribute";
public const string MagicOnionClientGenerationOptionAttributeFullName = $"MagicOnion.Client.{MagicOnionClientGenerationOptionAttributeName}";

static class Emitter
{
public static void Emit(GenerationContext context, ImmutableArray<INamedTypeSymbol> interfaceSymbols, ReferenceSymbols referenceSymbols)
Expand Down Expand Up @@ -45,8 +49,10 @@ public static void Emit(GenerationContext context, ImmutableArray<INamedTypeSymb
EnumFormatterGenerator: _ => string.Empty
),
SerializerType.MessagePack => (
Mapper: new MessagePackFormatterNameMapper(context.Options.MessagePackFormatterNamespace),
Generator: new MessagePackFormatterResolverGenerator(emitGenericFormatterInstantiationAndTypeHints: false),
Mapper: new MessagePackFormatterNameMapper(
(context.Options.AdditionalOptions.TryGetValue("MessagePack.FormatterNamespace", out var formatterNamespace) ? formatterNamespace as string : null) ?? "MessagePack.Formatters",
context.Options.AdditionalOptions.TryGetValue("MessagePack.GenerateResolverForCustomFormatter", out var generateTypeHintsForCustomFormatter) && generateTypeHintsForCustomFormatter.Equals(true)),
Generator: new MessagePackFormatterResolverGenerator(),
EnumFormatterGenerator: x => MessagePackEnumFormatterGenerator.Build(context, x)
),
_ => throw new NotImplementedException(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,13 @@ static void Traverse(INamespaceOrTypeSymbol rootNamespaceOrTypeSymbol, List<INam
}
}

static GenerationOptions ParseClientGenerationOptions(AttributeData attr)
static GenerationOptions ParseClientGenerationOptions(AttributeData attr, ClassDeclarationSyntax initializerClassDecl, SemanticModel semanticModel)
{
var options = GenerationOptions.Default;
var initializerClassSymbol = semanticModel.GetDeclaredSymbol(initializerClassDecl) ?? throw new InvalidOperationException();
var additionalOptionAttrs = initializerClassSymbol.GetAttributes().Where(x => x.AttributeClass?.Name == MagicOnionClientGenerationOptionAttributeName).ToArray();

var additionalOptions = new Dictionary<string, object>();
var options = GenerationOptions.Default with { AdditionalOptions = additionalOptions };

foreach (var namedArg in attr.NamedArguments)
{
Expand All @@ -90,8 +94,8 @@ static GenerationOptions ParseClientGenerationOptions(AttributeData attr)
case nameof(GenerationOptions.Serializer):
options = options with { Serializer = (SerializerType)(int)namedArg.Value.Value! };
break;
case nameof(GenerationOptions.MessagePackFormatterNamespace):
options = options with { MessagePackFormatterNamespace = (string)namedArg.Value.Value! };
case "MessagePackFormatterNamespace": // Backward compatibility
additionalOptions["MessagePack.FormatterNamespace"] = (string)namedArg.Value.Value!;
break;
case nameof(GenerationOptions.EnableStreamingHubDiagnosticHandler):
options = options with { EnableStreamingHubDiagnosticHandler = (bool)namedArg.Value.Value! };
Expand All @@ -102,6 +106,14 @@ static GenerationOptions ParseClientGenerationOptions(AttributeData attr)
}
}

if (additionalOptionAttrs.Length > 0)
{
foreach (var additionalOptionAttr in additionalOptionAttrs)
{
additionalOptions[additionalOptionAttr.ConstructorArguments[0].Value!.ToString()!] = additionalOptionAttr.ConstructorArguments[1].Value!;
}
}

return options;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
var attr = attrs.FirstOrDefault(x => x.AttributeClass?.Name == MagicOnionClientGenerationAttributeName);
if (attr is null) return; // TODO: ReportDiagnostic

var options = ParseClientGenerationOptions(attr);
var options = ParseClientGenerationOptions(attr, initializerClassDecl, semanticModel);
if (!TryParseClientGenerationSpec(sourceProductionContext, semanticModel, initializerClassDecl, attr, out var spec))
{
return;
Expand Down
25 changes: 24 additions & 1 deletion src/MagicOnion.Client/MagicOnionClientGenerationAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace MagicOnion.Client;
/// Marker attribute for generating clients of MagicOnion.
/// The source generator collects the classes specified by this attribute and uses them to generate source.
/// </summary>
[AttributeUsage(global::System.AttributeTargets.Class, AllowMultiple = false)]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class MagicOnionClientGenerationAttribute : Attribute
{
/// <summary>
Expand All @@ -20,6 +20,7 @@ public class MagicOnionClientGenerationAttribute : Attribute
/// <summary>
/// Gets or set the namespace of pre-generated MessagePackFormatters. The default value is <c>MessagePack.Formatters</c>.
/// </summary>
[Obsolete("This property is obsolete. Use [MagicOnionClientGenerationOption(\"MessagePack.FormatterNamespace\", \"MessagePack.Formatters\")] instead.")]
public string MessagePackFormatterNamespace { get; set; } = "MessagePack.Formatters";

/// <summary>
Expand All @@ -44,3 +45,25 @@ public enum GenerateSerializerType
MemoryPack = 1,
}
}

/// <summary>
/// Specifies the options for generating clients of MagicOnion.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class MagicOnionClientGenerationOptionAttribute : Attribute
{
/// <summary>
/// Gets or sets the key of the option.
/// </summary>
public string Key { get; set; }
/// <summary>
/// Gets or sets the value of the option.
/// </summary>
public object? Value { get; set; }

public MagicOnionClientGenerationOptionAttribute(string key, object value)
{
Key = key;
Value = value;
}
}
4 changes: 2 additions & 2 deletions src/MagicOnion.Client/PublicAPI.Shipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,11 @@ MagicOnion.Client.MagicOnionClientGenerationAttribute.GenerateSerializerType
MagicOnion.Client.MagicOnionClientGenerationAttribute.GenerateSerializerType.MemoryPack = 1 -> MagicOnion.Client.MagicOnionClientGenerationAttribute.GenerateSerializerType
MagicOnion.Client.MagicOnionClientGenerationAttribute.GenerateSerializerType.MessagePack = 0 -> MagicOnion.Client.MagicOnionClientGenerationAttribute.GenerateSerializerType
MagicOnion.Client.MagicOnionClientGenerationAttribute.MagicOnionClientGenerationAttribute(params System.Type![]! typesContainedInTargetAssembly) -> void
MagicOnion.Client.MagicOnionClientGenerationAttribute.MessagePackFormatterNamespace.get -> string!
MagicOnion.Client.MagicOnionClientGenerationAttribute.MessagePackFormatterNamespace.set -> void
MagicOnion.Client.MagicOnionClientGenerationAttribute.Serializer.get -> MagicOnion.Client.MagicOnionClientGenerationAttribute.GenerateSerializerType
MagicOnion.Client.MagicOnionClientGenerationAttribute.Serializer.set -> void
MagicOnion.Client.MagicOnionClientGenerationAttribute.TypesContainedInTargetAssembly.get -> System.Type![]!
MagicOnion.Client.MagicOnionClientGenerationOptionAttribute
MagicOnion.Client.MagicOnionClientGenerationOptionAttribute(string! key, object? value) -> void
MagicOnion.Client.MagicOnionClientOptions
MagicOnion.Client.MagicOnionClientOptions.CallInvoker.get -> Grpc.Core.CallInvoker!
MagicOnion.Client.MagicOnionClientOptions.CallOptions.get -> Grpc.Core.CallOptions
Expand Down
2 changes: 2 additions & 0 deletions src/MagicOnion.Client/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ MagicOnion.Client.IStreamingHubDiagnosticHandler.OnBroadcastEventRaw<THub>(THub
MagicOnion.Client.IStreamingHubDiagnosticHandler.OnBroadcastEvent<THub, T>(THub hubInstance, string! methodName, T value) -> void
MagicOnion.Client.IStreamingHubDiagnosticHandler.OnMethodInvoke<THub, TRequest, TResponse>(THub hubInstance, int methodId, string! methodName, TRequest request, bool isFireAndForget, MagicOnion.Client.IStreamingHubDiagnosticHandler.InvokeMethodDelegate<TRequest, TResponse>! invokeMethod) -> System.Threading.Tasks.ValueTask<TResponse>
MagicOnion.Client.IStreamingHubDiagnosticHandler.OnResponseEvent<THub, T>(THub hubInstance, string! methodName, System.ReadOnlyMemory<byte> data) -> void
MagicOnion.Client.MagicOnionClientGenerationAttribute.MessagePackFormatterNamespace.get -> string!
MagicOnion.Client.MagicOnionClientGenerationAttribute.MessagePackFormatterNamespace.set -> void
static MagicOnion.Client.StreamingHubClient.Connect<TStreamingHub, TReceiver>(Grpc.Core.CallInvoker! callInvoker, TReceiver receiver, string? host = null, Grpc.Core.CallOptions option = default(Grpc.Core.CallOptions), MagicOnion.Serialization.IMagicOnionSerializerProvider? serializerProvider = null, MagicOnion.Client.IStreamingHubClientFactoryProvider? factoryProvider = null, MagicOnion.Client.IMagicOnionClientLogger? logger = null) -> TStreamingHub
static MagicOnion.Client.StreamingHubClient.Connect<TStreamingHub, TReceiver>(Grpc.Core.ChannelBase! channel, TReceiver receiver, string? host = null, Grpc.Core.CallOptions option = default(Grpc.Core.CallOptions), MagicOnion.Serialization.IMagicOnionSerializerProvider? serializerProvider = null, MagicOnion.Client.IStreamingHubClientFactoryProvider? factoryProvider = null, MagicOnion.Client.IMagicOnionClientLogger? logger = null) -> TStreamingHub
Loading
Loading