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.

271 lines
12 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.Diagnostics;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Reflection.Emit;
  10. using System.Runtime.CompilerServices;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using Boolean = IPA.Config.Data.Boolean;
  14. #if NET3
  15. using Net3_Proxy;
  16. using Array = Net3_Proxy.Array;
  17. #endif
  18. namespace IPA.Config.Stores
  19. {
  20. internal static partial class GeneratedStoreImpl
  21. {
  22. #region Logs
  23. private static readonly MethodInfo LogErrorMethod = typeof(GeneratedStoreImpl).GetMethod(nameof(LogError), BindingFlags.NonPublic | BindingFlags.Static);
  24. internal static void LogError(Type expected, Type found, string message)
  25. {
  26. Logger.config.Notice($"{message}{(expected == null ? "" : $" (expected {expected}, found {found?.ToString() ?? "null"})")}");
  27. }
  28. private static readonly MethodInfo LogWarningMethod = typeof(GeneratedStoreImpl).GetMethod(nameof(LogWarning), BindingFlags.NonPublic | BindingFlags.Static);
  29. internal static void LogWarning(string message)
  30. {
  31. Logger.config.Warn(message);
  32. }
  33. private static readonly MethodInfo LogWarningExceptionMethod = typeof(GeneratedStoreImpl).GetMethod(nameof(LogWarningException), BindingFlags.NonPublic | BindingFlags.Static);
  34. internal static void LogWarningException(Exception exception)
  35. {
  36. Logger.config.Warn(exception);
  37. }
  38. #endregion
  39. //private delegate LocalBuilder LocalAllocator(Type type, int idx = 0);
  40. private static LocalAllocator MakeLocalAllocator(ILGenerator il)
  41. => new LocalAllocator(il);
  42. private struct AllocatedLocal : IDisposable
  43. {
  44. internal readonly LocalAllocator allocator;
  45. public LocalBuilder Local { get; }
  46. public AllocatedLocal(LocalAllocator alloc, LocalBuilder builder)
  47. {
  48. allocator = alloc;
  49. Local = builder;
  50. }
  51. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  52. public static implicit operator LocalBuilder(AllocatedLocal loc) => loc.Local;
  53. public void Dealloc() => allocator.Deallocate(this);
  54. public void Dispose() => Dealloc();
  55. }
  56. private sealed class LocalAllocator
  57. {
  58. private readonly ILGenerator ilSource;
  59. private readonly Dictionary<Type, Stack<LocalBuilder>> unallocatedLocals = new Dictionary<Type, Stack<LocalBuilder>>();
  60. public LocalAllocator(ILGenerator il)
  61. => ilSource = il;
  62. private Stack<LocalBuilder> GetLocalListForType(Type type)
  63. {
  64. if (!unallocatedLocals.TryGetValue(type, out var list))
  65. unallocatedLocals.Add(type, list = new Stack<LocalBuilder>());
  66. return list;
  67. }
  68. public AllocatedLocal Allocate(Type type)
  69. {
  70. var list = GetLocalListForType(type);
  71. if (list.Count < 1) list.Push(ilSource.DeclareLocal(type));
  72. return new AllocatedLocal(this, list.Pop());
  73. }
  74. public void Deallocate(AllocatedLocal loc)
  75. {
  76. Debug.Assert(loc.allocator == this);
  77. var list = GetLocalListForType(loc.Local.LocalType);
  78. list.Push(loc.Local);
  79. }
  80. }
  81. private static void EmitLoad(ILGenerator il, SerializedMemberInfo member, Action<ILGenerator> thisarg)
  82. {
  83. thisarg(il); // load this
  84. if (member.IsField)
  85. il.Emit(OpCodes.Ldfld, member.Member as FieldInfo);
  86. else
  87. { // member is a property
  88. var prop = member.Member as PropertyInfo;
  89. var getter = prop.GetGetMethod();
  90. if (getter == null) throw new InvalidOperationException($"Property {member.Name} does not have a getter and is not ignored");
  91. il.Emit(OpCodes.Call, getter);
  92. }
  93. }
  94. private static void EmitStore(ILGenerator il, SerializedMemberInfo member, Action<ILGenerator> value, Action<ILGenerator> thisobj)
  95. {
  96. thisobj(il);
  97. value(il);
  98. if (member.IsField)
  99. il.Emit(OpCodes.Stfld, member.Member as FieldInfo);
  100. else
  101. { // member is a property
  102. var prop = member.Member as PropertyInfo;
  103. var setter = prop.GetSetMethod();
  104. if (setter == null) throw new InvalidOperationException($"Property {member.Name} does not have a setter and is not ignored");
  105. il.Emit(OpCodes.Call, setter);
  106. }
  107. }
  108. private static void EmitWarnException(ILGenerator il, string v)
  109. {
  110. il.Emit(OpCodes.Ldstr, v);
  111. il.Emit(OpCodes.Call, LogWarningMethod);
  112. il.Emit(OpCodes.Call, LogWarningExceptionMethod);
  113. }
  114. private static void EmitLogError(ILGenerator il, string message, bool tailcall = false, Action<ILGenerator> expected = null, Action<ILGenerator> found = null)
  115. {
  116. if (expected == null) expected = il => il.Emit(OpCodes.Ldnull);
  117. if (found == null) found = il => il.Emit(OpCodes.Ldnull);
  118. expected(il);
  119. found(il);
  120. il.Emit(OpCodes.Ldstr, message);
  121. if (tailcall) il.Emit(OpCodes.Tailcall);
  122. il.Emit(OpCodes.Call, LogErrorMethod);
  123. }
  124. private static readonly MethodInfo Type_GetTypeFromHandle = typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle));
  125. private static void EmitTypeof(ILGenerator il, Type type)
  126. {
  127. il.Emit(OpCodes.Ldtoken, type);
  128. il.Emit(OpCodes.Call, Type_GetTypeFromHandle);
  129. }
  130. private static readonly Type IDisposable_t = typeof(IDisposable);
  131. private static readonly MethodInfo IDisposable_Dispose = IDisposable_t.GetMethod(nameof(IDisposable.Dispose));
  132. private static readonly Type Decimal_t = typeof(decimal);
  133. private static readonly ConstructorInfo Decimal_FromFloat = Decimal_t.GetConstructor(new[] { typeof(float) });
  134. private static readonly ConstructorInfo Decimal_FromDouble = Decimal_t.GetConstructor(new[] { typeof(double) });
  135. private static readonly ConstructorInfo Decimal_FromInt = Decimal_t.GetConstructor(new[] { typeof(int) });
  136. private static readonly ConstructorInfo Decimal_FromUInt = Decimal_t.GetConstructor(new[] { typeof(uint) });
  137. private static readonly ConstructorInfo Decimal_FromLong = Decimal_t.GetConstructor(new[] { typeof(long) });
  138. private static readonly ConstructorInfo Decimal_FromULong = Decimal_t.GetConstructor(new[] { typeof(ulong) });
  139. private static void EmitNumberConvertTo(ILGenerator il, Type to, Type from)
  140. { // WARNING: THIS USES THE NO-OVERFLOW OPCODES
  141. if (to == from) return;
  142. if (to == Decimal_t)
  143. {
  144. if (from == typeof(float)) il.Emit(OpCodes.Newobj, Decimal_FromFloat);
  145. else if (from == typeof(double)) il.Emit(OpCodes.Newobj, Decimal_FromDouble);
  146. else if (from == typeof(long)) il.Emit(OpCodes.Newobj, Decimal_FromLong);
  147. else if (from == typeof(ulong)) il.Emit(OpCodes.Newobj, Decimal_FromULong);
  148. else if (from == typeof(int)) il.Emit(OpCodes.Newobj, Decimal_FromInt);
  149. else if (from == typeof(uint)) il.Emit(OpCodes.Newobj, Decimal_FromUInt);
  150. else if (from == typeof(IntPtr))
  151. {
  152. EmitNumberConvertTo(il, typeof(long), from);
  153. EmitNumberConvertTo(il, to, typeof(long));
  154. }
  155. else if (from == typeof(UIntPtr))
  156. {
  157. EmitNumberConvertTo(il, typeof(ulong), from);
  158. EmitNumberConvertTo(il, to, typeof(ulong));
  159. }
  160. else
  161. { // if the source is anything else, we first convert to int because that can contain all other values
  162. EmitNumberConvertTo(il, typeof(int), from);
  163. EmitNumberConvertTo(il, to, typeof(int));
  164. };
  165. }
  166. else if (from == Decimal_t)
  167. {
  168. if (to == typeof(IntPtr))
  169. {
  170. EmitNumberConvertTo(il, typeof(long), from);
  171. EmitNumberConvertTo(il, to, typeof(long));
  172. }
  173. else if (to == typeof(UIntPtr))
  174. {
  175. EmitNumberConvertTo(il, typeof(ulong), from);
  176. EmitNumberConvertTo(il, to, typeof(ulong));
  177. }
  178. else
  179. {
  180. var method = Decimal_t.GetMethod($"To{to.Name}"); // conveniently, this is the pattern of the to* names
  181. il.Emit(OpCodes.Call, method);
  182. }
  183. }
  184. else if (to == typeof(IntPtr)) il.Emit(OpCodes.Conv_I);
  185. else if (to == typeof(UIntPtr)) il.Emit(OpCodes.Conv_U);
  186. else if (to == typeof(sbyte)) il.Emit(OpCodes.Conv_I1);
  187. else if (to == typeof(byte)) il.Emit(OpCodes.Conv_U1);
  188. else if (to == typeof(short)) il.Emit(OpCodes.Conv_I2);
  189. else if (to == typeof(ushort)) il.Emit(OpCodes.Conv_U2);
  190. else if (to == typeof(int)) il.Emit(OpCodes.Conv_I4);
  191. else if (to == typeof(uint)) il.Emit(OpCodes.Conv_U4);
  192. else if (to == typeof(long)) il.Emit(OpCodes.Conv_I8);
  193. else if (to == typeof(ulong)) il.Emit(OpCodes.Conv_U8);
  194. else if (to == typeof(float))
  195. {
  196. if (from == typeof(byte)
  197. || from == typeof(ushort)
  198. || from == typeof(uint)
  199. || from == typeof(ulong)
  200. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  201. il.Emit(OpCodes.Conv_R4);
  202. }
  203. else if (to == typeof(double))
  204. {
  205. if (from == typeof(byte)
  206. || from == typeof(ushort)
  207. || from == typeof(uint)
  208. || from == typeof(ulong)
  209. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  210. il.Emit(OpCodes.Conv_R8);
  211. }
  212. }
  213. private static void EmitCreateChildGenerated(ILGenerator il, Type childType, Action<ILGenerator> parentobj)
  214. {
  215. var method = CreateGParent.MakeGenericMethod(childType);
  216. parentobj(il);
  217. il.Emit(OpCodes.Call, method);
  218. }
  219. private static Type GetExpectedValueTypeForType(Type valT)
  220. {
  221. if (typeof(Value).IsAssignableFrom(valT)) // this is a Value subtype
  222. return valT;
  223. if (valT == typeof(string)
  224. || valT == typeof(char)) return typeof(Text);
  225. if (valT == typeof(bool)) return typeof(Boolean);
  226. if (valT == typeof(byte)
  227. || valT == typeof(sbyte)
  228. || valT == typeof(short)
  229. || valT == typeof(ushort)
  230. || valT == typeof(int)
  231. || valT == typeof(uint)
  232. || valT == typeof(long)
  233. || valT == typeof(IntPtr)) return typeof(Integer);
  234. if (valT == typeof(float)
  235. || valT == typeof(double)
  236. || valT == typeof(decimal)
  237. || valT == typeof(ulong) // ulong gets put into this, because decimal can hold it
  238. || valT == typeof(UIntPtr)) return typeof(FloatingPoint);
  239. if (typeof(IEnumerable).IsAssignableFrom(valT)) return typeof(List);
  240. // TODO: fill this out the rest of the way
  241. return typeof(Map); // default for various objects
  242. }
  243. }
  244. }