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.

1104 lines
49 KiB

  1. using IPA.Config.Data;
  2. using IPA.Config.Stores.Attributes;
  3. using IPA.Logging;
  4. using System;
  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;
  11. using System.Threading.Tasks;
  12. using System.Linq.Expressions;
  13. using System.Runtime.CompilerServices;
  14. using System.IO;
  15. using Boolean = IPA.Config.Data.Boolean;
  16. using System.Collections;
  17. using IPA.Utilities;
  18. #if NET3
  19. using Net3_Proxy;
  20. using Array = Net3_Proxy.Array;
  21. #endif
  22. [assembly: InternalsVisibleTo(IPA.Config.Stores.GeneratedExtension.AssemblyVisibilityTarget)]
  23. namespace IPA.Config.Stores
  24. {
  25. /// <summary>
  26. /// A class providing an extension for <see cref="Config"/> to make it easy to use generated
  27. /// config stores.
  28. /// </summary>
  29. public static class GeneratedExtension
  30. {
  31. /// <summary>
  32. /// The name of the assembly that internals must be visible to to allow internal protection.
  33. /// </summary>
  34. public const string AssemblyVisibilityTarget = GeneratedStore.GeneratedAssemblyName;
  35. /// <summary>
  36. /// Creates a generated <see cref="IConfigStore"/> of type <typeparamref name="T"/>, registers it to
  37. /// the <see cref="Config"/> object, and returns it. This also forces a synchronous config load via
  38. /// <see cref="Config.LoadSync"/> if <paramref name="loadSync"/> is <see langword="true"/>.
  39. /// </summary>
  40. /// <remarks>
  41. /// <para>
  42. /// <typeparamref name="T"/> must be a public non-<see langword="sealed"/> class.
  43. /// It can also be internal, but in that case, then your assembly must have the following attribute
  44. /// to allow the generated code to reference it.
  45. /// <code>
  46. /// [assembly: InternalsVisibleTo(IPA.Config.Stores.GeneratedExtension.AssemblyVisibilityTarget)]
  47. /// </code>
  48. /// </para>
  49. /// <para>
  50. /// Only fields and properties that are public or protected will be considered, and only properties
  51. /// where both the getter and setter are public or protected are considered. Any fields or properties
  52. /// with an <see cref="IgnoreAttribute"/> applied to them are also ignored. Having properties be <see langword="virtual"/> is not strictly
  53. /// necessary, however it allows the generated type to keep track of changes and lock around them so that the config will auto-save.
  54. /// </para>
  55. /// <para>
  56. /// All of the attributes in the <see cref="Attributes"/> namespace are handled as described by them.
  57. /// </para>
  58. /// <para>
  59. /// If the <typeparamref name="T"/> declares a public or protected, <see langword="virtual"/>
  60. /// method <c>Changed()</c>, then that method may be called to artificially signal to the runtime that the content of the object
  61. /// has changed. That method will also be called after the write locks are released when a property is set anywhere in the owning
  62. /// tree. This will only be called on the outermost generated object of the config structure, even if the change being signaled
  63. /// is somewhere deep into the tree.
  64. /// </para>
  65. /// <para>
  66. /// Similarly, <typeparamref name="T"/> can declare a public or protected, <see langword="virtual"/>
  67. /// method <c>OnReload()</c>, which will be called on the filesystem reader thread after the object has been repopulated with new data
  68. /// values. It will be called <i>after</i> the write lock for this object is released. This will only be called on the outermost generated
  69. /// object of the config structure.
  70. /// </para>
  71. /// <para>
  72. /// TODO: describe details of generated stores
  73. /// </para>
  74. /// </remarks>
  75. /// <typeparam name="T">the type to wrap</typeparam>
  76. /// <param name="cfg">the <see cref="Config"/> to register to</param>
  77. /// <param name="loadSync">whether to synchronously load the content, or trigger an async load</param>
  78. /// <returns>a generated instance of <typeparamref name="T"/> as a special <see cref="IConfigStore"/></returns>
  79. public static T Generated<T>(this Config cfg, bool loadSync = true) where T : class
  80. {
  81. var ret = GeneratedStore.Create<T>();
  82. cfg.SetStore(ret as IConfigStore);
  83. if (loadSync)
  84. cfg.LoadSync();
  85. else
  86. cfg.LoadAsync();
  87. return ret;
  88. }
  89. }
  90. internal static class GeneratedStore
  91. {
  92. internal interface IGeneratedStore
  93. {
  94. Type Type { get; }
  95. IGeneratedStore Parent { get; }
  96. Impl Impl { get; }
  97. void OnReload();
  98. Value Serialize();
  99. void Deserialize(Value val);
  100. }
  101. internal class Impl : IConfigStore
  102. {
  103. private IGeneratedStore generated;
  104. internal static ConstructorInfo Ctor = typeof(Impl).GetConstructor(new[] { typeof(IGeneratedStore) });
  105. public Impl(IGeneratedStore store) => generated = store;
  106. private readonly AutoResetEvent resetEvent = new AutoResetEvent(false);
  107. public WaitHandle SyncObject => resetEvent;
  108. internal static MethodInfo SyncObjectGetMethod = typeof(Impl).GetProperty(nameof(SyncObject)).GetGetMethod();
  109. public ReaderWriterLockSlim WriteSyncObject { get; } = new ReaderWriterLockSlim();
  110. internal static MethodInfo WriteSyncObjectGetMethod = typeof(Impl).GetProperty(nameof(WriteSyncObject)).GetGetMethod();
  111. internal static MethodInfo ImplSignalChangedMethod = typeof(Impl).GetMethod(nameof(ImplSignalChanged));
  112. public static void ImplSignalChanged(IGeneratedStore s) => FindImpl(s).SignalChanged();
  113. public void SignalChanged() => resetEvent.Set();
  114. internal static MethodInfo ImplTakeReadMethod = typeof(Impl).GetMethod(nameof(ImplTakeRead));
  115. public static void ImplTakeRead(IGeneratedStore s) => FindImpl(s).TakeRead();
  116. public void TakeRead() => WriteSyncObject.EnterReadLock();
  117. internal static MethodInfo ImplReleaseReadMethod = typeof(Impl).GetMethod(nameof(ImplReleaseRead));
  118. public static void ImplReleaseRead(IGeneratedStore s) => FindImpl(s).ReleaseRead();
  119. public void ReleaseRead() => WriteSyncObject.ExitReadLock();
  120. internal static MethodInfo ImplTakeWriteMethod = typeof(Impl).GetMethod(nameof(ImplTakeWrite));
  121. public static void ImplTakeWrite(IGeneratedStore s) => FindImpl(s).TakeWrite();
  122. public void TakeWrite() => WriteSyncObject.EnterWriteLock();
  123. internal static MethodInfo ImplReleaseWriteMethod = typeof(Impl).GetMethod(nameof(ImplReleaseWrite));
  124. public static void ImplReleaseWrite(IGeneratedStore s) => FindImpl(s).ReleaseWrite();
  125. public void ReleaseWrite() => WriteSyncObject.ExitWriteLock();
  126. internal static MethodInfo FindImplMethod = typeof(Impl).GetMethod(nameof(FindImpl));
  127. public static Impl FindImpl(IGeneratedStore store)
  128. {
  129. while (store?.Parent != null) store = store.Parent; // walk to the top of the tree
  130. return store?.Impl;
  131. }
  132. internal static MethodInfo ReadFromMethod = typeof(Impl).GetMethod(nameof(ReadFrom));
  133. public void ReadFrom(IConfigProvider provider)
  134. {
  135. var values = provider.Load();
  136. Logger.config.Debug("Generated impl ReadFrom");
  137. Logger.config.Debug($"Read {values}");
  138. generated.Deserialize(values);
  139. ReleaseWrite();
  140. generated.OnReload();
  141. TakeWrite(); // must take again for runtime to be happy (which is unfortunate)
  142. }
  143. internal static MethodInfo WriteToMethod = typeof(Impl).GetMethod(nameof(WriteTo));
  144. public void WriteTo(IConfigProvider provider)
  145. {
  146. var values = generated.Serialize();
  147. Logger.config.Debug("Generated impl WriteTo");
  148. Logger.config.Debug($"Serialized {values}");
  149. provider.Store(values);
  150. }
  151. }
  152. private static Dictionary<Type, Func<IGeneratedStore, IConfigStore>> generatedCreators = new Dictionary<Type, Func<IGeneratedStore, IConfigStore>>();
  153. private static Dictionary<Type, Dictionary<string, Type>> memberMaps = new Dictionary<Type, Dictionary<string, Type>>();
  154. public static T Create<T>() where T : class => (T)Create(typeof(T));
  155. public static IConfigStore Create(Type type) => Create(type, null);
  156. private static readonly MethodInfo CreateGParent =
  157. typeof(GeneratedStore).GetMethod(nameof(Create), BindingFlags.NonPublic | BindingFlags.Static, null,
  158. CallingConventions.Any, new[] { typeof(IGeneratedStore) }, Array.Empty<ParameterModifier>());
  159. internal static T Create<T>(IGeneratedStore parent) where T : class => (T)Create(typeof(T), parent);
  160. private static IConfigStore Create(Type type, IGeneratedStore parent)
  161. {
  162. if (generatedCreators.TryGetValue(type, out var creator))
  163. return creator(parent);
  164. else
  165. {
  166. creator = MakeCreator(type);
  167. generatedCreators.Add(type, creator);
  168. return creator(parent);
  169. }
  170. }
  171. internal const string GeneratedAssemblyName = "IPA.Config.Generated";
  172. private static AssemblyBuilder assembly = null;
  173. private static AssemblyBuilder Assembly
  174. {
  175. get
  176. {
  177. if (assembly == null)
  178. {
  179. var name = new AssemblyName(GeneratedAssemblyName);
  180. assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);
  181. }
  182. return assembly;
  183. }
  184. }
  185. internal static void DebugSaveAssembly(string file)
  186. {
  187. Assembly.Save(file);
  188. }
  189. private static ModuleBuilder module = null;
  190. private static ModuleBuilder Module
  191. {
  192. get
  193. {
  194. if (module == null)
  195. module = Assembly.DefineDynamicModule(Assembly.GetName().Name, Assembly.GetName().Name + ".dll");
  196. return module;
  197. }
  198. }
  199. private struct SerializedMemberInfo
  200. {
  201. public string Name;
  202. public MemberInfo Member;
  203. public Type Type;
  204. public bool AllowNull;
  205. public bool IsVirtual;
  206. public bool IsField;
  207. public bool IsNullable;
  208. // invalid for objects with IsNullabe false
  209. public Type NullableWrappedType => Nullable.GetUnderlyingType(Type);
  210. // invalid for objects with IsNullabe false
  211. public PropertyInfo Nullable_HasValue => Type.GetProperty(nameof(Nullable<int>.HasValue));
  212. // invalid for objects with IsNullabe false
  213. public PropertyInfo Nullable_Value => Type.GetProperty(nameof(Nullable<int>.Value));
  214. }
  215. private static Func<IGeneratedStore, IConfigStore> MakeCreator(Type type)
  216. {
  217. var baseCtor = type.GetConstructor(Type.EmptyTypes); // get a default constructor
  218. if (baseCtor == null)
  219. throw new ArgumentException("Config type does not have a public parameterless constructor");
  220. var typeBuilder = Module.DefineType($"{type.FullName}<Generated>",
  221. TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class, type);
  222. var typeField = typeBuilder.DefineField("<>_type", typeof(Type), FieldAttributes.Private | FieldAttributes.InitOnly);
  223. var implField = typeBuilder.DefineField("<>_impl", typeof(Impl), FieldAttributes.Private | FieldAttributes.InitOnly);
  224. var parentField = typeBuilder.DefineField("<>_parent", typeof(IGeneratedStore), FieldAttributes.Private | FieldAttributes.InitOnly);
  225. // none of this can be Expressions because CompileToMethod requires a static target method for some dumbass reason
  226. #region Parse base object structure
  227. var baseChanged = type.GetMethod("Changed", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  228. if (baseChanged != null && !baseChanged.IsVirtual) baseChanged = null; // limit this to just the one thing
  229. var baseOnReload = type.GetMethod("OnReload", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  230. if (baseOnReload != null && !baseOnReload.IsVirtual) baseOnReload = null; // limit this to just the one thing
  231. var structure = new List<SerializedMemberInfo>();
  232. // TODO: support converters
  233. bool ProcessAttributesFor(MemberInfo member, Type memberType, out string name, out bool allowNull, out bool isNullable)
  234. {
  235. var attrs = member.GetCustomAttributes(true);
  236. var ignores = attrs.Select(o => o as IgnoreAttribute).NonNull();
  237. if (ignores.Any()) // we ignore
  238. {
  239. name = null;
  240. allowNull = false;
  241. isNullable = false;
  242. return false;
  243. }
  244. var nonNullables = attrs.Select(o => o as NonNullableAttribute).NonNull();
  245. name = member.Name;
  246. isNullable = memberType.IsGenericType
  247. && memberType.GetGenericTypeDefinition() == typeof(Nullable<>);
  248. allowNull = !nonNullables.Any() && (!memberType.IsValueType || isNullable);
  249. var nameAttr = attrs.Select(o => o as SerializedNameAttribute).NonNull().FirstOrDefault();
  250. if (nameAttr != null)
  251. name = nameAttr.Name;
  252. return true;
  253. }
  254. // only looks at public/protected properties
  255. foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
  256. {
  257. if (prop.GetSetMethod(true)?.IsPrivate ?? true)
  258. { // we enter this block if the setter is inacessible or doesn't exist
  259. continue; // ignore props without setter
  260. }
  261. if (prop.GetGetMethod(true)?.IsPrivate ?? true)
  262. { // we enter this block if the getter is inacessible or doesn't exist
  263. continue; // ignore props without getter
  264. }
  265. var smi = new SerializedMemberInfo
  266. {
  267. Member = prop,
  268. IsVirtual = (prop.GetGetMethod(true)?.IsVirtual ?? false) ||
  269. (prop.GetSetMethod(true)?.IsVirtual ?? false),
  270. IsField = false,
  271. Type = prop.PropertyType
  272. };
  273. if (!ProcessAttributesFor(smi.Member, smi.Type, out smi.Name, out smi.AllowNull, out smi.IsNullable)) continue;
  274. structure.Add(smi);
  275. }
  276. // only look at public/protected fields
  277. foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
  278. {
  279. if (field.IsPrivate) continue;
  280. var smi = new SerializedMemberInfo
  281. {
  282. Member = field,
  283. IsVirtual = false,
  284. IsField = true,
  285. Type = field.FieldType
  286. };
  287. if (!ProcessAttributesFor(smi.Member, smi.Type, out smi.Name, out smi.AllowNull, out smi.IsNullable)) continue;
  288. structure.Add(smi);
  289. }
  290. #endregion
  291. #region Constructor
  292. var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IGeneratedStore) });
  293. { // because this is a constructor, it has to be raw IL
  294. var il = ctor.GetILGenerator();
  295. il.Emit(OpCodes.Ldarg_0); // keep this at bottom of stack
  296. il.Emit(OpCodes.Dup);
  297. il.Emit(OpCodes.Call, baseCtor);
  298. il.Emit(OpCodes.Dup);
  299. il.Emit(OpCodes.Ldarg_1); // load parent
  300. il.Emit(OpCodes.Stfld, parentField);
  301. il.Emit(OpCodes.Dup);
  302. EmitTypeof(il, type);
  303. il.Emit(OpCodes.Stfld, typeField);
  304. il.Emit(OpCodes.Dup);
  305. il.Emit(OpCodes.Dup);
  306. il.Emit(OpCodes.Newobj, Impl.Ctor);
  307. il.Emit(OpCodes.Stfld, implField);
  308. foreach (var member in structure)
  309. EmitMemberFix(il, member);
  310. il.Emit(OpCodes.Pop);
  311. il.Emit(OpCodes.Ret);
  312. }
  313. #endregion
  314. const MethodAttributes propertyMethodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
  315. const MethodAttributes virtualPropertyMethodAttr = propertyMethodAttr | MethodAttributes.Virtual | MethodAttributes.Final;
  316. const MethodAttributes virtualMemberMethod = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.Final;
  317. #region IGeneratedStore
  318. typeBuilder.AddInterfaceImplementation(typeof(IGeneratedStore));
  319. var IGeneratedStore_t = typeof(IGeneratedStore);
  320. var IGeneratedStore_GetImpl = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Impl)).GetGetMethod();
  321. var IGeneratedStore_GetType = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Type)).GetGetMethod();
  322. var IGeneratedStore_GetParent = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Parent)).GetGetMethod();
  323. var IGeneratedStore_Serialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Serialize));
  324. var IGeneratedStore_Deserialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Deserialize));
  325. var IGeneratedStore_OnReload = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.OnReload));
  326. #region IGeneratedStore.OnReload
  327. var onReload = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.OnReload)}", virtualMemberMethod, null, Type.EmptyTypes);
  328. typeBuilder.DefineMethodOverride(onReload, IGeneratedStore_OnReload);
  329. if (baseOnReload != null) typeBuilder.DefineMethodOverride(onReload, baseOnReload);
  330. {
  331. var il = onReload.GetILGenerator();
  332. if (baseOnReload != null)
  333. {
  334. il.Emit(OpCodes.Ldarg_0); // load this
  335. il.Emit(OpCodes.Tailcall);
  336. il.Emit(OpCodes.Call, baseOnReload); // load impl field
  337. }
  338. il.Emit(OpCodes.Ret);
  339. }
  340. #endregion
  341. #region IGeneratedStore.Impl
  342. var implProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Impl), PropertyAttributes.None, typeof(Impl), null);
  343. var implPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Impl)}", virtualPropertyMethodAttr, implProp.PropertyType, Type.EmptyTypes);
  344. implProp.SetGetMethod(implPropGet);
  345. typeBuilder.DefineMethodOverride(implPropGet, IGeneratedStore_GetImpl);
  346. {
  347. var il = implPropGet.GetILGenerator();
  348. il.Emit(OpCodes.Ldarg_0); // load this
  349. il.Emit(OpCodes.Ldfld, implField); // load impl field
  350. il.Emit(OpCodes.Ret);
  351. }
  352. #endregion
  353. #region IGeneratedStore.Type
  354. var typeProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Type), PropertyAttributes.None, typeof(Type), null);
  355. var typePropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Type)}", virtualPropertyMethodAttr, typeProp.PropertyType, Type.EmptyTypes);
  356. typeProp.SetGetMethod(typePropGet);
  357. typeBuilder.DefineMethodOverride(typePropGet, IGeneratedStore_GetType);
  358. {
  359. var il = typePropGet.GetILGenerator();
  360. il.Emit(OpCodes.Ldarg_0); // load this
  361. il.Emit(OpCodes.Ldfld, typeField); // load impl field
  362. il.Emit(OpCodes.Ret);
  363. }
  364. #endregion
  365. #region IGeneratedStore.Parent
  366. var parentProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Parent), PropertyAttributes.None, typeof(IGeneratedStore), null);
  367. var parentPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Parent)}", virtualPropertyMethodAttr, parentProp.PropertyType, Type.EmptyTypes);
  368. parentProp.SetGetMethod(parentPropGet);
  369. typeBuilder.DefineMethodOverride(parentPropGet, IGeneratedStore_GetParent);
  370. {
  371. var il = parentPropGet.GetILGenerator();
  372. il.Emit(OpCodes.Ldarg_0); // load this
  373. il.Emit(OpCodes.Ldfld, parentField); // load impl field
  374. il.Emit(OpCodes.Ret);
  375. }
  376. #endregion
  377. #region IGeneratedStore.Serialize
  378. var serializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Serialize)}", virtualPropertyMethodAttr, IGeneratedStore_Serialize.ReturnType, Type.EmptyTypes);
  379. typeBuilder.DefineMethodOverride(serializeGen, IGeneratedStore_Serialize);
  380. { // this is non-locking because the only code that will call this will already own the correct lock
  381. var il = serializeGen.GetILGenerator();
  382. var Map_Add = typeof(Map).GetMethod(nameof(Map.Add));
  383. il.Emit(OpCodes.Call, typeof(Value).GetMethod(nameof(Value.Map)));
  384. // the map is now at the top of the stack
  385. var locals = new List<LocalBuilder>();
  386. LocalBuilder GetLocal(Type ty, int i = 0)
  387. {
  388. var builder = locals.Where(b => b.LocalType == ty).Skip(i).FirstOrDefault();
  389. if (builder == null)
  390. {
  391. builder = il.DeclareLocal(ty);
  392. locals.Add(builder);
  393. }
  394. return builder;
  395. }
  396. foreach (var member in structure)
  397. {
  398. il.Emit(OpCodes.Dup);
  399. il.Emit(OpCodes.Ldstr, member.Name); // TODO: make this behave with annotations
  400. EmitSerializeMember(il, member, GetLocal);
  401. il.Emit(OpCodes.Call, Map_Add);
  402. }
  403. // the map is still at the top of the stack, return it
  404. il.Emit(OpCodes.Ret);
  405. }
  406. #endregion
  407. #region IGeneratedStore.Deserialize
  408. var deserializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Deserialize)}", virtualPropertyMethodAttr, null,
  409. new[] { IGeneratedStore_Deserialize.GetParameters()[0].ParameterType });
  410. typeBuilder.DefineMethodOverride(deserializeGen, IGeneratedStore_Deserialize);
  411. { // this is non-locking because the only code that will call this will already own the correct lock
  412. var il = deserializeGen.GetILGenerator();
  413. var Map_t = typeof(Map);
  414. var Map_TryGetValue = Map_t.GetMethod(nameof(Map.TryGetValue));
  415. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  416. var valueLocal = il.DeclareLocal(typeof(Value));
  417. var nonNull = il.DefineLabel();
  418. il.Emit(OpCodes.Ldarg_1);
  419. il.Emit(OpCodes.Brtrue, nonNull);
  420. EmitLogError(il, "Attempting to deserialize null", tailcall: true);
  421. il.Emit(OpCodes.Ret);
  422. il.MarkLabel(nonNull);
  423. il.Emit(OpCodes.Ldarg_1);
  424. il.Emit(OpCodes.Isinst, Map_t);
  425. il.Emit(OpCodes.Dup); // duplicate cloned value
  426. var notMapError = il.DefineLabel();
  427. il.Emit(OpCodes.Brtrue, notMapError);
  428. // handle error
  429. il.Emit(OpCodes.Pop); // removes the duplicate value
  430. EmitLogError(il, $"Invalid root for deserializing {type.FullName}", tailcall: true,
  431. expected: il => EmitTypeof(il, Map_t), found: il =>
  432. {
  433. il.Emit(OpCodes.Ldarg_1);
  434. il.Emit(OpCodes.Callvirt, Object_GetType);
  435. });
  436. il.Emit(OpCodes.Ret);
  437. var nextLabel = notMapError;
  438. var locals = new List<LocalBuilder>();
  439. LocalBuilder GetLocal(Type ty, int i = 0)
  440. {
  441. var builder = locals.Where(b => b.LocalType == ty).Skip(i).FirstOrDefault();
  442. if (builder == null)
  443. {
  444. builder = il.DeclareLocal(ty);
  445. locals.Add(builder);
  446. }
  447. return builder;
  448. }
  449. // head of stack is Map instance
  450. foreach (var member in structure)
  451. {
  452. il.MarkLabel(nextLabel);
  453. nextLabel = il.DefineLabel();
  454. var endErrorLabel = il.DefineLabel();
  455. il.Emit(OpCodes.Dup);
  456. il.Emit(OpCodes.Ldstr, member.Name);
  457. il.Emit(OpCodes.Ldloca_S, valueLocal);
  458. il.Emit(OpCodes.Call, Map_TryGetValue);
  459. il.Emit(OpCodes.Brtrue_S, endErrorLabel);
  460. EmitLogError(il, $"Missing key {member.Name}", tailcall: false);
  461. il.Emit(OpCodes.Br, nextLabel);
  462. il.MarkLabel(endErrorLabel);
  463. il.Emit(OpCodes.Ldloc_S, valueLocal);
  464. EmitDeserializeMember(il, member, nextLabel, il => il.Emit(OpCodes.Ldloc_S, valueLocal), GetLocal);
  465. }
  466. il.MarkLabel(nextLabel);
  467. il.Emit(OpCodes.Pop); // removes the duplicate value
  468. il.Emit(OpCodes.Ret);
  469. }
  470. #endregion
  471. #endregion
  472. #region IConfigStore
  473. typeBuilder.AddInterfaceImplementation(typeof(IConfigStore));
  474. var IConfigStore_t = typeof(IConfigStore);
  475. var IConfigStore_GetSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.SyncObject)).GetGetMethod();
  476. var IConfigStore_GetWriteSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.WriteSyncObject)).GetGetMethod();
  477. var IConfigStore_WriteTo = IConfigStore_t.GetMethod(nameof(IConfigStore.WriteTo));
  478. var IConfigStore_ReadFrom = IConfigStore_t.GetMethod(nameof(IConfigStore.ReadFrom));
  479. #region IConfigStore.SyncObject
  480. var syncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.SyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  481. var syncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.SyncObject)}", virtualPropertyMethodAttr, syncObjProp.PropertyType, Type.EmptyTypes);
  482. syncObjProp.SetGetMethod(syncObjPropGet);
  483. typeBuilder.DefineMethodOverride(syncObjPropGet, IConfigStore_GetSyncObject);
  484. {
  485. var il = syncObjPropGet.GetILGenerator();
  486. il.Emit(OpCodes.Ldarg_0);
  487. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  488. il.Emit(OpCodes.Tailcall);
  489. il.Emit(OpCodes.Call, Impl.SyncObjectGetMethod);
  490. il.Emit(OpCodes.Ret);
  491. }
  492. #endregion
  493. #region IConfigStore.WriteSyncObject
  494. var writeSyncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.WriteSyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  495. var writeSyncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.WriteSyncObject)}", virtualPropertyMethodAttr, writeSyncObjProp.PropertyType, Type.EmptyTypes);
  496. writeSyncObjProp.SetGetMethod(writeSyncObjPropGet);
  497. typeBuilder.DefineMethodOverride(writeSyncObjPropGet, IConfigStore_GetWriteSyncObject);
  498. {
  499. var il = writeSyncObjPropGet.GetILGenerator();
  500. il.Emit(OpCodes.Ldarg_0);
  501. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  502. il.Emit(OpCodes.Tailcall);
  503. il.Emit(OpCodes.Call, Impl.WriteSyncObjectGetMethod);
  504. il.Emit(OpCodes.Ret);
  505. }
  506. #endregion
  507. #region IConfigStore.WriteTo
  508. var writeTo = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.WriteTo)}", virtualMemberMethod, null, new[] { typeof(IConfigProvider) });
  509. typeBuilder.DefineMethodOverride(writeTo, IConfigStore_WriteTo);
  510. {
  511. var il = writeTo.GetILGenerator();
  512. il.Emit(OpCodes.Ldarg_0);
  513. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  514. il.Emit(OpCodes.Ldarg_1);
  515. il.Emit(OpCodes.Tailcall);
  516. il.Emit(OpCodes.Call, Impl.WriteToMethod);
  517. il.Emit(OpCodes.Ret);
  518. }
  519. #endregion
  520. #region IConfigStore.ReadFrom
  521. var readFrom = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.ReadFrom)}", virtualMemberMethod, null, new[] { typeof(IConfigProvider) });
  522. typeBuilder.DefineMethodOverride(readFrom, IConfigStore_ReadFrom);
  523. {
  524. var il = readFrom.GetILGenerator();
  525. il.Emit(OpCodes.Ldarg_0);
  526. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  527. il.Emit(OpCodes.Ldarg_1);
  528. il.Emit(OpCodes.Tailcall);
  529. il.Emit(OpCodes.Call, Impl.ReadFromMethod);
  530. il.Emit(OpCodes.Ret);
  531. }
  532. #endregion
  533. #endregion
  534. #region Changed
  535. var coreChanged = typeBuilder.DefineMethod(
  536. "<>Changed",
  537. MethodAttributes.Public | MethodAttributes.HideBySig,
  538. null, Type.EmptyTypes);
  539. {
  540. var il = coreChanged.GetILGenerator();
  541. il.Emit(OpCodes.Ldarg_0);
  542. il.Emit(OpCodes.Call, Impl.ImplSignalChangedMethod);
  543. il.Emit(OpCodes.Ret); // simply call our impl's SignalChanged method and return
  544. }
  545. if (baseChanged != null) {
  546. var changedMethod = typeBuilder.DefineMethod( // copy to override baseChanged
  547. baseChanged.Name,
  548. MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig,
  549. null, Type.EmptyTypes);
  550. typeBuilder.DefineMethodOverride(changedMethod, baseChanged);
  551. {
  552. var il = changedMethod.GetILGenerator();
  553. il.Emit(OpCodes.Ldarg_0);
  554. il.Emit(OpCodes.Call, baseChanged); // call base
  555. il.Emit(OpCodes.Ldarg_0);
  556. il.Emit(OpCodes.Tailcall);
  557. il.Emit(OpCodes.Call, coreChanged); // call back to the core change method
  558. il.Emit(OpCodes.Ret);
  559. }
  560. coreChanged = changedMethod; // switch to calling this version instead of just the default
  561. }
  562. #endregion
  563. // TODO: generate overrides for all the virtual properties
  564. var genType = typeBuilder.CreateType();
  565. var parentParam = Expression.Parameter(typeof(IGeneratedStore), "parent");
  566. var creatorDel = Expression.Lambda<Func<IGeneratedStore, IConfigStore>>(
  567. Expression.New(ctor, parentParam), parentParam
  568. ).Compile();
  569. { // register a member map
  570. var dict = new Dictionary<string, Type>();
  571. foreach (var member in structure)
  572. dict.Add(member.Name, member.Type);
  573. memberMaps.Add(type, dict);
  574. }
  575. return creatorDel;
  576. }
  577. #region Utility
  578. private static void EmitLogError(ILGenerator il, string message, bool tailcall = false, Action<ILGenerator> expected = null, Action<ILGenerator> found = null)
  579. {
  580. if (expected == null) expected = il => il.Emit(OpCodes.Ldnull);
  581. if (found == null) found = il => il.Emit(OpCodes.Ldnull);
  582. expected(il);
  583. found(il);
  584. il.Emit(OpCodes.Ldstr, message);
  585. if (tailcall) il.Emit(OpCodes.Tailcall);
  586. il.Emit(OpCodes.Call, LogErrorMethod);
  587. }
  588. private static readonly MethodInfo Type_GetTypeFromHandle = typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle));
  589. private static void EmitTypeof(ILGenerator il, Type type)
  590. {
  591. il.Emit(OpCodes.Ldtoken, type);
  592. il.Emit(OpCodes.Call, Type_GetTypeFromHandle);
  593. }
  594. private static Type Decimal_t = typeof(decimal);
  595. private static ConstructorInfo Decimal_FromFloat = Decimal_t.GetConstructor(new[] { typeof(float) });
  596. private static ConstructorInfo Decimal_FromDouble = Decimal_t.GetConstructor(new[] { typeof(double) });
  597. private static ConstructorInfo Decimal_FromInt = Decimal_t.GetConstructor(new[] { typeof(int) });
  598. private static ConstructorInfo Decimal_FromUInt = Decimal_t.GetConstructor(new[] { typeof(uint) });
  599. private static ConstructorInfo Decimal_FromLong = Decimal_t.GetConstructor(new[] { typeof(long) });
  600. private static ConstructorInfo Decimal_FromULong = Decimal_t.GetConstructor(new[] { typeof(ulong) });
  601. private static void EmitNumberConvertTo(ILGenerator il, Type to, Type from)
  602. { // WARNING: THIS USES THE NO-OVERFLOW OPCODES
  603. if (to == from) return;
  604. if (to == Decimal_t)
  605. {
  606. if (from == typeof(float)) il.Emit(OpCodes.Newobj, Decimal_FromFloat);
  607. else if (from == typeof(double)) il.Emit(OpCodes.Newobj, Decimal_FromDouble);
  608. else if (from == typeof(long)) il.Emit(OpCodes.Newobj, Decimal_FromLong);
  609. else if (from == typeof(ulong)) il.Emit(OpCodes.Newobj, Decimal_FromULong);
  610. else if (from == typeof(int)) il.Emit(OpCodes.Newobj, Decimal_FromInt);
  611. else if (from == typeof(uint)) il.Emit(OpCodes.Newobj, Decimal_FromUInt);
  612. else if (from == typeof(IntPtr))
  613. {
  614. EmitNumberConvertTo(il, typeof(long), from);
  615. EmitNumberConvertTo(il, to, typeof(long));
  616. }
  617. else if (from == typeof(UIntPtr))
  618. {
  619. EmitNumberConvertTo(il, typeof(ulong), from);
  620. EmitNumberConvertTo(il, to, typeof(ulong));
  621. }
  622. else
  623. { // if the source is anything else, we first convert to int because that can contain all other values
  624. EmitNumberConvertTo(il, typeof(int), from);
  625. EmitNumberConvertTo(il, to, typeof(int));
  626. };
  627. }
  628. else if (from == Decimal_t)
  629. {
  630. if (to == typeof(IntPtr))
  631. {
  632. EmitNumberConvertTo(il, typeof(long), from);
  633. EmitNumberConvertTo(il, to, typeof(long));
  634. }
  635. else if (to == typeof(UIntPtr))
  636. {
  637. EmitNumberConvertTo(il, typeof(ulong), from);
  638. EmitNumberConvertTo(il, to, typeof(ulong));
  639. }
  640. else
  641. {
  642. var method = Decimal_t.GetMethod($"To{to.Name}"); // conveniently, this is the pattern of the to* names
  643. il.Emit(OpCodes.Call, method);
  644. }
  645. }
  646. else if (to == typeof(IntPtr)) il.Emit(OpCodes.Conv_I);
  647. else if (to == typeof(UIntPtr)) il.Emit(OpCodes.Conv_U);
  648. else if (to == typeof(sbyte)) il.Emit(OpCodes.Conv_I1);
  649. else if (to == typeof(byte)) il.Emit(OpCodes.Conv_U1);
  650. else if (to == typeof(short)) il.Emit(OpCodes.Conv_I2);
  651. else if (to == typeof(ushort)) il.Emit(OpCodes.Conv_U2);
  652. else if (to == typeof(int)) il.Emit(OpCodes.Conv_I4);
  653. else if (to == typeof(uint)) il.Emit(OpCodes.Conv_U4);
  654. else if (to == typeof(long)) il.Emit(OpCodes.Conv_I8);
  655. else if (to == typeof(ulong)) il.Emit(OpCodes.Conv_U8);
  656. else if (to == typeof(float))
  657. {
  658. if (from == typeof(byte)
  659. || from == typeof(ushort)
  660. || from == typeof(uint)
  661. || from == typeof(ulong)
  662. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  663. il.Emit(OpCodes.Conv_R4);
  664. }
  665. else if (to == typeof(double))
  666. {
  667. if (from == typeof(byte)
  668. || from == typeof(ushort)
  669. || from == typeof(uint)
  670. || from == typeof(ulong)
  671. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  672. il.Emit(OpCodes.Conv_R8);
  673. }
  674. }
  675. private static void EmitCreateChildGenerated(ILGenerator il, Type childType)
  676. {
  677. var method = CreateGParent.MakeGenericMethod(childType);
  678. il.Emit(OpCodes.Ldarg_0);
  679. il.Emit(OpCodes.Call, method);
  680. }
  681. #endregion
  682. private static readonly MethodInfo LogErrorMethod = typeof(GeneratedStore).GetMethod(nameof(LogError), BindingFlags.NonPublic | BindingFlags.Static);
  683. internal static void LogError(Type expected, Type found, string message)
  684. {
  685. Logger.config.Notice($"{message}{(expected == null ? "" : $" (expected {expected}, found {found?.ToString() ?? "null"})")}");
  686. }
  687. // expects the this param to be on the stack
  688. private static void EmitMemberFix(ILGenerator il, SerializedMemberInfo member)
  689. {
  690. // TODO: impl
  691. }
  692. #region Serialize
  693. // emit takes no args, leaves Value at top of stack
  694. private static void EmitSerializeMember(ILGenerator il, SerializedMemberInfo member, Func<Type, int, LocalBuilder> GetLocal)
  695. {
  696. void EmitLoad()
  697. {
  698. il.Emit(OpCodes.Ldarg_0); // load this
  699. if (member.IsField)
  700. il.Emit(OpCodes.Ldfld, member.Member as FieldInfo);
  701. else
  702. { // member is a property
  703. var prop = member.Member as PropertyInfo;
  704. var getter = prop.GetGetMethod();
  705. if (getter == null) throw new InvalidOperationException($"Property {member.Name} does not have a getter and is not ignored");
  706. il.Emit(OpCodes.Call, getter);
  707. }
  708. }
  709. EmitLoad();
  710. var endSerialize = il.DefineLabel();
  711. if (member.AllowNull)
  712. {
  713. var passedNull = il.DefineLabel();
  714. il.Emit(OpCodes.Dup);
  715. il.Emit(OpCodes.Brtrue, passedNull);
  716. // TODO: add special check for nullables
  717. il.Emit(OpCodes.Pop);
  718. il.Emit(OpCodes.Ldnull);
  719. il.Emit(OpCodes.Br, endSerialize);
  720. il.MarkLabel(passedNull);
  721. }
  722. var targetType = GetExpectedValueTypeForType(member.Type);
  723. if (targetType == typeof(Text))
  724. { // only happens when arg is a string or char
  725. var TextCreate = typeof(Value).GetMethod(nameof(Value.Text));
  726. if (member.Type == typeof(char))
  727. {
  728. var strFromChar = typeof(char).GetMethod(nameof(char.ToString), new[] { typeof(char) });
  729. il.Emit(OpCodes.Call, strFromChar);
  730. }
  731. il.Emit(OpCodes.Call, TextCreate);
  732. }
  733. else if (targetType == typeof(Boolean))
  734. {
  735. var BoolCreate = typeof(Value).GetMethod(nameof(Value.Bool));
  736. il.Emit(OpCodes.Call, BoolCreate);
  737. }
  738. else if (targetType == typeof(Integer))
  739. {
  740. var IntCreate = typeof(Value).GetMethod(nameof(Value.Integer));
  741. EmitNumberConvertTo(il, IntCreate.GetParameters()[0].ParameterType, member.Type);
  742. il.Emit(OpCodes.Call, IntCreate);
  743. }
  744. else if (targetType == typeof(FloatingPoint))
  745. {
  746. var FloatCreate = typeof(Value).GetMethod(nameof(Value.Float));
  747. EmitNumberConvertTo(il, FloatCreate.GetParameters()[0].ParameterType, member.Type);
  748. il.Emit(OpCodes.Call, FloatCreate);
  749. }
  750. else if (targetType == typeof(List))
  751. {
  752. // TODO: impl this
  753. il.Emit(OpCodes.Pop);
  754. il.Emit(OpCodes.Ldnull);
  755. }
  756. else if (targetType == typeof(Map))
  757. {
  758. // TODO: support other aggregate types
  759. // for now, we assume that its a generated type implementing IGeneratedStore
  760. var IGeneratedStore_Serialize = typeof(IGeneratedStore).GetMethod(nameof(IGeneratedStore.Serialize));
  761. il.Emit(OpCodes.Callvirt, IGeneratedStore_Serialize);
  762. }
  763. il.MarkLabel(endSerialize);
  764. // TODO: implement converters
  765. }
  766. #endregion
  767. #region Deserialize
  768. private static Type GetExpectedValueTypeForType(Type valT)
  769. {
  770. if (typeof(Value).IsAssignableFrom(valT)) // this is a Value subtype
  771. return valT;
  772. if (valT == typeof(string)
  773. || valT == typeof(char)) return typeof(Text);
  774. if (valT == typeof(bool)) return typeof(Boolean);
  775. if (valT == typeof(byte)
  776. || valT == typeof(sbyte)
  777. || valT == typeof(short)
  778. || valT == typeof(ushort)
  779. || valT == typeof(int)
  780. || valT == typeof(uint)
  781. || valT == typeof(long)
  782. || valT == typeof(ulong)) return typeof(Integer);
  783. if (valT == typeof(float)
  784. || valT == typeof(double)
  785. || valT == typeof(decimal)) return typeof(FloatingPoint);
  786. if (typeof(IEnumerable).IsAssignableFrom(valT)) return typeof(List);
  787. // TODO: fill this out the rest of the way
  788. // TODO: support converters
  789. return typeof(Map); // default for various objects
  790. }
  791. private static void EmitDeserializeGeneratedValue(ILGenerator il, Type targetType, Type srcType, Func<Type, int, LocalBuilder> GetLocal)
  792. {
  793. var IGeneratedStore_Deserialize = typeof(IGeneratedStore).GetMethod(nameof(IGeneratedStore.Deserialize));
  794. var valuel = GetLocal(srcType, 0);
  795. il.Emit(OpCodes.Stloc, valuel);
  796. EmitCreateChildGenerated(il, targetType);
  797. il.Emit(OpCodes.Dup);
  798. il.Emit(OpCodes.Ldloc, valuel);
  799. il.Emit(OpCodes.Callvirt, IGeneratedStore_Deserialize);
  800. }
  801. // top of stack is the Value to deserialize; the type will be as returned from GetExpectedValueTypeForType
  802. // after, top of stack will be thing to write to field
  803. private static void EmitDeserializeValue(ILGenerator il, Type targetType, Type expected, Func<Type, int, LocalBuilder> GetLocal)
  804. {
  805. if (typeof(Value).IsAssignableFrom(targetType)) return; // do nothing
  806. if (expected == typeof(Text))
  807. {
  808. var getter = expected.GetProperty(nameof(Text.Value)).GetGetMethod();
  809. il.Emit(OpCodes.Call, getter);
  810. if (targetType == typeof(char))
  811. {
  812. var strIndex = typeof(string).GetProperty("Chars").GetGetMethod(); // string's indexer is specially named Chars
  813. il.Emit(OpCodes.Ldc_I4_0);
  814. il.Emit(OpCodes.Call, strIndex);
  815. }
  816. }
  817. else if (expected == typeof(Boolean))
  818. {
  819. var getter = expected.GetProperty(nameof(Boolean.Value)).GetGetMethod();
  820. il.Emit(OpCodes.Call, getter);
  821. }
  822. else if (expected == typeof(Integer))
  823. {
  824. var getter = expected.GetProperty(nameof(Integer.Value)).GetGetMethod();
  825. il.Emit(OpCodes.Call, getter);
  826. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  827. }
  828. else if (expected == typeof(FloatingPoint))
  829. {
  830. var getter = expected.GetProperty(nameof(FloatingPoint.Value)).GetGetMethod();
  831. il.Emit(OpCodes.Call, getter);
  832. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  833. } // TODO: implement stuff for lists and maps of various types (probably call out somewhere else to figure out what to do)
  834. else if (expected == typeof(Map))
  835. {
  836. EmitDeserializeGeneratedValue(il, targetType, expected, GetLocal);
  837. }
  838. else // TODO: support converters
  839. {
  840. il.Emit(OpCodes.Pop);
  841. il.Emit(OpCodes.Ldnull);
  842. }
  843. }
  844. // emit takes the value being deserialized, logs on error, leaves nothing on stack
  845. private static void EmitDeserializeMember(ILGenerator il, SerializedMemberInfo member, Label nextLabel, Action<ILGenerator> getValue, Func<Type, int, LocalBuilder> GetLocal)
  846. {
  847. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  848. var implLabel = il.DefineLabel();
  849. var passedTypeCheck = il.DefineLabel();
  850. var expectType = GetExpectedValueTypeForType(member.Type);
  851. void EmitStore(Action<ILGenerator> value)
  852. {
  853. il.Emit(OpCodes.Ldarg_0); // load this
  854. value(il);
  855. if (member.IsField)
  856. il.Emit(OpCodes.Stfld, member.Member as FieldInfo);
  857. else
  858. { // member is a property
  859. var prop = member.Member as PropertyInfo;
  860. var setter = prop.GetSetMethod();
  861. if (setter == null) throw new InvalidOperationException($"Property {member.Name} does not have a setter and is not ignored");
  862. il.Emit(OpCodes.Call, setter);
  863. }
  864. }
  865. il.Emit(OpCodes.Dup);
  866. il.Emit(OpCodes.Brtrue_S, implLabel); // null check
  867. // TODO: support Nullable<T>
  868. if (!member.AllowNull)
  869. {
  870. il.Emit(OpCodes.Pop);
  871. EmitLogError(il, $"Member {member.Name} ({member.Type}) not nullable", tailcall: false,
  872. expected: il => EmitTypeof(il, expectType));
  873. il.Emit(OpCodes.Br, nextLabel);
  874. }
  875. else
  876. {
  877. il.Emit(OpCodes.Pop);
  878. EmitStore(il => il.Emit(OpCodes.Ldnull));
  879. il.Emit(OpCodes.Br, nextLabel);
  880. }
  881. il.MarkLabel(implLabel);
  882. il.Emit(OpCodes.Isinst, expectType); //replaces on stack
  883. il.Emit(OpCodes.Dup); // duplicate cloned value
  884. il.Emit(OpCodes.Brtrue, passedTypeCheck); // null check
  885. var errorHandle = il.DefineLabel();
  886. // special cases to handle coersion between Float and Int
  887. if (expectType == typeof(FloatingPoint))
  888. {
  889. var specialTypeCheck = il.DefineLabel();
  890. il.Emit(OpCodes.Pop);
  891. getValue(il);
  892. il.Emit(OpCodes.Isinst, typeof(Integer)); //replaces on stack
  893. il.Emit(OpCodes.Dup); // duplicate cloned value
  894. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  895. var Integer_CoerceToFloat = typeof(Integer).GetMethod(nameof(Integer.AsFloat));
  896. il.Emit(OpCodes.Call, Integer_CoerceToFloat);
  897. il.Emit(OpCodes.Br, passedTypeCheck);
  898. }
  899. else if (expectType == typeof(Integer))
  900. {
  901. var specialTypeCheck = il.DefineLabel();
  902. il.Emit(OpCodes.Pop);
  903. getValue(il);
  904. il.Emit(OpCodes.Isinst, typeof(FloatingPoint)); //replaces on stack
  905. il.Emit(OpCodes.Dup); // duplicate cloned value
  906. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  907. var Float_CoerceToInt = typeof(FloatingPoint).GetMethod(nameof(FloatingPoint.AsInteger));
  908. il.Emit(OpCodes.Call, Float_CoerceToInt);
  909. il.Emit(OpCodes.Br, passedTypeCheck);
  910. }
  911. il.MarkLabel(errorHandle);
  912. il.Emit(OpCodes.Pop);
  913. EmitLogError(il, $"Unexpected type deserializing {member.Name}", tailcall: false,
  914. expected: il => EmitTypeof(il, expectType), found: il =>
  915. {
  916. getValue(il);
  917. il.Emit(OpCodes.Callvirt, Object_GetType);
  918. });
  919. il.Emit(OpCodes.Br, nextLabel);
  920. il.MarkLabel(passedTypeCheck);
  921. var local = GetLocal(member.Type, 0);
  922. EmitDeserializeValue(il, member.Type, expectType, GetLocal);
  923. il.Emit(OpCodes.Stloc, local);
  924. EmitStore(il => il.Emit(OpCodes.Ldloc, local));
  925. }
  926. #endregion
  927. }
  928. }