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.

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