diff --git a/sandbox/NativeAot/NativeAot.csproj b/sandbox/NativeAot/NativeAot.csproj
index 8e44189b..3a975332 100644
--- a/sandbox/NativeAot/NativeAot.csproj
+++ b/sandbox/NativeAot/NativeAot.csproj
@@ -15,4 +15,9 @@
true
+
+
+
+
+
diff --git a/sandbox/NativeAot/Program.cs b/sandbox/NativeAot/Program.cs
index b862e83a..b5a48f93 100644
--- a/sandbox/NativeAot/Program.cs
+++ b/sandbox/NativeAot/Program.cs
@@ -1,5 +1,7 @@
using System.Buffers;
+using MemoryPack;
+
// require this unused line for reproduce error?
var bufferWriter = new ArrayBufferWriter();
@@ -9,6 +11,21 @@
formatter.Serialize>(ref mc);
+var arrayPayload = new byte[] { 1, 0, 0, 0, 1, 1, 0, 0, 0, 65, 0 };
+var items = MemoryPackSerializer.Deserialize- (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
{
static abstract void Serialize(scoped ref T? value)
diff --git a/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs b/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs
index d17735fa..e456501d 100644
--- a/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs
+++ b/src/MemoryPack.Generator/MemoryPackGenerator.Emitter.cs
@@ -374,6 +374,31 @@ public void Emit(StringBuilder writer, IGeneratorContext context)
? "Serialize(ref MemoryPackWriter"
: "Serialize(ref MemoryPackWriter";
+ 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);
@@ -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]
@@ -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()
@@ -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();
diff --git a/tests/MemoryPack.Tests/SourceGeneratorTests/NativeAotRegistrationTest.cs b/tests/MemoryPack.Tests/SourceGeneratorTests/NativeAotRegistrationTest.cs
new file mode 100644
index 00000000..2eac07c6
--- /dev/null
+++ b/tests/MemoryPack.Tests/SourceGeneratorTests/NativeAotRegistrationTest.cs
@@ -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())")
+ .And.Contain("new global::MemoryPack.Formatters.ArrayFormatter()");
+ }
+
+ [Fact]
+ public void DoesNotEmitAotRegistrationForGenericModels()
+ {
+ var (compilation, diagnostics) = CSharpGeneratorRunner.RunGenerator("""
+using MemoryPack;
+
+[MemoryPackable]
+public partial record Item(T Value);
+""");
+
+ diagnostics.Should().BeEmpty();
+ compilation.SyntaxTrees
+ .Select(x => x.GetText().ToString())
+ .Should()
+ .NotContain(x => x.Contains("__MemoryPackAotRegistration_", StringComparison.Ordinal));
+ }
+}