Skip to content
Open
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
2 changes: 1 addition & 1 deletion src/MemoryPack.Core/Attributes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public enum SerializeLayout
Explicit
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
public sealed class MemoryPackUnionAttribute : Attribute
{
public ushort Tag { get; }
Expand Down
16 changes: 16 additions & 0 deletions src/MemoryPack.Generator/DiagnosticDescriptors.cs
Original file line number Diff line number Diff line change
Expand Up @@ -351,4 +351,20 @@ internal static class DiagnosticDescriptors
category: Category,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);

public static readonly DiagnosticDescriptor CSharpUnionTagsMustMatchCases = new(
id: "MEMPACK044",
title: "Union tags must match the union's case types",
messageFormat: "The MemoryPackable union '{0}' must have exactly one MemoryPackUnion tag for each case type when any are specified",
category: Category,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);

public static readonly DiagnosticDescriptor UnionOnStructMustBeCSharpUnion = new(
id: "MEMPACK045",
title: "MemoryPackUnion on a struct requires a union declaration",
messageFormat: "The MemoryPackable struct '{0}' can only use MemoryPackUnion if it is declared as a union",
category: Category,
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
}
6 changes: 6 additions & 0 deletions src/MemoryPack.Generator/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,12 @@ public static string FullyQualifiedToString(this ISymbol symbol)
return symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
}

public static bool IsCSharpUnion(this INamedTypeSymbol symbol)
{
// match by keyword as UnionDeclarationSyntax is newer than the referenced Roslyn
return symbol.DeclaringSyntaxReferences.Any(x => x.GetSyntax() is TypeDeclarationSyntax { Keyword.ValueText: "union" });
}

public static bool EqualsUnconstructedGenericType(this INamedTypeSymbol left, INamedTypeSymbol right)
{
var l = left.IsGenericType ? left.ConstructUnboundGenericType() : left;
Expand Down
114 changes: 103 additions & 11 deletions src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,12 @@ public void Emit(StringBuilder writer, IGeneratorContext context)

var serializeBody = "";
var deserializeBody = "";
if (IsUnmanagedType)
if (IsCSharpUnion)
{
serializeBody = EmitCSharpUnionSerializeBody();
deserializeBody = EmitCSharpUnionDeserializeBody();
}
else if (IsUnmanagedType)
{
serializeBody = $$"""
writer.WriteUnmanaged(value);
Expand Down Expand Up @@ -302,24 +307,26 @@ public void Emit(StringBuilder writer, IGeneratorContext context)
Members = originalMembers;
}

var classOrStructOrRecord = (IsRecord, IsValueType) switch
var classOrStructOrRecord = (IsCSharpUnion, IsRecord, IsValueType) switch
{
(true, true) => "record struct",
(true, false) => "record",
(false, true) => "struct",
(false, false) => "class",
(true, _, _) => "union",
(_, true, true) => "record struct",
(_, true, false) => "record",
(_, false, true) => "struct",
(_, false, false) => "class",
};

var containingTypeDeclarations = new List<string>();
var containingType = Symbol.ContainingType;
while (containingType is not null)
{
containingTypeDeclarations.Add((containingType.IsRecord, containingType.IsValueType) switch
containingTypeDeclarations.Add((containingType.IsCSharpUnion(), containingType.IsRecord, containingType.IsValueType) switch
{
(true, true) => $"partial record struct {containingType.Name}",
(true, false) => $"partial record {containingType.Name}",
(false, true) => $"partial struct {containingType.Name}",
(false, false) => $"partial class {containingType.Name}",
(true, _, _) => $"partial union {containingType.Name}",
(_, true, true) => $"partial record struct {containingType.Name}",
(_, true, false) => $"partial record {containingType.Name}",
(_, false, true) => $"partial struct {containingType.Name}",
(_, false, false) => $"partial class {containingType.Name}",
});
containingType = containingType.ContainingType;
}
Expand Down Expand Up @@ -1225,6 +1232,91 @@ string EmitUnionDeserializeBody()
""";
}

// C# union case types in declaration order
ITypeSymbol[] GetCSharpUnionCaseTypes()
{
return Symbol.InstanceConstructors
.Where(x => x.IsImplicitlyDeclared && x.Parameters.Length == 1)
.Select(x => x.Parameters[0].Type)
.ToArray();
}

// [MemoryPackUnion] tag if specified, otherwise the case index
ushort GetCSharpUnionTag(ITypeSymbol caseType, int index)
{
return UnionTags.Length == 0
? (ushort)index
: UnionTags.First(x => SymbolEqualityComparer.Default.Equals(x.Type, caseType)).Tag;
}

static string ToCSharpUnionTypePattern(ITypeSymbol type)
{
// type patterns can't be nullable
if (type is INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T } nullable)
{
type = nullable.TypeArguments[0];
}
// tuple syntax would be parsed as a positional pattern
if (type is INamedTypeSymbol { IsTupleType: true } tuple)
{
return $"global::System.ValueTuple<{string.Join(", ", tuple.TypeArguments.Select(x => x.FullyQualifiedToString()))}>";
}
return type.WithNullableAnnotation(NullableAnnotation.NotAnnotated).FullyQualifiedToString();
}

string EmitCSharpUnionSerializeBody()
{
var writeBody = GetCSharpUnionCaseTypes()
.Select((x, i) => $$"""
else if (__value is {{ToCSharpUnionTypePattern(x)}} __case{{i}})
{
writer.WriteUnionHeader({{GetCSharpUnionTag(x, i)}});
writer.WriteValue(__case{{i}});
}
""")
.NewLine();

return $$"""
var __value = value.Value;
if (__value == null)
{
writer.WriteNullUnionHeader();
}
{{writeBody}}
else
{
MemoryPackSerializationException.ThrowNotFoundInUnionType(__value.GetType(), typeof({{TypeName}}));
}
""";
}

string EmitCSharpUnionDeserializeBody()
{
var readBody = GetCSharpUnionCaseTypes()
.Select((x, i) => $$"""
case {{GetCSharpUnionTag(x, i)}}:
value = new {{TypeName}}(({{x.FullyQualifiedToString()}})reader.ReadValue<{{ToCSharpUnionTypePattern(x)}}>());
break;
""")
.NewLine();

return $$"""
if (!reader.TryReadUnionHeader(out var tag))
{
value = default;
goto END;
}

switch (tag)
{
{{readBody}}
default:
MemoryPackSerializationException.ThrowInvalidTag(tag, typeof({{TypeName}}));
break;
}
""";
}

string EmitGenericCollectionTemplate(IGeneratorContext context)
{
var (collectionKind, collectionSymbol) = ParseCollectionKind(Symbol, reference);
Expand Down
38 changes: 35 additions & 3 deletions src/MemoryPack.Generator/MemoryPackGenerator.Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ public partial class TypeMeta
public bool IsUnmanagedType { get; }
public bool IsUnion { get; }
public bool IsRecord { get; }
/// <summary>C# union declaration</summary>
public bool IsCSharpUnion { get; }
public bool IsInterfaceOrAbstract { get; }
public IMethodSymbol? Constructor { get; }
public MethodMeta[] OnSerializing { get; }
Expand All @@ -76,7 +78,9 @@ public TypeMeta(INamedTypeSymbol symbol, ReferenceSymbols reference)
this.SerializeLayout = serializeLayout;

this.TypeName = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
this.Constructor = ChooseConstructor(symbol, reference);
this.IsCSharpUnion = symbol.IsCSharpUnion();
// unions are always created through their case constructors
this.Constructor = IsCSharpUnion ? null : ChooseConstructor(symbol, reference);

this.Members = symbol.GetAllMembers() // iterate includes parent type
.Where(x => x is (IFieldSymbol or IPropertySymbol) and { IsStatic: false, IsImplicitlyDeclared: false, CanBeReferencedByName: true })
Expand Down Expand Up @@ -111,14 +115,19 @@ public TypeMeta(INamedTypeSymbol symbol, ReferenceSymbols reference)
this.IsValueType = symbol.IsValueType;
this.IsUnmanagedType = symbol.IsUnmanagedType;
this.IsInterfaceOrAbstract = symbol.IsAbstract;
this.IsUnion = symbol.ContainsAttribute(reference.MemoryPackUnionAttribute);
if (IsCSharpUnion)
{
// only Value is serialized
this.Members = Array.Empty<MemberMeta>();
}
this.IsUnion = !IsCSharpUnion && symbol.ContainsAttribute(reference.MemoryPackUnionAttribute);
this.IsRecord = symbol.IsRecord;
this.OnSerializing = CollectMethod(reference.MemoryPackOnSerializingAttribute, IsValueType, isReader: false);
this.OnSerialized = CollectMethod(reference.MemoryPackOnSerializedAttribute, IsValueType, isReader: false);
this.OnDeserializing = CollectMethod(reference.MemoryPackOnDeserializingAttribute, IsValueType, isReader: true);
this.OnDeserialized = CollectMethod(reference.MemoryPackOnDeserializedAttribute, IsValueType, isReader: true);

if (IsUnion)
if (IsUnion || IsCSharpUnion)
{
this.UnionTags = symbol.GetAttributes()
.Where(x => SymbolEqualityComparer.Default.Equals(x.AttributeClass, reference.MemoryPackUnionAttribute))
Expand Down Expand Up @@ -592,6 +601,12 @@ public bool Validate(TypeDeclarationSyntax syntax, IGeneratorContext context, bo
UNION_VALIDATIONS:
if (IsUnion)
{
if (Symbol.IsValueType)
{
context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.UnionOnStructMustBeCSharpUnion, syntax.Identifier.GetLocation(), Symbol.Name));
return false;
}

if (Symbol.IsSealed)
{
context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.SealedTypeCantBeUnion, syntax.Identifier.GetLocation(), Symbol.Name));
Expand Down Expand Up @@ -660,6 +675,23 @@ public bool Validate(TypeDeclarationSyntax syntax, IGeneratorContext context, bo
}
}

// explicit tags must cover every case once
if (IsCSharpUnion && UnionTags.Length != 0)
{
if (UnionTags.Select(x => x.Tag).HasDuplicate())
{
context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.UnionTagDuplicate, syntax.Identifier.GetLocation(), Symbol.Name));
noError = false;
}

var caseTypes = GetCSharpUnionCaseTypes();
if (UnionTags.Length != caseTypes.Length || !caseTypes.All(x => UnionTags.Count(y => SymbolEqualityComparer.Default.Equals(y.Type, x)) == 1))
{
context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.CSharpUnionTagsMustMatchCases, syntax.Identifier.GetLocation(), Symbol.Name));
noError = false;
}
}

return noError;
}

Expand Down
6 changes: 4 additions & 2 deletions src/MemoryPack.Generator/MemoryPackGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,13 @@ void RegisterMemoryPackable(IncrementalGeneratorInitializationContext context)
MemoryPackableAttributeFullName,
predicate: static (node, token) =>
{
// search [MemoryPackable] class or struct or interface or record
// search [MemoryPackable] class or struct or interface or record or union
return (node is ClassDeclarationSyntax
or StructDeclarationSyntax
or RecordDeclarationSyntax
or InterfaceDeclarationSyntax);
or InterfaceDeclarationSyntax
// UnionDeclarationSyntax is newer than the referenced Roslyn, so match by keyword
or TypeDeclarationSyntax { Keyword.ValueText: "union" });
},
transform: static (context, token) =>
{
Expand Down
Loading