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.

1500 lines
66 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 interface IGeneratedStore<T> : IGeneratedStore where T : class
  103. {
  104. void CopyFrom(T source);
  105. }
  106. internal class Impl : IConfigStore
  107. {
  108. private readonly IGeneratedStore generated;
  109. internal static ConstructorInfo Ctor = typeof(Impl).GetConstructor(new[] { typeof(IGeneratedStore) });
  110. public Impl(IGeneratedStore store) => generated = store;
  111. private readonly AutoResetEvent resetEvent = new AutoResetEvent(false);
  112. public WaitHandle SyncObject => resetEvent;
  113. internal static MethodInfo SyncObjectGetMethod = typeof(Impl).GetProperty(nameof(SyncObject)).GetGetMethod();
  114. public ReaderWriterLockSlim WriteSyncObject { get; } = new ReaderWriterLockSlim();
  115. internal static MethodInfo WriteSyncObjectGetMethod = typeof(Impl).GetProperty(nameof(WriteSyncObject)).GetGetMethod();
  116. internal static MethodInfo ImplSignalChangedMethod = typeof(Impl).GetMethod(nameof(ImplSignalChanged));
  117. public static void ImplSignalChanged(IGeneratedStore s) => FindImpl(s).SignalChanged();
  118. public void SignalChanged() => resetEvent.Set();
  119. internal static MethodInfo ImplInvokeChangedMethod = typeof(Impl).GetMethod(nameof(ImplInvokeChanged));
  120. public static void ImplInvokeChanged(IGeneratedStore s) => FindImpl(s).InvokeChanged();
  121. public void InvokeChanged() => generated.Changed();
  122. internal static MethodInfo ImplTakeReadMethod = typeof(Impl).GetMethod(nameof(ImplTakeRead));
  123. public static void ImplTakeRead(IGeneratedStore s) => FindImpl(s).TakeRead();
  124. public void TakeRead() => WriteSyncObject.EnterReadLock();
  125. internal static MethodInfo ImplReleaseReadMethod = typeof(Impl).GetMethod(nameof(ImplReleaseRead));
  126. public static void ImplReleaseRead(IGeneratedStore s) => FindImpl(s).ReleaseRead();
  127. public void ReleaseRead() => WriteSyncObject.ExitReadLock();
  128. internal static MethodInfo ImplTakeWriteMethod = typeof(Impl).GetMethod(nameof(ImplTakeWrite));
  129. public static void ImplTakeWrite(IGeneratedStore s) => FindImpl(s).TakeWrite();
  130. public void TakeWrite() => WriteSyncObject.EnterWriteLock();
  131. internal static MethodInfo ImplReleaseWriteMethod = typeof(Impl).GetMethod(nameof(ImplReleaseWrite));
  132. public static void ImplReleaseWrite(IGeneratedStore s) => FindImpl(s).ReleaseWrite();
  133. public void ReleaseWrite() => WriteSyncObject.ExitWriteLock();
  134. internal static MethodInfo FindImplMethod = typeof(Impl).GetMethod(nameof(FindImpl));
  135. public static Impl FindImpl(IGeneratedStore store)
  136. {
  137. while (store?.Parent != null) store = store.Parent; // walk to the top of the tree
  138. return store?.Impl;
  139. }
  140. internal static MethodInfo ReadFromMethod = typeof(Impl).GetMethod(nameof(ReadFrom));
  141. public void ReadFrom(ConfigProvider provider)
  142. {
  143. var values = provider.Load();
  144. Logger.config.Debug("Generated impl ReadFrom");
  145. Logger.config.Debug($"Read {values}");
  146. generated.Deserialize(values);
  147. ReleaseWrite();
  148. generated.OnReload();
  149. TakeWrite(); // must take again for runtime to be happy (which is unfortunate)
  150. }
  151. internal static MethodInfo WriteToMethod = typeof(Impl).GetMethod(nameof(WriteTo));
  152. public void WriteTo(ConfigProvider provider)
  153. {
  154. var values = generated.Serialize();
  155. Logger.config.Debug("Generated impl WriteTo");
  156. Logger.config.Debug($"Serialized {values}");
  157. provider.Store(values);
  158. }
  159. }
  160. private static readonly Dictionary<Type, (GeneratedStoreCreator ctor, Type type)> generatedCreators = new Dictionary<Type, (GeneratedStoreCreator ctor, Type type)>();
  161. public static T Create<T>() where T : class => (T)Create(typeof(T));
  162. public static IConfigStore Create(Type type) => Create(type, null);
  163. private static readonly MethodInfo CreateGParent =
  164. typeof(GeneratedStore).GetMethod(nameof(Create), BindingFlags.NonPublic | BindingFlags.Static, null,
  165. CallingConventions.Any, new[] { typeof(IGeneratedStore) }, Array.Empty<ParameterModifier>());
  166. internal static T Create<T>(IGeneratedStore parent) where T : class => (T)Create(typeof(T), parent);
  167. private static IConfigStore Create(Type type, IGeneratedStore parent)
  168. => GetCreator(type)(parent);
  169. internal static GeneratedStoreCreator GetCreator(Type t)
  170. {
  171. if (generatedCreators.TryGetValue(t, out var gen))
  172. return gen.ctor;
  173. else
  174. {
  175. gen = MakeCreator(t);
  176. generatedCreators.Add(t, gen);
  177. return gen.ctor;
  178. }
  179. }
  180. internal static Type GetGeneratedType(Type t)
  181. {
  182. if (generatedCreators.TryGetValue(t, out var gen))
  183. return gen.type;
  184. else
  185. {
  186. gen = MakeCreator(t);
  187. generatedCreators.Add(t, gen);
  188. return gen.type;
  189. }
  190. }
  191. internal const string GeneratedAssemblyName = "IPA.Config.Generated";
  192. private static AssemblyBuilder assembly = null;
  193. private static AssemblyBuilder Assembly
  194. {
  195. get
  196. {
  197. if (assembly == null)
  198. {
  199. var name = new AssemblyName(GeneratedAssemblyName);
  200. assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);
  201. }
  202. return assembly;
  203. }
  204. }
  205. internal static void DebugSaveAssembly(string file)
  206. {
  207. Assembly.Save(file);
  208. }
  209. private static ModuleBuilder module = null;
  210. private static ModuleBuilder Module
  211. {
  212. get
  213. {
  214. if (module == null)
  215. module = Assembly.DefineDynamicModule(Assembly.GetName().Name, Assembly.GetName().Name + ".dll");
  216. return module;
  217. }
  218. }
  219. private class SerializedMemberInfo
  220. {
  221. public string Name;
  222. public MemberInfo Member;
  223. public Type Type;
  224. public bool AllowNull;
  225. public bool IsVirtual;
  226. public bool IsField;
  227. public bool IsNullable; // signifies whether this is a Nullable<T>
  228. public bool HasConverter;
  229. public bool IsGenericConverter; // used so we can call directly to the generic version if it is
  230. public Type Converter;
  231. public Type ConverterBase;
  232. public Type ConverterTarget;
  233. public FieldInfo ConverterField;
  234. // invalid for objects with IsNullabe false
  235. public Type NullableWrappedType => Nullable.GetUnderlyingType(Type);
  236. // invalid for objects with IsNullabe false
  237. public PropertyInfo Nullable_HasValue => Type.GetProperty(nameof(Nullable<int>.HasValue));
  238. // invalid for objects with IsNullabe false
  239. public PropertyInfo Nullable_Value => Type.GetProperty(nameof(Nullable<int>.Value));
  240. // invalid for objects with IsNullabe false
  241. public ConstructorInfo Nullable_Construct => Type.GetConstructor(new[] { NullableWrappedType });
  242. }
  243. internal delegate IConfigStore GeneratedStoreCreator(IGeneratedStore parent);
  244. private static (GeneratedStoreCreator ctor, Type type) MakeCreator(Type type)
  245. { // note that this does not and should not use converters by default for everything
  246. if (!type.IsClass) throw new ArgumentException("Config type is not a class");
  247. var baseCtor = type.GetConstructor(Type.EmptyTypes); // get a default constructor
  248. if (baseCtor == null)
  249. throw new ArgumentException("Config type does not have a public parameterless constructor");
  250. #region Parse base object structure
  251. var baseChanged = type.GetMethod("Changed", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  252. if (baseChanged != null && !baseChanged.IsVirtual) baseChanged = null; // limit this to just the one thing
  253. var baseOnReload = type.GetMethod("OnReload", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  254. if (baseOnReload != null && !baseOnReload.IsVirtual) baseOnReload = null; // limit this to just the one thing
  255. var structure = new List<SerializedMemberInfo>();
  256. bool ProcessAttributesFor(ref SerializedMemberInfo member)
  257. {
  258. var attrs = member.Member.GetCustomAttributes(true);
  259. var ignores = attrs.Select(o => o as IgnoreAttribute).NonNull();
  260. if (ignores.Any()) // we ignore
  261. {
  262. return false;
  263. }
  264. var nonNullables = attrs.Select(o => o as NonNullableAttribute).NonNull();
  265. member.Name = member.Member.Name;
  266. member.IsNullable = member.Type.IsGenericType
  267. && member.Type.GetGenericTypeDefinition() == typeof(Nullable<>);
  268. member.AllowNull = !nonNullables.Any() && (!member.Type.IsValueType || member.IsNullable);
  269. var nameAttr = attrs.Select(o => o as SerializedNameAttribute).NonNull().FirstOrDefault();
  270. if (nameAttr != null)
  271. member.Name = nameAttr.Name;
  272. member.HasConverter = false;
  273. var converterAttr = attrs.Select(o => o as UseConverterAttribute).NonNull().FirstOrDefault();
  274. if (converterAttr != null)
  275. {
  276. member.Converter = converterAttr.ConverterType;
  277. member.IsGenericConverter = converterAttr.IsGenericConverter;
  278. if (member.Converter.GetConstructor(Type.EmptyTypes) == null)
  279. {
  280. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter that is not default-constructible");
  281. goto endConverterAttr; // is there a better control flow structure to do this?
  282. }
  283. if (member.Converter.ContainsGenericParameters)
  284. {
  285. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter that has unfilled type parameters");
  286. goto endConverterAttr;
  287. }
  288. if (member.Converter.IsInterface || member.Converter.IsAbstract)
  289. {
  290. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter that is not constructible");
  291. goto endConverterAttr;
  292. }
  293. var targetType = converterAttr.ConverterTargetType;
  294. if (!member.IsGenericConverter)
  295. {
  296. try
  297. {
  298. var conv = Activator.CreateInstance(converterAttr.ConverterType) as IValueConverter;
  299. targetType = conv.Type;
  300. }
  301. catch
  302. {
  303. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter who's target type could not be determined");
  304. goto endConverterAttr;
  305. }
  306. }
  307. if (targetType != member.Type)
  308. {
  309. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter that is not of the member's type");
  310. goto endConverterAttr;
  311. }
  312. member.ConverterTarget = targetType;
  313. if (member.IsGenericConverter)
  314. member.ConverterBase = typeof(ValueConverter<>).MakeGenericType(targetType);
  315. else
  316. member.ConverterBase = typeof(IValueConverter);
  317. member.HasConverter = true;
  318. }
  319. endConverterAttr:
  320. return true;
  321. }
  322. // only looks at public/protected properties
  323. foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
  324. {
  325. if (prop.GetSetMethod(true)?.IsPrivate ?? true)
  326. { // we enter this block if the setter is inacessible or doesn't exist
  327. continue; // ignore props without setter
  328. }
  329. if (prop.GetGetMethod(true)?.IsPrivate ?? true)
  330. { // we enter this block if the getter is inacessible or doesn't exist
  331. continue; // ignore props without getter
  332. }
  333. var smi = new SerializedMemberInfo
  334. {
  335. Member = prop,
  336. IsVirtual = (prop.GetGetMethod(true)?.IsVirtual ?? false) ||
  337. (prop.GetSetMethod(true)?.IsVirtual ?? false),
  338. IsField = false,
  339. Type = prop.PropertyType
  340. };
  341. if (!ProcessAttributesFor(ref smi)) continue;
  342. structure.Add(smi);
  343. }
  344. // only look at public/protected fields
  345. foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
  346. {
  347. if (field.IsPrivate) continue;
  348. var smi = new SerializedMemberInfo
  349. {
  350. Member = field,
  351. IsVirtual = false,
  352. IsField = true,
  353. Type = field.FieldType
  354. };
  355. if (!ProcessAttributesFor(ref smi)) continue;
  356. structure.Add(smi);
  357. }
  358. #endregion
  359. var typeBuilder = Module.DefineType($"{type.FullName}<Generated>",
  360. TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class, type);
  361. var typeField = typeBuilder.DefineField("<>_type", typeof(Type), FieldAttributes.Private | FieldAttributes.InitOnly);
  362. var implField = typeBuilder.DefineField("<>_impl", typeof(Impl), FieldAttributes.Private | FieldAttributes.InitOnly);
  363. var parentField = typeBuilder.DefineField("<>_parent", typeof(IGeneratedStore), FieldAttributes.Private | FieldAttributes.InitOnly);
  364. #region Converter fields
  365. var uniqueConverterTypes = structure.Where(m => m.HasConverter).Select(m => m.Converter).Distinct().ToArray();
  366. var converterFields = new Dictionary<Type, FieldInfo>(uniqueConverterTypes.Length);
  367. foreach (var convType in uniqueConverterTypes)
  368. {
  369. var field = typeBuilder.DefineField($"<converter>_{convType}", convType,
  370. FieldAttributes.Private | FieldAttributes.InitOnly | FieldAttributes.Static);
  371. converterFields.Add(convType, field);
  372. foreach (var member in structure.Where(m => m.HasConverter && m.Converter == convType))
  373. member.ConverterField = field;
  374. }
  375. #endregion
  376. #region Static constructor
  377. var cctor = typeBuilder.DefineConstructor(MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes);
  378. {
  379. var il = cctor.GetILGenerator();
  380. foreach (var kvp in converterFields)
  381. {
  382. var typeCtor = kvp.Key.GetConstructor(Type.EmptyTypes);
  383. il.Emit(OpCodes.Newobj, typeCtor);
  384. il.Emit(OpCodes.Stsfld, kvp.Value);
  385. }
  386. il.Emit(OpCodes.Ret);
  387. }
  388. #endregion
  389. #region Constructor
  390. var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IGeneratedStore) });
  391. {
  392. var il = ctor.GetILGenerator();
  393. il.Emit(OpCodes.Ldarg_0); // keep this at bottom of stack
  394. il.Emit(OpCodes.Dup);
  395. il.Emit(OpCodes.Call, baseCtor);
  396. il.Emit(OpCodes.Dup);
  397. il.Emit(OpCodes.Ldarg_1); // load parent
  398. il.Emit(OpCodes.Stfld, parentField);
  399. il.Emit(OpCodes.Dup);
  400. EmitTypeof(il, type);
  401. il.Emit(OpCodes.Stfld, typeField);
  402. il.Emit(OpCodes.Dup);
  403. il.Emit(OpCodes.Dup);
  404. il.Emit(OpCodes.Newobj, Impl.Ctor);
  405. il.Emit(OpCodes.Stfld, implField);
  406. var GetLocal = MakeGetLocal(il);
  407. foreach (var member in structure)
  408. {
  409. EmitMemberFix(il, member, GetLocal);
  410. }
  411. il.Emit(OpCodes.Pop);
  412. il.Emit(OpCodes.Ret);
  413. }
  414. #endregion
  415. const MethodAttributes propertyMethodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
  416. const MethodAttributes virtualPropertyMethodAttr = propertyMethodAttr | MethodAttributes.Virtual | MethodAttributes.Final;
  417. const MethodAttributes virtualMemberMethod = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.Final;
  418. #region IGeneratedStore
  419. typeBuilder.AddInterfaceImplementation(typeof(IGeneratedStore));
  420. var IGeneratedStore_t = typeof(IGeneratedStore);
  421. var IGeneratedStore_GetImpl = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Impl)).GetGetMethod();
  422. var IGeneratedStore_GetType = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Type)).GetGetMethod();
  423. var IGeneratedStore_GetParent = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Parent)).GetGetMethod();
  424. var IGeneratedStore_Serialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Serialize));
  425. var IGeneratedStore_Deserialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Deserialize));
  426. var IGeneratedStore_OnReload = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.OnReload));
  427. var IGeneratedStore_Changed = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Changed));
  428. #region IGeneratedStore.OnReload
  429. var onReload = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.OnReload)}", virtualMemberMethod, null, Type.EmptyTypes);
  430. typeBuilder.DefineMethodOverride(onReload, IGeneratedStore_OnReload);
  431. if (baseOnReload != null) typeBuilder.DefineMethodOverride(onReload, baseOnReload);
  432. {
  433. var il = onReload.GetILGenerator();
  434. if (baseOnReload != null)
  435. {
  436. il.Emit(OpCodes.Ldarg_0); // load this
  437. il.Emit(OpCodes.Tailcall);
  438. il.Emit(OpCodes.Call, baseOnReload); // load impl field
  439. }
  440. il.Emit(OpCodes.Ret);
  441. }
  442. #endregion
  443. #region IGeneratedStore.Impl
  444. var implProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Impl), PropertyAttributes.None, typeof(Impl), null);
  445. var implPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Impl)}", virtualPropertyMethodAttr, implProp.PropertyType, Type.EmptyTypes);
  446. implProp.SetGetMethod(implPropGet);
  447. typeBuilder.DefineMethodOverride(implPropGet, IGeneratedStore_GetImpl);
  448. {
  449. var il = implPropGet.GetILGenerator();
  450. il.Emit(OpCodes.Ldarg_0); // load this
  451. il.Emit(OpCodes.Ldfld, implField); // load impl field
  452. il.Emit(OpCodes.Ret);
  453. }
  454. #endregion
  455. #region IGeneratedStore.Type
  456. var typeProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Type), PropertyAttributes.None, typeof(Type), null);
  457. var typePropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Type)}", virtualPropertyMethodAttr, typeProp.PropertyType, Type.EmptyTypes);
  458. typeProp.SetGetMethod(typePropGet);
  459. typeBuilder.DefineMethodOverride(typePropGet, IGeneratedStore_GetType);
  460. {
  461. var il = typePropGet.GetILGenerator();
  462. il.Emit(OpCodes.Ldarg_0); // load this
  463. il.Emit(OpCodes.Ldfld, typeField); // load impl field
  464. il.Emit(OpCodes.Ret);
  465. }
  466. #endregion
  467. #region IGeneratedStore.Parent
  468. var parentProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Parent), PropertyAttributes.None, typeof(IGeneratedStore), null);
  469. var parentPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Parent)}", virtualPropertyMethodAttr, parentProp.PropertyType, Type.EmptyTypes);
  470. parentProp.SetGetMethod(parentPropGet);
  471. typeBuilder.DefineMethodOverride(parentPropGet, IGeneratedStore_GetParent);
  472. {
  473. var il = parentPropGet.GetILGenerator();
  474. il.Emit(OpCodes.Ldarg_0); // load this
  475. il.Emit(OpCodes.Ldfld, parentField); // load impl field
  476. il.Emit(OpCodes.Ret);
  477. }
  478. #endregion
  479. #region IGeneratedStore.Serialize
  480. var serializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Serialize)}", virtualPropertyMethodAttr, IGeneratedStore_Serialize.ReturnType, Type.EmptyTypes);
  481. typeBuilder.DefineMethodOverride(serializeGen, IGeneratedStore_Serialize);
  482. { // this is non-locking because the only code that will call this will already own the correct lock
  483. var il = serializeGen.GetILGenerator();
  484. var Map_Add = typeof(Map).GetMethod(nameof(Map.Add));
  485. var mapLocal = il.DeclareLocal(typeof(Map));
  486. var GetLocal = MakeGetLocal(il);
  487. var valLocal = GetLocal(typeof(Value));
  488. il.Emit(OpCodes.Call, typeof(Value).GetMethod(nameof(Value.Map)));
  489. il.Emit(OpCodes.Stloc, mapLocal);
  490. foreach (var member in structure)
  491. {
  492. EmitSerializeMember(il, member, GetLocal);
  493. il.Emit(OpCodes.Stloc, valLocal);
  494. il.Emit(OpCodes.Ldloc, mapLocal);
  495. il.Emit(OpCodes.Ldstr, member.Name);
  496. il.Emit(OpCodes.Ldloc, valLocal);
  497. il.Emit(OpCodes.Call, Map_Add);
  498. }
  499. il.Emit(OpCodes.Ldloc, mapLocal);
  500. il.Emit(OpCodes.Ret);
  501. }
  502. #endregion
  503. #region IGeneratedStore.Deserialize
  504. var deserializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Deserialize)}", virtualPropertyMethodAttr, null,
  505. new[] { IGeneratedStore_Deserialize.GetParameters()[0].ParameterType });
  506. typeBuilder.DefineMethodOverride(deserializeGen, IGeneratedStore_Deserialize);
  507. { // this is non-locking because the only code that will call this will already own the correct lock
  508. var il = deserializeGen.GetILGenerator();
  509. var Map_t = typeof(Map);
  510. var Map_TryGetValue = Map_t.GetMethod(nameof(Map.TryGetValue));
  511. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  512. var valueLocal = il.DeclareLocal(typeof(Value));
  513. var mapLocal = il.DeclareLocal(typeof(Map));
  514. var nonNull = il.DefineLabel();
  515. il.Emit(OpCodes.Ldarg_1);
  516. il.Emit(OpCodes.Brtrue, nonNull);
  517. EmitLogError(il, "Attempting to deserialize null", tailcall: true);
  518. il.Emit(OpCodes.Ret);
  519. il.MarkLabel(nonNull);
  520. il.Emit(OpCodes.Ldarg_1);
  521. il.Emit(OpCodes.Isinst, Map_t);
  522. il.Emit(OpCodes.Dup); // duplicate cloned value
  523. il.Emit(OpCodes.Stloc, mapLocal);
  524. var notMapError = il.DefineLabel();
  525. il.Emit(OpCodes.Brtrue, notMapError);
  526. // handle error
  527. EmitLogError(il, $"Invalid root for deserializing {type.FullName}", tailcall: true,
  528. expected: il => EmitTypeof(il, Map_t), found: il =>
  529. {
  530. il.Emit(OpCodes.Ldarg_1);
  531. il.Emit(OpCodes.Callvirt, Object_GetType);
  532. });
  533. il.Emit(OpCodes.Ret);
  534. var nextLabel = notMapError;
  535. var GetLocal = MakeGetLocal(il);
  536. // head of stack is Map instance
  537. foreach (var member in structure)
  538. {
  539. il.MarkLabel(nextLabel);
  540. nextLabel = il.DefineLabel();
  541. var endErrorLabel = il.DefineLabel();
  542. il.Emit(OpCodes.Ldloc, mapLocal);
  543. il.Emit(OpCodes.Ldstr, member.Name);
  544. il.Emit(OpCodes.Ldloca_S, valueLocal);
  545. il.Emit(OpCodes.Call, Map_TryGetValue);
  546. il.Emit(OpCodes.Brtrue_S, endErrorLabel);
  547. EmitLogError(il, $"Missing key {member.Name}", tailcall: false);
  548. il.Emit(OpCodes.Br, nextLabel);
  549. il.MarkLabel(endErrorLabel);
  550. il.Emit(OpCodes.Ldloc_S, valueLocal);
  551. EmitDeserializeMember(il, member, nextLabel, il => il.Emit(OpCodes.Ldloc_S, valueLocal), GetLocal);
  552. }
  553. il.MarkLabel(nextLabel);
  554. il.Emit(OpCodes.Ret);
  555. }
  556. #endregion
  557. #endregion
  558. #region IGeneratedStore<T>
  559. var IGeneratedStore_T_t = typeof(IGeneratedStore<>).MakeGenericType(type);
  560. typeBuilder.AddInterfaceImplementation(IGeneratedStore_T_t);
  561. var IGeneratedStore_T_CopyFrom = IGeneratedStore_T_t.GetMethod(nameof(IGeneratedStore<Config>.CopyFrom));
  562. #region IGeneratedStore<T>.CopyFrom
  563. var copyFrom = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore<Config>.CopyFrom)}", virtualMemberMethod, null, new[] { type });
  564. typeBuilder.DefineMethodOverride(copyFrom, IGeneratedStore_T_CopyFrom);
  565. {
  566. var il = copyFrom.GetILGenerator();
  567. il.Emit(OpCodes.Ldarg_0);
  568. il.Emit(OpCodes.Call, Impl.ImplTakeWriteMethod); // take the write lock
  569. var GetLocal = MakeGetLocal(il);
  570. foreach (var member in structure)
  571. {
  572. il.BeginExceptionBlock();
  573. EmitStore(il, member, il =>
  574. {
  575. EmitLoad(il, member, il => il.Emit(OpCodes.Ldarg_1));
  576. EmitCorrectMember(il, member, GetLocal);
  577. });
  578. il.BeginCatchBlock(typeof(Exception));
  579. EmitWarnException(il, $"Error while copying from member {member.Name}");
  580. il.EndExceptionBlock();
  581. }
  582. il.Emit(OpCodes.Ldarg_0);
  583. il.Emit(OpCodes.Call, Impl.ImplReleaseWriteMethod); // release write lock
  584. il.Emit(OpCodes.Ret);
  585. }
  586. #endregion
  587. #endregion
  588. #region IConfigStore
  589. typeBuilder.AddInterfaceImplementation(typeof(IConfigStore));
  590. var IConfigStore_t = typeof(IConfigStore);
  591. var IConfigStore_GetSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.SyncObject)).GetGetMethod();
  592. var IConfigStore_GetWriteSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.WriteSyncObject)).GetGetMethod();
  593. var IConfigStore_WriteTo = IConfigStore_t.GetMethod(nameof(IConfigStore.WriteTo));
  594. var IConfigStore_ReadFrom = IConfigStore_t.GetMethod(nameof(IConfigStore.ReadFrom));
  595. #region IConfigStore.SyncObject
  596. var syncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.SyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  597. var syncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.SyncObject)}", virtualPropertyMethodAttr, syncObjProp.PropertyType, Type.EmptyTypes);
  598. syncObjProp.SetGetMethod(syncObjPropGet);
  599. typeBuilder.DefineMethodOverride(syncObjPropGet, IConfigStore_GetSyncObject);
  600. {
  601. var il = syncObjPropGet.GetILGenerator();
  602. il.Emit(OpCodes.Ldarg_0);
  603. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  604. il.Emit(OpCodes.Tailcall);
  605. il.Emit(OpCodes.Call, Impl.SyncObjectGetMethod);
  606. il.Emit(OpCodes.Ret);
  607. }
  608. #endregion
  609. #region IConfigStore.WriteSyncObject
  610. var writeSyncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.WriteSyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  611. var writeSyncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.WriteSyncObject)}", virtualPropertyMethodAttr, writeSyncObjProp.PropertyType, Type.EmptyTypes);
  612. writeSyncObjProp.SetGetMethod(writeSyncObjPropGet);
  613. typeBuilder.DefineMethodOverride(writeSyncObjPropGet, IConfigStore_GetWriteSyncObject);
  614. {
  615. var il = writeSyncObjPropGet.GetILGenerator();
  616. il.Emit(OpCodes.Ldarg_0);
  617. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  618. il.Emit(OpCodes.Tailcall);
  619. il.Emit(OpCodes.Call, Impl.WriteSyncObjectGetMethod);
  620. il.Emit(OpCodes.Ret);
  621. }
  622. #endregion
  623. #region IConfigStore.WriteTo
  624. var writeTo = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.WriteTo)}", virtualMemberMethod, null, new[] { typeof(ConfigProvider) });
  625. typeBuilder.DefineMethodOverride(writeTo, IConfigStore_WriteTo);
  626. {
  627. var il = writeTo.GetILGenerator();
  628. il.Emit(OpCodes.Ldarg_0);
  629. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  630. il.Emit(OpCodes.Ldarg_1);
  631. il.Emit(OpCodes.Tailcall);
  632. il.Emit(OpCodes.Call, Impl.WriteToMethod);
  633. il.Emit(OpCodes.Ret);
  634. }
  635. #endregion
  636. #region IConfigStore.ReadFrom
  637. var readFrom = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.ReadFrom)}", virtualMemberMethod, null, new[] { typeof(ConfigProvider) });
  638. typeBuilder.DefineMethodOverride(readFrom, IConfigStore_ReadFrom);
  639. {
  640. var il = readFrom.GetILGenerator();
  641. il.Emit(OpCodes.Ldarg_0);
  642. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  643. il.Emit(OpCodes.Ldarg_1);
  644. il.Emit(OpCodes.Tailcall);
  645. il.Emit(OpCodes.Call, Impl.ReadFromMethod);
  646. il.Emit(OpCodes.Ret);
  647. }
  648. #endregion
  649. #endregion
  650. #region Changed
  651. var coreChanged = typeBuilder.DefineMethod(
  652. "<>Changed",
  653. virtualMemberMethod,
  654. null, Type.EmptyTypes);
  655. {
  656. var il = coreChanged.GetILGenerator();
  657. il.Emit(OpCodes.Ldarg_0);
  658. il.Emit(OpCodes.Call, Impl.ImplSignalChangedMethod);
  659. il.Emit(OpCodes.Ret); // simply call our impl's SignalChanged method and return
  660. }
  661. if (baseChanged != null) {
  662. var changedMethod = typeBuilder.DefineMethod( // copy to override baseChanged
  663. baseChanged.Name,
  664. virtualMemberMethod,
  665. null, Type.EmptyTypes);
  666. typeBuilder.DefineMethodOverride(changedMethod, baseChanged);
  667. {
  668. var il = changedMethod.GetILGenerator();
  669. il.Emit(OpCodes.Ldarg_0);
  670. il.Emit(OpCodes.Call, baseChanged); // call base
  671. il.Emit(OpCodes.Ldarg_0);
  672. il.Emit(OpCodes.Tailcall);
  673. il.Emit(OpCodes.Call, coreChanged); // call back to the core change method
  674. il.Emit(OpCodes.Ret);
  675. }
  676. coreChanged = changedMethod; // switch to calling this version instead of just the default
  677. }
  678. typeBuilder.DefineMethodOverride(coreChanged, IGeneratedStore_Changed);
  679. #endregion
  680. #region Members
  681. foreach (var member in structure.Where(m => m.IsVirtual))
  682. { // IsVirtual implies !IsField
  683. var prop = member.Member as PropertyInfo;
  684. var get = prop.GetGetMethod(true);
  685. var set = prop.GetSetMethod(true);
  686. var propBuilder = typeBuilder.DefineProperty($"{member.Name}#", PropertyAttributes.None, member.Type, null);
  687. var propGet = typeBuilder.DefineMethod($"<g>{propBuilder.Name}", virtualPropertyMethodAttr, member.Type, Type.EmptyTypes);
  688. propBuilder.SetGetMethod(propGet);
  689. typeBuilder.DefineMethodOverride(propGet, get);
  690. {
  691. var il = propGet.GetILGenerator();
  692. var local = il.DeclareLocal(member.Type);
  693. il.Emit(OpCodes.Ldarg_0);
  694. il.Emit(OpCodes.Call, Impl.ImplTakeReadMethod); // take the read lock
  695. il.BeginExceptionBlock();
  696. il.Emit(OpCodes.Ldarg_0);
  697. il.Emit(OpCodes.Call, get); // call base getter
  698. il.Emit(OpCodes.Stloc, local);
  699. il.BeginFinallyBlock();
  700. il.Emit(OpCodes.Ldarg_0);
  701. il.Emit(OpCodes.Call, Impl.ImplReleaseReadMethod); // release the read lock
  702. il.EndExceptionBlock();
  703. il.Emit(OpCodes.Ldloc, local);
  704. il.Emit(OpCodes.Ret);
  705. }
  706. var propSet = typeBuilder.DefineMethod($"<s>{propBuilder.Name}", virtualPropertyMethodAttr, null, new[] { member.Type });
  707. propBuilder.SetSetMethod(propSet);
  708. typeBuilder.DefineMethodOverride(propSet, set);
  709. { // TODO: decide if i want to correct the value before or after i take the write lock
  710. var il = propSet.GetILGenerator();
  711. var GetLocal = MakeGetLocal(il);
  712. il.Emit(OpCodes.Ldarg_0);
  713. il.Emit(OpCodes.Call, Impl.ImplTakeWriteMethod); // take the write lock
  714. il.BeginExceptionBlock();
  715. il.Emit(OpCodes.Ldarg_0);
  716. il.Emit(OpCodes.Ldarg_1);
  717. EmitCorrectMember(il, member, GetLocal);
  718. il.Emit(OpCodes.Call, set);
  719. il.BeginFinallyBlock();
  720. il.Emit(OpCodes.Ldarg_0);
  721. il.Emit(OpCodes.Call, Impl.ImplReleaseWriteMethod); // release the write lock
  722. il.EndExceptionBlock();
  723. il.Emit(OpCodes.Ldarg_0);
  724. il.Emit(OpCodes.Call, Impl.ImplInvokeChangedMethod);
  725. il.Emit(OpCodes.Ret);
  726. }
  727. }
  728. #endregion
  729. var genType = typeBuilder.CreateType();
  730. var parentParam = Expression.Parameter(typeof(IGeneratedStore), "parent");
  731. var creatorDel = Expression.Lambda<GeneratedStoreCreator>(
  732. Expression.New(ctor, parentParam), parentParam
  733. ).Compile();
  734. return (creatorDel, genType);
  735. }
  736. private delegate LocalBuilder GetLocal(Type type, int idx = 0);
  737. private static GetLocal MakeGetLocal(ILGenerator il)
  738. { // TODO: improve this shit a bit so that i can release a hold of a variable and do more auto managing
  739. var locals = new List<LocalBuilder>();
  740. LocalBuilder GetLocal(Type ty, int i = 0)
  741. {
  742. var builder = locals.Where(b => b.LocalType == ty).Skip(i).FirstOrDefault();
  743. if (builder == null)
  744. {
  745. builder = il.DeclareLocal(ty);
  746. locals.Add(builder);
  747. }
  748. return builder;
  749. }
  750. return GetLocal;
  751. }
  752. private static readonly MethodInfo LogErrorMethod = typeof(GeneratedStore).GetMethod(nameof(LogError), BindingFlags.NonPublic | BindingFlags.Static);
  753. internal static void LogError(Type expected, Type found, string message)
  754. {
  755. Logger.config.Notice($"{message}{(expected == null ? "" : $" (expected {expected}, found {found?.ToString() ?? "null"})")}");
  756. }
  757. private static readonly MethodInfo LogWarningMethod = typeof(GeneratedStore).GetMethod(nameof(LogWarning), BindingFlags.NonPublic | BindingFlags.Static);
  758. internal static void LogWarning(string message)
  759. {
  760. Logger.config.Warn(message);
  761. }
  762. private static readonly MethodInfo LogWarningExceptionMethod = typeof(GeneratedStore).GetMethod(nameof(LogWarningException), BindingFlags.NonPublic | BindingFlags.Static);
  763. internal static void LogWarningException(Exception exception)
  764. {
  765. Logger.config.Warn(exception);
  766. }
  767. private static bool NeedsCorrection(SerializedMemberInfo member)
  768. {
  769. var expectType = GetExpectedValueTypeForType(member.IsNullable ? member.NullableWrappedType : member.Type);
  770. if (expectType == typeof(Map)) // TODO: make this slightly saner
  771. return true;
  772. return false;
  773. }
  774. // expects start value on stack, exits with final value on stack
  775. private static void EmitCorrectMember(ILGenerator il, SerializedMemberInfo member, GetLocal GetLocal)
  776. {
  777. if (!NeedsCorrection(member)) return;
  778. var endLabel = il.DefineLabel();
  779. if (member.IsNullable)
  780. {
  781. il.Emit(OpCodes.Dup);
  782. il.Emit(OpCodes.Call, member.Nullable_HasValue.GetGetMethod());
  783. il.Emit(OpCodes.Brfalse, endLabel);
  784. il.Emit(OpCodes.Call, member.Nullable_Value.GetGetMethod());
  785. }
  786. // TODO: impl
  787. // currently the only thing for this is where expect == Map, so do generate shit
  788. il.Emit(OpCodes.Dup);
  789. il.Emit(OpCodes.Isinst, typeof(IGeneratedStore));
  790. il.Emit(OpCodes.Brtrue_S, endLabel); // our input is already something we like
  791. var copyFrom = typeof(IGeneratedStore<>).MakeGenericType(member.Type).GetMethod(nameof(IGeneratedStore<Config>.CopyFrom));
  792. var valLocal = GetLocal(member.Type);
  793. il.Emit(OpCodes.Stloc, valLocal);
  794. EmitCreateChildGenerated(il, member.Type);
  795. il.Emit(OpCodes.Dup);
  796. il.Emit(OpCodes.Ldloc, valLocal);
  797. il.Emit(OpCodes.Callvirt, copyFrom);
  798. if (member.IsNullable)
  799. il.Emit(OpCodes.Newobj, member.Nullable_Construct);
  800. il.MarkLabel(endLabel);
  801. }
  802. // expects the this param to be on the stack
  803. private static void EmitMemberFix(ILGenerator il, SerializedMemberInfo member, GetLocal GetLocal)
  804. {
  805. if (!NeedsCorrection(member)) return;
  806. //var local = GetLocal(member.Type);
  807. EmitStore(il, member, il =>
  808. {
  809. EmitLoad(il, member); // load the member
  810. EmitCorrectMember(il, member, GetLocal); // correct it
  811. });
  812. }
  813. #region Utility
  814. private static void EmitLoad(ILGenerator il, SerializedMemberInfo member, Action<ILGenerator> thisarg = null)
  815. {
  816. if (thisarg == null)
  817. thisarg = il => il.Emit(OpCodes.Ldarg_0);
  818. thisarg(il); // load this
  819. if (member.IsField)
  820. il.Emit(OpCodes.Ldfld, member.Member as FieldInfo);
  821. else
  822. { // member is a property
  823. var prop = member.Member as PropertyInfo;
  824. var getter = prop.GetGetMethod();
  825. if (getter == null) throw new InvalidOperationException($"Property {member.Name} does not have a getter and is not ignored");
  826. il.Emit(OpCodes.Call, getter);
  827. }
  828. }
  829. private static void EmitStore(ILGenerator il, SerializedMemberInfo member, Action<ILGenerator> value)
  830. {
  831. il.Emit(OpCodes.Ldarg_0); // load this
  832. value(il);
  833. if (member.IsField)
  834. il.Emit(OpCodes.Stfld, member.Member as FieldInfo);
  835. else
  836. { // member is a property
  837. var prop = member.Member as PropertyInfo;
  838. var setter = prop.GetSetMethod();
  839. if (setter == null) throw new InvalidOperationException($"Property {member.Name} does not have a setter and is not ignored");
  840. il.Emit(OpCodes.Call, setter);
  841. }
  842. }
  843. private static void EmitWarnException(ILGenerator il, string v)
  844. {
  845. il.Emit(OpCodes.Ldstr, v);
  846. il.Emit(OpCodes.Call, LogWarningMethod);
  847. il.Emit(OpCodes.Call, LogWarningExceptionMethod);
  848. }
  849. private static void EmitLogError(ILGenerator il, string message, bool tailcall = false, Action<ILGenerator> expected = null, Action<ILGenerator> found = null)
  850. {
  851. if (expected == null) expected = il => il.Emit(OpCodes.Ldnull);
  852. if (found == null) found = il => il.Emit(OpCodes.Ldnull);
  853. expected(il);
  854. found(il);
  855. il.Emit(OpCodes.Ldstr, message);
  856. if (tailcall) il.Emit(OpCodes.Tailcall);
  857. il.Emit(OpCodes.Call, LogErrorMethod);
  858. }
  859. private static readonly MethodInfo Type_GetTypeFromHandle = typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle));
  860. private static void EmitTypeof(ILGenerator il, Type type)
  861. {
  862. il.Emit(OpCodes.Ldtoken, type);
  863. il.Emit(OpCodes.Call, Type_GetTypeFromHandle);
  864. }
  865. private static Type Decimal_t = typeof(decimal);
  866. private static ConstructorInfo Decimal_FromFloat = Decimal_t.GetConstructor(new[] { typeof(float) });
  867. private static ConstructorInfo Decimal_FromDouble = Decimal_t.GetConstructor(new[] { typeof(double) });
  868. private static ConstructorInfo Decimal_FromInt = Decimal_t.GetConstructor(new[] { typeof(int) });
  869. private static ConstructorInfo Decimal_FromUInt = Decimal_t.GetConstructor(new[] { typeof(uint) });
  870. private static ConstructorInfo Decimal_FromLong = Decimal_t.GetConstructor(new[] { typeof(long) });
  871. private static ConstructorInfo Decimal_FromULong = Decimal_t.GetConstructor(new[] { typeof(ulong) });
  872. private static void EmitNumberConvertTo(ILGenerator il, Type to, Type from)
  873. { // WARNING: THIS USES THE NO-OVERFLOW OPCODES
  874. if (to == from) return;
  875. if (to == Decimal_t)
  876. {
  877. if (from == typeof(float)) il.Emit(OpCodes.Newobj, Decimal_FromFloat);
  878. else if (from == typeof(double)) il.Emit(OpCodes.Newobj, Decimal_FromDouble);
  879. else if (from == typeof(long)) il.Emit(OpCodes.Newobj, Decimal_FromLong);
  880. else if (from == typeof(ulong)) il.Emit(OpCodes.Newobj, Decimal_FromULong);
  881. else if (from == typeof(int)) il.Emit(OpCodes.Newobj, Decimal_FromInt);
  882. else if (from == typeof(uint)) il.Emit(OpCodes.Newobj, Decimal_FromUInt);
  883. else if (from == typeof(IntPtr))
  884. {
  885. EmitNumberConvertTo(il, typeof(long), from);
  886. EmitNumberConvertTo(il, to, typeof(long));
  887. }
  888. else if (from == typeof(UIntPtr))
  889. {
  890. EmitNumberConvertTo(il, typeof(ulong), from);
  891. EmitNumberConvertTo(il, to, typeof(ulong));
  892. }
  893. else
  894. { // if the source is anything else, we first convert to int because that can contain all other values
  895. EmitNumberConvertTo(il, typeof(int), from);
  896. EmitNumberConvertTo(il, to, typeof(int));
  897. };
  898. }
  899. else if (from == Decimal_t)
  900. {
  901. if (to == typeof(IntPtr))
  902. {
  903. EmitNumberConvertTo(il, typeof(long), from);
  904. EmitNumberConvertTo(il, to, typeof(long));
  905. }
  906. else if (to == typeof(UIntPtr))
  907. {
  908. EmitNumberConvertTo(il, typeof(ulong), from);
  909. EmitNumberConvertTo(il, to, typeof(ulong));
  910. }
  911. else
  912. {
  913. var method = Decimal_t.GetMethod($"To{to.Name}"); // conveniently, this is the pattern of the to* names
  914. il.Emit(OpCodes.Call, method);
  915. }
  916. }
  917. else if (to == typeof(IntPtr)) il.Emit(OpCodes.Conv_I);
  918. else if (to == typeof(UIntPtr)) il.Emit(OpCodes.Conv_U);
  919. else if (to == typeof(sbyte)) il.Emit(OpCodes.Conv_I1);
  920. else if (to == typeof(byte)) il.Emit(OpCodes.Conv_U1);
  921. else if (to == typeof(short)) il.Emit(OpCodes.Conv_I2);
  922. else if (to == typeof(ushort)) il.Emit(OpCodes.Conv_U2);
  923. else if (to == typeof(int)) il.Emit(OpCodes.Conv_I4);
  924. else if (to == typeof(uint)) il.Emit(OpCodes.Conv_U4);
  925. else if (to == typeof(long)) il.Emit(OpCodes.Conv_I8);
  926. else if (to == typeof(ulong)) il.Emit(OpCodes.Conv_U8);
  927. else if (to == typeof(float))
  928. {
  929. if (from == typeof(byte)
  930. || from == typeof(ushort)
  931. || from == typeof(uint)
  932. || from == typeof(ulong)
  933. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  934. il.Emit(OpCodes.Conv_R4);
  935. }
  936. else if (to == typeof(double))
  937. {
  938. if (from == typeof(byte)
  939. || from == typeof(ushort)
  940. || from == typeof(uint)
  941. || from == typeof(ulong)
  942. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  943. il.Emit(OpCodes.Conv_R8);
  944. }
  945. }
  946. private static void EmitCreateChildGenerated(ILGenerator il, Type childType)
  947. {
  948. var method = CreateGParent.MakeGenericMethod(childType);
  949. il.Emit(OpCodes.Ldarg_0);
  950. il.Emit(OpCodes.Call, method);
  951. }
  952. #endregion
  953. #region Serialize
  954. // emit takes no args, leaves Value at top of stack
  955. private static void EmitSerializeMember(ILGenerator il, SerializedMemberInfo member, GetLocal GetLocal)
  956. {
  957. EmitLoad(il, member);
  958. var endSerialize = il.DefineLabel();
  959. if (member.AllowNull)
  960. {
  961. var passedNull = il.DefineLabel();
  962. il.Emit(OpCodes.Dup);
  963. if (member.IsNullable)
  964. il.Emit(OpCodes.Call, member.Nullable_HasValue.GetGetMethod());
  965. il.Emit(OpCodes.Brtrue, passedNull);
  966. il.Emit(OpCodes.Pop);
  967. il.Emit(OpCodes.Ldnull);
  968. il.Emit(OpCodes.Br, endSerialize);
  969. il.MarkLabel(passedNull);
  970. }
  971. if (member.IsNullable)
  972. il.Emit(OpCodes.Call, member.Nullable_Value.GetGetMethod());
  973. var targetType = GetExpectedValueTypeForType(member.Type);
  974. if (member.HasConverter)
  975. {
  976. var stlocal = GetLocal(member.Type);
  977. var valLocal = GetLocal(typeof(Value));
  978. il.Emit(OpCodes.Stloc, stlocal);
  979. il.BeginExceptionBlock();
  980. il.Emit(OpCodes.Ldsfld, member.ConverterField);
  981. il.Emit(OpCodes.Ldloc, stlocal);
  982. if (member.IsGenericConverter)
  983. {
  984. var toValue = member.ConverterBase.GetMethod(nameof(ValueConverter<int>.ToValue),
  985. new[] { member.ConverterTarget, typeof(object) });
  986. il.Emit(OpCodes.Ldarg_0);
  987. il.Emit(OpCodes.Callvirt, toValue); // TODO: figure out how to devirtualize this
  988. }
  989. else
  990. {
  991. var toValue = typeof(IValueConverter).GetMethod(nameof(IValueConverter.ToValue),
  992. new[] { typeof(object), typeof(object) });
  993. il.Emit(OpCodes.Box);
  994. il.Emit(OpCodes.Ldarg_0);
  995. il.Emit(OpCodes.Callvirt, toValue);
  996. }
  997. il.Emit(OpCodes.Stloc, valLocal);
  998. il.BeginCatchBlock(typeof(Exception));
  999. EmitWarnException(il, "Error serializing member using converter");
  1000. il.Emit(OpCodes.Ldnull);
  1001. il.Emit(OpCodes.Stloc, valLocal);
  1002. il.EndExceptionBlock();
  1003. il.Emit(OpCodes.Ldloc, valLocal);
  1004. }
  1005. else if (targetType == typeof(Text))
  1006. { // only happens when arg is a string or char
  1007. var TextCreate = typeof(Value).GetMethod(nameof(Value.Text));
  1008. if (member.Type == typeof(char))
  1009. {
  1010. var strFromChar = typeof(char).GetMethod(nameof(char.ToString), new[] { typeof(char) });
  1011. il.Emit(OpCodes.Call, strFromChar);
  1012. }
  1013. il.Emit(OpCodes.Call, TextCreate);
  1014. }
  1015. else if (targetType == typeof(Boolean))
  1016. {
  1017. var BoolCreate = typeof(Value).GetMethod(nameof(Value.Bool));
  1018. il.Emit(OpCodes.Call, BoolCreate);
  1019. }
  1020. else if (targetType == typeof(Integer))
  1021. {
  1022. var IntCreate = typeof(Value).GetMethod(nameof(Value.Integer));
  1023. EmitNumberConvertTo(il, IntCreate.GetParameters()[0].ParameterType, member.Type);
  1024. il.Emit(OpCodes.Call, IntCreate);
  1025. }
  1026. else if (targetType == typeof(FloatingPoint))
  1027. {
  1028. var FloatCreate = typeof(Value).GetMethod(nameof(Value.Float));
  1029. EmitNumberConvertTo(il, FloatCreate.GetParameters()[0].ParameterType, member.Type);
  1030. il.Emit(OpCodes.Call, FloatCreate);
  1031. }
  1032. else if (targetType == typeof(List))
  1033. {
  1034. // TODO: impl this (enumerables)
  1035. il.Emit(OpCodes.Pop);
  1036. il.Emit(OpCodes.Ldnull);
  1037. }
  1038. else if (targetType == typeof(Map))
  1039. {
  1040. // TODO: support other aggregate types
  1041. // for now, we assume that its a generated type implementing IGeneratedStore
  1042. var IGeneratedStore_Serialize = typeof(IGeneratedStore).GetMethod(nameof(IGeneratedStore.Serialize));
  1043. il.Emit(OpCodes.Callvirt, IGeneratedStore_Serialize);
  1044. }
  1045. il.MarkLabel(endSerialize);
  1046. }
  1047. #endregion
  1048. #region Deserialize
  1049. private static Type GetExpectedValueTypeForType(Type valT)
  1050. {
  1051. if (typeof(Value).IsAssignableFrom(valT)) // this is a Value subtype
  1052. return valT;
  1053. if (valT == typeof(string)
  1054. || valT == typeof(char)) return typeof(Text);
  1055. if (valT == typeof(bool)) return typeof(Boolean);
  1056. if (valT == typeof(byte)
  1057. || valT == typeof(sbyte)
  1058. || valT == typeof(short)
  1059. || valT == typeof(ushort)
  1060. || valT == typeof(int)
  1061. || valT == typeof(uint)
  1062. || valT == typeof(long)
  1063. || valT == typeof(IntPtr)) return typeof(Integer);
  1064. if (valT == typeof(float)
  1065. || valT == typeof(double)
  1066. || valT == typeof(decimal)
  1067. || valT == typeof(ulong) // ulong gets put into this, because decimal can hold it
  1068. || valT == typeof(UIntPtr)) return typeof(FloatingPoint);
  1069. if (typeof(IEnumerable).IsAssignableFrom(valT)) return typeof(List);
  1070. // TODO: fill this out the rest of the way
  1071. return typeof(Map); // default for various objects
  1072. }
  1073. private static void EmitDeserializeGeneratedValue(ILGenerator il, Type targetType, Type srcType, GetLocal GetLocal)
  1074. {
  1075. var IGeneratedStore_Deserialize = typeof(IGeneratedStore).GetMethod(nameof(IGeneratedStore.Deserialize));
  1076. var valuel = GetLocal(srcType, 0);
  1077. il.Emit(OpCodes.Stloc, valuel);
  1078. EmitCreateChildGenerated(il, targetType);
  1079. il.Emit(OpCodes.Dup);
  1080. il.Emit(OpCodes.Ldloc, valuel);
  1081. il.Emit(OpCodes.Callvirt, IGeneratedStore_Deserialize);
  1082. }
  1083. private static void EmitDeserializeNullable(ILGenerator il, SerializedMemberInfo member, Type expected, GetLocal GetLocal)
  1084. {
  1085. EmitDeserializeValue(il, member.NullableWrappedType, expected, GetLocal);
  1086. il.Emit(OpCodes.Newobj, member.Nullable_Construct);
  1087. }
  1088. // top of stack is the Value to deserialize; the type will be as returned from GetExpectedValueTypeForType
  1089. // after, top of stack will be thing to write to field
  1090. private static void EmitDeserializeValue(ILGenerator il, Type targetType, Type expected, GetLocal GetLocal)
  1091. {
  1092. if (typeof(Value).IsAssignableFrom(targetType)) return; // do nothing
  1093. if (expected == typeof(Text))
  1094. {
  1095. var getter = expected.GetProperty(nameof(Text.Value)).GetGetMethod();
  1096. il.Emit(OpCodes.Call, getter);
  1097. if (targetType == typeof(char))
  1098. {
  1099. var strIndex = typeof(string).GetProperty("Chars").GetGetMethod(); // string's indexer is specially named Chars
  1100. il.Emit(OpCodes.Ldc_I4_0);
  1101. il.Emit(OpCodes.Call, strIndex);
  1102. }
  1103. }
  1104. else if (expected == typeof(Boolean))
  1105. {
  1106. var getter = expected.GetProperty(nameof(Boolean.Value)).GetGetMethod();
  1107. il.Emit(OpCodes.Call, getter);
  1108. }
  1109. else if (expected == typeof(Integer))
  1110. {
  1111. var getter = expected.GetProperty(nameof(Integer.Value)).GetGetMethod();
  1112. il.Emit(OpCodes.Call, getter);
  1113. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  1114. }
  1115. else if (expected == typeof(FloatingPoint))
  1116. {
  1117. var getter = expected.GetProperty(nameof(FloatingPoint.Value)).GetGetMethod();
  1118. il.Emit(OpCodes.Call, getter);
  1119. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  1120. } // TODO: implement stuff for lists and maps of various types (probably call out somewhere else to figure out what to do)
  1121. else if (expected == typeof(Map))
  1122. {
  1123. EmitDeserializeGeneratedValue(il, targetType, expected, GetLocal);
  1124. }
  1125. else
  1126. {
  1127. il.Emit(OpCodes.Pop);
  1128. il.Emit(OpCodes.Ldnull);
  1129. }
  1130. }
  1131. private static void EmitDeserializeConverter(ILGenerator il, SerializedMemberInfo member, Label nextLabel, GetLocal GetLocal)
  1132. {
  1133. var stlocal = GetLocal(typeof(Value));
  1134. var valLocal = GetLocal(member.Type);
  1135. il.Emit(OpCodes.Stloc, stlocal);
  1136. il.BeginExceptionBlock();
  1137. il.Emit(OpCodes.Ldsfld, member.ConverterField);
  1138. il.Emit(OpCodes.Ldloc, stlocal);
  1139. il.Emit(OpCodes.Ldarg_0);
  1140. if (member.IsGenericConverter)
  1141. {
  1142. var fromValue = member.ConverterBase.GetMethod(nameof(ValueConverter<int>.FromValue),
  1143. new[] { typeof(Value), typeof(object) });
  1144. il.Emit(OpCodes.Callvirt, fromValue);
  1145. }
  1146. else
  1147. {
  1148. var fromValue = typeof(IValueConverter).GetMethod(nameof(IValueConverter.FromValue),
  1149. new[] { typeof(Value), typeof(object) });
  1150. il.Emit(OpCodes.Callvirt, fromValue);
  1151. if (member.Type.IsValueType)
  1152. il.Emit(OpCodes.Unbox);
  1153. }
  1154. il.Emit(OpCodes.Stloc, valLocal);
  1155. il.BeginCatchBlock(typeof(Exception));
  1156. EmitWarnException(il, "Error occurred while deserializing");
  1157. il.Emit(OpCodes.Leave, nextLabel);
  1158. il.EndExceptionBlock();
  1159. il.Emit(OpCodes.Ldloc, valLocal);
  1160. }
  1161. // emit takes the value being deserialized, logs on error, leaves nothing on stack
  1162. private static void EmitDeserializeMember(ILGenerator il, SerializedMemberInfo member, Label nextLabel, Action<ILGenerator> getValue, GetLocal GetLocal)
  1163. {
  1164. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  1165. var implLabel = il.DefineLabel();
  1166. var passedTypeCheck = il.DefineLabel();
  1167. var expectType = GetExpectedValueTypeForType(member.IsNullable ? member.NullableWrappedType : member.Type);
  1168. il.Emit(OpCodes.Dup);
  1169. il.Emit(OpCodes.Brtrue_S, implLabel); // null check
  1170. if (!member.AllowNull)
  1171. {
  1172. il.Emit(OpCodes.Pop);
  1173. EmitLogError(il, $"Member {member.Name} ({member.Type}) not nullable", tailcall: false,
  1174. expected: il => EmitTypeof(il, expectType));
  1175. il.Emit(OpCodes.Br, nextLabel);
  1176. }
  1177. else if (member.IsNullable)
  1178. {
  1179. il.Emit(OpCodes.Pop);
  1180. var valTLocal = GetLocal(member.Type, 0);
  1181. il.Emit(OpCodes.Ldloca, valTLocal);
  1182. il.Emit(OpCodes.Initobj, member.Type);
  1183. EmitStore(il, member, il => il.Emit(OpCodes.Ldloc, valTLocal));
  1184. il.Emit(OpCodes.Br, nextLabel);
  1185. }
  1186. else
  1187. {
  1188. il.Emit(OpCodes.Pop);
  1189. EmitStore(il, member, il => il.Emit(OpCodes.Ldnull));
  1190. il.Emit(OpCodes.Br, nextLabel);
  1191. }
  1192. if (!member.HasConverter)
  1193. {
  1194. il.MarkLabel(implLabel);
  1195. il.Emit(OpCodes.Isinst, expectType); //replaces on stack
  1196. il.Emit(OpCodes.Dup); // duplicate cloned value
  1197. il.Emit(OpCodes.Brtrue, passedTypeCheck); // null check
  1198. }
  1199. var errorHandle = il.DefineLabel();
  1200. // special cases to handle coersion between Float and Int
  1201. if (member.HasConverter)
  1202. il.MarkLabel(implLabel);
  1203. else if (expectType == typeof(FloatingPoint))
  1204. {
  1205. var specialTypeCheck = il.DefineLabel();
  1206. il.Emit(OpCodes.Pop);
  1207. getValue(il);
  1208. il.Emit(OpCodes.Isinst, typeof(Integer)); //replaces on stack
  1209. il.Emit(OpCodes.Dup); // duplicate cloned value
  1210. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  1211. var Integer_CoerceToFloat = typeof(Integer).GetMethod(nameof(Integer.AsFloat));
  1212. il.Emit(OpCodes.Call, Integer_CoerceToFloat);
  1213. il.Emit(OpCodes.Br, passedTypeCheck);
  1214. }
  1215. else if (expectType == typeof(Integer))
  1216. {
  1217. var specialTypeCheck = il.DefineLabel();
  1218. il.Emit(OpCodes.Pop);
  1219. getValue(il);
  1220. il.Emit(OpCodes.Isinst, typeof(FloatingPoint)); //replaces on stack
  1221. il.Emit(OpCodes.Dup); // duplicate cloned value
  1222. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  1223. var Float_CoerceToInt = typeof(FloatingPoint).GetMethod(nameof(FloatingPoint.AsInteger));
  1224. il.Emit(OpCodes.Call, Float_CoerceToInt);
  1225. il.Emit(OpCodes.Br, passedTypeCheck);
  1226. }
  1227. if (!member.HasConverter)
  1228. {
  1229. il.MarkLabel(errorHandle);
  1230. il.Emit(OpCodes.Pop);
  1231. EmitLogError(il, $"Unexpected type deserializing {member.Name}", tailcall: false,
  1232. expected: il => EmitTypeof(il, expectType), found: il =>
  1233. {
  1234. getValue(il);
  1235. il.Emit(OpCodes.Callvirt, Object_GetType);
  1236. });
  1237. il.Emit(OpCodes.Br, nextLabel);
  1238. }
  1239. il.MarkLabel(passedTypeCheck);
  1240. var local = GetLocal(member.Type, 0);
  1241. if (member.HasConverter) EmitDeserializeConverter(il, member, nextLabel, GetLocal);
  1242. else if (member.IsNullable) EmitDeserializeNullable(il, member, expectType, GetLocal);
  1243. else EmitDeserializeValue(il, member.Type, expectType, GetLocal);
  1244. il.Emit(OpCodes.Stloc, local);
  1245. EmitStore(il, member, il => il.Emit(OpCodes.Ldloc, local));
  1246. }
  1247. #endregion
  1248. }
  1249. }