From da97ad05185305c3e91f4bf46e1cbc6d94691903 Mon Sep 17 00:00:00 2001 From: Andrew Arnott Date: Sat, 3 Dec 2022 14:46:23 -0700 Subject: [PATCH 1/2] Last of the nullable ref annotations This one may be a bit sloppy, as it is deep and complex Reflection code, and I don't have time to re-grok everything inside it. But if there are any inaccuracies, they are internal APIs, so they shouldn't adversely impact users. --- sandbox/DynamicCodeDumper/Program.cs | 2 +- .../Resolvers/DynamicObjectResolver.cs | 430 +++++++++--------- src/MessagePack/net6.0/PublicAPI.Shipped.txt | 18 +- .../netcoreapp3.1/PublicAPI.Shipped.txt | 18 +- .../netstandard2.0/PublicAPI.Shipped.txt | 18 +- 5 files changed, 238 insertions(+), 248 deletions(-) diff --git a/sandbox/DynamicCodeDumper/Program.cs b/sandbox/DynamicCodeDumper/Program.cs index 6aafc6079..d5299c5a7 100644 --- a/sandbox/DynamicCodeDumper/Program.cs +++ b/sandbox/DynamicCodeDumper/Program.cs @@ -43,7 +43,7 @@ private static void Main(string[] args) ////DynamicObjectResolver.Instance.GetFormatter(); ////DynamicObjectResolver.Instance.GetFormatter(); ////DynamicObjectResolver.Instance.GetFormatter(); - IMessagePackFormatter f = DynamicObjectResolverAllowPrivate.Instance.GetFormatter(); + IMessagePackFormatter f = DynamicObjectResolverAllowPrivate.Instance.GetFormatterWithVerify(); ////IMessagePackFormatter f = DynamicObjectResolver.Instance.GetFormatter(); ////DynamicObjectResolver.Instance.GetFormatter(); ////DynamicObjectResolver.Instance.GetFormatter(); diff --git a/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Resolvers/DynamicObjectResolver.cs b/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Resolvers/DynamicObjectResolver.cs index 69e6fdcb5..28533435a 100644 --- a/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Resolvers/DynamicObjectResolver.cs +++ b/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Resolvers/DynamicObjectResolver.cs @@ -3,11 +3,10 @@ #if !(UNITY_2018_3_OR_NEWER && NET_STANDARD_2_0) -#nullable disable - using System; using System.Buffers; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Reflection.Emit; @@ -16,7 +15,6 @@ using System.Threading; using MessagePack.Formatters; using MessagePack.Internal; -using MessagePack.Resolvers; #pragma warning disable SA1403 // File may only contain a single namespace @@ -59,14 +57,14 @@ public AssemblyBuilder Save() } #endif - public IMessagePackFormatter GetFormatter() + public IMessagePackFormatter? GetFormatter() { return FormatterCache.Formatter; } private static class FormatterCache { - public static readonly IMessagePackFormatter Formatter; + public static readonly IMessagePackFormatter? Formatter; static FormatterCache() { @@ -87,24 +85,24 @@ static FormatterCache() return; } - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); + Formatter = (IMessagePackFormatter?)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); return; } if (ti.IsAnonymous()) { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); + Formatter = (IMessagePackFormatter?)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); return; } - TypeInfo formatterTypeInfo; + TypeInfo? formatterTypeInfo; try { formatterTypeInfo = DynamicObjectTypeBuilder.BuildType(DynamicAssembly.Value, typeof(T), false, false); } catch (InitAccessorInGenericClassNotSupportedException) { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), false, false, false); + Formatter = (IMessagePackFormatter?)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), false, false, false); return; } @@ -129,14 +127,14 @@ private DynamicObjectResolverAllowPrivate() { } - public IMessagePackFormatter GetFormatter() + public IMessagePackFormatter? GetFormatter() { return FormatterCache.Formatter; } private static class FormatterCache { - internal static readonly IMessagePackFormatter Formatter; + internal static readonly IMessagePackFormatter? Formatter; static FormatterCache() { @@ -157,17 +155,17 @@ static FormatterCache() return; } - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); + Formatter = (IMessagePackFormatter?)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); return; } if (ti.IsAnonymous()) { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); + Formatter = (IMessagePackFormatter?)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); } else { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), false, false, true); + Formatter = (IMessagePackFormatter?)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), false, false, true); } } } @@ -200,14 +198,14 @@ public AssemblyBuilder Save() } #endif - public IMessagePackFormatter GetFormatter() + public IMessagePackFormatter? GetFormatter() { return FormatterCache.Formatter; } private static class FormatterCache { - public static readonly IMessagePackFormatter Formatter; + public static readonly IMessagePackFormatter? Formatter; static FormatterCache() { @@ -233,23 +231,23 @@ static FormatterCache() return; } - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); + Formatter = (IMessagePackFormatter?)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); return; } if (ti.IsAnonymous() || ti.HasPrivateCtorForSerialization()) { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); + Formatter = (IMessagePackFormatter?)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); return; } - TypeInfo formatterTypeInfo = DynamicObjectTypeBuilder.BuildType(DynamicAssembly.Value, typeof(T), true, true); + TypeInfo? formatterTypeInfo = DynamicObjectTypeBuilder.BuildType(DynamicAssembly.Value, typeof(T), true, true); if (formatterTypeInfo == null) { return; } - Formatter = (IMessagePackFormatter)Activator.CreateInstance(formatterTypeInfo.AsType()); + Formatter = (IMessagePackFormatter?)Activator.CreateInstance(formatterTypeInfo.AsType()); } } } @@ -261,14 +259,14 @@ public sealed class DynamicContractlessObjectResolverAllowPrivate : IFormatterRe { public static readonly DynamicContractlessObjectResolverAllowPrivate Instance = new DynamicContractlessObjectResolverAllowPrivate(); - public IMessagePackFormatter GetFormatter() + public IMessagePackFormatter? GetFormatter() { return FormatterCache.Formatter; } private static class FormatterCache { - internal static readonly IMessagePackFormatter Formatter; + internal static readonly IMessagePackFormatter? Formatter; static FormatterCache() { @@ -294,17 +292,17 @@ static FormatterCache() return; } - Formatter = (IMessagePackFormatter)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); + Formatter = (IMessagePackFormatter?)Activator.CreateInstance(typeof(StaticNullableFormatter<>).MakeGenericType(ti.AsType()), new object[] { innerFormatter }); return; } if (ti.IsAnonymous()) { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); + Formatter = (IMessagePackFormatter?)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, false); } else { - Formatter = (IMessagePackFormatter)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, true); + Formatter = (IMessagePackFormatter?)DynamicObjectTypeBuilder.BuildFormatterToDynamicMethod(typeof(T), true, true, true); } } } @@ -347,7 +345,7 @@ internal static class DynamicObjectTypeBuilder { typeof(MessagePack.Nil) }, }; - public static TypeInfo BuildType(DynamicAssembly assembly, Type type, bool forceStringKey, bool contractless) + public static TypeInfo? BuildType(DynamicAssembly assembly, Type type, bool forceStringKey, bool contractless) { if (ignoreTypes.Contains(type)) { @@ -368,10 +366,10 @@ public static TypeInfo BuildType(DynamicAssembly assembly, Type type, bool force using (MonoProtection.EnterRefEmitLock()) { Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type); - TypeBuilder typeBuilder = assembly.DefineType("MessagePack.Formatters." + SubtractFullNameRegex.Replace(type.FullName, string.Empty).Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType }); + TypeBuilder typeBuilder = assembly.DefineType("MessagePack.Formatters." + SubtractFullNameRegex.Replace(type.FullName!, string.Empty).Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType }); - FieldBuilder stringByteKeysField = null; - Dictionary customFormatterLookup = null; + FieldBuilder? stringByteKeysField = null; + Dictionary? customFormatterLookup = null; // string key needs string->int mapper for deserialize switch statement if (serializationInfo.IsStringKey) @@ -412,12 +410,11 @@ public static TypeInfo BuildType(DynamicAssembly assembly, Type type, bool force () => { il.EmitLoadThis(); - il.EmitLdfld(stringByteKeysField); + il.EmitLdfld(stringByteKeysField!); }, (index, member) => { - FieldInfo fi; - if (!customFormatterLookup.TryGetValue(member, out fi)) + if (!customFormatterLookup.TryGetValue(member, out FieldInfo? fi)) { return null; } @@ -447,8 +444,7 @@ public static TypeInfo BuildType(DynamicAssembly assembly, Type type, bool force il, (index, member) => { - FieldInfo fi; - if (!customFormatterLookup.TryGetValue(member, out fi)) + if (!customFormatterLookup.TryGetValue(member, out FieldInfo? fi)) { return null; } @@ -466,7 +462,7 @@ public static TypeInfo BuildType(DynamicAssembly assembly, Type type, bool force } } - public static object BuildFormatterToDynamicMethod(Type type, bool forceStringKey, bool contractless, bool allowPrivate) + public static object? BuildFormatterToDynamicMethod(Type type, bool forceStringKey, bool contractless, bool allowPrivate) { var serializationInfo = ObjectSerializationInfo.CreateOrNull(type, forceStringKey, contractless, allowPrivate, dynamicMethod: true); if (serializationInfo == null) @@ -477,25 +473,25 @@ public static object BuildFormatterToDynamicMethod(Type type, bool forceStringKe // internal delegate void AnonymousSerializeFunc(byte[][] stringByteKeysField, object[] customFormatters, ref MessagePackWriter writer, T value, MessagePackSerializerOptions options); // internal delegate T AnonymousDeserializeFunc(object[] customFormatters, ref MessagePackReader reader, MessagePackSerializerOptions options); var serialize = new DynamicMethod("Serialize", null, new[] { typeof(byte[][]), typeof(object[]), typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) }, type, true); - DynamicMethod deserialize = null; + DynamicMethod? deserialize = null; List stringByteKeysField = new List(); - List serializeCustomFormatters = new List(); - List deserializeCustomFormatters = new List(); + List serializeCustomFormatters = new List(); + List deserializeCustomFormatters = new List(); if (serializationInfo.IsStringKey) { var i = 0; foreach (ObjectSerializationInfo.EmittableMember item in serializationInfo.Members.Where(x => x.IsReadable)) { - stringByteKeysField.Add(Utilities.GetWriterBytes(item.StringKey, (ref MessagePackWriter writer, string arg) => writer.Write(arg), SequencePool.Shared)); + stringByteKeysField.Add(Utilities.GetWriterBytes(item.StringKey, (ref MessagePackWriter writer, string? arg) => writer.Write(arg), SequencePool.Shared)); i++; } } foreach (ObjectSerializationInfo.EmittableMember item in serializationInfo.Members.Where(x => x.IsReadable)) { - MessagePackFormatterAttribute attr = item.GetMessagePackFormatterAttribute(); + MessagePackFormatterAttribute? attr = item.GetMessagePackFormatterAttribute(); if (attr != null) { IMessagePackFormatter formatter = ResolverUtilities.ActivateFormatter(attr.FormatterType, attr.Arguments); @@ -510,7 +506,7 @@ public static object BuildFormatterToDynamicMethod(Type type, bool forceStringKe foreach (ObjectSerializationInfo.EmittableMember item in serializationInfo.Members) { // not only for writable because for use ctor. - MessagePackFormatterAttribute attr = item.GetMessagePackFormatterAttribute(); + MessagePackFormatterAttribute? attr = item.GetMessagePackFormatterAttribute(); if (attr != null) { IMessagePackFormatter formatter = ResolverUtilities.ActivateFormatter(attr.FormatterType, attr.Arguments); @@ -534,23 +530,20 @@ public static object BuildFormatterToDynamicMethod(Type type, bool forceStringKe }, (index, member) => { - if (serializeCustomFormatters.Count == 0) + if (serializeCustomFormatters.Count > 0 && serializeCustomFormatters[index] is object formatter) { - return null; + return () => + { + il.EmitLdarg(1); // read object[] + il.EmitLdc_I4(index); + il.Emit(OpCodes.Ldelem_Ref); // object + il.Emit(OpCodes.Castclass, formatter.GetType()); + }; } - - if (serializeCustomFormatters[index] == null) + else { return null; } - - return () => - { - il.EmitLdarg(1); // read object[] - il.EmitLdc_I4(index); - il.Emit(OpCodes.Ldelem_Ref); // object - il.Emit(OpCodes.Castclass, serializeCustomFormatters[index].GetType()); - }; }, 2); // 0, 1 is parameter. } @@ -566,31 +559,26 @@ public static object BuildFormatterToDynamicMethod(Type type, bool forceStringKe il, (index, member) => { - if (deserializeCustomFormatters.Count == 0) + if (deserializeCustomFormatters.Count > 0 && deserializeCustomFormatters[index] is object formatter) { - return null; + return () => + { + il.EmitLdarg(0); // read object[] + il.EmitLdc_I4(index); + il.Emit(OpCodes.Ldelem_Ref); // object + il.Emit(OpCodes.Castclass, formatter.GetType()); + }; } - - if (deserializeCustomFormatters[index] == null) + else { return null; } - - return () => - { - il.EmitLdarg(0); // read object[] - il.EmitLdc_I4(index); - il.Emit(OpCodes.Ldelem_Ref); // object - il.Emit(OpCodes.Castclass, deserializeCustomFormatters[index].GetType()); - }; }, 1); } object serializeDelegate = serialize.CreateDelegate(typeof(AnonymousSerializeFunc<>).MakeGenericType(type)); - object deserializeDelegate = (deserialize == null) - ? (object)null - : (object)deserialize.CreateDelegate(typeof(AnonymousDeserializeFunc<>).MakeGenericType(type)); + object? deserializeDelegate = deserialize?.CreateDelegate(typeof(AnonymousDeserializeFunc<>).MakeGenericType(type)); var resultFormatter = Activator.CreateInstance( typeof(AnonymousSerializableFormatter<>).MakeGenericType(type), new[] { stringByteKeysField.ToArray(), serializeCustomFormatters.ToArray(), deserializeCustomFormatters.ToArray(), serializeDelegate, deserializeDelegate }); @@ -612,7 +600,7 @@ private static void BuildConstructor(Type type, ObjectSerializationInfo info, Co { il.Emit(OpCodes.Dup); il.EmitLdc_I4(i); - il.Emit(OpCodes.Ldstr, item.StringKey); + il.Emit(OpCodes.Ldstr, item.StringKey!); il.EmitCall(CodeGenHelpersTypeInfo.GetEncodedStringBytes); il.Emit(OpCodes.Stelem_Ref); i++; @@ -626,7 +614,7 @@ private static void BuildConstructor(Type type, ObjectSerializationInfo info, Co Dictionary dict = new Dictionary(); foreach (ObjectSerializationInfo.EmittableMember item in info.Members.Where(x => x.IsReadable || x.IsActuallyWritable)) { - MessagePackFormatterAttribute attr = item.GetMessagePackFormatterAttribute(); + MessagePackFormatterAttribute? attr = item.GetMessagePackFormatterAttribute(); if (attr != null) { // Verify that the specified formatter implements the required interface. @@ -688,7 +676,7 @@ private static void BuildConstructor(Type type, ObjectSerializationInfo info, Co } // void Serialize(ref [arg:1]MessagePackWriter writer, [arg:2]T value, [arg:3]MessagePackSerializerOptions options); - private static void BuildSerialize(Type type, ObjectSerializationInfo info, ILGenerator il, Action emitStringByteKeys, Func tryEmitLoadCustomFormatter, int firstArgIndex) + private static void BuildSerialize(Type type, ObjectSerializationInfo info, ILGenerator il, Action emitStringByteKeys, Func tryEmitLoadCustomFormatter, int firstArgIndex) { var argWriter = new ArgumentField(il, firstArgIndex); var argValue = new ArgumentField(il, firstArgIndex + 1, type); @@ -746,8 +734,7 @@ private static void BuildSerialize(Type type, ObjectSerializationInfo info, ILGe var index = 0; for (int i = 0; i <= maxKey; i++) { - ObjectSerializationInfo.EmittableMember member; - if (intKeyMap.TryGetValue(i, out member)) + if (intKeyMap.TryGetValue(i, out ObjectSerializationInfo.EmittableMember? member)) { EmitSerializeValue(il, type.GetTypeInfo(), member, index++, tryEmitLoadCustomFormatter, argWriter, argValue, argOptions, localResolver); } @@ -786,16 +773,16 @@ private static void BuildSerialize(Type type, ObjectSerializationInfo info, ILGe // Optimize, WriteRaw(Unity, large) or UnsafeMemory32/64.WriteRawX #if !UNITY_2018_3_OR_NEWER - var valueLen = CodeGenHelpers.GetEncodedStringBytes(item.StringKey).Length; + var valueLen = CodeGenHelpers.GetEncodedStringBytes(item.StringKey!).Length; if (valueLen <= MessagePackRange.MaxFixStringLength) { if (UnsafeMemory.Is32Bit) { - il.EmitCall(typeof(UnsafeMemory32).GetRuntimeMethod("WriteRaw" + valueLen, new[] { typeof(MessagePackWriter).MakeByRefType(), typeof(ReadOnlySpan) })); + il.EmitCall(typeof(UnsafeMemory32).GetRuntimeMethod("WriteRaw" + valueLen, new[] { typeof(MessagePackWriter).MakeByRefType(), typeof(ReadOnlySpan) })!); } else { - il.EmitCall(typeof(UnsafeMemory64).GetRuntimeMethod("WriteRaw" + valueLen, new[] { typeof(MessagePackWriter).MakeByRefType(), typeof(ReadOnlySpan) })); + il.EmitCall(typeof(UnsafeMemory64).GetRuntimeMethod("WriteRaw" + valueLen, new[] { typeof(MessagePackWriter).MakeByRefType(), typeof(ReadOnlySpan) })!); } } else @@ -812,11 +799,11 @@ private static void BuildSerialize(Type type, ObjectSerializationInfo info, ILGe il.Emit(OpCodes.Ret); } - private static void EmitSerializeValue(ILGenerator il, TypeInfo type, ObjectSerializationInfo.EmittableMember member, int index, Func tryEmitLoadCustomFormatter, ArgumentField argWriter, ArgumentField argValue, ArgumentField argOptions, LocalBuilder localResolver) + private static void EmitSerializeValue(ILGenerator il, TypeInfo type, ObjectSerializationInfo.EmittableMember member, int index, Func tryEmitLoadCustomFormatter, ArgumentField argWriter, ArgumentField argValue, ArgumentField argOptions, LocalBuilder localResolver) { Label endLabel = il.DefineLabel(); Type t = member.Type; - Action emitter = tryEmitLoadCustomFormatter(index, member); + Action? emitter = tryEmitLoadCustomFormatter(index, member); if (emitter != null) { emitter(); @@ -860,7 +847,7 @@ private static void EmitSerializeValue(ILGenerator il, TypeInfo type, ObjectSeri } else { - il.EmitCall(typeof(MessagePackWriter).GetRuntimeMethod("Write", new Type[] { t })); + il.EmitCall(typeof(MessagePackWriter).GetRuntimeMethod("Write", new Type[] { t })!); } } else @@ -879,7 +866,7 @@ private static void EmitSerializeValue(ILGenerator il, TypeInfo type, ObjectSeri } // T Deserialize([arg:1]ref MessagePackReader reader, [arg:2]MessagePackSerializerOptions options); - private static void BuildDeserialize(Type type, ObjectSerializationInfo info, ILGenerator il, Func tryEmitLoadCustomFormatter, int firstArgIndex) + private static void BuildDeserialize(Type type, ObjectSerializationInfo info, ILGenerator il, Func tryEmitLoadCustomFormatter, int firstArgIndex) { var argReader = new ArgumentField(il, firstArgIndex, @ref: true); var argOptions = new ArgumentField(il, firstArgIndex + 1); @@ -905,7 +892,7 @@ private static void BuildDeserialize(Type type, ObjectSerializationInfo info, IL var localLength = BuildDeserializeInternalReadHeaderLength(info, il, ref argReader); // var resolver = options.Resolver; - var localResolver = BuildDeserializeInternalResolver(info, il, ref argOptions); + var localResolver = BuildDeserializeInternalResolver(info, il, ref argOptions)!; if (info.IsIntKey) { @@ -929,7 +916,7 @@ private static void BuildDeserialize(Type type, ObjectSerializationInfo info, IL il.Emit(OpCodes.Ret); } - private static void BuildDeserializeInternalDeserializeEachPropertyStringKey(ObjectSerializationInfo info, ILGenerator il, Func tryEmitLoadCustomFormatter, bool canOverwrite, ref ArgumentField argReader, ArgumentField argOptions, LocalBuilder localResolver, LocalBuilder localResult, LocalBuilder localLength) + private static void BuildDeserializeInternalDeserializeEachPropertyStringKey(ObjectSerializationInfo info, ILGenerator il, Func tryEmitLoadCustomFormatter, bool canOverwrite, ref ArgumentField argReader, ArgumentField argOptions, LocalBuilder localResolver, LocalBuilder localResult, LocalBuilder localLength) { // Prepare local variables or assignment fields/properties var infoList = BuildDeserializeInternalDeserializationInfoArrayStringKey(info, il, canOverwrite); @@ -949,7 +936,7 @@ private static void BuildDeserializeInternalDeserializeEachPropertyStringKey(Obj BuildDeserializeInternalAssignFieldFromLocalVariableStringKey(info, il, infoList, localResult); } - private static void BuildDeserializeInternalDeserializeEachPropertyIntKey(ObjectSerializationInfo info, ILGenerator il, Func tryEmitLoadCustomFormatter, bool canOverwrite, ref ArgumentField argReader, ref ArgumentField argOptions, LocalBuilder localResolver, LocalBuilder localResult, LocalBuilder localLength) + private static void BuildDeserializeInternalDeserializeEachPropertyIntKey(ObjectSerializationInfo info, ILGenerator il, Func tryEmitLoadCustomFormatter, bool canOverwrite, ref ArgumentField argReader, ref ArgumentField argOptions, LocalBuilder localResolver, LocalBuilder localResult, LocalBuilder localLength) { // Prepare local variables or assignment fields/properties var infoList = BuildDeserializeInternalDeserializationInfoArrayIntKey(info, il, canOverwrite, out var gotoDefault, out var maxKey); @@ -992,7 +979,7 @@ private static void BuildDeserializeInternalAssignFieldFromLocalVariableStringKe il.EmitLdloca(localResult); } - il.EmitLdloc(item.LocalVariable); + il.EmitLdloc(item.LocalVariable!); item.MemberInfo.EmitStoreValue(il); il.MarkLabel(skipLabel); @@ -1007,7 +994,7 @@ private static void BuildDeserializeInternalAssignFieldFromLocalVariableIntKey(O } Label? memberAssignmentDoneLabel = null; - var intKeyMap = infoList.Where(x => x.MemberInfo != null && x.MemberInfo.IsActuallyWritable).ToDictionary(x => x.MemberInfo.IntKey); + var intKeyMap = infoList.Where(x => x.MemberInfo != null && x.MemberInfo.IsActuallyWritable).ToDictionary(x => x.MemberInfo!.IntKey); for (var key = 0; key <= maxKey; key++) { if (!intKeyMap.TryGetValue(key, out var item)) @@ -1015,7 +1002,7 @@ private static void BuildDeserializeInternalAssignFieldFromLocalVariableIntKey(O continue; } - if (item.MemberInfo.IsWrittenByConstructor) + if (item.MemberInfo!.IsWrittenByConstructor) { continue; } @@ -1040,7 +1027,7 @@ private static void BuildDeserializeInternalAssignFieldFromLocalVariableIntKey(O il.EmitLdloca(localResult); } - il.EmitLdloc(item.LocalVariable); + il.EmitLdloc(item.LocalVariable!); item.MemberInfo.EmitStoreValue(il); } @@ -1056,9 +1043,9 @@ private static void BuildDeserializeInternalCreateInstanceWithArguments(ObjectSe foreach (var item in info.ConstructorParameters) { var local = infoList.First(x => x.MemberInfo == item.MemberInfo); - il.EmitLdloc(local.LocalVariable); + il.EmitLdloc(local.LocalVariable!); - if (!item.ConstructorParameter.ParameterType.IsValueType && local.MemberInfo.IsValueType) + if (!item.ConstructorParameter.ParameterType.IsValueType && local.MemberInfo?.IsValueType is true) { // When a constructor argument of type object is being provided by a serialized member value that is a value type // then that value must be boxed in order for the generated code to be valid (see issue #987). This may occur because @@ -1068,7 +1055,7 @@ private static void BuildDeserializeInternalCreateInstanceWithArguments(ObjectSe } } - il.Emit(OpCodes.Newobj, info.BestmatchConstructor); + il.Emit(OpCodes.Newobj, info.BestmatchConstructor!); il.Emit(OpCodes.Stloc, localResult); } @@ -1148,7 +1135,7 @@ private static DeserializeInfo[] BuildDeserializeInternalDeserializationInfoArra return infoList; } - private static void BuildDeserializeInternalDeserializeLoopIntKey(ILGenerator il, Func tryEmitLoadCustomFormatter, ref ArgumentField argReader, ref ArgumentField argOptions, DeserializeInfo[] infoList, LocalBuilder localResolver, LocalBuilder localResult, LocalBuilder localLength, bool canOverwrite, Label? gotoDefault) + private static void BuildDeserializeInternalDeserializeLoopIntKey(ILGenerator il, Func tryEmitLoadCustomFormatter, ref ArgumentField argReader, ref ArgumentField argOptions, DeserializeInfo[] infoList, LocalBuilder localResolver, LocalBuilder localResult, LocalBuilder localLength, bool canOverwrite, Label? gotoDefault) { var key = il.DeclareLocal(typeof(int)); var switchDefault = il.DefineLabel(); @@ -1207,12 +1194,12 @@ void ForBody(LocalBuilder forILocal) il.EmitIncrementFor(localLength, ForBody); } - private static void BuildDeserializeInternalDeserializeLoopStringKey(ILGenerator il, Func tryEmitLoadCustomFormatter, ref ArgumentField argReader, ref ArgumentField argOptions, DeserializeInfo[] infoList, LocalBuilder localResolver, LocalBuilder localResult, LocalBuilder localLength, bool canOverwrite, ObjectSerializationInfo info) + private static void BuildDeserializeInternalDeserializeLoopStringKey(ILGenerator il, Func tryEmitLoadCustomFormatter, ref ArgumentField argReader, ref ArgumentField argOptions, DeserializeInfo[] infoList, LocalBuilder localResolver, LocalBuilder localResult, LocalBuilder localLength, bool canOverwrite, ObjectSerializationInfo info) { var automata = new AutomataDictionary(); for (var i = 0; i < info.Members.Length; i++) { - automata.Add(info.Members[i].StringKey, i); + automata.Add(info.Members[i].StringKey!, i); } var buffer = il.DeclareLocal(typeof(ReadOnlySpan)); @@ -1231,7 +1218,7 @@ void ForBody(LocalBuilder forILocal) il.EmitStloc(buffer); // gen automata name lookup - void OnFoundAssignDirect(KeyValuePair x) + void OnFoundAssignDirect(KeyValuePair x) { var i = x.Value; var item = infoList[i]; @@ -1246,7 +1233,7 @@ void OnFoundAssignDirect(KeyValuePair x) } } - void OnFoundAssignLocalVariable(KeyValuePair x) + void OnFoundAssignLocalVariable(KeyValuePair x) { var i = x.Value; var item = infoList[i]; @@ -1352,7 +1339,7 @@ private static void BuildDeserializeInternalOnAfterDeserialize(Type type, Object } } - private static LocalBuilder BuildDeserializeInternalResolver(ObjectSerializationInfo info, ILGenerator il, ref ArgumentField argOptions) + private static LocalBuilder? BuildDeserializeInternalResolver(ObjectSerializationInfo info, ILGenerator il, ref ArgumentField argOptions) { if (!info.ShouldUseFormatterResolver) { @@ -1393,7 +1380,7 @@ private static void BuildDeserializeInternalCreateInstance(Type type, ObjectSeri // var result = new T(); if (info.IsClass) { - il.Emit(OpCodes.Newobj, info.BestmatchConstructor); + il.Emit(OpCodes.Newobj, info.BestmatchConstructor!); il.EmitStloc(localResult); } else @@ -1403,10 +1390,10 @@ private static void BuildDeserializeInternalCreateInstance(Type type, ObjectSeri } } - private static void BuildDeserializeInternalDeserializeValueAssignDirectly(ILGenerator il, DeserializeInfo info, int index, Func tryEmitLoadCustomFormatter, ref ArgumentField argReader, ref ArgumentField argOptions, LocalBuilder localResolver, LocalBuilder localResult) + private static void BuildDeserializeInternalDeserializeValueAssignDirectly(ILGenerator il, DeserializeInfo info, int index, Func tryEmitLoadCustomFormatter, ref ArgumentField argReader, ref ArgumentField argOptions, LocalBuilder localResolver, LocalBuilder localResult) { var storeLabel = il.DefineLabel(); - var member = info.MemberInfo; + var member = info.MemberInfo!; var t = member.Type; var emitter = tryEmitLoadCustomFormatter(index, member); @@ -1484,10 +1471,10 @@ private static void BuildDeserializeInternalDeserializeValueAssignDirectly(ILGen } } - private static void BuildDeserializeInternalDeserializeValueAssignLocalVariable(ILGenerator il, DeserializeInfo info, int index, Func tryEmitLoadCustomFormatter, ref ArgumentField argReader, ref ArgumentField argOptions, LocalBuilder localResolver, LocalBuilder localResult) + private static void BuildDeserializeInternalDeserializeValueAssignLocalVariable(ILGenerator il, DeserializeInfo info, int index, Func tryEmitLoadCustomFormatter, ref ArgumentField argReader, ref ArgumentField argOptions, LocalBuilder localResolver, LocalBuilder localResult) { var storeLabel = il.DefineLabel(); - var member = info.MemberInfo; + var member = info.MemberInfo!; var t = member.Type; var emitter = tryEmitLoadCustomFormatter(index, member); @@ -1544,7 +1531,7 @@ private static void BuildDeserializeInternalDeserializeValueAssignLocalVariable( } il.MarkLabel(storeLabel); - il.EmitStloc(info.LocalVariable); + il.EmitStloc(info.LocalVariable!); } #pragma warning disable SA1311 // Static readonly fields should begin with upper-case letter @@ -1552,18 +1539,18 @@ private static void BuildDeserializeInternalDeserializeValueAssignLocalVariable( // EmitInfos... private static readonly Type refMessagePackReader = typeof(MessagePackReader).MakeByRefType(); - private static readonly MethodInfo ReadOnlySpanFromByteArray = typeof(ReadOnlySpan).GetRuntimeMethod("op_Implicit", new[] { typeof(byte[]) }); - private static readonly MethodInfo ReadStringSpan = typeof(CodeGenHelpers).GetRuntimeMethod(nameof(CodeGenHelpers.ReadStringSpan), new[] { typeof(MessagePackReader).MakeByRefType() }); - private static readonly MethodInfo ArrayFromNullableReadOnlySequence = typeof(CodeGenHelpers).GetRuntimeMethod(nameof(CodeGenHelpers.GetArrayFromNullableSequence), new[] { typeof(ReadOnlySequence?).MakeByRefType() }); + private static readonly MethodInfo ReadOnlySpanFromByteArray = typeof(ReadOnlySpan).GetRuntimeMethod("op_Implicit", new[] { typeof(byte[]) })!; + private static readonly MethodInfo ReadStringSpan = typeof(CodeGenHelpers).GetRuntimeMethod(nameof(CodeGenHelpers.ReadStringSpan), new[] { typeof(MessagePackReader).MakeByRefType() })!; + private static readonly MethodInfo ArrayFromNullableReadOnlySequence = typeof(CodeGenHelpers).GetRuntimeMethod(nameof(CodeGenHelpers.GetArrayFromNullableSequence), new[] { typeof(ReadOnlySequence?).MakeByRefType() })!; private static readonly MethodInfo getFormatterWithVerify = typeof(FormatterResolverExtensions).GetRuntimeMethods().First(x => x.Name == nameof(FormatterResolverExtensions.GetFormatterWithVerify)); - private static readonly MethodInfo getResolverFromOptions = typeof(MessagePackSerializerOptions).GetRuntimeProperty(nameof(MessagePackSerializerOptions.Resolver)).GetMethod; - private static readonly MethodInfo getSecurityFromOptions = typeof(MessagePackSerializerOptions).GetRuntimeProperty(nameof(MessagePackSerializerOptions.Security)).GetMethod; - private static readonly MethodInfo securityDepthStep = typeof(MessagePackSecurity).GetRuntimeMethod(nameof(MessagePackSecurity.DepthStep), new[] { typeof(MessagePackReader).MakeByRefType() }); - private static readonly MethodInfo readerDepthGet = typeof(MessagePackReader).GetRuntimeProperty(nameof(MessagePackReader.Depth)).GetMethod; - private static readonly MethodInfo readerDepthSet = typeof(MessagePackReader).GetRuntimeProperty(nameof(MessagePackReader.Depth)).SetMethod; - private static readonly Func getSerialize = t => typeof(IMessagePackFormatter<>).MakeGenericType(t).GetRuntimeMethod(nameof(IMessagePackFormatter.Serialize), new[] { typeof(MessagePackWriter).MakeByRefType(), t, typeof(MessagePackSerializerOptions) }); - private static readonly Func getDeserialize = t => typeof(IMessagePackFormatter<>).MakeGenericType(t).GetRuntimeMethod(nameof(IMessagePackFormatter.Deserialize), new[] { refMessagePackReader, typeof(MessagePackSerializerOptions) }); + private static readonly MethodInfo getResolverFromOptions = typeof(MessagePackSerializerOptions).GetRuntimeProperty(nameof(MessagePackSerializerOptions.Resolver))!.GetMethod!; + private static readonly MethodInfo getSecurityFromOptions = typeof(MessagePackSerializerOptions).GetRuntimeProperty(nameof(MessagePackSerializerOptions.Security))!.GetMethod!; + private static readonly MethodInfo securityDepthStep = typeof(MessagePackSecurity).GetRuntimeMethod(nameof(MessagePackSecurity.DepthStep), new[] { typeof(MessagePackReader).MakeByRefType() })!; + private static readonly MethodInfo readerDepthGet = typeof(MessagePackReader).GetRuntimeProperty(nameof(MessagePackReader.Depth))!.GetMethod!; + private static readonly MethodInfo readerDepthSet = typeof(MessagePackReader).GetRuntimeProperty(nameof(MessagePackReader.Depth))!.SetMethod!; + private static readonly Func getSerialize = t => typeof(IMessagePackFormatter<>).MakeGenericType(t).GetRuntimeMethod(nameof(IMessagePackFormatter.Serialize), new[] { typeof(MessagePackWriter).MakeByRefType(), t, typeof(MessagePackSerializerOptions) })!; + private static readonly Func getDeserialize = t => typeof(IMessagePackFormatter<>).MakeGenericType(t).GetRuntimeMethod(nameof(IMessagePackFormatter.Deserialize), new[] { refMessagePackReader, typeof(MessagePackSerializerOptions) })!; //// static readonly ConstructorInfo dictionaryConstructor = typeof(ByteArrayStringHashTable).GetTypeInfo().DeclaredConstructors.First(x => { var p = x.GetParameters(); return p.Length == 1 && p[0].ParameterType == typeof(int); }); //// static readonly MethodInfo dictionaryAdd = typeof(ByteArrayStringHashTable).GetRuntimeMethod("Add", new[] { typeof(string), typeof(int) }); //// static readonly MethodInfo dictionaryTryGetValue = typeof(ByteArrayStringHashTable).GetRuntimeMethod("TryGetValue", new[] { typeof(ArraySegment), refInt }); @@ -1573,8 +1560,8 @@ private static void BuildDeserializeInternalDeserializeValueAssignLocalVariable( return p.Length == 1 && p[0].ParameterType == typeof(string); }); - private static readonly MethodInfo onBeforeSerialize = typeof(IMessagePackSerializationCallbackReceiver).GetRuntimeMethod(nameof(IMessagePackSerializationCallbackReceiver.OnBeforeSerialize), Type.EmptyTypes); - private static readonly MethodInfo onAfterDeserialize = typeof(IMessagePackSerializationCallbackReceiver).GetRuntimeMethod(nameof(IMessagePackSerializationCallbackReceiver.OnAfterDeserialize), Type.EmptyTypes); + private static readonly MethodInfo onBeforeSerialize = typeof(IMessagePackSerializationCallbackReceiver).GetRuntimeMethod(nameof(IMessagePackSerializationCallbackReceiver.OnBeforeSerialize), Type.EmptyTypes)!; + private static readonly MethodInfo onAfterDeserialize = typeof(IMessagePackSerializationCallbackReceiver).GetRuntimeMethod(nameof(IMessagePackSerializationCallbackReceiver.OnAfterDeserialize), Type.EmptyTypes)!; private static readonly ConstructorInfo objectCtor = typeof(object).GetTypeInfo().DeclaredConstructors.First(x => x.GetParameters().Length == 0); @@ -1596,51 +1583,51 @@ internal static class MessagePackWriterTypeInfo { internal static readonly TypeInfo TypeInfo = typeof(MessagePackWriter).GetTypeInfo(); - internal static readonly MethodInfo WriteMapHeader = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteMapHeader), new[] { typeof(int) }); - internal static readonly MethodInfo WriteArrayHeader = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteArrayHeader), new[] { typeof(int) }); - internal static readonly MethodInfo WriteBytes = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.Write), new[] { typeof(ReadOnlySpan) }); - internal static readonly MethodInfo WriteNil = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteNil), Type.EmptyTypes); - internal static readonly MethodInfo WriteRaw = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteRaw), new[] { typeof(ReadOnlySpan) }); + internal static readonly MethodInfo WriteMapHeader = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteMapHeader), new[] { typeof(int) })!; + internal static readonly MethodInfo WriteArrayHeader = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteArrayHeader), new[] { typeof(int) })!; + internal static readonly MethodInfo WriteBytes = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.Write), new[] { typeof(ReadOnlySpan) })!; + internal static readonly MethodInfo WriteNil = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteNil), Type.EmptyTypes)!; + internal static readonly MethodInfo WriteRaw = typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.WriteRaw), new[] { typeof(ReadOnlySpan) })!; } internal static class MessagePackReaderTypeInfo { internal static readonly TypeInfo TypeInfo = typeof(MessagePackReader).GetTypeInfo(); - internal static readonly MethodInfo ReadArrayHeader = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadArrayHeader), Type.EmptyTypes); - internal static readonly MethodInfo ReadMapHeader = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadMapHeader), Type.EmptyTypes); - internal static readonly MethodInfo ReadBytes = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadBytes), Type.EmptyTypes); - internal static readonly MethodInfo TryReadNil = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.TryReadNil), Type.EmptyTypes); - internal static readonly MethodInfo Skip = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.Skip), Type.EmptyTypes); + internal static readonly MethodInfo ReadArrayHeader = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadArrayHeader), Type.EmptyTypes)!; + internal static readonly MethodInfo ReadMapHeader = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadMapHeader), Type.EmptyTypes)!; + internal static readonly MethodInfo ReadBytes = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.ReadBytes), Type.EmptyTypes)!; + internal static readonly MethodInfo TryReadNil = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.TryReadNil), Type.EmptyTypes)!; + internal static readonly MethodInfo Skip = typeof(MessagePackReader).GetRuntimeMethod(nameof(MessagePackReader.Skip), Type.EmptyTypes)!; } internal static class CodeGenHelpersTypeInfo { - public static readonly MethodInfo GetEncodedStringBytes = typeof(CodeGenHelpers).GetRuntimeMethod(nameof(CodeGenHelpers.GetEncodedStringBytes), new[] { typeof(string) }); + public static readonly MethodInfo GetEncodedStringBytes = typeof(CodeGenHelpers).GetRuntimeMethod(nameof(CodeGenHelpers.GetEncodedStringBytes), new[] { typeof(string) })!; } internal static class EmitInfo { public static readonly MethodInfo GetTypeFromHandle = ExpressionUtility.GetMethodInfo(() => Type.GetTypeFromHandle(default(RuntimeTypeHandle))); - public static readonly MethodInfo TypeGetProperty = ExpressionUtility.GetMethodInfo((Type t) => t.GetTypeInfo().GetProperty(default(string), default(BindingFlags))); - public static readonly MethodInfo TypeGetField = ExpressionUtility.GetMethodInfo((Type t) => t.GetTypeInfo().GetField(default(string), default(BindingFlags))); - public static readonly MethodInfo GetCustomAttributeMessagePackFormatterAttribute = ExpressionUtility.GetMethodInfo(() => CustomAttributeExtensions.GetCustomAttribute(default(MemberInfo), default(bool))); - public static readonly MethodInfo ActivatorCreateInstance = ExpressionUtility.GetMethodInfo(() => Activator.CreateInstance(default(Type), default(object[]))); + public static readonly MethodInfo TypeGetProperty = ExpressionUtility.GetMethodInfo((Type t) => t.GetTypeInfo().GetProperty(default(string)!, default(BindingFlags))); + public static readonly MethodInfo TypeGetField = ExpressionUtility.GetMethodInfo((Type t) => t.GetTypeInfo().GetField(default(string)!, default(BindingFlags))); + public static readonly MethodInfo GetCustomAttributeMessagePackFormatterAttribute = ExpressionUtility.GetMethodInfo(() => CustomAttributeExtensions.GetCustomAttribute(default(MemberInfo)!, default(bool))); + public static readonly MethodInfo ActivatorCreateInstance = ExpressionUtility.GetMethodInfo(() => Activator.CreateInstance(default(Type)!, default(object[]))); internal static class MessagePackFormatterAttr { - internal static readonly MethodInfo FormatterType = ExpressionUtility.GetPropertyInfo((MessagePackFormatterAttribute attr) => attr.FormatterType).GetGetMethod(); - internal static readonly MethodInfo Arguments = ExpressionUtility.GetPropertyInfo((MessagePackFormatterAttribute attr) => attr.Arguments).GetGetMethod(); + internal static readonly MethodInfo FormatterType = ExpressionUtility.GetPropertyInfo((MessagePackFormatterAttribute attr) => attr.FormatterType).GetGetMethod()!; + internal static readonly MethodInfo Arguments = ExpressionUtility.GetPropertyInfo((MessagePackFormatterAttribute attr) => attr.Arguments).GetGetMethod()!; } } private class DeserializeInfo { - public ObjectSerializationInfo.EmittableMember MemberInfo { get; set; } + public ObjectSerializationInfo.EmittableMember? MemberInfo { get; set; } - public LocalBuilder LocalVariable { get; set; } + public LocalBuilder? LocalVariable { get; set; } - public LocalBuilder IsInitializedLocalVariable { get; set; } + public LocalBuilder? IsInitializedLocalVariable { get; set; } public Label SwitchLabel { get; set; } } @@ -1690,16 +1677,16 @@ public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions internal class ObjectSerializationInfo { - public Type Type { get; set; } + public Type Type { get; } - public bool IsIntKey { get; set; } + public bool IsIntKey { get; } public bool IsStringKey { get { return !this.IsIntKey; } } - public bool IsClass { get; set; } + public bool IsClass { get; } public bool IsStruct { @@ -1708,25 +1695,31 @@ public bool IsStruct public bool ShouldUseFormatterResolver { get; private set; } - public ConstructorInfo BestmatchConstructor { get; set; } + public ConstructorInfo? BestmatchConstructor { get; } - public EmittableMemberAndConstructorParameter[] ConstructorParameters { get; set; } + public EmittableMemberAndConstructorParameter[] ConstructorParameters { get; } - public EmittableMember[] Members { get; set; } + public EmittableMember[] Members { get; } - private ObjectSerializationInfo() + private ObjectSerializationInfo(Type type, EmittableMemberAndConstructorParameter[] constructorParameters, EmittableMember[] members, bool isClass, ConstructorInfo? bestmatchConstructor, bool isIntKey) { + this.Type = type; + this.ConstructorParameters = constructorParameters; + this.Members = members; + this.IsClass = isClass; + this.BestmatchConstructor = bestmatchConstructor; + this.IsIntKey = isIntKey; } - public static ObjectSerializationInfo CreateOrNull(Type type, bool forceStringKey, bool contractless, bool allowPrivate, bool dynamicMethod) + public static ObjectSerializationInfo? CreateOrNull(Type type, bool forceStringKey, bool contractless, bool allowPrivate, bool dynamicMethod) { TypeInfo ti = type.GetTypeInfo(); var isClass = ti.IsClass || ti.IsInterface || ti.IsAbstract; var isClassRecord = isClass && IsClassRecord(ti); var isStruct = ti.IsValueType; - MessagePackObjectAttribute contractAttr = ti.GetCustomAttributes().FirstOrDefault(); - DataContractAttribute dataContractAttr = ti.GetCustomAttribute(); + MessagePackObjectAttribute? contractAttr = ti.GetCustomAttributes().FirstOrDefault(); + DataContractAttribute? dataContractAttr = ti.GetCustomAttribute(); if (contractAttr == null && dataContractAttr == null && !forceStringKey && !contractless) { return null; @@ -1744,12 +1737,12 @@ bool AddEmittableMemberOrIgnore(bool isIntKeyMode, EmittableMember member, bool if (isIntKeyMode ? intMembers.TryGetValue(member.IntKey, out var conflictingMember) : stringMembers.TryGetValue(member.StringKey, out conflictingMember)) { // Quietly skip duplicate if this is an override property. - if (member.PropertyInfo != null && ((conflictingMember.PropertyInfo.SetMethod?.IsVirtual ?? false) || (conflictingMember.PropertyInfo.GetMethod?.IsVirtual ?? false))) + if (member.PropertyInfo != null && ((conflictingMember.PropertyInfo?.SetMethod?.IsVirtual ?? false) || (conflictingMember.PropertyInfo?.GetMethod?.IsVirtual ?? false))) { return false; } - var memberInfo = (MemberInfo)member.PropertyInfo ?? member.FieldInfo; + var memberInfo = (MemberInfo?)member.PropertyInfo ?? member.FieldInfo; throw new MessagePackDynamicObjectResolverException($"key is duplicated, all members key must be unique. type:{type.FullName} member:{memberInfo.Name}"); } } @@ -1766,7 +1759,7 @@ bool AddEmittableMemberOrIgnore(bool isIntKeyMode, EmittableMember member, bool return true; } - EmittableMember CreateEmittableMember(MemberInfo m) + EmittableMember? CreateEmittableMember(MemberInfo m) { if (m.IsDefined(typeof(IgnoreMemberAttribute), true) || m.IsDefined(typeof(IgnoreDataMemberAttribute), true)) { @@ -1789,9 +1782,8 @@ EmittableMember CreateEmittableMember(MemberInfo m) var getMethod = property.GetGetMethod(true); var setMethod = property.GetSetMethod(true); - result = new EmittableMember(dynamicMethod) + result = new EmittableMember(dynamicMethod, property) { - PropertyInfo = property, IsReadable = (getMethod != null) && (allowPrivate || getMethod.IsPublic) && !getMethod.IsStatic, IsWritable = (setMethod != null) && (allowPrivate || setMethod.IsPublic) && !setMethod.IsStatic, }; @@ -1807,9 +1799,8 @@ EmittableMember CreateEmittableMember(MemberInfo m) return null; } - result = new EmittableMember(dynamicMethod) + result = new EmittableMember(dynamicMethod, field) { - FieldInfo = field, IsReadable = allowPrivate || field.IsPublic, IsWritable = allowPrivate || (field.IsPublic && !field.IsInitOnly), }; @@ -1836,9 +1827,14 @@ EmittableMember CreateEmittableMember(MemberInfo m) foreach (var memberGroup in membersByName) { var first = true; - foreach (var member in memberGroup.Select(CreateEmittableMember).Where(n => n != null)) + foreach (var member in memberGroup.Select(CreateEmittableMember)) { - var memberInfo = (MemberInfo)member.PropertyInfo ?? member.FieldInfo; + if (member is null) + { + continue; + } + + var memberInfo = (MemberInfo?)member.PropertyInfo ?? member.FieldInfo!; if (first) { first = false; @@ -1846,7 +1842,7 @@ EmittableMember CreateEmittableMember(MemberInfo m) } else { - member.StringKey = $"{memberInfo.DeclaringType.FullName}.{memberInfo.Name}"; + member.StringKey = $"{memberInfo.DeclaringType!.FullName}.{memberInfo.Name}"; } member.IntKey = hiddenIntKey++; @@ -1861,9 +1857,14 @@ EmittableMember CreateEmittableMember(MemberInfo m) var hiddenIntKey = 0; var memberInfos = GetAllProperties(type).Cast().Concat(GetAllFields(type)); - foreach (var member in memberInfos.Select(CreateEmittableMember).Where(n => n != null)) + foreach (var member in memberInfos.Select(CreateEmittableMember)) { - var memberInfo = (MemberInfo)member.PropertyInfo ?? member.FieldInfo; + if (member is null) + { + continue; + } + + MemberInfo memberInfo = (MemberInfo?)member.PropertyInfo ?? member.FieldInfo!; KeyAttribute key; if (contractAttr != null) @@ -1908,7 +1909,7 @@ EmittableMember CreateEmittableMember(MemberInfo m) if (isIntKey) { - member.IntKey = key.IntKey.Value; + member.IntKey = key.IntKey!.Value; } else { @@ -1924,8 +1925,8 @@ EmittableMember CreateEmittableMember(MemberInfo m) } // GetConstructor - IEnumerator ctorEnumerator = null; - ConstructorInfo ctor = ti.DeclaredConstructors.SingleOrDefault(x => x.GetCustomAttribute(false) != null); + IEnumerator? ctorEnumerator = null; + ConstructorInfo? ctor = ti.DeclaredConstructors.SingleOrDefault(x => x.GetCustomAttribute(false) != null); if (ctor == null) { ctorEnumerator = @@ -1956,7 +1957,7 @@ EmittableMember CreateEmittableMember(MemberInfo m) var ctorParamIndex = 0; foreach (ParameterInfo item in ctor.GetParameters()) { - EmittableMember paramMember; + EmittableMember? paramMember; if (isIntKey) { if (ctorParamIndexIntMembersDictionary.TryGetValue(ctorParamIndex, out paramMember)) @@ -1965,7 +1966,7 @@ EmittableMember CreateEmittableMember(MemberInfo m) item.ParameterType.GetTypeInfo().IsAssignableFrom(paramMember.Type)) && paramMember.IsReadable) { - constructorParameters.Add(new EmittableMemberAndConstructorParameter { ConstructorParameter = item, MemberInfo = paramMember }); + constructorParameters.Add(new EmittableMemberAndConstructorParameter(paramMember, item)); } else { @@ -1996,8 +1997,8 @@ EmittableMember CreateEmittableMember(MemberInfo m) else { // Lookup by both string key name and member name - IEnumerable> hasKey = constructorLookupByKeyDictionary[item.Name]; - IEnumerable> hasKeyByMemberName = constructorLookupByMemberNameDictionary[item.Name]; + IEnumerable> hasKey = constructorLookupByKeyDictionary[item.Name!]; + IEnumerable> hasKeyByMemberName = constructorLookupByMemberNameDictionary[item.Name!]; var lenByKey = hasKey.Count(); var lenByMemberName = hasKeyByMemberName.Count(); @@ -2029,7 +2030,7 @@ EmittableMember CreateEmittableMember(MemberInfo m) paramMember = hasKey.First().Value; if (item.ParameterType.IsAssignableFrom(paramMember.Type) && paramMember.IsReadable) { - constructorParameters.Add(new EmittableMemberAndConstructorParameter { ConstructorParameter = item, MemberInfo = paramMember }); + constructorParameters.Add(new EmittableMemberAndConstructorParameter(paramMember, item)); } else { @@ -2079,7 +2080,7 @@ EmittableMember CreateEmittableMember(MemberInfo m) members = stringMembers.Values .OrderBy(x => { - DataMemberAttribute attr = x.GetDataMemberAttribute(); + DataMemberAttribute? attr = x.GetDataMemberAttribute(); if (attr == null) { return int.MaxValue; @@ -2125,15 +2126,9 @@ EmittableMember CreateEmittableMember(MemberInfo m) problematicProperties.FirstOrDefault()?.ThrowIfNotWritable(); } - return new ObjectSerializationInfo + return new ObjectSerializationInfo(type, constructorParameters.ToArray(), membersArray, isClass, ctor, isIntKey) { - Type = type, - IsClass = isClass, ShouldUseFormatterResolver = shouldUseFormatterResolver, - BestmatchConstructor = ctor, - ConstructorParameters = constructorParameters.ToArray(), - IsIntKey = isIntKey, - Members = membersArray, }; } @@ -2204,7 +2199,7 @@ private static bool IsClassRecord(TypeInfo type) && type.GetMethod("$", BindingFlags.Public | BindingFlags.Instance) is object; } - private static bool TryGetNextConstructor(IEnumerator ctorEnumerator, ref ConstructorInfo ctor) + private static bool TryGetNextConstructor(IEnumerator? ctorEnumerator, [NotNullWhen(true)] ref ConstructorInfo? ctor) { if (ctorEnumerator == null || ctor != null) { @@ -2225,18 +2220,25 @@ private static bool TryGetNextConstructor(IEnumerator ctorEnume public class EmittableMemberAndConstructorParameter { - public EmittableMember MemberInfo { get; set; } + internal EmittableMemberAndConstructorParameter(EmittableMember memberInfo, ParameterInfo constructorParameter) + { + this.MemberInfo = memberInfo; + this.ConstructorParameter = constructorParameter; + } + + public EmittableMember MemberInfo { get; } - public ParameterInfo ConstructorParameter { get; set; } + public ParameterInfo ConstructorParameter { get; } } public class EmittableMember { private readonly bool dynamicMethod; - internal EmittableMember(bool dynamicMethod) + internal EmittableMember(bool dynamicMethod, MemberInfo memberInfo) { this.dynamicMethod = dynamicMethod; + this.MemberInfo = memberInfo; } public bool IsProperty @@ -2262,30 +2264,23 @@ public bool IsField public int IntKey { get; set; } - public string StringKey { get; set; } + public string? StringKey { get; set; } - public Type Type - { - get { return this.IsField ? this.FieldInfo.FieldType : this.PropertyInfo.PropertyType; } - } + public Type Type => this.FieldInfo?.FieldType ?? this.PropertyInfo!.PropertyType; - public FieldInfo FieldInfo { get; set; } + public MemberInfo MemberInfo { get; } - public PropertyInfo PropertyInfo { get; set; } + public FieldInfo? FieldInfo => this.MemberInfo as FieldInfo; - public string Name - { - get - { - return this.IsProperty ? this.PropertyInfo.Name : this.FieldInfo.Name; - } - } + public string Name => this.PropertyInfo?.Name ?? this.FieldInfo!.Name; + + public PropertyInfo? PropertyInfo => this.MemberInfo as PropertyInfo; public bool IsValueType { get { - Type t = this.IsProperty ? this.PropertyInfo.PropertyType : this.FieldInfo.FieldType; + Type t = this.PropertyInfo?.PropertyType ?? this.FieldInfo!.FieldType; return t.IsValueType; } } @@ -2309,53 +2304,43 @@ public bool IsValueType /// A bug in /// blocks its ability to invoke property init accessors when in a generic class. /// - internal bool IsProblematicInitProperty => this.PropertyInfo is PropertyInfo property && property.DeclaringType.IsGenericType && this.IsInitOnly; + internal bool IsProblematicInitProperty => this.PropertyInfo is PropertyInfo property && property.DeclaringType!.IsGenericType && this.IsInitOnly; - public MessagePackFormatterAttribute GetMessagePackFormatterAttribute() + public MessagePackFormatterAttribute? GetMessagePackFormatterAttribute() { - if (this.IsProperty) - { - return (MessagePackFormatterAttribute)this.PropertyInfo.GetCustomAttribute(true); - } - else - { - return (MessagePackFormatterAttribute)this.FieldInfo.GetCustomAttribute(true); - } + return this.PropertyInfo is not null + ? this.PropertyInfo.GetCustomAttribute(true) + : this.FieldInfo!.GetCustomAttribute(true); } - public DataMemberAttribute GetDataMemberAttribute() + public DataMemberAttribute? GetDataMemberAttribute() { - if (this.IsProperty) - { - return (DataMemberAttribute)this.PropertyInfo.GetCustomAttribute(true); - } - else - { - return (DataMemberAttribute)this.FieldInfo.GetCustomAttribute(true); - } + return this.PropertyInfo is not null + ? this.PropertyInfo.GetCustomAttribute(true) + : this.FieldInfo!.GetCustomAttribute(true); } public void EmitLoadValue(ILGenerator il) { - if (this.IsProperty) + if (this.PropertyInfo != null) { - il.EmitCall(this.PropertyInfo.GetGetMethod(true)); + il.EmitCall(this.PropertyInfo.GetGetMethod(true) ?? throw new Exception("No get accessor")); } else { - il.Emit(OpCodes.Ldfld, this.FieldInfo); + il.Emit(OpCodes.Ldfld, this.FieldInfo!); } } public void EmitStoreValue(ILGenerator il) { - if (this.IsProperty) + if (this.PropertyInfo != null) { - il.EmitCall(this.PropertyInfo.GetSetMethod(true)); + il.EmitCall(this.PropertyInfo.GetSetMethod(true) ?? throw new Exception("No set accessor")); } else { - il.Emit(OpCodes.Stfld, this.FieldInfo); + il.Emit(OpCodes.Stfld, this.FieldInfo!); } } @@ -2364,7 +2349,7 @@ internal void ThrowIfNotWritable() if (this.IsProblematicInitProperty && !this.dynamicMethod) { throw new InitAccessorInGenericClassNotSupportedException( - $"`init` property accessor {this.PropertyInfo.SetMethod.DeclaringType.FullName}.{this.PropertyInfo.Name} found in generic type, " + + $"`init` property accessor {this.PropertyInfo!.SetMethod!.DeclaringType!.FullName}.{this.PropertyInfo.Name} found in generic type, " + $"which is not supported with the DynamicObjectResolver. Use the AllowPrivate variety of the resolver instead. " + $"See https://github.com/neuecc/MessagePack-CSharp/issues/1134 for details."); } @@ -2395,7 +2380,7 @@ internal void ThrowIfNotWritable() ////} } - private class OrderBaseTypesBeforeDerivedTypes : IComparer + private class OrderBaseTypesBeforeDerivedTypes : IComparer { internal static readonly OrderBaseTypesBeforeDerivedTypes Instance = new OrderBaseTypesBeforeDerivedTypes(); @@ -2403,10 +2388,15 @@ private OrderBaseTypesBeforeDerivedTypes() { } - public int Compare(Type x, Type y) + public int Compare(Type? x, Type? y) { + if (x is null || y is null) + { + throw new NotSupportedException(); + } + return - x.IsEquivalentTo(y) ? 0 : + x == y || x.IsEquivalentTo(y) ? 0 : x.IsAssignableFrom(y) ? -1 : y.IsAssignableFrom(x) ? 1 : 0; diff --git a/src/MessagePack/net6.0/PublicAPI.Shipped.txt b/src/MessagePack/net6.0/PublicAPI.Shipped.txt index 2e292fd9c..159e4b86c 100644 --- a/src/MessagePack/net6.0/PublicAPI.Shipped.txt +++ b/src/MessagePack/net6.0/PublicAPI.Shipped.txt @@ -641,10 +641,10 @@ MessagePack.Resolvers.ContractlessStandardResolver.GetFormatter() -> MessageP MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicContractlessObjectResolver -~MessagePack.Resolvers.DynamicContractlessObjectResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter +MessagePack.Resolvers.DynamicContractlessObjectResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.DynamicContractlessObjectResolverAllowPrivate() -> void -~MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter +MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicEnumAsStringResolver MessagePack.Resolvers.DynamicEnumAsStringResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicEnumResolver @@ -652,9 +652,9 @@ MessagePack.Resolvers.DynamicEnumResolver.GetFormatter() -> MessagePack.Forma MessagePack.Resolvers.DynamicGenericResolver MessagePack.Resolvers.DynamicGenericResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicObjectResolver -~MessagePack.Resolvers.DynamicObjectResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter +MessagePack.Resolvers.DynamicObjectResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicObjectResolverAllowPrivate -~MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter +MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicUnionResolver MessagePack.Resolvers.DynamicUnionResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.NativeDateTimeResolver @@ -963,15 +963,15 @@ static readonly MessagePack.Resolvers.ContractlessStandardResolver.Instance -> M static readonly MessagePack.Resolvers.ContractlessStandardResolver.Options -> MessagePack.MessagePackSerializerOptions! static readonly MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.Instance -> MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate! static readonly MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.Options -> MessagePack.MessagePackSerializerOptions! -~static readonly MessagePack.Resolvers.DynamicContractlessObjectResolver.Instance -> MessagePack.Resolvers.DynamicContractlessObjectResolver -~static readonly MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.Instance -> MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate +static readonly MessagePack.Resolvers.DynamicContractlessObjectResolver.Instance -> MessagePack.Resolvers.DynamicContractlessObjectResolver! +static readonly MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.Instance -> MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate! static readonly MessagePack.Resolvers.DynamicEnumAsStringResolver.Instance -> MessagePack.Resolvers.DynamicEnumAsStringResolver! static readonly MessagePack.Resolvers.DynamicEnumAsStringResolver.Options -> MessagePack.MessagePackSerializerOptions! static readonly MessagePack.Resolvers.DynamicEnumResolver.Instance -> MessagePack.Resolvers.DynamicEnumResolver! static readonly MessagePack.Resolvers.DynamicGenericResolver.Instance -> MessagePack.Resolvers.DynamicGenericResolver! -~static readonly MessagePack.Resolvers.DynamicObjectResolver.Instance -> MessagePack.Resolvers.DynamicObjectResolver -~static readonly MessagePack.Resolvers.DynamicObjectResolver.Options -> MessagePack.MessagePackSerializerOptions -~static readonly MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.Instance -> MessagePack.Resolvers.DynamicObjectResolverAllowPrivate +static readonly MessagePack.Resolvers.DynamicObjectResolver.Instance -> MessagePack.Resolvers.DynamicObjectResolver! +static readonly MessagePack.Resolvers.DynamicObjectResolver.Options -> MessagePack.MessagePackSerializerOptions! +static readonly MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.Instance -> MessagePack.Resolvers.DynamicObjectResolverAllowPrivate! static readonly MessagePack.Resolvers.DynamicUnionResolver.Instance -> MessagePack.Resolvers.DynamicUnionResolver! static readonly MessagePack.Resolvers.DynamicUnionResolver.Options -> MessagePack.MessagePackSerializerOptions! static readonly MessagePack.Resolvers.NativeDateTimeResolver.Instance -> MessagePack.Resolvers.NativeDateTimeResolver! diff --git a/src/MessagePack/netcoreapp3.1/PublicAPI.Shipped.txt b/src/MessagePack/netcoreapp3.1/PublicAPI.Shipped.txt index 0bf53e2af..0a13c4956 100644 --- a/src/MessagePack/netcoreapp3.1/PublicAPI.Shipped.txt +++ b/src/MessagePack/netcoreapp3.1/PublicAPI.Shipped.txt @@ -641,10 +641,10 @@ MessagePack.Resolvers.ContractlessStandardResolver.GetFormatter() -> MessageP MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicContractlessObjectResolver -~MessagePack.Resolvers.DynamicContractlessObjectResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter +MessagePack.Resolvers.DynamicContractlessObjectResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.DynamicContractlessObjectResolverAllowPrivate() -> void -~MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter +MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicEnumAsStringResolver MessagePack.Resolvers.DynamicEnumAsStringResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicEnumResolver @@ -652,9 +652,9 @@ MessagePack.Resolvers.DynamicEnumResolver.GetFormatter() -> MessagePack.Forma MessagePack.Resolvers.DynamicGenericResolver MessagePack.Resolvers.DynamicGenericResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicObjectResolver -~MessagePack.Resolvers.DynamicObjectResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter +MessagePack.Resolvers.DynamicObjectResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicObjectResolverAllowPrivate -~MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter +MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicUnionResolver MessagePack.Resolvers.DynamicUnionResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.NativeDateTimeResolver @@ -963,15 +963,15 @@ static readonly MessagePack.Resolvers.ContractlessStandardResolver.Instance -> M static readonly MessagePack.Resolvers.ContractlessStandardResolver.Options -> MessagePack.MessagePackSerializerOptions! static readonly MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.Instance -> MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate! static readonly MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.Options -> MessagePack.MessagePackSerializerOptions! -~static readonly MessagePack.Resolvers.DynamicContractlessObjectResolver.Instance -> MessagePack.Resolvers.DynamicContractlessObjectResolver -~static readonly MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.Instance -> MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate +static readonly MessagePack.Resolvers.DynamicContractlessObjectResolver.Instance -> MessagePack.Resolvers.DynamicContractlessObjectResolver! +static readonly MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.Instance -> MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate! static readonly MessagePack.Resolvers.DynamicEnumAsStringResolver.Instance -> MessagePack.Resolvers.DynamicEnumAsStringResolver! static readonly MessagePack.Resolvers.DynamicEnumAsStringResolver.Options -> MessagePack.MessagePackSerializerOptions! static readonly MessagePack.Resolvers.DynamicEnumResolver.Instance -> MessagePack.Resolvers.DynamicEnumResolver! static readonly MessagePack.Resolvers.DynamicGenericResolver.Instance -> MessagePack.Resolvers.DynamicGenericResolver! -~static readonly MessagePack.Resolvers.DynamicObjectResolver.Instance -> MessagePack.Resolvers.DynamicObjectResolver -~static readonly MessagePack.Resolvers.DynamicObjectResolver.Options -> MessagePack.MessagePackSerializerOptions -~static readonly MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.Instance -> MessagePack.Resolvers.DynamicObjectResolverAllowPrivate +static readonly MessagePack.Resolvers.DynamicObjectResolver.Instance -> MessagePack.Resolvers.DynamicObjectResolver! +static readonly MessagePack.Resolvers.DynamicObjectResolver.Options -> MessagePack.MessagePackSerializerOptions! +static readonly MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.Instance -> MessagePack.Resolvers.DynamicObjectResolverAllowPrivate! static readonly MessagePack.Resolvers.DynamicUnionResolver.Instance -> MessagePack.Resolvers.DynamicUnionResolver! static readonly MessagePack.Resolvers.DynamicUnionResolver.Options -> MessagePack.MessagePackSerializerOptions! static readonly MessagePack.Resolvers.NativeDateTimeResolver.Instance -> MessagePack.Resolvers.NativeDateTimeResolver! diff --git a/src/MessagePack/netstandard2.0/PublicAPI.Shipped.txt b/src/MessagePack/netstandard2.0/PublicAPI.Shipped.txt index 0bf53e2af..0a13c4956 100644 --- a/src/MessagePack/netstandard2.0/PublicAPI.Shipped.txt +++ b/src/MessagePack/netstandard2.0/PublicAPI.Shipped.txt @@ -641,10 +641,10 @@ MessagePack.Resolvers.ContractlessStandardResolver.GetFormatter() -> MessageP MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicContractlessObjectResolver -~MessagePack.Resolvers.DynamicContractlessObjectResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter +MessagePack.Resolvers.DynamicContractlessObjectResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.DynamicContractlessObjectResolverAllowPrivate() -> void -~MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter +MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicEnumAsStringResolver MessagePack.Resolvers.DynamicEnumAsStringResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicEnumResolver @@ -652,9 +652,9 @@ MessagePack.Resolvers.DynamicEnumResolver.GetFormatter() -> MessagePack.Forma MessagePack.Resolvers.DynamicGenericResolver MessagePack.Resolvers.DynamicGenericResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicObjectResolver -~MessagePack.Resolvers.DynamicObjectResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter +MessagePack.Resolvers.DynamicObjectResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicObjectResolverAllowPrivate -~MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter +MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.DynamicUnionResolver MessagePack.Resolvers.DynamicUnionResolver.GetFormatter() -> MessagePack.Formatters.IMessagePackFormatter? MessagePack.Resolvers.NativeDateTimeResolver @@ -963,15 +963,15 @@ static readonly MessagePack.Resolvers.ContractlessStandardResolver.Instance -> M static readonly MessagePack.Resolvers.ContractlessStandardResolver.Options -> MessagePack.MessagePackSerializerOptions! static readonly MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.Instance -> MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate! static readonly MessagePack.Resolvers.ContractlessStandardResolverAllowPrivate.Options -> MessagePack.MessagePackSerializerOptions! -~static readonly MessagePack.Resolvers.DynamicContractlessObjectResolver.Instance -> MessagePack.Resolvers.DynamicContractlessObjectResolver -~static readonly MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.Instance -> MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate +static readonly MessagePack.Resolvers.DynamicContractlessObjectResolver.Instance -> MessagePack.Resolvers.DynamicContractlessObjectResolver! +static readonly MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate.Instance -> MessagePack.Resolvers.DynamicContractlessObjectResolverAllowPrivate! static readonly MessagePack.Resolvers.DynamicEnumAsStringResolver.Instance -> MessagePack.Resolvers.DynamicEnumAsStringResolver! static readonly MessagePack.Resolvers.DynamicEnumAsStringResolver.Options -> MessagePack.MessagePackSerializerOptions! static readonly MessagePack.Resolvers.DynamicEnumResolver.Instance -> MessagePack.Resolvers.DynamicEnumResolver! static readonly MessagePack.Resolvers.DynamicGenericResolver.Instance -> MessagePack.Resolvers.DynamicGenericResolver! -~static readonly MessagePack.Resolvers.DynamicObjectResolver.Instance -> MessagePack.Resolvers.DynamicObjectResolver -~static readonly MessagePack.Resolvers.DynamicObjectResolver.Options -> MessagePack.MessagePackSerializerOptions -~static readonly MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.Instance -> MessagePack.Resolvers.DynamicObjectResolverAllowPrivate +static readonly MessagePack.Resolvers.DynamicObjectResolver.Instance -> MessagePack.Resolvers.DynamicObjectResolver! +static readonly MessagePack.Resolvers.DynamicObjectResolver.Options -> MessagePack.MessagePackSerializerOptions! +static readonly MessagePack.Resolvers.DynamicObjectResolverAllowPrivate.Instance -> MessagePack.Resolvers.DynamicObjectResolverAllowPrivate! static readonly MessagePack.Resolvers.DynamicUnionResolver.Instance -> MessagePack.Resolvers.DynamicUnionResolver! static readonly MessagePack.Resolvers.DynamicUnionResolver.Options -> MessagePack.MessagePackSerializerOptions! static readonly MessagePack.Resolvers.NativeDateTimeResolver.Instance -> MessagePack.Resolvers.NativeDateTimeResolver! From a477b7ede660e445a9876cbdbfbdf011c418423f Mon Sep 17 00:00:00 2001 From: Andrew Arnott Date: Sat, 3 Dec 2022 14:56:14 -0700 Subject: [PATCH 2/2] Enable nullable for all src projects --- MessagePack.sln | 4 ++++ src/Directory.Build.props | 6 +++++ .../MessagePack.Annotations.csproj | 1 - .../MessagePack.AspNetCoreMvcFormatter.csproj | 2 +- .../MessagePackInputFormatter.cs | 4 ++-- .../MessagePackOutputFormatter.cs | 4 ++-- .../MessagePack.Experimental.csproj | 1 - .../MessagePack.Generator.csproj | 1 - .../MessagePack.GeneratorCore.csproj | 1 - .../MessagePack.MSBuild.Tasks.csproj | 1 - .../Formatters.cs | 12 +++++----- .../ReactivePropertyResolver.cs | 10 ++++---- .../Unity/Extension/UnityBlitResolver.cs | 16 ++++++------- .../Unity/Extension/UnsafeBlitFormatter.cs | 6 ++--- .../Scripts/MessagePack/Unity/Formatters.cs | 24 +++++++++---------- .../MessagePack/Unity/UnityResolver.cs | 8 +++---- src/MessagePack.UnityShims/Shims.cs | 8 +++---- src/MessagePack/MessagePack.csproj | 1 - .../MessagePackAnalyzer.csproj | 1 - 19 files changed, 57 insertions(+), 54 deletions(-) create mode 100644 src/Directory.Build.props diff --git a/MessagePack.sln b/MessagePack.sln index 00d6afcfc..4120a5d03 100644 --- a/MessagePack.sln +++ b/MessagePack.sln @@ -4,6 +4,10 @@ Microsoft Visual Studio Solution File, Format Version 12.00 VisualStudioVersion = 17.5.33201.384 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{86309CF6-0054-4CE3-BFD3-CA0AA7DB17BC}" + ProjectSection(SolutionItems) = preProject + src\Directory.Build.props = src\Directory.Build.props + src\Directory.Build.targets = src\Directory.Build.targets + EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MessagePack", "src\MessagePack\MessagePack.csproj", "{7ABB33EE-A2F1-492B-8DAF-5DF89F0F0B79}" EndProject diff --git a/src/Directory.Build.props b/src/Directory.Build.props new file mode 100644 index 000000000..86283b94f --- /dev/null +++ b/src/Directory.Build.props @@ -0,0 +1,6 @@ + + + enable + + + diff --git a/src/MessagePack.Annotations/MessagePack.Annotations.csproj b/src/MessagePack.Annotations/MessagePack.Annotations.csproj index 9193f7a10..7561506dc 100644 --- a/src/MessagePack.Annotations/MessagePack.Annotations.csproj +++ b/src/MessagePack.Annotations/MessagePack.Annotations.csproj @@ -3,7 +3,6 @@ netstandard2.0 $(NoWarn);CS0649 - enable MessagePack true diff --git a/src/MessagePack.AspNetCoreMvcFormatter/MessagePack.AspNetCoreMvcFormatter.csproj b/src/MessagePack.AspNetCoreMvcFormatter/MessagePack.AspNetCoreMvcFormatter.csproj index eb6491fe5..9c854d47c 100644 --- a/src/MessagePack.AspNetCoreMvcFormatter/MessagePack.AspNetCoreMvcFormatter.csproj +++ b/src/MessagePack.AspNetCoreMvcFormatter/MessagePack.AspNetCoreMvcFormatter.csproj @@ -23,4 +23,4 @@ - \ No newline at end of file + diff --git a/src/MessagePack.AspNetCoreMvcFormatter/MessagePackInputFormatter.cs b/src/MessagePack.AspNetCoreMvcFormatter/MessagePackInputFormatter.cs index 59c49a998..c2038f5a0 100644 --- a/src/MessagePack.AspNetCoreMvcFormatter/MessagePackInputFormatter.cs +++ b/src/MessagePack.AspNetCoreMvcFormatter/MessagePackInputFormatter.cs @@ -9,14 +9,14 @@ namespace MessagePack.AspNetCoreMvcFormatter public class MessagePackInputFormatter : InputFormatter { private const string ContentType = "application/x-msgpack"; - private readonly MessagePackSerializerOptions options; + private readonly MessagePackSerializerOptions? options; public MessagePackInputFormatter() : this(null) { } - public MessagePackInputFormatter(MessagePackSerializerOptions options) + public MessagePackInputFormatter(MessagePackSerializerOptions? options) { this.options = options; diff --git a/src/MessagePack.AspNetCoreMvcFormatter/MessagePackOutputFormatter.cs b/src/MessagePack.AspNetCoreMvcFormatter/MessagePackOutputFormatter.cs index 409981148..54699a591 100644 --- a/src/MessagePack.AspNetCoreMvcFormatter/MessagePackOutputFormatter.cs +++ b/src/MessagePack.AspNetCoreMvcFormatter/MessagePackOutputFormatter.cs @@ -9,14 +9,14 @@ namespace MessagePack.AspNetCoreMvcFormatter public class MessagePackOutputFormatter : OutputFormatter { private const string ContentType = "application/x-msgpack"; - private readonly MessagePackSerializerOptions options; + private readonly MessagePackSerializerOptions? options; public MessagePackOutputFormatter() : this(null) { } - public MessagePackOutputFormatter(MessagePackSerializerOptions options) + public MessagePackOutputFormatter(MessagePackSerializerOptions? options) { this.options = options; diff --git a/src/MessagePack.Experimental/MessagePack.Experimental.csproj b/src/MessagePack.Experimental/MessagePack.Experimental.csproj index 58ab39f4b..ec9d1261a 100644 --- a/src/MessagePack.Experimental/MessagePack.Experimental.csproj +++ b/src/MessagePack.Experimental/MessagePack.Experimental.csproj @@ -3,7 +3,6 @@ netcoreapp3.1 true - enable True true diff --git a/src/MessagePack.Generator/MessagePack.Generator.csproj b/src/MessagePack.Generator/MessagePack.Generator.csproj index f77d7d627..3af80c2d2 100644 --- a/src/MessagePack.Generator/MessagePack.Generator.csproj +++ b/src/MessagePack.Generator/MessagePack.Generator.csproj @@ -4,7 +4,6 @@ mpc Exe net6.0;net7.0 - enable true true mpc diff --git a/src/MessagePack.GeneratorCore/MessagePack.GeneratorCore.csproj b/src/MessagePack.GeneratorCore/MessagePack.GeneratorCore.csproj index 565d6669e..891d7cace 100644 --- a/src/MessagePack.GeneratorCore/MessagePack.GeneratorCore.csproj +++ b/src/MessagePack.GeneratorCore/MessagePack.GeneratorCore.csproj @@ -6,7 +6,6 @@ True ..\..\opensource.snk - enable diff --git a/src/MessagePack.MSBuild.Tasks/MessagePack.MSBuild.Tasks.csproj b/src/MessagePack.MSBuild.Tasks/MessagePack.MSBuild.Tasks.csproj index b1f8d8d2d..d75fd1a89 100644 --- a/src/MessagePack.MSBuild.Tasks/MessagePack.MSBuild.Tasks.csproj +++ b/src/MessagePack.MSBuild.Tasks/MessagePack.MSBuild.Tasks.csproj @@ -2,7 +2,6 @@ netstandard2.0 - enable true true diff --git a/src/MessagePack.ReactiveProperty/Formatters.cs b/src/MessagePack.ReactiveProperty/Formatters.cs index 6374a63b3..048d802ab 100644 --- a/src/MessagePack.ReactiveProperty/Formatters.cs +++ b/src/MessagePack.ReactiveProperty/Formatters.cs @@ -109,9 +109,9 @@ internal static int ToReactivePropertySlimModeInt(global::Reactive.Bindings.R } // [Mode, SchedulerId, Value] : length should be three. - public class ReactivePropertyFormatter : IMessagePackFormatter> + public class ReactivePropertyFormatter : IMessagePackFormatter?> { - public void Serialize(ref MessagePackWriter writer, ReactiveProperty value, MessagePackSerializerOptions options) + public void Serialize(ref MessagePackWriter writer, ReactiveProperty? value, MessagePackSerializerOptions options) { if (value == null) { @@ -127,7 +127,7 @@ public void Serialize(ref MessagePackWriter writer, ReactiveProperty value, M } } - public ReactiveProperty Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + public ReactiveProperty? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) { if (reader.TryReadNil()) { @@ -332,9 +332,9 @@ public void Serialize(ref MessagePackWriter writer, Unit? value, MessagePackSeri } // [Mode, Value] - public class ReactivePropertySlimFormatter : IMessagePackFormatter> + public class ReactivePropertySlimFormatter : IMessagePackFormatter?> { - public void Serialize(ref MessagePackWriter writer, ReactivePropertySlim value, MessagePackSerializerOptions options) + public void Serialize(ref MessagePackWriter writer, ReactivePropertySlim? value, MessagePackSerializerOptions options) { if (value == null) { @@ -349,7 +349,7 @@ public void Serialize(ref MessagePackWriter writer, ReactivePropertySlim valu } } - public ReactivePropertySlim Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + public ReactivePropertySlim? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) { if (reader.TryReadNil()) { diff --git a/src/MessagePack.ReactiveProperty/ReactivePropertyResolver.cs b/src/MessagePack.ReactiveProperty/ReactivePropertyResolver.cs index 51e30e742..00fa342d2 100644 --- a/src/MessagePack.ReactiveProperty/ReactivePropertyResolver.cs +++ b/src/MessagePack.ReactiveProperty/ReactivePropertyResolver.cs @@ -18,18 +18,18 @@ private ReactivePropertyResolver() { } - public IMessagePackFormatter GetFormatter() + public IMessagePackFormatter? GetFormatter() { return FormatterCache.Formatter; } private static class FormatterCache { - internal static readonly IMessagePackFormatter Formatter; + internal static readonly IMessagePackFormatter? Formatter; static FormatterCache() { - Formatter = (IMessagePackFormatter)ReactivePropertyResolverGetFormatterHelper.GetFormatter(typeof(T)); + Formatter = (IMessagePackFormatter?)ReactivePropertyResolverGetFormatterHelper.GetFormatter(typeof(T)); } } } @@ -45,7 +45,7 @@ internal static class ReactivePropertyResolverGetFormatterHelper { typeof(ReactivePropertySlim<>), typeof(ReactivePropertySlimFormatter<>) }, }; - internal static object GetFormatter(Type t) + internal static object? GetFormatter(Type t) { if (t == typeof(Unit)) { @@ -71,7 +71,7 @@ internal static object GetFormatter(Type t) return null; } - private static object CreateInstance(Type genericType, Type[] genericTypeArguments, params object[] arguments) + private static object? CreateInstance(Type genericType, Type[] genericTypeArguments, params object[] arguments) { return Activator.CreateInstance(genericType.MakeGenericType(genericTypeArguments), arguments); } diff --git a/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/Extension/UnityBlitResolver.cs b/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/Extension/UnityBlitResolver.cs index f846da838..af3652a21 100644 --- a/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/Extension/UnityBlitResolver.cs +++ b/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/Extension/UnityBlitResolver.cs @@ -19,18 +19,18 @@ private UnityBlitResolver() { } - public IMessagePackFormatter GetFormatter() + public IMessagePackFormatter? GetFormatter() { return FormatterCache.Formatter; } private static class FormatterCache { - public static readonly IMessagePackFormatter Formatter; + public static readonly IMessagePackFormatter? Formatter; static FormatterCache() { - Formatter = (IMessagePackFormatter)UnityBlitResolverGetFormatterHelper.GetFormatter(typeof(T)); + Formatter = (IMessagePackFormatter?)UnityBlitResolverGetFormatterHelper.GetFormatter(typeof(T)); } } } @@ -46,18 +46,18 @@ private UnityBlitWithPrimitiveArrayResolver() { } - public IMessagePackFormatter GetFormatter() + public IMessagePackFormatter? GetFormatter() { return FormatterCache.Formatter; } private static class FormatterCache { - internal static readonly IMessagePackFormatter Formatter; + internal static readonly IMessagePackFormatter? Formatter; static FormatterCache() { - Formatter = (IMessagePackFormatter)UnityBlitWithPrimitiveResolverGetFormatterHelper.GetFormatter(typeof(T)); + Formatter = (IMessagePackFormatter?)UnityBlitWithPrimitiveResolverGetFormatterHelper.GetFormatter(typeof(T)); if (Formatter == null) { Formatter = UnityBlitResolver.Instance.GetFormatter(); @@ -79,7 +79,7 @@ internal static class UnityBlitResolverGetFormatterHelper { typeof(Rect[]), typeof(RectArrayBlitFormatter) }, }; - internal static object GetFormatter(Type t) + internal static object? GetFormatter(Type t) { Type formatterType; if (FormatterMap.TryGetValue(t, out formatterType)) @@ -100,7 +100,7 @@ internal static class UnityBlitWithPrimitiveResolverGetFormatterHelper { typeof(double[]), typeof(DoubleArrayBlitFormatter) }, }; - internal static object GetFormatter(Type t) + internal static object? GetFormatter(Type t) { Type formatterType; if (FormatterMap.TryGetValue(t, out formatterType)) diff --git a/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs b/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs index 3682b032d..390fdf9f3 100644 --- a/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs +++ b/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/Extension/UnsafeBlitFormatter.cs @@ -17,14 +17,14 @@ namespace MessagePack.Unity.Extension // use ext instead of ArrayFormatter to extremely boost up performance. // Layout: [extHeader, byteSize(integer), isLittleEndian(bool), bytes()] // Used Ext:30~36 - public abstract class UnsafeBlitFormatterBase : IMessagePackFormatter + public abstract class UnsafeBlitFormatterBase : IMessagePackFormatter where T : struct { protected abstract sbyte TypeCode { get; } protected void CopyDeserializeUnsafe(ReadOnlySpan src, Span dest) => src.CopyTo(MemoryMarshal.Cast(dest)); - public void Serialize(ref MessagePackWriter writer, T[] value, MessagePackSerializerOptions options) + public void Serialize(ref MessagePackWriter writer, T[]? value, MessagePackSerializerOptions options) { if (value == null) { @@ -40,7 +40,7 @@ public void Serialize(ref MessagePackWriter writer, T[] value, MessagePackSerial writer.WriteRaw(MemoryMarshal.Cast(value)); } - public T[] Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) + public T[]? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) { if (reader.TryReadNil()) { diff --git a/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/Formatters.cs b/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/Formatters.cs index e3b0876fe..6dfc8742a 100644 --- a/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/Formatters.cs +++ b/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/Formatters.cs @@ -428,9 +428,9 @@ public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Keyframe } } - public sealed class AnimationCurveFormatter : global::MessagePack.Formatters.IMessagePackFormatter + public sealed class AnimationCurveFormatter : global::MessagePack.Formatters.IMessagePackFormatter { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.AnimationCurve value, global::MessagePack.MessagePackSerializerOptions options) + public void Serialize(ref MessagePackWriter writer, global::UnityEngine.AnimationCurve? value, global::MessagePack.MessagePackSerializerOptions options) { if (value == null) { @@ -440,12 +440,12 @@ public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Animatio IFormatterResolver resolver = options.Resolver; writer.WriteArrayHeader(3); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.keys, options); + resolver.GetFormatterWithVerify().Serialize(ref writer, value.keys, options); resolver.GetFormatterWithVerify().Serialize(ref writer, value.postWrapMode, options); resolver.GetFormatterWithVerify().Serialize(ref writer, value.preWrapMode, options); } - public global::UnityEngine.AnimationCurve Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) + public global::UnityEngine.AnimationCurve? Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) { if (reader.IsNil) { @@ -699,9 +699,9 @@ public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Gradient } } - public sealed class GradientFormatter : global::MessagePack.Formatters.IMessagePackFormatter + public sealed class GradientFormatter : global::MessagePack.Formatters.IMessagePackFormatter { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Gradient value, global::MessagePack.MessagePackSerializerOptions options) + public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Gradient? value, global::MessagePack.MessagePackSerializerOptions options) { if (value == null) { @@ -711,12 +711,12 @@ public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Gradient IFormatterResolver resolver = options.Resolver; writer.WriteArrayHeader(3); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.colorKeys, options); - resolver.GetFormatterWithVerify().Serialize(ref writer, value.alphaKeys, options); + resolver.GetFormatterWithVerify().Serialize(ref writer, value.colorKeys, options); + resolver.GetFormatterWithVerify().Serialize(ref writer, value.alphaKeys, options); resolver.GetFormatterWithVerify().Serialize(ref writer, value.mode, options); } - public global::UnityEngine.Gradient Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) + public global::UnityEngine.Gradient? Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) { if (reader.IsNil) { @@ -811,9 +811,9 @@ public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Color32 } } - public sealed class RectOffsetFormatter : global::MessagePack.Formatters.IMessagePackFormatter + public sealed class RectOffsetFormatter : global::MessagePack.Formatters.IMessagePackFormatter { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.RectOffset value, global::MessagePack.MessagePackSerializerOptions options) + public void Serialize(ref MessagePackWriter writer, global::UnityEngine.RectOffset? value, global::MessagePack.MessagePackSerializerOptions options) { if (value == null) { @@ -828,7 +828,7 @@ public void Serialize(ref MessagePackWriter writer, global::UnityEngine.RectOffs writer.Write(value.bottom); } - public global::UnityEngine.RectOffset Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) + public global::UnityEngine.RectOffset? Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) { if (reader.IsNil) { diff --git a/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/UnityResolver.cs b/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/UnityResolver.cs index 033e513be..a7ef65713 100644 --- a/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/UnityResolver.cs +++ b/src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Unity/UnityResolver.cs @@ -16,18 +16,18 @@ private UnityResolver() { } - public IMessagePackFormatter GetFormatter() + public IMessagePackFormatter? GetFormatter() { return FormatterCache.Formatter; } private static class FormatterCache { - public static readonly IMessagePackFormatter Formatter; + public static readonly IMessagePackFormatter? Formatter; static FormatterCache() { - Formatter = (IMessagePackFormatter)UnityResolveryResolverGetFormatterHelper.GetFormatter(typeof(T)); + Formatter = (IMessagePackFormatter?)UnityResolveryResolverGetFormatterHelper.GetFormatter(typeof(T)); } } } @@ -186,7 +186,7 @@ internal static class UnityResolveryResolverGetFormatterHelper #endif }; - internal static object GetFormatter(Type t) + internal static object? GetFormatter(Type t) { object formatter; if (FormatterMap.TryGetValue(t, out formatter)) diff --git a/src/MessagePack.UnityShims/Shims.cs b/src/MessagePack.UnityShims/Shims.cs index 1a048ee3b..3ddb58b6d 100644 --- a/src/MessagePack.UnityShims/Shims.cs +++ b/src/MessagePack.UnityShims/Shims.cs @@ -199,12 +199,12 @@ public Rect(Rect source) public sealed class AnimationCurve { [Key(0)] - public Keyframe[] keys; + public Keyframe[]? keys; [IgnoreMember] public int length { - get { return this.keys.Length; } + get { return this.keys?.Length ?? 0; } } [Key(1)] @@ -298,10 +298,10 @@ public struct Matrix4x4 public sealed class Gradient { [Key(0)] - public GradientColorKey[] colorKeys; + public GradientColorKey[]? colorKeys; [Key(1)] - public GradientAlphaKey[] alphaKeys; + public GradientAlphaKey[]? alphaKeys; [Key(2)] public GradientMode mode; diff --git a/src/MessagePack/MessagePack.csproj b/src/MessagePack/MessagePack.csproj index 845eae65b..573853847 100644 --- a/src/MessagePack/MessagePack.csproj +++ b/src/MessagePack/MessagePack.csproj @@ -3,7 +3,6 @@ netstandard2.0;netcoreapp3.1;net6.0 $(NoWarn);CS0649 - enable True $(DefineConstants);SPAN_BUILTIN True diff --git a/src/MessagePackAnalyzer/MessagePackAnalyzer.csproj b/src/MessagePackAnalyzer/MessagePackAnalyzer.csproj index ebdfca244..1bf0624b7 100644 --- a/src/MessagePackAnalyzer/MessagePackAnalyzer.csproj +++ b/src/MessagePackAnalyzer/MessagePackAnalyzer.csproj @@ -1,7 +1,6 @@  netstandard2.0 - enable true Analyzer of MessagePack for C#, verify rule for [MessagePackObject] and code fix for [Key].