From 95e67c99d0b11a5c85446578aa679b7e2e0298d0 Mon Sep 17 00:00:00 2001 From: pixsperdavid Date: Tue, 10 Nov 2026 18:33:53 +0000 Subject: [PATCH 1/2] Support C# union types [MemoryPackable] partial union declarations serialize Value as a union header plus the case value. Tags default to the case's declaration position and can be set with [MemoryPackUnion(tag, typeof(Case))]. --- .github/workflows/build-debug.yaml | 16 ++ .github/workflows/build-release.yaml | 16 ++ src/MemoryPack.Core/Attributes.cs | 2 +- .../DiagnosticDescriptors.cs | 16 ++ src/MemoryPack.Generator/Extensions.cs | 6 + .../MemoryPackGenerator.Emitter.cs | 114 ++++++++- .../MemoryPackGenerator.Parser.cs | 38 ++- .../MemoryPackGenerator.cs | 6 +- tests/MemoryPack.Tests/CSharpUnionTest.cs | 231 ++++++++++++++++++ .../MemoryPack.Tests/MemoryPack.Tests.csproj | 4 +- .../GeneratorDiagnosticsTest.cs | 15 ++ 11 files changed, 446 insertions(+), 18 deletions(-) create mode 100644 tests/MemoryPack.Tests/CSharpUnionTest.cs diff --git a/.github/workflows/build-debug.yaml b/.github/workflows/build-debug.yaml index d3226a41..6fba2778 100644 --- a/.github/workflows/build-debug.yaml +++ b/.github/workflows/build-debug.yaml @@ -18,6 +18,14 @@ jobs: steps: - uses: Cysharp/Actions/.github/actions/checkout@main - uses: Cysharp/Actions/.github/actions/setup-dotnet@main + with: + dotnet-version: | + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + 11.0.x - run: dotnet build -c Release - run: dotnet test -c Release --no-build - run: dotnet pack -c Release --no-build -p:IncludeSymbols=true -o $GITHUB_WORKSPACE/artifacts @@ -48,6 +56,14 @@ jobs: # Run SourceGenerater to generate serialization code - uses: Cysharp/Actions/.github/actions/setup-dotnet@main + with: + dotnet-version: | + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + 11.0.x - run: dotnet build -c Debug # require build before run - name: Make sure generated files are exists. run: ls -lR "src/MemoryPack/bin/Debug/netstandard2.1" diff --git a/.github/workflows/build-release.yaml b/.github/workflows/build-release.yaml index 525396c5..ad9bdd21 100644 --- a/.github/workflows/build-release.yaml +++ b/.github/workflows/build-release.yaml @@ -50,6 +50,14 @@ jobs: with: ref: ${{ needs.update-packagejson.outputs.sha }} - uses: Cysharp/Actions/.github/actions/setup-dotnet@main + with: + dotnet-version: | + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + 11.0.x # pack nuget (.nupkg and .symbols.nupkg will be created) - run: dotnet build -c Release -p:Version=${{ needs.validate-release.outputs.tag }} - run: dotnet test -c Release --no-build @@ -88,6 +96,14 @@ jobs: # Run SourceGenerater to generate serialization code - uses: Cysharp/Actions/.github/actions/setup-dotnet@main + with: + dotnet-version: | + 6.0.x + 7.0.x + 8.0.x + 9.0.x + 10.0.x + 11.0.x - run: dotnet build -c Debug # require build before run - name: Make sure generated files are exists. run: ls -lR "src/MemoryPack/bin/Debug/netstandard2.1" diff --git a/src/MemoryPack.Core/Attributes.cs b/src/MemoryPack.Core/Attributes.cs index 9ace47c3..89731ea6 100644 --- a/src/MemoryPack.Core/Attributes.cs +++ b/src/MemoryPack.Core/Attributes.cs @@ -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; } diff --git a/src/MemoryPack.Generator/DiagnosticDescriptors.cs b/src/MemoryPack.Generator/DiagnosticDescriptors.cs index 50a77087..78557f39 100644 --- a/src/MemoryPack.Generator/DiagnosticDescriptors.cs +++ b/src/MemoryPack.Generator/DiagnosticDescriptors.cs @@ -340,4 +340,20 @@ internal static class DiagnosticDescriptors category: Category, defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); + + public static readonly DiagnosticDescriptor CSharpUnionTagsMustMatchCases = new( + id: "MEMPACK043", + 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: "MEMPACK044", + 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); } diff --git a/src/MemoryPack.Generator/Extensions.cs b/src/MemoryPack.Generator/Extensions.cs index c4a2de13..aabe2015 100644 --- a/src/MemoryPack.Generator/Extensions.cs +++ b/src/MemoryPack.Generator/Extensions.cs @@ -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; diff --git a/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs b/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs index d17735fa..04d12622 100644 --- a/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs +++ b/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs @@ -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); @@ -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(); 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; } @@ -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); diff --git a/src/MemoryPack.Generator/MemoryPackGenerator.Parser.cs b/src/MemoryPack.Generator/MemoryPackGenerator.Parser.cs index 0806cd14..03e7646f 100644 --- a/src/MemoryPack.Generator/MemoryPackGenerator.Parser.cs +++ b/src/MemoryPack.Generator/MemoryPackGenerator.Parser.cs @@ -57,6 +57,8 @@ public partial class TypeMeta public bool IsUnmanagedType { get; } public bool IsUnion { get; } public bool IsRecord { get; } + /// C# union declaration + public bool IsCSharpUnion { get; } public bool IsInterfaceOrAbstract { get; } public IMethodSymbol? Constructor { get; } public MethodMeta[] OnSerializing { get; } @@ -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 }) @@ -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(); + } + 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)) @@ -533,6 +542,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)); @@ -601,6 +616,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; } diff --git a/src/MemoryPack.Generator/MemoryPackGenerator.cs b/src/MemoryPack.Generator/MemoryPackGenerator.cs index 760a4c0a..0cdeeeca 100644 --- a/src/MemoryPack.Generator/MemoryPackGenerator.cs +++ b/src/MemoryPack.Generator/MemoryPackGenerator.cs @@ -72,11 +72,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) => { diff --git a/tests/MemoryPack.Tests/CSharpUnionTest.cs b/tests/MemoryPack.Tests/CSharpUnionTest.cs new file mode 100644 index 00000000..e795e98a --- /dev/null +++ b/tests/MemoryPack.Tests/CSharpUnionTest.cs @@ -0,0 +1,231 @@ +#if NET11_0_OR_GREATER +using System; +using System.Linq; + +namespace MemoryPack.Tests; + +[MemoryPackable] +public partial record CSharpUnionCat(string Name); + +[MemoryPackable] +public partial record CSharpUnionDog(string Name, int Age); + +[MemoryPackable] +public partial union CSharpUnionPet(CSharpUnionCat, CSharpUnionDog, int?, string); + +[MemoryPackable] +public partial union CSharpUnionResult(T, Exception); + +[MemoryPackable] +public partial class CSharpUnionHolder +{ + public CSharpUnionPet Pet { get; set; } + public CSharpUnionPet[]? Pets { get; set; } + public CSharpUnionPet? MaybePet { get; set; } +} + +[MemoryPackable] +public partial union CSharpUnionV1(int, string); + +[MemoryPackable] +public partial union CSharpUnionV2(int, string, CSharpUnionCat); + +[MemoryPackable] +public partial union CSharpUnionWithBody(int, string) +{ + public static int SerializingCount; + public static int DeserializedCount; + + public CSharpUnionWithBody() : this(1) { } + + public CSharpUnionWithBody(int a, int b) : this(a + b) { } + + public string Description => Value?.ToString() ?? ""; + + [MemoryPackOnSerializing] + static void OnSerializing() => SerializingCount++; + + [MemoryPackOnDeserialized] + static void OnDeserialized() => DeserializedCount++; +} + +public partial class CSharpUnionContainer +{ + [MemoryPackable] + public partial union Nested(int, string); +} + +[MemoryPackable] +public partial union CSharpUnionOuter(CSharpUnionOuter.Inner, int) +{ + [MemoryPackable] + public partial record Inner(string Name); +} + +[MemoryPackable] +public partial union CSharpUnionOfUnion(CSharpUnionPet, long); + +[MemoryPackable] +public partial record CSharpUnionBase(string Name); + +[MemoryPackable] +public partial record CSharpUnionDerived(string Name, int Age) : CSharpUnionBase(Name); + +// derived case first, as the first matching case is used +[MemoryPackable] +public partial union CSharpUnionOverlap(CSharpUnionDerived, CSharpUnionBase); + +[MemoryPackable] +[MemoryPackUnion(10, typeof(int?))] +[MemoryPackUnion(20, typeof(string))] +public partial union CSharpUnionTagged(int?, string); + +// same tags as CSharpUnionTagged, cases reordered +[MemoryPackable] +[MemoryPackUnion(20, typeof(string))] +[MemoryPackUnion(10, typeof(int?))] +public partial union CSharpUnionTaggedReordered(string, int?); + +[MemoryPackable] +public partial union CSharpUnionTuple((int, string), long); + +public class CSharpUnionTest +{ + static CSharpUnionPet RoundTrip(CSharpUnionPet value) + { + return MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(value)); + } + + [Fact] + public void Cases() + { + RoundTrip(new CSharpUnionCat("Tom")).Value.Should().Be(new CSharpUnionCat("Tom")); + RoundTrip(new CSharpUnionDog("Rex", 3)).Value.Should().Be(new CSharpUnionDog("Rex", 3)); + RoundTrip((int?)42).Value.Should().Be(42); + RoundTrip("foo").Value.Should().Be("foo"); + } + + [Fact] + public void Null() + { + RoundTrip(default).Value.Should().BeNull(); + RoundTrip((int?)null).Value.Should().BeNull(); + } + + [Fact] + public void Tag() + { + // union header then value + MemoryPackSerializer.Serialize(new CSharpUnionDog("Rex", 3))[0].Should().Be(1); + MemoryPackSerializer.Serialize(default).Should().Equal(MemoryPackCode.NullObject); + } + + [Fact] + public void Generic() + { + var bin = MemoryPackSerializer.Serialize>(10); + MemoryPackSerializer.Deserialize>(bin).Value.Should().Be(10); + } + + [Fact] + public void Member() + { + var holder = new CSharpUnionHolder { Pet = new CSharpUnionCat("Tom"), Pets = [new CSharpUnionDog("Rex", 3), default, "foo"] }; + var result = MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(holder))!; + result.Pet.Value.Should().Be(new CSharpUnionCat("Tom")); + result.Pets!.Select(x => x.Value).Should().Equal(new CSharpUnionDog("Rex", 3), null, "foo"); + result.MaybePet.Should().BeNull(); + + holder.MaybePet = "bar"; + MemoryPackSerializer.Deserialize(MemoryPackSerializer.Serialize(holder))!.MaybePet!.Value.Value.Should().Be("bar"); + } + + [Fact] + public void AddedCase() + { + var bin = MemoryPackSerializer.Serialize("foo"); + MemoryPackSerializer.Deserialize(bin).Value.Should().Be("foo"); + } + + [Fact] + public void UnknownTag() + { + var bin = MemoryPackSerializer.Serialize(new CSharpUnionCat("Tom")); + var action = () => MemoryPackSerializer.Deserialize(bin); + action.Should().Throw(); + } + + [Fact] + public void Body() + { + var serializing = CSharpUnionWithBody.SerializingCount; + var deserialized = CSharpUnionWithBody.DeserializedCount; + + var bin = MemoryPackSerializer.Serialize("foo"); + bin.Should().Equal(MemoryPackSerializer.Serialize("foo")); + MemoryPackSerializer.Deserialize(bin).Value.Should().Be("foo"); + + CSharpUnionWithBody.SerializingCount.Should().Be(serializing + 1); + CSharpUnionWithBody.DeserializedCount.Should().Be(deserialized + 1); + } + + [Fact] + public void Nested() + { + var bin = MemoryPackSerializer.Serialize("foo"); + MemoryPackSerializer.Deserialize(bin).Value.Should().Be("foo"); + + var bin2 = MemoryPackSerializer.Serialize(new CSharpUnionOuter.Inner("Tom")); + MemoryPackSerializer.Deserialize(bin2).Value.Should().Be(new CSharpUnionOuter.Inner("Tom")); + } + + [Fact] + public void UnionCase() + { + var bin = MemoryPackSerializer.Serialize((CSharpUnionPet)new CSharpUnionCat("Tom")); + var result = MemoryPackSerializer.Deserialize(bin).Value; + result.Should().BeOfType().Which.Value.Should().Be(new CSharpUnionCat("Tom")); + } + + [Fact] + public void OverlappingCases() + { + var derived = MemoryPackSerializer.Serialize(new CSharpUnionDerived("Rex", 3)); + derived[0].Should().Be(0); + MemoryPackSerializer.Deserialize(derived).Value.Should().Be(new CSharpUnionDerived("Rex", 3)); + + var baseValue = MemoryPackSerializer.Serialize(new CSharpUnionBase("Tom")); + baseValue[0].Should().Be(1); + MemoryPackSerializer.Deserialize(baseValue).Value.Should().Be(new CSharpUnionBase("Tom")); + } + + [Fact] + public void ExplicitTag() + { + var bin = MemoryPackSerializer.Serialize("foo"); + bin[0].Should().Be(20); + MemoryPackSerializer.Deserialize(bin).Value.Should().Be("foo"); + + var bin2 = MemoryPackSerializer.Serialize((int?)42); + bin2[0].Should().Be(10); + MemoryPackSerializer.Deserialize(bin2).Value.Should().Be(42); + } + + [Fact] + public void ExplicitTagReordered() + { + var bin = MemoryPackSerializer.Serialize("foo"); + MemoryPackSerializer.Deserialize(bin).Value.Should().Be("foo"); + + var bin2 = MemoryPackSerializer.Serialize((int?)42); + MemoryPackSerializer.Deserialize(bin2).Value.Should().Be(42); + } + + [Fact] + public void TupleCase() + { + var bin = MemoryPackSerializer.Serialize((1, "foo")); + MemoryPackSerializer.Deserialize(bin).Value.Should().Be((1, "foo")); + } +} +#endif diff --git a/tests/MemoryPack.Tests/MemoryPack.Tests.csproj b/tests/MemoryPack.Tests/MemoryPack.Tests.csproj index 313cbe3e..570a0250 100644 --- a/tests/MemoryPack.Tests/MemoryPack.Tests.csproj +++ b/tests/MemoryPack.Tests/MemoryPack.Tests.csproj @@ -1,7 +1,9 @@  - net8.0 + net8.0 + + $(TargetFrameworks);net11.0 enable true diff --git a/tests/MemoryPack.Tests/SourceGeneratorTests/GeneratorDiagnosticsTest.cs b/tests/MemoryPack.Tests/SourceGeneratorTests/GeneratorDiagnosticsTest.cs index 9ba79cb2..0b74f0f7 100644 --- a/tests/MemoryPack.Tests/SourceGeneratorTests/GeneratorDiagnosticsTest.cs +++ b/tests/MemoryPack.Tests/SourceGeneratorTests/GeneratorDiagnosticsTest.cs @@ -704,6 +704,21 @@ public partial struct NestedStruct } """); } + + [Fact] + public void MEMPACK044_UnionOnStructMustBeCSharpUnion() + { + Compile(44, """ +using MemoryPack; + +[MemoryPackable] +[MemoryPackUnion(0, typeof(int))] +public partial struct Tester +{ + public int I1 { get; set; } +} +"""); + } } #endif From 34d0582b86963663cdee74355c40ea9036e9b978 Mon Sep 17 00:00:00 2001 From: pixsperdavid Date: Fri, 13 Nov 2026 10:45:25 +0000 Subject: [PATCH 2/2] Revert workflow changes Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build-debug.yaml | 16 ---------------- .github/workflows/build-release.yaml | 16 ---------------- 2 files changed, 32 deletions(-) diff --git a/.github/workflows/build-debug.yaml b/.github/workflows/build-debug.yaml index 6fba2778..d3226a41 100644 --- a/.github/workflows/build-debug.yaml +++ b/.github/workflows/build-debug.yaml @@ -18,14 +18,6 @@ jobs: steps: - uses: Cysharp/Actions/.github/actions/checkout@main - uses: Cysharp/Actions/.github/actions/setup-dotnet@main - with: - dotnet-version: | - 6.0.x - 7.0.x - 8.0.x - 9.0.x - 10.0.x - 11.0.x - run: dotnet build -c Release - run: dotnet test -c Release --no-build - run: dotnet pack -c Release --no-build -p:IncludeSymbols=true -o $GITHUB_WORKSPACE/artifacts @@ -56,14 +48,6 @@ jobs: # Run SourceGenerater to generate serialization code - uses: Cysharp/Actions/.github/actions/setup-dotnet@main - with: - dotnet-version: | - 6.0.x - 7.0.x - 8.0.x - 9.0.x - 10.0.x - 11.0.x - run: dotnet build -c Debug # require build before run - name: Make sure generated files are exists. run: ls -lR "src/MemoryPack/bin/Debug/netstandard2.1" diff --git a/.github/workflows/build-release.yaml b/.github/workflows/build-release.yaml index ad9bdd21..525396c5 100644 --- a/.github/workflows/build-release.yaml +++ b/.github/workflows/build-release.yaml @@ -50,14 +50,6 @@ jobs: with: ref: ${{ needs.update-packagejson.outputs.sha }} - uses: Cysharp/Actions/.github/actions/setup-dotnet@main - with: - dotnet-version: | - 6.0.x - 7.0.x - 8.0.x - 9.0.x - 10.0.x - 11.0.x # pack nuget (.nupkg and .symbols.nupkg will be created) - run: dotnet build -c Release -p:Version=${{ needs.validate-release.outputs.tag }} - run: dotnet test -c Release --no-build @@ -96,14 +88,6 @@ jobs: # Run SourceGenerater to generate serialization code - uses: Cysharp/Actions/.github/actions/setup-dotnet@main - with: - dotnet-version: | - 6.0.x - 7.0.x - 8.0.x - 9.0.x - 10.0.x - 11.0.x - run: dotnet build -c Debug # require build before run - name: Make sure generated files are exists. run: ls -lR "src/MemoryPack/bin/Debug/netstandard2.1"