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
5 changes: 5 additions & 0 deletions sandbox/NativeAot/NativeAot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,9 @@
<IlcFoldIdenticalMethodBodies>true</IlcFoldIdenticalMethodBodies>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\MemoryPack.Core\MemoryPack.Core.csproj" />
<ProjectReference Include="..\..\src\MemoryPack.Generator\MemoryPack.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>

</Project>
17 changes: 17 additions & 0 deletions sandbox/NativeAot/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System.Buffers;

using MemoryPack;

// require this unused line for reproduce error?
var bufferWriter = new ArrayBufferWriter<byte>();

Expand All @@ -9,6 +11,21 @@
formatter.Serialize<ArrayBufferWriter<byte>>(ref mc);


var arrayPayload = new byte[] { 1, 0, 0, 0, 1, 1, 0, 0, 0, 65, 0 };
var items = MemoryPackSerializer.Deserialize<Item[]>(arrayPayload);
Console.WriteLine(items![0].Name);

[MemoryPackable]
public sealed partial record Item(string Name);

public sealed partial record Item
{
static partial void StaticConstructor()
{
Console.WriteLine("Item static constructor");
}
}

public interface IMemoryPackable2<T>
{
static abstract void Serialize<TBufferWriter>(scoped ref T? value)
Expand Down
80 changes: 71 additions & 9 deletions src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,31 @@ public void Emit(StringBuilder writer, IGeneratorContext context)
? "Serialize(ref MemoryPackWriter"
: "Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter>";

var formatterRegistrationBody = EmitFormatterRegistrationBody(context, " ", TypeName, registerBody);
var aotFormatterRegistration = "";
// NativeAOT may trim the static interface implementation when a model is only used as a collection element.
if (context.IsNet7OrGreater && !Symbol.IsGenericType && IsAccessibleFromTopLevel(Symbol))
{
var fullTypeName = Symbol.FullyQualifiedToString();
var aotRegisterBody = $"global::MemoryPack.MemoryPackFormatterProvider.Register(new global::MemoryPack.Formatters.MemoryPackableFormatter<{fullTypeName}>());";
var aotRegistrationBody = EmitFormatterRegistrationBody(context, " ", fullTypeName, aotRegisterBody);
var registrationName = "__MemoryPackAotRegistration_" + GetStableTypeHash(fullTypeName).ToString("X16");

aotFormatterRegistration = $$"""
internal static class {{registrationName}}
{
[global::System.Runtime.CompilerServices.ModuleInitializer]
internal static void RegisterFormatter()
{
if (!global::System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported)
{
{{aotRegistrationBody}}
}
}
}
""";
}

foreach (var declaration in containingTypeDeclarations)
{
writer.AppendLine(declaration);
Expand All @@ -395,15 +420,7 @@ public void Emit(StringBuilder writer, IGeneratorContext context)
[global::MemoryPack.Internal.Preserve]
{{staticRegisterFormatterMethod}}RegisterFormatter()
{
if (!global::MemoryPack.MemoryPackFormatterProvider.IsRegistered<{{TypeName}}>())
{
{{registerBody}}
}
if (!global::MemoryPack.MemoryPackFormatterProvider.IsRegistered<{{TypeName}}[]>())
{
global::MemoryPack.MemoryPackFormatterProvider.Register(new global::MemoryPack.Formatters.ArrayFormatter<{{TypeName}}>());
}
{{EmitAdditionalRegisterFormatter(" ", context)}}
{{formatterRegistrationBody}}
}

[global::MemoryPack.Internal.Preserve]
Expand Down Expand Up @@ -459,6 +476,11 @@ public override void Deserialize(ref MemoryPackReader reader, {{scopedRef}} {{Ty
{
writer.AppendLine("}");
}

if (aotFormatterRegistration.Length > 0)
{
writer.AppendLine(aotFormatterRegistration);
}
}

private string EmitDeserializeBody()
Expand Down Expand Up @@ -632,6 +654,46 @@ string EmitAdditionalRegisterFormatter(string indent, IGeneratorContext context)
return sb.ToString();
}

string EmitFormatterRegistrationBody(IGeneratorContext context, string indent, string typeName, string registerBody)
{
var sb = new StringBuilder();
sb.AppendLine($"{indent}if (!global::MemoryPack.MemoryPackFormatterProvider.IsRegistered<{typeName}>())");
sb.AppendLine($"{indent}{{");
sb.AppendLine($"{indent} {registerBody}");
sb.AppendLine($"{indent}}}");
sb.AppendLine($"{indent}if (!global::MemoryPack.MemoryPackFormatterProvider.IsRegistered<{typeName}[]>())");
sb.AppendLine($"{indent}{{");
sb.AppendLine($"{indent} global::MemoryPack.MemoryPackFormatterProvider.Register(new global::MemoryPack.Formatters.ArrayFormatter<{typeName}>());");
sb.AppendLine($"{indent}}}");
sb.Append(EmitAdditionalRegisterFormatter(indent, context));
return sb.ToString();
}

static ulong GetStableTypeHash(string value)
{
unchecked
{
ulong hash = 14695981039346656037;
foreach (var character in value)
{
hash = (hash ^ character) * 1099511628211UL;
}
return hash;
}
}

static bool IsAccessibleFromTopLevel(INamedTypeSymbol symbol)
{
for (var current = symbol; current is not null; current = current.ContainingType)
{
if (current.DeclaredAccessibility is Accessibility.Private or Accessibility.Protected or Accessibility.ProtectedAndInternal)
{
return false;
}
}
return true;
}

string EmitCustomFormatters()
{
var sb = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Linq;
using MemoryPack.Tests.Utils;

namespace MemoryPack.Tests.SourceGeneratorTests;

public class NativeAotRegistrationTest
{
[Fact]
public void EmitsAotRegistrationForNongenericModels()
{
var (compilation, diagnostics) = CSharpGeneratorRunner.RunGenerator("""
using MemoryPack;

[MemoryPackable]
public partial record Item(string Name);
""");

diagnostics.Should().BeEmpty();
var generatedCode = compilation.SyntaxTrees
.Select(x => x.GetText().ToString())
.First(x => x.Contains("__MemoryPackAotRegistration_", StringComparison.Ordinal));
generatedCode.Should().Contain("RuntimeFeature.IsDynamicCodeSupported")
.And.Contain("Register(new global::MemoryPack.Formatters.MemoryPackableFormatter<global::Item>())")
.And.Contain("new global::MemoryPack.Formatters.ArrayFormatter<global::Item>()");
}

[Fact]
public void DoesNotEmitAotRegistrationForGenericModels()
{
var (compilation, diagnostics) = CSharpGeneratorRunner.RunGenerator("""
using MemoryPack;

[MemoryPackable]
public partial record Item<T>(T Value);
""");

diagnostics.Should().BeEmpty();
compilation.SyntaxTrees
.Select(x => x.GetText().ToString())
.Should()
.NotContain(x => x.Contains("__MemoryPackAotRegistration_", StringComparison.Ordinal));
}
}