You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

325 lines
14 KiB

  1. using IPA.Config.Data;
  2. using IPA.Logging;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Reflection.Emit;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using Boolean = IPA.Config.Data.Boolean;
  12. #if NET3
  13. using Net3_Proxy;
  14. using Array = Net3_Proxy.Array;
  15. #endif
  16. namespace IPA.Config.Stores
  17. {
  18. internal static partial class GeneratedStoreImpl
  19. {
  20. private static Type GetExpectedValueTypeForType(Type valT)
  21. {
  22. if (typeof(Value).IsAssignableFrom(valT)) // this is a Value subtype
  23. return valT;
  24. if (valT == typeof(string)
  25. || valT == typeof(char)) return typeof(Text);
  26. if (valT == typeof(bool)) return typeof(Boolean);
  27. if (valT == typeof(byte)
  28. || valT == typeof(sbyte)
  29. || valT == typeof(short)
  30. || valT == typeof(ushort)
  31. || valT == typeof(int)
  32. || valT == typeof(uint)
  33. || valT == typeof(long)
  34. || valT == typeof(IntPtr)) return typeof(Integer);
  35. if (valT == typeof(float)
  36. || valT == typeof(double)
  37. || valT == typeof(decimal)
  38. || valT == typeof(ulong) // ulong gets put into this, because decimal can hold it
  39. || valT == typeof(UIntPtr)) return typeof(FloatingPoint);
  40. if (typeof(IEnumerable).IsAssignableFrom(valT)) return typeof(List);
  41. // TODO: fill this out the rest of the way
  42. return typeof(Map); // default for various objects
  43. }
  44. private static void EmitDeserializeGeneratedValue(ILGenerator il, SerializedMemberInfo member, Type srcType, GetLocal GetLocal,
  45. Action<ILGenerator> thisarg, Action<ILGenerator> parentobj)
  46. {
  47. var IGeneratedStore_Deserialize = typeof(IGeneratedStore).GetMethod(nameof(IGeneratedStore.Deserialize));
  48. var valuel = GetLocal(srcType, 0);
  49. var noCreate = il.DefineLabel();
  50. il.Emit(OpCodes.Stloc, valuel);
  51. EmitLoad(il, member, thisarg);
  52. il.Emit(OpCodes.Dup);
  53. il.Emit(OpCodes.Isinst, typeof(IGeneratedStore));
  54. il.Emit(OpCodes.Brtrue_S, noCreate);
  55. il.Emit(OpCodes.Pop);
  56. EmitCreateChildGenerated(il, member.Type, parentobj);
  57. il.MarkLabel(noCreate);
  58. il.Emit(OpCodes.Dup);
  59. il.Emit(OpCodes.Ldloc, valuel);
  60. il.Emit(OpCodes.Callvirt, IGeneratedStore_Deserialize);
  61. }
  62. private static void EmitDeserializeNullable(ILGenerator il, SerializedMemberInfo member, Type expected, GetLocal GetLocal,
  63. Action<ILGenerator> thisarg, Action<ILGenerator> parentobj)
  64. {
  65. thisarg ??= il => il.Emit(OpCodes.Ldarg_0);
  66. parentobj ??= thisarg;
  67. EmitDeserializeValue(il, member, member.NullableWrappedType, expected, GetLocal, thisarg, parentobj);
  68. il.Emit(OpCodes.Newobj, member.Nullable_Construct);
  69. }
  70. // top of stack is the Value to deserialize; the type will be as returned from GetExpectedValueTypeForType
  71. // after, top of stack will be thing to write to field
  72. private static void EmitDeserializeValue(ILGenerator il, SerializedMemberInfo member, Type targetType, Type expected, GetLocal GetLocal,
  73. Action<ILGenerator> thisarg, Action<ILGenerator> parentobj)
  74. {
  75. if (typeof(Value).IsAssignableFrom(targetType)) return; // do nothing
  76. if (expected == typeof(Text))
  77. {
  78. var getter = expected.GetProperty(nameof(Text.Value)).GetGetMethod();
  79. il.Emit(OpCodes.Call, getter);
  80. if (targetType == typeof(char))
  81. {
  82. var strIndex = typeof(string).GetProperty("Chars").GetGetMethod(); // string's indexer is specially named Chars
  83. il.Emit(OpCodes.Ldc_I4_0);
  84. il.Emit(OpCodes.Call, strIndex);
  85. }
  86. }
  87. else if (expected == typeof(Boolean))
  88. {
  89. var getter = expected.GetProperty(nameof(Boolean.Value)).GetGetMethod();
  90. il.Emit(OpCodes.Call, getter);
  91. }
  92. else if (expected == typeof(Integer))
  93. {
  94. var getter = expected.GetProperty(nameof(Integer.Value)).GetGetMethod();
  95. il.Emit(OpCodes.Call, getter);
  96. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  97. }
  98. else if (expected == typeof(FloatingPoint))
  99. {
  100. var getter = expected.GetProperty(nameof(FloatingPoint.Value)).GetGetMethod();
  101. il.Emit(OpCodes.Call, getter);
  102. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  103. } // TODO: implement stuff for lists and maps of various types (probably call out somewhere else to figure out what to do)
  104. else if (expected == typeof(Map))
  105. {
  106. if (!targetType.IsValueType)
  107. {
  108. EmitDeserializeGeneratedValue(il, member, expected, GetLocal, thisarg, parentobj);
  109. }
  110. else
  111. {
  112. var Map_TryGetValue = typeof(Map).GetMethod(nameof(Map.TryGetValue));
  113. var mapLocal = GetLocal(typeof(Map));
  114. var resultLocal = GetLocal(targetType, 1);
  115. var valueLocal = GetLocal(typeof(Value));
  116. var structure = ReadObjectMembers(targetType);
  117. if (!structure.Any())
  118. {
  119. Logger.config.Warn($"Custom value type {targetType.FullName} (when compiling serialization of" +
  120. $" {member.Name} on {member.Member.DeclaringType.FullName}) has no accessible members");
  121. il.Emit(OpCodes.Pop);
  122. il.Emit(OpCodes.Ldloca, resultLocal);
  123. il.Emit(OpCodes.Initobj, targetType);
  124. }
  125. else
  126. {
  127. il.Emit(OpCodes.Stloc, mapLocal);
  128. EmitLoad(il, member, thisarg);
  129. il.Emit(OpCodes.Stloc, resultLocal);
  130. // TODO: pull this and the MakeCreator version out into another function
  131. var nextLabel = il.DefineLabel();
  132. // head of stack is Map instance
  133. foreach (var mem in structure)
  134. {
  135. il.MarkLabel(nextLabel);
  136. nextLabel = il.DefineLabel();
  137. var endErrorLabel = il.DefineLabel();
  138. il.Emit(OpCodes.Ldloc, mapLocal);
  139. il.Emit(OpCodes.Ldstr, mem.Name);
  140. il.Emit(OpCodes.Ldloca_S, valueLocal);
  141. il.Emit(OpCodes.Call, Map_TryGetValue);
  142. il.Emit(OpCodes.Brtrue_S, endErrorLabel);
  143. EmitLogError(il, $"Missing key {mem.Name}", tailcall: false);
  144. il.Emit(OpCodes.Br, nextLabel);
  145. il.MarkLabel(endErrorLabel);
  146. il.Emit(OpCodes.Ldloc_S, valueLocal);
  147. EmitDeserializeMember(il, mem, nextLabel, il => il.Emit(OpCodes.Ldloc_S, valueLocal), GetLocal, il => il.Emit(OpCodes.Ldloca, resultLocal), parentobj);
  148. }
  149. il.MarkLabel(nextLabel);
  150. }
  151. il.Emit(OpCodes.Ldloc, resultLocal);
  152. /*il.Emit(OpCodes.Ldloca, resultLocal);
  153. il.Emit(OpCodes.Ldobj, targetType);*/
  154. }
  155. }
  156. else
  157. {
  158. il.Emit(OpCodes.Pop);
  159. il.Emit(OpCodes.Ldnull);
  160. }
  161. }
  162. private static void EmitDeserializeConverter(ILGenerator il, SerializedMemberInfo member, Label nextLabel, GetLocal GetLocal,
  163. Action<ILGenerator> thisobj, Action<ILGenerator> parentobj)
  164. {
  165. var stlocal = GetLocal(typeof(Value));
  166. var valLocal = GetLocal(member.Type);
  167. il.Emit(OpCodes.Stloc, stlocal);
  168. il.BeginExceptionBlock();
  169. il.Emit(OpCodes.Ldsfld, member.ConverterField);
  170. il.Emit(OpCodes.Ldloc, stlocal);
  171. parentobj(il);
  172. if (member.IsGenericConverter)
  173. {
  174. var fromValueBase = member.ConverterBase.GetMethod(nameof(ValueConverter<int>.FromValue),
  175. new[] { typeof(Value), typeof(object) });
  176. var fromValue = member.Converter.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
  177. .FirstOrDefault(m => m.GetBaseDefinition() == fromValueBase) ?? fromValueBase;
  178. il.Emit(OpCodes.Call, fromValue);
  179. }
  180. else
  181. {
  182. var fromValueBase = typeof(IValueConverter).GetMethod(nameof(IValueConverter.FromValue),
  183. new[] { typeof(Value), typeof(object) });
  184. var fromValue = member.Converter.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
  185. .FirstOrDefault(m => m.GetBaseDefinition() == fromValueBase) ?? fromValueBase;
  186. il.Emit(OpCodes.Call, fromValue);
  187. if (member.Type.IsValueType)
  188. il.Emit(OpCodes.Unbox);
  189. }
  190. il.Emit(OpCodes.Stloc, valLocal);
  191. il.BeginCatchBlock(typeof(Exception));
  192. EmitWarnException(il, "Error occurred while deserializing");
  193. il.Emit(OpCodes.Leave, nextLabel);
  194. il.EndExceptionBlock();
  195. il.Emit(OpCodes.Ldloc, valLocal);
  196. }
  197. // emit takes the value being deserialized, logs on error, leaves nothing on stack
  198. private static void EmitDeserializeMember(ILGenerator il, SerializedMemberInfo member, Label nextLabel, Action<ILGenerator> getValue, GetLocal GetLocal,
  199. Action<ILGenerator> thisobj, Action<ILGenerator> parentobj)
  200. {
  201. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  202. var implLabel = il.DefineLabel();
  203. var passedTypeCheck = il.DefineLabel();
  204. var expectType = GetExpectedValueTypeForType(member.ConversionType);
  205. il.Emit(OpCodes.Dup);
  206. il.Emit(OpCodes.Brtrue_S, implLabel); // null check
  207. if (!member.AllowNull)
  208. {
  209. il.Emit(OpCodes.Pop);
  210. EmitLogError(il, $"Member {member.Name} ({member.Type}) not nullable", tailcall: false,
  211. expected: il => EmitTypeof(il, expectType));
  212. il.Emit(OpCodes.Br, nextLabel);
  213. }
  214. else if (member.IsNullable)
  215. {
  216. il.Emit(OpCodes.Pop);
  217. var valTLocal = GetLocal(member.Type, 0);
  218. il.Emit(OpCodes.Ldloca, valTLocal);
  219. il.Emit(OpCodes.Initobj, member.Type);
  220. EmitStore(il, member, il => il.Emit(OpCodes.Ldloc, valTLocal), thisobj);
  221. il.Emit(OpCodes.Br, nextLabel);
  222. }
  223. else
  224. {
  225. il.Emit(OpCodes.Pop);
  226. EmitStore(il, member, il => il.Emit(OpCodes.Ldnull), thisobj);
  227. il.Emit(OpCodes.Br, nextLabel);
  228. }
  229. if (!member.HasConverter)
  230. {
  231. il.MarkLabel(implLabel);
  232. il.Emit(OpCodes.Isinst, expectType); //replaces on stack
  233. il.Emit(OpCodes.Dup); // duplicate cloned value
  234. il.Emit(OpCodes.Brtrue, passedTypeCheck); // null check
  235. }
  236. var errorHandle = il.DefineLabel();
  237. // special cases to handle coersion between Float and Int
  238. if (member.HasConverter)
  239. il.MarkLabel(implLabel);
  240. else if (expectType == typeof(FloatingPoint))
  241. {
  242. var specialTypeCheck = il.DefineLabel();
  243. il.Emit(OpCodes.Pop);
  244. getValue(il);
  245. il.Emit(OpCodes.Isinst, typeof(Integer)); //replaces on stack
  246. il.Emit(OpCodes.Dup); // duplicate cloned value
  247. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  248. var Integer_CoerceToFloat = typeof(Integer).GetMethod(nameof(Integer.AsFloat));
  249. il.Emit(OpCodes.Call, Integer_CoerceToFloat);
  250. il.Emit(OpCodes.Br, passedTypeCheck);
  251. }
  252. else if (expectType == typeof(Integer))
  253. {
  254. var specialTypeCheck = il.DefineLabel();
  255. il.Emit(OpCodes.Pop);
  256. getValue(il);
  257. il.Emit(OpCodes.Isinst, typeof(FloatingPoint)); //replaces on stack
  258. il.Emit(OpCodes.Dup); // duplicate cloned value
  259. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  260. var Float_CoerceToInt = typeof(FloatingPoint).GetMethod(nameof(FloatingPoint.AsInteger));
  261. il.Emit(OpCodes.Call, Float_CoerceToInt);
  262. il.Emit(OpCodes.Br, passedTypeCheck);
  263. }
  264. if (!member.HasConverter)
  265. {
  266. il.MarkLabel(errorHandle);
  267. il.Emit(OpCodes.Pop);
  268. EmitLogError(il, $"Unexpected type deserializing {member.Name}", tailcall: false,
  269. expected: il => EmitTypeof(il, expectType), found: il =>
  270. {
  271. getValue(il);
  272. il.Emit(OpCodes.Callvirt, Object_GetType);
  273. });
  274. il.Emit(OpCodes.Br, nextLabel);
  275. }
  276. il.MarkLabel(passedTypeCheck);
  277. var local = GetLocal(member.Type, 0);
  278. if (member.HasConverter) EmitDeserializeConverter(il, member, nextLabel, GetLocal, thisobj, parentobj);
  279. else if (member.IsNullable) EmitDeserializeNullable(il, member, expectType, GetLocal, thisobj, parentobj);
  280. else EmitDeserializeValue(il, member, member.Type, expectType, GetLocal, thisobj, parentobj);
  281. il.Emit(OpCodes.Stloc, local);
  282. EmitStore(il, member, il => il.Emit(OpCodes.Ldloc, local), thisobj);
  283. }
  284. }
  285. }