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.

1222 lines
54 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. TODO: is this a good idea?
  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. void Changed();
  99. Value Serialize();
  100. void Deserialize(Value val);
  101. }
  102. internal class Impl : IConfigStore
  103. {
  104. private IGeneratedStore generated;
  105. internal static ConstructorInfo Ctor = typeof(Impl).GetConstructor(new[] { typeof(IGeneratedStore) });
  106. public Impl(IGeneratedStore store) => generated = store;
  107. private readonly AutoResetEvent resetEvent = new AutoResetEvent(false);
  108. public WaitHandle SyncObject => resetEvent;
  109. internal static MethodInfo SyncObjectGetMethod = typeof(Impl).GetProperty(nameof(SyncObject)).GetGetMethod();
  110. public ReaderWriterLockSlim WriteSyncObject { get; } = new ReaderWriterLockSlim();
  111. internal static MethodInfo WriteSyncObjectGetMethod = typeof(Impl).GetProperty(nameof(WriteSyncObject)).GetGetMethod();
  112. internal static MethodInfo ImplSignalChangedMethod = typeof(Impl).GetMethod(nameof(ImplSignalChanged));
  113. public static void ImplSignalChanged(IGeneratedStore s) => FindImpl(s).SignalChanged();
  114. public void SignalChanged() => resetEvent.Set();
  115. internal static MethodInfo ImplInvokeChangedMethod = typeof(Impl).GetMethod(nameof(ImplInvokeChanged));
  116. public static void ImplInvokeChanged(IGeneratedStore s) => FindImpl(s).InvokeChanged();
  117. public void InvokeChanged() => generated.Changed();
  118. internal static MethodInfo ImplTakeReadMethod = typeof(Impl).GetMethod(nameof(ImplTakeRead));
  119. public static void ImplTakeRead(IGeneratedStore s) => FindImpl(s).TakeRead();
  120. public void TakeRead() => WriteSyncObject.EnterReadLock();
  121. internal static MethodInfo ImplReleaseReadMethod = typeof(Impl).GetMethod(nameof(ImplReleaseRead));
  122. public static void ImplReleaseRead(IGeneratedStore s) => FindImpl(s).ReleaseRead();
  123. public void ReleaseRead() => WriteSyncObject.ExitReadLock();
  124. internal static MethodInfo ImplTakeWriteMethod = typeof(Impl).GetMethod(nameof(ImplTakeWrite));
  125. public static void ImplTakeWrite(IGeneratedStore s) => FindImpl(s).TakeWrite();
  126. public void TakeWrite() => WriteSyncObject.EnterWriteLock();
  127. internal static MethodInfo ImplReleaseWriteMethod = typeof(Impl).GetMethod(nameof(ImplReleaseWrite));
  128. public static void ImplReleaseWrite(IGeneratedStore s) => FindImpl(s).ReleaseWrite();
  129. public void ReleaseWrite() => WriteSyncObject.ExitWriteLock();
  130. internal static MethodInfo FindImplMethod = typeof(Impl).GetMethod(nameof(FindImpl));
  131. public static Impl FindImpl(IGeneratedStore store)
  132. {
  133. while (store?.Parent != null) store = store.Parent; // walk to the top of the tree
  134. return store?.Impl;
  135. }
  136. internal static MethodInfo ReadFromMethod = typeof(Impl).GetMethod(nameof(ReadFrom));
  137. public void ReadFrom(IConfigProvider provider)
  138. {
  139. var values = provider.Load();
  140. Logger.config.Debug("Generated impl ReadFrom");
  141. Logger.config.Debug($"Read {values}");
  142. generated.Deserialize(values);
  143. ReleaseWrite();
  144. generated.OnReload();
  145. TakeWrite(); // must take again for runtime to be happy (which is unfortunate)
  146. }
  147. internal static MethodInfo WriteToMethod = typeof(Impl).GetMethod(nameof(WriteTo));
  148. public void WriteTo(IConfigProvider provider)
  149. {
  150. var values = generated.Serialize();
  151. Logger.config.Debug("Generated impl WriteTo");
  152. Logger.config.Debug($"Serialized {values}");
  153. provider.Store(values);
  154. }
  155. }
  156. private static Dictionary<Type, Func<IGeneratedStore, IConfigStore>> generatedCreators = new Dictionary<Type, Func<IGeneratedStore, IConfigStore>>();
  157. private static Dictionary<Type, Dictionary<string, Type>> memberMaps = new Dictionary<Type, Dictionary<string, Type>>();
  158. public static T Create<T>() where T : class => (T)Create(typeof(T));
  159. public static IConfigStore Create(Type type) => Create(type, null);
  160. private static readonly MethodInfo CreateGParent =
  161. typeof(GeneratedStore).GetMethod(nameof(Create), BindingFlags.NonPublic | BindingFlags.Static, null,
  162. CallingConventions.Any, new[] { typeof(IGeneratedStore) }, Array.Empty<ParameterModifier>());
  163. internal static T Create<T>(IGeneratedStore parent) where T : class => (T)Create(typeof(T), parent);
  164. private static IConfigStore Create(Type type, IGeneratedStore parent)
  165. {
  166. if (generatedCreators.TryGetValue(type, out var creator))
  167. return creator(parent);
  168. else
  169. {
  170. creator = MakeCreator(type);
  171. generatedCreators.Add(type, creator);
  172. return creator(parent);
  173. }
  174. }
  175. internal const string GeneratedAssemblyName = "IPA.Config.Generated";
  176. private static AssemblyBuilder assembly = null;
  177. private static AssemblyBuilder Assembly
  178. {
  179. get
  180. {
  181. if (assembly == null)
  182. {
  183. var name = new AssemblyName(GeneratedAssemblyName);
  184. assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);
  185. }
  186. return assembly;
  187. }
  188. }
  189. internal static void DebugSaveAssembly(string file)
  190. {
  191. Assembly.Save(file);
  192. }
  193. private static ModuleBuilder module = null;
  194. private static ModuleBuilder Module
  195. {
  196. get
  197. {
  198. if (module == null)
  199. module = Assembly.DefineDynamicModule(Assembly.GetName().Name, Assembly.GetName().Name + ".dll");
  200. return module;
  201. }
  202. }
  203. private struct SerializedMemberInfo
  204. {
  205. public string Name;
  206. public MemberInfo Member;
  207. public Type Type;
  208. public bool AllowNull;
  209. public bool IsVirtual;
  210. public bool IsField;
  211. public bool IsNullable; // signifies whether this is a Nullable<T>
  212. // invalid for objects with IsNullabe false
  213. public Type NullableWrappedType => Nullable.GetUnderlyingType(Type);
  214. // invalid for objects with IsNullabe false
  215. public PropertyInfo Nullable_HasValue => Type.GetProperty(nameof(Nullable<int>.HasValue));
  216. // invalid for objects with IsNullabe false
  217. public PropertyInfo Nullable_Value => Type.GetProperty(nameof(Nullable<int>.Value));
  218. // invalid for objects with IsNullabe false
  219. public ConstructorInfo Nullable_Construct => Type.GetConstructor(new[] { NullableWrappedType });
  220. }
  221. private static Func<IGeneratedStore, IConfigStore> MakeCreator(Type type)
  222. {
  223. var baseCtor = type.GetConstructor(Type.EmptyTypes); // get a default constructor
  224. if (baseCtor == null)
  225. throw new ArgumentException("Config type does not have a public parameterless constructor");
  226. var typeBuilder = Module.DefineType($"{type.FullName}<Generated>",
  227. TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class, type);
  228. var typeField = typeBuilder.DefineField("<>_type", typeof(Type), FieldAttributes.Private | FieldAttributes.InitOnly);
  229. var implField = typeBuilder.DefineField("<>_impl", typeof(Impl), FieldAttributes.Private | FieldAttributes.InitOnly);
  230. var parentField = typeBuilder.DefineField("<>_parent", typeof(IGeneratedStore), FieldAttributes.Private | FieldAttributes.InitOnly);
  231. // none of this can be Expressions because CompileToMethod requires a static target method for some dumbass reason
  232. #region Parse base object structure
  233. var baseChanged = type.GetMethod("Changed", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  234. if (baseChanged != null && !baseChanged.IsVirtual) baseChanged = null; // limit this to just the one thing
  235. var baseOnReload = type.GetMethod("OnReload", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  236. if (baseOnReload != null && !baseOnReload.IsVirtual) baseOnReload = null; // limit this to just the one thing
  237. var structure = new List<SerializedMemberInfo>();
  238. // TODO: support converters
  239. bool ProcessAttributesFor(MemberInfo member, Type memberType, out string name, out bool allowNull, out bool isNullable)
  240. {
  241. var attrs = member.GetCustomAttributes(true);
  242. var ignores = attrs.Select(o => o as IgnoreAttribute).NonNull();
  243. if (ignores.Any()) // we ignore
  244. {
  245. name = null;
  246. allowNull = false;
  247. isNullable = false;
  248. return false;
  249. }
  250. var nonNullables = attrs.Select(o => o as NonNullableAttribute).NonNull();
  251. name = member.Name;
  252. isNullable = memberType.IsGenericType
  253. && memberType.GetGenericTypeDefinition() == typeof(Nullable<>);
  254. allowNull = !nonNullables.Any() && (!memberType.IsValueType || isNullable);
  255. var nameAttr = attrs.Select(o => o as SerializedNameAttribute).NonNull().FirstOrDefault();
  256. if (nameAttr != null)
  257. name = nameAttr.Name;
  258. return true;
  259. }
  260. // only looks at public/protected properties
  261. foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
  262. {
  263. if (prop.GetSetMethod(true)?.IsPrivate ?? true)
  264. { // we enter this block if the setter is inacessible or doesn't exist
  265. continue; // ignore props without setter
  266. }
  267. if (prop.GetGetMethod(true)?.IsPrivate ?? true)
  268. { // we enter this block if the getter is inacessible or doesn't exist
  269. continue; // ignore props without getter
  270. }
  271. var smi = new SerializedMemberInfo
  272. {
  273. Member = prop,
  274. IsVirtual = (prop.GetGetMethod(true)?.IsVirtual ?? false) ||
  275. (prop.GetSetMethod(true)?.IsVirtual ?? false),
  276. IsField = false,
  277. Type = prop.PropertyType
  278. };
  279. if (!ProcessAttributesFor(smi.Member, smi.Type, out smi.Name, out smi.AllowNull, out smi.IsNullable)) continue;
  280. structure.Add(smi);
  281. }
  282. // only look at public/protected fields
  283. foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
  284. {
  285. if (field.IsPrivate) continue;
  286. var smi = new SerializedMemberInfo
  287. {
  288. Member = field,
  289. IsVirtual = false,
  290. IsField = true,
  291. Type = field.FieldType
  292. };
  293. if (!ProcessAttributesFor(smi.Member, smi.Type, out smi.Name, out smi.AllowNull, out smi.IsNullable)) continue;
  294. structure.Add(smi);
  295. }
  296. #endregion
  297. #region Constructor
  298. var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IGeneratedStore) });
  299. { // because this is a constructor, it has to be raw IL
  300. var il = ctor.GetILGenerator();
  301. il.Emit(OpCodes.Ldarg_0); // keep this at bottom of stack
  302. il.Emit(OpCodes.Dup);
  303. il.Emit(OpCodes.Call, baseCtor);
  304. il.Emit(OpCodes.Dup);
  305. il.Emit(OpCodes.Ldarg_1); // load parent
  306. il.Emit(OpCodes.Stfld, parentField);
  307. il.Emit(OpCodes.Dup);
  308. EmitTypeof(il, type);
  309. il.Emit(OpCodes.Stfld, typeField);
  310. il.Emit(OpCodes.Dup);
  311. il.Emit(OpCodes.Dup);
  312. il.Emit(OpCodes.Newobj, Impl.Ctor);
  313. il.Emit(OpCodes.Stfld, implField);
  314. var GetLocal = MakeGetLocal(il);
  315. foreach (var member in structure)
  316. {
  317. EmitMemberFix(il, member, GetLocal);
  318. }
  319. il.Emit(OpCodes.Pop);
  320. il.Emit(OpCodes.Ret);
  321. }
  322. #endregion
  323. const MethodAttributes propertyMethodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
  324. const MethodAttributes virtualPropertyMethodAttr = propertyMethodAttr | MethodAttributes.Virtual | MethodAttributes.Final;
  325. const MethodAttributes virtualMemberMethod = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.Final;
  326. #region IGeneratedStore
  327. typeBuilder.AddInterfaceImplementation(typeof(IGeneratedStore));
  328. var IGeneratedStore_t = typeof(IGeneratedStore);
  329. var IGeneratedStore_GetImpl = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Impl)).GetGetMethod();
  330. var IGeneratedStore_GetType = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Type)).GetGetMethod();
  331. var IGeneratedStore_GetParent = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Parent)).GetGetMethod();
  332. var IGeneratedStore_Serialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Serialize));
  333. var IGeneratedStore_Deserialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Deserialize));
  334. var IGeneratedStore_OnReload = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.OnReload));
  335. var IGeneratedStore_Changed = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Changed));
  336. #region IGeneratedStore.OnReload
  337. var onReload = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.OnReload)}", virtualMemberMethod, null, Type.EmptyTypes);
  338. typeBuilder.DefineMethodOverride(onReload, IGeneratedStore_OnReload);
  339. if (baseOnReload != null) typeBuilder.DefineMethodOverride(onReload, baseOnReload);
  340. {
  341. var il = onReload.GetILGenerator();
  342. if (baseOnReload != null)
  343. {
  344. il.Emit(OpCodes.Ldarg_0); // load this
  345. il.Emit(OpCodes.Tailcall);
  346. il.Emit(OpCodes.Call, baseOnReload); // load impl field
  347. }
  348. il.Emit(OpCodes.Ret);
  349. }
  350. #endregion
  351. #region IGeneratedStore.Impl
  352. var implProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Impl), PropertyAttributes.None, typeof(Impl), null);
  353. var implPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Impl)}", virtualPropertyMethodAttr, implProp.PropertyType, Type.EmptyTypes);
  354. implProp.SetGetMethod(implPropGet);
  355. typeBuilder.DefineMethodOverride(implPropGet, IGeneratedStore_GetImpl);
  356. {
  357. var il = implPropGet.GetILGenerator();
  358. il.Emit(OpCodes.Ldarg_0); // load this
  359. il.Emit(OpCodes.Ldfld, implField); // load impl field
  360. il.Emit(OpCodes.Ret);
  361. }
  362. #endregion
  363. #region IGeneratedStore.Type
  364. var typeProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Type), PropertyAttributes.None, typeof(Type), null);
  365. var typePropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Type)}", virtualPropertyMethodAttr, typeProp.PropertyType, Type.EmptyTypes);
  366. typeProp.SetGetMethod(typePropGet);
  367. typeBuilder.DefineMethodOverride(typePropGet, IGeneratedStore_GetType);
  368. {
  369. var il = typePropGet.GetILGenerator();
  370. il.Emit(OpCodes.Ldarg_0); // load this
  371. il.Emit(OpCodes.Ldfld, typeField); // load impl field
  372. il.Emit(OpCodes.Ret);
  373. }
  374. #endregion
  375. #region IGeneratedStore.Parent
  376. var parentProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Parent), PropertyAttributes.None, typeof(IGeneratedStore), null);
  377. var parentPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Parent)}", virtualPropertyMethodAttr, parentProp.PropertyType, Type.EmptyTypes);
  378. parentProp.SetGetMethod(parentPropGet);
  379. typeBuilder.DefineMethodOverride(parentPropGet, IGeneratedStore_GetParent);
  380. {
  381. var il = parentPropGet.GetILGenerator();
  382. il.Emit(OpCodes.Ldarg_0); // load this
  383. il.Emit(OpCodes.Ldfld, parentField); // load impl field
  384. il.Emit(OpCodes.Ret);
  385. }
  386. #endregion
  387. #region IGeneratedStore.Serialize
  388. var serializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Serialize)}", virtualPropertyMethodAttr, IGeneratedStore_Serialize.ReturnType, Type.EmptyTypes);
  389. typeBuilder.DefineMethodOverride(serializeGen, IGeneratedStore_Serialize);
  390. { // this is non-locking because the only code that will call this will already own the correct lock
  391. var il = serializeGen.GetILGenerator();
  392. var Map_Add = typeof(Map).GetMethod(nameof(Map.Add));
  393. il.Emit(OpCodes.Call, typeof(Value).GetMethod(nameof(Value.Map)));
  394. // the map is now at the top of the stack
  395. var GetLocal = MakeGetLocal(il);
  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 GetLocal = MakeGetLocal(il);
  439. // head of stack is Map instance
  440. foreach (var member in structure)
  441. {
  442. il.MarkLabel(nextLabel);
  443. nextLabel = il.DefineLabel();
  444. var endErrorLabel = il.DefineLabel();
  445. il.Emit(OpCodes.Dup);
  446. il.Emit(OpCodes.Ldstr, member.Name);
  447. il.Emit(OpCodes.Ldloca_S, valueLocal);
  448. il.Emit(OpCodes.Call, Map_TryGetValue);
  449. il.Emit(OpCodes.Brtrue_S, endErrorLabel);
  450. EmitLogError(il, $"Missing key {member.Name}", tailcall: false);
  451. il.Emit(OpCodes.Br, nextLabel);
  452. il.MarkLabel(endErrorLabel);
  453. il.Emit(OpCodes.Ldloc_S, valueLocal);
  454. EmitDeserializeMember(il, member, nextLabel, il => il.Emit(OpCodes.Ldloc_S, valueLocal), GetLocal);
  455. }
  456. il.MarkLabel(nextLabel);
  457. il.Emit(OpCodes.Pop); // removes the duplicate value
  458. il.Emit(OpCodes.Ret);
  459. }
  460. #endregion
  461. #endregion
  462. #region IConfigStore
  463. typeBuilder.AddInterfaceImplementation(typeof(IConfigStore));
  464. var IConfigStore_t = typeof(IConfigStore);
  465. var IConfigStore_GetSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.SyncObject)).GetGetMethod();
  466. var IConfigStore_GetWriteSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.WriteSyncObject)).GetGetMethod();
  467. var IConfigStore_WriteTo = IConfigStore_t.GetMethod(nameof(IConfigStore.WriteTo));
  468. var IConfigStore_ReadFrom = IConfigStore_t.GetMethod(nameof(IConfigStore.ReadFrom));
  469. #region IConfigStore.SyncObject
  470. var syncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.SyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  471. var syncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.SyncObject)}", virtualPropertyMethodAttr, syncObjProp.PropertyType, Type.EmptyTypes);
  472. syncObjProp.SetGetMethod(syncObjPropGet);
  473. typeBuilder.DefineMethodOverride(syncObjPropGet, IConfigStore_GetSyncObject);
  474. {
  475. var il = syncObjPropGet.GetILGenerator();
  476. il.Emit(OpCodes.Ldarg_0);
  477. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  478. il.Emit(OpCodes.Tailcall);
  479. il.Emit(OpCodes.Call, Impl.SyncObjectGetMethod);
  480. il.Emit(OpCodes.Ret);
  481. }
  482. #endregion
  483. #region IConfigStore.WriteSyncObject
  484. var writeSyncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.WriteSyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  485. var writeSyncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.WriteSyncObject)}", virtualPropertyMethodAttr, writeSyncObjProp.PropertyType, Type.EmptyTypes);
  486. writeSyncObjProp.SetGetMethod(writeSyncObjPropGet);
  487. typeBuilder.DefineMethodOverride(writeSyncObjPropGet, IConfigStore_GetWriteSyncObject);
  488. {
  489. var il = writeSyncObjPropGet.GetILGenerator();
  490. il.Emit(OpCodes.Ldarg_0);
  491. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  492. il.Emit(OpCodes.Tailcall);
  493. il.Emit(OpCodes.Call, Impl.WriteSyncObjectGetMethod);
  494. il.Emit(OpCodes.Ret);
  495. }
  496. #endregion
  497. #region IConfigStore.WriteTo
  498. var writeTo = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.WriteTo)}", virtualMemberMethod, null, new[] { typeof(IConfigProvider) });
  499. typeBuilder.DefineMethodOverride(writeTo, IConfigStore_WriteTo);
  500. {
  501. var il = writeTo.GetILGenerator();
  502. il.Emit(OpCodes.Ldarg_0);
  503. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  504. il.Emit(OpCodes.Ldarg_1);
  505. il.Emit(OpCodes.Tailcall);
  506. il.Emit(OpCodes.Call, Impl.WriteToMethod);
  507. il.Emit(OpCodes.Ret);
  508. }
  509. #endregion
  510. #region IConfigStore.ReadFrom
  511. var readFrom = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.ReadFrom)}", virtualMemberMethod, null, new[] { typeof(IConfigProvider) });
  512. typeBuilder.DefineMethodOverride(readFrom, IConfigStore_ReadFrom);
  513. {
  514. var il = readFrom.GetILGenerator();
  515. il.Emit(OpCodes.Ldarg_0);
  516. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  517. il.Emit(OpCodes.Ldarg_1);
  518. il.Emit(OpCodes.Tailcall);
  519. il.Emit(OpCodes.Call, Impl.ReadFromMethod);
  520. il.Emit(OpCodes.Ret);
  521. }
  522. #endregion
  523. #endregion
  524. #region Changed
  525. var coreChanged = typeBuilder.DefineMethod(
  526. "<>Changed",
  527. virtualMemberMethod,
  528. null, Type.EmptyTypes);
  529. {
  530. var il = coreChanged.GetILGenerator();
  531. il.Emit(OpCodes.Ldarg_0);
  532. il.Emit(OpCodes.Call, Impl.ImplSignalChangedMethod);
  533. il.Emit(OpCodes.Ret); // simply call our impl's SignalChanged method and return
  534. }
  535. if (baseChanged != null) {
  536. var changedMethod = typeBuilder.DefineMethod( // copy to override baseChanged
  537. baseChanged.Name,
  538. virtualMemberMethod,
  539. null, Type.EmptyTypes);
  540. typeBuilder.DefineMethodOverride(changedMethod, baseChanged);
  541. {
  542. var il = changedMethod.GetILGenerator();
  543. il.Emit(OpCodes.Ldarg_0);
  544. il.Emit(OpCodes.Call, baseChanged); // call base
  545. il.Emit(OpCodes.Ldarg_0);
  546. il.Emit(OpCodes.Tailcall);
  547. il.Emit(OpCodes.Call, coreChanged); // call back to the core change method
  548. il.Emit(OpCodes.Ret);
  549. }
  550. coreChanged = changedMethod; // switch to calling this version instead of just the default
  551. }
  552. typeBuilder.DefineMethodOverride(coreChanged, IGeneratedStore_Changed);
  553. #endregion
  554. // TODO: generate overrides for all the virtual properties
  555. foreach (var member in structure.Where(m => m.IsVirtual))
  556. { // IsVirtual implies !IsField
  557. var prop = member.Member as PropertyInfo;
  558. var get = prop.GetGetMethod(true);
  559. var set = prop.GetSetMethod(true);
  560. var propBuilder = typeBuilder.DefineProperty($"{member.Name}#", PropertyAttributes.None, member.Type, null);
  561. var propGet = typeBuilder.DefineMethod($"<g>{propBuilder.Name}", virtualPropertyMethodAttr, member.Type, Type.EmptyTypes);
  562. propBuilder.SetGetMethod(propGet);
  563. typeBuilder.DefineMethodOverride(propGet, get);
  564. {
  565. var il = propGet.GetILGenerator();
  566. var local = il.DeclareLocal(member.Type);
  567. il.Emit(OpCodes.Ldarg_0);
  568. il.Emit(OpCodes.Call, Impl.ImplTakeReadMethod); // take the read lock
  569. il.BeginExceptionBlock();
  570. il.Emit(OpCodes.Ldarg_0);
  571. il.Emit(OpCodes.Call, get); // call base getter
  572. il.Emit(OpCodes.Stloc, local);
  573. il.BeginFinallyBlock();
  574. il.Emit(OpCodes.Ldarg_0);
  575. il.Emit(OpCodes.Call, Impl.ImplReleaseReadMethod); // release the read lock
  576. il.EndExceptionBlock();
  577. il.Emit(OpCodes.Ldloc, local);
  578. il.Emit(OpCodes.Ret);
  579. }
  580. var propSet = typeBuilder.DefineMethod($"<s>{propBuilder.Name}", virtualPropertyMethodAttr, null, new[] { member.Type });
  581. propBuilder.SetSetMethod(propSet);
  582. typeBuilder.DefineMethodOverride(propSet, set);
  583. { // TODO: decide if i want to correct the value before or after i take the write lock
  584. var il = propSet.GetILGenerator();
  585. il.Emit(OpCodes.Ldarg_0);
  586. il.Emit(OpCodes.Call, Impl.ImplTakeWriteMethod); // take the write lock
  587. il.BeginExceptionBlock();
  588. il.Emit(OpCodes.Ldarg_0);
  589. il.Emit(OpCodes.Ldarg_1);
  590. EmitCorrectMember(il, member);
  591. il.Emit(OpCodes.Call, set);
  592. il.BeginFinallyBlock();
  593. il.Emit(OpCodes.Ldarg_0);
  594. il.Emit(OpCodes.Call, Impl.ImplReleaseWriteMethod); // release the write lock
  595. il.EndExceptionBlock();
  596. il.Emit(OpCodes.Ldarg_0);
  597. il.Emit(OpCodes.Call, Impl.ImplInvokeChangedMethod);
  598. il.Emit(OpCodes.Ret);
  599. }
  600. }
  601. var genType = typeBuilder.CreateType();
  602. var parentParam = Expression.Parameter(typeof(IGeneratedStore), "parent");
  603. var creatorDel = Expression.Lambda<Func<IGeneratedStore, IConfigStore>>(
  604. Expression.New(ctor, parentParam), parentParam
  605. ).Compile();
  606. { // register a member map
  607. var dict = new Dictionary<string, Type>();
  608. foreach (var member in structure)
  609. dict.Add(member.Name, member.Type);
  610. memberMaps.Add(type, dict);
  611. }
  612. return creatorDel;
  613. }
  614. private delegate LocalBuilder GetLocal(Type type, int idx = 0);
  615. private static GetLocal MakeGetLocal(ILGenerator il)
  616. { // TODO: improve this shit a bit so that i can release a hold of a variable and do more auto managing
  617. var locals = new List<LocalBuilder>();
  618. LocalBuilder GetLocal(Type ty, int i = 0)
  619. { // TODO: pull this garbage out somewhere sane somehow
  620. var builder = locals.Where(b => b.LocalType == ty).Skip(i).FirstOrDefault();
  621. if (builder == null)
  622. {
  623. builder = il.DeclareLocal(ty);
  624. locals.Add(builder);
  625. }
  626. return builder;
  627. }
  628. return GetLocal;
  629. }
  630. private static readonly MethodInfo LogErrorMethod = typeof(GeneratedStore).GetMethod(nameof(LogError), BindingFlags.NonPublic | BindingFlags.Static);
  631. internal static void LogError(Type expected, Type found, string message)
  632. {
  633. Logger.config.Notice($"{message}{(expected == null ? "" : $" (expected {expected}, found {found?.ToString() ?? "null"})")}");
  634. }
  635. private static bool NeedsCorrection(SerializedMemberInfo member)
  636. {
  637. return false;
  638. }
  639. // expects start value on stack, exits with final value on stack
  640. private static void EmitCorrectMember(ILGenerator il, SerializedMemberInfo member)
  641. {
  642. if (!NeedsCorrection(member)) return;
  643. // TODO: impl
  644. }
  645. // expects the this param to be on the stack
  646. private static void EmitMemberFix(ILGenerator il, SerializedMemberInfo member, GetLocal GetLocal)
  647. {
  648. if (!NeedsCorrection(member)) return;
  649. var local = GetLocal(member.Type);
  650. EmitLoad(il, member); // load the member
  651. EmitCorrectMember(il, member); // correct it
  652. il.Emit(OpCodes.Stloc, local);
  653. EmitStore(il, member, il => il.Emit(OpCodes.Ldloc, local));
  654. }
  655. #region Utility
  656. private static void EmitLoad(ILGenerator il, SerializedMemberInfo member)
  657. {
  658. il.Emit(OpCodes.Ldarg_0); // load this
  659. if (member.IsField)
  660. il.Emit(OpCodes.Ldfld, member.Member as FieldInfo);
  661. else
  662. { // member is a property
  663. var prop = member.Member as PropertyInfo;
  664. var getter = prop.GetGetMethod();
  665. if (getter == null) throw new InvalidOperationException($"Property {member.Name} does not have a getter and is not ignored");
  666. il.Emit(OpCodes.Call, getter);
  667. }
  668. }
  669. private static void EmitStore(ILGenerator il, SerializedMemberInfo member, Action<ILGenerator> value)
  670. {
  671. il.Emit(OpCodes.Ldarg_0); // load this
  672. value(il);
  673. if (member.IsField)
  674. il.Emit(OpCodes.Stfld, member.Member as FieldInfo);
  675. else
  676. { // member is a property
  677. var prop = member.Member as PropertyInfo;
  678. var setter = prop.GetSetMethod();
  679. if (setter == null) throw new InvalidOperationException($"Property {member.Name} does not have a setter and is not ignored");
  680. il.Emit(OpCodes.Call, setter);
  681. }
  682. }
  683. private static void EmitLogError(ILGenerator il, string message, bool tailcall = false, Action<ILGenerator> expected = null, Action<ILGenerator> found = null)
  684. {
  685. if (expected == null) expected = il => il.Emit(OpCodes.Ldnull);
  686. if (found == null) found = il => il.Emit(OpCodes.Ldnull);
  687. expected(il);
  688. found(il);
  689. il.Emit(OpCodes.Ldstr, message);
  690. if (tailcall) il.Emit(OpCodes.Tailcall);
  691. il.Emit(OpCodes.Call, LogErrorMethod);
  692. }
  693. private static readonly MethodInfo Type_GetTypeFromHandle = typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle));
  694. private static void EmitTypeof(ILGenerator il, Type type)
  695. {
  696. il.Emit(OpCodes.Ldtoken, type);
  697. il.Emit(OpCodes.Call, Type_GetTypeFromHandle);
  698. }
  699. private static Type Decimal_t = typeof(decimal);
  700. private static ConstructorInfo Decimal_FromFloat = Decimal_t.GetConstructor(new[] { typeof(float) });
  701. private static ConstructorInfo Decimal_FromDouble = Decimal_t.GetConstructor(new[] { typeof(double) });
  702. private static ConstructorInfo Decimal_FromInt = Decimal_t.GetConstructor(new[] { typeof(int) });
  703. private static ConstructorInfo Decimal_FromUInt = Decimal_t.GetConstructor(new[] { typeof(uint) });
  704. private static ConstructorInfo Decimal_FromLong = Decimal_t.GetConstructor(new[] { typeof(long) });
  705. private static ConstructorInfo Decimal_FromULong = Decimal_t.GetConstructor(new[] { typeof(ulong) });
  706. private static void EmitNumberConvertTo(ILGenerator il, Type to, Type from)
  707. { // WARNING: THIS USES THE NO-OVERFLOW OPCODES
  708. if (to == from) return;
  709. if (to == Decimal_t)
  710. {
  711. if (from == typeof(float)) il.Emit(OpCodes.Newobj, Decimal_FromFloat);
  712. else if (from == typeof(double)) il.Emit(OpCodes.Newobj, Decimal_FromDouble);
  713. else if (from == typeof(long)) il.Emit(OpCodes.Newobj, Decimal_FromLong);
  714. else if (from == typeof(ulong)) il.Emit(OpCodes.Newobj, Decimal_FromULong);
  715. else if (from == typeof(int)) il.Emit(OpCodes.Newobj, Decimal_FromInt);
  716. else if (from == typeof(uint)) il.Emit(OpCodes.Newobj, Decimal_FromUInt);
  717. else if (from == typeof(IntPtr))
  718. {
  719. EmitNumberConvertTo(il, typeof(long), from);
  720. EmitNumberConvertTo(il, to, typeof(long));
  721. }
  722. else if (from == typeof(UIntPtr))
  723. {
  724. EmitNumberConvertTo(il, typeof(ulong), from);
  725. EmitNumberConvertTo(il, to, typeof(ulong));
  726. }
  727. else
  728. { // if the source is anything else, we first convert to int because that can contain all other values
  729. EmitNumberConvertTo(il, typeof(int), from);
  730. EmitNumberConvertTo(il, to, typeof(int));
  731. };
  732. }
  733. else if (from == Decimal_t)
  734. {
  735. if (to == typeof(IntPtr))
  736. {
  737. EmitNumberConvertTo(il, typeof(long), from);
  738. EmitNumberConvertTo(il, to, typeof(long));
  739. }
  740. else if (to == typeof(UIntPtr))
  741. {
  742. EmitNumberConvertTo(il, typeof(ulong), from);
  743. EmitNumberConvertTo(il, to, typeof(ulong));
  744. }
  745. else
  746. {
  747. var method = Decimal_t.GetMethod($"To{to.Name}"); // conveniently, this is the pattern of the to* names
  748. il.Emit(OpCodes.Call, method);
  749. }
  750. }
  751. else if (to == typeof(IntPtr)) il.Emit(OpCodes.Conv_I);
  752. else if (to == typeof(UIntPtr)) il.Emit(OpCodes.Conv_U);
  753. else if (to == typeof(sbyte)) il.Emit(OpCodes.Conv_I1);
  754. else if (to == typeof(byte)) il.Emit(OpCodes.Conv_U1);
  755. else if (to == typeof(short)) il.Emit(OpCodes.Conv_I2);
  756. else if (to == typeof(ushort)) il.Emit(OpCodes.Conv_U2);
  757. else if (to == typeof(int)) il.Emit(OpCodes.Conv_I4);
  758. else if (to == typeof(uint)) il.Emit(OpCodes.Conv_U4);
  759. else if (to == typeof(long)) il.Emit(OpCodes.Conv_I8);
  760. else if (to == typeof(ulong)) il.Emit(OpCodes.Conv_U8);
  761. else if (to == typeof(float))
  762. {
  763. if (from == typeof(byte)
  764. || from == typeof(ushort)
  765. || from == typeof(uint)
  766. || from == typeof(ulong)
  767. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  768. il.Emit(OpCodes.Conv_R4);
  769. }
  770. else if (to == typeof(double))
  771. {
  772. if (from == typeof(byte)
  773. || from == typeof(ushort)
  774. || from == typeof(uint)
  775. || from == typeof(ulong)
  776. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  777. il.Emit(OpCodes.Conv_R8);
  778. }
  779. }
  780. private static void EmitCreateChildGenerated(ILGenerator il, Type childType)
  781. {
  782. var method = CreateGParent.MakeGenericMethod(childType);
  783. il.Emit(OpCodes.Ldarg_0);
  784. il.Emit(OpCodes.Call, method);
  785. }
  786. #endregion
  787. #region Serialize
  788. // emit takes no args, leaves Value at top of stack
  789. private static void EmitSerializeMember(ILGenerator il, SerializedMemberInfo member, GetLocal GetLocal)
  790. {
  791. EmitLoad(il, member);
  792. var endSerialize = il.DefineLabel();
  793. if (member.AllowNull)
  794. {
  795. var passedNull = il.DefineLabel();
  796. il.Emit(OpCodes.Dup);
  797. if (member.IsNullable)
  798. il.Emit(OpCodes.Call, member.Nullable_HasValue.GetGetMethod());
  799. il.Emit(OpCodes.Brtrue, passedNull);
  800. il.Emit(OpCodes.Pop);
  801. il.Emit(OpCodes.Ldnull);
  802. il.Emit(OpCodes.Br, endSerialize);
  803. il.MarkLabel(passedNull);
  804. }
  805. if (member.IsNullable)
  806. il.Emit(OpCodes.Call, member.Nullable_Value.GetGetMethod());
  807. var targetType = GetExpectedValueTypeForType(member.Type);
  808. if (targetType == typeof(Text))
  809. { // only happens when arg is a string or char
  810. var TextCreate = typeof(Value).GetMethod(nameof(Value.Text));
  811. if (member.Type == typeof(char))
  812. {
  813. var strFromChar = typeof(char).GetMethod(nameof(char.ToString), new[] { typeof(char) });
  814. il.Emit(OpCodes.Call, strFromChar);
  815. }
  816. il.Emit(OpCodes.Call, TextCreate);
  817. }
  818. else if (targetType == typeof(Boolean))
  819. {
  820. var BoolCreate = typeof(Value).GetMethod(nameof(Value.Bool));
  821. il.Emit(OpCodes.Call, BoolCreate);
  822. }
  823. else if (targetType == typeof(Integer))
  824. {
  825. var IntCreate = typeof(Value).GetMethod(nameof(Value.Integer));
  826. EmitNumberConvertTo(il, IntCreate.GetParameters()[0].ParameterType, member.Type);
  827. il.Emit(OpCodes.Call, IntCreate);
  828. }
  829. else if (targetType == typeof(FloatingPoint))
  830. {
  831. var FloatCreate = typeof(Value).GetMethod(nameof(Value.Float));
  832. EmitNumberConvertTo(il, FloatCreate.GetParameters()[0].ParameterType, member.Type);
  833. il.Emit(OpCodes.Call, FloatCreate);
  834. }
  835. else if (targetType == typeof(List))
  836. {
  837. // TODO: impl this (enumerables)
  838. il.Emit(OpCodes.Pop);
  839. il.Emit(OpCodes.Ldnull);
  840. }
  841. else if (targetType == typeof(Map))
  842. {
  843. // TODO: support other aggregate types
  844. // for now, we assume that its a generated type implementing IGeneratedStore
  845. var IGeneratedStore_Serialize = typeof(IGeneratedStore).GetMethod(nameof(IGeneratedStore.Serialize));
  846. il.Emit(OpCodes.Callvirt, IGeneratedStore_Serialize);
  847. }
  848. il.MarkLabel(endSerialize);
  849. // TODO: implement converters
  850. }
  851. #endregion
  852. #region Deserialize
  853. private static Type GetExpectedValueTypeForType(Type valT)
  854. {
  855. if (typeof(Value).IsAssignableFrom(valT)) // this is a Value subtype
  856. return valT;
  857. if (valT == typeof(string)
  858. || valT == typeof(char)) return typeof(Text);
  859. if (valT == typeof(bool)) return typeof(Boolean);
  860. if (valT == typeof(byte)
  861. || valT == typeof(sbyte)
  862. || valT == typeof(short)
  863. || valT == typeof(ushort)
  864. || valT == typeof(int)
  865. || valT == typeof(uint)
  866. || valT == typeof(long)
  867. || valT == typeof(ulong)) return typeof(Integer);
  868. if (valT == typeof(float)
  869. || valT == typeof(double)
  870. || valT == typeof(decimal)) return typeof(FloatingPoint);
  871. if (typeof(IEnumerable).IsAssignableFrom(valT)) return typeof(List);
  872. // TODO: fill this out the rest of the way
  873. // TODO: support converters
  874. return typeof(Map); // default for various objects
  875. }
  876. private static void EmitDeserializeGeneratedValue(ILGenerator il, Type targetType, Type srcType, GetLocal GetLocal)
  877. {
  878. var IGeneratedStore_Deserialize = typeof(IGeneratedStore).GetMethod(nameof(IGeneratedStore.Deserialize));
  879. var valuel = GetLocal(srcType, 0);
  880. il.Emit(OpCodes.Stloc, valuel);
  881. EmitCreateChildGenerated(il, targetType);
  882. il.Emit(OpCodes.Dup);
  883. il.Emit(OpCodes.Ldloc, valuel);
  884. il.Emit(OpCodes.Callvirt, IGeneratedStore_Deserialize);
  885. }
  886. private static void EmitDeserializeNullable(ILGenerator il, SerializedMemberInfo member, Type expected, GetLocal GetLocal)
  887. {
  888. EmitDeserializeValue(il, member.NullableWrappedType, expected, GetLocal);
  889. il.Emit(OpCodes.Newobj, member.Nullable_Construct);
  890. }
  891. // top of stack is the Value to deserialize; the type will be as returned from GetExpectedValueTypeForType
  892. // after, top of stack will be thing to write to field
  893. private static void EmitDeserializeValue(ILGenerator il, Type targetType, Type expected, GetLocal GetLocal)
  894. {
  895. if (typeof(Value).IsAssignableFrom(targetType)) return; // do nothing
  896. if (expected == typeof(Text))
  897. {
  898. var getter = expected.GetProperty(nameof(Text.Value)).GetGetMethod();
  899. il.Emit(OpCodes.Call, getter);
  900. if (targetType == typeof(char))
  901. {
  902. var strIndex = typeof(string).GetProperty("Chars").GetGetMethod(); // string's indexer is specially named Chars
  903. il.Emit(OpCodes.Ldc_I4_0);
  904. il.Emit(OpCodes.Call, strIndex);
  905. }
  906. }
  907. else if (expected == typeof(Boolean))
  908. {
  909. var getter = expected.GetProperty(nameof(Boolean.Value)).GetGetMethod();
  910. il.Emit(OpCodes.Call, getter);
  911. }
  912. else if (expected == typeof(Integer))
  913. {
  914. var getter = expected.GetProperty(nameof(Integer.Value)).GetGetMethod();
  915. il.Emit(OpCodes.Call, getter);
  916. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  917. }
  918. else if (expected == typeof(FloatingPoint))
  919. {
  920. var getter = expected.GetProperty(nameof(FloatingPoint.Value)).GetGetMethod();
  921. il.Emit(OpCodes.Call, getter);
  922. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  923. } // TODO: implement stuff for lists and maps of various types (probably call out somewhere else to figure out what to do)
  924. else if (expected == typeof(Map))
  925. {
  926. EmitDeserializeGeneratedValue(il, targetType, expected, GetLocal);
  927. }
  928. else // TODO: support converters
  929. {
  930. il.Emit(OpCodes.Pop);
  931. il.Emit(OpCodes.Ldnull);
  932. }
  933. }
  934. // emit takes the value being deserialized, logs on error, leaves nothing on stack
  935. private static void EmitDeserializeMember(ILGenerator il, SerializedMemberInfo member, Label nextLabel, Action<ILGenerator> getValue, GetLocal GetLocal)
  936. {
  937. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  938. var implLabel = il.DefineLabel();
  939. var passedTypeCheck = il.DefineLabel();
  940. var expectType = GetExpectedValueTypeForType(member.IsNullable ? member.NullableWrappedType : member.Type);
  941. il.Emit(OpCodes.Dup);
  942. il.Emit(OpCodes.Brtrue_S, implLabel); // null check
  943. if (!member.AllowNull)
  944. {
  945. il.Emit(OpCodes.Pop);
  946. EmitLogError(il, $"Member {member.Name} ({member.Type}) not nullable", tailcall: false,
  947. expected: il => EmitTypeof(il, expectType));
  948. il.Emit(OpCodes.Br, nextLabel);
  949. }
  950. else if (member.IsNullable)
  951. {
  952. il.Emit(OpCodes.Pop);
  953. var valTLocal = GetLocal(member.Type, 0);
  954. il.Emit(OpCodes.Ldloca, valTLocal);
  955. il.Emit(OpCodes.Initobj, member.Type);
  956. EmitStore(il, member, il => il.Emit(OpCodes.Ldloc, valTLocal));
  957. il.Emit(OpCodes.Br, nextLabel);
  958. }
  959. else
  960. {
  961. il.Emit(OpCodes.Pop);
  962. EmitStore(il, member, il => il.Emit(OpCodes.Ldnull));
  963. il.Emit(OpCodes.Br, nextLabel);
  964. }
  965. il.MarkLabel(implLabel);
  966. il.Emit(OpCodes.Isinst, expectType); //replaces on stack
  967. il.Emit(OpCodes.Dup); // duplicate cloned value
  968. il.Emit(OpCodes.Brtrue, passedTypeCheck); // null check
  969. var errorHandle = il.DefineLabel();
  970. // special cases to handle coersion between Float and Int
  971. if (expectType == typeof(FloatingPoint))
  972. {
  973. var specialTypeCheck = il.DefineLabel();
  974. il.Emit(OpCodes.Pop);
  975. getValue(il);
  976. il.Emit(OpCodes.Isinst, typeof(Integer)); //replaces on stack
  977. il.Emit(OpCodes.Dup); // duplicate cloned value
  978. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  979. var Integer_CoerceToFloat = typeof(Integer).GetMethod(nameof(Integer.AsFloat));
  980. il.Emit(OpCodes.Call, Integer_CoerceToFloat);
  981. il.Emit(OpCodes.Br, passedTypeCheck);
  982. }
  983. else if (expectType == typeof(Integer))
  984. {
  985. var specialTypeCheck = il.DefineLabel();
  986. il.Emit(OpCodes.Pop);
  987. getValue(il);
  988. il.Emit(OpCodes.Isinst, typeof(FloatingPoint)); //replaces on stack
  989. il.Emit(OpCodes.Dup); // duplicate cloned value
  990. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  991. var Float_CoerceToInt = typeof(FloatingPoint).GetMethod(nameof(FloatingPoint.AsInteger));
  992. il.Emit(OpCodes.Call, Float_CoerceToInt);
  993. il.Emit(OpCodes.Br, passedTypeCheck);
  994. }
  995. il.MarkLabel(errorHandle);
  996. il.Emit(OpCodes.Pop);
  997. EmitLogError(il, $"Unexpected type deserializing {member.Name}", tailcall: false,
  998. expected: il => EmitTypeof(il, expectType), found: il =>
  999. {
  1000. getValue(il);
  1001. il.Emit(OpCodes.Callvirt, Object_GetType);
  1002. });
  1003. il.Emit(OpCodes.Br, nextLabel);
  1004. il.MarkLabel(passedTypeCheck);
  1005. var local = GetLocal(member.Type, 0);
  1006. if (member.IsNullable) EmitDeserializeNullable(il, member, expectType, GetLocal);
  1007. else EmitDeserializeValue(il, member.Type, expectType, GetLocal);
  1008. il.Emit(OpCodes.Stloc, local);
  1009. EmitStore(il, member, il => il.Emit(OpCodes.Ldloc, local));
  1010. }
  1011. #endregion
  1012. }
  1013. }