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

Add support for nested explicit wrappers #140

Merged
merged 1 commit into from
Sep 6, 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
4 changes: 2 additions & 2 deletions src/generator/Generator.Impl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,9 @@ private static void GenerateISerializeWrapImpl(
{
var typeDeclContext = new TypeDeclContext(typeDecl);
var newType = SyntaxFactory.ParseMemberDeclaration($$"""
partial record struct {{wrapperName}}({{wrappedName}} Value) : ISerializeWrap<{{wrappedName}}, {{wrapperName}}>
partial record struct {{wrapperName}}({{wrappedName}} Value) : Serde.ISerializeWrap<{{wrappedName}}, {{wrapperName}}>
{
{{wrapperName}} ISerializeWrap<{{wrappedName}}, {{wrapperName}}>.Wrap({{wrappedName}} value) => new(value);
{{wrapperName}} Serde.ISerializeWrap<{{wrappedName}}, {{wrapperName}}>.Wrap({{wrappedName}} value) => new(value);
}
""")!;
newType = typeDeclContext.WrapNewType(newType);
Expand Down
36 changes: 36 additions & 0 deletions src/generator/Generator.Wrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Serde.Diagnostics;
using static Serde.WellKnownTypes;
using System.Reflection.Metadata.Ecma335;

namespace Serde
{
Expand Down Expand Up @@ -205,6 +206,23 @@ INamedTypeSymbol t when TryGetWrapperName(t, context, usage) is { } tuple
if (TryGetExplicitWrapperType(member, usage, context) is {} wrapperType)
{
var memberType = member.Type;
if (usage.HasFlag(SerdeUsage.Serialize))
{
var ctor = wrapperType.Constructors.Where(c => c.Parameters.Length == 1).SingleOrDefault();
if (ctor is { Parameters: [{ } typeArg] } && typeArg.Type.Equals(memberType, SymbolEqualityComparer.Default))
{
return ParseTypeName(wrapperType.ToDisplayString());
}
}
else if (usage.HasFlag(SerdeUsage.Deserialize))
{
var deserialize = context.Compilation.GetTypeByMetadataName("Serde.IDeserialize`1")?.Construct(memberType);
if (wrapperType.Interfaces.Contains(deserialize, SymbolEqualityComparer.Default))
{
return ParseTypeName(wrapperType.ToDisplayString());
}
}

var typeArgs = memberType switch
{
INamedTypeSymbol n => n.TypeArguments,
Expand Down Expand Up @@ -265,6 +283,24 @@ INamedTypeSymbol t when TryGetWrapperName(t, context, usage) is { } tuple
// TODO: produce a warning?
return null;
}
else if (attr is { AttributeClass.Name: nameof(SerdeMemberOptions), NamedArguments: { } named })
{
foreach (var arg in named)
{
if (usage.HasFlag(SerdeUsage.Serialize)
&& arg is { Key: nameof(SerdeMemberOptions.WrapperSerialize),
Value.Value: INamedTypeSymbol wrapperType })
{
return wrapperType;
}
if (usage.HasFlag(SerdeUsage.Deserialize)
&& arg is { Key: nameof(SerdeMemberOptions.WrapperDeserialize),
Value.Value: INamedTypeSymbol wrapperType2 })
{
return wrapperType2;
}
}
}
}
return null;
}
Expand Down
10 changes: 10 additions & 0 deletions src/serde/Attributes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,16 @@ sealed class SerdeMemberOptions : Attribute
/// Skip deserialization of this member.
/// </summary>
public bool SkipDeserialize { get; init; } = false;

/// <summary>
/// Type to use as the wrapper for the ISerialize implementation.
/// </summary>
public Type? WrapperSerialize { get; init; } = null;

/// <summary>
/// Type to use as the wrapper for the IDeserialize implementation.
/// </summary>
public Type? WrapperDeserialize { get; init; } = null;
}

/// <summary>
Expand Down
22 changes: 22 additions & 0 deletions test/Serde.Generation.Test/DeserializeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,28 @@ namespace Serde.Test
[UsesVerify]
public class DeserializeTests
{
[Fact]
public Task NestedExplicitDeserializeWrapper()
{
var src = """

using Serde;
using System.Collections.Immutable;
using System.Collections.Specialized;

[GenerateDeserialize(Through = nameof(Value))]
readonly partial record struct SectionWrap(BitVector32.Section Value);

[GenerateDeserialize]
partial struct S
{
[SerdeMemberOptions(WrapperDeserialize = typeof(ImmutableArrayWrap.DeserializeImpl<BitVector32.Section, SectionWrap>))]
public ImmutableArray<BitVector32.Section> Sections;
}

""";
return VerifyMultiFile(src);
}
[Fact]
public Task DeserializeOnlyWrap()
{
Expand Down
10 changes: 2 additions & 8 deletions test/Serde.Generation.Test/GeneratorTestUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,9 @@ public static async Task<VerifyResult> VerifyGeneratedCode(string src, VerifySet
var generatorInstance = new SerdeImplRoslynGenerator();
GeneratorDriver driver = CSharpGeneratorDriver.Create(generatorInstance);
var comp = await CreateCompilation(src, additionalRefs);
var diags = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ToList();
if (diags.Any())
{
var diagSettings = new VerifySettings(settings);
diagSettings.UseDirectory(settings.Directory + "_diagnostics");
_ = await Verifier.Verify(diags, diagSettings);
}
driver = driver.RunGenerators(comp);
return await Verifier.Verify(driver, settings);
var results = await Verifier.Verify(driver, settings);
return results;
}

public static async Task<CSharpCompilation> CreateCompilation(string src, MetadataReference[]? additionalRefs = null)
Expand Down
23 changes: 23 additions & 0 deletions test/Serde.Generation.Test/SerializeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,29 @@ namespace Serde.Test
[UsesVerify]
public class SerializeTests
{
[Fact]
public Task NestedExplicitSerializeWrapper()
{
var src = """

using Serde;
using System.Collections.Immutable;
using System.Collections.Specialized;

[GenerateSerialize(Through = nameof(Value))]
readonly partial record struct SectionWrap(BitVector32.Section Value);

[GenerateSerialize]
partial struct S
{
[SerdeMemberOptions(WrapperSerialize = typeof(ImmutableArrayWrap.SerializeImpl<BitVector32.Section, SectionWrap>))]
public ImmutableArray<BitVector32.Section> Sections;
}

""";
return VerifyMultiFile(src);
}

[Fact]
public Task SerializeOnlyWrapper()
{
Expand Down
27 changes: 27 additions & 0 deletions test/Serde.Generation.Test/WrapperTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,33 @@ namespace Serde.Test
[UsesVerify]
public class WrapperTests
{
[Fact]
public Task NestedExplicitWrapper()
{
var src = """

using Serde;
using System.Collections.Immutable;
using System.Collections.Specialized;

partial class Outer
{
[GenerateSerde(Through = nameof(Value))]
readonly partial record struct SectionWrap(BitVector32.Section Value);
}

[GenerateSerde]
partial struct S
{
[SerdeMemberOptions(
WrapperSerialize = typeof(ImmutableArrayWrap.SerializeImpl<BitVector32.Section, Outer.SectionWrap>),
WrapperDeserialize = typeof(ImmutableArrayWrap.DeserializeImpl<BitVector32.Section, Outer.SectionWrap>))]
public ImmutableArray<BitVector32.Section> Sections;
}
""";
return VerifyMultiFile(src);
}

[Fact]
public Task GenerateSerdeWrap()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
//HintName: S.IDeserialize.cs

#nullable enable
using System;
using Serde;

partial struct S : Serde.IDeserialize<S>
{
static S Serde.IDeserialize<S>.Deserialize<D>(ref D deserializer)
{
var visitor = new SerdeVisitor();
var fieldNames = new[]
{
"Sections"
};
return deserializer.DeserializeType<S, SerdeVisitor>("S", fieldNames, visitor);
}

private sealed class SerdeVisitor : Serde.IDeserializeVisitor<S>
{
public string ExpectedTypeName => "S";

private struct FieldNameVisitor : Serde.IDeserialize<byte>, Serde.IDeserializeVisitor<byte>
{
public static byte Deserialize<D>(ref D deserializer)
where D : IDeserializer => deserializer.DeserializeString<byte, FieldNameVisitor>(new FieldNameVisitor());
public string ExpectedTypeName => "string";

byte Serde.IDeserializeVisitor<byte>.VisitString(string s) => VisitUtf8Span(System.Text.Encoding.UTF8.GetBytes(s));
public byte VisitUtf8Span(System.ReadOnlySpan<byte> s)
{
switch (s[0])
{
case (byte)'s'when s.SequenceEqual("sections"u8):
return 1;
default:
return 0;
}
}
}

S Serde.IDeserializeVisitor<S>.VisitDictionary<D>(ref D d)
{
System.Collections.Immutable.ImmutableArray<System.Collections.Specialized.BitVector32.Section> _l_sections = default !;
byte _r_assignedValid = 0b0;
while (d.TryGetNextKey<byte, FieldNameVisitor>(out byte key))
{
switch (key)
{
case 1:
_l_sections = d.GetNextValue<System.Collections.Immutable.ImmutableArray<System.Collections.Specialized.BitVector32.Section>, Serde.ImmutableArrayWrap.DeserializeImpl<System.Collections.Specialized.BitVector32.Section, SectionWrap>>();
_r_assignedValid |= ((byte)1) << 0;
break;
}
}

if (_r_assignedValid != 0b1)
{
throw new Serde.InvalidDeserializeValueException("Not all members were assigned");
}

var newType = new S()
{
Sections = _l_sections,
};
return newType;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
//HintName: SectionWrap.IDeserialize.cs

#nullable enable
using System;
using Serde;

partial record struct SectionWrap : Serde.IDeserialize<System.Collections.Specialized.BitVector32.Section>
{
static System.Collections.Specialized.BitVector32.Section Serde.IDeserialize<System.Collections.Specialized.BitVector32.Section>.Deserialize<D>(ref D deserializer)
{
var visitor = new SerdeVisitor();
var fieldNames = new[]
{
"Mask",
"Offset"
};
return deserializer.DeserializeType<System.Collections.Specialized.BitVector32.Section, SerdeVisitor>("Section", fieldNames, visitor);
}

private sealed class SerdeVisitor : Serde.IDeserializeVisitor<System.Collections.Specialized.BitVector32.Section>
{
public string ExpectedTypeName => "System.Collections.Specialized.BitVector32.Section";

private struct FieldNameVisitor : Serde.IDeserialize<byte>, Serde.IDeserializeVisitor<byte>
{
public static byte Deserialize<D>(ref D deserializer)
where D : IDeserializer => deserializer.DeserializeString<byte, FieldNameVisitor>(new FieldNameVisitor());
public string ExpectedTypeName => "string";

byte Serde.IDeserializeVisitor<byte>.VisitString(string s) => VisitUtf8Span(System.Text.Encoding.UTF8.GetBytes(s));
public byte VisitUtf8Span(System.ReadOnlySpan<byte> s)
{
switch (s[0])
{
case (byte)'m'when s.SequenceEqual("mask"u8):
return 1;
case (byte)'o'when s.SequenceEqual("offset"u8):
return 2;
default:
return 0;
}
}
}

System.Collections.Specialized.BitVector32.Section Serde.IDeserializeVisitor<System.Collections.Specialized.BitVector32.Section>.VisitDictionary<D>(ref D d)
{
short _l_mask = default !;
short _l_offset = default !;
byte _r_assignedValid = 0b0;
while (d.TryGetNextKey<byte, FieldNameVisitor>(out byte key))
{
switch (key)
{
case 1:
_l_mask = d.GetNextValue<short, Int16Wrap>();
_r_assignedValid |= ((byte)1) << 0;
break;
case 2:
_l_offset = d.GetNextValue<short, Int16Wrap>();
_r_assignedValid |= ((byte)1) << 1;
break;
}
}

if (_r_assignedValid != 0b11)
{
throw new Serde.InvalidDeserializeValueException("Not all members were assigned");
}

var newType = new System.Collections.Specialized.BitVector32.Section()
{
Mask = _l_mask,
Offset = _l_offset,
};
return newType;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//HintName: S.ISerialize.cs

#nullable enable
using System;
using Serde;

partial struct S : Serde.ISerialize
{
void Serde.ISerialize.Serialize(ISerializer serializer)
{
var type = serializer.SerializeType("S", 1);
type.SerializeField("sections"u8, new Serde.ImmutableArrayWrap.SerializeImpl<System.Collections.Specialized.BitVector32.Section, SectionWrap>(this.Sections));
type.End();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//HintName: SectionWrap.ISerialize.cs

#nullable enable
using System;
using Serde;

partial record struct SectionWrap : Serde.ISerialize
{
void Serde.ISerialize.Serialize(ISerializer serializer)
{
var type = serializer.SerializeType("Section", 2);
type.SerializeField("mask"u8, new Int16Wrap(Value.Mask));
type.SerializeField("offset"u8, new Int16Wrap(Value.Offset));
type.End();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
//HintName: SectionWrap.ISerializeWrap.cs

partial record struct SectionWrap(System.Collections.Specialized.BitVector32.Section Value) : Serde.ISerializeWrap<System.Collections.Specialized.BitVector32.Section, SectionWrap>
{
SectionWrap Serde.ISerializeWrap<System.Collections.Specialized.BitVector32.Section, SectionWrap>.Wrap(System.Collections.Specialized.BitVector32.Section value) => new(value);
}
Loading
Loading